code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def topics_in(self, d, topn=5):
return self.theta.features[d].top(topn) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block return_statement call attribute subscript attribute attribute identifier identifier identifier identifier identifier argument_list identifier | List the top ``topn`` topics in document ``d``. |
def _validate_prepostloop_callable(cls, func: Callable[[None], None]) -> None:
cls._validate_callable_param_count(func, 0)
signature = inspect.signature(func)
if signature.return_annotation is not None:
raise TypeError("{} must declare return a return type of 'None'".format(
func.__name__,
)) | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type list none type none type none block expression_statement call attribute identifier identifier argument_list identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier | Check parameter and return types for preloop and postloop hooks. |
def _base_environ(self, **request):
environ = {
'HTTP_COOKIE': self.cookies.output(header='', sep='; '),
'PATH_INFO': str('/'),
'REMOTE_ADDR': str('127.0.0.1'),
'REQUEST_METHOD': str('GET'),
'SCRIPT_NAME': str(''),
'SERVER_NAME': str('localhost'),
'SERVER_PORT': str('8000'),
'SERVER_PROTOCOL': str('HTTP/1.1'),
'wsgi.version': (1, 0),
'wsgi.url_scheme': str('http'),
'wsgi.input': FakePayload(b''),
'wsgi.errors': self.errors,
'wsgi.multiprocess': True,
'wsgi.multithread': True,
'wsgi.run_once': False,
}
environ.update(self.defaults)
environ.update(request)
return environ | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_end keyword_argument identifier string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_end pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end tuple integer integer pair string string_start string_content string_end call identifier argument_list string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list string string_start string_end pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end true pair string string_start string_content string_end true pair string string_start string_content string_end false expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Override the default values for the wsgi environment variables. |
def _get_script_args(cls, type_, name, header, script_text):
"For Windows, add a .py extension"
ext = dict(console='.pya', gui='.pyw')[type_]
if ext not in os.environ['PATHEXT'].lower().split(';'):
msg = (
"{ext} not listed in PATHEXT; scripts will not be "
"recognized as executables."
).format(**locals())
warnings.warn(msg, UserWarning)
old = ['.pya', '.py', '-script.py', '.pyc', '.pyo', '.pyw', '.exe']
old.remove(ext)
header = cls._adjust_header(type_, header)
blockers = [name + x for x in old]
yield name + ext, header + script_text, 't', blockers | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript call identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end identifier if_statement comparison_operator identifier call attribute call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier argument_list string string_start string_content string_end block expression_statement assignment identifier call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list dictionary_splat call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end 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 expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier list_comprehension binary_operator identifier identifier for_in_clause identifier identifier expression_statement yield expression_list binary_operator identifier identifier binary_operator identifier identifier string string_start string_content string_end identifier | For Windows, add a .py extension |
def probes_used_generate_vector(probe_files_full, probe_files_model):
import numpy as np
C_probesUsed = np.ndarray((len(probe_files_full),), 'bool')
C_probesUsed.fill(False)
c=0
for k in sorted(probe_files_full.keys()):
if probe_files_model.has_key(k): C_probesUsed[c] = True
c+=1
return C_probesUsed | module function_definition identifier parameters identifier identifier block import_statement aliased_import dotted_name identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list tuple call identifier argument_list identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list false expression_statement assignment identifier integer for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement call attribute identifier identifier argument_list identifier block expression_statement assignment subscript identifier identifier true expression_statement augmented_assignment identifier integer return_statement identifier | Generates boolean matrices indicating which are the probes for each model |
def _flush(self, commit=True, using=None):
if commit:
if self._uses_savepoints():
self._commit_all_savepoints(using)
c = self.local.mget('%s_%s_*' %
(self.prefix, self._trunc_using(using)))
for key, value in c.items():
self.cache_backend.set(key, value, self.timeout)
else:
if self._uses_savepoints():
self._rollback_all_savepoints(using)
self._clear(using)
self._clear_sid_stack(using) | module function_definition identifier parameters identifier default_parameter identifier true default_parameter identifier none block if_statement identifier block if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end tuple attribute identifier identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier attribute identifier identifier else_clause block if_statement call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Flushes the internal cache, either to the memcache or rolls back |
def execute(self, input_data):
raw_bytes = input_data['sample']['raw_bytes']
matches = self.rules.match_data(raw_bytes)
flat_data = collections.defaultdict(list)
for filename, match_list in matches.iteritems():
for match in match_list:
if 'description' in match['meta']:
new_tag = filename+'_'+match['meta']['description']
else:
new_tag = filename+'_'+match['rule']
for match in match['strings']:
flat_data[new_tag].append(match['data'])
flat_data[new_tag] = list(set(flat_data[new_tag]))
return {'matches': flat_data} | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block for_statement identifier identifier block if_statement comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end subscript subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment identifier binary_operator binary_operator identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_statement identifier subscript identifier string string_start string_content string_end block expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier identifier call identifier argument_list call identifier argument_list subscript identifier identifier return_statement dictionary pair string string_start string_content string_end identifier | yara worker execute method |
def pages(self):
rev = self.db.get('site:rev')
if int(rev) != self.revision:
self.reload_site()
return self._pages | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list return_statement attribute identifier identifier | Get pages, reloading the site if needed. |
def NegateQueryFilter(es_query):
query = es_query.to_dict().get("query", {})
filtered = query.get("filtered", {})
negated_filter = filtered.get("filter", {})
return Not(**negated_filter) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end dictionary return_statement call identifier argument_list dictionary_splat identifier | Return a filter removing the contents of the provided query. |
def push_images():
registry = conf.get('docker.registry')
docker_images = conf.get('docker.images', [])
if registry is None:
log.err("You must define docker.registry conf variable to push images")
sys.exit(-1)
for image in docker_images:
push_image(registry, image) | module function_definition identifier parameters 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 list if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list unary_operator integer for_statement identifier identifier block expression_statement call identifier argument_list identifier identifier | Push all project docker images to a remote registry. |
def _response(self, pdu):
if _debug: UDPDirector._debug("_response %r", pdu)
addr = pdu.pduSource
peer = self.peers.get(addr, None)
if not peer:
peer = self.actorClass(self, addr)
peer.response(pdu) | module function_definition identifier parameters identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier none if_statement not_operator identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Incoming datagrams are routed through an actor. |
def com_google_fonts_check_name_no_copyright_on_description(ttFont):
failed = False
for name in ttFont['name'].names:
if 'opyright' in name.string.decode(name.getEncoding())\
and name.nameID == NameID.DESCRIPTION:
failed = True
if failed:
yield FAIL, ("Namerecords with ID={} (NameID.DESCRIPTION)"
" should be removed (perhaps these were added by"
" a longstanding FontLab Studio 5.x bug that"
" copied copyright notices to them.)"
"").format(NameID.DESCRIPTION)
else:
yield PASS, ("Description strings in the name table"
" do not contain any copyright string.") | module function_definition identifier parameters identifier block expression_statement assignment identifier false for_statement identifier attribute subscript identifier string string_start string_content string_end identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list line_continuation comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier true if_statement identifier block expression_statement yield expression_list identifier call attribute parenthesized_expression concatenated_string 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_end identifier argument_list attribute identifier identifier else_clause block expression_statement yield expression_list identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end | Description strings in the name table must not contain copyright info. |
def do_status(self):
pid = self.pid.get()
status_color = 'green' if pid else 'red'
status_dot = self._colorize(UNICODE['dot'], status_color, encode=True)
active_txt = {
'active': '{} since {}'.format(self._colorize('active (running)', 'green'), self.pid.birthday()[1]),
'inactive': 'inactive (dead)'
}
print(status_dot, end=' ')
print('{}.service - LSB: {}'.format(self.name, self.desc))
print(' Loaded: loaded (/etc/init.d/{})'.format(self.name))
print(' Active: {}'.format(active_txt['active' if pid else 'inactive']))
if pid:
ps = self.pid.ps()
print(' Process: {}; [{}]'.format(pid, ps[0]))
if ps[1]:
for c in ps[1]:
print(' Child: {}'.format(c))
print('') | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier keyword_argument identifier true expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end subscript call attribute attribute identifier identifier identifier argument_list integer pair string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list identifier keyword_argument identifier string string_start string_content string_end expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end if_statement identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier subscript identifier integer if_statement subscript identifier integer block for_statement identifier subscript identifier integer block expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement call identifier argument_list string string_start string_end | Get the status of the service. |
def author_display(author, *args):
url = getattr(author, 'get_absolute_url', lambda: None)()
short_name = getattr(author, 'get_short_name', lambda: six.text_type(author))()
if url:
return mark_safe('<a href="{}">{}</a>'.format(url, short_name))
else:
return short_name | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement assignment identifier call call identifier argument_list identifier string string_start string_content string_end lambda none argument_list expression_statement assignment identifier call call identifier argument_list identifier string string_start string_content string_end lambda call attribute identifier identifier argument_list identifier argument_list if_statement identifier block return_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier else_clause block return_statement identifier | Returns either the linked or not-linked profile name. |
def _relative(self, uri):
if uri.startswith("http:") or \
uri.startswith("https:") or \
uri.startswith("file:") or \
uri.startswith("/"):
return uri
elif exists(uri):
return relpath(uri, self.basedir)
else:
return uri | module function_definition identifier parameters identifier identifier block if_statement boolean_operator boolean_operator boolean_operator 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 line_continuation 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 identifier elif_clause call identifier argument_list identifier block return_statement call identifier argument_list identifier attribute identifier identifier else_clause block return_statement identifier | if uri is relative, re-relate it to our basedir |
def __learn_oneself(self):
if not self.__parent_path or not self.__text_nodes:
raise Exception("This error occurred because the step constructor\
had insufficient textnodes or it had empty string\
for its parent xpath")
self.tnodes_cnt = len(self.__text_nodes)
self.ttl_strlen = sum([len(tnode) for tnode in self.__text_nodes])
self.avg_strlen = self.ttl_strlen/self.tnodes_cnt | module function_definition identifier parameters identifier block if_statement boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content escape_sequence escape_sequence string_end expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier expression_statement assignment attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier | calculate cardinality, total and average string length |
def _add_global_counter(self):
assert self._global_step is None
with self.g.as_default(), self.g.name_scope(None):
try:
self._global_step = self.g.get_tensor_by_name('global_step:0')
except KeyError:
self._global_step = tf.Variable(0, name='global_step', trainable=False) | module function_definition identifier parameters identifier block assert_statement comparison_operator attribute identifier identifier none with_statement with_clause with_item call attribute attribute identifier identifier identifier argument_list with_item call attribute attribute identifier identifier identifier argument_list none block try_statement block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list integer keyword_argument identifier string string_start string_content string_end keyword_argument identifier false | Adds a global counter, called once for setup by @property global_step. |
def run(
self
):
if self._function and not self._kwargs:
return self._function()
if self._function and self._kwargs:
return self._function(**self._kwargs) | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier not_operator attribute identifier identifier block return_statement call attribute identifier identifier argument_list if_statement boolean_operator attribute identifier identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list dictionary_splat attribute identifier identifier | Engage contained function with optional keyword arguments. |
def shipping_options(request, country):
qrs = models.ShippingRate.objects.filter(countries__in=[country])
serializer = serializers.ShippingRateSerializer(qrs, many=True)
return Response(
data=serializer.data,
status=status.HTTP_200_OK
) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier true return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Get the shipping options for a given country |
def _initialize_variables(self):
self._global_vars = {}
for mtf_dimension_name in (
self._layout_validator.splittable_mtf_dimension_names):
for mesh_dimension_name in (
self._layout_validator.mesh_dimension_name_to_size):
name = _global_var_name(mtf_dimension_name, mesh_dimension_name)
self._global_vars[(mtf_dimension_name, mesh_dimension_name)] = (
self._model.NewBoolVar(name))
self._local_vars = {}
for mtf_dimension_set in self._mtf_dimension_sets:
self._local_vars[mtf_dimension_set] = {}
for assignment in self._assignments[mtf_dimension_set]:
name = _local_var_name(mtf_dimension_set, assignment)
self._local_vars[mtf_dimension_set][name] = (
self._model.NewBoolVar(name))
memory_upper_bound = 0
for tensor_name in self._graph.get_all_tensor_names():
if self._graph.is_tensor_on_canonical_device(tensor_name):
memory_upper_bound += int(self._graph.get_tensor_size(tensor_name))
self._memory_var = self._model.NewIntVar(0, memory_upper_bound, "z") | module function_definition identifier parameters identifier block expression_statement assignment attribute identifier identifier dictionary for_statement identifier parenthesized_expression attribute attribute identifier identifier identifier block for_statement identifier parenthesized_expression attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment subscript attribute identifier identifier tuple identifier identifier parenthesized_expression call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier dictionary for_statement identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier dictionary for_statement identifier subscript attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment subscript subscript attribute identifier identifier identifier identifier parenthesized_expression call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement augmented_assignment identifier call identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list integer identifier string string_start string_content string_end | Initializing the variables of the IP. |
def worker_errordown(self, node, error):
self.config.hook.pytest_testnodedown(node=node, error=error)
try:
crashitem = self.sched.remove_node(node)
except KeyError:
pass
else:
if crashitem:
self.handle_crashitem(crashitem, node)
self._failed_nodes_count += 1
maximum_reached = (
self._max_worker_restart is not None
and self._failed_nodes_count > self._max_worker_restart
)
if maximum_reached:
if self._max_worker_restart == 0:
msg = "Worker restarting disabled"
else:
msg = "Maximum crashed workers reached: %d" % self._max_worker_restart
self.report_line(msg)
else:
self.report_line("Replacing crashed worker %s" % node.gateway.id)
self._clone_node(node)
self._active_nodes.remove(node) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block pass_statement else_clause block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement augmented_assignment attribute identifier identifier integer expression_statement assignment identifier parenthesized_expression boolean_operator comparison_operator attribute identifier identifier none comparison_operator attribute identifier identifier attribute identifier identifier if_statement identifier block if_statement comparison_operator attribute identifier identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Emitted by the WorkerController when a node dies. |
def apply_lsadmin(fn):
cmd = ["lsadmin", "showconf", "lim"]
try:
output = subprocess.check_output(cmd).decode('utf-8')
except:
return None
return fn(output.split("\n")) | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end try_statement block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end except_clause block return_statement none return_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end | apply fn to each line of lsadmin, returning the result |
def remove_index(self):
self.index_client.close(self.index_name)
self.index_client.delete(self.index_name) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Remove Elasticsearch index associated to the campaign |
def who(self, *args):
if len(self._users) == 0:
self.log('No users connected')
if len(self._clients) == 0:
self.log('No clients connected')
return
Row = namedtuple("Row", ['User', 'Client', 'IP'])
rows = []
for user in self._users.values():
for key, client in self._clients.items():
if client.useruuid == user.uuid:
row = Row(user.account.name, key, client.ip)
rows.append(row)
for key, client in self._clients.items():
if client.useruuid is None:
row = Row('ANON', key, client.ip)
rows.append(row)
self.log("\n" + std_table(rows)) | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement expression_statement assignment identifier call identifier argument_list string string_start string_content string_end list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier list for_statement identifier call attribute attribute identifier identifier identifier argument_list block for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end call identifier argument_list identifier | Display a table of connected users and clients |
def parse_wait_time(text: str) -> int:
val = RATELIMIT.findall(text)
if len(val) > 0:
try:
res = val[0]
if res[1] == 'minutes':
return int(res[0]) * 60
if res[1] == 'seconds':
return int(res[0])
except Exception as e:
util_logger.warning('Could not parse ratelimit: ' + str(e))
return 1 * 60 | module function_definition identifier parameters typed_parameter identifier type identifier type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator call identifier argument_list identifier integer block try_statement block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator subscript identifier integer string string_start string_content string_end block return_statement binary_operator call identifier argument_list subscript identifier integer integer if_statement comparison_operator subscript identifier integer string string_start string_content string_end block return_statement call identifier argument_list subscript identifier integer except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier return_statement binary_operator integer integer | Parse the waiting time from the exception |
async def on_isupport_excepts(self, value):
if not value:
value = BAN_EXCEPT_MODE
self._channel_modes.add(value)
self._channel_modes_behaviour[rfc1459.protocol.BEHAVIOUR_LIST].add(value) | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block expression_statement assignment identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute subscript attribute identifier identifier attribute attribute identifier identifier identifier identifier argument_list identifier | Server allows ban exceptions. |
def nodes_minimum_distance_validation(self):
if self.layer and self.layer.nodes_minimum_distance:
minimum_distance = self.layer.nodes_minimum_distance
near_nodes = Node.objects.exclude(pk=self.id).filter(geometry__distance_lte=(self.geometry, D(m=minimum_distance))).count()
if near_nodes > 0:
raise ValidationError(_('Distance between nodes cannot be less than %s meters') % minimum_distance) | module function_definition identifier parameters identifier block if_statement boolean_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier identifier argument_list keyword_argument identifier tuple attribute identifier identifier call identifier argument_list keyword_argument identifier identifier identifier argument_list if_statement comparison_operator identifier integer block raise_statement call identifier argument_list binary_operator call identifier argument_list string string_start string_content string_end identifier | if minimum distance is specified, ensure node is not too close to other nodes; |
def _lstree(files, dirs):
for f, sha1 in files:
yield "100644 blob {}\t{}\0".format(sha1, f)
for d, sha1 in dirs:
yield "040000 tree {}\t{}\0".format(sha1, d) | module function_definition identifier parameters identifier identifier block for_statement pattern_list identifier identifier identifier block expression_statement yield call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier identifier for_statement pattern_list identifier identifier identifier block expression_statement yield call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list identifier identifier | Make git ls-tree like output. |
def on_task_status(self, task):
if not self.interactive:
super(OneScheduler, self).on_task_status(task)
try:
procesok = task['track']['process']['ok']
except KeyError as e:
logger.error("Bad status pack: %s", e)
return None
if procesok:
ret = self.on_task_done(task)
else:
ret = self.on_task_failed(task)
if task['track']['fetch'].get('time'):
self._cnt['5m_time'].event((task['project'], 'fetch_time'),
task['track']['fetch']['time'])
if task['track']['process'].get('time'):
self._cnt['5m_time'].event((task['project'], 'process_time'),
task['track']['process'].get('time'))
self.projects[task['project']].active_tasks.appendleft((time.time(), task))
return ret | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier try_statement block expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement none if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end block expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple subscript identifier string string_start string_content string_end string string_start string_content string_end subscript subscript subscript identifier string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end block expression_statement call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list tuple subscript identifier string string_start string_content string_end string string_start string_content string_end call attribute subscript subscript identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list string string_start string_content string_end expression_statement call attribute attribute subscript attribute identifier identifier subscript identifier string string_start string_content string_end identifier identifier argument_list tuple call attribute identifier identifier argument_list identifier return_statement identifier | Ignore not processing error in interactive mode |
def clear(self):
while self.current or self.idlers or self.queue or self.rpcs:
current = self.current
idlers = self.idlers
queue = self.queue
rpcs = self.rpcs
_logging_debug('Clearing stale EventLoop instance...')
if current:
_logging_debug(' current = %s', current)
if idlers:
_logging_debug(' idlers = %s', idlers)
if queue:
_logging_debug(' queue = %s', queue)
if rpcs:
_logging_debug(' rpcs = %s', rpcs)
self.__init__()
current.clear()
idlers.clear()
queue[:] = []
rpcs.clear()
_logging_debug('Cleared') | module function_definition identifier parameters identifier block while_statement boolean_operator boolean_operator boolean_operator attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement assignment subscript identifier slice list expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list string string_start string_content string_end | Remove all pending events without running any. |
def wrap_tuple_streams(unwrapped, kdims, streams):
param_groups = [(s.contents.keys(), s) for s in streams]
pairs = [(name,s) for (group, s) in param_groups for name in group]
substituted = []
for pos,el in enumerate(wrap_tuple(unwrapped)):
if el is None and pos < len(kdims):
matches = [(name,s) for (name,s) in pairs if name==kdims[pos].name]
if len(matches) == 1:
(name, stream) = matches[0]
el = stream.contents[name]
substituted.append(el)
return tuple(substituted) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier list_comprehension tuple call attribute attribute identifier identifier identifier argument_list identifier for_in_clause identifier identifier expression_statement assignment identifier list_comprehension tuple identifier identifier for_in_clause tuple_pattern identifier identifier identifier for_in_clause identifier identifier expression_statement assignment identifier list for_statement pattern_list identifier identifier call identifier argument_list call identifier argument_list identifier block if_statement boolean_operator comparison_operator identifier none comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier list_comprehension tuple identifier identifier for_in_clause tuple_pattern identifier identifier identifier if_clause comparison_operator identifier attribute subscript identifier identifier identifier if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment tuple_pattern identifier identifier subscript identifier integer expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier | Fills in tuple keys with dimensioned stream values as appropriate. |
def to_decimal(value, ctx):
if isinstance(value, bool):
return Decimal(1) if value else Decimal(0)
elif isinstance(value, int):
return Decimal(value)
elif isinstance(value, Decimal):
return value
elif isinstance(value, str):
try:
return Decimal(value)
except Exception:
pass
raise EvaluationError("Can't convert '%s' to a decimal" % str(value)) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement conditional_expression call identifier argument_list integer identifier call identifier argument_list integer elif_clause call identifier argument_list identifier identifier block return_statement call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier block try_statement block return_statement call identifier argument_list identifier except_clause identifier block pass_statement raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list identifier | Tries conversion of any value to a decimal |
def get(self, request, *args, **kwargs):
measurements = Measurement.objects.all()
return data_csv(self.request, measurements) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list attribute identifier identifier identifier | The queryset returns all measurement objects |
def compile(self):
if self.buffer is None:
self.buffer = self._compile_value(self.data, 0)
return self.buffer.strip() | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier integer return_statement call attribute attribute identifier identifier identifier argument_list | Return Hip string if already compiled else compile it. |
def _get_object_key(self, p_object):
matched_key = None
matched_index = None
if hasattr(p_object, self._searchNames[0]):
return getattr(p_object, self._searchNames[0])
for x in xrange(len(self._searchNames)):
key = self._searchNames[x]
if hasattr(p_object, key):
matched_key = key
matched_index = x
if matched_key is None:
raise KeyError()
if matched_index != 0 and self._searchOptimize:
self._searchNames.insert(0, self._searchNames.pop(matched_index))
return getattr(p_object, matched_key) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none expression_statement assignment identifier none if_statement call identifier argument_list identifier subscript attribute identifier identifier integer block return_statement call identifier argument_list identifier subscript attribute identifier identifier integer for_statement identifier call identifier argument_list call identifier argument_list attribute identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier identifier expression_statement assignment identifier identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list if_statement boolean_operator comparison_operator identifier integer attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list integer call attribute attribute identifier identifier identifier argument_list identifier return_statement call identifier argument_list identifier identifier | Get key from object |
def deobfuscate_email(text):
text = unescape(text)
text = _deobfuscate_dot1_re.sub('.', text)
text = _deobfuscate_dot2_re.sub(r'\1.\2', text)
text = _deobfuscate_dot3_re.sub(r'\1.\2', text)
text = _deobfuscate_at1_re.sub('@', text)
text = _deobfuscate_at2_re.sub(r'\1@\2', text)
text = _deobfuscate_at3_re.sub(r'\1@\2', text)
return text | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier return_statement identifier | Deobfuscate email addresses in provided text |
def cbow_fasttext_batch(centers, contexts, num_tokens, subword_lookup, dtype,
index_dtype):
_, contexts_row, contexts_col = contexts
data, row, col = subword_lookup(contexts_row, contexts_col)
centers = mx.nd.array(centers, dtype=index_dtype)
contexts = mx.nd.sparse.csr_matrix(
(data, (row, col)), dtype=dtype,
shape=(len(centers), num_tokens))
return centers, contexts | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment pattern_list identifier identifier identifier identifier expression_statement assignment pattern_list identifier identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier identifier expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list tuple identifier tuple identifier identifier keyword_argument identifier identifier keyword_argument identifier tuple call identifier argument_list identifier identifier return_statement expression_list identifier identifier | Create a batch for CBOW training objective with subwords. |
def _first(self, **spec):
for record in self._entries(spec).order_by(model.Entry.local_date,
model.Entry.id)[:1]:
return entry.Entry(record)
return None | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block for_statement identifier subscript call attribute call attribute identifier identifier argument_list identifier identifier argument_list attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier slice integer block return_statement call attribute identifier identifier argument_list identifier return_statement none | Get the earliest entry in this category, optionally including subcategories |
def write(self, directory, name=None, session=None, replaceParamFile=None):
if name != None:
filename = '%s.%s' % (name, self.fileExtension)
filePath = os.path.join(directory, filename)
else:
filePath = os.path.join(directory, self.filename)
if type(self.raster) != type(None):
converter = RasterConverter(session)
grassAsciiGrid = converter.getAsGrassAsciiRaster(rasterFieldName='raster',
tableName=self.__tablename__,
rasterIdFieldName='id',
rasterId=self.id)
with open(filePath, 'w') as mapFile:
mapFile.write(grassAsciiGrid)
else:
if self.rasterText is not None:
with open(filePath, 'w') as mapFile:
mapFile.write(self.rasterText) | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier binary_operator string string_start string_content string_end tuple identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier attribute identifier identifier if_statement comparison_operator call identifier argument_list attribute identifier identifier call identifier argument_list none block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier attribute identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list identifier else_clause block if_statement comparison_operator attribute identifier identifier none block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Index Map Write to File Method |
def ensure_ec_params(jwk_dict, private):
provided = frozenset(jwk_dict.keys())
if private is not None and private:
required = EC_PUBLIC_REQUIRED | EC_PRIVATE_REQUIRED
else:
required = EC_PUBLIC_REQUIRED
return ensure_params('EC', provided, required) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement boolean_operator comparison_operator identifier none identifier block expression_statement assignment identifier binary_operator identifier identifier else_clause block expression_statement assignment identifier identifier return_statement call identifier argument_list string string_start string_content string_end identifier identifier | Ensure all required EC parameters are present in dictionary |
def inactive(self):
qset = super(StaffMemberManager, self).get_queryset()
return qset.filter(is_active=False) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list return_statement call attribute identifier identifier argument_list keyword_argument identifier false | Return inactive staff members |
def workers(self):
worker_keys = self.redis_client.keys("Worker*")
workers_data = {}
for worker_key in worker_keys:
worker_info = self.redis_client.hgetall(worker_key)
worker_id = binary_to_hex(worker_key[len("Workers:"):])
workers_data[worker_id] = {
"node_ip_address": decode(worker_info[b"node_ip_address"]),
"plasma_store_socket": decode(
worker_info[b"plasma_store_socket"])
}
if b"stderr_file" in worker_info:
workers_data[worker_id]["stderr_file"] = decode(
worker_info[b"stderr_file"])
if b"stdout_file" in worker_info:
workers_data[worker_id]["stdout_file"] = decode(
worker_info[b"stdout_file"])
return workers_data | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier dictionary for_statement identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list subscript identifier slice call identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript subscript identifier identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript subscript identifier identifier string string_start string_content string_end call identifier argument_list subscript identifier string string_start string_content string_end return_statement identifier | Get a dictionary mapping worker ID to worker information. |
def list_manga_series(self, filter=None, content_type='jp_manga'):
result = self._manga_api.list_series(filter, content_type)
return result | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement identifier | Get a list of manga series |
def ep(self, exc: Exception) -> bool:
if not isinstance(exc, ConnectionAbortedError):
return False
if len(exc.args) != 2:
return False
origin, reason = exc.args
logging.getLogger(__name__).warning('Exited')
return True | module function_definition identifier parameters identifier typed_parameter identifier type identifier type identifier block if_statement not_operator call identifier argument_list identifier identifier block return_statement false if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block return_statement false expression_statement assignment pattern_list identifier identifier attribute identifier identifier expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end return_statement true | Return False if the exception had not been handled gracefully |
def validate(schema_file, config_file, deprecation):
result = validator_from_config_file(config_file, schema_file)
result.validate(error_on_deprecated=deprecation)
for error in result.errors():
click.secho('Error : %s' % error, err=True, fg='red')
for warning in result.warnings():
click.secho('Warning : %s' % warning, err=True, fg='yellow') | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier true keyword_argument identifier string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier true keyword_argument identifier string string_start string_content string_end | Validate a configuration file against a confirm schema. |
def Set(self, interface_name, property_name, value, *args, **kwargs):
self.log('Set %s.%s%s' % (interface_name,
property_name,
self.format_args((value,))))
try:
iface_props = self.props[interface_name]
except KeyError:
raise dbus.exceptions.DBusException(
'no such interface ' + interface_name,
name=self.interface + '.UnknownInterface')
if property_name not in iface_props:
raise dbus.exceptions.DBusException(
'no such property ' + property_name,
name=self.interface + '.UnknownProperty')
iface_props[property_name] = value
self.EmitSignal('org.freedesktop.DBus.Properties',
'PropertiesChanged',
'sa{sv}as',
[interface_name,
dbus.Dictionary({property_name: value}, signature='sv'),
dbus.Array([], signature='s')
]) | module function_definition identifier parameters identifier identifier identifier identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier call attribute identifier identifier argument_list tuple identifier try_statement block expression_statement assignment identifier subscript attribute identifier identifier identifier except_clause identifier block raise_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier binary_operator attribute identifier identifier string string_start string_content string_end if_statement comparison_operator identifier identifier block raise_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier binary_operator attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end list identifier call attribute identifier identifier argument_list dictionary pair identifier identifier keyword_argument identifier string string_start string_content string_end call attribute identifier identifier argument_list list keyword_argument identifier string string_start string_content string_end | Standard D-Bus API for setting a property value |
def _process_messages(self):
try:
for message in self.consumer:
try:
if message is None:
self.logger.debug("no message")
break
loaded_dict = json.loads(message.value)
self.logger.debug("got valid kafka message")
with self.uuids_lock:
if 'uuid' in loaded_dict:
if loaded_dict['uuid'] in self.uuids and \
self.uuids[loaded_dict['uuid']] != 'poll':
self.logger.debug("Found Kafka message from request")
self.uuids[loaded_dict['uuid']] = loaded_dict
else:
self.logger.debug("Got poll result")
self._send_result_to_redis(loaded_dict)
else:
self.logger.debug("Got message not intended for this process")
except ValueError:
extras = {}
if message is not None:
extras["data"] = message.value
self.logger.warning('Unparseable JSON Received from kafka',
extra=extras)
self._check_kafka_disconnect()
except OffsetOutOfRangeError:
self.consumer.seek_to_end()
self.logger.error("Kafka offset out of range error") | module function_definition identifier parameters identifier block try_statement block for_statement identifier attribute identifier identifier block try_statement block if_statement comparison_operator identifier none block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end break_statement expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end with_statement with_clause with_item attribute identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block if_statement boolean_operator comparison_operator subscript identifier string string_start string_content string_end attribute identifier identifier line_continuation comparison_operator subscript attribute identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier subscript identifier string string_start string_content string_end identifier else_clause block 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 identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement assignment identifier dictionary if_statement comparison_operator identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end | Processes messages received from kafka |
def dumps(self):
error = {'code': self.code,
'message': str(self.message)}
if self.data is not None:
error['data'] = self.data
return error | module function_definition identifier parameters 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 call identifier argument_list attribute identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier return_statement identifier | Return the Exception data in a format for JSON-RPC. |
def stamp(self, **kwargs):
kwargs_copy = self.base_dict.copy()
kwargs_copy.update(**kwargs)
return NameFactory.stamp_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 return_statement call attribute attribute identifier identifier identifier argument_list dictionary_splat identifier | Return the path for a stamp file for a scatter gather job |
def _init_state(self, initial_state: Union[int, np.ndarray]):
state = np.reshape(
sim.to_valid_state_vector(initial_state, self._num_qubits),
(self._num_shards, self._shard_size))
state_handle = mem_manager.SharedMemManager.create_array(
state.view(dtype=np.float32))
self._shared_mem_dict['state_handle'] = state_handle | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier tuple attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier | Initializes a the shard wavefunction and sets the initial state. |
def Compile(self, filter_implemention):
return self.operator_method(self.attribute_obj, filter_implemention,
*self.args) | module function_definition identifier parameters identifier identifier block return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier list_splat attribute identifier identifier | Returns the data_store filter implementation from the attribute. |
def view_indexes(self, done=None):
ret = []
if done is None:
done = set()
idx = 0
while idx < self.count():
if not idx in done:
break
idx += 1
while idx < self.count():
w = self.wp(idx)
if idx in done:
if w.x != 0 or w.y != 0:
ret.append(idx)
break
done.add(idx)
if w.command == mavutil.mavlink.MAV_CMD_DO_JUMP:
idx = int(w.param1)
w = self.wp(idx)
if w.x != 0 or w.y != 0:
ret.append(idx)
continue
if (w.x != 0 or w.y != 0) and self.is_location_command(w.command):
ret.append(idx)
idx += 1
return ret | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier list if_statement comparison_operator identifier none block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier integer while_statement comparison_operator identifier call attribute identifier identifier argument_list block if_statement not_operator comparison_operator identifier identifier block break_statement expression_statement augmented_assignment identifier integer while_statement comparison_operator identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier break_statement expression_statement call attribute identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier attribute attribute identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list identifier continue_statement if_statement boolean_operator parenthesized_expression boolean_operator comparison_operator attribute identifier identifier integer comparison_operator attribute identifier identifier integer call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement augmented_assignment identifier integer return_statement identifier | return a list waypoint indexes in view order |
def verbosedump(value, fn, compress=None):
print('Saving "%s"... (%s)' % (fn, type(value)))
dump(value, fn, compress=compress) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier call identifier argument_list identifier expression_statement call identifier argument_list identifier identifier keyword_argument identifier identifier | Verbose wrapper around dump |
def sync_groups_from_ad(self):
ad_list = ADGroupMapping.objects.values_list('ad_group', 'group')
mappings = {ad_group: group for ad_group, group in ad_list}
user_ad_groups = set(self.ad_groups.filter(groups__isnull=False).values_list(flat=True))
all_mapped_groups = set(mappings.values())
old_groups = set(self.groups.filter(id__in=all_mapped_groups).values_list(flat=True))
new_groups = set([mappings[x] for x in user_ad_groups])
groups_to_delete = old_groups - new_groups
if groups_to_delete:
self.groups.remove(*groups_to_delete)
groups_to_add = new_groups - old_groups
if groups_to_add:
self.groups.add(*groups_to_add) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier dictionary_comprehension pair identifier identifier for_in_clause pattern_list identifier identifier identifier expression_statement assignment identifier call identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier false identifier argument_list keyword_argument identifier true expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier identifier argument_list keyword_argument identifier true expression_statement assignment identifier call identifier argument_list list_comprehension subscript identifier identifier for_in_clause identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier | Determine which Django groups to add or remove based on AD groups. |
def format_exception(e):
from .utils.printing import fill
return '\n'.join(fill(line) for line in traceback.format_exception_only(type(e), e)) | module function_definition identifier parameters identifier block import_from_statement relative_import import_prefix dotted_name identifier identifier dotted_name identifier return_statement call attribute string string_start string_content escape_sequence string_end identifier generator_expression call identifier argument_list identifier for_in_clause identifier call attribute identifier identifier argument_list call identifier argument_list identifier identifier | Returns a string containing the type and text of the exception. |
def _check(self):
_logger.debug('Check if timeout.')
self._call_later_handle = None
if self._touch_time is not None:
difference = self._event_loop.time() - self._touch_time
_logger.debug('Time difference %s', difference)
if difference > self._timeout:
self._connection.close()
self._timed_out = True
if not self._connection.closed():
self._schedule() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier none if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier binary_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier true if_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list | Check and close connection if needed. |
def _get_conn():
try:
conn = psycopg2.connect(
host=__opts__['master_job_cache.postgres.host'],
user=__opts__['master_job_cache.postgres.user'],
password=__opts__['master_job_cache.postgres.passwd'],
database=__opts__['master_job_cache.postgres.db'],
port=__opts__['master_job_cache.postgres.port'])
except psycopg2.OperationalError:
log.error('Could not connect to SQL server: %s', sys.exc_info()[0])
return None
return conn | module function_definition identifier parameters block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end keyword_argument identifier subscript identifier string string_start string_content string_end except_clause attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end subscript call attribute identifier identifier argument_list integer return_statement none return_statement identifier | Return a postgres connection. |
def count(self):
args = self.format_args
if args is None or \
(isinstance(args, dict) and self.count_field not in args):
raise TypeError("count is required")
return args[self.count_field] if isinstance(args, dict) else args | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier if_statement boolean_operator comparison_operator identifier none line_continuation parenthesized_expression boolean_operator call identifier argument_list identifier identifier comparison_operator attribute identifier identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement conditional_expression subscript identifier attribute identifier identifier call identifier argument_list identifier identifier identifier | A count based on `count_field` and `format_args`. |
def roll(cls, num, sides, add):
rolls = []
for i in range(num):
rolls.append(random.randint(1, sides))
rolls.append(add)
return rolls | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier list for_statement identifier call identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list integer identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Rolls a die of sides sides, num times, sums them, and adds add |
def tabulate(lol, headers, eol='\n'):
yield '| %s |' % ' | '.join(headers) + eol
yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]) + eol
for row in lol:
yield '| %s |' % ' | '.join(str(c) for c in row) + eol | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content escape_sequence string_end block expression_statement yield binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement yield binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list list_comprehension binary_operator string string_start string_content string_end call identifier argument_list identifier for_in_clause identifier identifier identifier for_statement identifier identifier block expression_statement yield binary_operator binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier generator_expression call identifier argument_list identifier for_in_clause identifier identifier identifier | Use the pypi tabulate package instead! |
def list_wordpressess(self, service_id, version_number):
content = self._fetch("/service/%s/version/%d/wordpress" % (service_id, version_number))
return map(lambda x: FastlyWordpress(self, x), content) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement call identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier identifier identifier | Get all of the wordpresses for a specified service and version. |
def draw_edges(self):
if self.backend == "matplotlib":
for i, (n1, n2) in enumerate(self.edges):
x1, y1 = self.locs[n1]
x2, y2 = self.locs[n2]
color = self.edge_colors[i]
line = Line2D(
xdata=[x1, x2],
ydata=[y1, y2],
color=color,
zorder=0,
alpha=0.3,
)
self.ax.add_line(line)
elif self.backend == "altair":
marker_attrs = dict()
marker_attrs["color"] = "black"
marker_attrs["strokeWidth"] = 1
self.edge_chart = (
alt.Chart(self.edge_df)
.mark_line(**marker_attrs)
.encode(
alt.X(f"{self.node_lon}:Q"),
alt.Y(f"{self.node_lat}:Q"),
detail="edge",
)
) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment pattern_list identifier identifier subscript attribute identifier identifier identifier expression_statement assignment pattern_list identifier identifier subscript attribute identifier identifier identifier expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier list identifier identifier keyword_argument identifier list identifier identifier keyword_argument identifier identifier keyword_argument identifier integer keyword_argument identifier float expression_statement call attribute attribute identifier identifier identifier argument_list identifier elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment attribute identifier identifier parenthesized_expression call attribute call attribute call attribute identifier identifier argument_list attribute identifier identifier identifier argument_list dictionary_splat identifier identifier argument_list call attribute identifier identifier argument_list string string_start interpolation attribute identifier identifier string_content string_end call attribute identifier identifier argument_list string string_start interpolation attribute identifier identifier string_content string_end keyword_argument identifier string string_start string_content string_end | Draws edges to screen. |
def persist(self):
if self.object_hash:
data = dill.dumps(self.object_property)
f = ContentFile(data)
self.object_file.save(self.object_hash, f, save=False)
f.close()
self._persisted = True
return self._persisted | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier keyword_argument identifier false expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true return_statement attribute identifier identifier | a private method that persists an estimator object to the filesystem |
def wind_shear(shear: str, unit_alt: str = 'ft', unit_wind: str = 'kt') -> str:
unit_alt = SPOKEN_UNITS.get(unit_alt, unit_alt)
unit_wind = SPOKEN_UNITS.get(unit_wind, unit_wind)
return translate.wind_shear(shear, unit_alt, unit_wind, spoken=True) or 'Wind shear unknown' | module function_definition identifier parameters typed_parameter identifier type identifier typed_default_parameter identifier type identifier string string_start string_content string_end typed_default_parameter identifier type identifier string string_start string_content string_end type identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement boolean_operator call attribute identifier identifier argument_list identifier identifier identifier keyword_argument identifier true string string_start string_content string_end | Format wind shear string into a spoken word string |
def intersection(self, other):
taxa1 = self.labels
taxa2 = other.labels
return taxa1 & taxa2 | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier return_statement binary_operator identifier identifier | Returns the intersection of the taxon sets of two Trees |
def full_path(base, fmt):
ext = fmt['extension']
suffix = fmt.get('suffix')
prefix = fmt.get('prefix')
full = base
if prefix:
prefix_dir, prefix_file_name = os.path.split(prefix)
notebook_dir, notebook_file_name = os.path.split(base)
sep = base[len(notebook_dir):-len(notebook_file_name)] or '/'
prefix_dir = prefix_dir.replace('/', sep)
if prefix_file_name:
notebook_file_name = prefix_file_name + notebook_file_name
if prefix_dir:
if notebook_dir and not notebook_dir.endswith(sep):
notebook_dir = notebook_dir + sep
notebook_dir = notebook_dir + prefix_dir
if notebook_dir and not notebook_dir.endswith(sep):
notebook_dir = notebook_dir + sep
full = notebook_dir + notebook_file_name
if suffix:
full = full + suffix
return full + ext | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier identifier if_statement identifier block expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier boolean_operator subscript identifier slice call identifier argument_list identifier unary_operator call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement identifier block expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block if_statement boolean_operator identifier not_operator call attribute identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement boolean_operator identifier not_operator call attribute identifier identifier argument_list identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment identifier binary_operator identifier identifier if_statement identifier block expression_statement assignment identifier binary_operator identifier identifier return_statement binary_operator identifier identifier | Return the full path for the notebook, given the base path |
def aligner_from_header(in_bam):
from bcbio.pipeline.alignment import TOOLS
with pysam.Samfile(in_bam, "rb") as bamfile:
for pg in bamfile.header.get("PG", []):
for ka in TOOLS.keys():
if pg.get("PN", "").lower().find(ka) >= 0:
return ka | module function_definition identifier parameters identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end list block for_statement identifier call attribute identifier identifier argument_list block if_statement comparison_operator call attribute call attribute call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier argument_list identifier argument_list identifier integer block return_statement identifier | Identify aligner from the BAM header; handling pre-aligned inputs. |
def ikev2scan(ip, **kwargs):
return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),
exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs) | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list binary_operator binary_operator binary_operator call identifier argument_list keyword_argument identifier identifier call identifier argument_list call identifier argument_list keyword_argument identifier call identifier argument_list integer keyword_argument identifier integer call identifier argument_list keyword_argument identifier call identifier argument_list dictionary_splat identifier | Send a IKEv2 SA to an IP and wait for answers. |
def load_config_from_file(app, filepath):
try:
app.config.from_pyfile(filepath)
return True
except IOError:
print("Did not find settings file %s for additional settings, skipping it" % filepath, file=sys.stderr)
return False | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement true except_clause identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier attribute identifier identifier return_statement false | Helper function to load config from a specified file |
def _get_dispatches_for_update(filter_kwargs):
dispatches = Dispatch.objects.prefetch_related('message').filter(
**filter_kwargs
).select_for_update(
**GET_DISPATCHES_ARGS[1]
).order_by('-message__time_created')
try:
dispatches = list(dispatches)
except NotSupportedError:
return None
except DatabaseError:
return []
return dispatches | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute call attribute call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier argument_list dictionary_splat identifier identifier argument_list dictionary_splat subscript identifier integer identifier argument_list string string_start string_content string_end try_statement block expression_statement assignment identifier call identifier argument_list identifier except_clause identifier block return_statement none except_clause identifier block return_statement list return_statement identifier | Distributed friendly version using ``select for update``. |
def discovery(self, compute_resource):
if compute_resource is None:
cr_list = ComputeResource.all(self.client)
print("ERROR: You must specify a ComputeResource.")
print("Available ComputeResource's:")
for cr in cr_list:
print(cr.name)
sys.exit(1)
try:
ccr = ComputeResource.get(self.client, name=compute_resource)
except ObjectNotFoundError:
print("ERROR: Could not find ComputeResource with name %s" %
compute_resource)
sys.exit(1)
print('Cluster: %s (%s hosts)' % (ccr.name, len(ccr.host)))
ccr.preload("host", properties=["name", "vm"])
for host in ccr.host:
print(' Host: %s (%s VMs)' % (host.name, len(host.vm)))
host.preload("vm", properties=["name"])
for vm in host.vm:
print(' VM: %s' % vm.name) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier 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 for_statement identifier identifier block expression_statement call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list integer try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier identifier except_clause identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer 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 expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier list string string_start string_content string_end string string_start string_content string_end for_statement identifier attribute identifier identifier block 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 expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier list string string_start string_content string_end for_statement identifier attribute identifier identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | An example that discovers hosts and VMs in the inventory. |
def log_message(self, msg, *args):
if args:
msg = msg % args
self.logger.info(msg) | module function_definition identifier parameters identifier identifier list_splat_pattern identifier block if_statement identifier block expression_statement assignment identifier binary_operator identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Hook to log a message. |
def ConsultarLocalidades(self, cod_provincia, sep="||"):
"Consulta las localidades habilitadas"
ret = self.client.consultarLocalidadesPorProvincia(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
solicitud={'codProvincia': cod_provincia},
)['respuesta']
self.__analizar_errores(ret)
array = ret.get('localidad', [])
if sep is None:
return dict([(it['codigo'], it['descripcion']) for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigo'], it['descripcion']) for it in array] | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument 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 keyword_argument identifier dictionary pair string string_start string_content string_end identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list if_statement comparison_operator identifier none block return_statement call identifier argument_list list_comprehension tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier identifier else_clause block return_statement list_comprehension binary_operator parenthesized_expression binary_operator string string_start string_content string_end tuple identifier identifier identifier tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier identifier | Consulta las localidades habilitadas |
def write_eof(self):
self._check_status()
if not self._writable:
raise TransportError('transport is not writable')
if self._closing:
raise TransportError('transport is closing')
try:
self._handle.shutdown(self._on_write_complete)
except pyuv.error.UVError as e:
self._error = TransportError.from_errno(e.args[0])
self.abort()
raise compat.saved_exc(self._error)
self._write_buffer_size += 1 | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list subscript attribute identifier identifier integer expression_statement call attribute identifier identifier argument_list raise_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement augmented_assignment attribute identifier identifier integer | Shut down the write direction of the transport. |
def POST(self, id):
id = int(id)
model.del_todo(id)
raise web.seeother('/') | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier raise_statement call attribute identifier identifier argument_list string string_start string_content string_end | Delete based on ID |
def run(app, appbuilder, host, port, debug):
_appbuilder = import_application(app, appbuilder)
_appbuilder.get_app.run(host=host, port=port, debug=debug) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Runs Flask dev web server. |
def volume_detach(self,
name,
timeout=300):
try:
volume = self.volume_show(name)
except KeyError as exc:
raise SaltCloudSystemExit('Unable to find {0} volume: {1}'.format(name, exc))
if not volume['attachments']:
return True
response = self.compute_conn.volumes.delete_server_volume(
volume['attachments'][0]['server_id'],
volume['attachments'][0]['id']
)
trycount = 0
start = time.time()
while True:
trycount += 1
try:
response = self._volume_get(volume['id'])
if response['status'] == 'available':
return response
except Exception as exc:
log.debug('Volume is detaching: %s', name)
time.sleep(1)
if time.time() - start > timeout:
log.error('Timed out after %d seconds '
'while waiting for data', timeout)
return False
log.debug(
'Retrying volume_show() (try %d)', trycount
) | module function_definition identifier parameters identifier identifier default_parameter identifier integer block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier if_statement not_operator subscript identifier string string_start string_content string_end block return_statement true expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list subscript subscript subscript identifier string string_start string_content string_end integer string string_start string_content string_end subscript subscript subscript identifier string string_start string_content string_end integer string string_start string_content string_end expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list while_statement true block expression_statement augmented_assignment identifier integer try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block return_statement identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement call attribute identifier identifier argument_list integer if_statement comparison_operator binary_operator call attribute identifier identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end identifier return_statement false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier | Detach a block device |
def read(file_or_stream, fmt, as_version=4, **kwargs):
fmt = long_form_one_format(fmt)
if fmt['extension'] == '.ipynb':
notebook = nbformat.read(file_or_stream, as_version, **kwargs)
rearrange_jupytext_metadata(notebook.metadata)
return notebook
return reads(file_or_stream.read(), fmt, **kwargs) | module function_definition identifier parameters identifier identifier default_parameter identifier integer dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator subscript identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier dictionary_splat identifier expression_statement call identifier argument_list attribute identifier identifier return_statement identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier dictionary_splat identifier | Read a notebook from a file |
def report_pyflakes(document):
reporter = _FlakesReporter()
pyflakes.api.check(document.text, '', reporter=reporter)
def format_flake_message(message):
return [
('class:flakemessage.prefix', 'pyflakes:'),
('', ' '),
('class:flakemessage', message.message % message.message_args)
]
def message_to_reporter_error(message):
start_index = document.translate_row_col_to_index(message.lineno - 1, message.col)
end_index = start_index
while end_index < len(document.text) and document.text[end_index] in WORD_CHARACTERS:
end_index += 1
return ReporterError(lineno=message.lineno - 1,
start_column=message.col,
end_column=message.col + end_index - start_index,
formatted_text=format_flake_message(message))
return [message_to_reporter_error(m) for m in reporter.messages] | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_end keyword_argument identifier identifier function_definition identifier parameters identifier block return_statement list tuple string string_start string_content string_end string string_start string_content string_end tuple string string_start string_end string string_start string_content string_end tuple string string_start string_content string_end binary_operator attribute identifier identifier attribute identifier identifier function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator attribute identifier identifier integer attribute identifier identifier expression_statement assignment identifier identifier while_statement boolean_operator comparison_operator identifier call identifier argument_list attribute identifier identifier comparison_operator subscript attribute identifier identifier identifier identifier block expression_statement augmented_assignment identifier integer return_statement call identifier argument_list keyword_argument identifier binary_operator attribute identifier identifier integer keyword_argument identifier attribute identifier identifier keyword_argument identifier binary_operator binary_operator attribute identifier identifier identifier identifier keyword_argument identifier call identifier argument_list identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier attribute identifier identifier | Run pyflakes on document and return list of ReporterError instances. |
def clean(self, *args, **kwargs):
if not self.pk:
node = self.node
if node.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this node")
if 'nodeshot.core.layers' in settings.INSTALLED_APPS:
layer = node.layer
if layer.participation_settings.comments_allowed is False:
raise ValidationError("Comments not allowed for this layer") | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier false block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier false block raise_statement call identifier argument_list string string_start string_content string_end | Check if comments can be inserted for parent node or parent layer |
def replace(self, source, dest):
for i, broker in enumerate(self.replicas):
if broker == source:
self.replicas[i] = dest
return | module function_definition identifier parameters identifier identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier return_statement | Replace source broker with destination broker in replica set if found. |
def CallLoggedAndAccounted(f):
@functools.wraps(f)
def Decorator(*args, **kwargs):
try:
start_time = time.time()
result = f(*args, **kwargs)
latency = time.time() - start_time
stats_collector_instance.Get().RecordEvent(
"db_request_latency", latency, fields=[f.__name__])
logging.debug("DB request %s SUCCESS (%.3fs)", f.__name__, latency)
return result
except db.Error as e:
stats_collector_instance.Get().IncrementCounter(
"db_request_errors", fields=[f.__name__, "grr"])
logging.debug("DB request %s GRR ERROR: %s", f.__name__,
utils.SmartUnicode(e))
raise
except Exception as e:
stats_collector_instance.Get().IncrementCounter(
"db_request_errors", fields=[f.__name__, "db"])
logging.debug("DB request %s INTERNAL DB ERROR : %s", f.__name__,
utils.SmartUnicode(e))
raise
return Decorator | module function_definition identifier parameters identifier block decorated_definition decorator call attribute identifier identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end identifier keyword_argument identifier list attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier identifier return_statement identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end keyword_argument identifier list attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list identifier raise_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end keyword_argument identifier list attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list identifier raise_statement return_statement identifier | Decorator to log and account for a DB call. |
def _parse_key(key):
splt = key.split("\\")
hive = splt.pop(0)
key = '\\'.join(splt)
return hive, key | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier return_statement expression_list identifier identifier | split the hive from the key |
def push(**kwargs):
output, err = cli_syncthing_adapter.refresh(**kwargs)
if output:
click.echo("%s" % output, err=err)
if kwargs['verbose'] and not err:
with click.progressbar(
iterable=None,
length=100,
label='Synchronizing') as bar:
device_num = 0
max_devices = 1
prev_percent = 0
while True:
kwargs['progress'] = True
kwargs['device_num'] = device_num
data, err = cli_syncthing_adapter.refresh(**kwargs)
device_num = data['device_num']
max_devices = data['max_devices']
cur_percent = math.floor(data['percent']) - prev_percent
if cur_percent > 0:
bar.update(cur_percent)
prev_percent = math.floor(data['percent'])
if device_num < max_devices:
time.sleep(0.5)
else:
break | module function_definition identifier parameters dictionary_splat_pattern identifier block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list dictionary_splat identifier if_statement identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier identifier if_statement boolean_operator subscript identifier string string_start string_content string_end not_operator identifier block with_statement with_clause with_item as_pattern call attribute identifier identifier argument_list keyword_argument identifier none keyword_argument identifier integer keyword_argument identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer expression_statement assignment identifier integer while_statement true block expression_statement assignment subscript identifier string string_start string_content string_end true expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list dictionary_splat identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier binary_operator call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end identifier if_statement comparison_operator identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end if_statement comparison_operator identifier identifier block expression_statement call attribute identifier identifier argument_list float else_clause block break_statement | Force synchronization of directory. |
def choice(anon, obj, field, val):
return anon.faker.choice(field=field) | module function_definition identifier parameters identifier identifier identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier | Randomly chooses one of the choices set on the field. |
def login(self, username, password, application, application_url):
logger.debug(str((username, application, application_url)))
method = self._anaconda_client_api.authenticate
return self._create_worker(method, username, password, application,
application_url) | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list tuple identifier identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier identifier | Login to anaconda cloud. |
def textContent(self, text: str) -> None:
if self._inner_element:
self._inner_element.textContent = text
else:
super().textContent = text | module function_definition identifier parameters identifier typed_parameter identifier type identifier type none block if_statement attribute identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier identifier else_clause block expression_statement assignment attribute call identifier argument_list identifier identifier | Set text content to inner node. |
def in_reply_to(self) -> Optional[UnstructuredHeader]:
try:
return cast(UnstructuredHeader, self[b'in-reply-to'][0])
except (KeyError, IndexError):
return None | module function_definition identifier parameters identifier type generic_type identifier type_parameter type identifier block try_statement block return_statement call identifier argument_list identifier subscript subscript identifier string string_start string_content string_end integer except_clause tuple identifier identifier block return_statement none | The ``In-Reply-To`` header. |
def randbetween(ctx, bottom, top):
bottom = conversions.to_integer(bottom, ctx)
top = conversions.to_integer(top, ctx)
return random.randint(bottom, top) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier | Returns a random integer number between the numbers you specify |
def _save_traceback_history(self, status, trace, job_exc):
failure_date = datetime.datetime.utcnow()
new_history = {
"date": failure_date,
"status": status,
"exceptiontype": job_exc.__name__
}
traces = trace.split("---- Original exception: -----")
if len(traces) > 1:
new_history["original_traceback"] = traces[1]
worker = context.get_current_worker()
if worker:
new_history["worker"] = worker.id
new_history["traceback"] = traces[0]
self.collection.update({
"_id": self.id
}, {"$push": {"traceback_history": new_history}}) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator call identifier argument_list identifier integer block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair string string_start string_content string_end attribute identifier identifier dictionary pair string string_start string_content string_end dictionary pair string string_start string_content string_end identifier | Create traceback history or add a new traceback to history. |
def check_webhook_validation(app_configs=None, **kwargs):
from . import settings as djstripe_settings
messages = []
validation_options = ("verify_signature", "retrieve_event")
if djstripe_settings.WEBHOOK_VALIDATION is None:
messages.append(
checks.Warning(
"Webhook validation is disabled, this is a security risk if the webhook view is enabled",
hint="Set DJSTRIPE_WEBHOOK_VALIDATION to one of {}".format(
", ".join(validation_options)
),
id="djstripe.W004",
)
)
elif djstripe_settings.WEBHOOK_VALIDATION == "verify_signature":
if not djstripe_settings.WEBHOOK_SECRET:
messages.append(
checks.Critical(
"DJSTRIPE_WEBHOOK_VALIDATION='verify_signature' but DJSTRIPE_WEBHOOK_SECRET is not set",
hint="Set DJSTRIPE_WEBHOOK_SECRET or set DJSTRIPE_WEBHOOK_VALIDATION='retrieve_event'",
id="djstripe.C006",
)
)
elif djstripe_settings.WEBHOOK_VALIDATION not in validation_options:
messages.append(
checks.Critical(
"DJSTRIPE_WEBHOOK_VALIDATION is invalid",
hint="Set DJSTRIPE_WEBHOOK_VALIDATION to one of {} or None".format(
", ".join(validation_options)
),
id="djstripe.C007",
)
)
return messages | module function_definition identifier parameters default_parameter identifier none dictionary_splat_pattern identifier block import_from_statement relative_import import_prefix aliased_import dotted_name identifier identifier expression_statement assignment identifier list expression_statement assignment identifier tuple string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block if_statement not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier string string_start string_content string_end elif_clause comparison_operator attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier string string_start string_content string_end return_statement identifier | Check that DJSTRIPE_WEBHOOK_VALIDATION is valid |
def _summarize_peaks(peaks):
previous = peaks[0]
new_peaks = [previous]
for pos in peaks:
if pos > previous + 10:
new_peaks.add(pos)
previous = pos
return new_peaks | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier list identifier for_statement identifier identifier block if_statement comparison_operator identifier binary_operator identifier integer block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier return_statement identifier | merge peaks position if closer than 10 |
async def load_user(self, request):
if USER_KEY not in request:
session = await self.load(request)
if 'id' not in session:
return None
request[USER_KEY] = request.user = await self._user_loader(session['id'])
return request[USER_KEY] | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list identifier if_statement comparison_operator string string_start string_content string_end identifier block return_statement none expression_statement assignment subscript identifier identifier assignment attribute identifier identifier await call attribute identifier identifier argument_list subscript identifier string string_start string_content string_end return_statement subscript identifier identifier | Load user from request. |
def _iter_restrict(self, zeros, ones):
inputs = list(self.inputs)
unmapped = dict()
for i, v in enumerate(self.inputs):
if v in zeros:
inputs[i] = 0
elif v in ones:
inputs[i] = 1
else:
unmapped[v] = i
vs = sorted(unmapped.keys())
for num in range(1 << len(vs)):
for v, val in boolfunc.num2point(num, vs).items():
inputs[unmapped[v]] = val
yield sum((val << i) for i, val in enumerate(inputs)) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier integer elif_clause comparison_operator identifier identifier block expression_statement assignment subscript identifier identifier integer else_clause block expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list for_statement identifier call identifier argument_list binary_operator integer call identifier argument_list identifier block for_statement pattern_list identifier identifier call attribute call attribute identifier identifier argument_list identifier identifier identifier argument_list block expression_statement assignment subscript identifier subscript identifier identifier identifier expression_statement yield call identifier generator_expression parenthesized_expression binary_operator identifier identifier for_in_clause pattern_list identifier identifier call identifier argument_list identifier | Iterate through indices of all table entries that vary. |
def _setup_authentication(self, username, password):
if self.version < 1.1:
if not username:
username = self._key
self._key = None
if not username:
return
if not password:
password = '12345'
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_mgr.add_password(None, self._url, username, password )
handler = urllib2.HTTPBasicAuthHandler( password_mgr )
self._opener = urllib2.build_opener( handler )
self._opener.open( self._url )
urllib2.install_opener( self._opener ) | module function_definition identifier parameters identifier identifier identifier block if_statement comparison_operator attribute identifier identifier float block if_statement not_operator identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment attribute identifier identifier none if_statement not_operator identifier block return_statement if_statement not_operator identifier block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list none attribute identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier | Create the authentication object with the given credentials. |
def main(cls):
chain = cls.create()
args = chain._run_argparser(sys.argv[1:])
chain._run_chain(sys.stdout, args.dry_run)
chain._finalize(args.dry_run) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier slice integer 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 | Hook to run this `Chain` from the command line |
def add_seq(self, seq):
self.buffer.append(seq)
self.buf_count += 1
if self.buf_count % self.buffer_size == 0: self.flush() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement augmented_assignment attribute identifier identifier integer if_statement comparison_operator binary_operator attribute identifier identifier attribute identifier identifier integer block expression_statement call attribute identifier identifier argument_list | Use this method to add a SeqRecord object to this fasta. |
def add_product_version_to_build_configuration(id=None, name=None, product_version_id=None):
data = remove_product_version_from_build_configuration_raw(id, name, product_version_id)
if data:
return utils.format_json_list(data) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier identifier if_statement identifier block return_statement call attribute identifier identifier argument_list identifier | Associate an existing ProductVersion with a BuildConfiguration |
def authorize_url(self, state=''):
url = 'https://openapi.youku.com/v2/oauth2/authorize?'
params = {
'client_id': self.client_id,
'response_type': 'code',
'state': state,
'redirect_uri': self.redirect_uri
}
return url + urlencode(params) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier return_statement binary_operator identifier call identifier argument_list identifier | return user authorize url |
def opls_notation(atom_key):
conflicts = ['ne', 'he', 'na']
if atom_key in conflicts:
raise _AtomKeyConflict((
"One of the OPLS conflicting "
"atom_keys has occured '{0}'. "
"For how to solve this issue see the manual or "
"MolecularSystem._atom_key_swap() doc string.").format(atom_key))
for element in opls_atom_keys:
if atom_key in opls_atom_keys[element]:
return element
raise _AtomKeyError((
"OPLS atom key {0} was not found in OPLS keys dictionary.").format(
atom_key)) | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier for_statement identifier identifier block if_statement comparison_operator identifier subscript identifier identifier block return_statement identifier raise_statement call identifier argument_list call attribute parenthesized_expression string string_start string_content string_end identifier argument_list identifier | Return element for OPLS forcefield atom key. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.