code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def declaration_path(name):
from os.path import dirname, join, exists
import metatab.declarations
from metatab.exc import IncludeError
d = dirname(metatab.declarations.__file__)
path = join(d, name)
if not exists(path):
path = join(d, name + '.csv')
if not exists(path):
raise IncludeError("No local declaration file for name '{}' ".format(name))
return path | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier dotted_name identifier dotted_name identifier import_statement dotted_name identifier identifier import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier binary_operator identifier string string_start string_content string_end if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Return the path to an included declaration |
def _get(self, uri, params=None, headers=None):
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
response = self.session.get(uri, headers=headers, params=params)
logging.debug("STATUS=" + str(response.status_code))
if response.status_code == 200:
return response.json()
else:
logging.error(b"ERROR=" + response.content)
response.raise_for_status() | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block return_statement call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list | Simple GET request for a given path. |
def _kak_decomposition_to_operations(q0: ops.Qid,
q1: ops.Qid,
kak: linalg.KakDecomposition,
allow_partial_czs: bool,
atol: float = 1e-8
) -> List[ops.Operation]:
b0, b1 = kak.single_qubit_operations_before
pre = [_do_single_on(b0, q0, atol=atol), _do_single_on(b1, q1, atol=atol)]
a0, a1 = kak.single_qubit_operations_after
post = [_do_single_on(a0, q0, atol=atol), _do_single_on(a1, q1, atol=atol)]
return list(cast(Iterable[ops.Operation], ops.flatten_op_tree([
pre,
_non_local_part(q0,
q1,
kak.interaction_coefficients,
allow_partial_czs,
atol=atol),
post,
]))) | module function_definition identifier parameters typed_parameter identifier type attribute identifier identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type attribute identifier identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier float type generic_type identifier type_parameter type attribute identifier identifier block expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier list call identifier argument_list identifier identifier keyword_argument identifier identifier call identifier argument_list identifier identifier keyword_argument identifier identifier expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement assignment identifier list call identifier argument_list identifier identifier keyword_argument identifier identifier call identifier argument_list identifier identifier keyword_argument identifier identifier return_statement call identifier argument_list call identifier argument_list subscript identifier attribute identifier identifier call attribute identifier identifier argument_list list identifier call identifier argument_list identifier identifier attribute identifier identifier identifier keyword_argument identifier identifier identifier | Assumes that the decomposition is canonical. |
def parse_value(self, value):
value = value.strip()
if value == 'na':
return None
try:
return float(value)
except:
pass
try:
return float.fromhex(value)
except:
pass
return None | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier string string_start string_content string_end block return_statement none try_statement block return_statement call identifier argument_list identifier except_clause block pass_statement try_statement block return_statement call attribute identifier identifier argument_list identifier except_clause block pass_statement return_statement none | Convert value string to float for reporting |
def devices(self):
'return generator of configured devices'
return self.fs is not None and [JFSDevice(d, self, parentpath=self.rootpath) for d in self.fs.devices.iterchildren()] or [x for x in []] | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end return_statement boolean_operator boolean_operator comparison_operator attribute identifier identifier none list_comprehension call identifier argument_list identifier identifier keyword_argument identifier attribute identifier identifier for_in_clause identifier call attribute attribute attribute identifier identifier identifier identifier argument_list list_comprehension identifier for_in_clause identifier list | return generator of configured devices |
def vectorize_utterance_ohe(self, utterance):
for i, word in enumerate(utterance):
if not word in self.vocab_list:
utterance[i] = '<unk>'
ie_utterance = self.swap_pad_and_zero(self.ie.transform(utterance))
ohe_utterance = np.array(self.ohe.transform(ie_utterance.reshape(len(ie_utterance), 1)))
return ohe_utterance | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement not_operator comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier integer return_statement identifier | Take in a tokenized utterance and transform it into a sequence of one-hot vectors |
def next(self):
msg = cr.Message()
msg.type = cr.NEXT
self.send_message(msg) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Sends a "next" command to the player. |
def log_status (self, checked, in_progress, queue, duration, num_urls):
msg = _n("%2d thread active", "%2d threads active", in_progress) % \
in_progress
self.write(u"%s, " % msg)
msg = _n("%5d link queued", "%5d links queued", queue) % queue
self.write(u"%s, " % msg)
msg = _n("%4d link", "%4d links", checked) % checked
self.write(u"%s" % msg)
msg = _n("%3d URL", "%3d URLs", num_urls) % num_urls
self.write(u" in %s checked, " % msg)
msg = _("runtime %s") % strformat.strduration_long(duration)
self.writeln(msg)
self.flush() | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier line_continuation identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier binary_operator call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Write status message to file descriptor. |
def unpack_layer(plane):
size = point.Point.build(plane.size)
if size == (0, 0):
return None
data = np.frombuffer(plane.data, dtype=Feature.dtypes[plane.bits_per_pixel])
if plane.bits_per_pixel == 1:
data = np.unpackbits(data)
if data.shape[0] != size.x * size.y:
data = data[:size.x * size.y]
return data.reshape(size.y, size.x) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier tuple integer integer block return_statement none expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier subscript attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator subscript attribute identifier identifier integer binary_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier subscript identifier slice binary_operator attribute identifier identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Return a correctly shaped numpy array given the feature layer bytes. |
def _distributeCells(numCellsPop):
from .. import sim
hostCells = {}
for i in range(sim.nhosts):
hostCells[i] = []
for i in range(numCellsPop):
hostCells[sim.nextHost].append(i)
sim.nextHost+=1
if sim.nextHost>=sim.nhosts:
sim.nextHost=0
if sim.cfg.verbose:
print(("Distributed population of %i cells on %s hosts: %s, next: %s"%(numCellsPop,sim.nhosts,hostCells,sim.nextHost)))
return hostCells | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment subscript identifier identifier list for_statement identifier call identifier argument_list identifier block expression_statement call attribute subscript identifier attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier integer if_statement attribute attribute identifier identifier identifier block expression_statement call identifier argument_list parenthesized_expression binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier identifier attribute identifier identifier return_statement identifier | distribute cells across compute nodes using round-robin |
def invalid_content_type(self, request=None, response=None):
if callable(self.invalid_outputs.content_type):
return self.invalid_outputs.content_type(request=request, response=response)
else:
return self.invalid_outputs.content_type | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block if_statement call identifier argument_list attribute attribute identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier else_clause block return_statement attribute attribute identifier identifier identifier | Returns the content type that should be used by default on validation errors |
def unpack(self, obs):
planes = getattr(obs.feature_layer_data, self.layer_set)
plane = getattr(planes, self.name)
return self.unpack_layer(plane) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier return_statement call attribute identifier identifier argument_list identifier | Return a correctly shaped numpy array for this feature. |
def getMoonPhase(self):
sun = self.getObject(const.SUN)
moon = self.getObject(const.MOON)
dist = angle.distance(sun.lon, moon.lon)
if dist < 90:
return const.MOON_FIRST_QUARTER
elif dist < 180:
return const.MOON_SECOND_QUARTER
elif dist < 270:
return const.MOON_THIRD_QUARTER
else:
return const.MOON_LAST_QUARTER | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier integer block return_statement attribute identifier identifier elif_clause comparison_operator identifier integer block return_statement attribute identifier identifier elif_clause comparison_operator identifier integer block return_statement attribute identifier identifier else_clause block return_statement attribute identifier identifier | Returns the phase of the moon. |
def services(self):
ids = [ref['id'] for ref in self['services']]
return [Service.fetch(id) for id in ids] | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension subscript identifier string string_start string_content string_end for_in_clause identifier subscript identifier string string_start string_content string_end return_statement list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier | Fetch all instances of services for this EP. |
def train_epoch(self, epoch_info: EpochInfo, interactive=True):
epoch_info.on_epoch_begin()
if interactive:
iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch")
else:
iterator = range(epoch_info.batches_per_epoch)
for batch_idx in iterator:
batch_info = BatchInfo(epoch_info, batch_idx)
batch_info.on_batch_begin()
self.train_batch(batch_info)
batch_info.on_batch_end()
epoch_info.result_accumulator.freeze_results()
epoch_info.on_epoch_end() | module function_definition identifier parameters identifier typed_parameter identifier type identifier default_parameter identifier true block expression_statement call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Train model on an epoch of a fixed number of batch updates |
def read_follower_file(fname, min_followers=0, max_followers=1e10, blacklist=set()):
result = {}
with open(fname, 'rt') as f:
for line in f:
parts = line.split()
if len(parts) > 3:
if parts[1].lower() not in blacklist:
followers = set(int(x) for x in parts[2:])
if len(followers) > min_followers and len(followers) <= max_followers:
result[parts[1].lower()] = followers
else:
print('skipping exemplar', parts[1].lower())
return result | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier float default_parameter identifier call identifier argument_list block expression_statement assignment identifier dictionary with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block if_statement comparison_operator call attribute subscript identifier integer identifier argument_list identifier block expression_statement assignment identifier call identifier generator_expression call identifier argument_list identifier for_in_clause identifier subscript identifier slice integer if_statement boolean_operator comparison_operator call identifier argument_list identifier identifier comparison_operator call identifier argument_list identifier identifier block expression_statement assignment subscript identifier call attribute subscript identifier integer identifier argument_list identifier else_clause block expression_statement call identifier argument_list string string_start string_content string_end call attribute subscript identifier integer identifier argument_list return_statement identifier | Read a file of follower information and return a dictionary mapping screen_name to a set of follower ids. |
def request_password_reset(self, user, base_url):
user.generate_password_link()
db.session.add(user)
db.session.commit()
events.password_change_requested_event.send(user)
self.send_password_change_message(user, base_url) | module function_definition identifier parameters identifier identifier identifier block expression_statement 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 expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Regenerate password link and send message |
def link_tail(self, node):
assert not node.head
old_tail = self.tail
if old_tail:
assert old_tail.head == self
old_tail.head = node
node.tail = old_tail
node.head = self
self.tail = node | module function_definition identifier parameters identifier identifier block assert_statement not_operator attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement identifier block assert_statement comparison_operator 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 expression_statement assignment attribute identifier identifier identifier | Add a node to the tail. |
def create_tar (archive, compression, cmd, verbosity, interactive, filenames):
mode = get_tar_mode(compression)
try:
with tarfile.open(archive, mode) as tfile:
for filename in filenames:
tfile.add(filename)
except Exception as err:
msg = "error creating %s: %s" % (archive, err)
raise util.PatoolError(msg)
return None | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier identifier as_pattern_target identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier identifier raise_statement call attribute identifier identifier argument_list identifier return_statement none | Create a TAR archive with the tarfile Python module. |
def insertBPoint(self, index, type=None, anchor=None, bcpIn=None, bcpOut=None, bPoint=None):
if bPoint is not None:
if type is None:
type = bPoint.type
if anchor is None:
anchor = bPoint.anchor
if bcpIn is None:
bcpIn = bPoint.bcpIn
if bcpOut is None:
bcpOut = bPoint.bcpOut
index = normalizers.normalizeIndex(index)
type = normalizers.normalizeBPointType(type)
anchor = normalizers.normalizeCoordinateTuple(anchor)
if bcpIn is None:
bcpIn = (0, 0)
bcpIn = normalizers.normalizeCoordinateTuple(bcpIn)
if bcpOut is None:
bcpOut = (0, 0)
bcpOut = normalizers.normalizeCoordinateTuple(bcpOut)
self._insertBPoint(index=index, type=type, anchor=anchor,
bcpIn=bcpIn, bcpOut=bcpOut) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block 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 attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier tuple integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier tuple integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Insert a bPoint at index in the contour. |
def ttl(self):
now = time.time() * 1000
if self._need_update:
ttl = 0
else:
metadata_age = now - self._last_successful_refresh_ms
ttl = self.config['metadata_max_age_ms'] - metadata_age
retry_age = now - self._last_refresh_ms
next_retry = self.config['retry_backoff_ms'] - retry_age
return max(ttl, next_retry, 0) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list integer if_statement attribute identifier identifier block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier binary_operator identifier attribute identifier identifier expression_statement assignment identifier binary_operator subscript attribute identifier identifier string string_start string_content string_end identifier expression_statement assignment identifier binary_operator identifier attribute identifier identifier expression_statement assignment identifier binary_operator subscript attribute identifier identifier string string_start string_content string_end identifier return_statement call identifier argument_list identifier identifier integer | Milliseconds until metadata should be refreshed |
def metadata_lint(old, new, locations):
old = old.copy()
new = new.copy()
old.pop('$version', None)
new.pop('$version', None)
for old_group_name in old:
if old_group_name not in new:
yield LintError('', 'api group removed', api_name=old_group_name)
for group_name, new_group in new.items():
old_group = old.get(group_name, {'apis': {}})
for name, api in new_group['apis'].items():
old_api = old_group['apis'].get(name, {})
api_locations = locations[name]
for message in lint_api(name, old_api, api, api_locations):
message.api_name = name
if message.location is None:
message.location = api_locations['api']
yield message | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none expression_statement call attribute identifier identifier argument_list string string_start string_content string_end none for_statement identifier identifier block if_statement comparison_operator identifier identifier block expression_statement yield call identifier argument_list string string_start string_end string string_start string_content string_end keyword_argument identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier dictionary pair string string_start string_content string_end dictionary for_statement pattern_list identifier identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier dictionary expression_statement assignment identifier subscript identifier identifier for_statement identifier call identifier argument_list identifier identifier identifier identifier block expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement yield identifier | Run the linter over the new metadata, comparing to the old. |
def _GetBaseURLs(self):
result = config.CONFIG["Client.server_urls"]
if not result:
for control_url in config.CONFIG["Client.control_urls"]:
result.append(posixpath.dirname(control_url) + "/")
for url in result:
if not url.endswith("/"):
raise RuntimeError("Bad URL: %s URLs must end with /" % url)
return result | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator identifier block for_statement identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier string string_start string_content string_end for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list 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 identifier | Gathers a list of base URLs we will try. |
def multi_to_dict(multi):
return dict(
(key, value[0] if len(value) == 1 else value)
for key, value in multi.to_dict(False).items()
) | module function_definition identifier parameters identifier block return_statement call identifier generator_expression tuple identifier conditional_expression subscript identifier integer comparison_operator call identifier argument_list identifier integer identifier for_in_clause pattern_list identifier identifier call attribute call attribute identifier identifier argument_list false identifier argument_list | Transform a Werkzeug multidictionnary into a flat dictionnary |
def setpathcost(self, port, cost):
_runshell([brctlexe, 'setpathcost', self.name, port, str(cost)],
"Could not set path cost in port %s in %s." % (port, self.name)) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list list identifier string string_start string_content string_end attribute identifier identifier identifier call identifier argument_list identifier binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier | Set port path cost value for STP protocol. |
def primitives():
z = randomZ(orderG1())
P,Q = randomG1(),randomG1()
R = generatorG1()
g1Add = P + Q
g1ScalarMultiply = z*P
g1GeneratorMultiply = z*R
g1Hash = hashG1(hash_in)
P,Q = randomG2(),randomG2()
R = generatorG2()
g2Add = P + Q
g2ScalarMultiply = z*P
g2GeneratorMultiply = z*R
g2hash = hashG2(hash_in)
P = randomGt()
Q = randomGt()
gtMult = P * Q
gtExp = P**z
x,y = (randomG1(), randomG2())
R = pair(x,y) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list call identifier argument_list expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment pattern_list identifier identifier tuple call identifier argument_list call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier | Perform primitive operations for profiling |
def generic_visit(self, node):
assert isinstance(node, ast.expr)
res = self.assign(node)
return res, self.explanation_param(self.display(res)) | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement expression_list identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier | Handle expressions we don't have custom code for. |
def remove_header(self, header_name):
val1 = self.headers.pop(header_name, None)
val2 = self.unredirected_headers.pop(header_name, None)
return val1 or val2 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none return_statement boolean_operator identifier identifier | Remove ``header_name`` from this request. |
def keys(self):
keys = list()
for n in range(len(self)):
key = self.get_value()
if not key in ['', None]: keys.append(key)
return keys | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list for_statement identifier call identifier argument_list call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator comparison_operator identifier list string string_start string_end none block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Returns a sorted list of keys |
def add_source(self, source):
nodes = [n for n in self.nodes() if not isinstance(n, Source)]
source.connect(whom=nodes) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause not_operator call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Connect the source to all existing other nodes. |
def etd_ms_dict2xmlfile(filename, metadata_dict):
try:
f = open(filename, 'w')
f.write(generate_etd_ms_xml(metadata_dict).encode("utf-8"))
f.close()
except:
raise MetadataGeneratorException(
'Failed to create an XML file. Filename: %s' % (filename)
) | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list except_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression identifier | Create an ETD MS XML file. |
def _suffix(self):
_output_formats={'GCG':'.msf',
'GDE':'.gde',
'PHYLIP':'.phy',
'PIR':'.pir',
'NEXUS':'.nxs'}
if self.Parameters['-output'].isOn():
return _output_formats[self.Parameters['-output'].Value]
else:
return '.aln' | module function_definition identifier parameters 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 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 if_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list block return_statement subscript identifier attribute subscript attribute identifier identifier string string_start string_content string_end identifier else_clause block return_statement string string_start string_content string_end | Return appropriate suffix for alignment file |
def contains_duplicates(values: Iterable[Any]) -> bool:
for v in Counter(values).values():
if v > 1:
return True
return False | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier block for_statement identifier call attribute call identifier argument_list identifier identifier argument_list block if_statement comparison_operator identifier integer block return_statement true return_statement false | Does the iterable contain any duplicate values? |
def init(self):
self.y = {"version": int(time.time())}
recipient_email = raw_input("Enter Email ID: ")
self.import_key(emailid=recipient_email)
self.encrypt(emailid_list=[recipient_email]) | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary pair string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier list identifier | Initialize a new password db store |
def clean(bundle, before, after, keep_last):
bundles_module.clean(
bundle,
before,
after,
keep_last,
) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Clean up data downloaded with the ingest command. |
def change_identifiers(datadf, split_dict):
for rid, name in split_dict.items():
datadf.loc[datadf["runIDs"] == rid, "dataset"] = name | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier comparison_operator subscript identifier string string_start string_content string_end identifier string string_start string_content string_end identifier | Change the dataset identifiers based on the names in the dictionary. |
def subset_to_genome(in_file, out_file, data):
if not utils.file_uptodate(out_file, in_file):
contigs = set([x.name for x in ref.file_contigs(dd.get_ref_file(data))])
with utils.open_gzipsafe(in_file) as in_handle:
with file_transaction(data, out_file) as tx_out_file:
with open(tx_out_file, "w") as out_handle:
for line in in_handle:
parts = line.split()
if parts and parts[0] in contigs:
out_handle.write(line)
return out_file | module function_definition identifier parameters identifier identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier identifier as_pattern_target identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator identifier comparison_operator subscript identifier integer identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Subset a BED file to only contain contigs present in the reference genome. |
def paste_action_callback(self, *event):
if react_to_event(self.view, self.tree_view, event) and self.active_entry_widget is None:
_, dict_paths = self.get_view_selection()
selected_data_list = rafcon.gui.clipboard.global_clipboard.get_semantic_dictionary_list()
if not dict_paths and not self.model.state.semantic_data:
dict_paths = [[]]
for target_dict_path_as_list in dict_paths:
prev_value = self.model.state.semantic_data
value = self.model.state.semantic_data
for path_element in target_dict_path_as_list:
prev_value = value
value = value[path_element]
if not isinstance(value, dict) and len(dict_paths) <= 1:
target_dict_path_as_list.pop(-1)
value = prev_value
if isinstance(value, dict):
for key_to_paste, value_to_add in selected_data_list:
self.model.state.add_semantic_data(target_dict_path_as_list, value_to_add, key_to_paste)
self.reload_tree_store_data() | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement boolean_operator call identifier argument_list attribute identifier identifier attribute identifier identifier identifier comparison_operator attribute identifier identifier none block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list if_statement boolean_operator not_operator identifier not_operator attribute attribute attribute identifier identifier identifier identifier block expression_statement assignment identifier list list for_statement identifier identifier block expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier expression_statement assignment identifier attribute attribute attribute identifier identifier identifier identifier for_statement identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier subscript identifier identifier if_statement boolean_operator not_operator call identifier argument_list identifier identifier comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list unary_operator integer expression_statement assignment identifier identifier if_statement call identifier argument_list identifier identifier block for_statement pattern_list identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list | Add clipboard key value pairs into all selected sub-dictionary |
def _write_value_failed(self, dbus_error):
error = _error_from_dbus_error(dbus_error)
self.service.device.characteristic_write_value_failed(characteristic=self, error=error) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Called when the write request has failed. |
def on_release(self, window, key, scancode, action, mods):
if key == glfw.KEY_SPACE:
self.grasp = not self.grasp
elif key == glfw.KEY_Q:
self._reset_state = 1
self._enabled = False
self._reset_internal_state() | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier not_operator attribute identifier identifier elif_clause comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list | Key handler for key releases. |
def write_string(self, value, length):
format = '!' + str(length) + 's'
self.data.append(struct.pack(format, value))
self.size += length | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier binary_operator binary_operator string string_start string_content string_end call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier expression_statement augmented_assignment attribute identifier identifier identifier | Writes a string to the packet |
def dcnm_network_delete_event(self, network_info):
seg_id = network_info.get('segmentation_id')
if not seg_id:
LOG.error('Failed to delete network. Invalid network '
'info %s.', network_info)
query_net = self.get_network_by_segid(seg_id)
if not query_net:
LOG.info('dcnm_network_delete_event: network %(segid)s '
'does not exist.', {'segid': seg_id})
return
if self.fw_api.is_network_source_fw(query_net, query_net.name):
LOG.info("Service network %s, returning", query_net.name)
return
try:
del_net = self.network.pop(query_net.network_id)
self.neutronclient.delete_network(query_net.network_id)
self.delete_network_db(query_net.network_id)
except Exception as exc:
self.network[query_net.network_id] = del_net
LOG.exception('dcnm_network_delete_event: Failed to delete '
'%(network)s. Reason %(err)s.',
{'network': query_net.name, 'err': str(exc)}) | 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 expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier return_statement if_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call identifier argument_list identifier | Process network delete event from DCNM. |
def _get_public_key_count(self):
index = len(self._public_keys)
for authentication in self._authentications:
if authentication.is_public_key():
index += 1
return index | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier integer return_statement identifier | Return the count of public keys in the list and embedded. |
def _get_timezone(self, root):
tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text
hours = int(self._tz_re.search(tz_str).group(1))
return tzoffset(tz_str, hours * 60) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute subscript call attribute identifier identifier argument_list string string_start string_content string_end integer identifier expression_statement assignment identifier call identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list integer return_statement call identifier argument_list identifier binary_operator identifier integer | Find timezone informatation on bottom of the page. |
def add_chromedriver_to_path():
chromedriver_dir = os.path.abspath(os.path.dirname(__file__))
if 'PATH' not in os.environ:
os.environ['PATH'] = chromedriver_dir
elif chromedriver_dir not in os.environ['PATH']:
os.environ['PATH'] += utils.get_variable_separator()+chromedriver_dir | module function_definition identifier parameters block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier elif_clause comparison_operator identifier subscript attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment subscript attribute identifier identifier string string_start string_content string_end binary_operator call attribute identifier identifier argument_list identifier | Appends the directory of the chromedriver binary file to PATH. |
def download_series_gui(frame, urls, directory, min_file_size, max_file_size, no_redirects):
if not os.path.exists(directory):
os.makedirs(directory)
app = progress_class(frame, urls, directory, min_file_size, max_file_size, no_redirects) | module function_definition identifier parameters identifier identifier identifier identifier 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 assignment identifier call identifier argument_list identifier identifier identifier identifier identifier identifier | called when user wants serial downloading |
def Verify(self, message, signature):
siglen = len(signature)
if siglen == 20:
hash_algorithm = hashes.SHA1()
elif siglen == 32:
hash_algorithm = hashes.SHA256()
else:
raise VerificationError("Invalid signature length %d." % siglen)
h = hmac.HMAC(self.key, hash_algorithm, backend=openssl.backend)
h.update(message)
try:
h.verify(signature)
return True
except exceptions.InvalidSignature as e:
raise VerificationError(e) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list elif_clause comparison_operator identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list else_clause block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement call attribute identifier identifier argument_list identifier return_statement true except_clause as_pattern attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list identifier | Verifies the signature for a given message. |
def estimate(self, maxiter=250, convergence=1e-7):
self.loglik = np.zeros(maxiter)
iter = 0
while iter < maxiter:
self.loglik[iter] = self.E_step()
if np.isnan(self.loglik[iter]):
print("undefined log-likelihood")
break
self.M_step()
if self.loglik[iter] - self.loglik[iter - 1] < 0 and iter > 0:
print("log-likelihood decreased by %f at iteration %d"
% (self.loglik[iter] - self.loglik[iter - 1],
iter))
elif self.loglik[iter] - self.loglik[iter - 1] < convergence \
and iter > 0:
print("convergence at iteration %d, loglik = %f" %
(iter, self.loglik[iter]))
self.loglik = self.loglik[self.loglik < 0]
break
iter += 1 | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier float block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier integer while_statement comparison_operator identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list if_statement call attribute identifier identifier argument_list subscript attribute identifier identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end break_statement expression_statement call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator binary_operator subscript attribute identifier identifier identifier subscript attribute identifier identifier binary_operator identifier integer integer comparison_operator identifier integer block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple binary_operator subscript attribute identifier identifier identifier subscript attribute identifier identifier binary_operator identifier integer identifier elif_clause boolean_operator comparison_operator binary_operator subscript attribute identifier identifier identifier subscript attribute identifier identifier binary_operator identifier integer identifier line_continuation comparison_operator identifier integer block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier subscript attribute identifier identifier identifier expression_statement assignment attribute identifier identifier subscript attribute identifier identifier comparison_operator attribute identifier identifier integer break_statement expression_statement augmented_assignment identifier integer | run EM algorithm until convergence, or until maxiter reached |
def _load_bond_length_data():
with open(os.path.join(os.path.dirname(__file__),
"bond_lengths.json")) as f:
data = collections.defaultdict(dict)
for row in json.load(f):
els = sorted(row['elements'])
data[tuple(els)][row['bond_order']] = row['length']
return data | module function_definition identifier parameters block with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript subscript identifier call identifier argument_list identifier subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement identifier | Loads bond length data from json file |
def _quadPoints(size, disp1, disp2):
w, h = size
x1, y1 = disp1
x2, y2 = disp2
return (
x1, -y1,
-x1, h + y2,
w + x2, h - y2,
w - x2, y1
) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier return_statement tuple identifier unary_operator identifier unary_operator identifier binary_operator identifier identifier binary_operator identifier identifier binary_operator identifier identifier binary_operator identifier identifier identifier | Return points for QUAD transformation. |
def config_required(f):
def new_func(obj, *args, **kwargs):
if 'config' not in obj:
click.echo(_style(obj.get('show_color', False),
'Could not find a valid configuration file!',
fg='red', bold=True))
raise click.Abort()
else:
return f(obj, *args, **kwargs)
return update_wrapper(new_func, f) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end false string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier true raise_statement call attribute identifier identifier argument_list else_clause block return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement call identifier argument_list identifier identifier | Decorator that checks whether a configuration file was set. |
def stream_request(self, request, out_future):
request.close_argstreams()
def on_done(future):
if future.exception() and out_future.running():
out_future.set_exc_info(future.exc_info())
request.close_argstreams(force=True)
stream_future = self._stream(request, self.request_message_factory)
stream_future.add_done_callback(on_done)
return stream_future | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list function_definition identifier parameters identifier block if_statement boolean_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier true expression_statement assignment identifier call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | send the given request and response is not required |
def cast(
source: Union[DataType, str], target: Union[DataType, str], **kwargs
) -> DataType:
source, result_target = dtype(source), dtype(target)
if not castable(source, result_target, **kwargs):
raise com.IbisTypeError(
'Datatype {} cannot be implicitly '
'casted to {}'.format(source, result_target)
)
return result_target | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type identifier dictionary_splat_pattern identifier type identifier block expression_statement assignment pattern_list identifier identifier expression_list call identifier argument_list identifier call identifier argument_list identifier if_statement not_operator call identifier argument_list identifier identifier dictionary_splat identifier block raise_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier identifier return_statement identifier | Attempts to implicitly cast from source dtype to target dtype |
def pkg_list(self):
options = [
"-l",
"--list"
]
flag = ["--index", "--installed", "--name"]
name = INDEX = installed = False
for arg in self.args[2:]:
if flag[0] == arg:
INDEX = True
if flag[1] in arg:
installed = True
if flag[2] == arg:
name = True
if arg not in flag:
usage("")
raise SystemExit()
if (len(self.args) > 1 and len(self.args) <= 5 and
self.args[0] in options):
if self.args[1] in self.meta.repositories:
PackageManager(binary=None).package_list(self.args[1],
name,
INDEX,
installed)
else:
usage(self.args[1])
else:
usage("") | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list 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 assignment identifier assignment identifier false for_statement identifier subscript attribute identifier identifier slice integer block if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier true if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier true if_statement comparison_operator subscript identifier integer identifier block expression_statement assignment identifier true if_statement comparison_operator identifier identifier block expression_statement call identifier argument_list string string_start string_end raise_statement call identifier argument_list if_statement parenthesized_expression boolean_operator boolean_operator comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator call identifier argument_list attribute identifier identifier integer comparison_operator subscript attribute identifier identifier integer identifier block if_statement comparison_operator subscript attribute identifier identifier integer attribute attribute identifier identifier identifier block expression_statement call attribute call identifier argument_list keyword_argument identifier none identifier argument_list subscript attribute identifier identifier integer identifier identifier identifier else_clause block expression_statement call identifier argument_list subscript attribute identifier identifier integer else_clause block expression_statement call identifier argument_list string string_start string_end | List of packages by repository |
def clear_all():
frame = inspect.currentframe().f_back
try:
if frame.f_globals.get('variables_order'):
del frame.f_globals['variables_order']
if frame.f_globals.get('parameters_order'):
del frame.f_globals['parameters_order']
finally:
del frame | module function_definition identifier parameters block expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier try_statement block if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block delete_statement subscript attribute identifier identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block delete_statement subscript attribute identifier identifier string string_start string_content string_end finally_clause block delete_statement identifier | Clears all parameters, variables, and shocks defined previously |
def unscale_dict(C):
C_out = {k: _scale_dict[k] * v for k, v in C.items()}
for k in C_symm_keys[8]:
C_out['qqql'] = unscale_8(C_out['qqql'])
return C_out | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary_comprehension pair identifier binary_operator subscript identifier identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list for_statement identifier subscript identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier | Undo the scaling applied in `scale_dict`. |
def normalize_path(path, resolve_symlinks=True):
path = expanduser(path)
if resolve_symlinks:
path = os.path.realpath(path)
else:
path = os.path.abspath(path)
return os.path.normcase(path) | module function_definition identifier parameters identifier default_parameter identifier true block expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Convert a path to its canonical, case-normalized, absolute version. |
def post(self, object_type, object_id):
if object_id == 0:
return Response(status=404)
tagged_objects = []
for name in request.get_json(force=True):
if ':' in name:
type_name = name.split(':', 1)[0]
type_ = TagTypes[type_name]
else:
type_ = TagTypes.custom
tag = db.session.query(Tag).filter_by(name=name, type=type_).first()
if not tag:
tag = Tag(name=name, type=type_)
tagged_objects.append(
TaggedObject(
object_id=object_id,
object_type=object_type,
tag=tag,
),
)
db.session.add_all(tagged_objects)
db.session.commit()
return Response(status=201) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier integer block return_statement call identifier argument_list keyword_argument identifier integer expression_statement assignment identifier list for_statement identifier call attribute identifier identifier argument_list keyword_argument identifier true block if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end integer integer expression_statement assignment identifier subscript identifier identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute call attribute call attribute attribute identifier identifier identifier argument_list identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list keyword_argument identifier integer | Add new tags to an object. |
def ParseYAMLAuthorizationsList(yaml_data):
try:
raw_list = yaml.ParseMany(yaml_data)
except (ValueError, pyyaml.YAMLError) as e:
raise InvalidAPIAuthorization("Invalid YAML: %s" % e)
result = []
for auth_src in raw_list:
auth = APIAuthorization()
auth.router_cls = _GetRouterClass(auth_src["router"])
auth.users = auth_src.get("users", [])
auth.groups = auth_src.get("groups", [])
auth.router_params = auth_src.get("router_params", {})
result.append(auth)
return result | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern tuple identifier attribute identifier identifier as_pattern_target identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end list expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Parses YAML data into a list of APIAuthorization objects. |
def keys(self):
names = []
for i in range(self.n_blocks):
names.append(self.get_block_name(i))
return names | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier | Get all the block names in the dataset |
def satisfies_constraint(self, site):
if not site.is_ordered:
return False
if self.species_constraints \
and str(site.specie) in self.species_constraints:
satisfies_constraints = True
else:
satisfies_constraints = False
if self.site_constraint_name \
and self.site_constraint_name in site.properties:
prop = site.properties[self.site_constraint_name]
if prop in self.site_constraints:
satisfies_constraints = True
else:
satisfies_constraints = False
return satisfies_constraints | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block return_statement false if_statement boolean_operator attribute identifier identifier line_continuation comparison_operator call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier true else_clause block expression_statement assignment identifier false if_statement boolean_operator attribute identifier identifier line_continuation comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier true else_clause block expression_statement assignment identifier false return_statement identifier | Checks if a periodic site satisfies the constraint. |
def _json_reddit_objecter(self, json_data):
try:
object_class = self.config.by_kind[json_data['kind']]
except KeyError:
if 'json' in json_data:
if len(json_data) != 1:
msg = 'Unknown object type: {0}'.format(json_data)
warn_explicit(msg, UserWarning, '', 0)
return json_data['json']
else:
return object_class.from_api_response(self, json_data['data'])
return json_data | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier subscript identifier string string_start string_content string_end except_clause identifier block if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list identifier identifier string string_start string_end integer return_statement subscript identifier string string_start string_content string_end else_clause block return_statement call attribute identifier identifier argument_list identifier subscript identifier string string_start string_content string_end return_statement identifier | Return an appropriate RedditObject from json_data when possible. |
def add_client_to_manifest(self, client_id, client_secret, manifest):
assert self.is_admin, "Must authenticate() as admin to create client"
return self.uaac.add_client_to_manifest(client_id, client_secret,
manifest) | module function_definition identifier parameters identifier identifier identifier identifier block assert_statement attribute identifier identifier string string_start string_content string_end return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier | Add the client credentials to the specified manifest. |
def recv_data(self):
data, addr = self.sock.recvfrom(self.packetsize)
matrix = map(ord, data.strip())
if len(matrix) == self.packetsize:
self.matrix = matrix[:-4] | module function_definition identifier parameters identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier subscript identifier slice unary_operator integer | Grab the next frame and put it on the matrix. |
def join(path1, path2):
if path1.endswith('/') and path2.startswith('/'):
return ''.join([path1, path2[1:]])
elif path1.endswith('/') or path2.startswith('/'):
return ''.join([path1, path2])
else:
return ''.join([path1, '/', path2]) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call attribute string string_start string_end identifier argument_list list identifier subscript identifier slice integer elif_clause boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end block return_statement call attribute string string_start string_end identifier argument_list list identifier identifier else_clause block return_statement call attribute string string_start string_end identifier argument_list list identifier string string_start string_content string_end identifier | nicely join two path elements together |
def _sendDDEcommand(self, cmd, timeout=None):
reply = self.conversation.Request(cmd, timeout)
if self.pyver > 2:
reply = reply.decode('ascii').rstrip()
return reply | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list return_statement identifier | Send command to DDE client |
def add_info_from_hv(self):
if 'image' in self.hypervisor:
self.node['properties']['image'] = \
os.path.basename(self.hypervisor['image'])
if 'idlepc' in self.hypervisor:
self.node['properties']['idlepc'] = self.hypervisor['idlepc']
if 'ram' in self.hypervisor:
self.node['properties']['ram'] = self.hypervisor['ram']
if 'npe' in self.hypervisor:
self.device_info['npe'] = self.hypervisor['npe']
if 'chassis' in self.hypervisor:
self.device_info['chassis'] = self.hypervisor['chassis']
if self.device_info['model'] == 'c3600':
self.node['properties']['chassis'] = \
self.device_info['chassis'] | module function_definition identifier parameters identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end line_continuation call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end subscript attribute identifier identifier string string_start string_content string_end if_statement comparison_operator subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end line_continuation subscript attribute identifier identifier string string_start string_content string_end | Add the information we need from the old hypervisor section |
def layer(output_shape=None, new_parameters=None):
def layer_decorator(call):
def output_shape_fun(self, input_shape):
if output_shape is None:
return input_shape
kwargs = self._init_kwargs
return output_shape(input_shape, **kwargs)
def new_parameters_fun(self, input_shape, rng):
if new_parameters is None:
return ()
kwargs = self._init_kwargs
return new_parameters(input_shape, rng, **kwargs)
def call_fun(self, x, params=(), **kwargs):
call_kwargs = kwargs.copy()
call_kwargs.update(self._init_kwargs)
return call(x, params=params, **call_kwargs)
call_fun.__doc__ = call.__doc__
if output_shape is None:
output_shape_fun.__doc__ = output_shape.__doc__
if new_parameters is None:
new_parameters_fun.__doc__ = new_parameters.__doc__
cls = type(call.__name__, (Layer,),
{'call': call_fun,
'output_shape': output_shape_fun,
'new_parameters': new_parameters_fun})
return cls
return layer_decorator | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block function_definition identifier parameters identifier block function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment identifier attribute identifier identifier return_statement call identifier argument_list identifier dictionary_splat identifier function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier none block return_statement tuple expression_statement assignment identifier attribute identifier identifier return_statement call identifier argument_list identifier identifier dictionary_splat identifier function_definition identifier parameters identifier identifier default_parameter identifier tuple dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement call identifier argument_list identifier keyword_argument identifier identifier dictionary_splat identifier expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier tuple identifier 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 return_statement identifier return_statement identifier | Create a layer class from a function. |
def gpp(argv=None):
if argv is None:
argv = sys.argv[1:]
argv.insert(0, 'preview')
return main(argv) | module function_definition identifier parameters default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier subscript attribute identifier identifier slice integer expression_statement call attribute identifier identifier argument_list integer string string_start string_content string_end return_statement call identifier argument_list identifier | Shortcut function for running the previewing command. |
def format(self, obj, context, maxlevels, level):
if isinstance(obj, basestring) and "://" in fmt.to_unicode(obj):
obj = mask_keys(obj)
return pprint.PrettyPrinter.format(self, obj, context, maxlevels, level) | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier identifier identifier identifier identifier | Mask obj if it looks like an URL, then pass it to the super class. |
async def remove(self) -> None:
LOGGER.debug('Wallet.remove >>>')
try:
LOGGER.info('Removing wallet: %s', self.name)
await wallet.delete_wallet(json.dumps(self.cfg), json.dumps(self.access_creds))
except IndyError as x_indy:
LOGGER.info('Abstaining from wallet removal; indy-sdk error code %s', x_indy.error_code)
LOGGER.debug('Wallet.remove <<<') | module function_definition identifier parameters identifier type none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end try_statement block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement await call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Remove serialized wallet if it exists. |
def _has_match(self, assembled_summary):
if assembled_summary.startswith('yes'):
if self.data[0]['var_only'] == '0' or self._to_cluster_summary_has_known_nonsynonymous(assembled_summary) == 'yes':
return 'yes'
else:
return 'no'
else:
return 'no' | module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block if_statement boolean_operator comparison_operator subscript subscript attribute identifier identifier integer string string_start string_content string_end string string_start string_content string_end comparison_operator call attribute identifier identifier argument_list identifier string string_start string_content string_end block return_statement string string_start string_content string_end else_clause block return_statement string string_start string_content string_end else_clause block return_statement string string_start string_content string_end | assembled_summary should be output of _to_cluster_summary_assembled |
def _get_scripts(self, scripts_path_rel, files_deployment, script_type, project_path):
scripts_dict = {}
if scripts_path_rel:
self._logger.debug('Getting scripts with {0} definitions'.format(script_type))
scripts_dict = pgpm.lib.utils.misc.collect_scripts_from_sources(scripts_path_rel, files_deployment,
project_path, False, self._logger)
if len(scripts_dict) == 0:
self._logger.debug('No {0} definitions were found in {1} folder'.format(script_type, scripts_path_rel))
else:
self._logger.debug('No {0} folder was specified'.format(script_type))
return scripts_dict | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier dictionary if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier identifier identifier false attribute identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Gets scripts from specified folders |
def push_irq_registers(self):
self.cycles += 1
self.push_word(self.system_stack_pointer, self.program_counter.value)
self.push_word(self.system_stack_pointer, self.user_stack_pointer.value)
self.push_word(self.system_stack_pointer, self.index_y.value)
self.push_word(self.system_stack_pointer, self.index_x.value)
self.push_byte(self.system_stack_pointer, self.direct_page.value)
self.push_byte(self.system_stack_pointer, self.accu_b.value)
self.push_byte(self.system_stack_pointer, self.accu_a.value)
self.push_byte(self.system_stack_pointer, self.get_cc_value()) | module function_definition identifier parameters identifier block expression_statement augmented_assignment attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute identifier identifier argument_list | push PC, U, Y, X, DP, B, A, CC on System stack pointer |
def mul_table(self, other):
other = coerceBigInt(other)
if not other:
return NotImplemented
other %= orderG2()
if not self._table:
self._table = lwnafTable()
librelic.ep2_mul_pre_lwnaf(byref(self._table), byref(self))
result = G2Element()
librelic.ep2_mul_fix_lwnaf(byref(result), byref(self._table),
byref(other))
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator identifier block return_statement identifier expression_statement augmented_assignment identifier call identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list attribute identifier identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier call identifier argument_list attribute identifier identifier call identifier argument_list identifier return_statement identifier | Fast multiplication using a the LWNAF precomputation table. |
def load(self):
publish = self._get_publish()
self.architectures = publish['Architectures']
for source in publish['Sources']:
component = source['Component']
snapshot = source['Name']
self.publish_snapshots.append({
'Component': component,
'Name': snapshot
})
snapshot_remote = self._find_snapshot(snapshot)
for source in self._get_source_snapshots(snapshot_remote, fallback_self=True):
self.add(source, component) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list 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 for_statement identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true block expression_statement call attribute identifier identifier argument_list identifier identifier | Load publish info from remote |
def _determine_datatype(fields):
np_typestring = _TYPEMAP_NRRD2NUMPY[fields['type']]
if np.dtype(np_typestring).itemsize > 1 and fields['encoding'] not in ['ASCII', 'ascii', 'text', 'txt']:
if 'endian' not in fields:
raise NRRDError('Header is missing required field: "endian".')
elif fields['endian'] == 'big':
np_typestring = '>' + np_typestring
elif fields['endian'] == 'little':
np_typestring = '<' + np_typestring
else:
raise NRRDError('Invalid endian value in header: "%s"' % fields['endian'])
return np.dtype(np_typestring) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier subscript identifier string string_start string_content string_end if_statement boolean_operator comparison_operator attribute call attribute identifier identifier argument_list identifier identifier integer comparison_operator subscript identifier string string_start string_content string_end 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 block if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list string string_start string_content string_end elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier elif_clause comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier else_clause 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 return_statement call attribute identifier identifier argument_list identifier | Determine the numpy dtype of the data. |
def write_to_screen(self, screen, mouse_handlers, write_position,
parent_style, erase_bg, z_index):
" Fill the whole area of write_position with dots. "
default_char = Char(' ', 'class:background')
dot = Char('.', 'class:background')
ypos = write_position.ypos
xpos = write_position.xpos
for y in range(ypos, ypos + write_position.height):
row = screen.data_buffer[y]
for x in range(xpos, xpos + write_position.width):
row[x] = dot if (x + y) % 3 == 0 else default_char | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier for_statement identifier call identifier argument_list identifier binary_operator identifier attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier for_statement identifier call identifier argument_list identifier binary_operator identifier attribute identifier identifier block expression_statement assignment subscript identifier identifier conditional_expression identifier comparison_operator binary_operator parenthesized_expression binary_operator identifier identifier integer integer identifier | Fill the whole area of write_position with dots. |
def exceptions_log_path(cls, for_pid=None, in_dir=None):
if for_pid is None:
intermediate_filename_component = ''
else:
assert(isinstance(for_pid, IntegerForPid))
intermediate_filename_component = '.{}'.format(for_pid)
in_dir = in_dir or cls._log_dir
return os.path.join(
in_dir,
'logs',
'exceptions{}.log'.format(intermediate_filename_component)) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_end else_clause block assert_statement parenthesized_expression call identifier argument_list identifier identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier boolean_operator identifier attribute identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier | Get the path to either the shared or pid-specific fatal errors log file. |
def validate_ok_for_replace(replacement):
validate_is_mapping("replacement", replacement)
if replacement and not isinstance(replacement, RawBSONDocument):
first = next(iter(replacement))
if first.startswith('$'):
raise ValueError('replacement can not include $ operators') | module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block raise_statement call identifier argument_list string string_start string_content string_end | Validate a replacement document. |
def row(self, fields):
d = self.dict
row = [None] * len(fields)
for i, f in enumerate(fields):
if f in d:
row[i] = d[f]
return row | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator list none call identifier argument_list identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement identifier | Return a row for fields, for CSV files, pretty printing, etc, give a set of fields to return |
def on_open_input_tool_clicked(self):
input_path = self.input_path.text()
if not input_path:
input_path = os.path.expanduser('~')
filename, __ = QFileDialog.getOpenFileName(
self, tr('Input file'), input_path, tr('Raw grid file (*.xml)'))
if filename:
self.input_path.setText(filename) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement not_operator identifier block expression_statement assignment identifier call attribute attribute identifier 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 call identifier argument_list string string_start string_content string_end identifier call identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Autoconnect slot activated when open input tool button is clicked. |
async def _poll(self) -> None:
while True:
await asyncio.sleep(self._poll_delta)
for subproc in list(self._running_set):
subproc._poll() | module function_definition identifier parameters identifier type none block while_statement true block expression_statement await call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Coroutine to poll status of running subprocesses. |
def _get_scope_with_symbol(self, name):
scope = self
while True:
parent = scope.get_enclosing_scope()
if parent is None:
return
if name in parent.symbols:
return parent
scope = parent | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier identifier while_statement true block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier none block return_statement if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier expression_statement assignment identifier identifier | Return a scope containing passed name as a symbol name. |
def hosts_in_group(self, groupname):
result = []
for hostname, hostinfo in self.hosts.items():
if groupname == 'all':
result.append(hostname)
elif 'groups' in hostinfo:
if groupname in hostinfo['groups']:
result.append(hostname)
else:
hostinfo['groups'] = [groupname]
return result | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end list identifier return_statement identifier | Return a list of hostnames that are in a group. |
def _validate_region(self):
if not self.region:
raise GCECloudException(
'Zone is required for GCE cloud framework: '
'Example: us-west1-a'
)
try:
zone = self.compute_driver.ex_get_zone(self.region)
except Exception:
zone = None
if not zone:
raise GCECloudException(
'{region} is not a valid GCE zone. '
'Example: us-west1-a'.format(
region=self.region
)
) | module function_definition identifier parameters identifier block if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block expression_statement assignment identifier none if_statement not_operator identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier attribute identifier identifier | Validate region was passed in and is a valid GCE zone. |
def build_extensions (self):
extra = []
if self.compiler.compiler_type == 'unix':
option = "-std=gnu99"
if cc_supports_option(self.compiler.compiler, option):
extra.append(option)
self.check_extensions_list(self.extensions)
for ext in self.extensions:
for opt in extra:
if opt not in ext.extra_compile_args:
ext.extra_compile_args.append(opt)
self.build_extension(ext) | module function_definition identifier parameters identifier block expression_statement assignment identifier list if_statement comparison_operator attribute attribute identifier identifier identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end if_statement call identifier argument_list attribute attribute identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Add -std=gnu99 to build options if supported. |
def srv_data(url, token, data, kind):
ws = websocket.create_connection(url)
message = {'token': token, 'data': data, 'kind': kind}
ws.send(pd.io.json.dumps(message))
ws.close() | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier 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 expression_statement call attribute identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | Serve data to RainbowAlga |
def specs_to_string(specs):
if specs:
if isinstance(specs, six.string_types):
return specs
try:
extras = ",".join(["".join(spec) for spec in specs])
except TypeError:
extras = ",".join(["".join(spec._spec) for spec in specs])
return extras
return "" | module function_definition identifier parameters identifier block if_statement identifier block if_statement call identifier argument_list identifier attribute identifier identifier block return_statement identifier try_statement block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute string string_start string_end identifier argument_list identifier for_in_clause identifier identifier except_clause identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension call attribute string string_start string_end identifier argument_list attribute identifier identifier for_in_clause identifier identifier return_statement identifier return_statement string string_start string_end | Turn a list of specifier tuples into a string |
def WinMSGLoop():
LPMSG = POINTER(MSG)
LRESULT = c_ulong
GetMessage = get_winfunc("user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT))
TranslateMessage = get_winfunc("user32", "TranslateMessage", BOOL, (LPMSG,))
DispatchMessage = get_winfunc("user32", "DispatchMessageW", LRESULT, (LPMSG,))
msg = MSG()
lpmsg = byref(msg)
while GetMessage(lpmsg, HWND(), 0, 0) > 0:
TranslateMessage(lpmsg)
DispatchMessage(lpmsg) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier tuple identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier tuple identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end string string_start string_content string_end identifier tuple identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier while_statement comparison_operator call identifier argument_list identifier call identifier argument_list integer integer integer block expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier | Run the main windows message loop. |
def cluster_path(cls, project, instance, cluster):
return google.api_core.path_template.expand(
"projects/{project}/instances/{instance}/clusters/{cluster}",
project=project,
instance=instance,
cluster=cluster,
) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Return a fully-qualified cluster string. |
def main(argv=None):
report_paths = argv[1:]
fail_names = FLAGS.fail_names.split(',')
for report_path in report_paths:
plot_report_from_path(report_path, label=report_path, fail_names=fail_names)
pyplot.legend()
pyplot.xlim(-.01, 1.)
pyplot.ylim(0., 1.)
pyplot.show() | module function_definition identifier parameters default_parameter identifier none block expression_statement assignment identifier subscript identifier slice integer expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end for_statement identifier identifier block expression_statement call identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list unary_operator float float expression_statement call attribute identifier identifier argument_list float float expression_statement call attribute identifier identifier argument_list | Takes the path to a directory with reports and renders success fail plots. |
def _kill_process(self, pid, sig=signal.SIGKILL):
try:
os.kill(pid, sig)
except OSError as e:
if e.errno == errno.ESRCH:
logging.debug("Failure %s while killing process %s with signal %s: %s",
e.errno, pid, sig, e.strerror)
else:
logging.warning("Failure %s while killing process %s with signal %s: %s",
e.errno, pid, sig, e.strerror) | module function_definition identifier parameters identifier identifier default_parameter identifier attribute identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier identifier attribute identifier identifier | Try to send signal to given process. |
def after_update_oai_set(mapper, connection, target):
_delete_percolator(spec=target.spec, search_pattern=target.search_pattern)
_new_percolator(spec=target.spec, search_pattern=target.search_pattern)
sleep(2)
update_affected_records.delay(
spec=target.spec, search_pattern=target.search_pattern
) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list integer expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Update records on OAISet update. |
def build(self, x, h, mask=None):
xw = tf.split(tf.matmul(x, self.w_matrix) + self.bias, 3, 1)
hu = tf.split(tf.matmul(h, self.U), 3, 1)
r = tf.sigmoid(xw[0] + hu[0])
z = tf.sigmoid(xw[1] + hu[1])
h1 = tf.tanh(xw[2] + r * hu[2])
next_h = h1 * (1 - z) + h * z
if mask is not None:
next_h = next_h * mask + h * (1 - mask)
return next_h | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier attribute identifier identifier attribute identifier identifier integer integer expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier integer integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier integer subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator subscript identifier integer binary_operator identifier subscript identifier integer expression_statement assignment identifier binary_operator binary_operator identifier parenthesized_expression binary_operator integer identifier binary_operator identifier identifier if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator binary_operator identifier identifier binary_operator identifier parenthesized_expression binary_operator integer identifier return_statement identifier | Build the GRU cell. |
def hash_coloured_escapes(text):
ansi_code = int(sha256(text.encode('utf-8')).hexdigest(), 16) % 230
prefix, suffix = colored('SPLIT', ansi_code=ansi_code).split('SPLIT')
return prefix, suffix | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator call identifier argument_list call attribute call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list integer integer expression_statement assignment pattern_list identifier identifier call attribute call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier identifier argument_list string string_start string_content string_end return_statement expression_list identifier identifier | Return the ANSI hash colour prefix and suffix for a given text |
def clearkml(self):
for layer in self.curlayers:
self.mpstate.map.remove_object(layer)
for layer in self.curtextlayers:
self.mpstate.map.remove_object(layer)
self.allayers = []
self.curlayers = []
self.alltextlayers = []
self.curtextlayers = []
self.menu_needs_refreshing = True | module function_definition identifier parameters identifier block for_statement identifier attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier list expression_statement assignment attribute identifier identifier true | Clear the kmls from the map |
def _request_access_token(self):
payload = {'grant_type': 'authorization_code',
'code': code,
'redirect_uri': self.redirect_uri}
headers = _make_authorization_headers(self.client_id,
self.client_secret)
response = requests.post(self.OAUTH_TOKEN_URL, data=payload,
headers=headers,
verify=LOGIN_VERIFY_SSL_CERT)
if response.status_code is not 200:
raise MercedesMeAuthError(response.reason)
token_info = response.json()
return token_info | module function_definition identifier parameters 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 identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Gets client credentials access token |
def as_view(cls, **initkwargs):
view = super(AtomicMixin, cls).as_view(**initkwargs)
return cls.create_atomic_wrapper(view) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list dictionary_splat identifier return_statement call attribute identifier identifier argument_list identifier | Overrides as_view to add atomic transaction. |
def truncate_repeated_single_step_traversals_in_sub_queries(compound_match_query):
lowered_match_queries = []
for match_query in compound_match_query.match_queries:
new_match_query = truncate_repeated_single_step_traversals(match_query)
lowered_match_queries.append(new_match_query)
return compound_match_query._replace(match_queries=lowered_match_queries) | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | For each sub-query, remove one-step traversals that overlap a previous traversal location. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.