code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def get_request_setting(self, service_id, version_number, name):
"""Gets the specified Request Settings object."""
content = self._fetch("/service/%s/version/%d/request_settings/%s" % (service_id, version_number, name))
return FastlyRequestSetting(self, content) | Gets the specified Request Settings object. |
def _Operation(self,operation):
"""Execute specified operations task against one or more servers.
Returns a clc.v2.Requests object. If error due to server(s) already being in
the requested state this is not raised as an error at this level.
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').PowerOn().WaitUntil... | Execute specified operations task against one or more servers.
Returns a clc.v2.Requests object. If error due to server(s) already being in
the requested state this is not raised as an error at this level.
>>> clc.v2.Server(alias='BTDI',id='WA1BTDIKRT02').PowerOn().WaitUntilComplete()
0 |
def update_subports(self, port):
"""Set port attributes for trunk subports.
For baremetal deployments only, set the neutron port attributes
during the bind_port event.
"""
trunk_details = port.get('trunk_details')
subports = trunk_details['sub_ports']
host_id = ... | Set port attributes for trunk subports.
For baremetal deployments only, set the neutron port attributes
during the bind_port event. |
def is_secret_known(
end_state: NettingChannelEndState,
secrethash: SecretHash,
) -> bool:
"""True if the `secrethash` is for a lock with a known secret."""
return (
secrethash in end_state.secrethashes_to_unlockedlocks or
secrethash in end_state.secrethashes_to_onchain_unlockedl... | True if the `secrethash` is for a lock with a known secret. |
def createEditor(self, parent, option, index):
"""Returns the widget used to edit the item specified by index for editing. The parent widget and style option are used to control how the editor widget appears.
Args:
parent (QWidget): parent widget.
option (QStyleOptionViewItem): ... | Returns the widget used to edit the item specified by index for editing. The parent widget and style option are used to control how the editor widget appears.
Args:
parent (QWidget): parent widget.
option (QStyleOptionViewItem): controls how editor widget appears.
index (QMo... |
def _build_predict(self, Xnew, full_cov=False):
"""
Xnew is a data matrix, the points at which we want to predict.
This method computes
p(F* | Y)
where F* are points on the GP at Xnew, Y are noisy observations at X.
"""
y = self.Y - self.mean_function(self... | Xnew is a data matrix, the points at which we want to predict.
This method computes
p(F* | Y)
where F* are points on the GP at Xnew, Y are noisy observations at X. |
def _collect_capacity_curves(data, direction="charge"):
"""Create a list of pandas.DataFrames, one for each charge step.
The DataFrames are named by its cycle number.
Input: CellpyData
Returns: list of pandas.DataFrames
minimum voltage value,
maximum voltage value"""
minimum_v_val... | Create a list of pandas.DataFrames, one for each charge step.
The DataFrames are named by its cycle number.
Input: CellpyData
Returns: list of pandas.DataFrames
minimum voltage value,
maximum voltage value |
def load_sub_plugins_from_str(cls, plugins_str):
"""
Load plugin classes based on column separated list of plugin names.
Returns dict with plugin name as key and class as value.
"""
plugin_classes = {}
if plugins_str:
for plugin_name in plugins_str.split(":"... | Load plugin classes based on column separated list of plugin names.
Returns dict with plugin name as key and class as value. |
def _get_content_length(self,msg):
'''从消息中解析Content-length'''
m = re.search(r'[Cc]ontent-length:\s?(?P<len>\d+)',msg,re.S)
return (m and int(m.group('len'))) or 0 | 从消息中解析Content-length |
def create_branches(self, branches):
"""
Create branches from a TreeBuffer or dict mapping names to type names
Parameters
----------
branches : TreeBuffer or dict
"""
if not isinstance(branches, TreeBuffer):
branches = TreeBuffer(branches)
sel... | Create branches from a TreeBuffer or dict mapping names to type names
Parameters
----------
branches : TreeBuffer or dict |
def read_config(cls, configparser):
"""Read configuration file options."""
config = dict()
section = cls.__name__
option = "prefixes"
if configparser.has_option(section, option):
value = configparser.get(section, option)
names = [x.strip().lower() for x in... | Read configuration file options. |
def get_group(value):
""" group = display-name ":" [group-list] ";" [CFWS]
"""
group = Group()
token, value = get_display_name(value)
if not value or value[0] != ':':
raise errors.HeaderParseError("expected ':' at end of group "
"display name but found '{}'".format(value))
g... | group = display-name ":" [group-list] ";" [CFWS] |
def get_client(service, service_type='client', **conn_args):
"""
User function to get the correct client.
Based on the GOOGLE_CLIENT_MAP dictionary, the return will be a cloud or general
client that can interact with the desired service.
:param service: GCP service to connect to. E.g. 'gce', 'iam'... | User function to get the correct client.
Based on the GOOGLE_CLIENT_MAP dictionary, the return will be a cloud or general
client that can interact with the desired service.
:param service: GCP service to connect to. E.g. 'gce', 'iam'
:type service: ``str``
:param conn_args: Dictionary of connecti... |
def _rm_units_from_var_name_single(var):
"""
NOTE: USE THIS FOR SINGLE CELLS ONLY
When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections
However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes pro... | NOTE: USE THIS FOR SINGLE CELLS ONLY
When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections
However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes problems.
We're using this regex to match all variab... |
def cost_matrix(self, set_a, set_b, time_a, time_b):
"""
Calculates the costs (distances) between the items in set a and set b at the specified times.
Args:
set_a: List of STObjects
set_b: List of STObjects
time_a: time at which objects in set_a are evaluated... | Calculates the costs (distances) between the items in set a and set b at the specified times.
Args:
set_a: List of STObjects
set_b: List of STObjects
time_a: time at which objects in set_a are evaluated
time_b: time at whcih object in set_b are evaluated
... |
def serialize(v, known_modules=[]):
'''Get a text representation of an object.'''
tname = name(v, known_modules=known_modules)
func = serializer(tname)
return func(v), tname | Get a text representation of an object. |
def _compile_docker_commands(app_name, assembled_specs, port_spec):
""" This is used to compile the command that will be run when the docker container starts
up. This command has to install any libs that the app uses, run the `always` command, and
run the `once` command if the container is being launched fo... | This is used to compile the command that will be run when the docker container starts
up. This command has to install any libs that the app uses, run the `always` command, and
run the `once` command if the container is being launched for the first time |
def scale_down(self, workers, pods=None):
""" Remove the pods for the requested list of workers
When scale_down is called by the _adapt async loop, the workers are
assumed to have been cleanly closed first and in-memory data has been
migrated to the remaining workers.
Note that... | Remove the pods for the requested list of workers
When scale_down is called by the _adapt async loop, the workers are
assumed to have been cleanly closed first and in-memory data has been
migrated to the remaining workers.
Note that when the worker process exits, Kubernetes leaves the ... |
def ng_call_ctrl_function(self, element, func, params='', return_out=False):
"""
:Description: Will execute controller function with provided parameters.
:Warning: This will only work for angular.js 1.x.
:Warning: Requires angular debugging to be enabled.
:param element: Element ... | :Description: Will execute controller function with provided parameters.
:Warning: This will only work for angular.js 1.x.
:Warning: Requires angular debugging to be enabled.
:param element: Element for browser instance to target.
:param func: Function to execute from angular element con... |
def run_sql_script(conn, scriptname='results_md2grid.sql'):
"""This function runs .sql scripts in the folder 'sql_scripts' """
script_dir = os.path.abspath(
os.path.join(os.path.dirname(__file__), 'sql_scripts'))
script_str = open(os.path.join(script_dir, scriptname)).read()
conn.execution_opti... | This function runs .sql scripts in the folder 'sql_scripts' |
def find(self, title):
"""Return the first worksheet with the given title.
Args:
title(str): title/name of the worksheet to return
Returns:
WorkSheet: contained worksheet object
Raises:
KeyError: if the spreadsheet has no no worksheet with the given `... | Return the first worksheet with the given title.
Args:
title(str): title/name of the worksheet to return
Returns:
WorkSheet: contained worksheet object
Raises:
KeyError: if the spreadsheet has no no worksheet with the given ``title`` |
def get_app_perms(model_or_app_label):
"""
Get permission-string list of the specified django application.
Parameters
----------
model_or_app_label : model class or string
A model class or app_label string to specify the particular django
application.
Returns
-------
se... | Get permission-string list of the specified django application.
Parameters
----------
model_or_app_label : model class or string
A model class or app_label string to specify the particular django
application.
Returns
-------
set
A set of perms of the specified django ap... |
def _extract_stars(data, catalog, size=(11, 11), use_xy=True):
"""
Extract cutout images from a single image centered on stars defined
in the single input catalog.
Parameters
----------
data : `~astropy.nddata.NDData`
A `~astropy.nddata.NDData` object containing the 2D image from
... | Extract cutout images from a single image centered on stars defined
in the single input catalog.
Parameters
----------
data : `~astropy.nddata.NDData`
A `~astropy.nddata.NDData` object containing the 2D image from
which to extract the stars. If the input ``catalog`` contains
on... |
def start(self, *args):
"""
Create a singularity container instance
"""
if self.volumes:
volumes = " --bind " + " --bind ".join(self.volumes)
else:
volumes = ""
self._print("Instantiating container [{0:s}]. Timeout set to {1:d}. The cont... | Create a singularity container instance |
def reset(cls):
"""
Reset the conspect elements to initial state.
"""
cls.input_el.value = ""
cls.subconspect_el.html = ""
cls.show_error(False) | Reset the conspect elements to initial state. |
def make_fileitem_peinfo_detectedentrypointsignature_name(entrypoint_name, condition='is', negate=False,
preserve_case=False):
"""
Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name
:return: A IndicatorItem represented as an Elem... | Create a node for FileItem/PEInfo/DetectedEntryPointSignature/Name
:return: A IndicatorItem represented as an Element node |
def _insert_code(code_to_modify, code_to_insert, before_line):
"""
Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the
instruction on this line by modifying original bytecode
:param code_to_modify: Code to modify
:param code_to_insert: Code to in... | Insert piece of code `code_to_insert` to `code_to_modify` right inside the line `before_line` before the
instruction on this line by modifying original bytecode
:param code_to_modify: Code to modify
:param code_to_insert: Code to insert
:param before_line: Number of line for code insertion
:return:... |
def upload_model(self, path: str, meta: dict, force: bool) -> str:
"""
Put the given file to the remote storage.
:param path: Path to the model file.
:param meta: Metadata of the model.
:param force: Overwrite an existing model.
:return: URL of the uploaded model.
... | Put the given file to the remote storage.
:param path: Path to the model file.
:param meta: Metadata of the model.
:param force: Overwrite an existing model.
:return: URL of the uploaded model.
:raises BackendRequiredError: If supplied bucket is unusable.
:raises ModelAl... |
def get_blink_cookie(self, name):
"""Gets a blink cookie value"""
value = self.get_cookie(name)
if value != None:
self.clear_cookie(name)
return escape.url_unescape(value) | Gets a blink cookie value |
def _decode(s, encoding=None, errors=None):
"""Decodes *s*."""
if encoding is None:
encoding = ENCODING
if errors is None:
errors = ENCODING_ERRORS
return s if isinstance(s, unicode) else s.decode(encoding, errors) | Decodes *s*. |
def _handle_unknown_method(self, method, remainder, request=None):
'''
Routes undefined actions (like RESET) to the appropriate controller.
'''
if request is None:
self._raise_method_deprecation_warning(self._handle_unknown_method)
# try finding a post_{custom} or {c... | Routes undefined actions (like RESET) to the appropriate controller. |
def _override_cfg(container, yamlkeys, value):
"""
Override a hierarchical key in the config, setting it to the value.
Note that yamlkeys should be a non-empty list of strings.
"""
key = yamlkeys[0]
rest = yamlkeys[1:]
if len(rest) == 0:
# no rest means we found the key to update.... | Override a hierarchical key in the config, setting it to the value.
Note that yamlkeys should be a non-empty list of strings. |
def process_data_config_section(config, data_config):
""" Processes the data configuration section from the configuration
data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param data_config: Data configuration section from a co... | Processes the data configuration section from the configuration
data dict.
:param config: The config reference of the object that will hold the
configuration data from the config_data.
:param data_config: Data configuration section from a config data dict. |
def _release_waiter(self) -> None:
"""
Iterates over all waiters till found one that is not finsihed and
belongs to a host that has available connections.
"""
if not self._waiters:
return
# Having the dict keys ordered this avoids to iterate
# at the ... | Iterates over all waiters till found one that is not finsihed and
belongs to a host that has available connections. |
def _startJobWithRetries(self, jobID):
""" Place the given job in STATUS_RUNNING mode; the job is expected to be
STATUS_NOTSTARTED.
NOTE: this function was factored out of jobStartNext because it's also
needed for testing (e.g., test_client_jobs_dao.py)
"""
with ConnectionFactory.get() as conn... | Place the given job in STATUS_RUNNING mode; the job is expected to be
STATUS_NOTSTARTED.
NOTE: this function was factored out of jobStartNext because it's also
needed for testing (e.g., test_client_jobs_dao.py) |
def _get_seal_key_ntlm1(negotiate_flags, exported_session_key):
"""
3.4.5.3 SEALKEY
Calculates the seal_key used to seal (encrypt) messages. This for
authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has not
been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_56 is not
negot... | 3.4.5.3 SEALKEY
Calculates the seal_key used to seal (encrypt) messages. This for
authentication where NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY has not
been negotiated. Will weaken the keys if NTLMSSP_NEGOTIATE_56 is not
negotiated it will default to the 40-bit key
:param negotiate_flags: The neg... |
def request(self, batch, attempt=0):
"""Attempt to upload the batch and retry before raising an error """
try:
q = self.api.new_queue()
for msg in batch:
q.add(msg['event'], msg['value'], source=msg['source'])
q.submit()
except:
if ... | Attempt to upload the batch and retry before raising an error |
def _GetFormatErrorLocation(
self, yaml_definition, last_definition_object):
"""Retrieves a format error location.
Args:
yaml_definition (dict[str, object]): current YAML definition.
last_definition_object (DataTypeDefinition): previous data type
definition.
Returns:
str:... | Retrieves a format error location.
Args:
yaml_definition (dict[str, object]): current YAML definition.
last_definition_object (DataTypeDefinition): previous data type
definition.
Returns:
str: format error location. |
def encode(secret: Union[str, bytes], payload: dict = None,
alg: str = default_alg, header: dict = None) -> str:
"""
:param secret: The secret used to encode the token.
:type secret: Union[str, bytes]
:param payload: The payload to be encoded in the token.
:type payload: dict
:param a... | :param secret: The secret used to encode the token.
:type secret: Union[str, bytes]
:param payload: The payload to be encoded in the token.
:type payload: dict
:param alg: The algorithm used to hash the token.
:type alg: str
:param header: The header to be encoded in the token.
:type header:... |
def get_policy(policy_name,
region=None, key=None, keyid=None, profile=None):
'''
Check to see if policy exists.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.instance_profile_exists myiprofile
'''
conn = _get_conn(region=region, key=key, keyid=keyid, profile... | Check to see if policy exists.
CLI Example:
.. code-block:: bash
salt myminion boto_iam.instance_profile_exists myiprofile |
def CollectData(self):
"""Return some current samples. Call StartDataCollection() first.
"""
while 1: # loop until we get data or a timeout
_bytes = self._ReadPacket()
if not _bytes:
return None
if len(_bytes) < 4 + 8 + 1 or _bytes[0] < 0x20 o... | Return some current samples. Call StartDataCollection() first. |
def __gzip(filename):
""" Compress a file returning the new filename (.gz)
"""
zipname = filename + '.gz'
file_pointer = open(filename,'rb')
zip_pointer = gzip.open(zipname,'wb')
zip_pointer.writelines(file_pointer)
file_pointer.close()
zip_pointer.close()
return zipname | Compress a file returning the new filename (.gz) |
def clear_lock(self, abspath=True):
"""Clean any conda lock in the system."""
cmd_list = ['clean', '--lock', '--json']
return self._call_and_parse(cmd_list, abspath=abspath) | Clean any conda lock in the system. |
def slice(self, *slice_args, **kwargs):
"""Create a new SampleSet with rows sliced according to standard Python
slicing syntax.
Args:
start (int, optional, default=None):
Start index for `slice`.
stop (int):
Stop index for `slice`.
... | Create a new SampleSet with rows sliced according to standard Python
slicing syntax.
Args:
start (int, optional, default=None):
Start index for `slice`.
stop (int):
Stop index for `slice`.
step (int, optional, default=None):
... |
def call_git_branch():
"""return the string output of git desribe"""
try:
with open(devnull, "w") as fnull:
arguments = [GIT_COMMAND, 'rev-parse', '--abbrev-ref', 'HEAD']
return check_output(arguments, cwd=CURRENT_DIRECTORY,
stderr=fnull).decode("a... | return the string output of git desribe |
def geom_find_rotsymm(g, atwts, ax, improp, \
nmax=_DEF.SYMM_MATCH_NMAX, \
tol=_DEF.SYMM_MATCH_TOL):
""" Identify highest-order symmetry for a geometry on a given axis.
Regular and improper axes possible.
.. todo:: Complete geom_find_rotsymm docstring
"""
# Imports
import num... | Identify highest-order symmetry for a geometry on a given axis.
Regular and improper axes possible.
.. todo:: Complete geom_find_rotsymm docstring |
def mod2pi(ts):
"""For a timeseries where all variables represent phases (in radians),
return an equivalent timeseries where all values are in the range (-pi, pi]
"""
return np.pi - np.mod(np.pi - ts, 2*np.pi) | For a timeseries where all variables represent phases (in radians),
return an equivalent timeseries where all values are in the range (-pi, pi] |
def get_nearest_points_dirty(self, center_point, radius, unit='km'):
"""
return approx list of point from circle with given center and radius
it uses geohash and return with some error (see GEO_HASH_ERRORS)
:param center_point: center of search circle
:param radius: radius of sea... | return approx list of point from circle with given center and radius
it uses geohash and return with some error (see GEO_HASH_ERRORS)
:param center_point: center of search circle
:param radius: radius of search circle
:return: list of GeoPoints from given area |
def convert_areaSource(self, node):
"""
Convert the given node into an area source object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.AreaSource` instance
"""
geom = node.areaGeometry
coords = split_coords_2d(~geom.Po... | Convert the given node into an area source object.
:param node: a node with tag areaGeometry
:returns: a :class:`openquake.hazardlib.source.AreaSource` instance |
def make_movie(workdir, pf, dpi=120, fps=1, format="pdf", engine="ffmpeg"):
""" Make the movie using either ffmpeg or gifsicle.
"""
os.chdir(workdir)
if format != "png":
cmd = "parallel convert -density {}".format(dpi)
cmd += " {} {.}.png ::: " + "*.{}".format(format)
sh(cmd)
... | Make the movie using either ffmpeg or gifsicle. |
def _run_process(self, start_path, stop_path, process_num=0):
"""
The function calls _run_path for given set of paths
"""
# pre processing
self.producer.initialize_worker(process_num)
self.consumer.initialize_worker(process_num)
# processing
for path in r... | The function calls _run_path for given set of paths |
def _get_lowstate(self):
'''
Format the incoming data into a lowstate object
'''
if not self.request.body:
return
data = self.deserialize(self.request.body)
self.request_payload = copy(data)
if data and 'arg' in data and not isinstance(data['arg'], li... | Format the incoming data into a lowstate object |
def normalize_variables(cls, variables):
"""Make sure version is treated consistently
"""
# if the version is False, empty string, etc, throw it out
if variables.get('version', True) in ('', False, '_NO_VERSION', None):
del variables['version']
return super(PackageRes... | Make sure version is treated consistently |
def check_and_get_data(input_list,**pars):
"""Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list:... | Verify that all specified files are present. If not, retrieve them from MAST.
Parameters
----------
input_list : list
List of one or more calibrated fits images that will be used for catalog generation.
Returns
=======
total_input_list: list
list of full filenames |
def forward_backward(self, x):
"""forward backward implementation"""
with mx.autograd.record():
(ls, next_sentence_label, classified, masked_id, decoded, \
masked_weight, ls1, ls2, valid_length) = forward(x, self._model, self._mlm_loss,
... | forward backward implementation |
def save_itemgetter(self, obj):
"""itemgetter serializer (needed for namedtuple support)"""
class Dummy:
def __getitem__(self, item):
return item
items = obj(Dummy())
if not isinstance(items, tuple):
items = (items,)
return self.save_reduce... | itemgetter serializer (needed for namedtuple support) |
def __validate_dates(start_date, end_date):
"""Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year.
"""
try:
start_date = datetime.datetime.strptime(start_date, '%Y-%m-%d')
end_date = datetime.datetime.str... | Validate if a date string.
Validate if a string is a date on yyyy-mm-dd format and it the
period between them is less than a year. |
def decrypt_with_ad(self, ad: bytes, ciphertext: bytes) -> bytes:
"""
If k is non-empty returns DECRYPT(k, n++, ad, ciphertext). Otherwise returns ciphertext. If an authentication
failure occurs in DECRYPT() then n is not incremented and an error is signaled to the caller.
:param a... | If k is non-empty returns DECRYPT(k, n++, ad, ciphertext). Otherwise returns ciphertext. If an authentication
failure occurs in DECRYPT() then n is not incremented and an error is signaled to the caller.
:param ad: bytes sequence
:param ciphertext: bytes sequence
:return: plaintext... |
def validate_input(self):
"""Raise appropriate exception if gate was defined incorrectly."""
if self.vert[1] <= self.vert[0]:
raise ValueError(u'{} must be larger than {}'.format(self.vert[1], self.vert[0])) | Raise appropriate exception if gate was defined incorrectly. |
def run(self):
"""Loop forever, pushing out stats."""
self.graphite.start()
while True:
log.debug('Graphite pusher is sleeping for %d seconds', self.period)
time.sleep(self.period)
log.debug('Pushing stats to Graphite')
try:
self.push()
log.debug('Done pushing stats t... | Loop forever, pushing out stats. |
def streams(self):
"""Returns a :class:`StreamingQueryManager` that allows managing all the
:class:`StreamingQuery` StreamingQueries active on `this` context.
.. note:: Evolving.
"""
from pyspark.sql.streaming import StreamingQueryManager
return StreamingQueryManager(sel... | Returns a :class:`StreamingQueryManager` that allows managing all the
:class:`StreamingQuery` StreamingQueries active on `this` context.
.. note:: Evolving. |
def _init_map(self):
"""stub"""
TextAnswerFormRecord._init_map(self)
FilesAnswerFormRecord._init_map(self)
super(AnswerTextAndFilesMixin, self)._init_map() | stub |
def broadcast(self, data_dict):
'''
Send to the visualizer (if there is one) or enqueue for later
'''
if self.vis_socket:
self.queued_messages.append(data_dict)
self.send_all_updates() | Send to the visualizer (if there is one) or enqueue for later |
def get_iso3_country_code(cls, country, use_live=True, exception=None):
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
"""Get ISO3 code for cls. Only exact matches or None are returned.
Args:
country (str): Country for which to get ISO3 code
use_live... | Get ISO3 code for cls. Only exact matches or None are returned.
Args:
country (str): Country for which to get ISO3 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception... |
def get_locations():
"""
Pull the accounts locations.
"""
arequest = requests.get(LOCATIONS_URL, headers=HEADERS)
status_code = str(arequest.status_code)
if status_code == '401':
_LOGGER.error("Token expired.")
return False
return arequest.... | Pull the accounts locations. |
def main():
"""
Project's main method which will parse the command line arguments, run a
scan using the TagCubeClient and exit.
"""
cmd_args = TagCubeCLI.parse_args()
try:
tagcube_cli = TagCubeCLI.from_cmd_args(cmd_args)
except ValueError, ve:
# We get here when there are no... | Project's main method which will parse the command line arguments, run a
scan using the TagCubeClient and exit. |
def new(self, data):
"""通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description]
"""
temp = copy(self)
temp.__init__(data)
return temp | 通过data新建一个stock_block
Arguments:
data {[type]} -- [description]
Returns:
[type] -- [description] |
def generate_orbital_path(self, factor=3., n_points=20, viewup=None, z_shift=None):
"""Genrates an orbital path around the data scene
Parameters
----------
facotr : float
A scaling factor when biulding the orbital extent
n_points : int
number of points o... | Genrates an orbital path around the data scene
Parameters
----------
facotr : float
A scaling factor when biulding the orbital extent
n_points : int
number of points on the orbital path
viewup : list(float)
the normal to the orbital plane
... |
def multiply(traj, result_list):
"""Example of a sophisticated simulation that involves multiplying two values.
This time we will store tha value in a shared list and only in the end add the result.
:param traj:
Trajectory containing
the parameters in a particular combination,
it ... | Example of a sophisticated simulation that involves multiplying two values.
This time we will store tha value in a shared list and only in the end add the result.
:param traj:
Trajectory containing
the parameters in a particular combination,
it also serves as a container for results. |
def add(self, pattern, function, method=None, type_cast=None):
"""Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to d... | Function for registering a path pattern.
Args:
pattern (str): Regex pattern to match a certain path.
function (function): Function to associate with this path.
method (str, optional): Usually used to define one of GET, POST,
PUT, DELETE. You may use whatever ... |
def OnActivateReader(self, event):
"""Called when the user activates a reader in the tree."""
item = event.GetItem()
if item:
itemdata = self.readertreepanel.readertreectrl.GetItemPyData(item)
if isinstance(itemdata, smartcard.Card.Card):
self.ActivateCard... | Called when the user activates a reader in the tree. |
def on_demand_annotation(twitter_app_key, twitter_app_secret, user_twitter_id):
"""
A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this.
"""
##################################################################################################################... | A service that leverages twitter lists for on-demand annotation of popular users.
TODO: Do this. |
def notification_selected_sm_changed(self, model, prop_name, info):
"""If a new state machine is selected, make sure the tab is open"""
selected_state_machine_id = self.model.selected_state_machine_id
if selected_state_machine_id is None:
return
page_id = self.get_page_num(s... | If a new state machine is selected, make sure the tab is open |
def next_population(self, population, fitnesses):
"""Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
lis... | Make a new population after each optimization iteration.
Args:
population: The population current population of solutions.
fitnesses: The fitness associated with each solution in the population
Returns:
list; a list of solutions. |
def finalize(self):
"""
finalize simulation for consumer
"""
super(StringWriterConsumer, self).finalize()
self.result = self.decoder(self.result) | finalize simulation for consumer |
def fen(self, *, shredder: bool = False, en_passant: str = "legal", promoted: Optional[bool] = None) -> str:
"""
Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~che... | Gets a FEN representation of the position.
A FEN string (e.g.,
``rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1``) consists
of the position part :func:`~chess.Board.board_fen()`, the
:data:`~chess.Board.turn`, the castling part
(:data:`~chess.Board.castling_rights`),
... |
def day(self):
'''set unit to day'''
self.magnification = 86400
self._update(self.baseNumber, self.magnification)
return self | set unit to day |
def compareBIMfiles(beforeFileName, afterFileName, outputFileName):
"""Compare two BIM files for differences.
:param beforeFileName: the name of the file before modification.
:param afterFileName: the name of the file after modification.
:param outputFileName: the name of the output file (containing th... | Compare two BIM files for differences.
:param beforeFileName: the name of the file before modification.
:param afterFileName: the name of the file after modification.
:param outputFileName: the name of the output file (containing the
differences between the ``before`` and the ``a... |
def split_on(word: str, section: str) -> Tuple[str, str]:
"""
Given a string, split on a section, and return the two sections as a tuple.
:param word:
:param section:
:return:
>>> split_on('hamrye', 'ham')
('ham', 'rye')
"""
return word[:word.index(section)] + section, word[word.in... | Given a string, split on a section, and return the two sections as a tuple.
:param word:
:param section:
:return:
>>> split_on('hamrye', 'ham')
('ham', 'rye') |
def canvasReleaseEvent(self, e):
"""Handle canvas release events has finished capturing e.
:param e: A Qt event object.
:type: QEvent
"""
_ = e # NOQA
self.is_emitting_point = False
self.rectangle_created.emit() | Handle canvas release events has finished capturing e.
:param e: A Qt event object.
:type: QEvent |
def ctrl_srfc_pt_send(self, target, bitfieldPt, force_mavlink1=False):
'''
This message sets the control surfaces for selective passthrough mode.
target : The system setting the commands (uint8_t)
bitfieldPt : Bitfield co... | This message sets the control surfaces for selective passthrough mode.
target : The system setting the commands (uint8_t)
bitfieldPt : Bitfield containing the passthrough configuration, see CONTROL_SURFACE_FLAG ENUM. (uint16_t) |
def progression_sinusoidal(week, start_weight, final_weight, start_week,
end_week,
periods=2, scale=0.025, offset=0):
"""A sinusoidal progression function going through the points
('start_week', 'start_weight') and ('end_week', 'final_weight'), evaluated
... | A sinusoidal progression function going through the points
('start_week', 'start_weight') and ('end_week', 'final_weight'), evaluated
in 'week'. This function calls a linear progression function
and multiplies it by a sinusoid.
Parameters
----------
week
The week to evaluate the linear ... |
def mask(args):
"""
%prog mask data.bin samples.ids STR.ids meta.tsv
OR
%prog mask data.tsv meta.tsv
Compute P-values based on meta and data. The `data.bin` should be the matrix
containing filtered loci and the output mask.tsv will have the same
dimension.
"""
p = OptionParser(mas... | %prog mask data.bin samples.ids STR.ids meta.tsv
OR
%prog mask data.tsv meta.tsv
Compute P-values based on meta and data. The `data.bin` should be the matrix
containing filtered loci and the output mask.tsv will have the same
dimension. |
def saveCustomParams(self, data):
"""
Send custom dictionary to Polyglot to save and be retrieved on startup.
:param data: Dictionary of key value pairs to store in Polyglot database.
"""
LOGGER.info('Sending customParams to Polyglot.')
message = { 'customparams': data }... | Send custom dictionary to Polyglot to save and be retrieved on startup.
:param data: Dictionary of key value pairs to store in Polyglot database. |
def delete(args):
"""Delete nodes from the cluster
"""
nodes = [ClusterNode.from_uri(n) for n in args.nodes]
cluster = Cluster.from_node(ClusterNode.from_uri(args.cluster))
echo("Deleting...")
for node in nodes:
cluster.delete_node(node)
cluster.wait() | Delete nodes from the cluster |
def bedtools_merge(data, sample):
"""
Get all contiguous genomic regions with one or more overlapping
reads. This is the shell command we'll eventually run
bedtools bamtobed -i 1A_0.sorted.bam | bedtools merge [-d 100]
-i <input_bam> : specifies the input file to bed'ize
-d <int> ... | Get all contiguous genomic regions with one or more overlapping
reads. This is the shell command we'll eventually run
bedtools bamtobed -i 1A_0.sorted.bam | bedtools merge [-d 100]
-i <input_bam> : specifies the input file to bed'ize
-d <int> : For PE set max distance between reads |
def log_response(self, response):
"""
Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
... | Helper method provided to enable the logging of responses in case if
the :attr:`HttpProtocol.access_log` is enabled.
:param response: Response generated for the current request
:type response: :class:`sanic.response.HTTPResponse` or
:class:`sanic.response.StreamingHTTPResponse`
... |
def pdf(self, x, e=0., w=1., a=0.):
"""
probability density function
see: https://en.wikipedia.org/wiki/Skew_normal_distribution
:param x: input value
:param e:
:param w:
:param a:
:return:
"""
t = (x-e) / w
return 2. / w * stats.no... | probability density function
see: https://en.wikipedia.org/wiki/Skew_normal_distribution
:param x: input value
:param e:
:param w:
:param a:
:return: |
def _extended_gcd(self, a, b):
"""
Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t
"""
s, old_s = 0, 1
t, old_t = 1, 0
r, old_r = b, a
while ... | Extended Euclidean algorithms to solve Bezout's identity:
a*x + b*y = gcd(x, y)
Finds one particular solution for x, y: s, t
Returns: gcd, s, t |
def determine_result(self, returncode, returnsignal, output, isTimeout):
"""
Parse the output of the tool and extract the verification result.
This method always needs to be overridden.
If the tool gave a result, this method needs to return one of the
benchexec.result.RESULT_* st... | Parse the output of the tool and extract the verification result.
This method always needs to be overridden.
If the tool gave a result, this method needs to return one of the
benchexec.result.RESULT_* strings.
Otherwise an arbitrary string can be returned that will be shown to the user
... |
def send_batches(self, batch_list):
"""Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict
"""
if isinstance(batch_list, BaseMessage):
batch_list = ... | Sends a list of batches to the validator.
Args:
batch_list (:obj:`BatchList`): the list of batches
Returns:
dict: the json result data, as a dict |
def OnTextColor(self, event):
"""Text color choice event handler"""
color = event.GetValue().GetRGB()
post_command_event(self, self.TextColorMsg, color=color) | Text color choice event handler |
def get_form_value(self, form_key, object_brain_uid, default=None):
"""Returns a value from the request's form for the given uid, if any
"""
if form_key not in self.request.form:
return default
uid = object_brain_uid
if not api.is_uid(uid):
uid = api.get_... | Returns a value from the request's form for the given uid, if any |
def _remove_add_key(self, key):
"""Move a key to the end of the linked list and discard old entries."""
if not hasattr(self, '_queue'):
return # haven't initialized yet, so don't bother
if key in self._queue:
self._queue.remove(key)
self._queue.append(key)
... | Move a key to the end of the linked list and discard old entries. |
def reynolds(target, u0, b, temperature='pore.temperature'):
r"""
Uses exponential model by Reynolds [1] for the temperature dependance of
shear viscosity
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the len... | r"""
Uses exponential model by Reynolds [1] for the temperature dependance of
shear viscosity
Parameters
----------
target : OpenPNM Object
The object for which these values are being calculated. This
controls the length of the calculated array, and also provides
access to ... |
def address_by_interface(ifname):
"""Returns the IP address of the given interface name, e.g. 'eth0'
Parameters
----------
ifname : str
Name of the interface whose address is to be returned. Required.
Taken from this Stack Overflow answer: https://stackoverflow.com/questions/24196932/how-c... | Returns the IP address of the given interface name, e.g. 'eth0'
Parameters
----------
ifname : str
Name of the interface whose address is to be returned. Required.
Taken from this Stack Overflow answer: https://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python... |
def status(name, sig=None):
'''
Return the status for a service.
If the name contains globbing, a dict mapping service name to PID or empty
string is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the ser... | Return the status for a service.
If the name contains globbing, a dict mapping service name to PID or empty
string is returned.
.. versionchanged:: 2018.3.0
The service name can now be a glob (e.g. ``salt*``)
Args:
name (str): The name of the service to check
sig (str): Signatu... |
def decode(self, covertext):
"""Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``.
"""
if not isinstance(covertext, str):
raise InvalidInputException('Input must be of type string.')
insufficient = (len(covertext) < self._fixed_slice)
if insufficient:
... | Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. |
def add_progress(self, count, symbol='#',
color=None, on_color=None, attrs=None):
"""Add a section of progress to the progressbar.
The progress is captured by "count" and displayed as a fraction
of the statusbar width proportional to this count over the total
progre... | Add a section of progress to the progressbar.
The progress is captured by "count" and displayed as a fraction
of the statusbar width proportional to this count over the total
progress displayed. The progress will be displayed using the "symbol"
character and the foreground and backgroun... |
def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
# create input matrix and target vector
self.x_mem[:,1:] = self.x_mem[:,:-1]
... | Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.