code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def _listen_comments(self):
comments_queue = Queue(maxsize=self._n_jobs * 4)
threads = []
try:
for i in range(self._n_jobs):
t = BotQueueWorker(name='CommentThread-t-{}'.format(i),
jobs=comments_queue,
target=self._process_comment)
t.start()
threads.append(t)
for comment in self._reddit.subreddit('+'.join(self._subs)).stream.comments():
if self._stop:
self._do_stop(comments_queue, threads)
break
comments_queue.put(comment)
self.log.debug('Listen comments stopped')
except Exception as e:
self._do_stop(comments_queue, threads)
self.log.error('Exception while listening to comments:')
self.log.error(str(e))
self.log.error('Waiting for 10 minutes and trying again.')
time.sleep(10 * 60)
self._listen_comments() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier binary_operator attribute identifier identifier integer expression_statement assignment identifier list try_statement block for_statement identifier call identifier argument_list attribute identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier for_statement identifier call attribute attribute call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier identifier identifier argument_list block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier break_statement expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list binary_operator integer integer expression_statement call attribute identifier identifier argument_list | Start listening to comments, using a separate thread. |
def mtf_bitransformer_base():
hparams = mtf_transformer2_base()
hparams.max_length = 256
hparams.shared_embedding = True
hparams.add_hparam("encoder_layers", ["self_att", "drd"] * 6)
hparams.add_hparam("decoder_layers", ["self_att", "enc_att", "drd"] * 6)
hparams.add_hparam("encoder_num_layers", 6)
hparams.add_hparam("decoder_num_layers", 6)
hparams.add_hparam("encoder_num_heads", 8)
hparams.add_hparam("decoder_num_heads", 8)
hparams.add_hparam("local_attention_radius", 128)
hparams.add_hparam("encoder_num_memory_heads", 0)
hparams.add_hparam("decoder_num_memory_heads", 0)
hparams.add_hparam("encoder_shared_kv", False)
hparams.add_hparam("decoder_shared_kv", False)
hparams.add_hparam("decode_length_multiplier", 1.5)
hparams.add_hparam("decode_length_constant", 10.0)
hparams.add_hparam("alpha", 0.6)
hparams.sampling_temp = 0.0
return hparams | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator list string string_start string_content string_end string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end binary_operator list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end float expression_statement call attribute identifier identifier argument_list string string_start string_content string_end float expression_statement call attribute identifier identifier argument_list string string_start string_content string_end float expression_statement assignment attribute identifier identifier float return_statement identifier | Machine translation base configuration. |
def retrieve_by_id(self, id_):
items_with_id = [item for item in self if item.id == int(id_)]
if len(items_with_id) == 1:
return items_with_id[0].retrieve() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list_comprehension identifier for_in_clause identifier identifier if_clause comparison_operator attribute identifier identifier call identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block return_statement call attribute subscript identifier integer identifier argument_list | Return a JSSObject for the element with ID id_ |
def _bld_pnab_generic(self, funcname, **kwargs):
margs = {'mtype': pnab, 'kwargs': kwargs}
setattr(self, funcname, margs) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier expression_statement call identifier argument_list identifier identifier identifier | implement's a generic version of a non-attribute based pandas function |
def _get_rate(self, value):
if value == 0:
return 0
else:
return MINIMAL_RATE_HZ * math.exp(value * self._get_factor()) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier integer block return_statement integer else_clause block return_statement binary_operator identifier call attribute identifier identifier argument_list binary_operator identifier call attribute identifier identifier argument_list | Return the rate in Hz from the short int value |
def check_xlim_change(self):
if self.xlim_pipe is None:
return None
xlim = None
while self.xlim_pipe[0].poll():
try:
xlim = self.xlim_pipe[0].recv()
except EOFError:
return None
if xlim != self.xlim:
return xlim
return None | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block return_statement none expression_statement assignment identifier none while_statement call attribute subscript attribute identifier identifier integer identifier argument_list block try_statement block expression_statement assignment identifier call attribute subscript attribute identifier identifier integer identifier argument_list except_clause identifier block return_statement none if_statement comparison_operator identifier attribute identifier identifier block return_statement identifier return_statement none | check for new X bounds |
def partial_update(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
if getattr(instance, '_prefetched_objects_cache', None):
instance = self.get_object()
serializer = self.get_serializer(instance)
return response.Response(serializer.data) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier true keyword_argument identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier true expression_statement call attribute identifier identifier argument_list if_statement call identifier argument_list identifier string string_start string_content string_end none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier | We do not include the mixin as we want only PATCH and no PUT |
def add_filter(self, filter_key, operator, value):
filter_key = self._metadata_map.get(filter_key, filter_key)
self.filters.append({'filter': filter_key, 'operator': operator, 'value': value}) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier 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 pair string string_start string_content string_end identifier | Adds a filter given a key, operator, and value |
def convert_block_dicts_to_string(self, block_1st2nd, block_1st, block_2nd, block_3rd):
out = ""
if self.codon_positions in ['ALL', '1st-2nd']:
for gene_code, seqs in block_1st2nd.items():
out += '>{0}_1st-2nd\n----\n'.format(gene_code)
for seq in seqs:
out += seq
elif self.codon_positions == '1st':
for gene_code, seqs in block_1st.items():
out += '>{0}_1st\n----\n'.format(gene_code)
for seq in seqs:
out += seq
elif self.codon_positions == '2nd':
for gene_code, seqs in block_2nd.items():
out += '>{0}_2nd\n----\n'.format(gene_code)
for seq in seqs:
out += seq
if self.codon_positions in ['ALL', '3rd']:
for gene_code, seqs in block_3rd.items():
out += '\n>{0}_3rd\n----\n'.format(gene_code)
for seq in seqs:
out += seq
return out | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier string string_start string_end if_statement comparison_operator attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier for_statement identifier identifier block expression_statement augmented_assignment identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier for_statement identifier identifier block expression_statement augmented_assignment identifier identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier for_statement identifier identifier block expression_statement augmented_assignment identifier identifier if_statement comparison_operator attribute identifier identifier list string string_start string_content string_end string string_start string_content string_end block for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement augmented_assignment identifier call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list identifier for_statement identifier identifier block expression_statement augmented_assignment identifier identifier return_statement identifier | Takes into account whether we need to output all codon positions. |
def isHiddenName(astr):
if astr is not None and len(astr) > 2 and astr.startswith('_') and \
astr.endswith('_'):
return True
else:
return False | module function_definition identifier parameters identifier block if_statement boolean_operator boolean_operator boolean_operator comparison_operator identifier none comparison_operator call identifier argument_list identifier integer call attribute identifier identifier argument_list string string_start string_content string_end line_continuation call attribute identifier identifier argument_list string string_start string_content string_end block return_statement true else_clause block return_statement false | Return True if this string name denotes a hidden par or section |
def _rmv_pkg(self, package):
removes = []
if GetFromInstalled(package).name() and package not in self.skip:
ver = GetFromInstalled(package).version()
removes.append(package + ver)
self._removepkg(package)
return removes | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list if_statement boolean_operator call attribute call identifier argument_list identifier identifier argument_list comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Remove one signle package |
def diff_texts(a, b, filename):
a = a.splitlines()
b = b.splitlines()
return difflib.unified_diff(a, b, filename, filename,
"(original)", "(refactored)",
lineterm="") | 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 return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier string string_start string_content string_end string string_start string_content string_end keyword_argument identifier string string_start string_end | Return a unified diff of two strings. |
def _get_stack(self, orchestration_client, stack_name):
try:
stack = orchestration_client.stacks.get(stack_name)
self.log.info("Stack found, will be doing a stack update")
return stack
except HTTPNotFound:
self.log.info("No stack found, will be doing a stack create") | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Get the ID for the current deployed overcloud stack if it exists. |
def socket_worker(sock, msg_q):
_LOGGER.debug("Starting Socket Thread.")
while True:
try:
data, addr = sock.recvfrom(1024)
except OSError as err:
_LOGGER.error(err)
else:
_LOGGER.debug("received message: %s from %s", data, addr)
msg_q.put(data)
time.sleep(0.2) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end while_statement true block try_statement block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list integer except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list float | Socket Loop that fills message queue |
def inv(self):
if self.det == 0:
raise ValueError("SquareTensor is non-invertible")
return SquareTensor(np.linalg.inv(self)) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier integer block raise_statement call identifier argument_list string string_start string_content string_end return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier | shorthand for matrix inverse on SquareTensor |
def CountClientPlatformReleasesByLabel(self, day_buckets):
return self._CountClientStatisticByLabel(
day_buckets, lambda client_info: client_info.last_snapshot.Uname()) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list identifier lambda lambda_parameters identifier call attribute attribute identifier identifier identifier argument_list | Computes client-activity stats for OS-release strings in the DB. |
def shell_django(session: DjangoSession, backend: ShellBackend):
namespace = {
'session': session
}
namespace.update(backend.get_namespace())
embed(user_ns=namespace, header=backend.header) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | This command includes Django DB Session |
def OnImport(self, event):
wildcards = get_filetypes2wildcards(["csv", "txt"]).values()
wildcard = "|".join(wildcards)
message = _("Choose file to import.")
style = wx.OPEN
filepath, filterindex = \
self.interfaces.get_filepath_findex_from_user(wildcard, message,
style)
if filepath is None:
return
import_data = self.main_window.actions.import_file(filepath,
filterindex)
if import_data is None:
return
grid = self.main_window.grid
tl_cell = grid.GetGridCursorRow(), grid.GetGridCursorCol()
grid.actions.paste(tl_cell, import_data)
self.main_window.grid.ForceRefresh() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list list string string_start string_content string_end string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement assignment pattern_list identifier identifier line_continuation call attribute attribute identifier identifier identifier argument_list identifier identifier identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier identifier if_statement comparison_operator identifier none block return_statement expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier expression_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list | File import event handler |
def fixed_step_return(reward, value, length, discount, window):
timestep = tf.range(reward.shape[1].value)
mask = tf.cast(timestep[None, :] < length[:, None], tf.float32)
return_ = tf.zeros_like(reward)
for _ in range(window):
return_ += reward
reward = discount * tf.concat(
[reward[:, 1:], tf.zeros_like(reward[:, -1:])], 1)
return_ += discount ** window * tf.concat(
[value[:, window:], tf.zeros_like(value[:, -window:])], 1)
return tf.check_numerics(tf.stop_gradient(mask * return_), 'return') | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute subscript attribute identifier identifier integer identifier expression_statement assignment identifier call attribute identifier identifier argument_list comparison_operator subscript identifier none slice subscript identifier slice none attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement augmented_assignment identifier identifier expression_statement assignment identifier binary_operator identifier call attribute identifier identifier argument_list list subscript identifier slice slice integer call attribute identifier identifier argument_list subscript identifier slice slice unary_operator integer integer expression_statement augmented_assignment identifier binary_operator binary_operator identifier identifier call attribute identifier identifier argument_list list subscript identifier slice slice identifier call attribute identifier identifier argument_list subscript identifier slice slice unary_operator identifier integer return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list binary_operator identifier identifier string string_start string_content string_end | N-step discounted return. |
def delete_dcnm_in_nwk(self, tenant_id, fw_dict, is_fw_virt=False):
tenant_name = fw_dict.get('tenant_name')
ret = self._delete_service_nwk(tenant_id, tenant_name, 'in')
if ret:
res = fw_const.DCNM_IN_NETWORK_DEL_SUCCESS
LOG.info("In Service network deleted for tenant %s",
tenant_id)
else:
res = fw_const.DCNM_IN_NETWORK_DEL_FAIL
LOG.info("In Service network deleted failed for tenant %s",
tenant_id)
self.update_fw_db_result(tenant_id, dcnm_status=res)
return ret | module function_definition identifier parameters identifier identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier string string_start string_content string_end if_statement identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier else_clause block expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier return_statement identifier | Delete the DCNM In Network and store the result in DB. |
def _edge_both_nodes(nodes: List[Node]):
node_ids = [node.id for node in nodes]
return and_(
Edge.source_id.in_(node_ids),
Edge.target_id.in_(node_ids),
) | module function_definition identifier parameters typed_parameter identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier list_comprehension attribute identifier identifier for_in_clause identifier identifier return_statement call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list identifier | Get edges where both the source and target are in the list of nodes. |
def _exec(self, query, **kwargs):
variables = {'entity': self.username,
'project': self.project, 'name': self.name}
variables.update(kwargs)
return self.client.execute(query, variable_values=variables) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier | Execute a query against the cloud backend |
def load_vi_open_in_editor_bindings():
registry = Registry()
navigation_mode = ViNavigationMode()
registry.add_binding('v', filter=navigation_mode)(
get_by_name('edit-and-execute-command'))
return registry | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement call call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier argument_list call identifier argument_list string string_start string_content string_end return_statement identifier | Pressing 'v' in navigation mode will open the buffer in an external editor. |
def _from_dict(cls, _dict):
args = {}
if 'source_url' in _dict:
args['source_url'] = _dict.get('source_url')
if 'resolved_url' in _dict:
args['resolved_url'] = _dict.get('resolved_url')
if 'image' in _dict:
args['image'] = _dict.get('image')
if 'error' in _dict:
args['error'] = ErrorInfo._from_dict(_dict.get('error'))
if 'classifiers' in _dict:
args['classifiers'] = [
ClassifierResult._from_dict(x)
for x in (_dict.get('classifiers'))
]
else:
raise ValueError(
'Required property \'classifiers\' not present in ClassifiedImage JSON'
)
return cls(**args) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier parenthesized_expression call attribute identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end return_statement call identifier argument_list dictionary_splat identifier | Initialize a ClassifiedImage object from a json dictionary. |
def calc_nfalse(d):
dtfactor = n.sum([1./i for i in d['dtarr']])
ntrials = d['readints'] * dtfactor * len(d['dmarr']) * d['npixx'] * d['npixy']
qfrac = 1 - (erf(d['sigma_image1']/n.sqrt(2)) + 1)/2.
nfalse = int(qfrac*ntrials)
return nfalse | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list_comprehension binary_operator float identifier for_in_clause identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator binary_operator binary_operator binary_operator subscript identifier string string_start string_content string_end identifier call identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator integer binary_operator parenthesized_expression binary_operator call identifier argument_list binary_operator subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list integer integer float expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier return_statement identifier | Calculate the number of thermal-noise false positives per segment. |
def _convert_size(self, size_str):
suffix = size_str[-1]
if suffix == 'K':
multiplier = 1.0 / (1024.0 * 1024.0)
elif suffix == 'M':
multiplier = 1.0 / 1024.0
elif suffix == 'T':
multiplier = 1024.0
else:
multiplier = 1
try:
val = float(size_str.split(' ')[0])
return val * multiplier
except ValueError:
return 0.0 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier unary_operator integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator float parenthesized_expression binary_operator float float elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator float float elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier float else_clause block expression_statement assignment identifier integer try_statement block expression_statement assignment identifier call identifier argument_list subscript call attribute identifier identifier argument_list string string_start string_content string_end integer return_statement binary_operator identifier identifier except_clause identifier block return_statement float | Convert units to GB |
def delete(stack, region, profile):
ini_data = {}
environment = {}
environment['stack_name'] = stack
if region:
environment['region'] = region
else:
environment['region'] = find_myself()
if profile:
environment['profile'] = profile
ini_data['environment'] = environment
if start_smash(ini_data):
sys.exit(0)
else:
sys.exit(1) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list integer else_clause block expression_statement call attribute identifier identifier argument_list integer | Delete the given CloudFormation stack. |
def diff_bearing(b1, b2):
d = abs(b2 - b1)
d = 360 - d if d > 180 else d
return d | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator identifier identifier expression_statement assignment identifier conditional_expression binary_operator integer identifier comparison_operator identifier integer identifier return_statement identifier | Compute difference between two bearings |
def requires_password_auth(fn):
def wrapper(self, *args, **kwargs):
self.auth_context = HAPI.auth_context_password
return fn(self, *args, **kwargs)
return wrapper | module function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement call identifier argument_list identifier list_splat identifier dictionary_splat identifier return_statement identifier | Decorator for HAPI methods that requires the instance to be authenticated with a password |
def copy(self):
content = [(k, v) for k, v in self.items()]
intidx = [(k, v) for k, v in content if isinstance(k, int)]
args = [v for k, v in sorted(intidx)]
kwargs = {k: v
for k, v in content
if not isinstance(k, int) and not self.is_special(k)}
return self.__class__(*args, **kwargs) | module function_definition identifier parameters identifier block expression_statement assignment identifier list_comprehension tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement assignment identifier list_comprehension tuple identifier identifier for_in_clause pattern_list identifier identifier identifier if_clause call identifier argument_list identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier identifier if_clause boolean_operator not_operator call identifier argument_list identifier identifier not_operator call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier | Return a copy of this `Fact`. |
def sum(self, axis=None, keepdims=False):
return self.numpy().sum(axis=axis, keepdims=keepdims) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier false block return_statement call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Return sum along specified axis |
def _add_cookies(self, request: Request):
self._cookie_jar.add_cookie_header(
request, self._get_cookie_referrer_host()
) | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier call attribute identifier identifier argument_list | Add the cookie headers to the Request. |
def distinct(iterable, keyfunc=None):
seen = set()
for item in iterable:
key = item if keyfunc is None else keyfunc(item)
if key not in seen:
seen.add(key)
yield item | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier none call identifier argument_list identifier if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement yield identifier | Yields distinct items from `iterable` in the order that they appear. |
def _mpv_coax_proptype(value, proptype=str):
if type(value) is bytes:
return value;
elif type(value) is bool:
return b'yes' if value else b'no'
elif proptype in (str, int, float):
return str(proptype(value)).encode('utf-8')
else:
raise TypeError('Cannot coax value of type {} into property type {}'.format(type(value), proptype)) | module function_definition identifier parameters identifier default_parameter identifier identifier block if_statement comparison_operator call identifier argument_list identifier identifier block return_statement identifier elif_clause comparison_operator call identifier argument_list identifier identifier block return_statement conditional_expression string string_start string_content string_end identifier string string_start string_content string_end elif_clause comparison_operator identifier tuple identifier identifier identifier block return_statement call attribute call identifier argument_list call identifier argument_list identifier identifier argument_list string string_start string_content string_end else_clause block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier | Intelligently coax the given python value into something that can be understood as a proptype property. |
def cli(env, identifier, enable, permission, from_user):
mgr = SoftLayer.UserManager(env.client)
user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
result = False
if from_user:
from_user_id = helpers.resolve_id(mgr.resolve_ids, from_user, 'username')
result = mgr.permissions_from_user(user_id, from_user_id)
elif enable:
result = mgr.add_permissions(user_id, permission)
else:
result = mgr.remove_permissions(user_id, permission)
if result:
click.secho("Permissions updated successfully: %s" % ", ".join(permission), fg='green')
else:
click.secho("Failed to update permissions: %s" % ", ".join(permission), fg='red') | module function_definition identifier parameters identifier identifier identifier identifier 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 identifier string string_start string_content string_end expression_statement assignment identifier false if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier elif_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end | Enable or Disable specific permissions. |
def data(self):
import warnings
warnings.warn(
'`data` attribute is deprecated and will be removed in a future release, '
'use %s as an iterable instead' % (PaginatedResponse,),
category=DeprecationWarning,
stacklevel=2
)
return list(self) | module function_definition identifier parameters identifier block import_statement dotted_name identifier expression_statement call attribute identifier identifier argument_list binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end tuple identifier keyword_argument identifier identifier keyword_argument identifier integer return_statement call identifier argument_list identifier | Deprecated. Returns the data as a `list` |
async def postback_send(msg: BaseMessage, platform: Platform) -> Response:
await platform.inject_message(msg)
return json_response({
'status': 'ok',
}) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block expression_statement await call attribute identifier identifier argument_list identifier return_statement call identifier argument_list dictionary pair string string_start string_content string_end string string_start string_content string_end | Injects the POST body into the FSM as a Postback message. |
def warn(msg, *args):
if not args:
sys.stderr.write('WARNING: ' + msg)
else:
sys.stderr.write('WARNING: ' + msg % args) | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement not_operator identifier block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end binary_operator identifier identifier | Print a warning on stderr |
def google(self, qs):
csvf = writer(sys.stdout)
csvf.writerow(['Name', 'Email'])
for ent in qs:
csvf.writerow([full_name(**ent), ent['email']]) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list list call identifier argument_list dictionary_splat identifier subscript identifier string string_start string_content string_end | CSV format suitable for importing into google GMail |
def input_fn(data_file, num_epochs, shuffle, batch_size):
assert tf.gfile.Exists(data_file), (
'%s not found. Please make sure you have run census_dataset.py and '
'set the --data_dir argument to the correct path.' % data_file)
def parse_csv(value):
tf.logging.info('Parsing {}'.format(data_file))
columns = tf.decode_csv(value, record_defaults=_CSV_COLUMN_DEFAULTS)
features = dict(zip(_CSV_COLUMNS, columns))
labels = features.pop('income_bracket')
classes = tf.equal(labels, '>50K')
return features, classes
dataset = tf.data.TextLineDataset(data_file)
if shuffle:
dataset = dataset.shuffle(buffer_size=_NUM_EXAMPLES['train'])
dataset = dataset.map(parse_csv, num_parallel_calls=5)
dataset = dataset.repeat(num_epochs)
dataset = dataset.batch(batch_size)
return dataset | module function_definition identifier parameters identifier identifier identifier identifier block assert_statement call attribute attribute identifier identifier identifier argument_list identifier parenthesized_expression binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end identifier function_definition identifier parameters 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 identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end return_statement expression_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Generate an input function for the Estimator. |
def fullpath(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
self._replace_none(kwargs_copy)
return NameFactory.fullpath_format.format(**kwargs_copy) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list dictionary_splat identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier | Return a full path name for a given file |
def lattice(self, lattice):
self._lattice = lattice
self._coords = self._lattice.get_cartesian_coords(self._frac_coords) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Sets Lattice associated with PeriodicSite |
def stop_class(self, class_):
"Stop all services of a given class"
matches = filter(lambda svc: isinstance(svc, class_), self)
map(self.stop, matches) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier identifier identifier expression_statement call identifier argument_list attribute identifier identifier identifier | Stop all services of a given class |
def _IsMap(message, field):
value = message.get_assigned_value(field.name)
if not isinstance(value, messages.Message):
return False
try:
additional_properties = value.field_by_name('additionalProperties')
except KeyError:
return False
else:
return additional_properties.repeated | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement not_operator call identifier argument_list identifier attribute identifier identifier block return_statement false try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block return_statement false else_clause block return_statement attribute identifier identifier | Returns whether the "field" is actually a map-type. |
def rotate(args, credentials):
current_access_key_id = credentials.get(
args.identity_profile, 'aws_access_key_id')
session, session3, err = make_session(args.target_profile)
if err:
return err
iam = session3.resource('iam')
current_access_key = next((key for key
in iam.CurrentUser().access_keys.all()
if key.access_key_id == current_access_key_id))
current_access_key.delete()
iam_service = session3.client('iam')
new_access_key_pair = iam_service.create_access_key()["AccessKey"]
print("Rotating from %s to %s." % (current_access_key.access_key_id,
new_access_key_pair['AccessKeyId']),
file=sys.stderr)
update_credentials_file(args.aws_credentials,
args.identity_profile,
args.identity_profile,
credentials,
new_access_key_pair)
print("%s profile updated." % args.identity_profile, file=sys.stderr)
return OK | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list attribute identifier identifier if_statement identifier block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list generator_expression identifier for_in_clause identifier call attribute attribute call attribute identifier identifier argument_list identifier identifier argument_list if_clause comparison_operator attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier subscript call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier subscript identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier expression_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier keyword_argument identifier attribute identifier identifier return_statement identifier | rotate the identity profile's AWS access key pair. |
def add_screenshot(self, screenshot):
if screenshot in self.screenshots:
return
self.screenshots.append(screenshot) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Add a screenshot object if it does not already exist |
def handle_output(results, output_type, action):
if output_type == 'QUIET':
return
if not output_type == 'JSON':
if action == 'list':
table = generate_list_table_result(
logger, results, output_type == 'TABLE-NO-HEADER')
else:
table = generate_table_results(results, output_type == 'TABLE-NO-HEADER')
if table:
print(table)
else:
try:
json_str = json.dumps(results)
if json_str:
print(json_str)
except TypeError:
logger.debug('Output is not JSON serializable, and then cannot '
'be printed with --output=JSON parameter.') | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block return_statement if_statement not_operator comparison_operator identifier string string_start string_content string_end block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier identifier comparison_operator identifier string string_start string_content string_end else_clause block expression_statement assignment identifier call identifier argument_list identifier comparison_operator identifier string string_start string_content string_end if_statement identifier block expression_statement call identifier argument_list identifier else_clause block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement call identifier argument_list identifier except_clause 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 | Print the relevant output for given output_type |
def memoize(fn):
memo = {}
@wraps(fn)
def wrapper(*args, **kwargs):
if not memoize.disabled:
key = pickle.dumps((args, kwargs))
if key not in memo:
memo[key] = fn(*args, **kwargs)
value = memo[key]
else:
value = fn(*args, **kwargs)
return value
return wrapper | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list tuple identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment identifier subscript identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | Caches previous calls to the function. |
def _setup_tf(self, stream=False):
if self.tf_version < (0, 9, 0):
self._set_remote(stream=stream)
return
self._run_tf('init', stream=stream)
logger.info('Terraform initialized') | module function_definition identifier parameters identifier default_parameter identifier false block if_statement comparison_operator attribute identifier identifier tuple integer integer integer block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier return_statement expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | Setup terraform; either 'remote config' or 'init' depending on version. |
def on_train_begin(self, epoch:int, **kwargs:Any)->None:
"Initialize the schedulers for training."
res = {'epoch':self.start_epoch} if self.start_epoch is not None else None
self.start_epoch = ifnone(self.start_epoch, epoch)
self.scheds = [p.scheds for p in self.phases]
self.opt = self.learn.opt
for k,v in self.scheds[0].items():
v.restart()
self.opt.set_stat(k, v.start)
self.idx_s = 0
return res | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter dictionary_splat_pattern identifier type identifier type none block expression_statement string string_start string_content string_end expression_statement assignment identifier conditional_expression dictionary pair string string_start string_content string_end attribute identifier identifier comparison_operator attribute identifier identifier none none expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment attribute identifier identifier list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier for_statement pattern_list identifier identifier call attribute subscript attribute identifier identifier integer identifier argument_list block expression_statement call attribute identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment attribute identifier identifier integer return_statement identifier | Initialize the schedulers for training. |
def download_to(self, folder):
urlretrieve(self.maven_url, os.path.join(folder, self.filename)) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier | Download into a folder |
def unpack_from(self, buff, offset=0):
return self._create(super(NamedStruct, self).unpack_from(buff, offset)) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block return_statement call attribute identifier identifier argument_list call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier | Read bytes from a buffer and return as a namedtuple. |
def sendline(sock, msg, confidential=False):
log.debug('<- %r', ('<snip>' if confidential else msg))
sock.sendall(msg + b'\n') | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end parenthesized_expression conditional_expression string string_start string_content string_end identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator identifier string string_start string_content escape_sequence string_end | Send a binary message, followed by EOL. |
def previous(self):
msg = cr.Message()
msg.type = cr.PREVIOUS
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 "previous" command to the player. |
def validate_uncle(cls, block: BaseBlock, uncle: BaseBlock, uncle_parent: BaseBlock) -> None:
if uncle.block_number >= block.number:
raise ValidationError(
"Uncle number ({0}) is higher than block number ({1})".format(
uncle.block_number, block.number))
if uncle.block_number != uncle_parent.block_number + 1:
raise ValidationError(
"Uncle number ({0}) is not one above ancestor's number ({1})".format(
uncle.block_number, uncle_parent.block_number))
if uncle.timestamp < uncle_parent.timestamp:
raise ValidationError(
"Uncle timestamp ({0}) is before ancestor's timestamp ({1})".format(
uncle.timestamp, uncle_parent.timestamp))
if uncle.gas_used > uncle.gas_limit:
raise ValidationError(
"Uncle's gas usage ({0}) is above the limit ({1})".format(
uncle.gas_used, uncle.gas_limit)) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type none block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier binary_operator attribute identifier identifier integer block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier | Validate the given uncle in the context of the given block. |
def add(self, resource):
if isinstance(resource, Resource):
if isinstance(resource, Secret) and \
resource.mount != 'cubbyhole':
ensure_backend(resource,
SecretBackend,
self._mounts,
self.opt,
False)
elif isinstance(resource, Mount):
ensure_backend(resource, SecretBackend, self._mounts, self.opt)
elif isinstance(resource, Auth):
ensure_backend(resource, AuthBackend, self._auths, self.opt)
elif isinstance(resource, AuditLog):
ensure_backend(resource, LogBackend, self._logs, self.opt)
self._resources.append(resource)
else:
msg = "Unknown resource %s being " \
"added to context" % resource.__class__
raise aomi_excep.AomiError(msg) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement boolean_operator call identifier argument_list identifier identifier line_continuation comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier false elif_clause call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement call identifier argument_list identifier identifier attribute identifier identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier binary_operator concatenated_string string string_start string_content string_end string string_start string_content string_end attribute identifier identifier raise_statement call attribute identifier identifier argument_list identifier | Add a resource to the context |
def forward_char(event):
" Move forward a character. "
buff = event.current_buffer
buff.cursor_position += buff.document.get_cursor_right_position(count=event.arg) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier | Move forward a character. |
def finished(cls, jobid):
output = subprocess.check_output(
[SACCT, '-n', '-X', '-o', "end", '-j', str(jobid)]
)
end = output.strip().decode()
return end not in {'Unknown', ''} | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list list identifier 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 string string_start string_content string_end call identifier argument_list identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list return_statement comparison_operator identifier set string string_start string_content string_end string string_start string_end | Check whether a SLURM job is finished or not |
def generate(basename, xml_list):
generate_shared(basename, xml_list)
for xml in xml_list:
generate_message_definitions(basename, xml) | module function_definition identifier parameters identifier identifier block expression_statement call identifier argument_list identifier identifier for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier | generate complete MAVLink Objective-C implemenation |
def repositories(self):
if self.repo == "sbo":
self.sbo_case_insensitive()
self.find_pkg = sbo_search_pkg(self.name)
if self.find_pkg:
self.dependencies_list = Requires(self.flag).sbo(self.name)
else:
PACKAGES_TXT = Utils().read_file(
self.meta.lib_path + "{0}_repo/PACKAGES.TXT".format(self.repo))
self.names = Utils().package_name(PACKAGES_TXT)
self.bin_case_insensitive()
self.find_pkg = search_pkg(self.name, self.repo)
if self.find_pkg:
self.black = BlackList().packages(self.names, self.repo)
self.dependencies_list = Dependencies(
self.repo, self.black).binary(self.name, self.flag) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list attribute identifier identifier else_clause block expression_statement assignment identifier call attribute call identifier argument_list identifier argument_list binary_operator attribute attribute identifier identifier identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute call identifier argument_list identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call attribute call identifier argument_list identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute call identifier argument_list attribute identifier identifier attribute identifier identifier identifier argument_list attribute identifier identifier attribute identifier identifier | Get dependencies by repositories |
def veq_samples(R_dist,Prot_dist,N=1e4,alpha=0.23,l0=20,sigl=20):
ls = stats.norm(l0,sigl).rvs(N)
Prots = Prot_dist.rvs(N)
Prots *= diff_Prot_factor(ls,alpha)
return R_dist.rvs(N)*2*np.pi*RSUN/(Prots*DAY)/1e5 | module function_definition identifier parameters identifier identifier default_parameter identifier float default_parameter identifier float default_parameter identifier integer default_parameter identifier integer block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier call identifier argument_list identifier identifier return_statement binary_operator binary_operator binary_operator binary_operator binary_operator call attribute identifier identifier argument_list identifier integer attribute identifier identifier identifier parenthesized_expression binary_operator identifier identifier float | Source for diff rot |
def build(
documentPath,
outputUFOFormatVersion=3,
roundGeometry=True,
verbose=True,
logPath=None,
progressFunc=None,
processRules=True,
logger=None,
useVarlib=False,
):
import os, glob
if os.path.isdir(documentPath):
todo = glob.glob(os.path.join(documentPath, "*.designspace"))
else:
todo = [documentPath]
results = []
for path in todo:
document = DesignSpaceProcessor(ufoVersion=outputUFOFormatVersion)
document.useVarlib = useVarlib
document.roundGeometry = roundGeometry
document.read(path)
try:
r = document.generateUFO(processRules=processRules)
results.append(r)
except:
if logger:
logger.exception("ufoProcessor error")
reader = None
return results | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier true default_parameter identifier true default_parameter identifier none default_parameter identifier none default_parameter identifier true default_parameter identifier none default_parameter identifier false block import_statement dotted_name identifier dotted_name identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end else_clause block expression_statement assignment identifier list identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier except_clause block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier none return_statement identifier | Simple builder for UFO designspaces. |
def _check_email_changed(cls, username, email):
ret = cls.exec_request('user/{}'.format(username), 'get', raise_for_status=True)
return ret['email'] != email | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end keyword_argument identifier true return_statement comparison_operator subscript identifier string string_start string_content string_end identifier | Compares email to one set on SeAT |
def show_settings(self):
self.notes.config.put_values()
self.overview.config.put_values()
self.settings.config.put_values()
self.spectrum.config.put_values()
self.traces.config.put_values()
self.video.config.put_values()
self.settings.show() | module function_definition identifier parameters identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list | Open the Setting windows, after updating the values in GUI. |
def max_abs(self):
if self.__len__() == 0:
return ArgumentError('empty set has no maximum absolute value.')
return numpy.max(numpy.abs([self.max(), self.min()])) | module function_definition identifier parameters identifier block if_statement comparison_operator call attribute identifier identifier argument_list integer block return_statement call identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Returns maximum absolute value. |
def _linux_id(self):
linux_id = None
hardware = self.detector.get_cpuinfo_field("Hardware")
if hardware is None:
vendor_id = self.detector.get_cpuinfo_field("vendor_id")
if vendor_id in ("GenuineIntel", "AuthenticAMD"):
linux_id = GENERIC_X86
compatible = self.detector.get_device_compatible()
if compatible and 'tegra' in compatible:
if 'cv' in compatible or 'nano' in compatible:
linux_id = T210
elif 'quill' in compatible:
linux_id = T186
elif 'xavier' in compatible:
linux_id = T194
elif hardware in ("BCM2708", "BCM2709", "BCM2835"):
linux_id = BCM2XXX
elif "AM33XX" in hardware:
linux_id = AM33XX
elif "sun8i" in hardware:
linux_id = SUN8I
elif "ODROIDC" in hardware:
linux_id = S805
elif "ODROID-C2" in hardware:
linux_id = S905
elif "SAMA5" in hardware:
linux_id = SAMA5
return linux_id | module function_definition identifier parameters identifier block expression_statement assignment identifier none expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement boolean_operator identifier comparison_operator string string_start string_content string_end identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier identifier return_statement identifier | Attempt to detect the CPU on a computer running the Linux kernel. |
def push_entity(self, entity):
if entity.id:
print('Updating {} entity'.format(entity.name))
self.update(entity)
else:
print('Registering {} entity'.format(entity.name))
entity = self.register(entity)
return entity | module function_definition identifier parameters identifier identifier block if_statement attribute identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Registers or updates an entity and returns the entity_json with an ID |
def keys_to_values(self, keys):
"Return the items in the keystore with keys in `keys`."
return dict((k, v) for k, v in self.data.items() if k in keys) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end return_statement call identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause comparison_operator identifier identifier | Return the items in the keystore with keys in `keys`. |
def from_dict(cls, d):
o = super(DistributionList, cls).from_dict(d)
o.members = []
if 'dlm' in d:
o.members = [utils.get_content(member)
for member in utils.as_list(d["dlm"])]
return o | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier list if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier | Override default, adding the capture of members. |
def groupQuery( self ):
items = self.uiQueryTREE.selectedItems()
if ( not len(items) > 2 ):
return
if ( isinstance(items[-1], XJoinItem) ):
items = items[:-1]
tree = self.uiQueryTREE
parent = items[0].parent()
if ( not parent ):
parent = tree
preceeding = items[-1]
tree.blockSignals(True)
tree.setUpdatesEnabled(False)
grp_item = XQueryItem(parent, Q(), preceeding = preceeding)
for item in items:
parent = item.parent()
if ( not parent ):
tree.takeTopLevelItem(tree.indexOfTopLevelItem(item))
else:
parent.takeChild(parent.indexOfChild(item))
grp_item.addChild(item)
grp_item.update()
tree.blockSignals(False)
tree.setUpdatesEnabled(True) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list if_statement parenthesized_expression not_operator comparison_operator call identifier argument_list identifier integer block return_statement if_statement parenthesized_expression call identifier argument_list subscript identifier unary_operator integer identifier block expression_statement assignment identifier subscript identifier slice unary_operator integer expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list if_statement parenthesized_expression not_operator identifier block expression_statement assignment identifier identifier expression_statement assignment identifier subscript identifier unary_operator integer expression_statement call attribute identifier identifier argument_list true expression_statement call attribute identifier identifier argument_list false expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list keyword_argument identifier identifier for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement parenthesized_expression not_operator identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list false expression_statement call attribute identifier identifier argument_list true | Groups the selected items together into a sub query |
def _timestamps_eq(a, b):
assert isinstance(a, datetime)
if not isinstance(b, datetime):
return False
if (a.tzinfo is None) ^ (b.tzinfo is None):
return False
if a.utcoffset() != b.utcoffset():
return False
for a, b in ((a, b), (b, a)):
if isinstance(a, Timestamp):
if isinstance(b, Timestamp):
if a.precision is b.precision and a.fractional_precision is b.fractional_precision:
break
return False
elif a.precision is not TimestampPrecision.SECOND or a.fractional_precision != MICROSECOND_PRECISION:
return False
return a == b | module function_definition identifier parameters identifier identifier block assert_statement call identifier argument_list identifier identifier if_statement not_operator call identifier argument_list identifier identifier block return_statement false if_statement binary_operator parenthesized_expression comparison_operator attribute identifier identifier none parenthesized_expression comparison_operator attribute identifier identifier none block return_statement false if_statement comparison_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block return_statement false for_statement pattern_list identifier identifier tuple tuple identifier identifier tuple identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement call identifier argument_list identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block break_statement return_statement false elif_clause boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier identifier block return_statement false return_statement comparison_operator identifier identifier | Compares two timestamp operands for equivalence under the Ion data model. |
def average_colors(c1, c2):
r = int((c1[0] + c2[0])/2)
g = int((c1[1] + c2[1])/2)
b = int((c1[2] + c2[2])/2)
return (r, g, b) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list binary_operator parenthesized_expression binary_operator subscript identifier integer subscript identifier integer integer expression_statement assignment identifier call identifier argument_list binary_operator parenthesized_expression binary_operator subscript identifier integer subscript identifier integer integer expression_statement assignment identifier call identifier argument_list binary_operator parenthesized_expression binary_operator subscript identifier integer subscript identifier integer integer return_statement tuple identifier identifier identifier | Average the values of two colors together |
def wait_for_crm_operation(operation):
logger.info("wait_for_crm_operation: "
"Waiting for operation {} to finish...".format(operation))
for _ in range(MAX_POLLS):
result = crm.operations().get(name=operation["name"]).execute()
if "error" in result:
raise Exception(result["error"])
if "done" in result and result["done"]:
logger.info("wait_for_crm_operation: Operation done.")
break
time.sleep(POLL_INTERVAL)
return result | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier for_statement identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end identifier argument_list if_statement comparison_operator string string_start string_content string_end identifier block raise_statement call identifier argument_list subscript identifier string string_start string_content string_end if_statement boolean_operator comparison_operator string string_start string_content string_end identifier subscript identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end break_statement expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Poll for cloud resource manager operation until finished. |
def _prune_all_if_small(self, small_size, a_or_u):
"Return True and delete children if small enough."
if self._nodes is None:
return True
total_size = (self.app_size() if a_or_u else self.use_size())
if total_size < small_size:
if a_or_u:
self._set_size(total_size, self.use_size())
else:
self._set_size(self.app_size(), total_size)
return True
return False | module function_definition identifier parameters identifier identifier identifier block expression_statement string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block return_statement true expression_statement assignment identifier parenthesized_expression conditional_expression call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list else_clause block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement true return_statement false | Return True and delete children if small enough. |
def listdir(self, folder_id='0', offset=None, limit=None, fields=None):
'Get Box object, representing list of objects in a folder.'
if fields is not None\
and not isinstance(fields, types.StringTypes): fields = ','.join(fields)
return self(
join('folders', folder_id, 'items'),
dict(offset=offset, limit=limit, fields=fields) ) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement string string_start string_content string_end if_statement boolean_operator comparison_operator identifier none line_continuation not_operator call identifier argument_list identifier attribute identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list string string_start string_content string_end identifier string string_start string_content string_end call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Get Box object, representing list of objects in a folder. |
def isconsistent(self):
for dt1, dt0 in laggeddates(self):
if dt1 <= dt0:
return False
return True | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator identifier identifier block return_statement false return_statement true | Check if the timeseries is consistent |
def activities(self, limit=1, event=None):
activities = self._activities or []
if event:
activities = list(
filter(
lambda activity:
activity[CONST.EVENT] == event, activities))
return activities[:limit] | module function_definition identifier parameters identifier default_parameter identifier integer default_parameter identifier none block expression_statement assignment identifier boolean_operator attribute identifier identifier list if_statement identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list lambda lambda_parameters identifier comparison_operator subscript identifier attribute identifier identifier identifier identifier return_statement subscript identifier slice identifier | Return device activity information. |
def main():
WIDTH, HEIGHT = 120, 60
TITLE = None
with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F",
renderer=tcod.RENDERER_SDL) as console:
tcod.sys_set_fps(24)
while True:
tcod.console_flush()
for event in tcod.event.wait():
print(event)
if event.type == "QUIT":
raise SystemExit()
elif event.type == "MOUSEMOTION":
console.ch[:, -1] = 0
console.print_(0, HEIGHT - 1, str(event))
else:
console.blit(console, 0, 0, 0, 1, WIDTH, HEIGHT - 2)
console.ch[:, -3] = 0
console.print_(0, HEIGHT - 3, str(event)) | module function_definition identifier parameters block expression_statement assignment pattern_list identifier identifier expression_list integer integer expression_statement assignment identifier none with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list integer while_statement true block expression_statement call attribute identifier identifier argument_list for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement call identifier argument_list identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block raise_statement call identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment subscript attribute identifier identifier slice unary_operator integer integer expression_statement call attribute identifier identifier argument_list integer binary_operator identifier integer call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier integer integer integer integer identifier binary_operator identifier integer expression_statement assignment subscript attribute identifier identifier slice unary_operator integer integer expression_statement call attribute identifier identifier argument_list integer binary_operator identifier integer call identifier argument_list identifier | Example program for tcod.event |
def make_string(seq):
string = ''
for c in seq:
try:
if 32 <= c and c < 256:
string += chr(c)
except TypeError:
pass
if not string:
return str(seq)
return string | module function_definition identifier parameters identifier block expression_statement assignment identifier string string_start string_end for_statement identifier identifier block try_statement block if_statement boolean_operator comparison_operator integer identifier comparison_operator identifier integer block expression_statement augmented_assignment identifier call identifier argument_list identifier except_clause identifier block pass_statement if_statement not_operator identifier block return_statement call identifier argument_list identifier return_statement identifier | Don't throw an exception when given an out of range character. |
def group(self):
yield self.current
for num, item in enumerate(self.iterator, 1):
self.current = item
if num == self.limit:
break
yield item
else:
self.on_going = False | module function_definition identifier parameters identifier block expression_statement yield attribute identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier integer block expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator identifier attribute identifier identifier block break_statement expression_statement yield identifier else_clause block expression_statement assignment attribute identifier identifier false | Yield a group from the iterable |
def build_configuration_parameters(app):
env = Environment(loader=FileSystemLoader("{0}/_data_templates".format(BASEPATH)))
template_file = env.get_template("configuration-parameters.j2")
data = {}
data["schema"] = Config.schema()
rendered_template = template_file.render(**data)
output_dir = "{0}/configuration/generated".format(BASEPATH)
with open("{}/parameters.rst".format(output_dir), "w") as f:
f.write(rendered_template) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier with_statement with_clause with_item as_pattern call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier | Create documentation for configuration parameters. |
def unused_port(hostname):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((hostname, 0))
return s.getsockname()[1] | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list tuple identifier integer return_statement subscript call attribute identifier identifier argument_list integer | Return a port that is unused on the current host. |
def brew(clean=False):
try: cmd('which brew')
except:
return
print('-[brew]----------')
cmd('brew update')
p = cmd('brew outdated')
if not p: return
pkgs = getPackages(p)
for p in pkgs:
cmd('brew upgrade {}'.format(p), run=global_run)
if clean:
print(' > brew prune old sym links and cleanup')
cmd('brew prune')
cmd('brew cleanup') | module function_definition identifier parameters default_parameter identifier false block try_statement block expression_statement call identifier argument_list string string_start string_content string_end except_clause block return_statement expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list string string_start string_content string_end if_statement not_operator identifier block return_statement expression_statement assignment identifier call identifier argument_list identifier for_statement identifier identifier block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier identifier if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list string string_start string_content string_end | Handle homebrew on macOS |
def edit(self, request, id):
try:
object = self.model.objects.get(id=id)
except self.model.DoesNotExist:
return self._render(
request = request,
template = '404',
context = {
'error': 'The %s could not be found.' % self.model.__name__.lower()
},
status = 404,
prefix_template_path = False
)
form = (self.form or generate_form(self.model))(instance=object)
form.fields['_method'] = CharField(required=True, initial='PUT', widget=HiddenInput)
return self._render(
request = request,
template = 'edit',
context = {
cc2us(self.model.__name__): object,
'form': form
},
status = 200
) | module function_definition identifier parameters identifier identifier identifier block try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier except_clause attribute attribute identifier identifier identifier block return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair string string_start string_content string_end binary_operator string string_start string_content string_end call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier integer keyword_argument identifier false expression_statement assignment identifier call parenthesized_expression boolean_operator attribute identifier identifier call identifier argument_list attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call identifier argument_list keyword_argument identifier true keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier dictionary pair call identifier argument_list attribute attribute identifier identifier identifier identifier pair string string_start string_content string_end identifier keyword_argument identifier integer | Render a form to edit an object. |
def sender(self, func, routing=None, routing_re=None):
if routing and not isinstance(routing, list):
routing = [routing]
if routing_re:
if not isinstance(routing_re, list):
routing_re = [routing_re]
routing_re[:] = [re.compile(r) for r in routing_re]
self.senders.append((func, routing, routing_re)) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block if_statement boolean_operator identifier not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier if_statement identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment subscript identifier slice list_comprehension call attribute identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier | Registers a sender function |
def finalize(self, initial=True):
if getattr(self, '_finalized', False):
return
if (
self.proxy is None or
not hasattr(self.proxy, 'name')
):
Clock.schedule_once(self.finalize, 0)
return
if initial:
self.name = self.proxy.name
self.paths = self.proxy.setdefault(
'_image_paths', self.default_image_paths
)
zeroes = [0] * len(self.paths)
self.offxs = self.proxy.setdefault('_offxs', zeroes)
self.offys = self.proxy.setdefault('_offys', zeroes)
self.proxy.connect(self._trigger_pull_from_proxy)
self.bind(
paths=self._trigger_push_image_paths,
offxs=self._trigger_push_offxs,
offys=self._trigger_push_offys
)
self._finalized = True
self.finalize_children() | module function_definition identifier parameters identifier default_parameter identifier true block if_statement call identifier argument_list identifier string string_start string_content string_end false block return_statement if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none not_operator call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list attribute identifier identifier integer return_statement if_statement identifier block expression_statement assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier binary_operator list integer call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment attribute identifier identifier true expression_statement call attribute identifier identifier argument_list | Call this after you've created all the PawnSpot you need and are ready to add them to the board. |
def validate(self):
try:
response = self.client.get_access_key_last_used(
AccessKeyId=self.access_key_id
)
username = response['UserName']
access_keys = self.client.list_access_keys(
UserName=username
)
for key in access_keys['AccessKeyMetadata']:
if \
(key['AccessKeyId'] == self.access_key_id)\
and (key['Status'] == 'Inactive'):
return True
return False
except Exception as e:
logger.info(
"Failed to validate key disable for "
"key {id} due to: {e}.".format(
e=e, id=self.access_key_id
)
)
return False | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier for_statement identifier subscript identifier string string_start string_content string_end block if_statement line_continuation boolean_operator parenthesized_expression comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier line_continuation parenthesized_expression comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block return_statement true return_statement false except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier return_statement false | Returns whether this plugin does what it claims to have done |
def __taint_move(self, instr):
op0_taint = self.get_operand_taint(instr.operands[0])
self.set_operand_taint(instr.operands[2], op0_taint) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier integer identifier | Taint registers move instruction. |
def generate_catalogue(args, parser):
catalogue = tacl.Catalogue()
catalogue.generate(args.corpus, args.label)
catalogue.save(args.catalogue) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Generates and saves a catalogue file. |
def _CheckLogFileSize(cursor):
innodb_log_file_size = int(_ReadVariable("innodb_log_file_size", cursor))
required_size = 10 * mysql_blobs.BLOB_CHUNK_SIZE
if innodb_log_file_size < required_size:
max_blob_size = innodb_log_file_size / 10
max_blob_size_mib = max_blob_size / 2**20
logging.warning(
"MySQL innodb_log_file_size of %d is required, got %d. "
"Storing Blobs bigger than %.4f MiB will fail.", required_size,
innodb_log_file_size, max_blob_size_mib) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier binary_operator integer attribute identifier identifier if_statement comparison_operator identifier identifier block expression_statement assignment identifier binary_operator identifier integer expression_statement assignment identifier binary_operator identifier binary_operator integer integer 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 identifier identifier | Warns if MySQL log file size is not large enough for blob insertions. |
def execute(self, request):
handle = None
if request:
request[0] = command = to_string(request[0]).lower()
info = COMMANDS_INFO.get(command)
if info:
handle = getattr(self.store, info.method_name)
if self.channels or self.patterns:
if command not in self.store.SUBSCRIBE_COMMANDS:
return self.reply_error(self.store.PUBSUB_ONLY)
if self.blocked:
return self.reply_error('Blocked client cannot request')
if self.transaction is not None and command not in 'exec':
self.transaction.append((handle, request))
return self.connection.write(self.store.QUEUED)
self.execute_command(handle, request) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none if_statement identifier block expression_statement assignment subscript identifier integer assignment identifier call attribute call identifier argument_list subscript identifier integer identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier attribute identifier identifier if_statement boolean_operator attribute identifier identifier attribute identifier identifier block if_statement comparison_operator identifier attribute attribute identifier identifier identifier block return_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier if_statement attribute identifier identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list tuple identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier | Execute a new ``request``. |
def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray:
x0 = np.linspace(0, 3.14, Np)
return np.tanh(x0)*gridmax+gridmin | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list integer float identifier return_statement binary_operator binary_operator call attribute identifier identifier argument_list identifier identifier identifier | typically call via setupz instead |
def docs(root_url, path):
root_url = root_url.rstrip('/')
path = path.lstrip('/')
if root_url == OLD_ROOT_URL:
return 'https://docs.taskcluster.net/{}'.format(path)
else:
return '{}/docs/{}'.format(root_url, path) | 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 expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list identifier else_clause block return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier | Generate URL for path in the Taskcluster docs. |
def to_cartesian(r, theta, theta_units="radians"):
assert theta_units in ['radians', 'degrees'],\
"kwarg theta_units must specified in radians or degrees"
if theta_units == "degrees":
theta = to_radians(theta)
theta = to_proper_radians(theta)
x = r * cos(theta)
y = r * sin(theta)
return x, y | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block assert_statement comparison_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator identifier call identifier argument_list identifier return_statement expression_list identifier identifier | Converts polar r, theta to cartesian x, y. |
def asdict(self):
d = dict(self._odict)
for k,v in d.items():
if isinstance(v, Struct):
d[k] = v.asdict()
return d | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list return_statement identifier | Return a recursive dict representation of self |
def combine_dictionaries(a, b):
c = {}
for key in list(b.keys()): c[key]=b[key]
for key in list(a.keys()): c[key]=a[key]
return c | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier subscript identifier identifier for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement identifier | returns the combined dictionary. a's values preferentially chosen |
def _merge_colormaps(kwargs):
from trollimage.colormap import Colormap
full_cmap = None
palette = kwargs['palettes']
if isinstance(palette, Colormap):
full_cmap = palette
else:
for itm in palette:
cmap = create_colormap(itm)
cmap.set_range(itm["min_value"], itm["max_value"])
if full_cmap is None:
full_cmap = cmap
else:
full_cmap = full_cmap + cmap
return full_cmap | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier none expression_statement assignment identifier subscript identifier string string_start string_content string_end if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier else_clause block for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier identifier else_clause block expression_statement assignment identifier binary_operator identifier identifier return_statement identifier | Merge colormaps listed in kwargs. |
def _translate(self, x, y):
return self.parent._translate((x + self.x), (y + self.y)) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list parenthesized_expression binary_operator identifier attribute identifier identifier parenthesized_expression binary_operator identifier attribute identifier identifier | Convertion x and y to their position on the root Console |
def print_update(self):
print("\r\n")
now = datetime.datetime.now()
print("Update info: (from: %s)" % now.strftime("%c"))
current_total_size = self.total_stined_bytes + self.total_new_bytes
if self.total_errored_items:
print(" * WARNING: %i omitted files!" % self.total_errored_items)
print(" * fast backup: %i files" % self.total_fast_backup)
print(
" * new content saved: %i files (%s %.1f%%)"
% (
self.total_new_file_count,
human_filesize(self.total_new_bytes),
to_percent(self.total_new_bytes, current_total_size),
)
)
print(
" * stint space via hardlinks: %i files (%s %.1f%%)"
% (
self.total_file_link_count,
human_filesize(self.total_stined_bytes),
to_percent(self.total_stined_bytes, current_total_size),
)
)
duration = default_timer() - self.start_time
performance = current_total_size / duration / 1024.0 / 1024.0
print(" * present performance: %.1fMB/s\n" % performance) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier call identifier argument_list attribute identifier identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier binary_operator call identifier argument_list attribute identifier identifier expression_statement assignment identifier binary_operator binary_operator binary_operator identifier identifier float float expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier | print some status information in between. |
def _clauses(lexer, varname, nvars):
tok = next(lexer)
toktype = type(tok)
if toktype is OP_not or toktype is IntegerToken:
lexer.unpop_token(tok)
first = _clause(lexer, varname, nvars)
rest = _clauses(lexer, varname, nvars)
return (first, ) + rest
else:
lexer.unpop_token(tok)
return tuple() | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier identifier return_statement binary_operator tuple identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list | Return a tuple of DIMACS CNF clauses. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.