code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def custom_observable_object_prefix_lax(instance):
for key, obj in instance['objects'].items():
if ('type' in obj and obj['type'] not in enums.OBSERVABLE_TYPES and
obj['type'] not in enums.OBSERVABLE_RESERVED_OBJECTS and
not CUSTOM_TYPE_LAX_PREFIX_RE.match(obj['type'])):
yield JSONError("Custom Observable Object type '%s' should start "
"with 'x-'."
% obj['type'], instance['id'],
'custom-prefix-lax') | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list block if_statement parenthesized_expression boolean_operator boolean_operator boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier not_operator call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end block expression_statement yield call identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end string string_start string_content string_end | Ensure custom observable objects follow naming style conventions. |
def _timeout_thread(self, remain):
time.sleep(remain)
if not self._ended:
self._ended = True
self._release_all() | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list identifier if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list | Timeout before releasing every thing, if nothing was returned |
def _validate_j2k_colorspace(self, cparams, colorspace):
if cparams.codec_fmt == opj2.CODEC_J2K and colorspace is not None:
msg = 'Do not specify a colorspace when writing a raw codestream.'
raise IOError(msg) | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list identifier | Cannot specify a colorspace with J2K. |
def xray_heartbeat_batch_handler(self, unused_channel, data):
gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry(
data, 0)
heartbeat_data = gcs_entries.Entries(0)
message = (ray.gcs_utils.HeartbeatBatchTableData.
GetRootAsHeartbeatBatchTableData(heartbeat_data, 0))
for j in range(message.BatchLength()):
heartbeat_message = message.Batch(j)
num_resources = heartbeat_message.ResourcesAvailableLabelLength()
static_resources = {}
dynamic_resources = {}
for i in range(num_resources):
dyn = heartbeat_message.ResourcesAvailableLabel(i)
static = heartbeat_message.ResourcesTotalLabel(i)
dynamic_resources[dyn] = (
heartbeat_message.ResourcesAvailableCapacity(i))
static_resources[static] = (
heartbeat_message.ResourcesTotalCapacity(i))
client_id = ray.utils.binary_to_hex(heartbeat_message.ClientId())
ip = self.raylet_id_to_ip_map.get(client_id)
if ip:
self.load_metrics.update(ip, static_resources,
dynamic_resources)
else:
logger.warning(
"Monitor: "
"could not find ip for client {}".format(client_id)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier parenthesized_expression call attribute attribute attribute identifier identifier identifier identifier argument_list identifier integer for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier parenthesized_expression call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier parenthesized_expression call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier | Handle an xray heartbeat batch message from Redis. |
def solar_constant(self):
if self.wavenumber is not None:
return np.trapz(self.irradiance, self.wavenumber)
elif self.wavelength is not None:
return np.trapz(self.irradiance, self.wavelength)
else:
raise TypeError('Neither wavelengths nor wavenumbers available!') | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier none block return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list string string_start string_content string_end | Calculate the solar constant |
def sink_bigquery(client, to_delete):
dataset = _sink_bigquery_setup(client)
to_delete.append(dataset)
SINK_NAME = "robots-bigquery-%d" % (_millis(),)
FILTER = "textPayload:robot"
DESTINATION = "bigquery.googleapis.com%s" % (dataset.path,)
sink = client.sink(SINK_NAME, filter_=FILTER, destination=DESTINATION)
assert not sink.exists()
sink.create()
assert sink.exists()
to_delete.insert(0, sink) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple call identifier argument_list expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier assert_statement not_operator call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list assert_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer identifier | Sink log entries to bigquery. |
def passwordChallengeResponse(self, cnonce, response):
return self._login(_AMPUsernamePassword(
self.username, self.challenge, cnonce, response)) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier identifier identifier | Verify the response to a challenge. |
def option(self, key=None):
if key is None:
return self._args.options()
return self._args.option(key) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block return_statement call attribute attribute identifier identifier identifier argument_list return_statement call attribute attribute identifier identifier identifier argument_list identifier | Get the value of a command option. |
def delete(self, to_delete):
if not isinstance(to_delete, list):
to_delete = [to_delete]
for zenpy_object in to_delete:
object_type = get_object_type(zenpy_object)
object_cache = self.mapping.get(object_type, None)
if object_cache:
removed_object = object_cache.pop(zenpy_object.id, None)
if removed_object:
log.debug("Cache RM: [%s %s]" % (object_type.capitalize(), zenpy_object.id)) | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier none if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple call attribute identifier identifier argument_list attribute identifier identifier | Purge one or more items from the relevant caches |
def _collapse_subitems(base, items):
out = []
for d in items:
newd = _diff_dict(base, d)
out.append(newd)
return out | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Collapse full data representations relative to a standard base. |
def _create_class_proxy(cls, theclass):
def make_method(name):
def method(self, *args, **kw):
return getattr(object.__getattribute__(self, "_obj"), name)(*args, **kw)
return method
namespace = {}
for name in cls._special_names:
if hasattr(theclass, name):
namespace[name] = make_method(name)
return type("%s(%s)" % (cls.__name__, theclass.__name__), (cls,), namespace) | module function_definition identifier parameters identifier identifier block function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call call identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier return_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier tuple identifier identifier | creates a proxy for the given class |
def dataset_detail(request, dataset_id):
active_dataset = get_object_or_404(Dataset, pk=dataset_id)
datadict_id = active_dataset.data_dictionary_id
datadict = DataDictionaryField.objects.filter(
parent_dict=datadict_id
).order_by('columnIndex')
uploader_name = grab_names_from_emails([active_dataset.uploaded_by])
tags = Tag.objects.filter(dataset=dataset_id)
articles = Article.objects.filter(dataset=dataset_id)
for hub in HUBS_LIST:
if hub['slug'] == active_dataset.hub_slug:
active_dataset.hub = hub['name']
active_dataset.vertical = hub['vertical']['name']
if len(uploader_name) == 0:
uploader_name = active_dataset.uploaded_by
else:
uploader_name = uploader_name[active_dataset.uploaded_by]
return render(
request,
'datafreezer/dataset_details.html',
{
'dataset': active_dataset,
'datadict': datadict,
'uploader_name': uploader_name,
'tags': tags,
'articles': articles,
}
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list list attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier for_statement identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier subscript identifier attribute identifier identifier return_statement call identifier argument_list identifier string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Renders individual dataset detail page. |
def versionok_for_gui():
if sys.hexversion < 0x02060000:
return False
if sys.hexversion >= 0x03000000 and sys.hexversion < 0x03020000:
return False
if sys.platform.startswith("java") or sys.platform.startswith('cli'):
return False
return True | module function_definition identifier parameters block if_statement comparison_operator attribute identifier identifier integer block return_statement false if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block return_statement false if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block return_statement false return_statement true | Return True if running Python is suitable for GUI Event Integration and deeper IPython integration |
def app_token(vault_client, app_id, user_id):
resp = vault_client.auth_app_id(app_id, user_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiCredentials('invalid apptoken') | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block return_statement subscript subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block raise_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Returns a vault token based on the app and user id. |
def getCheck(self, checkid):
check = PingdomCheck(self, {'id': checkid})
check.getDetails()
return check | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Returns a detailed description of a specified check. |
def reset_mode(self):
self.command(0x18, b"\x01", timeout=0.1)
self.transport.write(Chipset.ACK)
time.sleep(0.010) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list integer string string_start string_content escape_sequence string_end keyword_argument identifier float expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list float | Send a Reset command to set the operation mode to 0. |
def run(self, name):
for entry in self.entries:
if entry.name == name:
run_func(entry)
break | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement call identifier argument_list identifier break_statement | Runs the function associated with the given entry `name`. |
def rados_df(self,
host_list=None,
remote_user=None,
remote_pass=None):
result, failed_hosts = self.runner.ansible_perform_operation(
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module="command",
module_args="rados df")
parsed_result = self.rados_parse_df(result)
return parsed_result | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Invoked the rados df command and return output to user |
def _extract_header(time_series):
return TimeSeries(
metric=time_series.metric,
resource=time_series.resource,
metric_kind=time_series.metric_kind,
value_type=time_series.value_type,
) | module function_definition identifier parameters identifier block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Return a copy of time_series with the points removed. |
def swapaxes(self, axis1, axis2):
if self.ndim <=1 or axis1 == axis2:
return self
ar = np.asarray(self).swapaxes(axis1, axis2)
if axis1 != 0 and axis2 != 0:
labels = self.labels[:]
labels[axis1], labels[axis2] = labels[axis2], labels[axis1]
return Timeseries(ar, self.tspan, labels)
return ar | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator identifier identifier block return_statement identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier integer comparison_operator identifier integer block expression_statement assignment identifier subscript attribute identifier identifier slice expression_statement assignment pattern_list subscript identifier identifier subscript identifier identifier expression_list subscript identifier identifier subscript identifier identifier return_statement call identifier argument_list identifier attribute identifier identifier identifier return_statement identifier | Interchange two axes of a Timeseries. |
def mode(self, target, *data):
self.send_line('MODE %s %s' % (target, ' '.join(data)), nowait=True) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier true | set user or channel mode |
def program_rtr(self, args, rout_id, namespace=None):
if namespace is None:
namespace = self.find_rtr_namespace(rout_id)
if namespace is None:
LOG.error("Unable to find namespace for router %s", rout_id)
return False
final_args = ['ip', 'netns', 'exec', namespace] + args
try:
utils.execute(final_args, root_helper=self.root_helper)
except Exception as e:
LOG.error("Unable to execute %(cmd)s. "
"Exception: %(exception)s",
{'cmd': final_args, 'exception': e})
return False
return True | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement false expression_statement assignment identifier binary_operator list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier return_statement false return_statement true | Execute the command against the namespace. |
def _load_model(self):
super()._load_model()
self.mujoco_robot.set_base_xpos([0, 0, 0])
self.mujoco_arena = TableArena(
table_full_size=self.table_full_size, table_friction=self.table_friction
)
if self.use_indicator_object:
self.mujoco_arena.add_pos_indicator()
self.mujoco_arena.set_origin([0.45 + self.table_full_size[0] / 2, 0, 0])
self.model = TableTopTask(
self.mujoco_arena,
self.mujoco_robot,
self.mujoco_objects,
self.object_initializer,
)
self.model.place_objects() | module function_definition identifier parameters identifier block expression_statement call attribute call identifier argument_list identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list list integer integer integer expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list list binary_operator float binary_operator subscript attribute identifier identifier integer integer integer integer expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Loads the arena and pot object. |
def option(self, opt):
if 'config.merge' in self.functions:
return self.functions['config.merge'](opt, {}, omit_master=True)
return self.opts.get(opt, {}) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block return_statement call subscript attribute identifier identifier string string_start string_content string_end argument_list identifier dictionary keyword_argument identifier true return_statement call attribute attribute identifier identifier identifier argument_list identifier dictionary | Return options merged from config and pillar |
def all(cls, connection=None, **params):
request = cls._make_request('GET', cls._get_all_path(), connection, params=params)
return cls._create_object(request, connection=connection) | module function_definition identifier parameters identifier default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Returns first page if no params passed in as a list. |
def copy_from_csv_sql(qualified_name: str, delimiter=',', encoding='utf8',
null_str='', header=True, escape_str='\\', quote_char='"',
force_not_null=None, force_null=None):
options = []
options.append("DELIMITER '%s'" % delimiter)
options.append("NULL '%s'" % null_str)
if header:
options.append('HEADER')
options.append("QUOTE '%s'" % quote_char)
options.append("ESCAPE '%s'" % escape_str)
if force_not_null:
options.append(_format_force_not_null(column_names=force_not_null))
if force_null:
options.append(_format_force_null(column_names=force_null))
postgres_encoding = get_postgres_encoding(encoding)
options.append("ENCODING '%s'" % postgres_encoding)
copy_sql = _format_copy_csv_sql(qualified_name, copy_options=options)
return copy_sql | module function_definition identifier parameters typed_parameter identifier type identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_end default_parameter identifier true default_parameter identifier string string_start string_content escape_sequence string_end default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Generate copy from csv statement. |
def ip_check(*args, func=None):
func = func or inspect.stack()[2][3]
for var in args:
if not isinstance(var, ipaddress._IPAddressBase):
name = type(var).__name__
raise IPError(
f'Function {func} expected IP address, {name} got instead.') | module function_definition identifier parameters list_splat_pattern identifier default_parameter identifier none block expression_statement assignment identifier boolean_operator identifier subscript subscript call attribute identifier identifier argument_list integer integer for_statement identifier identifier block if_statement not_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier attribute call identifier argument_list identifier identifier raise_statement call identifier argument_list string string_start string_content interpolation identifier string_content interpolation identifier string_content string_end | Check if arguments are IP addresses. |
def _initialize(self, show_bounds, reset_camera, outline):
self.plotter.subplot(*self.loc)
if outline is None:
self.plotter.add_mesh(self.input_dataset.outline_corners(),
reset_camera=False, color=vtki.rcParams['outline_color'],
loc=self.loc)
elif outline:
self.plotter.add_mesh(self.input_dataset.outline(),
reset_camera=False, color=vtki.rcParams['outline_color'],
loc=self.loc)
if show_bounds:
self.plotter.show_bounds(reset_camera=False, loc=loc)
if reset_camera:
cpos = self.plotter.get_default_cam_pos()
self.plotter.camera_position = cpos
self.plotter.reset_camera()
self.plotter.camera_set = False | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat attribute identifier identifier if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier elif_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false keyword_argument identifier identifier if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute attribute identifier identifier identifier false | Outlines the input dataset and sets up the scene |
def gauss_box_model(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):
z = (x - mean) / stddev
z2 = z + hpix / stddev
z1 = z - hpix / stddev
return amplitude * (norm.cdf(z2) - norm.cdf(z1)) | module function_definition identifier parameters identifier default_parameter identifier float default_parameter identifier float default_parameter identifier float default_parameter identifier float block expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier identifier expression_statement assignment identifier binary_operator identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier binary_operator identifier identifier return_statement binary_operator identifier parenthesized_expression binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier | Integrate a Gaussian profile. |
def _gen_etetoolkit_tree(self, node, subject_info_tree):
for si_node in subject_info_tree.child_list:
if si_node.type_str == TYPE_NODE_TAG:
child = self._add_type_node(node, si_node.label_str)
elif si_node.type_str == SUBJECT_NODE_TAG:
child = self._add_subject_node(node, si_node.label_str)
else:
raise AssertionError(
'Unknown node type. type_str="{}"'.format(si_node.type_str)
)
self._gen_etetoolkit_tree(child, si_node) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier elif_clause comparison_operator attribute identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Copy SubjectInfoTree to a ETE Tree. |
def document(schema_file):
schema = load_schema_file(open(schema_file, 'r'))
documentation = generate_documentation(schema)
sys.stdout.write(documentation) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Generate reStructuredText documentation from a confirm schema. |
def namespace_to_taxon() -> Dict[str, Node]:
human_taxon = Node(
id='NCBITaxon:9606',
label='Homo sapiens'
)
return {
'MGI': Node(
id='NCBITaxon:10090',
label='Mus musculus'
),
'MONDO': human_taxon,
'OMIM': human_taxon,
'MONARCH': human_taxon,
'HGNC': human_taxon,
'FlyBase': Node(
id='NCBITaxon:7227',
label='Drosophila melanogaster'
),
'WormBase': Node(
id='NCBITaxon:6239',
label='Caenorhabditis elegans'
),
'ZFIN': Node(
id='NCBITaxon:7955',
label='Danio rerio'
)
} | module function_definition identifier parameters type generic_type identifier type_parameter type identifier type identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end return_statement dictionary pair string string_start string_content string_end call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end | namespace to taxon mapping |
def dump_collection(cfg, f, indent=0):
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n') | module function_definition identifier parameters identifier identifier default_parameter identifier integer block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement call identifier argument_list none identifier identifier identifier if_statement comparison_operator identifier binary_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end | Save a collection of attributes |
def _write_file(self, slug, folderpath, html):
if not os.path.isdir(folderpath):
try:
os.makedirs(folderpath)
self.info("Creating directory " + folderpath)
except Exception as e:
self.err(e)
return
filepath = folderpath + "/" + slug + ".html"
try:
filex = open(filepath, "w")
filex.write(html)
filex.close()
if self.notebook is False:
self.ok("File written to", filepath)
else:
html = '<a href="' + filepath + '">' + filepath + '</a>'
self.html("File written to", html)
except Exception as e:
self.err(e)
return filepath | module function_definition identifier parameters identifier identifier identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement expression_statement assignment identifier binary_operator binary_operator binary_operator identifier string string_start string_content string_end identifier string string_start string_content string_end try_statement block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier false block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Writes a chart's html to a file |
def annotation_path(cls, project, incident, annotation):
return google.api_core.path_template.expand(
"projects/{project}/incidents/{incident}/annotations/{annotation}",
project=project,
incident=incident,
annotation=annotation,
) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified annotation string. |
def restart_stopped_apps():
cozy_apps = monitor.status(only_cozy=True)
for app in cozy_apps.keys():
state = cozy_apps[app]
if state == 'up':
next
elif state == 'down':
print 'Start {}'.format(app)
rebuild_app(app, force=False)
monitor.start(app) | module function_definition identifier parameters block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier subscript identifier identifier if_statement comparison_operator identifier string string_start string_content string_end block expression_statement identifier elif_clause comparison_operator identifier string string_start string_content string_end block print_statement call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list identifier | Restart all apps in stopped state |
def clear_lock(self, remote=None, lock_type='update'):
cleared = []
errors = []
for repo in self.remotes:
if remote:
try:
if not fnmatch.fnmatch(repo.url, remote):
continue
except TypeError:
if not fnmatch.fnmatch(repo.url, six.text_type(remote)):
continue
success, failed = repo.clear_lock(lock_type=lock_type)
cleared.extend(success)
errors.extend(failed)
return cleared, errors | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier list expression_statement assignment identifier list for_statement identifier attribute identifier identifier block if_statement identifier block try_statement block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier identifier block continue_statement except_clause identifier block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier block continue_statement expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement expression_list identifier identifier | Clear update.lk for all remotes |
def join(rasters):
raster = rasters[0]
mask_band = None
nodata = None
with raster._raster_opener(raster.source_file) as r:
nodata = r.nodata
mask_flags = r.mask_flag_enums
per_dataset_mask = all([rasterio.enums.MaskFlags.per_dataset in flags for flags in mask_flags])
if per_dataset_mask and nodata is None:
mask_band = 0
return GeoRaster2.from_rasters(rasters, relative_to_vrt=False, nodata=nodata, mask_band=mask_band) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier none expression_statement assignment identifier none with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list list_comprehension comparison_operator attribute attribute attribute identifier identifier identifier identifier identifier for_in_clause identifier identifier if_statement boolean_operator identifier comparison_operator identifier none block expression_statement assignment identifier integer return_statement call attribute identifier identifier argument_list identifier keyword_argument identifier false keyword_argument identifier identifier keyword_argument identifier identifier | This method takes a list of rasters and returns a raster that is constructed of all of them |
def isConjSouthNode(self):
node = self.chart.getObject(const.SOUTH_NODE)
return aspects.hasAspect(self.obj, node, aspList=[0]) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier list integer | Returns if object is conjunct south node. |
def node_from_nid(self, nid):
for node in self.iflat_nodes():
if node.node_id == nid: return node
raise ValueError("Cannot find node with node id: %s" % nid) | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier identifier block return_statement identifier raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier | Return the node in the `Flow` with the given `nid` identifier |
def remove(self):
self.canvas.get_first_view().unselect_item(self)
for child in self.canvas.get_children(self)[:]:
child.remove()
self.remove_income()
for outcome_v in self.outcomes[:]:
self.remove_outcome(outcome_v)
for input_port_v in self.inputs[:]:
self.remove_input_port(input_port_v)
for output_port_v in self.outputs[:]:
self.remove_output_port(output_port_v)
for scoped_variable_port_v in self.scoped_variables[:]:
self.remove_scoped_variable(scoped_variable_port_v)
self.remove_keep_rect_within_constraint_from_parent()
for constraint in self._constraints[:]:
self.canvas.solver.remove_constraint(constraint)
self._constraints.remove(constraint)
self.canvas.remove(self) | module function_definition identifier parameters identifier block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list identifier for_statement identifier subscript call attribute attribute identifier identifier identifier argument_list identifier slice block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list for_statement identifier subscript attribute identifier identifier slice block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier subscript attribute identifier identifier slice block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier subscript attribute identifier identifier slice block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier subscript attribute identifier identifier slice block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list for_statement identifier subscript attribute identifier identifier slice block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Remove recursively all children and then the StateView itself |
def calc_paired_insert_stats_save(in_bam, stat_file, nsample=1000000):
if utils.file_exists(stat_file):
with open(stat_file) as in_handle:
return yaml.safe_load(in_handle)
else:
stats = calc_paired_insert_stats(in_bam, nsample)
with open(stat_file, "w") as out_handle:
yaml.safe_dump(stats, out_handle, default_flow_style=False, allow_unicode=False)
return stats | module function_definition identifier parameters identifier identifier default_parameter identifier integer block if_statement call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block return_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier false keyword_argument identifier false return_statement identifier | Calculate paired stats, saving to a file for re-runs. |
def int_bytes(cls, string):
if string[-1] in ('k', 'm'):
value = cls.int_0_inf(string[:-1])
unit = string[-1]
if unit == 'k':
value *= 2 ** 10
else:
value *= 2 ** 20
return value
else:
return cls.int_0_inf(string) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator subscript identifier unary_operator integer tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier slice unary_operator integer expression_statement assignment identifier subscript identifier unary_operator integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator integer integer else_clause block expression_statement augmented_assignment identifier binary_operator integer integer return_statement identifier else_clause block return_statement call attribute identifier identifier argument_list identifier | Convert string describing size to int. |
def _get_receiver_name(self):
if self._name is None and self._urls.mainzone is not None:
name_tag = {"FriendlyName": None}
try:
root = self.get_status_xml(self._urls.mainzone)
except (ValueError,
requests.exceptions.RequestException):
_LOGGER.warning("Receiver name could not be determined. "
"Using standard name: Denon AVR.")
self._name = "Denon AVR"
else:
name_tag = self._get_status_from_xml_tags(root, name_tag)
if name_tag:
_LOGGER.warning("Receiver name could not be determined. "
"Using standard name: Denon AVR.")
self._name = "Denon AVR" | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end none try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier except_clause tuple identifier attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier string string_start string_content string_end | Get name of receiver from web interface if not set. |
def _shutdown(self):
for exit_handler in self._exit_handlers:
exit_handler()
if self._socket:
self._socket.close()
self._socket = None | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none | Shut down the server. |
def _combine_transfers(self, result):
transfers = {}
for reaction_id, c1, c2, form in result:
key = reaction_id, c1, c2
combined_form = transfers.setdefault(key, Formula())
transfers[key] = combined_form | form
for (reaction_id, c1, c2), form in iteritems(transfers):
yield reaction_id, c1, c2, form | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier identifier identifier identifier block expression_statement assignment identifier expression_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list expression_statement assignment subscript identifier identifier binary_operator identifier identifier for_statement pattern_list tuple_pattern identifier identifier identifier identifier call identifier argument_list identifier block expression_statement yield expression_list identifier identifier identifier identifier | Combine multiple pair transfers into one. |
def pad_batch(features, batch_multiple):
feature = list(features.items())[0][1]
batch_size = tf.shape(feature)[0]
mod = batch_size % batch_multiple
has_mod = tf.cast(tf.cast(mod, tf.bool), tf.int32)
batch_padding = batch_multiple * has_mod - mod
padded_features = {}
for k, feature in features.items():
rank = len(feature.shape)
paddings = [[0, 0] for _ in range(rank)]
paddings[0][1] = batch_padding
padded_feature = tf.pad(feature, paddings)
padded_features[k] = padded_feature
return padded_features | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript subscript call identifier argument_list call attribute identifier identifier argument_list integer integer expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator binary_operator identifier identifier identifier expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier list_comprehension list integer integer for_in_clause identifier call identifier argument_list identifier expression_statement assignment subscript subscript identifier integer integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Pad batch dim of features to nearest multiple of batch_multiple. |
def _reorder_columns(bed_file):
new_bed = utils.splitext_plus(bed_file)[0] + '_order.bed'
with open(bed_file) as in_handle:
with open(new_bed, 'w') as out_handle:
for line in in_handle:
cols = line.strip().split("\t")
cols[3] = _select_anno(cols[3]) + "_" + cols[4]
cols[4] = "0"
print("\t".join(cols), file=out_handle, end="")
return new_bed | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator subscript call attribute identifier identifier argument_list identifier integer string string_start string_content string_end with_statement with_clause with_item as_pattern call identifier argument_list identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment subscript identifier integer binary_operator binary_operator call identifier argument_list subscript identifier integer string string_start string_content string_end subscript identifier integer expression_statement assignment subscript identifier integer string string_start string_content string_end expression_statement call identifier argument_list call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_end return_statement identifier | Reorder columns to be compatible with CoRaL |
def _get_uploaded_versions_pypicloud(project_name, index_url, requests_verify=True):
api_url = index_url
for suffix in ('/pypi', '/pypi/', '/simple', '/simple/'):
if api_url.endswith(suffix):
api_url = api_url[:len(suffix) * -1] + '/api/package'
break
url = '/'.join((api_url, project_name))
response = requests.get(url, verify=requests_verify)
if response.status_code == 200:
return [p['version'] for p in response.json()['packages']]
return None | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier identifier for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator subscript identifier slice binary_operator call identifier argument_list identifier unary_operator integer string string_start string_content string_end break_statement expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier integer block return_statement list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end return_statement none | Query the pypi index at index_url using pypicloud api to find all versions |
def send(self, topic, message):
if not message:
Log.error("Expecting a message")
message._prepare()
if not self.connection:
self.connect()
producer = Producer(
channel=self.connection,
exchange=Exchange(self.settings.exchange, type='topic'),
routing_key=topic
)
final_data = Data(
payload=message.data,
_meta=set_default({
'exchange': self.settings.exchange,
'routing_key': message.routing_key,
'serializer': self.settings.serializer,
'sent': time_to_string(datetime.datetime.now(timezone(self.settings.broker_timezone))),
'count': self.count
}, message.metadata)
)
producer.publish(jsons.scrub(final_data), serializer=self.settings.serializer)
self.count += 1 | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list attribute attribute identifier identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier call identifier argument_list dictionary pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute attribute identifier identifier identifier pair string string_start string_content string_end call identifier argument_list call attribute attribute identifier identifier identifier argument_list call identifier argument_list attribute attribute identifier identifier identifier pair string string_start string_content string_end attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier integer | Publishes a pulse message to the proper exchange. |
def _fetch_features(self):
if self.next_page_url is None:
return
response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers)
self.features.extend(response['features'])
self.next_page_url = response['pagination']['next']
self.layer_size = response['pagination']['total'] | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment identifier call identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment attribute identifier identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end | Retrieves a new page of features from Geopedia |
def load_model_data(self, path, model):
if os.path.isdir(path):
if os.path.isfile(os.path.join(path, '_all.yml')):
self.load_model_data_collection(path, model)
self.load_model_data_from_files(path, model)
self.session.commit() | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block if_statement call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Loads the data for the specified model from the given path. |
def _parse_for_errors(self):
error = self._response.find('{www.clusterpoint.com}error')
if error is not None:
if error.find('level').text.lower() in ('rejected', 'failed', 'error', 'fatal'):
raise APIError(error)
else:
warnings.warn(APIWarning(error)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block if_statement comparison_operator call attribute attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier argument_list tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block raise_statement call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier | Look for an error tag and raise APIError for fatal errors or APIWarning for nonfatal ones. |
def add_role(ctx, role):
if role is None:
log('Specify the role with --role')
return
if ctx.obj['username'] is None:
log('Specify the username with --username')
return
change_user = ctx.obj['db'].objectmodels['user'].find_one({
'name': ctx.obj['username']
})
if role not in change_user.roles:
change_user.roles.append(role)
change_user.save()
log('Done')
else:
log('User already has that role!', lvl=warn) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement call identifier argument_list string string_start string_content string_end return_statement if_statement comparison_operator subscript attribute identifier identifier string string_start string_content string_end none block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call attribute subscript attribute subscript attribute identifier identifier string string_start string_content string_end identifier string string_start string_content string_end identifier argument_list dictionary pair string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end else_clause block expression_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier | Grant a role to an existing user |
def assemble_rom_code(self, asm):
stream = StringIO(asm)
worker = assembler.Assembler(self.processor, stream)
try:
result = worker.assemble()
except BaseException as e:
return e, None
self.rom.program(result)
return None, result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause as_pattern identifier as_pattern_target identifier block return_statement expression_list identifier none expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement expression_list none identifier | assemble the given code and program the ROM |
def _compute_results(self):
self.Y_best = best_value(self.Y)
self.x_opt = self.X[np.argmin(self.Y),:]
self.fx_opt = np.min(self.Y) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier slice expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier | Computes the optimum and its value. |
def visit_project(self, item):
if not item.remote_id:
command = CreateProjectCommand(self.settings, item)
self.task_runner_add(None, item, command)
else:
self.settings.project_id = item.remote_id | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list none identifier identifier else_clause block expression_statement assignment attribute attribute identifier identifier identifier attribute identifier identifier | Adds create project command to task runner if project doesn't already exist. |
def _get_things(self, method, thing, thing_type, params=None, cacheable=True):
limit = params.get("limit", 1)
seq = []
for node in _collect_nodes(
limit, self, self.ws_prefix + "." + method, cacheable, params
):
title = _extract(node, "name")
artist = _extract(node, "name", 1)
playcount = _number(_extract(node, "playcount"))
seq.append(TopItem(thing_type(artist, title, self.network), playcount))
return seq | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end integer expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list identifier identifier attribute identifier identifier identifier return_statement identifier | Returns a list of the most played thing_types by this thing. |
def csv(self, output):
import csv
csvwriter = csv.writer(self.outfile)
csvwriter.writerows(output) | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Output data as excel-compatible CSV |
def show_floatingip(self, floatingip, **_params):
return self.get(self.floatingip_path % (floatingip), params=_params) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier parenthesized_expression identifier keyword_argument identifier identifier | Fetches information of a certain floatingip. |
def save_npz(object, handle):
log.warning("Saving npz files currently only works locally. :/")
path = handle.name
handle.close()
if type(object) is dict:
np.savez(path, **object)
elif type(object) is list:
np.savez(path, *object)
else:
log.warning("Saving non dict or list as npz file, did you maybe want npy?")
np.savez(path, object) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier dictionary_splat identifier elif_clause comparison_operator call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier list_splat identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier identifier | Save dict of numpy array as npz file. |
def request_set_sensor_unreachable(self, req, sensor_name):
sensor = self.get_sensor(sensor_name)
ts, status, value = sensor.read()
sensor.set_value(value, sensor.UNREACHABLE, ts)
return('ok',) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier identifier return_statement tuple string string_start string_content string_end | Set sensor status to unreachable |
def _define_absl_flag(self, flag_instance, suppress):
flag_name = flag_instance.name
short_name = flag_instance.short_name
argument_names = ['--' + flag_name]
if short_name:
argument_names.insert(0, '-' + short_name)
if suppress:
helptext = argparse.SUPPRESS
else:
helptext = flag_instance.help.replace('%', '%%')
if flag_instance.boolean:
argument_names.append('--no' + flag_name)
self.add_argument(
*argument_names, action=_BooleanFlagAction, help=helptext,
metavar=flag_instance.name.upper(),
flag_instance=flag_instance)
else:
self.add_argument(
*argument_names, action=_FlagAction, help=helptext,
metavar=flag_instance.name.upper(),
flag_instance=flag_instance) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier list binary_operator string string_start string_content string_end identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list integer binary_operator string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list list_splat identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list list_splat identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Defines a flag from the flag_instance. |
def print_app_meta_data(self):
l_metaData = dir(self)
l_classVar = [x for x in l_metaData if x.isupper() ]
for str_var in l_classVar:
str_val = getattr(self, str_var)
print("%20s: %s" % (str_var, str_val)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier | Print the app's meta data. |
def _from_dict(cls, _dict):
args = {}
if 'text' in _dict:
args['text'] = _dict.get('text')
if 'keywords' in _dict:
args['keywords'] = [
SemanticRolesKeyword._from_dict(x)
for x in (_dict.get('keywords'))
]
return cls(**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end return_statement call identifier argument_list dictionary_splat identifier | Initialize a SemanticRolesResultObject object from a json dictionary. |
def initial_state(self) -> StateTensor:
s0 = []
for fluent in self._compiler.compile_initial_state(self._batch_size):
s0.append(self._output_size(fluent))
s0 = tuple(s0)
return s0 | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement identifier | Returns the initial state tensor. |
def call_sync(func):
@wraps(func)
def wrapper(self, *args, **kw):
if self.thread.ident == get_ident():
return func(self, *args, **kw)
barrier = Barrier(2)
result = None
ex = None
def call():
nonlocal result, ex
try:
result = func(self, *args, **kw)
except Exception as exc:
ex = exc
finally:
barrier.wait()
self.loop.call_soon_threadsafe(call)
barrier.wait()
if ex:
raise ex or Exception("Unknown error")
return result
return wrapper | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute attribute identifier identifier identifier call identifier argument_list block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier expression_statement assignment identifier call identifier argument_list integer expression_statement assignment identifier none expression_statement assignment identifier none function_definition identifier parameters block nonlocal_statement identifier identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list if_statement identifier block raise_statement boolean_operator identifier call identifier argument_list string string_start string_content string_end return_statement identifier return_statement identifier | Decorates a function to be called sync on the loop thread |
def _stringify_na_values(na_values):
result = []
for x in na_values:
result.append(str(x))
result.append(x)
try:
v = float(x)
if v == int(v):
v = int(v)
result.append("{value}.0".format(value=v))
result.append(str(v))
result.append(v)
except (TypeError, ValueError, OverflowError):
pass
try:
result.append(int(x))
except (TypeError, ValueError, OverflowError):
pass
return set(result) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier except_clause tuple identifier identifier identifier block pass_statement try_statement block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier except_clause tuple identifier identifier identifier block pass_statement return_statement call identifier argument_list identifier | return a stringified and numeric for these values |
def exists(self, path):
import hdfs
try:
self.client.status(path)
return True
except hdfs.util.HdfsError as e:
if str(e).startswith('File does not exist: '):
return False
else:
raise e | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement true except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block if_statement call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end block return_statement false else_clause block raise_statement identifier | Returns true if the path exists and false otherwise. |
def generated_password_entropy(self) -> float:
characters = self._get_password_characters()
if (
self.passwordlen is None
or not characters
):
raise ValueError("Can't calculate the password entropy: character"
" set is empty or passwordlen isn't set")
if self.passwordlen == 0:
return 0.0
return calc_password_entropy(self.passwordlen, characters) | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none not_operator identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier integer block return_statement float return_statement call identifier argument_list attribute identifier identifier identifier | Calculate the entropy of a password that would be generated. |
def shutdown(self):
if not process.proc_alive(self.proc):
return
logger.info("Attempting to connect to %s", self.hostname)
client = self.connection
attempts = 2
for i in range(attempts):
logger.info("Attempting to send shutdown command to %s",
self.hostname)
try:
client.admin.command("shutdown", force=True)
except ConnectionFailure:
pass
try:
return process.wait_mprocess(self.proc, 5)
except TimeoutError as exc:
logger.info("Timed out waiting on process: %s", exc)
continue
raise ServersError("Server %s failed to shutdown after %s attempts" %
(self.hostname, attempts)) | module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list attribute identifier identifier block return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier integer for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier true except_clause identifier block pass_statement try_statement block return_statement call attribute identifier identifier argument_list attribute identifier identifier integer except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier continue_statement raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier | Send shutdown command and wait for the process to exit. |
def send_to_pipe_channel(channel_name,
label,
value):
'Send message through pipe to client component'
async_to_sync(async_send_to_pipe_channel)(channel_name=channel_name,
label=label,
value=value) | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement call call identifier argument_list identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Send message through pipe to client component |
def Describe(self):
result = ["\nUsername: %s" % self.urn.Basename()]
labels = [l.name for l in self.GetLabels()]
result.append("Labels: %s" % ",".join(labels))
if self.Get(self.Schema.PASSWORD) is None:
result.append("Password: not set")
else:
result.append("Password: set")
return "\n".join(result) | module function_definition identifier parameters identifier block expression_statement assignment identifier list binary_operator string string_start string_content escape_sequence string_end call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier if_statement comparison_operator call attribute identifier identifier argument_list attribute attribute identifier identifier identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier | Return a description of this user. |
def portals(self):
char = self.character
make_edge = self.engine._get_edge
for (o, d) in self.engine._edges_cache.iter_keys(
self.character.name, *self.engine._btt()
):
yield make_edge(char, o, d) | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier for_statement tuple_pattern identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier list_splat call attribute attribute identifier identifier identifier argument_list block expression_statement yield call identifier argument_list identifier identifier identifier | Iterate over all portals. |
def center_at(self, x, y):
self.x = x - (self.width / 2)
self.y = y - (self.height / 2) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment attribute identifier identifier binary_operator identifier parenthesized_expression binary_operator attribute identifier identifier integer expression_statement assignment attribute identifier identifier binary_operator identifier parenthesized_expression binary_operator attribute identifier identifier integer | Center the menu at x, y |
async def send_rpc(self, msg, _context):
service = msg.get('name')
rpc_id = msg.get('rpc_id')
payload = msg.get('payload')
timeout = msg.get('timeout')
response_id = await self.service_manager.send_rpc_command(service, rpc_id, payload,
timeout)
try:
result = await self.service_manager.rpc_results.get(response_id, timeout=timeout)
except asyncio.TimeoutError:
self._logger.warning("RPC 0x%04X on service %s timed out after %f seconds",
rpc_id, service, timeout)
result = dict(result='timeout', response=b'')
return result | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier await call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier try_statement block expression_statement assignment identifier await call attribute attribute attribute identifier identifier identifier identifier argument_list identifier keyword_argument identifier identifier except_clause attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_end return_statement identifier | Send an RPC to a service on behalf of a client. |
def regex_span_tokenize(s, regex):
left = 0
for m in re.finditer(regex, s, re.U):
right, next = m.span()
if right != 0:
yield left, right
left = next
yield left, len(s) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer for_statement identifier call attribute identifier identifier argument_list identifier identifier attribute identifier identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier integer block expression_statement yield expression_list identifier identifier expression_statement assignment identifier identifier expression_statement yield expression_list identifier call identifier argument_list identifier | Return spans that identify tokens in s split using regex. |
def averageOutsidePercentile(requestContext, seriesList, n):
averages = [safeAvg(s) for s in seriesList]
if n < 50:
n = 100 - n
lowPercentile = _getPercentile(averages, 100 - n)
highPercentile = _getPercentile(averages, n)
return [s for s in seriesList
if not lowPercentile < safeAvg(s) < highPercentile] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier for_in_clause identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier binary_operator integer identifier expression_statement assignment identifier call identifier argument_list identifier binary_operator integer identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement list_comprehension identifier for_in_clause identifier identifier if_clause not_operator comparison_operator identifier call identifier argument_list identifier identifier | Removes functions lying inside an average percentile interval |
def _retry_usb_function(count, func, *args, **kwargs):
helper = timeouts.RetryHelper(count)
while True:
try:
return func(*args, **kwargs)
except usb_exceptions.CommonUsbError:
if not helper.retry_if_possible():
raise
time.sleep(0.1)
else:
break | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier while_statement true block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause attribute identifier identifier block if_statement not_operator call attribute identifier identifier argument_list block raise_statement expression_statement call attribute identifier identifier argument_list float else_clause block break_statement | Helper function to retry USB. |
def status(self, status_in):
if isinstance(status_in, PIDStatus):
status_in = [status_in, ]
return self.filter(
self._filtered_pid_class.status.in_(status_in)
) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier return_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list identifier | Filter the PIDs based on their status. |
def remove_cluster(self, name):
cluster = self.get_cluster(name)
clusters = self.get_clusters()
clusters.remove(cluster) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier | Remove a cluster from kubeconfig. |
def _reachable_subsystems(network, indices, state):
validate.is_network(network)
for subset in utils.powerset(indices, nonempty=True, reverse=True):
try:
yield Subsystem(network, state, subset)
except exceptions.StateUnreachableError:
pass | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true keyword_argument identifier true block try_statement block expression_statement yield call identifier argument_list identifier identifier identifier except_clause attribute identifier identifier block pass_statement | A generator over all subsystems in a valid state. |
def iterright(self):
offs = 1
while True:
sibl = self.sibling(offs)
if sibl is None:
break
yield sibl
offs += 1 | module function_definition identifier parameters identifier block expression_statement assignment identifier integer while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block break_statement expression_statement yield identifier expression_statement augmented_assignment identifier integer | Yield "rightward" siblings until None. |
def _set_field_on_message(msg, key, value):
if isinstance(value, (collections_abc.MutableSequence, tuple)):
while getattr(msg, key):
getattr(msg, key).pop()
for item in value:
if isinstance(item, collections_abc.Mapping):
getattr(msg, key).add(**item)
else:
getattr(msg, key).extend([item])
elif isinstance(value, collections_abc.Mapping):
for item_key, item_value in value.items():
set(getattr(msg, key), item_key, item_value)
elif isinstance(value, message.Message):
getattr(msg, key).CopyFrom(value)
else:
setattr(msg, key, value) | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier tuple attribute identifier identifier identifier block while_statement call identifier argument_list identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list for_statement identifier identifier block if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list dictionary_splat identifier else_clause block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list list identifier elif_clause call identifier argument_list identifier attribute identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call identifier argument_list call identifier argument_list identifier identifier identifier identifier elif_clause call identifier argument_list identifier attribute identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier else_clause block expression_statement call identifier argument_list identifier identifier identifier | Set helper for protobuf Messages. |
def delete_license(license_id):
response = utils.checked_api_call(pnc_api.licenses, 'delete', id=license_id)
if response:
return utils.format_json(response.content) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end keyword_argument identifier identifier if_statement identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier | Delete a License by ID |
def derive_title(self):
title = super(SmartListView, self).derive_title()
if not title:
return force_text(self.model._meta.verbose_name_plural).title()
else:
return title | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list if_statement not_operator identifier block return_statement call attribute call identifier argument_list attribute attribute attribute identifier identifier identifier identifier identifier argument_list else_clause block return_statement identifier | Derives our title from our list |
def _count(self, X, Y):
self.feature_count_ += safe_sparse_dot(Y.T, X)
self.class_count_ += Y.sum(axis=0) | module function_definition identifier parameters identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement augmented_assignment attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier integer | Count and smooth feature occurrences. |
def statsd_middleware_factory(app, handler):
@coroutine
def middleware(request):
timer = Timer()
timer.start()
statsd = yield from app.ps.metrics.client()
pipe = statsd.pipe()
pipe.incr('request.method.%s' % request.method)
try:
response = yield from handler(request)
pipe.incr('response.status.%s' % response.status)
return response
except HTTPException as exc:
pipe.incr('response.status.%s' % exc.status_code)
raise
except Exception:
pipe.incr('response.exception')
raise
finally:
timer.stop()
pipe.timing('response.time', timer.ms)
pipe.disconnect()
return middleware | module function_definition identifier parameters identifier identifier block decorated_definition decorator identifier function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier yield call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier try_statement block expression_statement assignment identifier yield call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier raise_statement except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end raise_statement finally_clause block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement identifier | Send the application stats to statsd. |
def delete_channel(self, chname):
name = chname.lower()
if len(self.channel_names) < 1:
self.logger.error('Delete channel={0} failed. '
'No channels left.'.format(chname))
return
with self.lock:
channel = self.channel[name]
self.close_plugins(channel)
try:
idx = self.channel_names.index(chname)
except ValueError:
idx = 0
self.channel_names.remove(channel.name)
self.channel_names.sort()
self.ds.remove_tab(chname)
del self.channel[name]
self.prefs.remove_settings('channel_' + chname)
num_channels = len(self.channel_names)
if num_channels > 0:
if idx >= num_channels:
idx = num_channels - 1
self.change_channel(self.channel_names[idx])
else:
self.cur_channel = None
self.make_gui_callback('delete-channel', channel) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier return_statement with_statement with_clause with_item attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block expression_statement assignment identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier delete_statement subscript attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement comparison_operator identifier integer block if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier else_clause block expression_statement assignment attribute identifier identifier none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Delete a given channel from viewer. |
def loadtoc(self):
self.toc = self.TOCTMPLT()
self.lib.seek(self.pkgstart+self.tocpos)
tocstr = self.lib.read(self.toclen)
self.toc.frombinary(tocstr) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Load the table of contents into memory. |
def log_url (self, url_data):
node = self.get_node(url_data)
if node:
self.xml_starttag(u'node', attrs={u"name": u"%d" % node["id"]})
self.xml_tag(u"label", node["label"])
if self.has_part("realurl"):
self.xml_tag(u"url", node["url"])
self.xml_starttag(u"data")
if node["dltime"] >= 0 and self.has_part("dltime"):
self.xml_tag(u"dltime", u"%f" % node["dltime"])
if node["size"] >= 0 and self.has_part("dlsize"):
self.xml_tag(u"size", u"%d" % node["size"])
if node["checktime"] and self.has_part("checktime"):
self.xml_tag(u"checktime", u"%f" % node["checktime"])
if self.has_part("extern"):
self.xml_tag(u"extern", u"%d" % node["extern"])
self.xml_endtag(u"data")
self.xml_endtag(u"node") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end integer call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end integer call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement boolean_operator subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Write one node and all possible edges. |
def format_py2js(cls, datetime_format):
for js_format, py_format in cls.format_map:
datetime_format = datetime_format.replace(py_format, js_format)
return datetime_format | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Convert python datetime format to moment datetime format. |
def ang_veltoaxisangledot(angle, axis, Omega):
angle_dot = axis.dot(Omega)
axis_dot = 1/2*(hat_map(axis) - 1/np.tan(angle/2) * hat_map(axis).dot(hat_map(axis))).dot(Omega)
return angle_dot, axis_dot | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator integer integer call attribute parenthesized_expression binary_operator call identifier argument_list identifier binary_operator binary_operator integer call attribute identifier identifier argument_list binary_operator identifier integer call attribute call identifier argument_list identifier identifier argument_list call identifier argument_list identifier identifier argument_list identifier return_statement expression_list identifier identifier | Compute kinematics for axis angle representation |
def to_np(*args):
if len(args) > 1:
return (cp.asnumpy(x) for x in args)
else:
return cp.asnumpy(args[0]) | module function_definition identifier parameters list_splat_pattern identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier identifier else_clause block return_statement call attribute identifier identifier argument_list subscript identifier integer | convert GPU arras to numpy and return them |
def validate(token):
token_url = TOKEN_URL_FMT.format(token=token)
headers = {
'x-auth-token': token,
'accept': 'application/json',
}
resp = requests.get(token_url, headers=headers)
if not resp.status_code == 200:
raise HTTPError(status=401)
return resp.json() | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier if_statement not_operator comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list keyword_argument identifier integer return_statement call attribute identifier identifier argument_list | Validate token and return auth context. |
def check_collections_are_supported(saved_model_handler, supported):
for meta_graph in saved_model_handler.meta_graphs:
used_collection_keys = set(meta_graph.collection_def.keys())
unsupported = used_collection_keys - supported
if unsupported:
raise ValueError("Unsupported collections in graph: %s\n"
"Use hub.create_module_spec(..., drop_collections=[...])"
" as appropriate." % list(unsupported)) | module function_definition identifier parameters identifier identifier block for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block raise_statement call identifier argument_list binary_operator concatenated_string string string_start string_content escape_sequence string_end string string_start string_content string_end string string_start string_content string_end call identifier argument_list identifier | Checks that SavedModelHandler only uses supported collections. |
def create_named_notebook(fname, context):
if os.path.exists(fname):
return
from nbformat import v4 as nbf
text = "Welcome to *pyramid_notebook!* Use *File* *>* *Shutdown* to close this."
cells = [nbf.new_markdown_cell(text)]
greeting = context.get("greeting")
if greeting:
cells.append(nbf.new_markdown_cell(greeting))
cells.append(nbf.new_code_cell(''))
nb = nbf.new_notebook(cells=cells)
with open(fname, 'w') as f:
writer = JSONWriter()
writer.write(nb, f) | module function_definition identifier parameters identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block return_statement import_from_statement dotted_name identifier aliased_import dotted_name identifier identifier expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier list call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier | Create a named notebook if one doesn't exist. |
def simToReg(self, sim):
res = re.sub('^/', '', sim)
res = re.sub('/$', '', res)
return '^/?' + re.sub('\*', '[^/]+', res) + '/?$' | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier return_statement binary_operator binary_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end | Convert simplified domain expression to regular expression |
def partition(a:Collection, sz:int)->List[Collection]:
"Split iterables `a` in equal parts of size `sz`"
return [a[i:i+sz] for i in range(0, len(a), sz)] | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement string string_start string_content string_end return_statement list_comprehension subscript identifier slice identifier binary_operator identifier identifier for_in_clause identifier call identifier argument_list integer call identifier argument_list identifier identifier | Split iterables `a` in equal parts of size `sz` |
def delete(self):
resource = self.RESOURCE.format(
account_id=self.account.id,
tailored_audience_id=self.tailored_audience_id,
id=self.id)
response = Request(self.account.client, 'delete', resource).perform()
return self.from_response(response.body['data']) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute call identifier argument_list attribute attribute identifier identifier identifier string string_start string_content string_end identifier identifier argument_list return_statement call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end | Deletes the current tailored audience permission. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.