code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def lookup_users(self, user_ids=None, screen_names=None, include_entities=None, tweet_mode=None):
post_data = {}
if include_entities is not None:
include_entities = 'true' if include_entities else 'false'
post_data['include_entities'] = include_entities
if user_ids:
post_data['user_id'] = list_to_csv(user_ids)
if screen_names:
post_data['screen_name'] = list_to_csv(screen_names)
if tweet_mode:
post_data['tweet_mode'] = tweet_mode
return self._lookup_users(post_data=post_data) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary if_statement comparison_operator identifier none block expression_statement assignment identifier conditional_expression string string_start string_content string_end identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list keyword_argument identifier identifier | Perform bulk look up of users from user ID or screen_name |
def _set_scroll(self, *args):
self._canvas_scroll.xview(*args)
self._canvas_ticks.xview(*args) | module function_definition identifier parameters identifier list_splat_pattern identifier block expression_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier expression_statement call attribute attribute identifier identifier identifier argument_list list_splat identifier | Set horizontal scroll of scroll container and ticks Canvas |
def salt_syndic():
import salt.utils.process
salt.utils.process.notify_systemd()
import salt.cli.daemons
pid = os.getpid()
try:
syndic = salt.cli.daemons.Syndic()
syndic.start()
except KeyboardInterrupt:
os.kill(pid, 15) | module function_definition identifier parameters block import_statement dotted_name identifier identifier identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list import_statement dotted_name identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list except_clause identifier block expression_statement call attribute identifier identifier argument_list identifier integer | Start the salt syndic. |
def bisine_wahwah_wave(frequency):
waves_a = bisine_wave(frequency)
waves_b = tf.reverse(waves_a, axis=[2])
iterations = 4
xs = tf.reshape(tf.range(_samples(), dtype=tf.float32), [1, _samples(), 1])
thetas = xs / _samples() * iterations
ts = (tf.sin(math.pi * 2 * thetas) + 1) / 2
wave = ts * waves_a + (1.0 - ts) * waves_b
exaggerated_wave = wave ** 3.0
return tf.concat([wave, exaggerated_wave], axis=0) | 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 identifier keyword_argument identifier list integer expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list call identifier argument_list keyword_argument identifier attribute identifier identifier list integer call identifier argument_list integer expression_statement assignment identifier binary_operator binary_operator identifier call identifier argument_list identifier expression_statement assignment identifier binary_operator parenthesized_expression binary_operator call attribute identifier identifier argument_list binary_operator binary_operator attribute identifier identifier integer identifier integer integer expression_statement assignment identifier binary_operator binary_operator identifier identifier binary_operator parenthesized_expression binary_operator float identifier identifier expression_statement assignment identifier binary_operator identifier float return_statement call attribute identifier identifier argument_list list identifier identifier keyword_argument identifier integer | Emit two sine waves with balance oscillating left and right. |
def safe_import(self, name):
module = None
if name not in self._modules:
self._modules[name] = importlib.import_module(name)
module = self._modules[name]
if not module:
dist = next(iter(
dist for dist in self.base_working_set if dist.project_name == name
), None)
if dist:
dist.activate()
module = importlib.import_module(name)
if name in sys.modules:
try:
six.moves.reload_module(module)
six.moves.reload_module(sys.modules[name])
except TypeError:
del sys.modules[name]
sys.modules[name] = self._modules[name]
return module | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier subscript attribute identifier identifier identifier if_statement not_operator identifier block expression_statement assignment identifier call identifier argument_list call identifier generator_expression identifier for_in_clause identifier attribute identifier identifier if_clause comparison_operator attribute identifier identifier identifier none if_statement identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list subscript attribute identifier identifier identifier except_clause identifier block delete_statement subscript attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier subscript attribute identifier identifier identifier return_statement identifier | Helper utility for reimporting previously imported modules while inside the env |
def add_tags(self, tags):
if isinstance(tags, (str, unicode)):
tags = [tags]
objs = object_session(self)
tmps = [FeedTag(tag=t, feed=self) for t in tags]
objs.add_all(tmps)
objs.commit() | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier tuple identifier identifier block expression_statement assignment identifier list identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier for_in_clause identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list | add a tag or tags to a Feed |
def timeout(self, value):
if not self.params:
self.params = dict(timeout=value)
return self
self.params['timeout'] = value
return self | module function_definition identifier parameters identifier identifier block if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier identifier return_statement identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end identifier return_statement identifier | Specifies a timeout on the search query |
def info(cls, name, get_state=True, get_pid=True):
command = ['lxc-info', '-n', name]
response = subwrap.run(command)
lines = map(split_info_line, response.std_out.splitlines())
return dict(lines) | module function_definition identifier parameters identifier identifier default_parameter identifier true default_parameter identifier true block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier call attribute attribute identifier identifier identifier argument_list return_statement call identifier argument_list identifier | Retrieves and parses info about an LXC |
def Output(self):
self.Open()
self.Header()
self.Body()
self.Footer() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | Output all sections of the page. |
def _ensure_content_type():
from django.contrib.contenttypes.models import ContentType
try:
row = ContentType.objects.get(app_label=PERM_APP_NAME)
except ContentType.DoesNotExist:
row = ContentType(name=PERM_APP_NAME, app_label=PERM_APP_NAME, model=PERM_APP_NAME)
row.save()
return row.id | module function_definition identifier parameters block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier try_statement block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier except_clause attribute identifier identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list return_statement attribute identifier identifier | Add the bulldog content type to the database if it's missing. |
def ir_instrs(self):
ir_instrs = []
for asm_instr in self._instrs:
ir_instrs += asm_instr.ir_instrs
return ir_instrs | module function_definition identifier parameters identifier block expression_statement assignment identifier list for_statement identifier attribute identifier identifier block expression_statement augmented_assignment identifier attribute identifier identifier return_statement identifier | Get gadgets IR instructions. |
def _fall(self):
a = self._array
for column in [a[:, c] for c in range(a.shape[1])]:
target_p = column.shape[0] - 1
fall_distance = 1
while target_p - fall_distance >= 0:
if column[target_p].is_blank():
blank = column[target_p]
while target_p - fall_distance >= 0:
next_p = target_p - fall_distance
if column[next_p].is_blank():
fall_distance += 1
else:
break
if target_p - fall_distance >= 0:
source_position = target_p - fall_distance
column[target_p] = column[source_position]
column[source_position] = blank
target_p -= 1 | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement identifier list_comprehension subscript identifier slice identifier for_in_clause identifier call identifier argument_list subscript attribute identifier identifier integer block expression_statement assignment identifier binary_operator subscript attribute identifier identifier integer integer expression_statement assignment identifier integer while_statement comparison_operator binary_operator identifier identifier integer block if_statement call attribute subscript identifier identifier identifier argument_list block expression_statement assignment identifier subscript identifier identifier while_statement comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier binary_operator identifier identifier if_statement call attribute subscript identifier identifier identifier argument_list block expression_statement augmented_assignment identifier integer else_clause block break_statement if_statement comparison_operator binary_operator identifier identifier integer block expression_statement assignment identifier binary_operator identifier identifier expression_statement assignment subscript identifier identifier subscript identifier identifier expression_statement assignment subscript identifier identifier identifier expression_statement augmented_assignment identifier integer | Cause tiles to fall down to fill blanks below them. |
def clean_descriptor(self, number):
self.descriptors[number]['stdout'].close()
self.descriptors[number]['stderr'].close()
if os.path.exists(self.descriptors[number]['stdout_path']):
os.remove(self.descriptors[number]['stdout_path'])
if os.path.exists(self.descriptors[number]['stderr_path']):
os.remove(self.descriptors[number]['stderr_path']) | module function_definition identifier parameters identifier identifier block expression_statement call attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier argument_list expression_statement call attribute subscript subscript attribute identifier identifier identifier string string_start string_content string_end identifier argument_list if_statement call attribute attribute identifier identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list subscript subscript attribute identifier identifier identifier string string_start string_content string_end | Close file descriptor and remove underlying files. |
def raise_api_error(resp, state=None):
error_code = resp.status_code
if error_code == 402:
error_message = (
"Please add a payment method to upload more samples. If you continue to "
"experience problems, contact us at help@onecodex.com for assistance."
)
elif error_code == 403:
error_message = "Please login to your One Codex account or pass the appropriate API key."
else:
try:
error_json = resp.json()
except ValueError:
error_json = {}
if "msg" in error_json:
error_message = error_json["msg"].rstrip(".")
elif "message" in error_json:
error_message = error_json["message"].rstrip(".")
else:
error_message = None
if state == "init" and not error_message:
error_message = (
"Could not initialize upload. Are you logged in? If this problem "
"continues, please contact help@onecodex.com for assistance."
)
elif state == "upload" and not error_message:
error_message = (
"File could not be uploaded. If this problem continues, please contact "
"help@onecodex.com for assistance."
)
elif state == "callback" and not error_message:
error_message = (
"Callback could not be completed. If this problem continues, please "
"contact help@onecodex.com for assistance."
)
if error_message is None:
error_message = "Upload failed. Please contact help@onecodex.com for assistance."
raise UploadException(error_message) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier integer block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end else_clause block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause identifier block expression_statement assignment identifier dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end elif_clause comparison_operator string string_start string_content string_end identifier block expression_statement assignment identifier call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end else_clause block expression_statement assignment identifier none if_statement boolean_operator comparison_operator identifier string string_start string_content string_end not_operator identifier block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause boolean_operator comparison_operator identifier string string_start string_content string_end not_operator identifier block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end elif_clause boolean_operator comparison_operator identifier string string_start string_content string_end not_operator identifier block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list identifier | Raise an exception with a pretty message in various states of upload |
def codestr2rst(codestr, lang='python', lineno=None):
if lineno is not None:
if LooseVersion(sphinx.__version__) >= '1.3':
blank_lines = codestr.count('\n', 0, -len(codestr.lstrip()))
lineno = ' :lineno-start: {0}\n'.format(lineno + blank_lines)
else:
lineno = ' :linenos:\n'
else:
lineno = ''
code_directive = "\n.. code-block:: {0}\n{1}\n".format(lang, lineno)
indented_block = indent(codestr, ' ' * 4)
return code_directive + indented_block | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none block if_statement comparison_operator identifier none block if_statement comparison_operator call identifier argument_list attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end integer unary_operator call identifier argument_list call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list binary_operator identifier identifier else_clause block expression_statement assignment identifier string string_start string_content escape_sequence string_end else_clause block expression_statement assignment identifier string string_start string_end expression_statement assignment identifier call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier binary_operator string string_start string_content string_end integer return_statement binary_operator identifier identifier | Return reStructuredText code block from code string |
def _xmlTextReaderErrorFunc(xxx_todo_changeme,msg,severity,locator):
(f,arg) = xxx_todo_changeme
return f(arg,msg,severity,xmlTextReaderLocator(locator)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier return_statement call identifier argument_list identifier identifier identifier call identifier argument_list identifier | Intermediate callback to wrap the locator |
def dumb_property_dict(style):
return dict([(x.strip(), y.strip()) for x, y in [z.split(':', 1) for z in style.split(';') if ':' in z]]); | module function_definition identifier parameters identifier block return_statement call identifier argument_list list_comprehension tuple call attribute identifier identifier argument_list call attribute identifier identifier argument_list for_in_clause pattern_list identifier identifier list_comprehension call attribute identifier identifier argument_list string string_start string_content string_end integer for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content string_end if_clause comparison_operator string string_start string_content string_end identifier | returns a hash of css attributes |
def plot_trunc_gr_model(
aval, bval, min_mag, max_mag, dmag,
catalogue=None, completeness=None, filename=None,
figure_size=(8, 6), filetype='png', dpi=300, ax=None):
input_model = TruncatedGRMFD(min_mag, max_mag, dmag, aval, bval)
if not catalogue:
annual_rates, cumulative_rates = _get_recurrence_model(input_model)
if ax is None:
fig, ax = plt.subplots(figsize=figure_size)
else:
fig = ax.get_figure()
ax.semilogy(annual_rates[:, 0], annual_rates[:, 1], 'b-')
ax.semilogy(annual_rates[:, 0], cumulative_rates, 'r-')
ax.xlabel('Magnitude')
ax.set_ylabel('Annual Rate')
ax.set_legend(['Incremental Rate', 'Cumulative Rate'])
_save_image(fig, filename, filetype, dpi)
else:
completeness = _check_completeness_table(completeness, catalogue)
plot_recurrence_model(
input_model, catalogue, completeness, dmag, filename=filename,
figure_size=figure_size, filetype=filetype, dpi=dpi, ax=ax) | module function_definition identifier parameters identifier identifier identifier identifier identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier tuple integer integer default_parameter identifier string string_start string_content string_end default_parameter identifier integer default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier if_statement not_operator identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list subscript identifier slice integer subscript identifier slice integer string string_start string_content string_end expression_statement call attribute identifier identifier argument_list subscript identifier slice integer identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list list string string_start string_content string_end string string_start string_content string_end expression_statement call identifier argument_list identifier identifier identifier identifier else_clause block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Plots a Gutenberg-Richter model |
def manage_config(cmd, *args):
if cmd == "file":
print(config.config_file)
elif cmd == "show":
with open(config.config_file) as f:
print(f.read())
elif cmd == "generate":
fname = os.path.join(
user_config_dir("genomepy"), "{}.yaml".format("genomepy")
)
if not os.path.exists(user_config_dir("genomepy")):
os.makedirs(user_config_dir("genomepy"))
with open(fname, "w") as fout:
with open(config.config_file) as fin:
fout.write(fin.read())
print("Created config file {}".format(fname)) | module function_definition identifier parameters identifier list_splat_pattern identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list attribute identifier identifier elif_clause comparison_operator identifier string string_start string_content string_end block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement call identifier argument_list call attribute identifier identifier argument_list elif_clause comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list call identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end 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 with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Manage genomepy config file. |
def new( self, min, max ):
assert MIN <= min <= max <= MAX
self.min = min
self.max = max
self.offsets = offsets_for_max_size( max )
self.bin_count = bin_for_range( max - 1, max, offsets = self.offsets ) + 1
self.bins = [ [] for i in range( self.bin_count ) ] | module function_definition identifier parameters identifier identifier identifier block assert_statement comparison_operator identifier identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier binary_operator call identifier argument_list binary_operator identifier integer identifier keyword_argument identifier attribute identifier identifier integer expression_statement assignment attribute identifier identifier list_comprehension list for_in_clause identifier call identifier argument_list attribute identifier identifier | Create an empty index for intervals in the range min, max |
def validate_parent_id(self, key, parent_id):
id_ = getattr(self, 'id', None)
if id_ is not None and parent_id is not None:
assert id_ != parent_id, 'Can not be attached to itself.'
return parent_id | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call identifier argument_list identifier string string_start string_content string_end none if_statement boolean_operator comparison_operator identifier none comparison_operator identifier none block assert_statement comparison_operator identifier identifier string string_start string_content string_end return_statement identifier | Parent has to be different from itself. |
def command(results_dir, result_id):
campaign = sem.CampaignManager.load(results_dir)
result = campaign.db.get_results(result_id=result_id)[0]
click.echo("Simulation command:")
click.echo(sem.utils.get_command_from_result(campaign.db.get_script(),
result))
click.echo("Debug command:")
click.echo(sem.utils.get_command_from_result(campaign.db.get_script(),
result,
debug=True)) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier integer expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier true | Print the command that needs to be used to reproduce a result. |
def newEntry(self, ident = "", seq = "", plus = "", qual = "") :
e = FastqEntry()
self.data.append(e)
return e | module function_definition identifier parameters identifier default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end default_parameter identifier string string_start string_end block expression_statement assignment identifier call identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Appends an empty entry at the end of the CSV and returns it |
def register_scf_task(self, *args, **kwargs):
kwargs["task_class"] = ScfTask
return self.register_task(*args, **kwargs) | module function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement call attribute identifier identifier argument_list list_splat identifier dictionary_splat identifier | Register a Scf task. |
def _token_to_subwords(self, token):
subwords = []
start = 0
while start < len(token):
subword = None
for end in range(
min(len(token), start + self._max_subword_len), start, -1):
candidate = token[start:end]
if (candidate in self._subword_to_id or
candidate == _UNDERSCORE_REPLACEMENT):
subword = candidate
subwords.append(subword)
start = end
break
if subword is None:
subwords.append(token[start])
start += 1
return subwords | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier none for_statement identifier call identifier argument_list call identifier argument_list call identifier argument_list identifier binary_operator identifier attribute identifier identifier identifier unary_operator integer block expression_statement assignment identifier subscript identifier slice identifier identifier if_statement parenthesized_expression boolean_operator comparison_operator identifier attribute identifier identifier comparison_operator identifier identifier block expression_statement assignment identifier identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier identifier break_statement if_statement comparison_operator identifier none block expression_statement call attribute identifier identifier argument_list subscript identifier identifier expression_statement augmented_assignment identifier integer return_statement identifier | Greedily split token into subwords. |
def _extract_docs_other(self):
if self.dst.style['in'] == 'numpydoc':
data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
lst = self.dst.numpydoc.get_list_key(data, 'also')
lst = self.dst.numpydoc.get_list_key(data, 'ref')
lst = self.dst.numpydoc.get_list_key(data, 'note')
lst = self.dst.numpydoc.get_list_key(data, 'other')
lst = self.dst.numpydoc.get_list_key(data, 'example')
lst = self.dst.numpydoc.get_list_key(data, 'attr') | module function_definition identifier parameters identifier block if_statement comparison_operator subscript attribute attribute identifier identifier identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list list_comprehension call attribute call attribute identifier identifier argument_list identifier argument_list subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end string string_start string_end integer for_in_clause identifier call attribute subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end identifier argument_list expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier string string_start string_content string_end | Extract other specific sections |
def getPart(ID, chart):
obj = GenericObject()
obj.id = ID
obj.type = const.OBJ_ARABIC_PART
obj.relocate(partLon(ID, chart))
return obj | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier identifier return_statement identifier | Returns an Arabic Part. |
def _get_style_of_faulting_term(self, C, rup):
if (rup.rake > 30.0) and (rup.rake < 150.):
frv = 1.0
fnm = 0.0
elif (rup.rake > -150.0) and (rup.rake < -30.0):
fnm = 1.0
frv = 0.0
else:
fnm = 0.0
frv = 0.0
fflt_f = (self.CONSTS["c8"] * frv) + (C["c9"] * fnm)
if rup.mag <= 4.5:
fflt_m = 0.0
elif rup.mag > 5.5:
fflt_m = 1.0
else:
fflt_m = rup.mag - 4.5
return fflt_f * fflt_m | module function_definition identifier parameters identifier identifier identifier block if_statement boolean_operator parenthesized_expression comparison_operator attribute identifier identifier float parenthesized_expression comparison_operator attribute identifier identifier float block expression_statement assignment identifier float expression_statement assignment identifier float elif_clause boolean_operator parenthesized_expression comparison_operator attribute identifier identifier unary_operator float parenthesized_expression comparison_operator attribute identifier identifier unary_operator float block expression_statement assignment identifier float expression_statement assignment identifier float else_clause block expression_statement assignment identifier float expression_statement assignment identifier float expression_statement assignment identifier binary_operator parenthesized_expression binary_operator subscript attribute identifier identifier string string_start string_content string_end identifier parenthesized_expression binary_operator subscript identifier string string_start string_content string_end identifier if_statement comparison_operator attribute identifier identifier float block expression_statement assignment identifier float elif_clause comparison_operator attribute identifier identifier float block expression_statement assignment identifier float else_clause block expression_statement assignment identifier binary_operator attribute identifier identifier float return_statement binary_operator identifier identifier | Returns the style-of-faulting scaling term defined in equations 4 to 6 |
def _set_attribute(self, name, value):
setattr(self, name, value)
self.namespace.update({name: getattr(self, name)}) | module function_definition identifier parameters identifier identifier identifier block expression_statement call identifier argument_list identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list dictionary pair identifier call identifier argument_list identifier identifier | Make sure namespace gets updated when setting attributes. |
def total_level(source_levels):
sums = 0.0
for l in source_levels:
if l is None:
continue
if l == 0:
continue
sums += pow(10.0, float(l) / 10.0)
level = 10.0 * math.log10(sums)
return level | module function_definition identifier parameters identifier block expression_statement assignment identifier float for_statement identifier identifier block if_statement comparison_operator identifier none block continue_statement if_statement comparison_operator identifier integer block continue_statement expression_statement augmented_assignment identifier call identifier argument_list float binary_operator call identifier argument_list identifier float expression_statement assignment identifier binary_operator float call attribute identifier identifier argument_list identifier return_statement identifier | Calculates the total sound pressure level based on multiple source levels |
def joint_hex(x, y, **kwargs):
return sns.jointplot(
x, y, kind='hex', stat_func=None, marginal_kws={'kde': True}, **kwargs
) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier none keyword_argument identifier dictionary pair string string_start string_content string_end true dictionary_splat identifier | Seaborn Joint Hexplot with marginal KDE + hists. |
def _load_scalar_fit(self, fit_key=None, h5file=None, fit_data=None):
if (fit_key is None) ^ (h5file is None):
raise ValueError("Either specify both fit_key and h5file, or"
" neither")
if not ((fit_key is None) ^ (fit_data is None)):
raise ValueError("Specify exactly one of fit_key and fit_data.")
if fit_data is None:
fit_data = self._read_dict(h5file[fit_key])
if 'fitType' in fit_data.keys() and fit_data['fitType'] == 'GPR':
fit = _eval_pysur.evaluate_fit.getGPRFitAndErrorEvaluator(fit_data)
else:
fit = _eval_pysur.evaluate_fit.getFitEvaluator(fit_data)
return fit | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none block if_statement binary_operator parenthesized_expression comparison_operator identifier none parenthesized_expression comparison_operator identifier none block raise_statement call identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end if_statement not_operator parenthesized_expression binary_operator parenthesized_expression comparison_operator identifier none parenthesized_expression comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier identifier if_statement boolean_operator comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list 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 attribute identifier identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Loads a single fit |
def _rectangular(n):
for i in n:
if len(i) != len(n[0]):
return False
return True | module function_definition identifier parameters identifier block for_statement identifier identifier block if_statement comparison_operator call identifier argument_list identifier call identifier argument_list subscript identifier integer block return_statement false return_statement true | Checks to see if a 2D list is a valid 2D matrix |
def interval_lengths( bits ):
end = 0
while 1:
start = bits.next_set( end )
if start == bits.size: break
end = bits.next_clear( start )
yield end - start | module function_definition identifier parameters identifier block expression_statement assignment identifier integer while_statement integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier attribute identifier identifier block break_statement expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement yield binary_operator identifier identifier | Get the length distribution of all contiguous runs of set bits from |
def execute_with_client(quiet=False,
bootstrap_server=False,
create_client=True):
def wrapper(f):
def wrapper2(self, *args, **kwargs):
client = self.current_client(
quiet=quiet,
bootstrap_server=bootstrap_server,
create_client=create_client)
if client and client.running:
return f(self, client, *args, **kwargs)
return wrapper2
return wrapper | module function_definition identifier parameters default_parameter identifier false default_parameter identifier false default_parameter identifier true block function_definition identifier parameters identifier block function_definition identifier parameters identifier list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier if_statement boolean_operator identifier attribute identifier identifier block return_statement call identifier argument_list identifier identifier list_splat identifier dictionary_splat identifier return_statement identifier return_statement identifier | Decorator that gets a client and performs an operation on it. |
def _set_covars(self, covars):
covars = np.asarray(covars)
_validate_covars(covars, self.covariance_type, self.n_components)
self.covars_ = covars | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list identifier attribute identifier identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier | Provide values for covariance |
def update_result_ctrl(self, event):
if not self:
return
printLen = 0
self.result_ctrl.SetValue('')
if hasattr(event, 'msg'):
self.result_ctrl.AppendText(event.msg)
printLen = len(event.msg)
if hasattr(event, 'err'):
errLen = len(event.err)
errStyle = wx.TextAttr(wx.RED)
self.result_ctrl.AppendText(event.err)
self.result_ctrl.SetStyle(printLen, printLen+errLen, errStyle)
if not hasattr(event, 'err') or event.err == '':
if self._ok_pressed:
self.Destroy()
self._ok_pressed = False | module function_definition identifier parameters identifier identifier block if_statement not_operator identifier block return_statement expression_statement assignment identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_end if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier if_statement call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier binary_operator identifier identifier identifier if_statement boolean_operator not_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute identifier identifier string string_start string_end block if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier false | Update event result following execution by main window |
def b58encode(v):
long_value = 0
for c in v:
long_value = long_value * 256 + c
result = ""
while long_value >= __b58base:
div, mod = divmod(long_value, __b58base)
result = __b58chars[mod] + result
long_value = div
result = __b58chars[long_value] + result
nPad = 0
for c in v:
if c == 0:
nPad += 1
else:
break
return (__b58chars[0] * nPad) + result | module function_definition identifier parameters identifier block expression_statement assignment identifier integer for_statement identifier identifier block expression_statement assignment identifier binary_operator binary_operator identifier integer identifier expression_statement assignment identifier string string_start string_end while_statement comparison_operator identifier identifier block expression_statement assignment pattern_list identifier identifier call identifier argument_list identifier identifier expression_statement assignment identifier binary_operator subscript identifier identifier identifier expression_statement assignment identifier identifier expression_statement assignment identifier binary_operator subscript identifier identifier identifier expression_statement assignment identifier integer for_statement identifier identifier block if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier integer else_clause block break_statement return_statement binary_operator parenthesized_expression binary_operator subscript identifier integer identifier identifier | encode v, which is a string of bytes, to base58. |
def _transform(xsl_filename, xml, **kwargs):
xslt = _make_xsl(xsl_filename)
xml = xslt(xml, **kwargs)
return xml | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier dictionary_splat identifier return_statement identifier | Transforms the xml using the specifiec xsl file. |
def call(function, args, pseudo_type=None):
if not isinstance(function, Node):
function = local(function)
return Node('call', function=function, args=args, pseudo_type=pseudo_type) | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement not_operator call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier return_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | A shortcut for a call with an identifier callee |
def _parse_g_dir(repo, gdirpath):
for f in repo.get_contents(gdirpath):
if f.type == "dir":
for sf in repo.get_contents(f.path):
yield sf
else:
yield f | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block for_statement identifier call attribute identifier identifier argument_list attribute identifier identifier block expression_statement yield identifier else_clause block expression_statement yield identifier | parses a repo directory two-levels deep |
async def _handle_job_queue_update(self, message: BackendGetQueue):
self._logger.debug("Received job queue update")
self._queue_update_last_attempt = 0
self._queue_cache = message
new_job_queue_cache = {}
for (job_id, is_local, _, _2, _3, _4, max_end) in message.jobs_running:
if is_local:
new_job_queue_cache[job_id] = (-1, max_end - time.time())
wait_time = 0
nb_tasks = 0
for (job_id, is_local, _, _2, timeout) in message.jobs_waiting:
if timeout > 0:
wait_time += timeout
if is_local:
new_job_queue_cache[job_id] = (nb_tasks, wait_time)
nb_tasks += 1
self._queue_job_cache = new_job_queue_cache | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier integer expression_statement assignment attribute identifier identifier identifier expression_statement assignment identifier dictionary for_statement tuple_pattern identifier identifier identifier identifier identifier identifier identifier attribute identifier identifier block if_statement identifier block expression_statement assignment subscript identifier identifier tuple unary_operator integer binary_operator identifier call attribute identifier identifier argument_list expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement tuple_pattern identifier identifier identifier identifier identifier attribute identifier identifier block if_statement comparison_operator identifier integer block expression_statement augmented_assignment identifier identifier if_statement identifier block expression_statement assignment subscript identifier identifier tuple identifier identifier expression_statement augmented_assignment identifier integer expression_statement assignment attribute identifier identifier identifier | Handles a BackendGetQueue containing a snapshot of the job queue |
def transform(self, m):
if len(m) != 6:
raise ValueError("bad sequ. length")
self.x, self.y = TOOLS._transform_point(self, m)
return self | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Replace point by its transformation with matrix-like m. |
def _format_param_value(key, value):
if isinstance(value, str):
value = "'{}'".format(value)
return "{}={}".format(key, value) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier argument_list identifier identifier | Wraps string values in quotes, and returns as 'key=value'. |
def tree_to_dict(cls, tree):
specs = {}
for k in tree.keys():
spec_key = '.'.join(k)
specs[spec_key] = {}
for grp in tree[k].groups:
kwargs = tree[k].groups[grp].kwargs
if kwargs:
specs[spec_key][grp] = kwargs
return specs | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment subscript identifier identifier dictionary for_statement identifier attribute subscript identifier identifier identifier block expression_statement assignment identifier attribute subscript attribute subscript identifier identifier identifier identifier identifier if_statement identifier block expression_statement assignment subscript subscript identifier identifier identifier identifier return_statement identifier | Given an OptionTree, convert it into the equivalent dictionary format. |
def install (self):
outs = super(MyInstallLib, self).install()
infile = self.create_conf_file()
outfile = os.path.join(self.install_dir, os.path.basename(infile))
self.copy_file(infile, outfile)
outs.append(outfile)
return outs | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Install the generated config file. |
def download(self, protocol, host, user, password,
file_name, rbridge='all'):
urn = "{urn:brocade.com:mgmt:brocade-firmware}"
request_fwdl = self.get_firmware_download_request(protocol, host,
user, password,
file_name, rbridge)
response = self._callback(request_fwdl, 'get')
fwdl_result = None
for item in response.findall('%scluster-output' % urn):
fwdl_result = item.find('%sfwdl-msg' % urn).text
if not fwdl_result:
fwdl_result = response.find('%sfwdl-cmd-msg' % urn).text
return fwdl_result | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier none for_statement identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier identifier if_statement not_operator identifier block expression_statement assignment identifier attribute call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier identifier return_statement identifier | Download firmware to device |
def FindUniqueId(dic):
name = str(len(dic))
while name in dic:
name = str(random.randint(1000000, 999999999))
return name | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier while_statement comparison_operator identifier identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list integer integer return_statement identifier | Return a string not used as a key in the dictionary dic |
def _render_corpus_row(self, label, ngrams):
row = ('<tr>\n<td>{label}</td>\n<td>{first}</td>\n<td>{only}</td>\n'
'<td>{last}</td>\n</tr>')
cell_data = {'label': label}
for period in ('first', 'only', 'last'):
cell_data[period] = ', '.join(ngrams[label][period])
return row.format(**cell_data) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier parenthesized_expression concatenated_string string string_start string_content escape_sequence escape_sequence escape_sequence escape_sequence string_end string string_start string_content escape_sequence string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier for_statement identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block expression_statement assignment subscript identifier identifier call attribute string string_start string_content string_end identifier argument_list subscript subscript identifier identifier identifier return_statement call attribute identifier identifier argument_list dictionary_splat identifier | Returns the HTML for a corpus row. |
def _file_chunks(self, data, chunk_size):
for i in xrange(0, len(data), chunk_size):
yield self.compressor(data[i:i+chunk_size]) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call identifier argument_list integer call identifier argument_list identifier identifier block expression_statement yield call attribute identifier identifier argument_list subscript identifier slice identifier binary_operator identifier identifier | Yield compressed chunks from a data array |
def agent_updated(self, context, payload):
try:
if payload['admin_state_up']:
pass
except KeyError as e:
LOG.error("Invalid payload format for received RPC message "
"`agent_updated`. Error is %(error)s. Payload is "
"%(payload)s", {'error': e, 'payload': payload}) | module function_definition identifier parameters identifier identifier identifier block try_statement block if_statement subscript identifier string string_start string_content string_end block pass_statement except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier | Deal with agent updated RPC message. |
def execute_sql(self, sql, commit=False):
logger.info("Running sqlite query: \"%s\"", sql)
self.connection.execute(sql)
if commit:
self.connection.commit() | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list | Log and then execute a SQL query |
def date_range(self):
try:
days = int(self.days)
except ValueError:
exit_after_echo(QUERY_DAYS_INVALID)
if days < 1:
exit_after_echo(QUERY_DAYS_INVALID)
start = datetime.today()
end = start + timedelta(days=days)
return (
datetime.strftime(start, '%Y-%m-%d'),
datetime.strftime(end, '%Y-%m-%d')
) | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call identifier argument_list attribute identifier identifier except_clause identifier block expression_statement call identifier argument_list identifier if_statement comparison_operator identifier integer block expression_statement call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator identifier call identifier argument_list keyword_argument identifier identifier return_statement tuple call attribute identifier identifier argument_list identifier string string_start string_content string_end call attribute identifier identifier argument_list identifier string string_start string_content string_end | Generate date range according to the `days` user input. |
def parse_hpxregion(region):
m = re.match(r'([A-Za-z\_]*?)\((.*?)\)', region)
if m is None:
raise Exception('Failed to parse hpx region string.')
if not m.group(1):
return re.split(',', m.group(2))
else:
return [m.group(1)] + re.split(',', m.group(2)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement comparison_operator identifier none block raise_statement call identifier argument_list string string_start string_content string_end if_statement not_operator call attribute identifier identifier argument_list integer block return_statement call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list integer else_clause block return_statement binary_operator list call attribute identifier identifier argument_list integer call attribute identifier identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list integer | Parse the HPX_REG header keyword into a list of tokens. |
def _validate_information(self):
needed_variables = ["ModuleName", "ModuleVersion", "APIVersion"]
for var in needed_variables:
if var not in self.variables:
raise DataError("Needed variable was not defined in mib file.", variable=var)
if len(self.variables["ModuleName"]) > 6:
raise DataError("ModuleName too long, must be 6 or fewer characters.",
module_name=self.variables["ModuleName"])
if not isinstance(self.variables["ModuleVersion"], str):
raise ValueError("ModuleVersion ('%s') must be a string of the form X.Y.Z" %
str(self.variables['ModuleVersion']))
if not isinstance(self.variables["APIVersion"], str):
raise ValueError("APIVersion ('%s') must be a string of the form X.Y" % str(self.variables['APIVersion']))
self.variables['ModuleVersion'] = self._convert_module_version(self.variables["ModuleVersion"])
self.variables['APIVersion'] = self._convert_api_version(self.variables["APIVersion"])
self.variables["ModuleName"] = self.variables["ModuleName"].ljust(6)
self.valid = True | 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 for_statement identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier identifier if_statement comparison_operator call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end integer block raise_statement call identifier argument_list string string_start string_content string_end keyword_argument identifier subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end if_statement not_operator call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier block raise_statement call identifier argument_list binary_operator string string_start string_content string_end call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list integer expression_statement assignment attribute identifier identifier true | Validate that all information has been filled in |
def finish (self):
if not self.urlqueue.empty():
self.cancel()
for t in self.threads:
t.stop() | module function_definition identifier parameters identifier block if_statement not_operator call attribute attribute identifier identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list for_statement identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list | Wait for checker threads to finish. |
def sha(self):
if self._sha is None:
self._sha = compute_auth_key(self.userid, self.password)
return self._sha | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier attribute identifier identifier return_statement attribute identifier identifier | Return sha, lazily compute if not done yet. |
def _get_conn(ret=None):
_options = _get_options(ret)
dsn = _options.get('dsn')
user = _options.get('user')
passwd = _options.get('passwd')
return pyodbc.connect('DSN={0};UID={1};PWD={2}'.format(
dsn,
user,
passwd)) | module function_definition identifier parameters default_parameter identifier none 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 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 return_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier | Return a MSSQL connection. |
def iter_halfs_double(graph):
edges = graph.edges
for index1, (atom_a1, atom_b1) in enumerate(edges):
for atom_a2, atom_b2 in edges[:index1]:
try:
affected_atoms1, affected_atoms2, hinge_atoms = graph.get_halfs_double(atom_a1, atom_b1, atom_a2, atom_b2)
yield affected_atoms1, affected_atoms2, hinge_atoms
except GraphError:
pass | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier for_statement pattern_list identifier tuple_pattern identifier identifier call identifier argument_list identifier block for_statement pattern_list identifier identifier subscript identifier slice identifier block try_statement block expression_statement assignment pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier identifier identifier identifier expression_statement yield expression_list identifier identifier identifier except_clause identifier block pass_statement | Select two random non-consecutive bonds that divide the molecule in two |
def targetword(self, index, targetwords, alignment):
if alignment[index]:
return targetwords[alignment[index]]
else:
return None | module function_definition identifier parameters identifier identifier identifier identifier block if_statement subscript identifier identifier block return_statement subscript identifier subscript identifier identifier else_clause block return_statement none | Return the aligned targetword for a specified index in the source words |
def _build_url(self, resource, **kwargs):
return urljoin(self.api_root, API_PATH[resource].format(**kwargs)) | module function_definition identifier parameters identifier identifier dictionary_splat_pattern identifier block return_statement call identifier argument_list attribute identifier identifier call attribute subscript identifier identifier identifier argument_list dictionary_splat identifier | Build the correct API url. |
def write_chunk(self, x, z, nbt_file):
data = BytesIO()
nbt_file.write_file(buffer=data)
self.write_blockdata(x, z, data.getvalue()) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier call attribute identifier identifier argument_list | Pack the NBT file as binary data, and write to file in a compressed format. |
def new_empty(self, name):
if name in self:
raise KeyError("Already have rule {}".format(name))
new = Rule(self.engine, name)
self._cache[name] = new
self.send(self, rule=new, active=True)
return new | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier true return_statement identifier | Make a new rule with no actions or anything, and return it. |
def _process_failures(self, key):
if self.settings['RETRY_FAILURES']:
self.logger.debug("going to retry failure")
failkey = self._get_fail_key(key)
current = self.redis_conn.get(failkey)
if current is None:
current = 0
else:
current = int(current)
if current < self.settings['RETRY_FAILURES_MAX']:
self.logger.debug("Incr fail key")
current += 1
self.redis_conn.set(failkey, current)
else:
self.logger.error("Could not process action within"
" failure limit")
self.redis_conn.delete(failkey)
self.redis_conn.delete(key) | module function_definition identifier parameters identifier identifier block if_statement subscript attribute identifier identifier 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 identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block expression_statement assignment identifier integer else_clause block expression_statement assignment identifier call identifier argument_list identifier if_statement comparison_operator identifier subscript attribute identifier identifier 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 augmented_assignment identifier integer expression_statement call attribute attribute identifier identifier identifier argument_list identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list concatenated_string string string_start string_content string_end string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Handles the retrying of the failed key |
def _rand_init(x_bounds, x_types, selection_num_starting_points):
return [lib_data.rand(x_bounds, x_types) for i \
in range(0, selection_num_starting_points)] | module function_definition identifier parameters identifier identifier identifier block return_statement list_comprehension call attribute identifier identifier argument_list identifier identifier for_in_clause identifier line_continuation call identifier argument_list integer identifier | Random sample some init seed within bounds. |
def rotation_matrix_to_quaternion(rotation_matrix):
invert = (np.linalg.det(rotation_matrix) < 0)
if invert:
factor = -1
else:
factor = 1
c2 = 0.25*(factor*np.trace(rotation_matrix) + 1)
if c2 < 0:
c2 = 0.0
c = np.sqrt(c2)
r2 = 0.5*(1 + factor*np.diagonal(rotation_matrix)) - c2
r = np.zeros(3, float)
for index, r2_comp in enumerate(r2):
if r2_comp < 0:
continue
else:
row, col = off_diagonals[index]
if (rotation_matrix[row, col] - rotation_matrix[col, row] < 0):
r[index] = -np.sqrt(r2_comp)
else:
r[index] = +np.sqrt(r2_comp)
return factor, np.array([c, r[0], r[1], r[2]], float) | module function_definition identifier parameters identifier block expression_statement assignment identifier parenthesized_expression comparison_operator call attribute attribute identifier identifier identifier argument_list identifier integer if_statement identifier block expression_statement assignment identifier unary_operator integer else_clause block expression_statement assignment identifier integer expression_statement assignment identifier binary_operator float parenthesized_expression binary_operator binary_operator identifier call attribute identifier identifier argument_list identifier integer if_statement comparison_operator identifier integer block expression_statement assignment identifier float expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator binary_operator float parenthesized_expression binary_operator integer binary_operator identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list integer identifier for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator identifier integer block continue_statement else_clause block expression_statement assignment pattern_list identifier identifier subscript identifier identifier if_statement parenthesized_expression comparison_operator binary_operator subscript identifier identifier identifier subscript identifier identifier identifier integer block expression_statement assignment subscript identifier identifier unary_operator call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment subscript identifier identifier unary_operator call attribute identifier identifier argument_list identifier return_statement expression_list identifier call attribute identifier identifier argument_list list identifier subscript identifier integer subscript identifier integer subscript identifier integer identifier | Compute the quaternion representing the rotation given by the matrix |
def create_table(clas,pool_or_cursor):
"uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model"
def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else 'jsonb')
fields = ','.join(map(' '.join,map(mkfield,clas.FIELDS)))
base = 'create table if not exists %s (%s'%(clas.TABLE,fields)
if clas.PKEY: base += ',primary key (%s)'%clas.PKEY
base += ')'
commit_or_execute(pool_or_cursor,base)
clas.create_indexes(pool_or_cursor) | module function_definition identifier parameters identifier identifier block expression_statement string string_start string_content string_end function_definition identifier parameters tuple_pattern identifier identifier block return_statement expression_list identifier parenthesized_expression conditional_expression identifier call identifier argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list call identifier argument_list attribute string string_start string_content string_end identifier call identifier argument_list identifier attribute identifier identifier expression_statement assignment identifier binary_operator string string_start string_content string_end tuple attribute identifier identifier identifier if_statement attribute identifier identifier block expression_statement augmented_assignment identifier binary_operator string string_start string_content string_end attribute identifier identifier expression_statement augmented_assignment identifier string string_start string_content string_end expression_statement call identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier | uses FIELDS, PKEY, INDEXES and TABLE members to create a sql table for the model |
def tchar(tree_style, cur_level, level, item, size):
if (cur_level == level):
i1 = '1' if level == 0 else 'x'
i2 = '1' if item == 0 else 'x'
i3 = 'x'
if size == 1:
i3 = '1'
elif item == (size - 1):
i3 = 'l'
index = '{}{}{}'.format(i1, i2, i3)
else:
index = 'non' if item == (size - 1) else 'ver'
return TREE_STYLES[tree_style][index] | module function_definition identifier parameters identifier identifier identifier identifier identifier block if_statement parenthesized_expression comparison_operator identifier identifier block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier integer string string_start string_content string_end expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier integer string string_start string_content string_end expression_statement assignment identifier string string_start string_content string_end if_statement comparison_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end elif_clause comparison_operator identifier parenthesized_expression binary_operator identifier integer block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier identifier else_clause block expression_statement assignment identifier conditional_expression string string_start string_content string_end comparison_operator identifier parenthesized_expression binary_operator identifier integer string string_start string_content string_end return_statement subscript subscript identifier identifier identifier | Retrieve tree character for particular tree node. |
def register_callback(self, sensorid, callback, user_data=None):
if sensorid not in self._registry:
self._registry[sensorid] = list()
self._registry[sensorid].append((callback, user_data)) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier call identifier argument_list expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list tuple identifier identifier | Register a callback for the specified sensor id. |
def _kput(url, data):
headers = {"Content-Type": "application/json"}
ret = http.query(url,
method='PUT',
header_dict=headers,
data=salt.utils.json.dumps(data))
if ret.get('error'):
return ret
else:
return salt.utils.json.loads(ret.get('body')) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier call attribute attribute attribute identifier identifier identifier identifier argument_list identifier if_statement call attribute identifier identifier argument_list string string_start string_content string_end block return_statement identifier else_clause block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end | put any object in kubernetes based on URL |
def compute_file_metrics(processors, language, key, token_list):
tli = itertools.tee(token_list, len(processors))
metrics = OrderedDict()
for p in processors:
p.reset()
for p, tl in zip(processors, tli):
p.process_file(language, key, tl)
for p in processors:
metrics.update(p.metrics)
return metrics | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list for_statement pattern_list identifier identifier call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list identifier identifier identifier for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | use processors to compute file metrics. |
def getChild(self, suffix):
if suffix is None:
return self
if self.root is not self:
if suffix.startswith(self.name + "."):
suffix = suffix[len(self.name + "."):]
suf_parts = suffix.split(".")
if len(suf_parts) > 1 and suf_parts[-1] == suf_parts[-2]:
suffix = ".".join(suf_parts[:-1])
suffix = '.'.join((self.name, suffix))
return self.manager.getLogger(suffix) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier none block return_statement identifier if_statement comparison_operator attribute identifier identifier identifier block if_statement call attribute identifier identifier argument_list binary_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript identifier slice call identifier argument_list binary_operator attribute identifier 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 if_statement boolean_operator comparison_operator call identifier argument_list identifier integer comparison_operator subscript identifier unary_operator integer subscript identifier unary_operator integer block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list subscript identifier slice unary_operator integer expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple attribute identifier identifier identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Taken from CPython 2.7, modified to remove duplicate prefix and suffixes |
def point_mutate(self,p_i,func_set,term_set):
x = self.random_state.randint(len(p_i))
arity = p_i[x].arity[p_i[x].in_type]
reps = [n for n in func_set+term_set
if n.arity[n.in_type]==arity and n.out_type==p_i[x].out_type
and n.in_type==p_i[x].in_type]
tmp = reps[self.random_state.randint(len(reps))]
tmp_p = p_i[:]
p_i[x] = tmp
if not self.is_valid_program(p_i):
print("old:",tmp_p)
print("new:",p_i)
raise ValueError('Mutation produced an invalid program.') | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier subscript attribute subscript identifier identifier identifier attribute subscript identifier identifier identifier expression_statement assignment identifier list_comprehension identifier for_in_clause identifier binary_operator identifier identifier if_clause boolean_operator boolean_operator comparison_operator subscript attribute identifier identifier attribute identifier identifier identifier comparison_operator attribute identifier identifier attribute subscript identifier identifier identifier comparison_operator attribute identifier identifier attribute subscript identifier identifier identifier expression_statement assignment identifier subscript identifier call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier expression_statement assignment identifier subscript identifier slice expression_statement assignment subscript identifier identifier identifier if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement call identifier argument_list string string_start string_content string_end identifier raise_statement call identifier argument_list string string_start string_content string_end | point mutation on individual p_i |
def indent(text, n=4):
_indent = ' ' * n
return '\n'.join(_indent + line for line in text.split('\n')) | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier binary_operator string string_start string_content string_end identifier return_statement call attribute string string_start string_content escape_sequence string_end identifier generator_expression binary_operator identifier identifier for_in_clause identifier call attribute identifier identifier argument_list string string_start string_content escape_sequence string_end | Indent each line of text by n spaces |
def find_config_files():
config_files = []
for config_dir in _get_config_dirs():
path = os.path.join(config_dir, "rapport.conf")
if os.path.exists(path):
config_files.append(path)
return list(filter(bool, config_files)) | module function_definition identifier parameters block expression_statement assignment identifier list for_statement identifier call identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end if_statement call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list call identifier argument_list identifier identifier | Return a list of default configuration files. |
def recent_comments(context):
latest = context["settings"].COMMENTS_NUM_LATEST
comments = ThreadedComment.objects.all().select_related("user")
context["comments"] = comments.order_by("-id")[:latest]
return context | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end subscript call attribute identifier identifier argument_list string string_start string_content string_end slice identifier return_statement identifier | Dashboard widget for displaying recent comments. |
def normalize_bboxes(bboxes, rows, cols):
return [normalize_bbox(bbox, rows, cols) for bbox in bboxes] | module function_definition identifier parameters identifier identifier identifier block return_statement list_comprehension call identifier argument_list identifier identifier identifier for_in_clause identifier identifier | Normalize a list of bounding boxes. |
def include_library(libname):
if exclude_list:
if exclude_list.search(libname) and not include_list.search(libname):
return False
else:
return True
else:
return True | module function_definition identifier parameters identifier block if_statement identifier block if_statement boolean_operator call attribute identifier identifier argument_list identifier not_operator call attribute identifier identifier argument_list identifier block return_statement false else_clause block return_statement true else_clause block return_statement true | Check if a dynamic library should be included with application or not. |
def upload_mission(aFileName):
missionlist = readmission(aFileName)
print("\nUpload mission from a file: %s" % aFileName)
print(' Clear mission')
cmds = vehicle.commands
cmds.clear()
for command in missionlist:
cmds.add(command)
print(' Upload mission')
vehicle.commands.upload() | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list | Upload a mission from a file. |
def _and(ctx, *logical):
for arg in logical:
if not conversions.to_boolean(arg, ctx):
return False
return True | module function_definition identifier parameters identifier list_splat_pattern identifier block for_statement identifier identifier block if_statement not_operator call attribute identifier identifier argument_list identifier identifier block return_statement false return_statement true | Returns TRUE if and only if all its arguments evaluate to TRUE |
def available_styles(self):
styles = self._schema_item.get("styles", [])
return list(map(operator.itemgetter("name"), styles)) | 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 list return_statement call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end identifier | Returns a list of all styles defined for the item |
def _load_from_tar(self, dtype_out_time, dtype_out_vert=False):
path = os.path.join(self.dir_tar_out, 'data.tar')
utils.io.dmget([path])
with tarfile.open(path, 'r') as data_tar:
ds = xr.open_dataset(
data_tar.extractfile(self.file_name[dtype_out_time])
)
return ds[self.name] | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list list 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 expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript attribute identifier identifier identifier return_statement subscript identifier attribute identifier identifier | Load data save in tarball form on the file system. |
def parallel_assimilate(self, rootpath):
logger.info('Scanning for valid paths...')
valid_paths = []
for (parent, subdirs, files) in os.walk(rootpath):
valid_paths.extend(self._drone.get_valid_paths((parent, subdirs,
files)))
manager = Manager()
data = manager.list()
status = manager.dict()
status['count'] = 0
status['total'] = len(valid_paths)
logger.info('{} valid paths found.'.format(len(valid_paths)))
p = Pool(self._num_drones)
p.map(order_assimilation, ((path, self._drone, data, status)
for path in valid_paths))
for d in data:
self._data.append(json.loads(d, cls=MontyDecoder)) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier list for_statement tuple_pattern identifier identifier identifier call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list tuple identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment subscript identifier string string_start string_content string_end integer expression_statement assignment subscript identifier string string_start string_content string_end call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier generator_expression tuple identifier attribute identifier identifier identifier identifier for_in_clause identifier identifier for_statement identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier keyword_argument identifier identifier | Assimilate the entire subdirectory structure in rootpath. |
def _call_method(self, request):
method = self.method_data[request['method']]['method']
params = request['params']
result = None
try:
if isinstance(params, list):
if len(params) < self._man_args(method):
raise InvalidParamsError('not enough arguments')
if not self._vargs(method) \
and len(params) > self._max_args(method):
raise InvalidParamsError('too many arguments')
result = yield defer.maybeDeferred(method, *params)
elif isinstance(params, dict):
if request['jsonrpc'] < 11:
raise KeywordError
result = yield defer.maybeDeferred(method, **params)
else:
result = yield defer.maybeDeferred(method)
except JSONRPCError:
raise
except Exception:
log.msg('Exception raised while invoking RPC method "{}".'.format(
request['method']))
log.err()
raise ServerError
defer.returnValue(result) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier subscript subscript attribute identifier identifier subscript identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement assignment identifier none try_statement block if_statement call identifier argument_list identifier identifier block if_statement comparison_operator call identifier argument_list identifier call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end if_statement boolean_operator not_operator call attribute identifier identifier argument_list identifier line_continuation comparison_operator call identifier argument_list identifier call attribute identifier identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier yield call attribute identifier identifier argument_list identifier list_splat identifier elif_clause call identifier argument_list identifier identifier block if_statement comparison_operator subscript identifier string string_start string_content string_end integer block raise_statement identifier expression_statement assignment identifier yield call attribute identifier identifier argument_list identifier dictionary_splat identifier else_clause block expression_statement assignment identifier yield call attribute identifier identifier argument_list identifier except_clause identifier block raise_statement except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list raise_statement identifier expression_statement call attribute identifier identifier argument_list identifier | Calls given method with given params and returns it value. |
def loadImageData(filename, spacing=()):
if not os.path.isfile(filename):
colors.printc("~noentry File not found:", filename, c=1)
return None
if ".tif" in filename.lower():
reader = vtk.vtkTIFFReader()
elif ".slc" in filename.lower():
reader = vtk.vtkSLCReader()
if not reader.CanReadFile(filename):
colors.printc("~prohibited Sorry bad slc file " + filename, c=1)
exit(1)
elif ".vti" in filename.lower():
reader = vtk.vtkXMLImageDataReader()
elif ".mhd" in filename.lower():
reader = vtk.vtkMetaImageReader()
reader.SetFileName(filename)
reader.Update()
image = reader.GetOutput()
if len(spacing) == 3:
image.SetSpacing(spacing[0], spacing[1], spacing[2])
return image | module function_definition identifier parameters identifier default_parameter identifier tuple block if_statement not_operator call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier integer return_statement none if_statement comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list elif_clause comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier integer expression_statement call identifier argument_list integer elif_clause comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list elif_clause comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator call identifier argument_list identifier integer block expression_statement call attribute identifier identifier argument_list subscript identifier integer subscript identifier integer subscript identifier integer return_statement identifier | Read and return a ``vtkImageData`` object from file. |
def numericalize(self, t:Collection[str]) -> List[int]:
"Convert a list of tokens `t` to their ids."
return [self.stoi[w] for w in t] | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type identifier type generic_type identifier type_parameter type identifier block expression_statement string string_start string_content string_end return_statement list_comprehension subscript attribute identifier identifier identifier for_in_clause identifier identifier | Convert a list of tokens `t` to their ids. |
def zoom(self, factor):
camera = self.ren.GetActiveCamera()
camera.Zoom(factor)
self.ren_win.Render() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Zoom the camera view by a factor. |
def data_changed(self, change):
index = self.index
if index:
self.view.model.dataChanged.emit(index, index) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier if_statement identifier block expression_statement call attribute attribute attribute attribute identifier identifier identifier identifier identifier argument_list identifier identifier | Notify the model that data has changed in this cell! |
def stop_listener_thread(self):
if self.sync_thread:
self.should_listen = False
self.sync_thread.join()
self.sync_thread = None | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier false expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment attribute identifier identifier none | Stop listener thread running in the background |
def plugin_valid(self, filename):
filename = os.path.basename(filename)
for regex in self.regex_expressions:
if regex.match(filename):
return True
return False | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier attribute identifier identifier block if_statement call attribute identifier identifier argument_list identifier block return_statement true return_statement false | Checks if the given filename is a valid plugin for this Strategy |
def _f90repr(self, value):
if isinstance(value, bool):
return self._f90bool(value)
elif isinstance(value, numbers.Integral):
return self._f90int(value)
elif isinstance(value, numbers.Real):
return self._f90float(value)
elif isinstance(value, numbers.Complex):
return self._f90complex(value)
elif isinstance(value, basestring):
return self._f90str(value)
elif value is None:
return ''
else:
raise ValueError('Type {0} of {1} cannot be converted to a Fortran'
' type.'.format(type(value), value)) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier attribute identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute identifier identifier argument_list identifier elif_clause comparison_operator identifier none block return_statement string string_start string_end else_clause block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list call identifier argument_list identifier identifier | Convert primitive Python types to equivalent Fortran strings. |
def stack(datasets):
base = datasets[0].copy()
for dataset in datasets[1:]:
base = base.where(dataset.isnull(), dataset)
return base | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute subscript identifier integer identifier argument_list for_statement identifier subscript identifier slice integer block expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier return_statement identifier | First dataset at the bottom. |
def availability(self):
if not hasattr(self, '_availability'):
self._availability = conf.lib.clang_getCursorAvailability(self)
return AvailabilityKind.from_id(self._availability) | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list attribute identifier identifier | Retrieves the availability of the entity pointed at by the cursor. |
def _handle_request_exception(request):
try:
data = request.json()
except:
data = {}
code = request.status_code
if code == requests.codes.bad:
raise BadRequestException(response=data)
if code == requests.codes.unauthorized:
raise UnauthorizedException(response=data)
if code == requests.codes.not_found:
raise NotFoundException(response=data)
request.raise_for_status() | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list except_clause block expression_statement assignment identifier dictionary expression_statement assignment identifier attribute identifier identifier if_statement comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list keyword_argument identifier identifier if_statement comparison_operator identifier attribute attribute identifier identifier identifier block raise_statement call identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list | Raise the proper exception based on the response |
def target_query(plugin, port, location):
return ((r.row[PLUGIN_NAME_KEY] == plugin) &
(r.row[PORT_FIELD] == port) &
(r.row[LOCATION_FIELD] == location)) | module function_definition identifier parameters identifier identifier identifier block return_statement parenthesized_expression binary_operator binary_operator parenthesized_expression comparison_operator subscript attribute identifier identifier identifier identifier parenthesized_expression comparison_operator subscript attribute identifier identifier identifier identifier parenthesized_expression comparison_operator subscript attribute identifier identifier identifier identifier | prepared ReQL for target |
def groups_set_description(self, room_id, description, **kwargs):
return self.__call_api_post('groups.setDescription', roomId=room_id, description=description, kwargs=kwargs) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Sets the description for the private group. |
def verb_chain_starts(self):
if not self.is_tagged(VERB_CHAINS):
self.tag_verb_chains()
return self.starts(VERB_CHAINS) | module function_definition identifier parameters identifier block if_statement not_operator call attribute identifier identifier argument_list identifier block expression_statement call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier | The start positions of ``verb_chains`` elements. |
def raw_shell(s):
'Not a member of ShellQuoted so we get a useful error for raw strings'
if isinstance(s, ShellQuoted):
return s.do_not_use_raw_str
raise RuntimeError('{0} should have been ShellQuoted'.format(s)) | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end if_statement call identifier argument_list identifier identifier block return_statement attribute identifier identifier raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Not a member of ShellQuoted so we get a useful error for raw strings |
def convert_all(folder, dest_path='.', force_all=False):
"Convert modified notebooks in `folder` to html pages in `dest_path`."
path = Path(folder)
changed_cnt = 0
for fname in path.glob("*.ipynb"):
fname_out = Path(dest_path)/fname.with_suffix('.html').name
if not force_all and fname_out.exists():
in_mod = os.path.getmtime(fname)
out_mod = os.path.getmtime(fname_out)
if in_mod < out_mod: continue
print(f"converting: {fname} => {fname_out}")
changed_cnt += 1
convert_nb(fname, dest_path=dest_path)
if not changed_cnt: print("No notebooks were modified") | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false block expression_statement string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier binary_operator call identifier argument_list identifier attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier if_statement boolean_operator not_operator identifier call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier identifier block continue_statement expression_statement call identifier argument_list string string_start string_content interpolation identifier string_content interpolation identifier string_end expression_statement augmented_assignment identifier integer expression_statement call identifier argument_list identifier keyword_argument identifier identifier if_statement not_operator identifier block expression_statement call identifier argument_list string string_start string_content string_end | Convert modified notebooks in `folder` to html pages in `dest_path`. |
def make_connection(self):
"Make a fresh connection."
connection = self.connection_class(**self.connection_kwargs)
self._connections.append(connection)
return connection | module function_definition identifier parameters identifier block expression_statement string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Make a fresh connection. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.