function_name stringlengths 1 63 | docstring stringlengths 50 5.89k | masked_code stringlengths 50 882k | implementation stringlengths 169 12.9k | start_line int32 1 14.6k | end_line int32 16 14.6k | file_content stringlengths 274 882k |
|---|---|---|---|---|---|---|
note | Summary
====
Print chapter28.1 note
Example
====
```python
Chapter28_1().note()
``` | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... | def note(self):
"""
Summary
====
Print chapter28.1 note
Example
====
```python
Chapter28_1().note()
```
"""
print('chapter28.1 note as follow')
print('28.1 矩阵的性质')
print('矩阵运算在科学计算中非常重要')
print('矩阵是数字的一个... | 30 | 88 | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... |
note | Summary
====
Print chapter28.2 note
Example
====
```python
Chapter28_2().note()
``` | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... | def note(self):
'''
Summary
====
Print chapter28.2 note
Example
====
```python
Chapter28_2().note()
```
'''
print('chapter28.2 note as follow')
print('28.2 矩阵乘法的Strassen算法')
print('两个n*n矩阵乘积的著名的Strassen递归算法,其运... | 100 | 146 | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... |
note | Summary
====
Print chapter28.3 note
Example
====
```python
Chapter28_3().note()
``` | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... | def note(self):
'''
Summary
====
Print chapter28.3 note
Example
====
```python
Chapter28_3().note()
```
'''
print('chapter28.3 note as follow')
print('28.3 求解线性方程组')
print('对一组同时成立的线性方程组Ax=b求解时很多应用中都会出现的基本问题。一... | 158 | 199 | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... |
note | Summary
====
Print chapter28.4 note
Example
====
```python
Chapter28_4().note()
``` | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... | def note(self):
"""
Summary
====
Print chapter28.4 note
Example
====
```python
Chapter28_4().note()
```
"""
print('chapter28.4 note as follow')
print('28.4 矩阵求逆')
print('在实际应用中,一般并不使用逆矩阵来求解线性方程组的解,而是运用一些更具数值稳定... | 207 | 254 | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... |
note | Summary
====
Print chapter28.5 note
Example
====
```python
Chapter28_5().note()
``` | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... | def note(self):
"""
Summary
====
Print chapter28.5 note
Example
====
```python
Chapter28_5().note()
```
"""
print('chapter28.5 note as follow')
print('28.5 对称正定矩阵与最小二乘逼近')
print('对称正定矩阵有许多有趣而很理想的性质。例如,它们都是非奇异矩... | 262 | 309 | # coding:utf-8
# usr/bin/python3
# python src/chapter28/chapter28note.py
# python3 src/chapter28/chapter28note.py
"""
Class Chapter28_1
Class Chapter28_2
Class Chapter28_3
Class Chapter28_4
Class Chapter28_5
"""
from __future__ import absolute_import, division, print_function
import numpy as np
class Chapter28_... |
set_clip_grad_norm | Sets maximum gradient norm.
None means gradient clipping is disabled. Defaults to None. | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | def set_clip_grad_norm(self, clip_grad_norm: Optional[float]):
"""Sets maximum gradient norm.
None means gradient clipping is disabled. Defaults to None."""
self.clip_grad_norm = clip_grad_norm
if clip_grad_norm is None:
logging.info("Disabled gradient norm clipping.")
... | 219 | 230 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... |
set_dataset | Set dataset for phase type on task
Args:
dataset: ClassyDataset for returning samples.
phase_type: str must be one of "train" or "test" | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | def set_dataset(self, dataset: ClassyDataset, phase_type: str):
"""Set dataset for phase type on task
Args:
dataset: ClassyDataset for returning samples.
phase_type: str must be one of "train" or "test"
"""
assert phase_type in [
"train",
... | 280 | 296 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... |
set_distributed_options | Set distributed options.
Args:
broadcast_buffers_mode: Broadcast buffers mode. See
:class:`BroadcastBuffersMode` for options.
batch_norm_sync_mode: Batch normalization synchronization mode. See
:class:`BatchNormSyncMode` for options.
batch_norm_sync_group_size: Group size to use for synchro... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | def set_distributed_options(
self,
broadcast_buffers_mode: BroadcastBuffersMode = BroadcastBuffersMode.BEFORE_EVAL,
batch_norm_sync_mode: BatchNormSyncMode = BatchNormSyncMode.DISABLED,
batch_norm_sync_group_size: int = 0,
find_unused_parameters: bool = False,
bucket_... | 336 | 401 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... |
set_hooks | Set hooks for task
Args:
hooks: List of hooks to apply during training | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | def set_hooks(self, hooks: List["ClassyHook"]):
"""Set hooks for task
Args:
hooks: List of hooks to apply during training
"""
from classy_vision.hooks import ClassyHook
assert isinstance(hooks, list)
assert all(isinstance(hook, ClassyHook) for hook in ho... | 403 | 425 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... |
set_amp_args | Disable / enable apex.amp and set the automatic mixed precision parameters.
apex.amp can be utilized for mixed / half precision training.
Args:
amp_args: Dictionary containing arguments to be passed to
amp.initialize. Set to None to disable amp. To enable mixed
precision training, pass amp_args={"opt_lev... | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | def set_amp_args(self, amp_args: Optional[Dict[str, Any]]):
"""Disable / enable apex.amp and set the automatic mixed precision parameters.
apex.amp can be utilized for mixed / half precision training.
Args:
amp_args: Dictionary containing arguments to be passed to
a... | 451 | 512 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... |
set_mixup_transform | Disable / enable mixup transform for data augmentation
Args::
mixup_transform: a callable object which performs mixup data augmentation | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... | def set_mixup_transform(self, mixup_transform: Optional["MixupTransform"]):
"""Disable / enable mixup transform for data augmentation
Args::
mixup_transform: a callable object which performs mixup data augmentation
"""
self.mixup_transform = mixup_transform
if mi... | 514 | 525 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import contextlib
import copy
import enum
import json
import logging
import math
import multiprocessing as mp
import ti... |
__init__ | @param engine: The engine that instanciated this plugin.
@type engine: L{Engine}
@param path: The path of the plugin file to load.
@type path: I{str}
@raise ValueError: If the path to the plugin is not a valid file. | #!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... | def __init__(self, engine, path):
"""
@param engine: The engine that instanciated this plugin.
@type engine: L{Engine}
@param path: The path of the plugin file to load.
@type path: I{str}
@raise ValueError: If the path to the plugin is not a valid file.
"""
... | 723 | 753 | #!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... |
__init__ | @param callback: The function to run when a Shotgun event occurs.
@type callback: A function object.
@param engine: The engine that will dispatch to this callback.
@type engine: L{Engine}.
@param shotgun: The Shotgun instance that will be used to communicate
with your Shotgun server.
@type shotgun: L{sg.Shotgun}
@p... | #!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... | def __init__(
self,
callback,
plugin,
engine,
shotgun,
matchEvents=None,
args=None,
stopOnError=True,
):
"""
@param callback: The function to run when a Shotgun event occurs.
@type callback: A function object.
@param... | 1,011 | 1,064 | #!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... |
process | Process an event with the callback object supplied on initialization.
If an error occurs, it will be logged appropriately and the callback
will be deactivated.
@param event: The Shotgun event to process.
@type event: I{dict} | #!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... | def process(self, event):
"""
Process an event with the callback object supplied on initialization.
If an error occurs, it will be logged appropriately and the callback
will be deactivated.
@param event: The Shotgun event to process.
@type event: I{dict}
"""... | 1,087 | 1,142 | #!/usr/bin/env python
#
# Init file for Shotgun event daemon
#
# chkconfig: 345 99 00
# description: Shotgun event daemon
#
### BEGIN INIT INFO
# Provides: shotgunEvent
# Required-Start: $network
# Should-Start: $remote_fs
# Required-Stop: $network
# Should-Stop: $remote_fs
# Default-Start: 2 3 4 5
# Short-Description:... |
get_schema | A record of an event made for purposes of maintaining a security log. Typical
uses include detection of intrusion attempts and monitoring for inappropriate
usage.
id: unique id for the element within a resource (for internal references). This
may be any string value that does not contain spaces.
extension: May b... | from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class AuditEvent_EntitySchema:
"""
A record of an event made for purposes of mai... | @staticmethod
def get_schema(
max_nesting_depth: Optional[int] = 6,
nesting_depth: int = 0,
nesting_list: List[str] = [],
max_recursion_limit: Optional[int] = 2,
include_extension: Optional[bool] = False,
extension_fields: Optional[List[str]] = [
"valu... | 16 | 249 | from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class AuditEvent_EntitySchema:
"""
A record of an event made for purposes of mai... |
autocorrelate | Gives the correlation coefficient for the signal's correlation with itself.
Args:
signal: The signal on which to compute the autocorrelation. Can be a list.
lag: The offset at which to correlate the signal with itself. E.g. if lag
is 1, will compute the correlation between the signal and itself 1 beat
late... | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | def autocorrelate(signal, lag=1):
"""Gives the correlation coefficient for the signal's correlation with itself.
Args:
signal: The signal on which to compute the autocorrelation. Can be a list.
lag: The offset at which to correlate the signal with itself. E.g. if lag
is 1, will compute the correlatio... | 125 | 140 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
get_next_file_name | Finds next available filename in directory by appending numbers to prefix.
E.g. If prefix is 'myfile', extenstion is '.png', and 'directory' already
contains 'myfile.png' and 'myfile1.png', this function will return
'myfile2.png'.
Args:
directory: Path to the relevant directory.
prefix: The filename prefix to use... | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | def get_next_file_name(directory, prefix, extension):
"""Finds next available filename in directory by appending numbers to prefix.
E.g. If prefix is 'myfile', extenstion is '.png', and 'directory' already
contains 'myfile.png' and 'myfile1.png', this function will return
'myfile2.png'.
Args:
directory:... | 269 | 288 | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
set_logging_level | Set up logging for the CLI.
We either set up global logging based on the verbosity
or, if `logger` is specified, we only limit to a single
sqlfluff logger. Verbosity is applied in the same way.
Implementation: If `logger` is not specified, the handler
is attached to the `sqlfluff` logger. If it is specified
then it a... | """Contains the CLI."""
import sys
import json
import logging
import oyaml as yaml
import click
# For the profiler
import pstats
from io import StringIO
# To enable colour cross platform
import colorama
from sqlfluff.cli.formatters import (
format_rules,
format_violation,
format_linting_result_header,... | def set_logging_level(verbosity, logger=None, stderr_output=False):
"""Set up logging for the CLI.
We either set up global logging based on the verbosity
or, if `logger` is specified, we only limit to a single
sqlfluff logger. Verbosity is applied in the same way.
Implementation: If `logger` is no... | 51 | 100 | """Contains the CLI."""
import sys
import json
import logging
import oyaml as yaml
import click
# For the profiler
import pstats
from io import StringIO
# To enable colour cross platform
import colorama
from sqlfluff.cli.formatters import (
format_rules,
format_violation,
format_linting_result_header,... |
__init__ | Active Directory
:param pulumi.Input[str] active_directory_id: Id of the Active Directory
:param pulumi.Input[str] dns: Comma separated list of DNS server IP addresses for the Active Directory domain
:param pulumi.Input[str] domain: Name of the Active Directory domain
:param pulumi.Input[str] organizational_unit: The O... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | def __init__(__self__, *,
active_directory_id: Optional[pulumi.Input[str]] = None,
dns: Optional[pulumi.Input[str]] = None,
domain: Optional[pulumi.Input[str]] = None,
organizational_unit: Optional[pulumi.Input[str]] = None,
passwo... | 20 | 55 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
__init__ | Volume Export Policy Rule
:param pulumi.Input[str] allowed_clients: Client ingress specification as comma separated string with IPv4 CIDRs, IPv4 host addresses and host names
:param pulumi.Input[bool] cifs: Allows CIFS protocol
:param pulumi.Input[bool] nfsv3: Allows NFSv3 protocol
:param pulumi.Input[bool] nfsv4: Depr... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | def __init__(__self__, *,
allowed_clients: Optional[pulumi.Input[str]] = None,
cifs: Optional[pulumi.Input[bool]] = None,
nfsv3: Optional[pulumi.Input[bool]] = None,
nfsv4: Optional[pulumi.Input[bool]] = None,
rule_index: Optional[... | 156 | 187 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
__init__ | Constructs a SubtopicPageContents domain object.
Args:
subtitled_html: SubtitledHtml. The html data being displayed on
the page.
recorded_voiceovers: RecordedVoiceovers. The recorded voiceovers for
the subtopic page content and their translations in different
languages.
written_tran... | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | def __init__(
self, subtitled_html, recorded_voiceovers, written_translations):
"""Constructs a SubtopicPageContents domain object.
Args:
subtitled_html: SubtitledHtml. The html data being displayed on
the page.
recorded_voiceovers: RecordedVoiceo... | 77 | 92 | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
__init__ | Constructs a SubtopicPage domain object.
Args:
subtopic_page_id: str. The unique ID of the subtopic page.
topic_id: str. The ID of the topic that this subtopic is a part of.
page_contents: SubtopicPageContents. The html and audio
translations to be surfaced to the learner.
page_contents_schema_... | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | def __init__(
self, subtopic_page_id, topic_id, page_contents,
page_contents_schema_version, language_code, version):
"""Constructs a SubtopicPage domain object.
Args:
subtopic_page_id: str. The unique ID of the subtopic page.
topic_id: str. The ID of... | 156 | 177 | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
convert_html_fields_in_subtopic_page_contents | Applies a conversion function on all the html strings in subtopic
page contents to migrate them to a desired state.
Args:
subtopic_page_contents_dict: dict. The dict representation of
subtopic page contents.
conversion_fn: function. The conversion function to be applied on
the subtopic_page_con... | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | @classmethod
def convert_html_fields_in_subtopic_page_contents(
cls, subtopic_page_contents_dict, conversion_fn):
"""Applies a conversion function on all the html strings in subtopic
page contents to migrate them to a desired state.
Args:
subtopic_page_contents_d... | 227 | 250 | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
validate | Validates various properties of the SubtopicPage object.
Raises:
ValidationError. One or more attributes of the subtopic page are
invalid. | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... | def validate(self):
"""Validates various properties of the SubtopicPage object.
Raises:
ValidationError. One or more attributes of the subtopic page are
invalid.
"""
if not isinstance(self.topic_id, python_utils.BASESTRING):
raise utils.Valida... | 363 | 403 | # coding: utf-8
#
# Copyright 2018 The Oppia Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless requi... |
checkFormatVisitor | Run checkFormat in parallel for the given files.
Args:
arg: a tuple (pool, result_list, owned_directories, error_messages)
pool and result_list are for starting tasks asynchronously.
owned_directories tracks directories listed in the CODEOWNERS file.
error_messages is a list of string format errors.
di... | #!/usr/bin/env python3
import argparse
import common
import functools
import multiprocessing
import os
import os.path
import pathlib
import re
import subprocess
import stat
import sys
import traceback
import shutil
import paths
EXCLUDED_PREFIXES = ("./generated/", "./thirdparty/", "./build", "./.git/", "./bazel-", ".... | def checkFormatVisitor(arg, dir_name, names):
"""Run checkFormat in parallel for the given files.
Args:
arg: a tuple (pool, result_list, owned_directories, error_messages)
pool and result_list are for starting tasks asynchronously.
owned_directories tracks directories listed in the CODEOWNERS file.... | 775 | 805 | #!/usr/bin/env python3
import argparse
import common
import functools
import multiprocessing
import os
import os.path
import pathlib
import re
import subprocess
import stat
import sys
import traceback
import shutil
import paths
EXCLUDED_PREFIXES = ("./generated/", "./thirdparty/", "./build", "./.git/", "./bazel-", ".... |
__init__ | Create a new gate.
Args:
name: The Qobj name of the gate.
num_qubits: The number of qubits the gate acts on.
params: A list of parameters.
label: An optional label for the gate. | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | def __init__(self, name: str, num_qubits: int, params: List,
label: Optional[str] = None) -> None:
"""Create a new gate.
Args:
name: The Qobj name of the gate.
num_qubits: The number of qubits the gate acts on.
params: A list of parameters.
... | 28 | 40 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
to_matrix | Return a Numpy.array for the gate unitary matrix.
Returns:
np.ndarray: if the Gate subclass has a matrix definition.
Raises:
CircuitError: If a Gate subclass does not implement this method an
exception will be raised when this base class method is called. | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | def to_matrix(self) -> np.ndarray:
"""Return a Numpy.array for the gate unitary matrix.
Returns:
np.ndarray: if the Gate subclass has a matrix definition.
Raises:
CircuitError: If a Gate subclass does not implement this method an
exception will be ra... | 45 | 58 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
power | Creates a unitary gate as `gate^exponent`.
Args:
exponent (float): Gate^exponent
Returns:
qiskit.extensions.UnitaryGate: To which `to_matrix` is self.to_matrix^exponent.
Raises:
CircuitError: If Gate is not unitary | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | def power(self, exponent: float):
"""Creates a unitary gate as `gate^exponent`.
Args:
exponent (float): Gate^exponent
Returns:
qiskit.extensions.UnitaryGate: To which `to_matrix` is self.to_matrix^exponent.
Raises:
CircuitError: If Gate is not u... | 60 | 88 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
broadcast_arguments | Validation and handling of the arguments and its relationship.
For example, ``cx([q[0],q[1]], q[2])`` means ``cx(q[0], q[2]); cx(q[1], q[2])``. This
method yields the arguments in the right grouping. In the given example::
in: [[q[0],q[1]], q[2]],[]
outs: [q[0], q[2]], []
[q[1], q[2]], []
The gener... | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... | def broadcast_arguments(self, qargs: List, cargs: List) -> Tuple[List, List]:
"""Validation and handling of the arguments and its relationship.
For example, ``cx([q[0],q[1]], q[2])`` means ``cx(q[0], q[2]); cx(q[1], q[2])``. This
method yields the arguments in the right grouping. In the giv... | 184 | 236 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2017.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
find_in_path | Search user's PATH for a given executable.
Returns:
Full path to executable. | # Copyright 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fcntl
import hashlib
import os
import shutil
import subprocess
import sys
# Allow use of this module even if termcolor is missing. There are ma... | def find_in_path(command_name):
"""Search user's PATH for a given executable.
Returns:
Full path to executable.
"""
extensions = ('',)
if not os.path.splitext(command_name)[1] and os.name == 'nt':
extensions = ('.bat', '.com', '.exe')
for path in os.environ.get('PATH', '').split(os.pathsep):
f... | 152 | 168 | # Copyright 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fcntl
import hashlib
import os
import shutil
import subprocess
import sys
# Allow use of this module even if termcolor is missing. There are ma... |
check_stamp | Check that a given stamp file is up-to-date.
Returns: False is the file does not exists or is older that that given
comparison file, or does not contain the given contents. True otherwise. | # Copyright 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fcntl
import hashlib
import os
import shutil
import subprocess
import sys
# Allow use of this module even if termcolor is missing. There are ma... | def check_stamp(filename, contents=None):
"""Check that a given stamp file is up-to-date.
Returns: False is the file does not exists or is older that that given
comparison file, or does not contain the given contents. True otherwise.
"""
if not os.path.exists(filename):
return False
if contents is n... | 205 | 219 | # Copyright 2014 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import fcntl
import hashlib
import os
import shutil
import subprocess
import sys
# Allow use of this module even if termcolor is missing. There are ma... |
__init__ | Response to get user settings
API Version: 2018-10-01.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['UserPropertiesArgs']] properties: The cloud shell user settings properties.
:param pulumi.Input[str] user_settin... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... | def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
properties: Optional[pulumi.Input[pulumi.InputType['UserPropertiesArgs']]] = None,
user_settings_name: Optional[pulumi.Input[str]] = None,
__... | 18 | 62 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... |
get | Get an existing UserSettings resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Option... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... | @staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'UserSettings':
"""
Get an existing UserSettings resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
... | 64 | 81 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables
from ... |
FormatExtensionCategory | Format extension metadata as RST.
Args:
extension_category: the name of the extension_category, e.g. com.acme.
Returns:
RST formatted extension category description. | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatExtensionCategory(extension_category):
"""Format extension metadata as RST.
Args:
extension_category: the name of the extension_category, e.g. com.acme.
Returns:
RST formatted extension category description.
"""
try:
extensions = EXTENSION_CATEGORIES[extension_category]
except KeyErr... | 251 | 266 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
FormatHeaderFromFile | Format RST header based on special file level title
Args:
style: underline style, e.g. '=', '-'.
source_code_info: SourceCodeInfo object.
proto_name: If the file_level_comment does not contain a user specified
title, use this as page title.
Returns:
RST formatted header, and file level comment without pag... | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatHeaderFromFile(style, source_code_info, proto_name):
"""Format RST header based on special file level title
Args:
style: underline style, e.g. '=', '-'.
source_code_info: SourceCodeInfo object.
proto_name: If the file_level_comment does not contain a user specified
title, use this as pa... | 269 | 292 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
FormatFieldTypeAsJson | Format FieldDescriptorProto.Type as a pseudo-JSON string.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Return: RST formatted pseudo-JSON string representation of field type. | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatFieldTypeAsJson(type_context, field):
"""Format FieldDescriptorProto.Type as a pseudo-JSON string.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Return: RST formatted pseudo-JSON string representation of field type.
"""
if TypeNameFromFQN(f... | 295 | 309 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
FormatMessageAsJson | Format a message definition DescriptorProto as a pseudo-JSON block.
Args:
type_context: contextual information for message/enum/field.
msg: message definition DescriptorProto.
Return: RST formatted pseudo-JSON string representation of message definition. | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatMessageAsJson(type_context, msg):
"""Format a message definition DescriptorProto as a pseudo-JSON block.
Args:
type_context: contextual information for message/enum/field.
msg: message definition DescriptorProto.
Return: RST formatted pseudo-JSON string representation of message definition.
"... | 312 | 331 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
FormatFieldType | Format a FieldDescriptorProto type description.
Adds cross-refs for message types.
TODO(htuch): Add cross-refs for enums as well.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Return: RST formatted field type. | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatFieldType(type_context, field):
"""Format a FieldDescriptorProto type description.
Adds cross-refs for message types.
TODO(htuch): Add cross-refs for enums as well.
Args:
type_context: contextual information for message/enum/field.
field: FieldDescriptor proto.
Return: RST formatted field ... | 379 | 435 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
FormatMessageAsDefinitionList | Format a DescriptorProto as RST definition list.
Args:
type_context: contextual information for message/enum/field.
msg: DescriptorProto.
protodoc_manifest: tools.protodoc.Manifest for proto.
Returns:
RST formatted definition list item. | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatMessageAsDefinitionList(type_context, msg, protodoc_manifest):
"""Format a DescriptorProto as RST definition list.
Args:
type_context: contextual information for message/enum/field.
msg: DescriptorProto.
protodoc_manifest: tools.protodoc.Manifest for proto.
Returns:
RST formatted defin... | 574 | 601 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
FormatEnumValueAsDefinitionListItem | Format a EnumValueDescriptorProto as RST definition list item.
Args:
type_context: contextual information for message/enum/field.
enum_value: EnumValueDescriptorProto.
Returns:
RST formatted definition list item. | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... | def FormatEnumValueAsDefinitionListItem(type_context, enum_value):
"""Format a EnumValueDescriptorProto as RST definition list item.
Args:
type_context: contextual information for message/enum/field.
enum_value: EnumValueDescriptorProto.
Returns:
RST formatted definition list item.
"""
anchor = ... | 604 | 621 | # protoc plugin to map from FileDescriptorProtos to Envoy doc style RST.
# See https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto
# for the underlying protos mentioned in this file. See
# https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html for Sphinx RST syntax.
fro... |
get_devilryrole_for_requestuser | Get the devilryrole for the requesting user on the current
period (request.cradmin_instance).
The return values is the same as for
:meth:`devilry.devilry_account.models.PeriodPermissionGroupQuerySet.get_devilryrole_for_user_on_period`,
exept that this method raises ValueError if it does not find a role. | from django_cradmin import crinstance, crapp
from django_cradmin.crinstance import reverse_cradmin_url
from devilry.apps.core.models import Period
from devilry.devilry_account.models import PeriodPermissionGroup
from devilry.devilry_admin.cradminextensions import devilry_crmenu_admin
from devilry.devilry_cradmin impor... | def get_devilryrole_for_requestuser(self):
"""
Get the devilryrole for the requesting user on the current
period (request.cradmin_instance).
The return values is the same as for
:meth:`devilry.devilry_account.models.PeriodPermissionGroupQuerySet.get_devilryrole_for_user_on_p... | 98 | 109 | from django_cradmin import crinstance, crapp
from django_cradmin.crinstance import reverse_cradmin_url
from devilry.apps.core.models import Period
from devilry.devilry_account.models import PeriodPermissionGroup
from devilry.devilry_admin.cradminextensions import devilry_crmenu_admin
from devilry.devilry_cradmin impor... |
get_title | Return the proper title of this object.
If :attr:`self.title <earwax.mixins.TitleMixin.title>` is a callable,
its return value will be returned. | """Provides the MenuItem class."""
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union
from attr import attrs
from ..action import ActionFunctionType
from ..mixins import RegisterEventMixin
if TYPE_CHECKING:
from ..types import TitleFunction
@attrs(auto_attribs=True)
class MenuItem(Regi... | def get_title(self) -> Optional[str]:
"""Return the proper title of this object.
If :attr:`self.title <earwax.mixins.TitleMixin.title>` is a callable,
its return value will be returned.
"""
if callable(self.title):
return self.title()
return self.title | 62 | 70 | """Provides the MenuItem class."""
from pathlib import Path
from typing import TYPE_CHECKING, Optional, Union
from attr import attrs
from ..action import ActionFunctionType
from ..mixins import RegisterEventMixin
if TYPE_CHECKING:
from ..types import TitleFunction
@attrs(auto_attribs=True)
class MenuItem(Regi... |
step | Performs a single optimization step.
Args:
closure (callable, optional): A closure that reevaluates the model
and returns the loss. | from typing import Tuple
import math
import torch
from torch.optim.optimizer import Optimizer
def linear_warmup_and_cosine_protocol(
f_values: Tuple[float, float, float],
x_milestones: Tuple[int, int, int, int]):
"""
There are 5 regions:
1. constant at f0 for x < x0
2. linear increase ... | @torch.no_grad()
def step(self, closure=None):
"""Performs a single optimization step.
Args:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
with torch... | 128 | 179 | from typing import Tuple
import math
import torch
from torch.optim.optimizer import Optimizer
def linear_warmup_and_cosine_protocol(
f_values: Tuple[float, float, float],
x_milestones: Tuple[int, int, int, int]):
"""
There are 5 regions:
1. constant at f0 for x < x0
2. linear increase ... |
equation_checker | Check equation for balanced parentheses
Args:
equation(string): String form of equation
Returns:
bool: Return if parentheses are balanced or not | """
In this exercise you are going to apply what you learned about stacks with a real world problem.
We will be using stacks to make sure the parentheses are balanced in mathematical expressions such as:
((3^2 + 8)*(5/2))/(2+6)
In real life you can see this extend to many things such as text editor plugins
and... | def equation_checker(equation):
"""
Check equation for balanced parentheses
Args:
equation(string): String form of equation
Returns:
bool: Return if parentheses are balanced or not
"""
opening_parenthesis = Stack()
closing_parenthesis = Stack()
for _ in equation:
... | 32 | 51 | """
In this exercise you are going to apply what you learned about stacks with a real world problem.
We will be using stacks to make sure the parentheses are balanced in mathematical expressions such as:
((3^2 + 8)*(5/2))/(2+6)
In real life you can see this extend to many things such as text editor plugins
and... |
__handleInline | Process string with inline patterns and replace it
with placeholders
Keyword arguments:
* data: A line of Markdown text
* patternIndex: The index of the inlinePattern to start with
Returns: String with placeholders. | import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... | def __handleInline(self, data, patternIndex=0):
"""
Process string with inline patterns and replace it
with placeholders
Keyword arguments:
* data: A line of Markdown text
* patternIndex: The index of the inlinePattern to start with
Returns: String with pla... | 92 | 113 | import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... |
__processPlaceholders | Process string with placeholders and generate ElementTree tree.
Keyword arguments:
* data: string with placeholders instead of ElementTree elements.
* parent: Element, which contains processing inline data
Returns: list with ElementTree elements with applied inline patterns. | import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... | def __processPlaceholders(self, data, parent):
"""
Process string with placeholders and generate ElementTree tree.
Keyword arguments:
* data: string with placeholders instead of ElementTree elements.
* parent: Element, which contains processing inline data
Returns:... | 148 | 214 | import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... |
run | Apply inline patterns to a parsed Markdown tree.
Iterate over ElementTree, find elements with inline tag, apply inline
patterns and append newly created Elements to tree. If you don't
want to process your data with inline paterns, instead of normal string,
use subclass AtomicString:
node.text = markdown.AtomicSt... | import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... | def run(self, tree):
"""Apply inline patterns to a parsed Markdown tree.
Iterate over ElementTree, find elements with inline tag, apply inline
patterns and append newly created Elements to tree. If you don't
want to process your data with inline paterns, instead of normal string,
... | 260 | 327 | import re
from . import inlinepatterns
from . import util
from . import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] ... |
__init__ | This method adds additional items to the `self.general` dictionary
which are only needed for validations using datasets.
Arguments:
- `valName`: String which identifies individual validation instances
- `alignment`: `Alignment` instance to validate
- `config`: `BetterConfigParser` instance which includes the
... | from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... | def __init__(self, valName, alignment, config):
"""
This method adds additional items to the `self.general` dictionary
which are only needed for validations using datasets.
Arguments:
- `valName`: String which identifies individual validation instances
- `ali... | 271 | 396 | from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... |
createCrabCfg | Method which creates a `crab.cfg` for a validation on datasets.
Arguments:
- `path`: Path at which the file will be stored.
- `crabCfgBaseName`: String which depends on the actual type of
validation calling this method. | from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... | def createCrabCfg(self, path, crabCfgBaseName):
"""
Method which creates a `crab.cfg` for a validation on datasets.
Arguments:
- `path`: Path at which the file will be stored.
- `crabCfgBaseName`: String which depends on the actual type of
... | 462 | 492 | from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... |
__init__ | name: name of the summary item, goes on top of the column
values: value for each alignment (in order of rows)
format: python format string (default: {:.3g}, meaning up to 3 significant digits)
latexname: name in latex form, e.g. if name=sigma you might want latexname=\sigma (default: name)
latexforma... | from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... | def __init__(self, name, values, format=None, latexname=None, latexformat=None):
"""
name: name of the summary item, goes on top of the column
values: value for each alignment (in order of rows)
format: python format string (default: {:.3g}, meani... | 640 | 656 | from __future__ import print_function
from __future__ import absolute_import
from builtins import range
from abc import ABCMeta, abstractmethod, abstractproperty
import os
import re
import json
from . import globalDictionaries
from . import configTemplates
from .dataset import Dataset
from .helperFunctions import repla... |
main | Main entry point.
Keyword arguments:
searchpath (str), default: "."
Search path for .cfg files.
display (str), default: "all"
List of metadata to display in search results.
keywords (str), default: None
Comma delimited list of keywords for filtering search results.
features (str... | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... | def main(self, **kwargs):
"""Main entry point.
Keyword arguments:
searchpath (str), default: "."
Search path for .cfg files.
display (str), default: "all"
List of metadata to display in search results.
keywords (str), default: None... | 36 | 70 | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... |
_apply_filters | Apply filters to metadata.
Args:
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
Returns: (bool)
True if metadata meets filter requirements, False otherwise. | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... | def _apply_filters(self, metadata):
"""Apply filters to metadata.
Args:
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
Returns: (bool)
True if metadata meets filter requirements, False otherwise.
"""
if "keywo... | 88 | 119 | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... |
_apply_filters_incompatible | Apply filters to metadata to find incompatible parameter files.
Args:
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
Returns: (bool)
True if metadata is incompatible with filter requirements, False otherwise. | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... | def _apply_filters_incompatible(self, metadata):
"""Apply filters to metadata to find incompatible parameter files.
Args:
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
Returns: (bool)
True if metadata is incompatible with fi... | 121 | 146 | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... |
_display_metadata | Print metadata to stdout.
Args:
filename (str)
Name of simulation .cfg file.
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
options (list of str)
List of metadata to display. | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... | def _display_metadata(self, filename, metadata, options):
"""Print metadata to stdout.
Args:
filename (str)
Name of simulation .cfg file.
metadata (pylith.utils.SimulationMetadata)
Simulation metadata.
options (list of str)
... | 148 | 204 | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... |
_parse_command_line | Parse command line arguments.
Returns (argsparse.Namespace)
Command line arguments. | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... | def _parse_command_line(self):
"""Parse command line arguments.
Returns (argsparse.Namespace)
Command line arguments.
"""
DESCRIPTION = (
"Application for searching PyLith .cfg parameter files."
)
parser = argparse.ArgumentParser(description=D... | 206 | 238 | # ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University at Buffalo
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://geodynamics.org).
#
# Copy... |
list_user_usage | A list of usage user entries
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_user_usage(callback=callback_... | # coding: utf-8
"""
Purity//FB REST Client
Client for Purity//FB REST API (1.0 - 1.6), developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.6
Contact: info@purestorage.com
... | def list_user_usage(self, **kwargs):
"""
A list of usage user entries
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_functio... | 43 | 73 | # coding: utf-8
"""
Purity//FB REST Client
Client for Purity//FB REST API (1.0 - 1.6), developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.6
Contact: info@purestorage.com
... |
list_user_usage_with_http_info | A list of usage user entries
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.list_user_usage_with_http_info(cal... | # coding: utf-8
"""
Purity//FB REST Client
Client for Purity//FB REST API (1.0 - 1.6), developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.6
Contact: info@purestorage.com
... | def list_user_usage_with_http_info(self, **kwargs):
"""
A list of usage user entries
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def c... | 75 | 169 | # coding: utf-8
"""
Purity//FB REST Client
Client for Purity//FB REST API (1.0 - 1.6), developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.6
Contact: info@purestorage.com
... |
fetch | Fetch data.
This method fetches all data of the dataset/view.
Note that this method returns a column-major data
(i.e. :obj:`([a[0], ..., a[3]], ..., [c[0], ... c[3]])`,
:obj:`{'a': [a[0], ..., a[3]], ..., 'c': [c[0], ..., c[3]]}`, or
:obj:`[a[0], ..., a[3]]`).
Returns:
If :attr:`mode` is :class:`tuple`,
this ... | import numpy
import torch
import pytorch_pfn_extras as ppe
from torch.utils.data import Dataset
class TabularDataset(Dataset):
"""An abstract class that represents tabular dataset.
This class represents a tabular dataset.
In a tabular dataset, all examples have the same number of elements.
For examp... | def fetch(self):
"""Fetch data.
This method fetches all data of the dataset/view.
Note that this method returns a column-major data
(i.e. :obj:`([a[0], ..., a[3]], ..., [c[0], ... c[3]])`,
:obj:`{'a': [a[0], ..., a[3]], ..., 'c': [c[0], ..., c[3]]}`, or
:obj:`[a[0], ... | 128 | 149 | import numpy
import torch
import pytorch_pfn_extras as ppe
from torch.utils.data import Dataset
class TabularDataset(Dataset):
"""An abstract class that represents tabular dataset.
This class represents a tabular dataset.
In a tabular dataset, all examples have the same number of elements.
For examp... |
run | Run a script in a separate thread and start a server for the app.
This starts a blocking ioloop.
Parameters
----------
script_path : str
command_line : str
args : [str]
flag_options : Dict[str, Any] | # Copyright 2018-2021 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def run(script_path, command_line, args, flag_options):
"""Run a script in a separate thread and start a server for the app.
This starts a blocking ioloop.
Parameters
----------
script_path : str
command_line : str
args : [str]
flag_options : Dict[str, Any]
"""
_fix_sys_path(sc... | 330 | 365 | # Copyright 2018-2021 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
distance | >>> city1 = make_city('city1', 0, 1)
>>> city2 = make_city('city2', 0, 2)
>>> distance(city1, city2)
1.0
>>> city3 = make_city('city3', 6.5, 12)
>>> city4 = make_city('city4', 2.5, 15)
>>> distance(city3, city4)
5.0 | LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... | def distance(city1, city2):
"""
>>> city1 = make_city('city1', 0, 1)
>>> city2 = make_city('city2', 0, 2)
>>> distance(city1, city2)
1.0
>>> city3 = make_city('city3', 6.5, 12)
>>> city4 = make_city('city4', 2.5, 15)
>>> distance(city3, city4)
5.0
"""
x1, y1 = get_lat(city1),... | 24 | 38 | LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... |
closer_city | Returns the name of either city1 or city2, whichever is closest to
coordinate (lat, lon).
>>> berkeley = make_city('Berkeley', 37.87, 112.26)
>>> stanford = make_city('Stanford', 34.05, 118.25)
>>> closer_city(38.33, 121.44, berkeley, stanford)
'Stanford'
>>> bucharest = make_city('Bucharest', 44.43, 26.10)
>>> vienna... | LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... | def closer_city(lat, lon, city1, city2):
"""
Returns the name of either city1 or city2, whichever is closest to
coordinate (lat, lon).
>>> berkeley = make_city('Berkeley', 37.87, 112.26)
>>> stanford = make_city('Stanford', 34.05, 118.25)
>>> closer_city(38.33, 121.44, berkeley, stanford)
'... | 40 | 61 | LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... |
build_successors_table | Return a dictionary: keys are words; values are lists of successors.
>>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
>>> table = build_successors_table(text)
>>> sorted(table)
[',', '.', 'We', 'and', 'bad', 'came', 'catch', 'eat', 'guys', 'investigate', 'pie'... | LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... | def build_successors_table(tokens):
"""Return a dictionary: keys are words; values are lists of successors.
>>> text = ['We', 'came', 'to', 'investigate', ',', 'catch', 'bad', 'guys', 'and', 'to', 'eat', 'pie', '.']
>>> table = build_successors_table(text)
>>> sorted(table)
[',', '.', 'We', 'and', ... | 335 | 356 | LAB_SOURCE_FILE = "lab05.py"
""" Lab 05: Trees and Proj2 Prep """
def couple(lst1, lst2):
"""Return a list that contains lists with i-th elements of two sequences
coupled together.
>>> lst1 = [1, 2, 3]
>>> lst2 = [4, 5, 6]
>>> couple(lst1, lst2)
[[1, 4], [2, 5], [3, 6]]
>>> lst3 = ['c', 6]... |
__init__ | Init.
Args:
name: the entity's name.
cloud_device_id: Device id iot core or any iot application.
type_name: DBO entity type stored in EntityType instance.
fields: List of standard field names.
is_reporting: if an entity maps 1:1 to a reporting device, it is a
reporting entity.
guid: [Optional] Universa... | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... | def __init__(self,
name: str,
cloud_device_id: Optional[str],
type_name: EntityType,
fields: List[EntityField],
is_reporting: bool,
guid: Optional[str] = None,
metadata: Optional[Dict[str, str]] = None):
"""In... | 42 | 69 | # Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, sof... |
build_simple_model | Build a simple model for test
Returns:
DNN, [ (input layer name, input placeholder, input data) ], Target data | '''
This file contains test cases for tflearn
'''
import tensorflow as tf
import zqtflearn
import unittest
class TestInputs(unittest.TestCase):
'''
This class contains test cases for serval input types
'''
INPUT_DATA_1 = [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ]
INPUT_DATA_2 = [ [ 6 ], [ 7 ], ... | def build_simple_model(self):
"""Build a simple model for test
Returns:
DNN, [ (input layer name, input placeholder, input data) ], Target data
"""
inputPlaceholder1, inputPlaceholder2 = \
tf.placeholder(tf.float32, (1, 1), name = "input1"), tf.placeholder(tf.... | 38 | 55 | '''
This file contains test cases for tflearn
'''
import tensorflow as tf
import zqtflearn
import unittest
class TestInputs(unittest.TestCase):
'''
This class contains test cases for serval input types
'''
INPUT_DATA_1 = [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ] ]
INPUT_DATA_2 = [ [ 6 ], [ 7 ], ... |
from_b58check | Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... | @staticmethod
def from_b58check(private_key):
""" Decodes a Base58Check encoded private-key.
Args:
private_key (str): A Base58Check encoded private key.
Returns:
PrivateKey: A PrivateKey object
"""
b58dec = base58.b58decode_check(private_key)
... | 348 | 363 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... |
raw_sign | Signs message using this private key.
Args:
message (bytes): The message to be signed. If a string is
provided it is assumed the encoding is 'ascii' and
converted to bytes. If this is not the case, it is up
to the caller to convert the string to bytes
appropriately and pass in the b... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... | def raw_sign(self, message, do_hash=True):
""" Signs message using this private key.
Args:
message (bytes): The message to be signed. If a string is
provided it is assumed the encoding is 'ascii' and
converted to bytes. If this is not the case, it is up
... | 392 | 428 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... |
sign_bitcoin | Signs a message using this private key such that it
is compatible with bitcoind, bx, and other Bitcoin
clients/nodes/utilities.
Note:
0x18 + b"Bitcoin Signed Message:" + newline + len(message) is
prepended to the message before signing.
Args:
message (bytes or str): Message to be signed.
compressed (b... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... | def sign_bitcoin(self, message, compressed=False):
""" Signs a message using this private key such that it
is compatible with bitcoind, bx, and other Bitcoin
clients/nodes/utilities.
Note:
0x18 + b\"Bitcoin Signed Message:" + newline + len(message) is
prepend... | 456 | 492 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... |
from_der | Decodes a Signature that was DER-encoded.
Args:
der (bytes or str): The DER encoding to be decoded.
Returns:
Signature: The deserialized signature. | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... | @staticmethod
def from_der(der):
""" Decodes a Signature that was DER-encoded.
Args:
der (bytes or str): The DER encoding to be decoded.
Returns:
Signature: The deserialized signature.
"""
d = get_bytes(der)
# d must conform to (from btcd... | 811 | 884 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... |
to_der | Encodes this signature using DER
Returns:
bytes: The DER encoding of (self.r, self.s). | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... | def to_der(self):
""" Encodes this signature using DER
Returns:
bytes: The DER encoding of (self.r, self.s).
"""
# Output should be:
# 0x30 <length> 0x02 <length r> r 0x02 <length s> s
r, s = self._canonicalize()
total_length = 6 + len(r) + len(s... | 971 | 983 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Code from:
https://github.com/michailbrynard/ethereum-bip44-python
This submodule provides the PublicKey, PrivateKey, and Signature classes.
It also provides HDPublicKey and HDPrivateKey classes for working with HD
wallets."""
import os
import math
import codecs
impo... |
_set_widget_id | Set the widget id.
Parameters
----------
widget_type : str
The type of the widget as stored in proto.
element : proto
The proto of the element
user_key : str
Optional user-specified key to use for the widget ID.
If this is None, we'll generate an ID by hashing the element. | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def _set_widget_id(widget_type, element, user_key=None):
"""Set the widget id.
Parameters
----------
widget_type : str
The type of the widget as stored in proto.
element : proto
The proto of the element
user_key : str
Optional user-specified key to use for the widget ID.... | 156 | 184 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
_value_or_dg | Return either value, or None, or dg.
This is needed because Widgets have meaningful return values. This is
unlike other elements, which always return None. Then we internally replace
that None with a DeltaGenerator instance.
However, sometimes a widget may want to return None, and in this case it
should not be replac... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def _value_or_dg(value, dg):
"""Return either value, or None, or dg.
This is needed because Widgets have meaningful return values. This is
unlike other elements, which always return None. Then we internally replace
that None with a DeltaGenerator instance.
However, sometimes a widget may want to r... | 3,163 | 3,179 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
_get_coordinates | Returns the element's 4-component location as string like "M.(1,2).3".
This function uniquely identifies the element's position in the front-end,
which allows (among other potential uses) the MediaFileManager to maintain
session-specific maps of MediaFile objects placed with their "coordinates".
This way, users can (... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def _get_coordinates(self):
"""Returns the element's 4-component location as string like "M.(1,2).3".
This function uniquely identifies the element's position in the front-end,
which allows (among other potential uses) the MediaFileManager to maintain
session-specific maps of MediaF... | 312 | 334 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
_enqueue_new_element_delta | Create NewElement delta, fill it, and enqueue it.
Parameters
----------
marshall_element : callable
Function which sets the fields for a NewElement protobuf.
element_width : int or None
Desired width for the element
element_height : int or None
Desired height for the element
Returns
-------
DeltaGenerator... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def _enqueue_new_element_delta(
self,
marshall_element,
delta_type,
last_index=None,
element_width=None,
element_height=None,
):
"""Create NewElement delta, fill it, and enqueue it.
Parameters
----------
marshall_element : callable... | 336 | 400 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
latex | Display mathematical expressions formatted as LaTeX.
Supported LaTeX functions are listed at
https://katex.org/docs/supported.html.
Parameters
----------
body : str or SymPy expression
The string or SymPy expression to display as LaTeX. If str, it's
a good idea to use raw Python strings since LaTeX uses backs... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def latex(self, element, body):
# This docstring needs to be "raw" because of the backslashes in the
# example below.
r"""Display mathematical expressions formatted as LaTeX.
Supported LaTeX functions are listed at
https://katex.org/docs/supported.html.
... | 516 | 551 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
json | Display object or string as a pretty-printed JSON string.
Parameters
----------
body : Object or str
The object to print as JSON. All referenced objects should be
serializable to JSON as well. If object is a string, we assume it
contains serialized JSON.
Example
-------
>>> st.json({
... 'foo': 'bar',... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def json(self, element, body):
"""Display object or string as a pretty-printed JSON string.
Parameters
----------
body : Object or str
The object to print as JSON. All referenced objects should be
serializable to JSON as well. If object is ... | 585 | 626 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
dataframe | Display a dataframe as an interactive table.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,
or None
The data to display.
If 'data' is a pandas.Styler, it will be used to style its
underyling DataFrame. Streamlit supports custom cell
values and colors. ... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | def dataframe(self, data=None, width=None, height=None):
"""Display a dataframe as an interactive table.
Parameters
----------
data : pandas.DataFrame, pandas.Styler, numpy.ndarray, Iterable, dict,
or None
The data to display.
If 'data' is a pand... | 807 | 863 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
button | Display a button widget.
Parameters
----------
label : str
A short label explaining to the user what this button is for.
key : str
An optional string to use as the unique key for the widget.
If this is omitted, a key will be generated for the widget
based on its content. Multiple widgets of the same ty... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def button(self, element, label, key=None):
"""Display a button widget.
Parameters
----------
label : str
A short label explaining to the user what this button is for.
key : str
An optional string to use as the unique key for the wi... | 1,610 | 1,642 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
text_input | Display a single-line text input widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
value : any
The text value of this widget when it first renders. This will be
cast to str internally.
max_chars : int or None
Max number of characters allowed in text ... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def text_input(
self, element, label, value="", max_chars=None, key=None, type="default"
):
"""Display a single-line text input widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
v... | 2,231 | 2,285 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
text_area | Display a multi-line text input widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
value : any
The text value of this widget when it first renders. This will be
cast to str internally.
height : int or None
Desired height of the UI element expressed in... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def text_area(
self, element, label, value="", height=None, max_chars=None, key=None
):
"""Display a multi-line text input widget.
Parameters
----------
label : str
A short label explaining to the user what this input is for.
value ... | 2,287 | 2,339 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
time_input | Display a time input widget.
Parameters
----------
label : str
A short label explaining to the user what this time input is for.
value : datetime.time/datetime.datetime
The value of this widget when it first renders. This will be
cast to str internally. Defaults to the current time.
key : str
An option... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def time_input(self, element, label, value=None, key=None):
"""Display a time input widget.
Parameters
----------
label : str
A short label explaining to the user what this time input is for.
value : datetime.time/datetime.datetime
... | 2,341 | 2,392 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
map | Display a map with points on it.
This is a wrapper around st.pydeck_chart to quickly create scatterplot
charts on top of a map, with auto-centering and auto-zoom.
When using this command, we advise all users to use a personal Mapbox
token. This ensures the map tiles used in this chart are more
robust. You can do this... | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... | @_with_element
def map(self, element, data=None, zoom=None, use_container_width=True):
"""Display a map with points on it.
This is a wrapper around st.pydeck_chart to quickly create scatterplot
charts on top of a map, with auto-centering and auto-zoom.
When using this command, ... | 2,743 | 2,788 | # Copyright 2018-2020 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
ra_dec_format | Ra/Dec string formatting
Converts the input string format of a right ascension/ declination coordinate
to one recognizable by astroquery
Args:
val (str): string; an ra/dec expression formatted as "005313.81 +130955.0".
Returns:
string: the ra/dec coordinates re-formatted as "00h53m13.81s +13d09m55.0s" | #define functions that will extract the data from SDSS based on an input RA/DEC
from astroquery.sdss import SDSS
from astropy import coordinates as coords
import pandas as pd
from astroquery.ned import Ned
import matplotlib.pyplot as plt
from astropy.convolution import convolve, Box1DKernel
import numpy as np
from a... | def ra_dec_format(val):
""" Ra/Dec string formatting
Converts the input string format of a right ascension/ declination coordinate
to one recognizable by astroquery
Args:
val (str): string; an ra/dec expression formatted as "005313.81 +130955.0".
Returns:
string: the ra/dec coordinate... | 13 | 35 | #define functions that will extract the data from SDSS based on an input RA/DEC
from astroquery.sdss import SDSS
from astropy import coordinates as coords
import pandas as pd
from astroquery.ned import Ned
import matplotlib.pyplot as plt
from astropy.convolution import convolve, Box1DKernel
import numpy as np
from a... |
evaluate | A parser which recursively evaluates the custom_variables passed against
the expression tree represented by segments, and returns the result.
Args:
segments(dict): The segments representing the expression tree
custom_variables(dict): Key/value pair of variables
Returns:
bool(result): True or False | # Copyright 2019-2021 Wingify Software Pvt. Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... | def evaluate(self, segments, custom_variables):
"""A parser which recursively evaluates the custom_variables passed against
the expression tree represented by segments, and returns the result.
Args:
segments(dict): The segments representing the expression tree
custom... | 31 | 53 | # Copyright 2019-2021 Wingify Software Pvt. Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
create_view | Create and return test view class instance
Args:
es_ordering_fields (tuple): ordering fields
Returns:
ElasticAPIView: test view instance | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... | def create_view(self, es_ordering_fields):
"""Create and return test view class instance
Args:
es_ordering_fields (tuple): ordering fields
Returns:
ElasticAPIView: test view instance
"""
view = ElasticAPIView()
view.es_ordering_fields = es_ord... | 45 | 55 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... |
create_view | Create and return test view class instance
Args:
es_filter_fields ([ESFieldFilter]): filtering fields
Returns:
ElasticAPIView: test view instance | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... | def create_view(self, es_filter_fields):
"""Create and return test view class instance
Args:
es_filter_fields ([ESFieldFilter]): filtering fields
Returns:
ElasticAPIView: test view instance
"""
view = ElasticAPIView()
view.es_model = DataDocTy... | 169 | 180 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... |
create_view | Create and return test view class instance
Args:
es_range_filter_fields ([ESFieldFilter]): filtering range fields
Returns:
ElasticAPIView: test view instance | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... | def create_view(self, es_range_filter_fields):
"""Create and return test view class instance
Args:
es_range_filter_fields ([ESFieldFilter]): filtering range fields
Returns:
ElasticAPIView: test view instance
"""
view = ElasticAPIView()
view.es... | 245 | 256 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... |
create_view | Create and return test view class instance
Args:
es_search_fields ([ESFieldFilter]): search fields
Returns:
ElasticAPIView: test view instance | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... | def create_view(self, es_search_fields):
"""Create and return test view class instance
Args:
es_search_fields ([ESFieldFilter]): search fields
Returns:
ElasticAPIView: test view instance
"""
view = ElasticAPIView()
view.es_model = DataDocType
... | 302 | 313 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from rest_framework.test import APIRequestFactory
from elasticsearch_dsl import Q
from rest_framework_elasticsearch.es_filters import (
ESFieldFilter, ElasticOrderingFilter, ElasticFieldsFilter,
ElasticFieldsRangeFilter, ElasticSear... |
initialize | Initialize inference algorithm.
Args:
step_size: float, optional.
Constant scale factor of learning rate.
friction: float, optional.
Constant scale on the friction term in the Hamiltonian system. | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
import tensorflow as tf
from edward.inferences.monte_carlo import MonteCarlo
from edward.models import RandomVariable, Empirical
from edward.util import copy
try:
from edward.models import Normal... | def initialize(self, step_size=0.25, friction=0.1, *args, **kwargs):
"""Initialize inference algorithm.
Args:
step_size: float, optional.
Constant scale factor of learning rate.
friction: float, optional.
Constant scale on the friction term in the Hamiltonian system.
"""
s... | 48 | 61 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
import tensorflow as tf
from edward.inferences.monte_carlo import MonteCarlo
from edward.models import RandomVariable, Empirical
from edward.util import copy
try:
from edward.models import Normal... |
generate | Generate the next neural architecture.
Args:
multiprocessing_queue: the Queue for multiprocessing return value.
Returns:
list of 2-element tuples: generated_graph and other_info,
for random searcher the length of list is 1.
generated_graph: An instance of Graph.
other_info: Anything to be saved in... | from random import randrange
from autokeras.bayesian import SearchTree, contain
from autokeras.net_transformer import transform
from autokeras.search import Searcher
class RandomSearcher(Searcher):
""" Class to search for neural architectures using Random search strategy.
Attributes:
search_tree: The... | def generate(self, multiprocessing_queue):
"""Generate the next neural architecture.
Args:
multiprocessing_queue: the Queue for multiprocessing return value.
Returns:
list of 2-element tuples: generated_graph and other_info,
for random searcher the lengt... | 24 | 52 | from random import randrange
from autokeras.bayesian import SearchTree, contain
from autokeras.net_transformer import transform
from autokeras.search import Searcher
class RandomSearcher(Searcher):
""" Class to search for neural architectures using Random search strategy.
Attributes:
search_tree: The... |
get_transport_class | Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use. | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | def get_transport_class(cls, label: str = None,) -> Type[JobServiceTransport]:
"""Return an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
T... | 59 | 75 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
_get_default_mtls_endpoint | Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint. | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | @staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Convert api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[st... | 83 | 110 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from_service_account_file | Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
{@api.name}: The constru... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | @classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Addition... | 117 | 133 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
create_job | Creates a new job.
Typically, the job becomes searchable within 10 seconds,
but it may take up to 5 minutes.
Args:
request (:class:`~.job_service.CreateJobRequest`):
The request object. Create job request.
parent (:class:`str`):
Required. The resource name of the tenant under which
the ... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | def create_job(
self,
request: job_service.CreateJobRequest = None,
*,
parent: str = None,
job: gct_job.Job = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> gct_job.Job:
... | 243 | 332 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
get_job | Retrieves the specified job, whose status is OPEN or
recently EXPIRED within the last 90 days.
Args:
request (:class:`~.job_service.GetJobRequest`):
The request object. Get job request.
name (:class:`str`):
Required. The resource name of the job to retrieve.
The format is
"proj... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | def get_job(
self,
request: job_service.GetJobRequest = None,
*,
name: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> job.Job:
r"""Retrieves the specified job, whose... | 437 | 517 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
list_jobs | Lists jobs by filter.
Args:
request (:class:`~.job_service.ListJobsRequest`):
The request object. List jobs request.
parent (:class:`str`):
Required. The resource name of the tenant under which
the job is created.
The format is
"projects/{project_id}/tenants/{tenant_id}... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | def list_jobs(
self,
request: job_service.ListJobsRequest = None,
*,
parent: str = None,
filter: str = None,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.ListJobsPager:... | 863 | 976 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
search_jobs | Searches for jobs using the provided
[SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
This call constrains the
[visibility][google.cloud.talent.v4beta1.Job.visibility] of jobs
present in the database, and only returns jobs that the caller
has permission to search against.
Args:
request (:class:... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | def search_jobs(
self,
request: job_service.SearchJobsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.SearchJobsPager:
r"""Searches for jobs using the provided
... | 978 | 1,042 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
search_jobs_for_alert | Searches for jobs using the provided
[SearchJobsRequest][google.cloud.talent.v4beta1.SearchJobsRequest].
This API call is intended for the use case of targeting passive
job seekers (for example, job seekers who have signed up to
receive email alerts about potential job opportunities), and has
different algorithmic adj... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | def search_jobs_for_alert(
self,
request: job_service.SearchJobsRequest = None,
*,
retry: retries.Retry = gapic_v1.method.DEFAULT,
timeout: float = None,
metadata: Sequence[Tuple[str, str]] = (),
) -> pagers.SearchJobsForAlertPager:
r"""Searches for jobs u... | 1,044 | 1,114 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
replace_material_pyleecan_obj | replace first material by the second in the object
Parameters
----------
obj: Pyleecan object
mat1: Material
material to replace
mat2: Material
new material
comp_name_path: bool
replace strictly mat1 or replace materials without comparing mat1.path and mat1.name
Returns
-------
is_change: bool
True if... | from ...Classes.Material import Material
from ...Functions.Material.compare_material import compare_material
# MASKED: replace_material_pyleecan_obj function (lines 5-56) | def replace_material_pyleecan_obj(obj, mat1, mat2, comp_name_path=True):
"""
replace first material by the second in the object
Parameters
----------
obj: Pyleecan object
mat1: Material
material to replace
mat2: Material
new material
comp_name_path: bool
replace ... | 5 | 56 | from ...Classes.Material import Material
from ...Functions.Material.compare_material import compare_material
def replace_material_pyleecan_obj(obj, mat1, mat2, comp_name_path=True):
"""
replace first material by the second in the object
Parameters
----------
obj: Pyleecan object
mat1: Materia... |
generate_anchors_for_grid_cell | Like ATSS, generate anchors based on grid size.
Args:
feats (List[Tensor]): shape[s, (b, c, h, w)]
fpn_strides (tuple|list): shape[s], stride for each scale feature
grid_cell_size (float): anchor size
grid_cell_offset (float): The range is between 0 and 1.
Returns:
anchors (List[Tensor]): shape[s, (... | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | def generate_anchors_for_grid_cell(feats,
fpn_strides,
grid_cell_size=5.0,
grid_cell_offset=0.5):
r"""
Like ATSS, generate anchors based on grid size.
Args:
feats (List[Tensor]): shape[s, (b, c, ... | 159 | 195 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
normalize | Normalize ``url`` according to policy.
:param str url: The URL to be normalized.
:returns: The normalized URL.
:rtype str: | import logging
import random
import re
from uuid import UUID
import dateutil.parser
import w3lib.url
from yarl import URL
from .captcha import CaptchaSolver
from .starbelly_pb2 import (
PatternMatch as PbPatternMatch,
PolicyRobotsTxt as PbPolicyRobotsTxt,
PolicyUrlRule as PbPolicyUrlRule
)
logger = logg... | def normalize(self, url):
'''
Normalize ``url`` according to policy.
:param str url: The URL to be normalized.
:returns: The normalized URL.
:rtype str:
'''
if self._enabled:
if self._strip_parameters:
url = w3lib.url.url_query_cle... | 607 | 622 | import logging
import random
import re
from uuid import UUID
import dateutil.parser
import w3lib.url
from yarl import URL
from .captcha import CaptchaSolver
from .starbelly_pb2 import (
PatternMatch as PbPatternMatch,
PolicyRobotsTxt as PbPolicyRobotsTxt,
PolicyUrlRule as PbPolicyUrlRule
)
logger = logg... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.