code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def dump_conndata(self):
attrs = vars(self)
return ', '.join("%s: %s" % item for item in attrs.items()) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier generator_expression binary_operator string string_start string_content string_end identifier for_in_clause identifier call attribute identifier identifier argument_list | Developer tool for debugging forensics. |
def create_weapon_layer(weapon, hashcode, isSecond=False):
return pgnreader.parse_pagan_file(('%s%spgn%s' % (PACKAGE_DIR, os.sep, os.sep)) + weapon + '.pgn', hashcode, sym=False, invert=isSecond) | module function_definition identifier parameters identifier identifier default_parameter identifier false block return_statement call attribute identifier identifier argument_list binary_operator binary_operator parenthesized_expression binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier attribute identifier identifier identifier string string_start string_content string_end identifier keyword_argument identifier false keyword_argument identifier identifier | Creates the layer for weapons. |
def describe(self):
if isinstance(self._plugin, list):
pl = [p.name for p in self._plugin]
elif isinstance(self._plugin, dict):
pl = {k: classname(v) for k, v in self._plugin.items()}
else:
pl = self._plugin if isinstance(self._plugin, str) else self._plugin.name
return {
'name': self._name,
'container': self._container,
'plugin': pl,
'description': self._description,
'direct_access': self._direct_access,
'user_parameters': [u.describe() for u in self._user_parameters],
'metadata': self._metadata,
'args': self._open_args
} | module function_definition identifier parameters identifier block if_statement call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier elif_clause call identifier argument_list attribute identifier identifier identifier block expression_statement assignment identifier dictionary_comprehension pair identifier call identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list else_clause block expression_statement assignment identifier conditional_expression attribute identifier identifier call identifier argument_list attribute identifier identifier identifier attribute attribute identifier identifier identifier return_statement dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list for_in_clause identifier attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier | Basic information about this entry |
def _run_with_different_python(executable):
args = [arg for arg in sys.argv if arg != VIRTUALENV_OPTION]
args.insert(0, executable)
print("Running bootstrap.py with {0}".format(executable))
exit(subprocess.call(args)) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator identifier identifier expression_statement call attribute identifier identifier argument_list integer identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list identifier | Run bootstrap.py with a different python executable |
def shapes(self):
if self._shapes:
return self._shapes
self.log("Generating shapes...")
ret = collections.defaultdict(entities.ShapeLine)
for point in self.read('shapes'):
ret[point['shape_id']].add_child(point)
self._shapes = ret
return self._shapes | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute subscript identifier subscript identifier string string_start string_content string_end identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier return_statement attribute identifier identifier | Return the route shapes as a dictionary. |
def modify_item(self, item_uri, metadata):
md = json.dumps({'metadata': metadata})
response = self.api_request(item_uri, method='PUT', data=md)
return self.__check_success(response) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list identifier | Modify the metadata on an item |
def _fromiter(it, dtype, count, progress, log):
if progress > 0:
it = _iter_withprogress(it, progress, log)
if count is not None:
a = np.fromiter(it, dtype=dtype, count=count)
else:
a = np.fromiter(it, dtype=dtype)
return a | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement comparison_operator identifier integer block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Utility function to load an array from an iterator. |
def dump(self):
print("pagesize=%08x, reccount=%08x, pagecount=%08x" % (self.pagesize, self.reccount, self.pagecount))
self.dumpfree()
self.dumptree(self.firstindex) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier | raw dump of all records in the b-tree |
def ExpirePrefix(self, prefix):
for key in list(self._hash):
if key.startswith(prefix):
self.ExpireObject(key) | module function_definition identifier parameters identifier identifier block for_statement identifier call identifier argument_list attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier | Expire all the objects with the key having a given prefix. |
def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource",
middleware=None):
def inner(c):
op = ResourceOperation(c, path or NoPath, method, resource, tags, summary, middleware)
op.responses.add(Response(HTTPStatus.CREATED, "{name} has been created"))
op.responses.add(Response(HTTPStatus.BAD_REQUEST, "Validation failed.", Error))
return op
return inner(callback) if callback else inner | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier attribute identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier none block function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier boolean_operator identifier identifier identifier identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list attribute identifier identifier string string_start string_content string_end identifier return_statement identifier return_statement conditional_expression call identifier argument_list identifier identifier identifier | Decorator to configure an operation that creates a resource. |
def filter_users_by_claims(self, claims):
email = claims.get('email')
if not email:
return self.UserModel.objects.none()
return self.UserModel.objects.filter(email__iexact=email) | 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 if_statement not_operator identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier | Return all users matching the specified email. |
def to_transitions(self) -> 'Transitions':
return Transitions(
size=self.num_steps * self.num_envs,
environment_information=
[ei for l in self.environment_information for ei in l]
if self.environment_information is not None else None,
transition_tensors={
name: tensor_util.merge_first_two_dims(t) for name, t in self.transition_tensors.items()
},
extra_data=self.extra_data
) | module function_definition identifier parameters identifier type string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier binary_operator attribute identifier identifier attribute identifier identifier keyword_argument identifier conditional_expression list_comprehension identifier for_in_clause identifier attribute identifier identifier for_in_clause identifier identifier comparison_operator attribute identifier identifier none none keyword_argument identifier dictionary_comprehension pair identifier call attribute identifier identifier argument_list identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier | Convert given rollout to Transitions |
def split_leading_trailing_indent(line, max_indents=None):
leading_indent, line = split_leading_indent(line, max_indents)
line, trailing_indent = split_trailing_indent(line, max_indents)
return leading_indent, line, trailing_indent | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier return_statement expression_list identifier identifier identifier | Split leading and trailing indent. |
def shape_list(l,shape,dtype):
return np.array(l, dtype=dtype).reshape(shape) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute call attribute identifier identifier argument_list identifier keyword_argument identifier identifier identifier argument_list identifier | Shape a list of lists into the appropriate shape and data type |
def package_info(self, package, abspath=True):
return self._call_and_parse(['info', package, '--json'],
abspath=abspath) | module function_definition identifier parameters identifier identifier default_parameter identifier true block return_statement call attribute identifier identifier argument_list list string string_start string_content string_end identifier string string_start string_content string_end keyword_argument identifier identifier | Return a dictionary with package information. |
def _ensure_queue(self):
if self._queue_path not in self._client.kv:
self._client.kv[self._queue_path] = None | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment subscript attribute attribute identifier identifier identifier attribute identifier identifier none | Ensure queue exists in Consul. |
def write_xml(self, xmlfile):
xmlfile = self.get_model_path(xmlfile)
self.logger.info('Writing %s...', xmlfile)
self.like.writeXml(str(xmlfile)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier | Write the XML model for this analysis component. |
def organisations(self):
class Org:
def __init__(self, sdo_id, org_id, members, obj):
self.sdo_id = sdo_id
self.org_id = org_id
self.members = members
self.obj = obj
with self._mutex:
if not self._orgs:
for org in self._obj.get_owned_organizations():
owner = org.get_owner()
if owner:
sdo_id = owner._narrow(SDOPackage.SDO).get_sdo_id()
else:
sdo_id = ''
org_id = org.get_organization_id()
members = [m.get_sdo_id() for m in org.get_members()]
self._orgs.append(Org(sdo_id, org_id, members, org))
return self._orgs | module function_definition identifier parameters identifier block class_definition identifier block function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier with_statement with_clause with_item attribute identifier identifier block if_statement not_operator attribute identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list else_clause block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier identifier identifier return_statement attribute identifier identifier | The organisations of this composition. |
def intervention(self, commit, conf):
if not conf.harpoon.interactive or conf.harpoon.no_intervention:
yield
return
hp.write_to(conf.harpoon.stdout, "!!!!\n")
hp.write_to(conf.harpoon.stdout, "It would appear building the image failed\n")
hp.write_to(conf.harpoon.stdout, "Do you want to run {0} where the build to help debug why it failed?\n".format(conf.resolved_shell))
conf.harpoon.stdout.flush()
answer = input("[y]: ")
if answer and not answer.lower().startswith("y"):
yield
return
with self.commit_and_run(commit, conf, command=conf.resolved_shell):
yield | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator not_operator attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier block expression_statement yield return_statement expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier string string_start string_content escape_sequence string_end expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list attribute identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement boolean_operator identifier not_operator call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement yield return_statement with_statement with_clause with_item call attribute identifier identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier block expression_statement yield | Ask the user if they want to commit this container and run sh in it |
def _get_id_format(self):
id_format = gf.safe_get(
self.parameters,
gc.PPN_TASK_OS_FILE_ID_REGEX,
self.DEFAULT_ID_FORMAT,
can_return_none=False
)
try:
identifier = id_format % 1
except (TypeError, ValueError) as exc:
self.log_exc(u"String '%s' is not a valid id format" % (id_format), exc, True, ValueError)
return id_format | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier keyword_argument identifier false try_statement block expression_statement assignment identifier binary_operator identifier integer except_clause as_pattern tuple identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier identifier true identifier return_statement identifier | Return the id regex from the parameters |
def loop(self):
while True:
text = compat.input('ctl > ')
command, args = self.parse_input(text)
if not command:
continue
response = self.call(command, *args)
response.show() | module function_definition identifier parameters identifier block while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier list_splat identifier expression_statement call attribute identifier identifier argument_list | Enter loop, read user input then run command. Repeat |
def _cnvbed_to_bed(in_file, caller, out_file):
with open(out_file, "w") as out_handle:
for feat in pybedtools.BedTool(in_file):
out_handle.write("\t".join([feat.chrom, str(feat.start), str(feat.end),
"cnv%s_%s" % (feat.score, caller)])
+ "\n") | module function_definition identifier parameters identifier identifier 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 call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator call attribute string string_start string_content escape_sequence string_end identifier argument_list list attribute identifier identifier call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier string string_start string_content escape_sequence string_end | Convert cn_mops CNV based bed files into flattened BED |
def find_best_rsquared(list_of_fits):
res = sorted(list_of_fits, key=lambda x: x.rsquared)
return res[-1] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier lambda lambda_parameters identifier attribute identifier identifier return_statement subscript identifier unary_operator integer | Return the best fit, based on rsquared |
def _filter(self, text, context, encoding):
content = []
blocks, attributes, comments = self.to_text(bs4.BeautifulSoup(text, self.parser))
if self.comments:
for c, desc in comments:
content.append(filters.SourceText(c, context + ': ' + desc, encoding, self.type + 'comment'))
if self.attributes:
for a, desc in attributes:
content.append(filters.SourceText(a, context + ': ' + desc, encoding, self.type + 'attribute'))
for b, desc in blocks:
content.append(filters.SourceText(b, context + ': ' + desc, encoding, self.type + 'content'))
return content | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier if_statement attribute identifier identifier block for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier binary_operator binary_operator identifier string string_start string_content string_end identifier identifier binary_operator attribute identifier identifier string string_start string_content string_end if_statement attribute identifier identifier block for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier binary_operator binary_operator identifier string string_start string_content string_end identifier identifier binary_operator attribute identifier identifier string string_start string_content string_end for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier binary_operator binary_operator identifier string string_start string_content string_end identifier identifier binary_operator attribute identifier identifier string string_start string_content string_end return_statement identifier | Filter the source text. |
def poll_open_file_languages(self):
languages = []
for index in range(self.get_stack_count()):
languages.append(
self.tabs.widget(index).language.lower())
return set(languages) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute attribute call attribute attribute identifier identifier identifier argument_list identifier identifier identifier argument_list return_statement call identifier argument_list identifier | Get list of current opened files' languages |
def discard(self, s):
lines = s.splitlines(True)
for line in lines:
if line[-1] not in '\r\n':
if not self.warn:
logger.warning(
'partial line discard UNSUPPORTED; source map '
'generated will not match at the column level'
)
self.warn = True
else:
self.row += 1 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list true for_statement identifier identifier block if_statement comparison_operator subscript identifier unary_operator integer string string_start string_content escape_sequence escape_sequence string_end block if_statement not_operator attribute 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 true else_clause block expression_statement augmented_assignment attribute identifier identifier integer | Discard from original file. |
def _logout(self, reset=True):
url = '{base}/client/auth/logout'.format(base=self.base_url)
response = self._session.get(url, params=self._parameters)
if response.ok:
if reset:
self._reset()
return True
else:
return False | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier if_statement attribute identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list return_statement true else_clause block return_statement false | Log out of the API. |
def dcm2body313(dcm):
theta = np.zeros(3)
theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1])
theta[1] = np.arccos(dcm[2, 2])
theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2])
return theta | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment subscript identifier integer call attribute identifier identifier argument_list subscript identifier integer integer subscript identifier integer integer expression_statement assignment subscript identifier integer call attribute identifier identifier argument_list subscript identifier integer integer expression_statement assignment subscript identifier integer call attribute identifier identifier argument_list subscript identifier integer integer unary_operator subscript identifier integer integer return_statement identifier | Convert DCM to body Euler 3-1-3 angles |
def clear(self):
for root, dirs, files in os.walk(self._root_dir, topdown=False):
for file in files:
os.unlink(os.path.join(root, file))
os.rmdir(root)
root_dir = os.path.abspath(
os.path.join(self._root_dir, os.pardir))
self.__init__(root_dir) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier false block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Clears all data from the data store permanently |
def update(self, *args, **kwargs):
d = {}
d.update(*args, **kwargs)
for key, value in d.items():
self[key] = value | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary expression_statement call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier identifier | Update self with new content |
def standardize_cnv_reference(data):
out = tz.get_in(["config", "algorithm", "background", "cnv_reference"], data, {})
cur_callers = set(data["config"]["algorithm"].get("svcaller")) & _CNV_REFERENCE
if isinstance(out, six.string_types):
if not len(cur_callers) == 1:
raise ValueError("Multiple CNV callers and single background reference for %s: %s" %
data["description"], list(cur_callers))
else:
out = {cur_callers.pop(): out}
return out | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list 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 identifier dictionary expression_statement assignment identifier binary_operator call identifier argument_list call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end identifier if_statement call identifier argument_list identifier attribute identifier identifier block if_statement not_operator comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end subscript identifier string string_start string_content string_end call identifier argument_list identifier else_clause block expression_statement assignment identifier dictionary pair call attribute identifier identifier argument_list identifier return_statement identifier | Standardize cnv_reference background to support multiple callers. |
def compute_stability_classification(self, predicted_data, record, dataframe_record):
stability_classification, stability_classication_x_cutoff, stability_classication_y_cutoff = None, self.stability_classication_x_cutoff, self.stability_classication_y_cutoff
if record['DDG'] != None:
stability_classification = fraction_correct([record['DDG']], [predicted_data[self.ddg_analysis_type]], x_cutoff = stability_classication_x_cutoff, y_cutoff = stability_classication_y_cutoff)
stability_classification = int(stability_classification)
assert(stability_classification == 0 or stability_classification == 1)
dataframe_record['StabilityClassification'] = stability_classification | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_list none attribute identifier identifier attribute identifier identifier if_statement comparison_operator subscript identifier string string_start string_content string_end none block expression_statement assignment identifier call identifier argument_list list subscript identifier string string_start string_content string_end list subscript identifier attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list identifier assert_statement parenthesized_expression boolean_operator comparison_operator identifier integer comparison_operator identifier integer expression_statement assignment subscript identifier string string_start string_content string_end identifier | Calculate the stability classification for this case. |
def normalized_distance(self, *sequences):
return float(self.distance(*sequences)) / self.maximum(*sequences) | module function_definition identifier parameters identifier list_splat_pattern identifier block return_statement binary_operator call identifier argument_list call attribute identifier identifier argument_list list_splat identifier call attribute identifier identifier argument_list list_splat identifier | Get distance from 0 to 1 |
def last_update_time(self) -> float:
stdout = self.stdout_interceptor
stderr = self.stderr_interceptor
return max([
self._last_update_time,
stdout.last_write_time if stdout else 0,
stderr.last_write_time if stderr else 0,
]) | module function_definition identifier parameters identifier type identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier return_statement call identifier argument_list list attribute identifier identifier conditional_expression attribute identifier identifier identifier integer conditional_expression attribute identifier identifier identifier integer | The last time at which the report was modified. |
def valid_date(date):
"Validate an expires datetime object"
if not hasattr(date, 'tzinfo'):
return False
if date.tzinfo is None or _total_seconds(date.utcoffset()) < 1.1:
return True
return False | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block return_statement false if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator call identifier argument_list call attribute identifier identifier argument_list float block return_statement true return_statement false | Validate an expires datetime object |
def _initialize_expectations(self, config=None, data_asset_name=None):
super(Dataset, self)._initialize_expectations(config=config, data_asset_name=data_asset_name)
self._expectations_config["data_asset_type"] = "Dataset" | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end | Override data_asset_type with "Dataset" |
def sigmoid_grad(self, z):
return np.multiply(self.sigmoid(z), 1-self.sigmoid(z)) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier binary_operator integer call attribute identifier identifier argument_list identifier | Gradient of sigmoid function. |
def startThread(self):
if self._thread is not None:
return
self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None)
self._thread.start() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement assignment attribute identifier identifier call attribute call attribute identifier identifier argument_list identifier argument_list identifier string string_start string_content string_end none expression_statement call attribute attribute identifier identifier identifier argument_list | Spawns new NSThread to handle notifications. |
def dump_memdb(self, with_source_contents=True, with_names=True):
len_out = _ffi.new('unsigned int *')
buf = rustcall(
_lib.lsm_view_dump_memdb,
self._get_ptr(), len_out,
with_source_contents, with_names)
try:
rv = _ffi.unpack(buf, len_out[0])
finally:
_lib.lsm_buffer_free(buf)
return rv | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier true block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list identifier identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier subscript identifier integer finally_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Dumps a sourcemap in MemDB format into bytes. |
def _register_dependencies(self):
for tree_name, context_entry in context.timetable_context.items():
tree = self.trees[tree_name]
assert isinstance(tree, MultiLevelTree)
for dependent_on in context_entry.dependent_on:
dependent_on_tree = self.trees[dependent_on]
assert isinstance(dependent_on_tree, MultiLevelTree)
tree.register_dependent_on(dependent_on_tree) | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier subscript attribute identifier identifier identifier assert_statement call identifier argument_list identifier identifier for_statement identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier assert_statement call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | register dependencies between trees |
def compute_refresh_time(self):
if self.z == 0:
self.z = 1E-10
s = float(self.expiration) * (1.0/(self.nbr_bits)) * (1.0/(self.counter_init - 1 + (1.0/(self.z * (self.nbr_slices + 1)))))
return s | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment attribute identifier identifier float expression_statement assignment identifier binary_operator binary_operator call identifier argument_list attribute identifier identifier parenthesized_expression binary_operator float parenthesized_expression attribute identifier identifier parenthesized_expression binary_operator float parenthesized_expression binary_operator binary_operator attribute identifier identifier integer parenthesized_expression binary_operator float parenthesized_expression binary_operator attribute identifier identifier parenthesized_expression binary_operator attribute identifier identifier integer return_statement identifier | Compute the refresh period for the given expiration delay |
def join_field(path):
output = ".".join([f.replace(".", "\\.") for f in path if f != None])
return output if output else "." | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content escape_sequence string_end for_in_clause identifier identifier if_clause comparison_operator identifier none return_statement conditional_expression identifier identifier string string_start string_content string_end | RETURN field SEQUENCE AS STRING |
def async_func(self, function):
@wraps(function)
def wrapped(*args, **kwargs):
return self.submit(function, *args, **kwargs)
return wrapped | module function_definition identifier parameters identifier identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Decorator for let a normal function return the NewFuture |
def vt_name_check(domain, vt_api):
if not is_fqdn(domain):
return None
url = 'https://www.virustotal.com/vtapi/v2/domain/report'
parameters = {'domain': domain, 'apikey': vt_api}
response = requests.get(url, params=parameters)
try:
return response.json()
except ValueError:
return None | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier block return_statement none expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier try_statement block return_statement call attribute identifier identifier argument_list except_clause identifier block return_statement none | Checks VirusTotal for occurrences of a domain name |
def createDocParserCtxt(cur):
ret = libxml2mod.xmlCreateDocParserCtxt(cur)
if ret is None:raise parserError('xmlCreateDocParserCtxt() failed')
return parserCtxt(_obj=ret) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end return_statement call identifier argument_list keyword_argument identifier identifier | Creates a parser context for an XML in-memory document. |
def addSSLService(self):
"adds a SSLService to the instaitated HendrixService"
https_port = self.options['https_port']
self.tls_service = HendrixTCPServiceWithTLS(https_port, self.hendrix.site, self.key, self.cert,
self.context_factory, self.context_factory_kwargs)
self.tls_service.setServiceParent(self.hendrix) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call identifier argument_list identifier attribute attribute identifier identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | adds a SSLService to the instaitated HendrixService |
def locate_bar_r(icut, epos):
sm = len(icut)
def swap_coor(x):
return sm - 1 - x
def swap_line(tab):
return tab[::-1]
return _locate_bar_gen(icut, epos, transform1=swap_coor,
transform2=swap_line) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier function_definition identifier parameters identifier block return_statement binary_operator binary_operator identifier integer identifier function_definition identifier parameters identifier block return_statement subscript identifier slice unary_operator integer return_statement call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Fine position of the right CSU bar |
def _tostream(parser, obj, stream, skipprepack = False):
if hasattr(parser, 'tostream'):
return parser.tostream(obj, stream, skipprepack)
else:
data = parser.tobytes(obj, skipprepack)
cls = type(parser)
if cls not in _deprecated_parsers:
_deprecated_parsers.add(cls)
warnings.warn("Parser %r does not have 'tostream' interfaces" % (cls,), UserWarning)
return stream.write(data) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block if_statement call identifier argument_list identifier string string_start string_content string_end block return_statement call attribute identifier identifier argument_list identifier identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier identifier 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 tuple identifier identifier return_statement call attribute identifier identifier argument_list identifier | Compatible to old parsers |
def find_pingback_urls(self, urls):
pingback_urls = {}
for url in urls:
try:
page = urlopen(url)
headers = page.info()
server_url = headers.get('X-Pingback')
if not server_url:
content_type = headers.get('Content-Type', '').split(
';')[0].strip().lower()
if content_type in ['text/html', 'application/xhtml+xml']:
server_url = self.find_pingback_href(
page.read(5 * 1024))
if server_url:
server_url_splitted = urlsplit(server_url)
if not server_url_splitted.netloc:
url_splitted = urlsplit(url)
server_url = '%s://%s%s' % (url_splitted.scheme,
url_splitted.netloc,
server_url)
pingback_urls[url] = server_url
except IOError:
pass
return pingback_urls | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment identifier call attribute call attribute subscript call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list string string_start string_content string_end integer identifier argument_list identifier argument_list if_statement comparison_operator identifier list 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 call attribute identifier identifier argument_list binary_operator integer integer if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier attribute identifier identifier identifier expression_statement assignment subscript identifier identifier identifier except_clause identifier block pass_statement return_statement identifier | Find the pingback URL for each URLs. |
def unflatten(self, obj):
obj.substitutions = [
dict(from_id=key, to_id=value)
for key, value in getattr(obj, "substitutions", {}).items()
] | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier list_comprehension call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause pattern_list identifier identifier call attribute call identifier argument_list identifier string string_start string_content string_end dictionary identifier argument_list | Translate substitutions dictionary into objects. |
def _CollectArtifact(self, artifact, apply_parsers):
artifact_result = rdf_artifacts.CollectedArtifact(name=artifact.name)
if apply_parsers:
parser_factory = parsers.ArtifactParserFactory(str(artifact.name))
else:
parser_factory = None
for source_result_list in self._ProcessSources(artifact.sources,
parser_factory):
for response in source_result_list:
action_result = rdf_artifacts.ClientActionResult()
action_result.type = response.__class__.__name__
action_result.value = response
artifact_result.action_results.append(action_result)
self.UpdateKnowledgeBase(response, artifact.provides)
return artifact_result | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier none for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier return_statement identifier | Returns an `CollectedArtifact` rdf object for the requested artifact. |
def connect_gridfs(uri, db=None):
return gridfs.GridFS(
db or connect_db(uri),
collection=get_collection(uri) or 'fs',
) | module function_definition identifier parameters identifier default_parameter identifier none block return_statement call attribute identifier identifier argument_list boolean_operator identifier call identifier argument_list identifier keyword_argument identifier boolean_operator call identifier argument_list identifier string string_start string_content string_end | Construct a GridFS instance for a MongoDB URI. |
def create(python, env_dir, system, prompt, bare, virtualenv_py=None):
if not python or python == sys.executable:
_create_with_this(
env_dir=env_dir, system=system, prompt=prompt,
bare=bare, virtualenv_py=virtualenv_py,
)
else:
_create_with_python(
python=python,
env_dir=env_dir, system=system, prompt=prompt,
bare=bare, virtualenv_py=virtualenv_py,
) | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none block if_statement boolean_operator not_operator identifier comparison_operator identifier attribute identifier identifier block expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier else_clause block expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Main entry point to use this as a module. |
def _previous(self, **kwargs):
spec = self._pagination_default_spec(kwargs)
spec.update(kwargs)
query = queries.build_query(spec)
query = queries.where_before_entry(query, self._record)
for record in query.order_by(orm.desc(model.Entry.local_date),
orm.desc(model.Entry.id))[:1]:
return Entry(record)
return None | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier for_statement identifier subscript call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute attribute identifier identifier identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier slice integer block return_statement call identifier argument_list identifier return_statement none | Get the previous item in any particular category |
def _generate_constructor(cls, names):
cache = cls._constructors
if names in cache:
return cache[names]
elif len(cache) > 3:
cache.clear()
func = generate_constructor(cls, names)
cache[names] = func
return func | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier identifier block return_statement subscript identifier identifier elif_clause comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment subscript identifier identifier identifier return_statement identifier | Get a hopefully cache constructor |
def compile(expr, params=None):
from ibis.sql.alchemy import to_sqlalchemy
return to_sqlalchemy(expr, dialect.make_context(params=params)) | module function_definition identifier parameters identifier default_parameter identifier none block import_from_statement dotted_name identifier identifier identifier dotted_name identifier return_statement call identifier argument_list identifier call attribute identifier identifier argument_list keyword_argument identifier identifier | Force compilation of expression for the SQLite target |
def serialized (self, sep=os.linesep):
return unicode_safe(sep).join([
u"%s link" % self.scheme,
u"base_url=%r" % self.base_url,
u"parent_url=%r" % self.parent_url,
u"base_ref=%r" % self.base_ref,
u"recursion_level=%d" % self.recursion_level,
u"url_connection=%s" % self.url_connection,
u"line=%d" % self.line,
u"column=%d" % self.column,
u"page=%d" % self.page,
u"name=%r" % self.name,
u"anchor=%r" % self.anchor,
u"cache_url=%s" % self.cache_url,
]) | module function_definition identifier parameters identifier default_parameter identifier attribute identifier identifier block return_statement call attribute call identifier argument_list identifier identifier argument_list list binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier binary_operator string string_start string_content string_end attribute identifier identifier | Return serialized url check data as unicode string. |
def command_new_config(self):
if len(self.args) == 1 and self.args[0] == "new-config":
NewConfig().run()
else:
usage("") | module function_definition identifier parameters identifier block if_statement boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator subscript attribute identifier identifier integer string string_start string_content string_end block expression_statement call attribute call identifier argument_list identifier argument_list else_clause block expression_statement call identifier argument_list string string_start string_end | Manage .new configuration files |
def chmod(path, mode):
import os, stat
st = os.stat(path)
return os.chmod(path, mode) | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier | change pernmissions of path |
def _index_files(path):
with zipfile.ZipFile(path) as zf:
names = sorted(zf.namelist())
names = [nn for nn in names if nn.endswith(".tif")]
names = [nn for nn in names if nn.startswith("SID PHA")]
phasefiles = []
for name in names:
with zf.open(name) as pt:
fd = io.BytesIO(pt.read())
if SingleTifPhasics.verify(fd):
phasefiles.append(name)
return phasefiles | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement identifier identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Search zip file for SID PHA files |
def create(cls, entry):
try:
module = import_module(entry)
except ImportError:
module = None
mod_path, _, cls_name = entry.rpartition('.')
if not mod_path:
raise
else:
try:
entry = module.default_bot
except AttributeError:
return cls(f'{entry}.Bot', module)
else:
mod_path, _, cls_name = entry.rpartition('.')
mod = import_module(mod_path)
try:
bot_cls = getattr(mod, cls_name)
except AttributeError:
if module is None:
import_module(entry)
raise
if not issubclass(bot_cls, Bot):
raise ImproperlyConfigured(
"'%s' isn't a subclass of Bot." % entry)
return cls(entry, mod, bot_cls.label) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block expression_statement assignment identifier none expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement not_operator identifier block raise_statement else_clause block try_statement block expression_statement assignment identifier attribute identifier identifier except_clause identifier block return_statement call identifier argument_list string string_start interpolation identifier string_content string_end identifier else_clause block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier try_statement block expression_statement assignment identifier call identifier argument_list identifier identifier except_clause identifier block if_statement comparison_operator identifier none block expression_statement call identifier argument_list identifier raise_statement if_statement not_operator call identifier argument_list identifier identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement call identifier argument_list identifier identifier attribute identifier identifier | Factory that creates an bot config from an entry in INSTALLED_APPS. |
def wrap_exception(func: Callable) -> Callable:
try:
from pygatt.backends.bgapi.exceptions import BGAPIError
from pygatt.exceptions import NotConnectedError
except ImportError:
return func
def _func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except BGAPIError as exception:
raise BluetoothBackendException() from exception
except NotConnectedError as exception:
raise BluetoothBackendException() from exception
return _func_wrapper | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block try_statement block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier import_from_statement dotted_name identifier identifier dotted_name identifier except_clause identifier block return_statement identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier return_statement identifier | Decorator to wrap pygatt exceptions into BluetoothBackendException. |
def prepare_service(args=None):
options.register_opts(cfg.CONF)
services.load_service_opts(cfg.CONF)
_configure(args)
_setup_logging()
cfg.CONF.log_opt_values(logging.getLogger(), logging.DEBUG) | module function_definition identifier parameters default_parameter identifier none block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call identifier argument_list identifier expression_statement call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier | Configures application and setups logging. |
def _get_mapping_from_secret_type_to_class_name():
mapping = {}
for key, value in globals().items():
try:
if issubclass(value, BasePlugin) and value != BasePlugin:
mapping[value.secret_type] = key
except TypeError:
pass
return mapping | module function_definition identifier parameters block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute call identifier argument_list identifier argument_list block try_statement block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator identifier identifier block expression_statement assignment subscript identifier attribute identifier identifier identifier except_clause identifier block pass_statement return_statement identifier | Returns secret_type => plugin classname |
def SetLowerTimestamp(cls, timestamp):
if not hasattr(cls, '_lower'):
cls._lower = timestamp
return
if timestamp < cls._lower:
cls._lower = timestamp | module function_definition identifier parameters identifier identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier identifier return_statement if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier identifier | Sets the lower bound timestamp. |
def values(service, id, ranges):
params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING'}
params.update(spreadsheetId=id, ranges=ranges)
response = service.spreadsheets().values().batchGet(**params).execute()
return response['valueRanges'] | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute call attribute call attribute call attribute identifier identifier argument_list identifier argument_list identifier argument_list dictionary_splat identifier identifier argument_list return_statement subscript identifier string string_start string_content string_end | Fetch and return spreadsheet cell values with Google sheets API. |
def format_wsfc_domain_profile(result):
from collections import OrderedDict
order_dict = OrderedDict()
if result.cluster_bootstrap_account is not None:
order_dict['clusterBootstrapAccount'] = result.cluster_bootstrap_account
if result.domain_fqdn is not None:
order_dict['domainFqdn'] = result.domain_fqdn
if result.ou_path is not None:
order_dict['ouPath'] = result.ou_path
if result.cluster_operator_account is not None:
order_dict['clusterOperatorAccount'] = result.cluster_operator_account
if result.file_share_witness_path is not None:
order_dict['fileShareWitnessPath'] = result.file_share_witness_path
if result.sql_service_account is not None:
order_dict['sqlServiceAccount'] = result.sql_service_account
if result.storage_account_url is not None:
order_dict['storageAccountUrl'] = result.storage_account_url
return order_dict | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Formats the WSFCDomainProfile object removing arguments that are empty |
def unsign_filters_and_actions(sign, dotted_model_name):
permissions = signing.loads(sign)
return permissions.get(dotted_model_name, []) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier list | Return the list of filters and actions for dotted_model_name. |
def risk(self, domain, **kwargs):
return self._results('risk', '/v1/risk', items_path=('components', ), domain=domain, cls=Reputation,
**kwargs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end keyword_argument identifier tuple string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier | Returns back the risk score for a given domain |
def inject_func_as_unbound_method(class_, func, method_name=None):
if method_name is None:
method_name = get_funcname(func)
setattr(class_, method_name, func) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier identifier | This is actually quite simple |
def random_real_solution(solution_size, lower_bounds, upper_bounds):
return [
random.uniform(lower_bounds[i], upper_bounds[i])
for i in range(solution_size)
] | module function_definition identifier parameters identifier identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list subscript identifier identifier subscript identifier identifier for_in_clause identifier call identifier argument_list identifier | Make a list of random real numbers between lower and upper bounds. |
def eps(self):
import tkFileDialog,tkMessageBox
filename=tkFileDialog.asksaveasfilename(message="save postscript to file",filetypes=['eps','ps'])
if filename is None:
return
self.postscript(file=filename) | module function_definition identifier parameters identifier block import_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier none block return_statement expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Print the canvas to a postscript file |
def _log(self):
self._log_platform()
self._log_app_data()
self._log_python_version()
self._log_tcex_version()
self._log_tc_proxy() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Send System and App data to logs. |
def _compile_value(self, data, indent_level):
if isinstance(data, dict):
return self._compile_key_val(data, indent_level)
elif isinstance(data, list):
return self._compile_list(data, indent_level)
else:
return self._compile_literal(data) | module function_definition identifier parameters identifier identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier identifier else_clause block return_statement call attribute identifier identifier argument_list identifier | Dispatch to correct compilation method. |
def _create_event_listeners(self):
LOG.debug("Create the event listeners.")
for event_type, callback in self._event_callback_pairs:
LOG.debug("Create listener for %r event", event_type)
listener = self._utils.get_vnic_event_listener(event_type)
eventlet.spawn_n(listener, callback) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Create and bind the event listeners. |
def _create_core_dns_instance(self, instance):
endpoint = instance.get('prometheus_url')
if endpoint is None:
raise ConfigurationError("Unable to find prometheus endpoint in config file.")
metrics = [DEFAULT_METRICS, GO_METRICS]
metrics.extend(instance.get('metrics', []))
instance.update({'prometheus_url': endpoint, 'namespace': 'coredns', 'metrics': metrics})
return instance | 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 if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier list identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement call attribute identifier identifier argument_list 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 pair string string_start string_content string_end identifier return_statement identifier | Set up coredns instance so it can be used in OpenMetricsBaseCheck |
def unzip(self, directory):
if not os.path.exists(directory):
os.makedirs(directory)
shutil.copytree(self.src_dir, directory) | module function_definition identifier parameters identifier identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Write contents of zipfile to directory |
def auth_url(self, scope):
params = {
'response_type': 'code',
'client_id': self.__client_id,
'redirect_uri': self.__redirect_uri,
'scope': scope
}
if self.__state is not None:
params['state'] = self.__state
return settings.AUTH_ENDPOINT + '/authorize?' + urllib.urlencode(params) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement binary_operator binary_operator attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier | Gets the url a user needs to access to give up a user token |
def prepare_params(self):
if self.options.resolve_fragment:
self.fragment_name = self.node.fragment_name.resolve(self.context)
else:
self.fragment_name = str(self.node.fragment_name)
for char in '\'\"':
if self.fragment_name.startswith(char) or self.fragment_name.endswith(char):
if self.fragment_name.startswith(char) and self.fragment_name.endswith(char):
self.fragment_name = self.fragment_name[1:-1]
break
else:
raise ValueError('Number of quotes around the fragment name is incoherent')
self.expire_time = self.get_expire_time()
if self.options.versioning:
self.version = force_bytes(self.get_version())
self.vary_on = [template.Variable(var).resolve(self.context) for var in self.node.vary_on] | module function_definition identifier parameters identifier block if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call attribute attribute attribute identifier identifier identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list attribute attribute identifier identifier identifier for_statement identifier string string_start string_content escape_sequence escape_sequence string_end block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier block if_statement boolean_operator call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment attribute identifier identifier subscript attribute identifier identifier slice integer unary_operator integer break_statement else_clause block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list if_statement attribute attribute identifier identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier list_comprehension call attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier | Prepare the parameters passed to the templatetag |
def DeleteOldCronJobRuns(self, cutoff_timestamp):
deleted = 0
for run in list(itervalues(self.cronjob_runs)):
if run.timestamp < cutoff_timestamp:
del self.cronjob_runs[(run.cron_job_id, run.run_id)]
deleted += 1
return deleted | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer for_statement identifier call identifier argument_list call identifier argument_list attribute identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block delete_statement subscript attribute identifier identifier tuple attribute identifier identifier attribute identifier identifier expression_statement augmented_assignment identifier integer return_statement identifier | Deletes cron job runs for a given job id. |
def put_ops(self, key, time, ops):
if self._store.get(key) is None:
self._store[key] = ops | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator call attribute attribute identifier identifier identifier argument_list identifier none block expression_statement assignment subscript attribute identifier identifier identifier identifier | Put an ops only if not already there, otherwise it's a no op. |
def create_dicts(data):
chars = set()
for sample in data:
chars.update(set(sample))
char_indices = dict((c, i) for i, c in enumerate(chars))
indices_char = dict((i, c) for i, c in enumerate(chars))
return char_indices, indices_char | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier return_statement expression_list identifier identifier | Modified from Keras LSTM example |
def BuildLegacySubject(subject_id, approval_type):
at = rdf_objects.ApprovalRequest.ApprovalType
if approval_type == at.APPROVAL_TYPE_CLIENT:
return "aff4:/%s" % subject_id
elif approval_type == at.APPROVAL_TYPE_HUNT:
return "aff4:/hunts/%s" % subject_id
elif approval_type == at.APPROVAL_TYPE_CRON_JOB:
return "aff4:/cron/%s" % subject_id
raise ValueError("Invalid approval type.") | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement binary_operator string string_start string_content string_end identifier elif_clause comparison_operator identifier attribute identifier identifier block return_statement binary_operator string string_start string_content string_end identifier elif_clause comparison_operator identifier attribute identifier identifier block return_statement binary_operator string string_start string_content string_end identifier raise_statement call identifier argument_list string string_start string_content string_end | Builds a legacy AFF4 urn string for a given subject and approval type. |
def cmd_oreoled(self, args):
if len(args) < 4:
print("Usage: oreoled LEDNUM RED GREEN BLUE <RATE>")
return
lednum = int(args[0])
pattern = [0] * 24
pattern[0] = ord('R')
pattern[1] = ord('G')
pattern[2] = ord('B')
pattern[3] = ord('0')
pattern[4] = 0
pattern[5] = int(args[1])
pattern[6] = int(args[2])
pattern[7] = int(args[3])
self.master.mav.led_control_send(self.settings.target_system,
self.settings.target_component,
lednum, 255, 8, pattern) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list subscript identifier integer expression_statement assignment identifier binary_operator list integer integer expression_statement assignment subscript identifier integer call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier integer call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier integer call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier integer call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier integer integer expression_statement assignment subscript identifier integer call identifier argument_list subscript identifier integer expression_statement assignment subscript identifier integer call identifier argument_list subscript identifier integer expression_statement assignment subscript identifier integer call identifier argument_list subscript identifier integer expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier identifier integer integer identifier | send LED pattern as override, using OreoLED conventions |
def delete_by_field(self, table: str, field: str, value: Any) -> int:
sql = ("DELETE FROM " + self.delimit(table) +
" WHERE " + self.delimit(field) + "=?")
return self.db_exec(sql, value) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement assignment identifier parenthesized_expression binary_operator binary_operator binary_operator binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement call attribute identifier identifier argument_list identifier identifier | Deletes all records where "field" is "value". |
def showConfig( self ):
item = self.uiPluginTREE.currentItem()
if not isinstance(item, PluginItem):
return
plugin = item.plugin()
widget = self.findChild(QWidget, plugin.uniqueName())
if ( not widget ):
widget = plugin.createWidget(self)
widget.setObjectName(plugin.uniqueName())
self.uiConfigSTACK.addWidget(widget)
self.uiConfigSTACK.setCurrentWidget(widget) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator call identifier argument_list identifier identifier block return_statement expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list if_statement parenthesized_expression not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Show the config widget for the currently selected plugin. |
def free_symbols(self):
return set([
sym for sym in self.term.free_symbols
if sym not in self.bound_symbols]) | module function_definition identifier parameters identifier block return_statement call identifier argument_list list_comprehension identifier for_in_clause identifier attribute attribute identifier identifier identifier if_clause comparison_operator identifier attribute identifier identifier | Set of all free symbols |
def parse_eprocess(self, eprocess_data):
Name = eprocess_data['_EPROCESS']['Cybox']['Name']
PID = eprocess_data['_EPROCESS']['Cybox']['PID']
PPID = eprocess_data['_EPROCESS']['Cybox']['Parent_PID']
return {'Name': Name, 'PID': PID, 'PPID': PPID} | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end return_statement 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 | Parse the EProcess object we get from some rekall output |
def UrnStringToHuntId(urn):
if urn.startswith(AFF4_PREFIX):
urn = urn[len(AFF4_PREFIX):]
components = urn.split("/")
if len(components) != 2 or components[0] != "hunts":
raise ValueError("Invalid hunt URN: %s" % urn)
return components[-1] | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment identifier subscript identifier slice call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator subscript identifier integer string string_start string_content string_end block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier return_statement subscript identifier unary_operator integer | Converts given URN string to a flow id string. |
def dump(esp, _efuses, args):
for block in range(len(EFUSE_BLOCK_OFFS)):
print("EFUSE block %d:" % block)
offsets = [x + EFUSE_BLOCK_OFFS[block] for x in range(EFUSE_BLOCK_LEN[block])]
print(" ".join(["%08x" % esp.read_efuse(offs) for offs in offsets])) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier list_comprehension binary_operator identifier subscript identifier identifier for_in_clause identifier call identifier argument_list subscript identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier for_in_clause identifier identifier | Dump raw efuse data registers |
def insert(python_data: LdapObject, database: Optional[Database] = None) -> LdapObject:
assert isinstance(python_data, LdapObject)
table: LdapObjectClass = type(python_data)
empty_data = table()
changes = changeset(empty_data, python_data.to_dict())
return save(changes, database) | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type generic_type identifier type_parameter type identifier none type identifier block assert_statement call identifier argument_list identifier identifier expression_statement assignment identifier type identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list return_statement call identifier argument_list identifier identifier | Insert a new python_data object in the database. |
def template(client, force):
import pkg_resources
for tpl_file in CI_TEMPLATES:
tpl_path = client.path / tpl_file
with pkg_resources.resource_stream(__name__, tpl_file) as tpl:
content = tpl.read()
if not force and tpl_path.exists():
click.confirm(
'Do you want to override "{tpl_file}"'.format(
tpl_file=tpl_file
),
abort=True,
)
with tpl_path.open('wb') as dest:
dest.write(content) | module function_definition identifier parameters identifier identifier block import_statement dotted_name identifier for_statement identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator not_operator identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier true with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | Render templated configuration files. |
def run_command(cmd, env=None, max_timeout=None):
arglist = cmd.split()
output = os.tmpfile()
try:
pipe = Popen(arglist, stdout=output, stderr=STDOUT, env=env)
except Exception as errmsg:
return 1, errmsg
if max_timeout:
start = time.time()
while pipe.poll() is None:
time.sleep(0.1)
if time.time() - start > max_timeout:
os.kill(pipe.pid, signal.SIGINT)
pipe.wait()
return 1, "Time exceeded"
pipe.wait()
output.seek(0)
return pipe.returncode, output.read() | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier except_clause as_pattern identifier as_pattern_target identifier block return_statement expression_list integer identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list while_statement comparison_operator call attribute identifier identifier argument_list none block expression_statement call attribute identifier identifier argument_list float if_statement comparison_operator binary_operator call attribute identifier identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement expression_list integer string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list integer return_statement expression_list attribute identifier identifier call attribute identifier identifier argument_list | Run command and return its return status code and its output |
def update(self, action: torch.Tensor) -> 'ChecklistStatelet':
checklist_addition = (self.terminal_actions == action).float()
new_checklist = self.checklist + checklist_addition
new_checklist_state = ChecklistStatelet(terminal_actions=self.terminal_actions,
checklist_target=self.checklist_target,
checklist_mask=self.checklist_mask,
checklist=new_checklist,
terminal_indices_dict=self.terminal_indices_dict)
return new_checklist_state | module function_definition identifier parameters identifier typed_parameter identifier type attribute identifier identifier type string string_start string_content string_end block expression_statement assignment identifier call attribute parenthesized_expression comparison_operator attribute identifier identifier identifier identifier argument_list expression_statement assignment identifier binary_operator attribute identifier identifier identifier expression_statement assignment identifier 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 identifier keyword_argument identifier attribute identifier identifier return_statement identifier | Takes an action index, updates checklist and returns an updated state. |
def getAceTypeBit(self, t):
try:
return self.validAceTypes[t]['BITS']
except KeyError:
raise CommandExecutionError((
'No ACE type "{0}". It should be one of the following: {1}'
).format(t, ', '.join(self.validAceTypes))) | module function_definition identifier parameters identifier identifier block try_statement block return_statement subscript subscript attribute identifier identifier identifier string string_start string_content string_end except_clause identifier block raise_statement call identifier argument_list call attribute parenthesized_expression string string_start string_content string_end identifier argument_list identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | returns the acetype bit of a text value |
def replace_exceptions(
old_to_new_exceptions: Dict[Type[BaseException], Type[BaseException]]
) -> Callable[..., Any]:
old_exceptions = tuple(old_to_new_exceptions.keys())
def decorator(to_wrap: Callable[..., Any]) -> Callable[..., Any]:
@functools.wraps(to_wrap)
def wrapper(
*args: Iterable[Any], **kwargs: Dict[str, Any]
) -> Callable[..., Any]:
try:
return to_wrap(*args, **kwargs)
except old_exceptions as err:
try:
raise old_to_new_exceptions[type(err)] from err
except KeyError:
raise TypeError(
"could not look up new exception to use for %r" % err
) from err
return wrapper
return decorator | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type ellipsis type identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type ellipsis type identifier type generic_type identifier type_parameter type ellipsis type identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters typed_parameter list_splat_pattern identifier type generic_type identifier type_parameter type identifier typed_parameter dictionary_splat_pattern identifier type generic_type identifier type_parameter type identifier type identifier type generic_type identifier type_parameter type ellipsis type identifier block try_statement block return_statement call identifier argument_list list_splat identifier dictionary_splat identifier except_clause as_pattern identifier as_pattern_target identifier block try_statement block raise_statement subscript identifier call identifier argument_list identifier identifier except_clause identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier identifier return_statement identifier return_statement identifier | Replaces old exceptions with new exceptions to be raised in their place. |
def reschedule(self, date, callable_name=None, content_object=None,
expires='7d', args=None, kwargs=None):
if isinstance(date, basestring):
date = parse_timedelta(date)
if isinstance(date, datetime.timedelta):
date = self.time_slot_start + date
if callable_name is None:
callable_name = self.callable_name
if content_object is None:
content_object = self.content_object
if args is None:
args = self.args or []
if kwargs is None:
kwargs = self.kwargs or {}
from django_future import schedule_job
return schedule_job(date, callable_name, content_object=content_object,
expires=expires, args=args, kwargs=kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier boolean_operator attribute identifier identifier list if_statement comparison_operator identifier none block expression_statement assignment identifier boolean_operator attribute identifier identifier dictionary import_from_statement dotted_name identifier dotted_name identifier return_statement call identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Schedule a clone of this job. |
def search_product(self, limit=100, offset=0, with_price=0, with_supported_software=0,
with_description=0):
response = self.request(E.searchProductSslCertRequest(
E.limit(limit),
E.offset(offset),
E.withPrice(int(with_price)),
E.withSupportedSoftware(int(with_supported_software)),
E.withDescription(int(with_description)),
))
return response.as_models(SSLProduct) | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Search the list of available products. |
def Flush(self):
if self.locked and self.CheckLease() == 0:
self._RaiseLockError("Flush")
self._WriteAttributes()
self._SyncAttributes()
if self.parent:
self.parent.Flush() | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier comparison_operator call attribute identifier identifier argument_list integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list | Syncs this object with the data store, maintaining object validity. |
def getClassInPackageFromName(className, pkg):
n = getAvClassNamesInPackage(pkg)
i = n.index(className)
c = getAvailableClassesInPackage(pkg)
return c[i] | 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 identifier expression_statement assignment identifier call identifier argument_list identifier return_statement subscript identifier identifier | get a class from name within a package |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.