code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def purge_queues(queues=None):
current_queues.purge(queues=queues)
click.secho(
'Queues {} have been purged.'.format(
queues or current_queues.queues.keys()),
fg='green'
) | module function_definition identifier parameters default_parameter identifier none block expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list boolean_operator identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier string string_start string_content string_end | Purge the given queues. |
def export(self, name, columns, points):
if self.prefix is not None:
name = self.prefix + '.' + name
try:
self.client.write_points(self._normalize(name, columns, points))
except Exception as e:
logger.error("Cannot export {} stats to InfluxDB ({})".format(name,
e))
else:
logger.debug("Export {} stats to InfluxDB".format(name)) | module function_definition identifier parameters identifier identifier identifier identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier string string_start string_content string_end identifier try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier | Write the points to the InfluxDB server. |
def _message_received(self, message):
with self.lock:
self._state.receive_message(message)
for callable in chain(self._on_message_received, self._on_message):
callable(message) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier for_statement identifier call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call identifier argument_list identifier | Notify the observers about the received message. |
def register_postloop_hook(self, func: Callable[[None], None]) -> None:
self._validate_prepostloop_callable(func)
self._postloop_hooks.append(func) | module function_definition identifier parameters identifier typed_parameter identifier type generic_type identifier type_parameter type list none type none type none block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Register a function to be called at the end of the command loop. |
def parallel(processes, threads):
pool = multithread(threads)
pool.map(run_process, processes)
pool.close()
pool.join() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | execute jobs in processes using N threads |
def confidenceInterval(self, alpha=0.6827, steps=1.e5, plot=False):
x_dense, y_dense = self.densify()
y_dense -= np.max(y_dense)
f = scipy.interpolate.interp1d(x_dense, y_dense, kind='linear')
x = np.linspace(0., np.max(x_dense), steps)
pdf = np.exp(f(x) / 2.)
cut = (pdf / np.max(pdf)) > 1.e-10
x = x[cut]
pdf = pdf[cut]
sorted_pdf_indices = np.argsort(pdf)[::-1]
cdf = np.cumsum(pdf[sorted_pdf_indices])
cdf /= cdf[-1]
sorted_pdf_index_max = np.argmin((cdf - alpha)**2)
x_select = x[sorted_pdf_indices[0: sorted_pdf_index_max]]
return np.min(x_select), np.max(x_select) | module function_definition identifier parameters identifier default_parameter identifier float default_parameter identifier float default_parameter identifier false block expression_statement assignment pattern_list identifier identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list float call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call identifier argument_list identifier float expression_statement assignment identifier comparison_operator parenthesized_expression binary_operator identifier call attribute identifier identifier argument_list identifier float expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript identifier identifier expression_statement assignment identifier subscript call attribute identifier identifier argument_list identifier slice unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list subscript identifier identifier expression_statement augmented_assignment identifier subscript identifier unary_operator integer expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator parenthesized_expression binary_operator identifier identifier integer expression_statement assignment identifier subscript identifier subscript identifier slice integer identifier return_statement expression_list call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier | Compute two-sided confidence interval by taking x-values corresponding to the largest PDF-values first. |
def path_end_to_end_distance(neurite):
trunk = neurite.root_node.points[0]
return max(morphmath.point_dist(l.points[-1], trunk)
for l in neurite.root_node.ileaf()) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute attribute identifier identifier identifier integer return_statement call identifier generator_expression call attribute identifier identifier argument_list subscript attribute identifier identifier unary_operator integer identifier for_in_clause identifier call attribute attribute identifier identifier identifier argument_list | Calculate and return end-to-end-distance of a given neurite. |
def prompt(text, default=None, show_default=True, invisible=False,
confirm=False, skip=False, type=None, input_function=None):
t = determine_type(type, default)
input_function = get_input_fn(input_function, invisible)
if default is not None and show_default:
text = '{} [{}]: '.format(text, default)
while True:
val = prompt_fn(input_function, text, default, t, skip, repeat=True)
if not confirm or (skip and val is None):
return val
if val == prompt_fn(input_function, 'Confirm: ', default, t, repeat=True):
return val
echo('Error: The two values you entered do not match', True) | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier true default_parameter identifier false default_parameter identifier false default_parameter identifier false default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list identifier identifier if_statement boolean_operator comparison_operator identifier none identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier while_statement true block expression_statement assignment identifier call identifier argument_list identifier identifier identifier identifier identifier keyword_argument identifier true if_statement boolean_operator not_operator identifier parenthesized_expression boolean_operator identifier comparison_operator identifier none block return_statement identifier if_statement comparison_operator identifier call identifier argument_list identifier string string_start string_content string_end identifier identifier keyword_argument identifier true block return_statement identifier expression_statement call identifier argument_list string string_start string_content string_end true | Prompts for input from the user. |
def add_user(self, name: str, email: str) -> models.User:
new_user = self.User(name=name, email=email)
self.add_commit(new_user)
return new_user | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Add a new user to the database. |
def scatter_blocks_2d(x, indices, shape):
x_shape = common_layers.shape_list(x)
x_t = tf.transpose(
tf.reshape(x, [x_shape[0], x_shape[1], -1, x_shape[-1]]), [2, 0, 1, 3])
x_t_shape = common_layers.shape_list(x_t)
indices = tf.reshape(indices, [-1, 1])
scattered_x = tf.scatter_nd(indices, x_t, x_t_shape)
scattered_x = tf.transpose(scattered_x, [1, 2, 0, 3])
return tf.reshape(scattered_x, shape) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier list subscript identifier integer subscript identifier integer unary_operator integer subscript identifier unary_operator integer list integer integer integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier list unary_operator integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier list integer integer integer integer return_statement call attribute identifier identifier argument_list identifier identifier | scatters blocks from x into shape with indices. |
def with_app(f):
@wraps(f)
def decorator(*args, **kwargs):
app = create_app()
configure_extensions(app)
configure_views(app)
return f(app=app, *args, **kwargs)
return decorator | module function_definition identifier parameters identifier block decorated_definition decorator call identifier argument_list identifier function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement call identifier argument_list identifier expression_statement call identifier argument_list identifier return_statement call identifier argument_list keyword_argument identifier identifier list_splat identifier dictionary_splat identifier return_statement identifier | Calls function passing app as first argument |
def _format_job_instance(job):
if not job:
ret = {'Error': 'Cannot contact returner or no job with this jid'}
return ret
ret = {'Function': job.get('fun', 'unknown-function'),
'Arguments': list(job.get('arg', [])),
'Target': job.get('tgt', 'unknown-target'),
'Target-type': job.get('tgt_type', 'list'),
'User': job.get('user', 'root')}
if 'metadata' in job:
ret['Metadata'] = job.get('metadata', {})
else:
if 'kwargs' in job:
if 'metadata' in job['kwargs']:
ret['Metadata'] = job['kwargs'].get('metadata', {})
if 'Minions' in job:
ret['Minions'] = job['Minions']
return ret | module function_definition identifier parameters identifier block if_statement not_operator identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end string string_start string_content string_end return_statement identifier expression_statement assignment identifier dictionary pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end list pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end pair string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end dictionary else_clause block if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator string string_start string_content string_end subscript identifier string string_start string_content string_end block expression_statement assignment subscript identifier string string_start string_content string_end call attribute subscript identifier string string_start string_content string_end identifier argument_list string string_start string_content string_end dictionary if_statement comparison_operator string string_start string_content string_end identifier block expression_statement assignment subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end return_statement identifier | Helper to format a job instance |
def _add_url(self, chunk):
if 'url' in chunk:
return chunk
public_path = chunk.get('publicPath')
if public_path:
chunk['url'] = public_path
else:
fullpath = posixpath.join(self.state.static_view_path,
chunk['name'])
chunk['url'] = self._request.static_url(fullpath)
return chunk | module function_definition identifier parameters identifier identifier block if_statement comparison_operator string string_start string_content string_end identifier block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute attribute identifier identifier identifier subscript identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Add a 'url' property to a chunk and return it |
def master(self):
if len(self.mav_master) == 0:
return None
if self.settings.link > len(self.mav_master):
self.settings.link = 1
if not self.mav_master[self.settings.link-1].linkerror:
return self.mav_master[self.settings.link-1]
for m in self.mav_master:
if not m.linkerror:
return m
return self.mav_master[self.settings.link-1] | module function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block return_statement none if_statement comparison_operator attribute attribute identifier identifier identifier call identifier argument_list attribute identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier integer if_statement not_operator attribute subscript attribute identifier identifier binary_operator attribute attribute identifier identifier identifier integer identifier block return_statement subscript attribute identifier identifier binary_operator attribute attribute identifier identifier identifier integer for_statement identifier attribute identifier identifier block if_statement not_operator attribute identifier identifier block return_statement identifier return_statement subscript attribute identifier identifier binary_operator attribute attribute identifier identifier identifier integer | return the currently chosen mavlink master object |
def delete_policy(self, policy):
return self.manager.delete_policy(scaling_group=self, policy=policy) | module function_definition identifier parameters identifier identifier block return_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier | Deletes the specified policy from this scaling group. |
def _write_pidfile(self):
flags = os.O_CREAT | os.O_RDWR
try:
flags = flags | os.O_EXLOCK
except AttributeError:
pass
self._pid_fd = os.open(self.pidfile, flags, 0o666 & ~self.umask)
os.write(self._pid_fd, str(os.getpid()).encode('utf-8')) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier try_statement block expression_statement assignment identifier binary_operator identifier attribute identifier identifier except_clause identifier block pass_statement expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list attribute identifier identifier identifier binary_operator integer unary_operator attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier call attribute call identifier argument_list call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end | Create, write to, and lock the PID file. |
def content_present(self, x: int, y: int) -> bool:
if (x, y) in self.entries:
return True
if any(v.x == x and v.y1 < y < v.y2 for v in self.vertical_lines):
return True
if any(line_y == y and x1 < x < x2
for line_y, x1, x2, _ in self.horizontal_lines):
return True
return False | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type identifier type identifier block if_statement comparison_operator tuple identifier identifier attribute identifier identifier block return_statement true if_statement call identifier generator_expression boolean_operator comparison_operator attribute identifier identifier identifier comparison_operator attribute identifier identifier identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier block return_statement true if_statement call identifier generator_expression boolean_operator comparison_operator identifier identifier comparison_operator identifier identifier identifier for_in_clause pattern_list identifier identifier identifier identifier attribute identifier identifier block return_statement true return_statement false | Determines if a line or printed text is at the given location. |
def from_kirbidir(directory_path):
cc = CCACHE()
dir_path = os.path.join(os.path.abspath(directory_path), '*.kirbi')
for filename in glob.glob(dir_path):
with open(filename, 'rb') as f:
kirbidata = f.read()
kirbi = KRBCRED.load(kirbidata).native
cc.add_kirbi(kirbi)
return cc | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list identifier block with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier identifier expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Iterates trough all .kirbi files in a given directory and converts all of them into one CCACHE object |
def invoke(ctx, name, profile, stage):
factory = ctx.obj['factory']
factory.profile = profile
try:
invoke_handler = factory.create_lambda_invoke_handler(name, stage)
payload = factory.create_stdin_reader().read()
invoke_handler.invoke(payload)
except NoSuchFunctionError as e:
err = click.ClickException(
"could not find a lambda function named %s." % e.name)
err.exit_code = 2
raise err
except botocore.exceptions.ClientError as e:
error = e.response['Error']
err = click.ClickException(
"got '%s' exception back from Lambda\n%s"
% (error['Code'], error['Message']))
err.exit_code = 1
raise err
except UnhandledLambdaError:
err = click.ClickException(
"Unhandled exception in Lambda function, details above.")
err.exit_code = 1
raise err
except ReadTimeout as e:
err = click.ClickException(e.message)
err.exit_code = 1
raise err | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier argument_list expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement assignment attribute identifier identifier integer raise_statement identifier except_clause as_pattern attribute attribute identifier identifier identifier as_pattern_target identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment attribute identifier identifier integer raise_statement identifier except_clause identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier integer raise_statement identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment attribute identifier identifier integer raise_statement identifier | Invoke the deployed lambda function NAME. |
def run_once(func):
def _inner(*args, **kwargs):
if func.__name__ in CTX.run_once:
LOGGER.info('skipping %s', func.__name__)
return CTX.run_once[func.__name__]
LOGGER.info('running: %s', func.__name__)
result = func(*args, **kwargs)
CTX.run_once[func.__name__] = result
return result
return _inner | module function_definition identifier parameters identifier block function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier return_statement subscript attribute identifier identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement assignment identifier call identifier argument_list list_splat identifier dictionary_splat identifier expression_statement assignment subscript attribute identifier identifier attribute identifier identifier identifier return_statement identifier return_statement identifier | Simple decorator to ensure a function is ran only once |
def create_room(room):
if room.custom_server:
return
def _create_room(xmpp):
muc = xmpp.plugin['xep_0045']
muc.joinMUC(room.jid, xmpp.requested_jid.user)
muc.configureRoom(room.jid, _set_form_values(xmpp, room))
current_plugin.logger.info('Creating room %s', room.jid)
_execute_xmpp(_create_room) | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier call identifier argument_list identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call identifier argument_list identifier | Creates a MUC room on the XMPP server. |
def add_instruction(self, reil_instruction):
for expr in self._translator.translate(reil_instruction):
self._solver.add(expr) | module function_definition identifier parameters identifier identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier | Add an instruction for analysis. |
def _safe_mkdir(directory):
try:
os.makedirs(directory)
except OSError as error:
if error.errno != errno.EEXIST:
raise error | module function_definition identifier parameters identifier block try_statement block expression_statement call attribute identifier identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block raise_statement identifier | Create a directory, ignoring errors if it already exists. |
def output_links(self):
output_links = []
pm_dict = self.get_dict()
output_links.append('surface_sample')
if pm_dict['target_volume'] != 0.0:
output_links.append('cell')
return output_links | module function_definition identifier parameters identifier block expression_statement assignment identifier list expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator subscript identifier string string_start string_content string_end float block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement identifier | Return list of output link names |
def clean(self,x):
return x[~np.any(np.isnan(x) | np.isinf(x),axis=1)] | module function_definition identifier parameters identifier identifier block return_statement subscript identifier unary_operator call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier keyword_argument identifier integer | remove nan and inf rows from x |
def phi_a(mass1, mass2, spin1x, spin1y, spin2x, spin2y):
phi1 = phi_from_spinx_spiny(primary_spin(mass1, mass2, spin1x, spin2x),
primary_spin(mass1, mass2, spin1y, spin2y))
phi2 = phi_from_spinx_spiny(secondary_spin(mass1, mass2, spin1x, spin2x),
secondary_spin(mass1, mass2, spin1y, spin2y))
return (phi1 - phi2) % (2 * numpy.pi) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier identifier identifier call identifier argument_list identifier identifier identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier identifier identifier identifier call identifier argument_list identifier identifier identifier identifier return_statement binary_operator parenthesized_expression binary_operator identifier identifier parenthesized_expression binary_operator integer attribute identifier identifier | Returns the angle between the in-plane perpendicular spins. |
def select(table, index_track, field_name, op, value, includeMissing):
result = []
result_index = []
counter = 0
for row in table:
if detect_fields(field_name, convert_to_dict(row)):
final_value = get_value(row, field_name)
if do_op(final_value, op, value):
result.append(row)
result_index.append(index_track[counter])
else:
if includeMissing:
result.append(row)
result_index.append(index_track[counter])
counter += 1
return (result, result_index) | module function_definition identifier parameters identifier identifier identifier identifier identifier identifier block expression_statement assignment identifier list expression_statement assignment identifier list expression_statement assignment identifier integer for_statement identifier identifier block if_statement call identifier argument_list identifier call identifier argument_list identifier block expression_statement assignment identifier call identifier argument_list identifier identifier if_statement call identifier argument_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier identifier else_clause block if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list subscript identifier identifier expression_statement augmented_assignment identifier integer return_statement tuple identifier identifier | Modifies the table and index_track lists based on the comparison. |
def setup_completion(shell):
import glob
try:
import readline
except ImportError:
import pyreadline as readline
def _complete(text, state):
buf = readline.get_line_buffer()
if buf.startswith('help ') or " " not in buf:
return [x for x in shell.valid_identifiers() if x.startswith(text)][state]
return (glob.glob(os.path.expanduser(text)+'*')+[None])[state]
readline.set_completer_delims(' \t\n;')
if readline.__doc__ is not None and 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
readline.set_completer(_complete) | module function_definition identifier parameters identifier block import_statement dotted_name identifier try_statement block import_statement dotted_name identifier except_clause identifier block import_statement aliased_import dotted_name identifier identifier function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement boolean_operator call attribute identifier identifier argument_list string string_start string_content string_end comparison_operator string string_start string_content string_end identifier block return_statement subscript list_comprehension identifier for_in_clause identifier call attribute identifier identifier argument_list if_clause call attribute identifier identifier argument_list identifier identifier return_statement subscript parenthesized_expression binary_operator call attribute identifier identifier argument_list binary_operator call attribute attribute identifier identifier identifier argument_list identifier string string_start string_content string_end list none identifier expression_statement call attribute identifier identifier argument_list string string_start string_content escape_sequence escape_sequence string_end if_statement boolean_operator comparison_operator attribute identifier identifier none comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end else_clause block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier | Setup readline to tab complete in a cross platform way. |
def write(self, obj):
accept = self.request.headers.get("Accept")
if "json" in accept:
if JsonDefaultHandler.__parser is None:
JsonDefaultHandler.__parser = Parser()
super(JsonDefaultHandler, self).write(JsonDefaultHandler.__parser.encode(obj))
return
super(JsonDefaultHandler, self).write(obj) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block if_statement comparison_operator attribute identifier identifier none block expression_statement assignment attribute identifier identifier call identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier return_statement expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list identifier | Print object on output |
def _next_pattern(self):
current_state = self.state_stack[-1]
position = self._position
for pattern in self.patterns:
if current_state not in pattern.states:
continue
m = pattern.regex.match(self.source, position)
if not m:
continue
position = m.end()
token = None
if pattern.next_state:
self.state_stack.append(pattern.next_state)
if pattern.action:
callback = getattr(self, pattern.action, None)
if callback is None:
raise RuntimeError(
"No method defined for pattern action %s!" %
pattern.action)
if "token" in m.groups():
value = m.group("token")
else:
value = m.group(0)
token = callback(string=value, match=m,
pattern=pattern)
self._position = position
return token
self._error("Don't know how to match next. Did you forget quotes?",
start=self._position, end=self._position + 1) | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript attribute identifier identifier unary_operator integer expression_statement assignment identifier attribute identifier identifier for_statement identifier attribute identifier identifier block if_statement comparison_operator identifier attribute identifier identifier block continue_statement expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier if_statement not_operator identifier block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier none if_statement attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier none if_statement comparison_operator identifier none block raise_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier 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 string string_start string_content string_end else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier binary_operator attribute identifier identifier integer | Parses the next pattern by matching each in turn. |
async def make_transition_register(self, request: 'Request'):
register = {}
for stack in self._stacks:
register = await stack.patch_register(register, request)
return register | module function_definition identifier parameters identifier typed_parameter identifier type string string_start string_content string_end block expression_statement assignment identifier dictionary for_statement identifier attribute identifier identifier block expression_statement assignment identifier await call attribute identifier identifier argument_list identifier identifier return_statement identifier | Use all underlying stacks to generate the next transition register. |
def create_scroll_region(self):
canvas_width = 0
canvas_height = 0
for label in self._category_labels.values():
width = label.winfo_reqwidth()
canvas_height += label.winfo_reqheight()
canvas_width = width if width > canvas_width else canvas_width
self._canvas_categories.config(scrollregion="0 0 {0} {1}".format(canvas_width, canvas_height)) | module function_definition identifier parameters identifier block expression_statement assignment identifier integer expression_statement assignment identifier integer for_statement identifier call attribute attribute identifier identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier conditional_expression identifier comparison_operator identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier identifier | Setup the scroll region on the Canvas |
def cli(env,
format='table',
config=None,
verbose=0,
proxy=None,
really=False,
demo=False,
**kwargs):
env.skip_confirmations = really
env.config_file = config
env.format = format
env.ensure_client(config_file=config, is_demo=demo, proxy=proxy)
env.vars['_start'] = time.time()
logger = logging.getLogger()
if demo is False:
logger.addHandler(logging.StreamHandler())
else:
logging.getLogger("urllib3").setLevel(logging.WARNING)
logger.addHandler(logging.NullHandler())
logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG))
env.vars['_timings'] = SoftLayer.DebugTransport(env.client.transport)
env.client.transport = env.vars['_timings'] | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier none default_parameter identifier integer default_parameter identifier none default_parameter identifier false default_parameter identifier false dictionary_splat_pattern identifier block expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator identifier false block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list else_clause block expression_statement call attribute call attribute identifier identifier argument_list string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier attribute identifier identifier expression_statement assignment subscript attribute identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier subscript attribute identifier identifier string string_start string_content string_end | Main click CLI entry-point. |
def each_img(img_dir):
for fname in utils.each_img(img_dir):
fname = os.path.join(img_dir, fname)
yield cv.imread(fname), fname | module function_definition identifier parameters identifier block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier expression_statement yield expression_list call attribute identifier identifier argument_list identifier identifier | Reads and iterates through each image file in the given directory |
def create_default_element(self, name):
found = self.root.find(name)
if found is not None:
return found
ele = ET.Element(name)
self.root.append(ele)
return ele | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement identifier | Creates a <@name/> tag under root if there is none. |
def update(self, td):
self.sprite.last_position = self.sprite.position
self.sprite.last_velocity = self.sprite.velocity
if self.particle_group != None:
self.update_particle_group(td) | module function_definition identifier parameters identifier identifier block expression_statement assignment attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier none block expression_statement call attribute identifier identifier argument_list identifier | Update state of ball |
def execution_duration(self):
duration = None
if self.execution_start and self.execution_end:
delta = self.execution_end - self.execution_start
duration = delta.total_seconds()
return duration | module function_definition identifier parameters identifier block expression_statement assignment identifier none if_statement boolean_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment identifier binary_operator attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list return_statement identifier | Returns total BMDS execution time, in seconds. |
def start(self):
global parallel
for self.i in range(0, self.length):
if parallel:
self.thread.append(myThread(self.url[ self.i ], self.directory, self.i,
self.min_file_size, self.max_file_size, self.no_redirects))
else:
self.thread.append(myThread(self.url, self.directory, self.i , self.min_file_size,
self.max_file_size, self.no_redirects))
self.progress[self.i]["value"] = 0
self.bytes[self.i] = 0
self.thread[self.i].start()
self.read_bytes() | module function_definition identifier parameters identifier block global_statement identifier for_statement attribute identifier identifier call identifier argument_list integer attribute identifier identifier block if_statement identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list subscript attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment subscript subscript attribute identifier identifier attribute identifier identifier string string_start string_content string_end integer expression_statement assignment subscript attribute identifier identifier attribute identifier identifier integer expression_statement call attribute subscript attribute identifier identifier attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list | function to initialize thread for downloading |
def _update_sys_path(self, package_path=None):
self.package_path = package_path
if not self.package_path in sys.path:
sys.path.append(self.package_path) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment attribute identifier identifier identifier if_statement not_operator comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier | Updates and adds current directory to sys path |
def balanced_binary_tree(n_leaves):
def _balanced_subtree(leaves):
if len(leaves) == 1:
return leaves[0]
elif len(leaves) == 2:
return (leaves[0], leaves[1])
else:
split = len(leaves) // 2
return (_balanced_subtree(leaves[:split]),
_balanced_subtree(leaves[split:]))
return _balanced_subtree(np.arange(n_leaves)) | module function_definition identifier parameters identifier block function_definition identifier parameters identifier block if_statement comparison_operator call identifier argument_list identifier integer block return_statement subscript identifier integer elif_clause comparison_operator call identifier argument_list identifier integer block return_statement tuple subscript identifier integer subscript identifier integer else_clause block expression_statement assignment identifier binary_operator call identifier argument_list identifier integer return_statement tuple call identifier argument_list subscript identifier slice identifier call identifier argument_list subscript identifier slice identifier return_statement call identifier argument_list call attribute identifier identifier argument_list identifier | Create a balanced binary tree |
def iter_finds(regex_obj, s):
if isinstance(regex_obj, str):
for m in re.finditer(regex_obj, s):
yield m.group()
else:
for m in regex_obj.finditer(s):
yield m.group() | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block for_statement identifier call attribute identifier identifier argument_list identifier identifier block expression_statement yield call attribute identifier identifier argument_list else_clause block for_statement identifier call attribute identifier identifier argument_list identifier block expression_statement yield call attribute identifier identifier argument_list | Generate all matches found within a string for a regex and yield each match as a string |
def register(self, library: str, cbl: Callable[['_AsyncLib'], None]):
self._handlers[library] = cbl | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_parameter identifier type generic_type identifier type_parameter type list string string_start string_content string_end type none block expression_statement assignment subscript attribute identifier identifier identifier identifier | Registers a callable to set up a library. |
def filter(self, info, releases):
for version in list(releases.keys()):
if any(pattern.match(version) for pattern in self.patterns):
del releases[version] | module function_definition identifier parameters identifier identifier identifier block for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block if_statement call identifier generator_expression call attribute identifier identifier argument_list identifier for_in_clause identifier attribute identifier identifier block delete_statement subscript identifier identifier | Remove all release versions that match any of the specificed patterns. |
def Get(self):
args = flow_pb2.ApiGetFlowArgs(
client_id=self.client_id, flow_id=self.flow_id)
data = self._context.SendRequest("GetFlow", args)
return Flow(data=data, context=self._context) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end identifier return_statement call identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier | Fetch flow's data and return proper Flow object. |
def delete_network_postcommit(self, context):
network = context.current
log_context("delete_network_postcommit: network", network)
segments = context.network_segments
tenant_id = network['project_id']
self.delete_segments(segments)
self.delete_network(network)
self.delete_tenant_if_removed(tenant_id) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement call identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier | Delete the network from CVX |
def search_complete(self, completed):
self.result_browser.set_sorting(ON)
self.find_options.ok_button.setEnabled(True)
self.find_options.stop_button.setEnabled(False)
self.status_bar.hide()
self.result_browser.expandAll()
if self.search_thread is None:
return
self.sig_finished.emit()
found = self.search_thread.get_results()
self.stop_and_reset_thread()
if found is not None:
results, pathlist, nb, error_flag = found
self.result_browser.show() | module function_definition identifier parameters identifier identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list true expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list false expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier none block return_statement expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment pattern_list identifier identifier identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list | Current search thread has finished |
def option(self, section, option):
if self.config.has_section(section):
if self.config.has_option(section, option):
return (True, self.config.get(section, option))
return (False, 'Option: ' + option + ' does not exist')
return (False, 'Section: ' + section + ' does not exist') | module function_definition identifier parameters identifier identifier identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier block if_statement call attribute attribute identifier identifier identifier argument_list identifier identifier block return_statement tuple true call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement tuple false binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end return_statement tuple false binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content string_end | Returns the value of the option |
def unit(self):
s = self.x * self.x + self.y * self.y
if s < 1e-5:
return Point(0,0)
s = math.sqrt(s)
return Point(self.x / s, self.y / s) | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier attribute identifier identifier binary_operator attribute identifier identifier attribute identifier identifier if_statement comparison_operator identifier float block return_statement call identifier argument_list integer integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call identifier argument_list binary_operator attribute identifier identifier identifier binary_operator attribute identifier identifier identifier | Return unit vector of a point. |
def bpoints(self):
return self.start, self.control1, self.control2, self.end | module function_definition identifier parameters identifier block return_statement expression_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier | returns the Bezier control points of the segment. |
def addRnaQuantificationSet(self):
self._openRepo()
dataset = self._repo.getDatasetByName(self._args.datasetName)
if self._args.name is None:
name = getNameFromPath(self._args.filePath)
else:
name = self._args.name
rnaQuantificationSet = rna_quantification.SqliteRnaQuantificationSet(
dataset, name)
referenceSetName = self._args.referenceSetName
if referenceSetName is None:
raise exceptions.RepoManagerException(
"A reference set name must be provided")
referenceSet = self._repo.getReferenceSetByName(referenceSetName)
rnaQuantificationSet.setReferenceSet(referenceSet)
rnaQuantificationSet.populateFromFile(self._args.filePath)
rnaQuantificationSet.setAttributes(json.loads(self._args.attributes))
self._updateRepo(
self._repo.insertRnaQuantificationSet, rnaQuantificationSet) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute attribute identifier identifier identifier if_statement comparison_operator attribute attribute identifier identifier identifier none block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier else_clause block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier none block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute attribute identifier identifier identifier identifier | Adds an rnaQuantificationSet into this repo |
def read(*paths):
basedir = os.path.dirname(__file__)
fullpath = os.path.join(basedir, *paths)
contents = io.open(fullpath, encoding='utf-8').read().strip()
return contents | module function_definition identifier parameters list_splat_pattern identifier 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 list_splat identifier expression_statement assignment identifier call attribute call attribute call attribute identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end identifier argument_list identifier argument_list return_statement identifier | Read a text file. |
def _set_flask_alembic():
from flask_alembic import Alembic
application.app.extensions["sqlalchemy"] = type('', (), {"db": db})
alembic = Alembic()
alembic.init_app(application.app)
return alembic | module function_definition identifier parameters block import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment subscript attribute attribute identifier identifier identifier string string_start string_content string_end call identifier argument_list string string_start string_end tuple dictionary pair string string_start string_content string_end identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier return_statement identifier | Add the SQLAlchemy object in the global extension |
def load_ui_file(name):
ui = gtk.Builder()
ui.add_from_file(os.path.join(runtime.data_dir, name))
return ui | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier return_statement identifier | loads interface from the glade file; sorts out the path business |
def request(self, method, url, data=None, headers=None, **kwargs):
_credential_refresh_attempt = kwargs.pop(
'_credential_refresh_attempt', 0)
request_headers = headers.copy() if headers is not None else {}
self.credentials.before_request(
self._auth_request, method, url, request_headers)
response = super(AuthorizedSession, self).request(
method, url, data=data, headers=request_headers, **kwargs)
if (response.status_code in self._refresh_status_codes
and _credential_refresh_attempt < self._max_refresh_attempts):
_LOGGER.info(
'Refreshing credentials due to a %s response. Attempt %s/%s.',
response.status_code, _credential_refresh_attempt + 1,
self._max_refresh_attempts)
auth_request_with_timeout = functools.partial(
self._auth_request, timeout=self._refresh_timeout)
self.credentials.refresh(auth_request_with_timeout)
return self.request(
method, url, data=data, headers=headers,
_credential_refresh_attempt=_credential_refresh_attempt + 1,
**kwargs)
return response | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none default_parameter identifier none dictionary_splat_pattern identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier conditional_expression call attribute identifier identifier argument_list comparison_operator identifier none dictionary expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier identifier identifier expression_statement assignment identifier call attribute call identifier argument_list identifier identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier dictionary_splat identifier if_statement parenthesized_expression boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier binary_operator identifier integer attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier binary_operator identifier integer dictionary_splat identifier return_statement identifier | Implementation of Requests' request. |
def makediagram(edges):
graph = pydot.Dot(graph_type='digraph')
nodes = edges2nodes(edges)
epnodes = [(node,
makeanode(node[0])) for node in nodes if nodetype(node)=="epnode"]
endnodes = [(node,
makeendnode(node[0])) for node in nodes if nodetype(node)=="EndNode"]
epbr = [(node, makeabranch(node)) for node in nodes if not istuple(node)]
nodedict = dict(epnodes + epbr + endnodes)
for value in list(nodedict.values()):
graph.add_node(value)
for e1, e2 in edges:
graph.add_edge(pydot.Edge(nodedict[e1], nodedict[e2]))
return graph | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier list_comprehension tuple identifier call identifier argument_list subscript identifier integer for_in_clause identifier identifier if_clause comparison_operator call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier list_comprehension tuple identifier call identifier argument_list subscript identifier integer for_in_clause identifier identifier if_clause comparison_operator call identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier list_comprehension tuple identifier call identifier argument_list identifier for_in_clause identifier identifier if_clause not_operator call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list binary_operator binary_operator identifier identifier identifier for_statement identifier call identifier argument_list call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list identifier for_statement pattern_list identifier identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list subscript identifier identifier subscript identifier identifier return_statement identifier | make the diagram with the edges |
def _process_response(cls, response):
if len(response) != 1:
raise BadResponseError("Malformed response: {}".format(response))
stats = list(itervalues(response))[0]
if not len(stats):
raise BadResponseError("Malformed response for host: {}".format(stats))
return stats | 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 call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier subscript call identifier argument_list call identifier argument_list identifier integer if_statement not_operator call identifier argument_list identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier return_statement identifier | Examine the response and raise an error is something is off |
def unpack_rawr_zip_payload(table_sources, payload):
from tilequeue.query.common import Table
from io import BytesIO
zfh = zipfile.ZipFile(BytesIO(payload), 'r')
def get_table(table_name):
data = zfh.open(table_name, 'r').read()
unpacker = Unpacker(file_like=BytesIO(data))
source = table_sources[table_name]
return Table(source, unpacker)
return get_table | module function_definition identifier parameters identifier identifier block import_from_statement dotted_name identifier identifier identifier dotted_name identifier import_from_statement dotted_name identifier dotted_name identifier expression_statement assignment identifier call attribute identifier identifier argument_list call identifier argument_list identifier string string_start string_content string_end function_definition identifier parameters identifier block expression_statement assignment identifier call attribute call attribute identifier identifier argument_list identifier string string_start string_content string_end identifier argument_list expression_statement assignment identifier call identifier argument_list keyword_argument identifier call identifier argument_list identifier expression_statement assignment identifier subscript identifier identifier return_statement call identifier argument_list identifier identifier return_statement identifier | unpack a zipfile and turn it into a callable "tables" object. |
def list_cache_settings(self, service_id, version_number):
content = self._fetch("/service/%s/version/%d/cache_settings" % (service_id, version_number))
return map(lambda x: FastlyCacheSettings(self, x), content) | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier return_statement call identifier argument_list lambda lambda_parameters identifier call identifier argument_list identifier identifier identifier | Get a list of all cache settings for a particular service and version. |
def ngram_diff(args, parser):
store = utils.get_data_store(args)
corpus = utils.get_corpus(args)
catalogue = utils.get_catalogue(args)
tokenizer = utils.get_tokenizer(args)
store.validate(corpus, catalogue)
if args.asymmetric:
store.diff_asymmetric(catalogue, args.asymmetric, tokenizer,
sys.stdout)
else:
store.diff(catalogue, tokenizer, sys.stdout) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier attribute identifier identifier identifier attribute identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier identifier attribute identifier identifier | Outputs the results of performing a diff query. |
def submission_filenames(round_num=None, tournament=None):
click.echo(prettify(
napi.get_submission_filenames(tournament, round_num))) | module function_definition identifier parameters default_parameter identifier none default_parameter identifier none block expression_statement call attribute identifier identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier identifier | Get filenames of your submissions |
def exp_transform(params):
weights = np.exp(np.asarray(params) - np.mean(params))
return (len(weights) / weights.sum()) * weights | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier return_statement binary_operator parenthesized_expression binary_operator call identifier argument_list identifier call attribute identifier identifier argument_list identifier | Transform parameters into exp-scale weights. |
def atlasdb_renew_peer( peer_hostport, now, con=None, path=None ):
with AtlasDBOpen(con=con, path=path) as dbcon:
if now is None:
now = time.time()
sql = "UPDATE peers SET discovery_time = ? WHERE peer_hostport = ?;"
args = (now, peer_hostport)
cur = dbcon.cursor()
res = atlasdb_query_execute( cur, sql, args )
dbcon.commit()
return True | module function_definition identifier parameters identifier identifier default_parameter identifier none default_parameter identifier none block with_statement with_clause with_item as_pattern call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier as_pattern_target identifier block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier tuple identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute identifier identifier argument_list return_statement true | Renew a peer's discovery time |
def check(self):
for unsorted in iter(self[i] for i in range(len(self) - 2) if not operator.le(self[i], self[i + 1])):
self.resort(unsorted) | module function_definition identifier parameters identifier block for_statement identifier call identifier generator_expression subscript identifier identifier for_in_clause identifier call identifier argument_list binary_operator call identifier argument_list identifier integer if_clause not_operator call attribute identifier identifier argument_list subscript identifier identifier subscript identifier binary_operator identifier integer block expression_statement call attribute identifier identifier argument_list identifier | re-sort any items in self that are not sorted |
def ask_for_confirm_with_message(cls, ui, prompt='Do you agree?', message='', **options):
return cls.get_appropriate_helper(ui).ask_for_confirm_with_message(prompt, message) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_end dictionary_splat_pattern identifier block return_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list identifier identifier | Returns True if user agrees, False otherwise |
def nv_tuple_list_replace(l, v):
_found = False
for i, x in enumerate(l):
if x[0] == v[0]:
l[i] = v
_found = True
if not _found:
l.append(v) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier false for_statement pattern_list identifier identifier call identifier argument_list identifier block if_statement comparison_operator subscript identifier integer subscript identifier integer block expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier true if_statement not_operator identifier block expression_statement call attribute identifier identifier argument_list identifier | replace a tuple in a tuple list |
def createSomeItems(store, itemType, values, counter):
for i in counter:
itemType(store=store, **values) | module function_definition identifier parameters identifier identifier identifier identifier block for_statement identifier identifier block expression_statement call identifier argument_list keyword_argument identifier identifier dictionary_splat identifier | Create some instances of a particular type in a store. |
def upload_cart(cart, collection):
cart_cols = cart_db()
cart_json = read_json_document(cart.cart_file())
try:
cart_id = cart_cols[collection].save(cart_json)
except MongoErrors.AutoReconnect:
raise JuicerConfigError("Error saving cart to `cart_host`. Ensure that this node is the master.")
return cart_id | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list try_statement block expression_statement assignment identifier call attribute subscript identifier identifier identifier argument_list identifier except_clause attribute identifier identifier block raise_statement call identifier argument_list string string_start string_content string_end return_statement identifier | Connect to mongo and store your cart in the specified collection. |
def _send_heartbeat_request(self):
if self.coordinator_unknown():
e = Errors.GroupCoordinatorNotAvailableError(self.coordinator_id)
return Future().failure(e)
elif not self._client.ready(self.coordinator_id, metadata_priority=False):
e = Errors.NodeNotReadyError(self.coordinator_id)
return Future().failure(e)
version = 0 if self.config['api_version'] < (0, 11, 0) else 1
request = HeartbeatRequest[version](self.group_id,
self._generation.generation_id,
self._generation.member_id)
log.debug("Heartbeat: %s[%s] %s", request.group, request.generation_id, request.member_id)
future = Future()
_f = self._client.send(self.coordinator_id, request)
_f.add_callback(self._handle_heartbeat_response, future, time.time())
_f.add_errback(self._failed_request, self.coordinator_id,
request, future)
return future | module function_definition identifier parameters identifier block if_statement call attribute identifier identifier argument_list block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute call identifier argument_list identifier argument_list identifier elif_clause not_operator call attribute attribute identifier identifier identifier argument_list attribute identifier identifier keyword_argument identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier return_statement call attribute call identifier argument_list identifier argument_list identifier expression_statement assignment identifier conditional_expression integer comparison_operator subscript attribute identifier identifier string string_start string_content string_end tuple integer integer integer integer expression_statement assignment identifier call subscript identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier attribute identifier identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier identifier identifier return_statement identifier | Send a heartbeat request |
def modifierFactor(chart, factor, factorObj, otherObj, aspList):
asp = aspects.aspectType(factorObj, otherObj, aspList)
if asp != const.NO_ASPECT:
return {
'factor': factor,
'aspect': asp,
'objID': otherObj.id,
'element': otherObj.element()
}
return None | module function_definition identifier parameters identifier identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier identifier if_statement comparison_operator identifier attribute identifier identifier block return_statement dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list return_statement none | Computes a factor for a modifier. |
def OnBackView(self, event):
self.historyIndex -= 1
try:
self.RestoreHistory(self.history[self.historyIndex])
except IndexError, err:
self.SetStatusText(_('No further history available')) | module function_definition identifier parameters identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer try_statement block expression_statement call attribute identifier identifier argument_list subscript attribute identifier identifier attribute identifier identifier except_clause identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list string string_start string_content string_end | Request to move backward in the history |
def matrixToMathTransform(matrix):
if isinstance(matrix, ShallowTransform):
return matrix
off, scl, rot = MathTransform(matrix).decompose()
return ShallowTransform(off, scl, rot) | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier expression_statement assignment pattern_list identifier identifier identifier call attribute call identifier argument_list identifier identifier argument_list return_statement call identifier argument_list identifier identifier identifier | Take a 6-tuple and return a ShallowTransform object. |
def hourly(dt=datetime.datetime.utcnow(), fmt=None):
date = datetime.datetime(dt.year, dt.month, dt.day, dt.hour, 1, 1, 0, dt.tzinfo)
if fmt is not None:
return date.strftime(fmt)
return date | module function_definition identifier parameters default_parameter identifier call attribute attribute identifier identifier identifier argument_list default_parameter identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier integer integer integer attribute identifier identifier if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list identifier return_statement identifier | Get a new datetime object every hour. |
def df(self, list_of_points, force_read=True):
his = []
for point in list_of_points:
try:
his.append(self._findPoint(point, force_read=force_read).history)
except ValueError as ve:
self._log.error("{}".format(ve))
continue
if not _PANDAS:
return dict(zip(list_of_points, his))
return pd.DataFrame(dict(zip(list_of_points, his))) | module function_definition identifier parameters identifier identifier default_parameter identifier true block expression_statement assignment identifier list for_statement identifier identifier block try_statement block expression_statement call attribute identifier identifier argument_list attribute call attribute identifier identifier argument_list identifier keyword_argument identifier identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier continue_statement if_statement not_operator identifier block return_statement call identifier argument_list call identifier argument_list identifier identifier return_statement call attribute identifier identifier argument_list call identifier argument_list call identifier argument_list identifier identifier | When connected, calling DF should force a reading on the network. |
def meta_dump_or_deepcopy(meta):
if DEBUG_META_REFERENCES:
from rafcon.gui.helpers.meta_data import meta_data_reference_check
meta_data_reference_check(meta)
return copy.deepcopy(meta) | module function_definition identifier parameters identifier block if_statement identifier block import_from_statement dotted_name identifier identifier identifier identifier dotted_name identifier expression_statement call identifier argument_list identifier return_statement call attribute identifier identifier argument_list identifier | Function to observe meta data vivi-dict copy process and to debug it at one point |
def delay(self, params, now=None):
if now is None:
now = time.time()
if not self.last:
self.last = now
elif now < self.last:
now = self.last
leaked = now - self.last
self.last = now
self.level = max(self.level - leaked, 0)
difference = self.level + self.limit.cost - self.limit.unit_value
if difference >= self.eps:
self.next = now + difference
return difference
self.level += self.limit.cost
self.next = now
return None | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute identifier identifier argument_list if_statement not_operator attribute identifier identifier block expression_statement assignment attribute identifier identifier identifier elif_clause comparison_operator identifier attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier binary_operator identifier attribute identifier identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier call identifier argument_list binary_operator attribute identifier identifier identifier integer expression_statement assignment identifier binary_operator binary_operator attribute identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier if_statement comparison_operator identifier attribute identifier identifier block expression_statement assignment attribute identifier identifier binary_operator identifier identifier return_statement identifier expression_statement augmented_assignment attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement none | Determine delay until next request. |
def store_async_result(async_id, async_result):
logging.debug("Storing result for %s", async_id)
key = FuriousAsyncMarker(
id=async_id, result=json.dumps(async_result.to_dict()),
status=async_result.status).put()
logging.debug("Setting Async result %s using marker: %s.", async_result,
key) | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier expression_statement assignment identifier call attribute call identifier argument_list keyword_argument identifier identifier keyword_argument identifier call attribute identifier identifier argument_list call attribute identifier identifier argument_list keyword_argument identifier attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier | Persist the Async's result to the datastore. |
def _token_auth(self):
return TcExTokenAuth(
self,
self.args.tc_token,
self.args.tc_token_expires,
self.args.tc_api_path,
self.tcex.log,
) | module function_definition identifier parameters identifier block return_statement call identifier argument_list identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier attribute attribute identifier identifier identifier | Add ThreatConnect Token Auth to Session. |
def _get_predicton_csv_lines(data, headers, images):
if images:
data = copy.deepcopy(data)
for img_col in images:
for d, im in zip(data, images[img_col]):
if im == '':
continue
im = im.copy()
im.thumbnail((299, 299), Image.ANTIALIAS)
buf = BytesIO()
im.save(buf, "JPEG")
content = base64.urlsafe_b64encode(buf.getvalue()).decode('ascii')
d[img_col] = content
csv_lines = []
for d in data:
buf = six.StringIO()
writer = csv.DictWriter(buf, fieldnames=headers, lineterminator='')
writer.writerow(d)
csv_lines.append(buf.getvalue())
return csv_lines | module function_definition identifier parameters identifier identifier identifier block if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier subscript identifier identifier block if_statement comparison_operator identifier string string_start string_end block continue_statement expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list tuple integer integer attribute identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement call attribute identifier identifier argument_list identifier string string_start string_content string_end expression_statement assignment identifier call attribute call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier argument_list string string_start string_content string_end expression_statement assignment subscript identifier identifier identifier expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier string string_start string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list return_statement identifier | Create CSV lines from list-of-dict data. |
def __ungrabHotkey(self, key, modifiers, window):
logger.debug("Ungrabbing hotkey: %r %r", modifiers, key)
try:
keycode = self.__lookupKeyCode(key)
mask = 0
for mod in modifiers:
mask |= self.modMasks[mod]
window.ungrab_key(keycode, mask)
if Key.NUMLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.NUMLOCK])
if Key.CAPSLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.CAPSLOCK])
if Key.CAPSLOCK in self.modMasks and Key.NUMLOCK in self.modMasks:
window.ungrab_key(keycode, mask|self.modMasks[Key.CAPSLOCK]|self.modMasks[Key.NUMLOCK])
except Exception as e:
logger.warning("Failed to ungrab hotkey %r %r: %s", modifiers, key, str(e)) | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier integer for_statement identifier identifier block expression_statement augmented_assignment identifier subscript attribute identifier identifier identifier expression_statement call attribute identifier identifier argument_list identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier binary_operator identifier subscript attribute identifier identifier attribute identifier identifier if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier binary_operator identifier subscript attribute identifier identifier attribute identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list identifier binary_operator binary_operator identifier subscript attribute identifier identifier attribute identifier identifier subscript attribute identifier identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end identifier identifier call identifier argument_list identifier | Ungrab a specific hotkey in the given window |
def _write_commits_to_release_notes(self):
with open(self.release_file, 'a') as out:
out.write("==========\n{}\n".format(self.tag))
for commit in self.commits:
try:
msg = commit[1]
if msg != "cosmetic":
out.write("-" + msg + "\n")
except:
pass | module function_definition identifier parameters identifier block with_statement with_clause with_item as_pattern call identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence string_end identifier argument_list attribute identifier identifier for_statement identifier attribute identifier identifier block try_statement block expression_statement assignment identifier subscript identifier integer if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content string_end identifier string string_start string_content escape_sequence string_end except_clause block pass_statement | writes commits to the releasenotes file by appending to the end |
def read_pdb(pdbfname, as_string=False):
pybel.ob.obErrorLog.StopLogging()
if os.name != 'nt':
maxsize = resource.getrlimit(resource.RLIMIT_STACK)[-1]
resource.setrlimit(resource.RLIMIT_STACK, (min(2 ** 28, maxsize), maxsize))
sys.setrecursionlimit(10 ** 5)
return readmol(pdbfname, as_string=as_string) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment identifier subscript call attribute identifier identifier argument_list attribute identifier identifier unary_operator integer expression_statement call attribute identifier identifier argument_list attribute identifier identifier tuple call identifier argument_list binary_operator integer integer identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator integer integer return_statement call identifier argument_list identifier keyword_argument identifier identifier | Reads a given PDB file and returns a Pybel Molecule. |
def _remote_add(self):
self.repo.create_remote(
'origin',
'git@github.com:{username}/{repo}.git'.format(
username=self.metadata.username,
repo=self.metadata.name)) | module function_definition identifier parameters identifier block expression_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier keyword_argument identifier attribute attribute identifier identifier identifier | Execute git remote add. |
def validate(data):
if not isinstance(data, dict):
error('Data must be a dictionary.')
for value in data.values():
if not isinstance(value, basestring):
error('Values must be strings.') | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end for_statement identifier call attribute identifier identifier argument_list block if_statement not_operator call identifier argument_list identifier identifier block expression_statement call identifier argument_list string string_start string_content string_end | Query data and result data must have keys who's values are strings. |
def _network_show(self, name, network_lst):
for net in network_lst:
if net.label == name:
return net.__dict__
return {} | module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier identifier block return_statement attribute identifier identifier return_statement dictionary | Parse the returned network list |
def StartObject(self, numfields):
self.assertNotNested()
self.current_vtable = [0 for _ in range_func(numfields)]
self.objectEnd = self.Offset()
self.nested = True | module function_definition identifier parameters identifier identifier block expression_statement call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier list_comprehension integer for_in_clause identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier true | StartObject initializes bookkeeping for writing a new object. |
def render_doc(self):
if self._doc_view:
return self._doc_view()
elif not self._doc:
self.abort(self.bc_HTTPStatus_NOT_FOUND)
res = render_template('swagger-ui.html', title=self.title, specs_url=self.specs_url)
res = res.replace(self.complexReplaceString,self.APIDOCSPath)
regexp="\"https?:\/\/[a-zA-Z0\-9._]*(:[0-9]*)?" + self.internal_api_prefix.replace("/","\/") + "\/swagger.json\""
regexp="\"https?:\/\/[a-zA-Z0\-9._]*(:[0-9]*)?" + self.internal_apidoc_prefix.replace("/","\/") + "\/swagger.json\""
p = re.compile(regexp)
res = p.sub("\"" + self.apidocsurl + "/swagger.json\"", res)
return res | module function_definition identifier parameters identifier block if_statement attribute identifier identifier block return_statement call attribute identifier identifier argument_list elif_clause not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier expression_statement assignment identifier binary_operator binary_operator string string_start string_content escape_sequence string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content escape_sequence string_end expression_statement assignment identifier binary_operator binary_operator string string_start string_content escape_sequence string_end call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end string string_start string_content escape_sequence string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier string string_start string_content escape_sequence string_end identifier return_statement identifier | Override this method to customize the documentation page |
def build(level, code, validity=None):
spatial = ':'.join((level, code))
if not validity:
return spatial
elif isinstance(validity, basestring):
return '@'.join((spatial, validity))
elif isinstance(validity, datetime):
return '@'.join((spatial, validity.date().isoformat()))
elif isinstance(validity, date):
return '@'.join((spatial, validity.isoformat()))
else:
msg = 'Unknown GeoID validity type: {0}'
raise GeoIDError(msg.format(type(validity).__name__)) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple identifier identifier if_statement not_operator identifier block return_statement identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list tuple identifier identifier elif_clause call identifier argument_list identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list tuple identifier call attribute call attribute identifier identifier argument_list identifier argument_list elif_clause call identifier argument_list identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list tuple identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment identifier string string_start string_content string_end raise_statement call identifier argument_list call attribute identifier identifier argument_list attribute call identifier argument_list identifier identifier | Serialize a GeoID from its parts |
def ConsultarPuntosVentas(self, sep="||"):
"Retorna los puntos de ventas autorizados para la utilizacion de WS"
ret = self.client.consultarPuntosVenta(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
)['respuesta']
self.__analizar_errores(ret)
array = ret.get('puntoVenta', [])
if sep is None:
return dict([(it['codigo'], it['descripcion']) for it in array])
else:
return [("%s %%s %s %%s %s" % (sep, sep, sep)) %
(it['codigo'], it['descripcion']) for it in array] | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end block expression_statement string string_start string_content string_end expression_statement assignment identifier subscript call attribute attribute identifier identifier identifier argument_list keyword_argument identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end attribute identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end list if_statement comparison_operator identifier none block return_statement call identifier argument_list list_comprehension tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier identifier else_clause block return_statement list_comprehension binary_operator parenthesized_expression binary_operator string string_start string_content string_end tuple identifier identifier identifier tuple subscript identifier string string_start string_content string_end subscript identifier string string_start string_content string_end for_in_clause identifier identifier | Retorna los puntos de ventas autorizados para la utilizacion de WS |
def do_signal(self, signame: str) -> None:
if hasattr(signal, signame):
os.kill(os.getpid(), getattr(signal, signame))
else:
self._sout.write('Unknown signal %s\n' % signame) | module function_definition identifier parameters identifier typed_parameter identifier type identifier type none block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list binary_operator string string_start string_content escape_sequence string_end identifier | Send a Unix signal |
def dispatch(self, args):
if not args.list and not args.group:
if not args.font and not args.char and not args.block:
self.info()
return
else:
args.list = args.group = True
self._display = {k: args.__dict__[k] for k in ('list', 'group', 'omit_summary')}
if args.char:
char = self._getChar(args.char)
if args.font:
self.fontChar(args.font, char)
else:
self.char(char)
else:
block = self._getBlock(args.block)
self.chars(args.font, block) | module function_definition identifier parameters identifier identifier block if_statement boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier block if_statement boolean_operator boolean_operator not_operator attribute identifier identifier not_operator attribute identifier identifier not_operator attribute identifier identifier block expression_statement call attribute identifier identifier argument_list return_statement else_clause block expression_statement assignment attribute identifier identifier assignment attribute identifier identifier true expression_statement assignment attribute identifier identifier dictionary_comprehension pair identifier subscript attribute identifier identifier identifier for_in_clause identifier tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end if_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier else_clause block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Calls proper method depending on command-line arguments. |
def create_model_class(cls, name, table_name, attrs, validations=None, *, otherattrs=None,
other_bases=None):
members = dict(table_name=table_name, attrs=attrs, validations=validations or [])
if otherattrs:
members.update(otherattrs)
return type(name, other_bases or (), members) | module function_definition identifier parameters identifier identifier identifier identifier default_parameter identifier none keyword_separator default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier boolean_operator identifier list if_statement identifier block expression_statement call attribute identifier identifier argument_list identifier return_statement call identifier argument_list identifier boolean_operator identifier tuple identifier | Creates a new class derived from ModelBase. |
def make_opfields( cls ):
opfields = {}
for opname in SERIALIZE_FIELDS.keys():
opcode = NAME_OPCODES[opname]
opfields[opcode] = SERIALIZE_FIELDS[opname]
return opfields | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment identifier subscript identifier identifier expression_statement assignment subscript identifier identifier subscript identifier identifier return_statement identifier | Calculate the virtulachain-required opfields dict. |
def addon(self, name):
cmd = ["heroku", "addons:create", name, "--app", self.name]
self._run(cmd) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end identifier string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list identifier | Set up an addon |
def write_file(content, *path):
with open(os.path.join(*path), "w") as file:
return file.write(content) | module function_definition identifier parameters identifier list_splat_pattern identifier block with_statement with_clause with_item as_pattern call identifier argument_list call attribute attribute identifier identifier identifier argument_list list_splat identifier string string_start string_content string_end as_pattern_target identifier block return_statement call attribute identifier identifier argument_list identifier | Simply write some content to a file, overriding the file if necessary. |
def resolve_and_build(self):
pdebug("resolving and building task '%s'" % self.name,
groups=["build_task"])
indent_text(indent="++2")
toret = self.build(**self.resolve_dependencies())
indent_text(indent="--2")
return toret | module function_definition identifier parameters identifier block expression_statement call identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier keyword_argument identifier list string string_start string_content string_end expression_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list dictionary_splat call attribute identifier identifier argument_list expression_statement call identifier argument_list keyword_argument identifier string string_start string_content string_end return_statement identifier | resolves the dependencies of this build target and builds it |
def summary(self, scoring):
if scoring == 'class_confusion':
print('*' * 50)
print(' Confusion Matrix ')
print('x-axis: ' + ' | '.join(list(self.class_dictionary.keys())))
print('y-axis: ' + ' | '.join(self.truth_classes))
print(self.confusion_matrix()) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator identifier string string_start string_content string_end block expression_statement call identifier argument_list binary_operator string string_start string_content string_end integer expression_statement call identifier argument_list string string_start string_content string_end expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list call identifier argument_list call attribute attribute identifier identifier identifier argument_list expression_statement call identifier argument_list binary_operator string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier expression_statement call identifier argument_list call attribute identifier identifier argument_list | Prints out the summary of validation for giving scoring function. |
def count(self) -> "CountQuery":
return CountQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._custom_filters,
) | module function_definition identifier parameters identifier type string string_start string_content string_end block return_statement call identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier attribute identifier identifier | Return count of objects in queryset instead of objects. |
def estimate_size_in_bytes(cls, magic, compression_type, key, value):
assert magic in [0, 1], "Not supported magic"
if compression_type:
return (
cls.LOG_OVERHEAD + cls.record_overhead(magic) +
cls.record_size(magic, key, value)
)
return cls.LOG_OVERHEAD + cls.record_size(magic, key, value) | module function_definition identifier parameters identifier identifier identifier identifier identifier block assert_statement comparison_operator identifier list integer integer string string_start string_content string_end if_statement identifier block return_statement parenthesized_expression binary_operator binary_operator attribute identifier identifier call attribute identifier identifier argument_list identifier call attribute identifier identifier argument_list identifier identifier identifier return_statement binary_operator attribute identifier identifier call attribute identifier identifier argument_list identifier identifier identifier | Upper bound estimate of record size. |
def build_signature(self, user_api_key, user_secret, request):
path = request.get_full_path()
sent_signature = request.META.get(
self.header_canonical('Authorization'))
signature_headers = self.get_headers_from_signature(sent_signature)
unsigned = self.build_dict_to_sign(request, signature_headers)
signer = HeaderSigner(
key_id=user_api_key, secret=user_secret,
headers=signature_headers, algorithm=self.ALGORITHM)
signed = signer.sign(unsigned, method=request.method, path=path)
return signed['authorization'] | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute 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 identifier identifier argument_list identifier identifier expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier return_statement subscript identifier string string_start string_content string_end | Return the signature for the request. |
def deurlform_app(parser, cmd, args):
parser.add_argument('value', help='the query string to decode')
args = parser.parse_args(args)
return ' '.join('%s=%s' % (key, value) for key, values in deurlform(args.value).items() for value in values) | module function_definition identifier parameters identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute string string_start string_content string_end identifier generator_expression binary_operator string string_start string_content string_end tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute call identifier argument_list attribute identifier identifier identifier argument_list for_in_clause identifier identifier | decode a query string into its key value pairs. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.