code stringlengths 51 2.34k | sequence stringlengths 186 3.94k | docstring stringlengths 11 171 |
|---|---|---|
def fishers_method(pvals):
pvals = np.asarray(pvals)
degrees_of_freedom = 2 * pvals.size
chisq_stat = np.sum(-2*np.log(pvals))
fishers_pval = stats.chi2.sf(chisq_stat, degrees_of_freedom)
return fishers_pval | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier binary_operator integer attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list binary_operator unary_operator integer call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier identifier return_statement identifier | Fisher's method for combining independent p-values. |
def store_edges(self, edges):
with open(self.get_path(OslomRunner.TMP_EDGES_FILE), "w") as writer:
for edge in edges:
writer.write("{}\t{}\t{}\n".format(
self.id_remapper.get_int_id(edge[0]),
self.id_remapper.get_int_id(edge[1]),
edge[2])) | module function_definition identifier parameters identifier identifier block with_statement with_clause with_item as_pattern call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end as_pattern_target identifier block for_statement identifier identifier block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content escape_sequence escape_sequence escape_sequence string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list subscript identifier integer call attribute attribute identifier identifier identifier argument_list subscript identifier integer subscript identifier integer | Store the temporary network edges input file with re-mapped Ids. |
def moveToPoint(self, xxx_todo_changeme2):
(x,y) = xxx_todo_changeme2
self.set_x1(float(self.get_x1()) + float(x))
self.set_x2(float(self.get_x2()) + float(x))
self.set_y1(float(self.get_y1()) + float(y))
self.set_y2(float(self.get_y2()) + float(y)) | module function_definition identifier parameters identifier identifier block expression_statement assignment tuple_pattern identifier identifier identifier expression_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator call identifier argument_list call attribute identifier identifier argument_list call identifier argument_list identifier | Moves the line to the point x,y |
def getin(m, path, default=None):
keynotfound = ':com.gooey-project/not-found'
result = reduce(lambda acc, val: acc.get(val, {keynotfound: None}), path, m)
if isinstance(result, dict) and keynotfound in result:
return default
return result | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list lambda lambda_parameters identifier identifier call attribute identifier identifier argument_list identifier dictionary pair identifier none identifier identifier if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator identifier identifier block return_statement identifier return_statement identifier | returns the value in a nested dict |
def split_by_idxs(seq, idxs):
last = 0
for idx in idxs:
if not (-len(seq) <= idx < len(seq)):
raise KeyError(f'Idx {idx} is out-of-bounds')
yield seq[last:idx]
last = idx
yield seq[last:] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier integer for_statement identifier identifier block if_statement not_operator parenthesized_expression comparison_operator unary_operator call identifier argument_list identifier identifier call identifier argument_list identifier block raise_statement call identifier argument_list string string_start string_content interpolation identifier string_content string_end expression_statement yield subscript identifier slice identifier identifier expression_statement assignment identifier identifier expression_statement yield subscript identifier slice identifier | A generator that returns sequence pieces, seperated by indexes specified in idxs. |
def items(self):
for key, task in self._tasks:
if not (task and task.result):
yield key, None
else:
yield key, json.loads(task.result)["payload"] | module function_definition identifier parameters identifier block for_statement pattern_list identifier identifier attribute identifier identifier block if_statement not_operator parenthesized_expression boolean_operator identifier attribute identifier identifier block expression_statement yield expression_list identifier none else_clause block expression_statement yield expression_list identifier subscript call attribute identifier identifier argument_list attribute identifier identifier string string_start string_content string_end | Yield the async reuslts for the context. |
def clf():
Visualizer3D._scene = Scene(background_color=Visualizer3D._scene.background_color)
Visualizer3D._scene.ambient_light = AmbientLight(color=[1.0, 1.0, 1.0], strength=1.0) | module function_definition identifier parameters block expression_statement assignment attribute identifier identifier call identifier argument_list keyword_argument identifier attribute attribute identifier identifier identifier expression_statement assignment attribute attribute identifier identifier identifier call identifier argument_list keyword_argument identifier list float float float keyword_argument identifier float | Clear the current figure |
def aschannel(self) -> 'Channel':
N = self.qubit_nb
R = 4
tensor = bk.outer(self.tensor, self.H.tensor)
tensor = bk.reshape(tensor, [2**N]*R)
tensor = bk.transpose(tensor, [0, 3, 1, 2])
return Channel(tensor, self.qubits) | module function_definition identifier parameters identifier type string string_start string_content string_end block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier integer expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier binary_operator list binary_operator integer identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier list integer integer integer integer return_statement call identifier argument_list identifier attribute identifier identifier | Converts a Gate into a Channel |
def getlist(self, name: str, default: Any = None) -> List[Any]:
return super().get(name, default) | module function_definition identifier parameters identifier typed_parameter identifier type identifier typed_default_parameter identifier type identifier none type generic_type identifier type_parameter type identifier block return_statement call attribute call identifier argument_list identifier argument_list identifier identifier | Return the entire list |
def stop(self):
try:
self.running = False
logger.info('Waiting tasks to finish...')
self.queue.join()
self.socket.close()
logger.info('Exiting (C-Ctrl again to force it)...')
except KeyboardInterrupt:
logger.info('Forced.')
sys.exit(1) | module function_definition identifier parameters identifier block try_statement block expression_statement assignment attribute identifier identifier false expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list integer | Stop server and all its threads. |
def parse_iscsiname(rule):
parser = argparse.ArgumentParser()
rules = shlex.split(rule)
rules.pop(0)
args = clean_args(vars(parser.parse_args(rules)))
parser = None
return args | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list integer expression_statement assignment identifier call identifier argument_list call identifier argument_list call attribute identifier identifier argument_list identifier expression_statement assignment identifier none return_statement identifier | Parse the iscsiname line |
def add_field(self, name, default_value=None):
self._fields[name] = default_value
def func(cluster):
return self.get(name, cluster)
setattr(self, name, func) | module function_definition identifier parameters identifier identifier default_parameter identifier none block expression_statement assignment subscript attribute identifier identifier identifier identifier function_definition identifier parameters identifier block return_statement call attribute identifier identifier argument_list identifier identifier expression_statement call identifier argument_list identifier identifier identifier | Add a field with an optional default value. |
def quick_search(limit, pretty, sort, **kw):
req = search_req_from_opts(**kw)
cl = clientv1()
page_size = min(limit, 250)
echo_json_response(call_and_wrap(
cl.quick_search, req, page_size=page_size, sort=sort
), pretty, limit) | module function_definition identifier parameters identifier identifier identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list dictionary_splat identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier integer expression_statement call identifier argument_list call identifier argument_list attribute identifier identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier identifier identifier | Execute a quick search. |
def to_gremlin(self):
self.validate()
if self.optional:
operation = u'optional'
else:
operation = u'back'
mark_name, _ = self.location.get_location_name()
return u'{operation}({mark_name})'.format(
operation=operation,
mark_name=safe_quoted_string(mark_name)) | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list if_statement attribute identifier identifier block expression_statement assignment identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list return_statement call attribute string string_start string_content string_end identifier argument_list keyword_argument identifier identifier keyword_argument identifier call identifier argument_list identifier | Return a unicode object with the Gremlin representation of this BasicBlock. |
def _get_numeric_status(self, key):
value = self._get_status(key)
if value and any(i.isdigit() for i in value):
return float(re.sub("[^0-9.]", "", value))
return None | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement boolean_operator identifier call identifier generator_expression call attribute identifier identifier argument_list for_in_clause identifier identifier block return_statement call identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_end identifier return_statement none | Extract the numeric value from the statuses object. |
def create_dataclass_loader(cls, registry, field_getters):
fields = cls.__dataclass_fields__
item_loaders = map(registry, map(attrgetter('type'), fields.values()))
getters = map(field_getters.__getitem__, fields)
loaders = list(starmap(compose, zip(item_loaders, getters)))
def dloader(obj):
return cls(*(g(obj) for g in loaders))
return dloader | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier call identifier argument_list call identifier argument_list string string_start string_content string_end call attribute identifier identifier argument_list expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call identifier argument_list identifier identifier function_definition identifier parameters identifier block return_statement call identifier argument_list list_splat generator_expression call identifier argument_list identifier for_in_clause identifier identifier return_statement identifier | create a loader for a dataclass type |
def _read_select_kqueue(k_queue):
npipes = len(NonBlockingStreamReader._streams)
kevents = [select.kevent(s.stream.fileno(),
filter=select.KQ_FILTER_READ,
flags=select.KQ_EV_ADD | select.KQ_EV_ENABLE)
for s in NonBlockingStreamReader._streams]
while NonBlockingStreamReader._run_flag:
events = k_queue.control(kevents, npipes, 0.5)
for event in events:
if event.filter == select.KQ_FILTER_READ:
NonBlockingStreamReader._read_fd(event.ident)
if npipes != len(NonBlockingStreamReader._streams):
return | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier expression_statement assignment identifier list_comprehension call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list keyword_argument identifier attribute identifier identifier keyword_argument identifier binary_operator attribute identifier identifier attribute identifier identifier for_in_clause identifier attribute identifier identifier while_statement attribute identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier identifier float for_statement identifier identifier block if_statement comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier call identifier argument_list attribute identifier identifier block return_statement | Read PIPES using BSD Kqueue |
def _addDataFile(self, filename):
if filename.endswith('.ttl'):
self._rdfGraph.parse(filename, format='n3')
else:
self._rdfGraph.parse(filename, format='xml') | module function_definition identifier parameters identifier identifier block if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier keyword_argument identifier string string_start string_content string_end | Given a filename, add it to the graph |
def update_last_backup_meta_data(self):
self.meta['last_backup']['time'] = get_time_string_for_float(self.last_backup_time)
self.meta['last_backup']['file_system_path'] = self._tmp_storage_path
self.meta['last_backup']['marked_dirty'] = self.state_machine_model.state_machine.marked_dirty | module function_definition identifier parameters identifier block expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end call identifier argument_list attribute identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute identifier identifier expression_statement assignment subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end attribute attribute attribute identifier identifier identifier identifier | Update the auto backup meta data with internal recovery information |
def initialize(self):
mkdir_p(self.archive_path)
mkdir_p(self.bin_path)
mkdir_p(self.codebase_path)
mkdir_p(self.input_basepath) | module function_definition identifier parameters identifier block expression_statement call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list attribute identifier identifier expression_statement call identifier argument_list attribute identifier identifier | Create the laboratory directories. |
def create_keys_in():
keys = Group(
Optional(Suppress("("))
+ value
+ Optional(Suppress(",") + value)
+ Optional(Suppress(")"))
)
return (Suppress(upkey("keys") + upkey("in")) + delimitedList(keys)).setResultsName(
"keys_in"
) | module function_definition identifier parameters block expression_statement assignment identifier call identifier argument_list binary_operator binary_operator binary_operator call identifier argument_list call identifier argument_list string string_start string_content string_end identifier call identifier argument_list binary_operator call identifier argument_list string string_start string_content string_end identifier call identifier argument_list call identifier argument_list string string_start string_content string_end return_statement call attribute parenthesized_expression binary_operator call identifier argument_list binary_operator call identifier argument_list string string_start string_content string_end call identifier argument_list string string_start string_content string_end call identifier argument_list identifier identifier argument_list string string_start string_content string_end | Create a grammer for the 'KEYS IN' clause used for queries |
def add_stack_frame(self, stack_frame):
if len(self.stack_frames) >= MAX_FRAMES:
self.dropped_frames_count += 1
else:
self.stack_frames.append(stack_frame.format_stack_frame_json()) | module function_definition identifier parameters identifier identifier block if_statement comparison_operator call identifier argument_list attribute identifier identifier identifier block expression_statement augmented_assignment attribute identifier identifier integer else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list call attribute identifier identifier argument_list | Add StackFrame to frames list. |
def copy(self):
connection = self.connection
del self.connection
copied_query = deepcopy(self)
copied_query.connection = connection
self.connection = connection
return copied_query | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier delete_statement attribute identifier identifier expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier identifier expression_statement assignment attribute identifier identifier identifier return_statement identifier | Deeply copies everything in the query object except the connection object is shared |
def isignored(self, relpath, directory=False):
relpath = self._relpath_no_dot(relpath)
if directory:
relpath = self._append_trailing_slash(relpath)
return self.ignore.match_file(relpath) | module function_definition identifier parameters identifier identifier default_parameter identifier false block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement call attribute attribute identifier identifier identifier argument_list identifier | Returns True if path matches pants ignore pattern. |
def log_run(self):
version = get_system_spec()['raiden']
cursor = self.conn.cursor()
cursor.execute('INSERT INTO runs(raiden_version) VALUES (?)', [version])
self.maybe_commit() | module function_definition identifier parameters identifier block expression_statement assignment identifier subscript call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end list identifier expression_statement call attribute identifier identifier argument_list | Log timestamp and raiden version to help with debugging |
def getOverlayDualAnalogTransform(self, ulOverlay, eWhich):
fn = self.function_table.getOverlayDualAnalogTransform
pvCenter = HmdVector2_t()
pfRadius = c_float()
result = fn(ulOverlay, eWhich, byref(pvCenter), byref(pfRadius))
return result, pvCenter, pfRadius.value | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier call identifier argument_list identifier identifier call identifier argument_list identifier call identifier argument_list identifier return_statement expression_list identifier identifier attribute identifier identifier | Gets the analog input to Dual Analog coordinate scale for the specified overlay. |
def _setup_eventloop(self):
if os.name == 'nt':
self.eventloop = asyncio.ProactorEventLoop()
else:
self.eventloop = asyncio.new_event_loop()
asyncio.set_event_loop(self.eventloop)
if os.name == 'posix' and isinstance(threading.current_thread(), threading._MainThread):
asyncio.get_child_watcher().attach_loop(self.eventloop) | module function_definition identifier parameters identifier block if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list else_clause block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list attribute identifier identifier if_statement boolean_operator comparison_operator attribute identifier identifier string string_start string_content string_end call identifier argument_list call attribute identifier identifier argument_list attribute identifier identifier block expression_statement call attribute call attribute identifier identifier argument_list identifier argument_list attribute identifier identifier | Sets up a new eventloop as the current one according to the OS. |
def _add_researcher_summary(samples, summary_yaml):
by_researcher = collections.defaultdict(list)
for data in (x[0] for x in samples):
researcher = utils.get_in(data, ("upload", "researcher"))
if researcher:
by_researcher[researcher].append(data["description"])
out_by_researcher = {}
for researcher, descrs in by_researcher.items():
out_by_researcher[researcher] = _summary_csv_by_researcher(summary_yaml, researcher,
set(descrs), samples[0][0])
out = []
for data in (x[0] for x in samples):
researcher = utils.get_in(data, ("upload", "researcher"))
if researcher:
data["summary"]["researcher"] = out_by_researcher[researcher]
out.append([data])
return out | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier for_statement identifier generator_expression subscript identifier integer for_in_clause identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier tuple string string_start string_content string_end string string_start string_content string_end if_statement identifier block expression_statement call attribute subscript identifier identifier identifier argument_list subscript identifier string string_start string_content string_end expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier call identifier argument_list identifier identifier call identifier argument_list identifier subscript subscript identifier integer integer expression_statement assignment identifier list for_statement identifier generator_expression subscript identifier integer for_in_clause identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier tuple string string_start string_content string_end string string_start string_content string_end if_statement identifier block expression_statement assignment subscript subscript identifier string string_start string_content string_end string string_start string_content string_end subscript identifier identifier expression_statement call attribute identifier identifier argument_list list identifier return_statement identifier | Generate summary files per researcher if organized via a LIMS. |
def send_status(self, payload):
answer = {}
data = []
if self.paused:
answer['status'] = 'paused'
else:
answer['status'] = 'running'
if len(self.queue) > 0:
data = deepcopy(self.queue.queue)
for key, item in data.items():
if 'stderr' in item:
del item['stderr']
if 'stdout' in item:
del item['stdout']
else:
data = 'Queue is empty'
answer['data'] = data
return answer | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier list if_statement attribute identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end else_clause block expression_statement assignment subscript identifier string string_start string_content string_end string string_start string_content string_end if_statement comparison_operator call identifier argument_list attribute identifier identifier integer block expression_statement assignment identifier call identifier argument_list attribute attribute identifier identifier identifier for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement comparison_operator string string_start string_content string_end identifier block delete_statement subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block delete_statement subscript identifier string string_start string_content string_end else_clause block expression_statement assignment identifier string string_start string_content string_end expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Send the daemon status and the current queue for displaying. |
def focusPrev(self, event):
try:
event.widget.tk_focusPrev().focus_set()
except TypeError:
name = event.widget.tk.call('tk_focusPrev', event.widget._w)
event.widget._nametowidget(str(name)).focus_set() | module function_definition identifier parameters identifier identifier block try_statement block expression_statement call attribute call attribute attribute identifier identifier identifier argument_list identifier argument_list except_clause identifier block expression_statement assignment identifier call attribute attribute attribute identifier identifier identifier identifier argument_list string string_start string_content string_end attribute attribute identifier identifier identifier expression_statement call attribute call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier identifier argument_list | Set focus to previous item in sequence |
def __summary(self):
text = "Time: %s\n" % self.when
text += "Comitter: %s\n" % self.editor
inst = self.timemachine.presently
if self.action_type == "dl":
text += "Deleted %s\n" % inst._object_type_text()
elif self.action_type == "cr":
text += "Created %s\n" % inst._object_type_text()
else:
text += "Modified %s\n" % inst._object_type_text()
text += self._details(nohtml=True)
return text | module function_definition identifier parameters identifier block expression_statement assignment identifier binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end attribute identifier identifier expression_statement assignment identifier attribute attribute identifier identifier identifier if_statement comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list elif_clause comparison_operator attribute identifier identifier string string_start string_content string_end block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list else_clause block expression_statement augmented_assignment identifier binary_operator string string_start string_content escape_sequence string_end call attribute identifier identifier argument_list expression_statement augmented_assignment identifier call attribute identifier identifier argument_list keyword_argument identifier true return_statement identifier | A plaintext summary of the Action, useful for debugging. |
def _confused_state(self, request: Request) -> Type[BaseState]:
origin = request.register.get(Register.STATE)
if origin in self._allowed_states:
try:
return import_class(origin)
except (AttributeError, ImportError):
pass
return import_class(settings.DEFAULT_STATE) | module function_definition identifier parameters identifier typed_parameter identifier type identifier type generic_type identifier type_parameter type identifier block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list attribute identifier identifier if_statement comparison_operator identifier attribute identifier identifier block try_statement block return_statement call identifier argument_list identifier except_clause tuple identifier identifier block pass_statement return_statement call identifier argument_list attribute identifier identifier | If we're confused, find which state to call. |
def stamp_excerpt(kb_app: kb,
sphinx_app: Sphinx,
doctree: doctree):
resources = sphinx_app.env.resources
confdir = sphinx_app.confdir
source = PurePath(doctree.attributes['source'])
docname = str(source.relative_to(confdir)).split('.rst')[0]
resource = resources.get(docname)
if resource:
excerpt = getattr(resource.props, 'excerpt', False)
auto_excerpt = getattr(resource.props, 'auto_excerpt', False)
if excerpt:
resource.excerpt = excerpt
elif not auto_excerpt:
resource.excerpt = None
else:
resource.excerpt = get_rst_excerpt(doctree, auto_excerpt) | module function_definition identifier parameters typed_parameter identifier type identifier typed_parameter identifier type identifier typed_parameter identifier type identifier block expression_statement assignment identifier attribute attribute identifier identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript call attribute call identifier argument_list call attribute identifier identifier argument_list identifier identifier argument_list string string_start string_content string_end integer expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end false expression_statement assignment identifier call identifier argument_list attribute identifier identifier string string_start string_content string_end false if_statement identifier block expression_statement assignment attribute identifier identifier identifier elif_clause not_operator identifier block expression_statement assignment attribute identifier identifier none else_clause block expression_statement assignment attribute identifier identifier call identifier argument_list identifier identifier | Walk the tree and extract excert into resource.excerpt |
def replicate(ctx, args):
slave = ClusterNode.from_uri(args.node)
master = ClusterNode.from_uri(args.master)
if not master.is_master():
ctx.abort("Node {!r} is not a master.".format(args.master))
try:
slave.replicate(master.name)
except redis.ResponseError as e:
ctx.abort(str(e))
Cluster.from_node(master).wait() | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier if_statement not_operator call attribute identifier identifier argument_list block expression_statement call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list attribute identifier identifier except_clause as_pattern attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier expression_statement call attribute call attribute identifier identifier argument_list identifier identifier argument_list | Make node to be the slave of a master. |
def runctx(self, cmd, globals, locals):
self.enable_by_count()
try:
exec(cmd, globals, locals)
finally:
self.disable_by_count()
return self | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement call attribute identifier identifier argument_list try_statement block expression_statement call identifier argument_list identifier identifier identifier finally_clause block expression_statement call attribute identifier identifier argument_list return_statement identifier | Profile a single executable statement in the given namespaces. |
def lazyfunc(func):
closuremem_ = [{}]
def wrapper(*args, **kwargs):
mem = closuremem_[0]
key = (repr(args), repr(kwargs))
try:
return mem[key]
except KeyError:
mem[key] = func(*args, **kwargs)
return mem[key]
return wrapper | module function_definition identifier parameters identifier block expression_statement assignment identifier list dictionary function_definition identifier parameters list_splat_pattern identifier dictionary_splat_pattern identifier block expression_statement assignment identifier subscript identifier integer expression_statement assignment identifier tuple call identifier argument_list identifier call identifier argument_list identifier try_statement block return_statement subscript identifier identifier except_clause identifier block expression_statement assignment subscript identifier identifier call identifier argument_list list_splat identifier dictionary_splat identifier return_statement subscript identifier identifier return_statement identifier | Returns a memcached version of a function |
def return_on_initial_capital(capital, period_pl, leverage=None):
if capital <= 0:
raise ValueError('cost must be a positive number not %s' % capital)
leverage = leverage or 1.
eod = capital + (leverage * period_pl.cumsum())
ltd_rets = (eod / capital) - 1.
dly_rets = ltd_rets
dly_rets.iloc[1:] = (1. + ltd_rets).pct_change().iloc[1:]
return dly_rets | module function_definition identifier parameters identifier identifier default_parameter identifier none block if_statement comparison_operator identifier integer block raise_statement call identifier argument_list binary_operator string string_start string_content string_end identifier expression_statement assignment identifier boolean_operator identifier float expression_statement assignment identifier binary_operator identifier parenthesized_expression binary_operator identifier call attribute identifier identifier argument_list expression_statement assignment identifier binary_operator parenthesized_expression binary_operator identifier identifier float expression_statement assignment identifier identifier expression_statement assignment subscript attribute identifier identifier slice integer subscript attribute call attribute parenthesized_expression binary_operator float identifier identifier argument_list identifier slice integer return_statement identifier | Return the daily return series based on the capital |
def backup_name(self, timestamp=None):
suffix = datetime2string(coalesce(timestamp, datetime.now()), "%Y%m%d_%H%M%S")
return File.add_suffix(self._filename, suffix) | module function_definition identifier parameters identifier default_parameter identifier none block expression_statement assignment identifier call identifier argument_list call identifier argument_list identifier call attribute identifier identifier argument_list string string_start string_content string_end return_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | RETURN A FILENAME THAT CAN SERVE AS A BACKUP FOR THIS FILE |
def clear( self ):
self.setCurrentLayer(None)
self._layers = []
self._cache.clear()
super(XNodeScene, self).clear() | module function_definition identifier parameters identifier block expression_statement call attribute identifier identifier argument_list none expression_statement assignment attribute identifier identifier list expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute call identifier argument_list identifier identifier identifier argument_list | Clears the current scene of all the items and layers. |
def _check_align(self):
if not hasattr(self, "_align"):
self._align = ["l"]*self._row_size
if not hasattr(self, "_valign"):
self._valign = ["t"]*self._row_size | module function_definition identifier parameters identifier block if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier binary_operator list string string_start string_content string_end attribute identifier identifier if_statement not_operator call identifier argument_list identifier string string_start string_content string_end block expression_statement assignment attribute identifier identifier binary_operator list string string_start string_content string_end attribute identifier identifier | Check if alignment has been specified, set default one if not |
def run_cmd(call, cmd, *, echo=True, **kwargs):
if echo:
print('$> ' + ' '.join(map(pipes.quote, cmd)))
return call(cmd, **kwargs) | module function_definition identifier parameters identifier identifier keyword_separator default_parameter identifier true dictionary_splat_pattern identifier block if_statement identifier block 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 attribute identifier identifier identifier return_statement call identifier argument_list identifier dictionary_splat identifier | Run a command and echo it first |
def decode_list(input_props, name):
val_str = input_props.get(name, None)
if val_str:
return val_str.split(" ")
return [] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier none if_statement identifier block return_statement call attribute identifier identifier argument_list string string_start string_content string_end return_statement list | Decodes a space-separated list |
def return_buffer_contents(self, frame, force_unescaped=False):
if not force_unescaped:
if frame.eval_ctx.volatile:
self.writeline('if context.eval_ctx.autoescape:')
self.indent()
self.writeline('return Markup(concat(%s))' % frame.buffer)
self.outdent()
self.writeline('else:')
self.indent()
self.writeline('return concat(%s)' % frame.buffer)
self.outdent()
return
elif frame.eval_ctx.autoescape:
self.writeline('return Markup(concat(%s))' % frame.buffer)
return
self.writeline('return concat(%s)' % frame.buffer) | module function_definition identifier parameters identifier identifier default_parameter identifier false block if_statement not_operator identifier block if_statement attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list return_statement elif_clause attribute attribute identifier identifier identifier block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier return_statement expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end attribute identifier identifier | Return the buffer contents of the frame. |
def _handle_ls(self):
try:
arg1 = self.argument(1)
arg2 = self.argument(2)
todos = []
if arg2 == 'to' or arg1 == 'before':
number = arg1 if arg2 == 'to' else arg2
todo = self.todolist.todo(number)
todos = self.todolist.children(todo)
elif arg1 in {'to', 'after'}:
number = arg2
todo = self.todolist.todo(number)
todos = self.todolist.parents(todo)
else:
raise InvalidCommandArgument
sorter = Sorter(config().sort_string())
instance_filter = Filter.InstanceFilter(todos)
view = View(sorter, [instance_filter], self.todolist)
self.out(self.printer.print_list(view.todos))
except InvalidTodoException:
self.error("Invalid todo number given.")
except InvalidCommandArgument:
self.error(self.usage()) | module function_definition identifier parameters identifier block try_statement block expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier call attribute identifier identifier argument_list integer expression_statement assignment identifier list if_statement boolean_operator comparison_operator identifier string string_start string_content string_end comparison_operator identifier string string_start string_content string_end block expression_statement assignment identifier conditional_expression identifier comparison_operator identifier string string_start string_content string_end identifier 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 elif_clause comparison_operator identifier set string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list identifier else_clause block raise_statement identifier expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier list identifier attribute identifier identifier expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list attribute identifier identifier except_clause identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list | Handles the ls subsubcommand. |
def log_entries(self, time_zone='UTC', is_overview=False,
include=None, fetch_all=True):
endpoint = '/'.join((self.endpoint, self.id, 'log_entries'))
query_params = {
'time_zone': time_zone,
'is_overview': json.dumps(is_overview),
}
if include:
query_params['include'] = include
result = self.logEntryFactory.find(
endpoint=endpoint,
api_key=self.api_key,
fetch_all=fetch_all,
**query_params
)
return result | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier false default_parameter identifier none default_parameter identifier true block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list tuple attribute identifier identifier attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end call attribute identifier identifier argument_list identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier attribute identifier identifier keyword_argument identifier identifier dictionary_splat identifier return_statement identifier | Query for log entries on an incident instance. |
def FilePrinter(filename, mode='a', closing=True):
path = os.path.abspath(os.path.expanduser(filename))
f = open(path, mode)
return Printer(f, closing) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier identifier return_statement call identifier argument_list identifier identifier | Opens the given file and returns a printer to it. |
def _is_default(path, dest, name):
subvol_id = __salt__['btrfs.subvolume_show'](path)[name]['subvolume id']
def_id = __salt__['btrfs.subvolume_get_default'](dest)['id']
return subvol_id == def_id | module function_definition identifier parameters identifier identifier identifier block expression_statement assignment identifier subscript subscript call subscript identifier string string_start string_content string_end argument_list identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript call subscript identifier string string_start string_content string_end argument_list identifier string string_start string_content string_end return_statement comparison_operator identifier identifier | Check if the subvolume is the current default. |
def _tool_from_string(name):
known_tools = sorted(_known_tools.keys())
if name in known_tools:
tool_fn = _known_tools[name]
if isinstance(tool_fn, string_types):
tool_fn = _known_tools[tool_fn]
return tool_fn()
else:
matches, text = difflib.get_close_matches(name.lower(), known_tools), "similar"
if not matches:
matches, text = known_tools, "possible"
raise ValueError("unexpected tool name '%s', %s tools are %s" % (name, text, nice_join(matches))) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list call attribute identifier identifier argument_list if_statement comparison_operator identifier identifier block expression_statement assignment identifier subscript identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier subscript identifier identifier return_statement call identifier argument_list else_clause block expression_statement assignment pattern_list identifier identifier expression_list call attribute identifier identifier argument_list call attribute identifier identifier argument_list identifier string string_start string_content string_end if_statement not_operator identifier block expression_statement assignment pattern_list identifier identifier expression_list identifier string string_start string_content string_end raise_statement call identifier argument_list binary_operator string string_start string_content string_end tuple identifier identifier call identifier argument_list identifier | Takes a string and returns a corresponding `Tool` instance. |
def _get_management_client(self, client_class):
try:
client = get_client_from_auth_file(
client_class, auth_path=self.service_account_file
)
except ValueError as error:
raise AzureCloudException(
'Service account file format is invalid: {0}.'.format(error)
)
except KeyError as error:
raise AzureCloudException(
'Service account file missing key: {0}.'.format(error)
)
except Exception as error:
raise AzureCloudException(
'Unable to create resource management client: '
'{0}.'.format(error)
)
return client | module function_definition identifier parameters identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier keyword_argument identifier attribute identifier identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier except_clause as_pattern identifier as_pattern_target identifier block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end identifier argument_list identifier return_statement identifier | Return instance of resource management client. |
def filter(self, p_todo_str, p_todo):
return "|{:>3}| {}".format(self.todolist.number(p_todo), p_todo_str) | module function_definition identifier parameters identifier identifier identifier block return_statement call attribute string string_start string_content string_end identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier | Prepends the number to the todo string. |
def register(tag, end_tag=None):
def register_function(function):
tagmap[tag] = {'func': function, 'endtag': end_tag}
if end_tag:
tagmap['endtags'].append(end_tag)
return function
return register_function | module function_definition identifier parameters identifier default_parameter identifier none block function_definition identifier parameters identifier block expression_statement assignment subscript identifier identifier dictionary pair string string_start string_content string_end identifier pair string string_start string_content string_end identifier if_statement identifier block expression_statement call attribute subscript identifier string string_start string_content string_end identifier argument_list identifier return_statement identifier return_statement identifier | Decorator for registering shortcode functions. |
def for_all_targets(self, module, func, filter_func=None):
for target in self.targets(module):
if filter_func is None or filter_func(target):
func(target) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier none block for_statement identifier call attribute identifier identifier argument_list identifier block if_statement boolean_operator comparison_operator identifier none call identifier argument_list identifier block expression_statement call identifier argument_list identifier | Call func once for all of the targets of this module. |
def enable_notebook():
try:
from IPython.core.getipython import get_ipython
except ImportError:
raise ImportError('This feature requires IPython 1.0+')
ip = get_ipython()
f = ip.display_formatter.formatters['text/html']
f.for_type(np.ndarray, _array_to_html) | module function_definition identifier parameters block try_statement block import_from_statement dotted_name identifier identifier identifier dotted_name identifier except_clause identifier block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list expression_statement assignment identifier subscript attribute attribute identifier identifier identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier | Enable automatic visualization of NumPy arrays in the IPython Notebook. |
def convert_dict_to_datetime(obj_map):
converted_map = {}
for key, value in obj_map.items():
if isinstance(value, dict) and 'tzinfo' in value.keys():
converted_map[key] = datetime.datetime(**value)
elif isinstance(value, dict):
converted_map[key] = convert_dict_to_datetime(value)
elif isinstance(value, list):
updated_list = []
for internal_item in value:
if isinstance(internal_item, dict):
updated_list.append(convert_dict_to_datetime(internal_item))
else:
updated_list.append(internal_item)
converted_map[key] = updated_list
else:
converted_map[key] = value
return converted_map | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary for_statement pattern_list identifier identifier call attribute identifier identifier argument_list block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator string string_start string_content string_end call attribute identifier identifier argument_list block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list dictionary_splat identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment subscript identifier identifier call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement call attribute identifier identifier argument_list call identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment subscript identifier identifier identifier else_clause block expression_statement assignment subscript identifier identifier identifier return_statement identifier | converts dictionary representations of datetime back to datetime obj |
def quit(self, message=None):
if message is None:
message = 'Quit'
if self.connected:
self.send('QUIT', params=[message]) | module function_definition identifier parameters identifier default_parameter identifier none block if_statement comparison_operator identifier none block expression_statement assignment identifier string string_start string_content string_end if_statement attribute identifier identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier list identifier | Quit from the server. |
def reconstruct_files(input_dir):
input_dir = input_dir.rstrip('/')
with nl.notify('Attempting to organize/reconstruct directory'):
for r,ds,fs in os.walk(input_dir):
for f in fs:
if f[0]=='.':
shutil.move(os.path.join(r,f),os.path.join(r,'i'+f))
nl.dicom.organize_dir(input_dir)
output_dir = '%s-sorted' % input_dir
if os.path.exists(output_dir):
with nl.run_in(output_dir):
for dset_dir in os.listdir('.'):
with nl.notify('creating dataset from %s' % dset_dir):
nl.dicom.create_dset(dset_dir)
else:
nl.notify('Warning: failed to auto-organize directory %s' % input_dir,level=nl.level.warning) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end with_statement with_clause with_item call attribute identifier identifier argument_list string string_start string_content string_end block for_statement pattern_list identifier identifier identifier call attribute identifier identifier argument_list identifier block for_statement identifier identifier block if_statement comparison_operator subscript identifier integer string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute attribute identifier identifier identifier argument_list identifier identifier call attribute attribute identifier identifier identifier argument_list identifier binary_operator string string_start string_content string_end identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement assignment identifier binary_operator string string_start string_content string_end identifier if_statement call attribute attribute identifier identifier identifier argument_list identifier block with_statement with_clause with_item call attribute identifier identifier argument_list identifier block for_statement identifier call attribute identifier identifier argument_list string string_start string_content string_end block with_statement with_clause with_item call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier block expression_statement call attribute attribute identifier identifier identifier argument_list identifier else_clause block expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier keyword_argument identifier attribute attribute identifier identifier identifier | sorts ``input_dir`` and tries to reconstruct the subdirectories found |
def _put_file(self, file):
post_params = {
'file_size': file.size,
'file_hash': file.md5hash(),
'content_type': self._get_content_type(file),
}
headers = self._request_headers('PUT', file.prefixed_name, post_params=post_params)
with closing(HTTPConnection(self.netloc)) as conn:
conn.request('PUT', file.prefixed_name, file.read(), headers=headers)
response = conn.getresponse()
if response.status not in (200,):
raise S3IOError(
'py3s3 PUT error. '
'Response status: {}. '
'Reason: {}. '
'Response Text: \n'
'{}'.format(response.status, response.reason, response.read())) | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier dictionary pair string string_start string_content string_end attribute identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier keyword_argument identifier identifier with_statement with_clause with_item as_pattern call identifier argument_list call identifier argument_list attribute identifier identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier call attribute identifier identifier argument_list keyword_argument identifier identifier expression_statement assignment identifier call attribute identifier identifier argument_list if_statement comparison_operator attribute identifier identifier tuple integer block raise_statement call identifier argument_list call attribute concatenated_string string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end string string_start string_content escape_sequence string_end string string_start string_content string_end identifier argument_list attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list | Send PUT request to S3 with file contents |
def distribute_libs(self, arch, src_dirs, wildcard='*', dest_dir="libs"):
info('Copying libs')
tgt_dir = join(dest_dir, arch.arch)
ensure_dir(tgt_dir)
for src_dir in src_dirs:
for lib in glob.glob(join(src_dir, wildcard)):
shprint(sh.cp, '-a', lib, tgt_dir) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier string string_start string_content string_end default_parameter identifier string string_start string_content string_end block expression_statement call identifier argument_list string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier attribute identifier identifier expression_statement call identifier argument_list identifier for_statement identifier identifier block for_statement identifier call attribute identifier identifier argument_list call identifier argument_list identifier identifier block expression_statement call identifier argument_list attribute identifier identifier string string_start string_content string_end identifier identifier | Copy existing arch libs from build dirs to current dist dir. |
def replace_emphasis(self, s, index = 0):
e = self.emphasized[index]
self.body[e[0]:e[1]] = [s]
del self.emphasized[index] | module function_definition identifier parameters identifier identifier default_parameter identifier integer block expression_statement assignment identifier subscript attribute identifier identifier identifier expression_statement assignment subscript attribute identifier identifier slice subscript identifier integer subscript identifier integer list identifier delete_statement subscript attribute identifier identifier identifier | replace the index'th emphasized text with s |
def add_template(template, **kwargs):
tmpl = Template()
tmpl.name = template.name
if template.description:
tmpl.description = template.description
if template.layout:
tmpl.layout = get_layout_as_string(template.layout)
db.DBSession.add(tmpl)
if template.templatetypes is not None:
types = template.templatetypes
for templatetype in types:
ttype = _update_templatetype(templatetype)
tmpl.templatetypes.append(ttype)
db.DBSession.flush()
return tmpl | module function_definition identifier parameters identifier dictionary_splat_pattern identifier block expression_statement assignment identifier call identifier argument_list expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier attribute identifier identifier if_statement attribute identifier identifier block expression_statement assignment attribute identifier identifier call identifier argument_list attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier if_statement comparison_operator attribute identifier identifier none block expression_statement assignment identifier attribute identifier identifier for_statement identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute attribute identifier identifier identifier argument_list return_statement identifier | Add template and a type and typeattrs. |
def md_options_to_metadata(options):
metadata = parse_md_code_options(options)
if metadata:
language = metadata[0][0]
for lang in _JUPYTER_LANGUAGES + ['julia', 'scheme', 'c++']:
if language.lower() == lang.lower():
return lang, dict(metadata[1:])
return None, dict(metadata) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier if_statement identifier block expression_statement assignment identifier subscript subscript identifier integer integer for_statement identifier binary_operator identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end block if_statement comparison_operator call attribute identifier identifier argument_list call attribute identifier identifier argument_list block return_statement expression_list identifier call identifier argument_list subscript identifier slice integer return_statement expression_list none call identifier argument_list identifier | Parse markdown options and return language and metadata |
def load_styles(path_or_doc):
if isinstance(path_or_doc, string_types):
doc = load(path_or_doc)
else:
if isinstance(path_or_doc, ODFDocument):
doc = path_or_doc._doc
else:
doc = path_or_doc
assert isinstance(doc, OpenDocument), doc
styles = {_style_name(style): style for style in doc.styles.childNodes}
return styles | module function_definition identifier parameters identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier else_clause block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier else_clause block expression_statement assignment identifier identifier assert_statement call identifier argument_list identifier identifier identifier expression_statement assignment identifier dictionary_comprehension pair call identifier argument_list identifier identifier for_in_clause identifier attribute attribute identifier identifier identifier return_statement identifier | Return a dictionary of all styles contained in an ODF document. |
def _match_setters(self, query):
q = query.decode('utf-8')
for name, parser, response, error_response in self._setters:
try:
parsed = parser(q)
logger.debug('Found response in setter of %s' % name)
except ValueError:
continue
try:
if isinstance(parsed, dict) and 'ch_id' in parsed:
self._selected = parsed['ch_id']
self._properties[name].set_value(parsed['0'])
else:
self._properties[name].set_value(parsed)
return response
except ValueError:
if isinstance(error_response, bytes):
return error_response
return self._device.error_response('command_error')
return None | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list string string_start string_content string_end for_statement pattern_list identifier identifier identifier identifier attribute identifier identifier block try_statement block expression_statement assignment identifier call identifier argument_list identifier expression_statement call attribute identifier identifier argument_list binary_operator string string_start string_content string_end identifier except_clause identifier block continue_statement try_statement block if_statement boolean_operator call identifier argument_list identifier identifier comparison_operator string string_start string_content string_end identifier block expression_statement assignment attribute identifier identifier subscript identifier string string_start string_content string_end expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list subscript identifier string string_start string_content string_end else_clause block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier return_statement identifier except_clause identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier return_statement call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end return_statement none | Try to find a match |
def check_public_permissions(payload):
allowed_public_permissions = ['view', 'add', 'download']
for perm_type in ['add', 'remove']:
for perm in payload.get('public', {}).get(perm_type, []):
if perm not in allowed_public_permissions:
raise exceptions.PermissionDenied("Permissions for public users are too open") | module function_definition identifier parameters identifier block expression_statement assignment identifier list string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end for_statement identifier list string string_start string_content string_end string string_start string_content string_end block for_statement identifier call attribute call attribute identifier identifier argument_list string string_start string_content string_end dictionary identifier argument_list identifier list block if_statement comparison_operator identifier identifier block raise_statement call attribute identifier identifier argument_list string string_start string_content string_end | Raise ``PermissionDenied`` if public permissions are too open. |
def _rgb_randomize(x, channel:int=None, thresh:float=0.3):
"Randomize one of the channels of the input image"
if channel is None: channel = np.random.randint(0, x.shape[0] - 1)
x[channel] = torch.rand(x.shape[1:]) * np.random.uniform(0, thresh)
return x | module function_definition identifier parameters identifier typed_default_parameter identifier type identifier none typed_default_parameter identifier type identifier float block expression_statement string string_start string_content string_end if_statement comparison_operator identifier none block expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list integer binary_operator subscript attribute identifier identifier integer integer expression_statement assignment subscript identifier identifier binary_operator call attribute identifier identifier argument_list subscript attribute identifier identifier slice integer call attribute attribute identifier identifier identifier argument_list integer identifier return_statement identifier | Randomize one of the channels of the input image |
def cwlout(key, valtype=None, extensions=None, fields=None, exclude=None):
out = {"id": key}
if valtype:
out["type"] = valtype
if fields:
out["fields"] = fields
if extensions:
out["secondaryFiles"] = extensions
if exclude:
out["exclude"] = exclude
return out | module function_definition identifier parameters identifier default_parameter identifier none default_parameter identifier none default_parameter identifier none default_parameter identifier none block expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier if_statement identifier block expression_statement assignment subscript identifier string string_start string_content string_end identifier return_statement identifier | Definition of an output variable, defining the type and associated secondary files. |
def favicon(request):
favicon = u"{}tree/images/favicon.ico".format(settings.STATIC_URL)
try:
from seo.models import MetaSite
site = MetaSite.objects.get(default=True)
return HttpResponseRedirect(site.favicon.url)
except:
return HttpResponseRedirect(favicon) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list attribute identifier identifier try_statement block import_from_statement dotted_name identifier identifier dotted_name identifier expression_statement assignment identifier call attribute attribute identifier identifier identifier argument_list keyword_argument identifier true return_statement call identifier argument_list attribute attribute identifier identifier identifier except_clause block return_statement call identifier argument_list identifier | It returns favicon's location |
def async_get_device(self, uid, fields='*'):
return (yield from self._get('/pods/{}'.format(uid),
fields=fields)) | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block return_statement parenthesized_expression yield call attribute identifier identifier argument_list call attribute string string_start string_content string_end identifier argument_list identifier keyword_argument identifier identifier | Get specific device by ID. |
def get(args):
html = args.H
lang = args.l
nowrap = args.n
query = args.q
silent = args.s
title = args.t
verbose = args.v
wiki = args.w
if query:
qobj = WPToolsQuery(lang=lang, wiki=wiki)
if title:
return qobj.query(title)
return qobj.random()
page = wptools.page(title, lang=lang, silent=silent,
verbose=verbose, wiki=wiki)
try:
page.get_query()
except (StandardError, ValueError, LookupError):
return "NOT_FOUND"
if not page.data.get('extext'):
out = page.cache['query']['query']
out = _page_text(page, nowrap)
if html:
out = _page_html(page)
try:
return out.encode('utf-8')
except KeyError:
return out | module function_definition identifier parameters identifier block expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier expression_statement assignment identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier if_statement identifier block return_statement call attribute identifier identifier argument_list identifier return_statement call attribute identifier identifier argument_list expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list except_clause tuple identifier identifier identifier block return_statement string string_start string_content string_end if_statement not_operator call attribute attribute identifier identifier identifier argument_list string string_start string_content string_end block expression_statement assignment identifier subscript subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end expression_statement assignment identifier call identifier argument_list identifier identifier if_statement identifier block expression_statement assignment identifier call identifier argument_list identifier try_statement block return_statement call attribute identifier identifier argument_list string string_start string_content string_end except_clause identifier block return_statement identifier | invoke wptools and assemble selected output |
def _py2java(sc, obj):
if isinstance(obj, RDD):
obj = _to_java_object_rdd(obj)
elif isinstance(obj, DataFrame):
obj = obj._jdf
elif isinstance(obj, SparkContext):
obj = obj._jsc
elif isinstance(obj, list):
obj = [_py2java(sc, x) for x in obj]
elif isinstance(obj, JavaObject):
pass
elif isinstance(obj, (int, long, float, bool, bytes, unicode)):
pass
else:
data = bytearray(PickleSerializer().dumps(obj))
obj = sc._jvm.org.apache.spark.mllib.api.python.SerDe.loads(data)
return obj | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block expression_statement assignment identifier call identifier argument_list identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier attribute identifier identifier elif_clause call identifier argument_list identifier identifier block expression_statement assignment identifier list_comprehension call identifier argument_list identifier identifier for_in_clause identifier identifier elif_clause call identifier argument_list identifier identifier block pass_statement elif_clause call identifier argument_list identifier tuple identifier identifier identifier identifier identifier identifier block pass_statement else_clause block expression_statement assignment identifier call identifier argument_list call attribute call identifier argument_list identifier argument_list identifier expression_statement assignment identifier call attribute attribute attribute attribute attribute attribute attribute attribute attribute identifier identifier identifier identifier identifier identifier identifier identifier identifier identifier argument_list identifier return_statement identifier | Convert Python object into Java |
def _visible_in_diff(merge_result, context_lines=3):
i = old_line = new_line = 0
while i < len(merge_result):
line_or_conflict = merge_result[i]
if isinstance(line_or_conflict, tuple):
yield old_line, new_line, line_or_conflict
old_line += len(line_or_conflict[0])
new_line += len(line_or_conflict[1])
else:
for j in (list(range(max(0, i-context_lines), i )) +
list(range(i+1 , min(len(merge_result), i+1+context_lines)))):
if isinstance(merge_result[j], tuple):
yield old_line, new_line, line_or_conflict
break
else:
yield None
old_line += 1
new_line += 1
i += 1
yield None | module function_definition identifier parameters identifier default_parameter identifier integer block expression_statement assignment identifier assignment identifier assignment identifier integer while_statement comparison_operator identifier call identifier argument_list identifier block expression_statement assignment identifier subscript identifier identifier if_statement call identifier argument_list identifier identifier block expression_statement yield expression_list identifier identifier identifier expression_statement augmented_assignment identifier call identifier argument_list subscript identifier integer expression_statement augmented_assignment identifier call identifier argument_list subscript identifier integer else_clause block for_statement identifier parenthesized_expression binary_operator call identifier argument_list call identifier argument_list call identifier argument_list integer binary_operator identifier identifier identifier call identifier argument_list call identifier argument_list binary_operator identifier integer call identifier argument_list call identifier argument_list identifier binary_operator binary_operator identifier integer identifier block if_statement call identifier argument_list subscript identifier identifier identifier block expression_statement yield expression_list identifier identifier identifier break_statement else_clause block expression_statement yield none expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier integer expression_statement augmented_assignment identifier integer expression_statement yield none | Collects the set of lines that should be visible in a diff with a certain number of context lines |
def _save_multi(data, file_name, sep=";"):
logger.debug("saving multi")
with open(file_name, "w", newline='') as f:
logger.debug(f"{file_name} opened")
writer = csv.writer(f, delimiter=sep)
try:
writer.writerows(itertools.zip_longest(*data))
except Exception as e:
logger.info(f"Exception encountered in batch._save_multi: {e}")
raise ExportFailed
logger.debug("wrote rows using itertools in _save_multi") | module function_definition identifier parameters identifier identifier default_parameter identifier string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end with_statement with_clause with_item as_pattern call identifier argument_list identifier string string_start string_content string_end keyword_argument identifier string string_start string_end as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start interpolation identifier string_content string_end expression_statement assignment identifier call attribute identifier identifier argument_list identifier keyword_argument identifier identifier try_statement block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list list_splat identifier except_clause as_pattern identifier as_pattern_target identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content interpolation identifier string_end raise_statement identifier expression_statement call attribute identifier identifier argument_list string string_start string_content string_end | convenience function for storing data column-wise in a csv-file. |
def includePoint(self, p):
if not len(p) == 2:
raise ValueError("bad sequ. length")
self.x0, self.y0, self.x1, self.y1 = TOOLS._include_point_in_rect(self, p)
return self | module function_definition identifier parameters identifier identifier block if_statement not_operator comparison_operator call identifier argument_list identifier integer block raise_statement call identifier argument_list string string_start string_content string_end expression_statement assignment pattern_list attribute identifier identifier attribute identifier identifier attribute identifier identifier attribute identifier identifier call attribute identifier identifier argument_list identifier identifier return_statement identifier | Extend rectangle to include point p. |
def close(self):
target = self.prev if (self.is_current and self.prev != self) else None
with switch_window(self._browser, self.name):
self._browser.driver.close()
if target is not None:
target.is_current = True | module function_definition identifier parameters identifier block expression_statement assignment identifier conditional_expression attribute identifier identifier parenthesized_expression boolean_operator attribute identifier identifier comparison_operator attribute identifier identifier identifier none with_statement with_clause with_item call identifier argument_list attribute identifier identifier attribute identifier identifier block expression_statement call attribute attribute attribute identifier identifier identifier identifier argument_list if_statement comparison_operator identifier none block expression_statement assignment attribute identifier identifier true | Close this window. If this window is active, switch to previous window |
def parameters_as_string(self):
params = ", ".join([ p.name for p in self.ordered_parameters ])
return params | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute string string_start string_content string_end identifier argument_list list_comprehension attribute identifier identifier for_in_clause identifier attribute identifier identifier return_statement identifier | Returns a comma-separated list of the parameters in the executable definition. |
def make_config(self, data: dict):
self.validate_config(data)
config_data = self.prepare_config(data)
return config_data | module function_definition identifier parameters identifier typed_parameter identifier type identifier block expression_statement call attribute identifier identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement identifier | Make a MIP config. |
def cnxml_to_html(cnxml_source):
source = _string2io(cnxml_source)
xml = etree.parse(source)
xml = _transform('cnxml-to-html5.xsl', xml,
version='"{}"'.format(version))
xml = XHTML_MODULE_BODY_XPATH(xml)
return etree.tostring(xml[0]) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier expression_statement assignment identifier call identifier argument_list string string_start string_content string_end identifier keyword_argument identifier call attribute string string_start string_content string_end identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier return_statement call attribute identifier identifier argument_list subscript identifier integer | Transform the CNXML source to HTML |
def withHeartbeater(cls, heartbeater):
instance = cls(heartbeater)
heartbeater.writeHeartbeat = instance.heartbeat
return instance | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier expression_statement assignment attribute identifier identifier attribute identifier identifier return_statement identifier | Connect a SockJSProtocolMachine to its heartbeater. |
def unsubscribe_all(self, callback=False):
futures = ((f, r) for f, r in self._requests.items()
if isinstance(r, Subscribe)
and f not in self._pending_unsubscribes)
if futures:
for future, request in futures:
if callback:
log.warn("Unsubscribing from %s", request.path)
cothread.Callback(self.unsubscribe, future)
else:
self.unsubscribe(future) | module function_definition identifier parameters identifier default_parameter identifier false block expression_statement assignment identifier generator_expression tuple identifier identifier for_in_clause pattern_list identifier identifier call attribute attribute identifier identifier identifier argument_list if_clause boolean_operator call identifier argument_list identifier identifier comparison_operator identifier attribute identifier identifier if_statement identifier block for_statement pattern_list identifier identifier identifier block if_statement identifier block expression_statement call attribute identifier identifier argument_list string string_start string_content string_end attribute identifier identifier expression_statement call attribute identifier identifier argument_list attribute identifier identifier identifier else_clause block expression_statement call attribute identifier identifier argument_list identifier | Send an unsubscribe for all active subscriptions |
def build_funding(award_groups):
if not award_groups:
return []
funding_awards = []
for award_groups_item in award_groups:
for award_group_id, award_group in iteritems(award_groups_item):
award = ea.FundingAward()
award.award_group_id = award_group_id
if award_group.get('id-type') == "FundRef":
award.institution_id = award_group.get('id')
award.institution_name = award_group.get('institution')
if award_group.get('award-id'):
award.add_award_id(award_group.get('award-id'))
funding_awards.append(award)
return funding_awards | module function_definition identifier parameters identifier block if_statement not_operator identifier block return_statement list expression_statement assignment identifier list for_statement identifier identifier block for_statement pattern_list identifier identifier call identifier argument_list identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment attribute identifier identifier identifier if_statement comparison_operator call attribute identifier identifier argument_list string string_start string_content string_end string string_start string_content string_end block expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end expression_statement assignment attribute identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end if_statement call attribute identifier identifier argument_list string string_start string_content string_end block expression_statement call attribute identifier identifier argument_list call attribute identifier identifier argument_list string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Given a funding data, format it |
def _ordereddict2dict(input_ordered_dict):
return salt.utils.json.loads(salt.utils.json.dumps(input_ordered_dict)) | module function_definition identifier parameters identifier block return_statement call attribute attribute attribute identifier identifier identifier identifier argument_list call attribute attribute attribute identifier identifier identifier identifier argument_list identifier | Convert ordered dictionary to a dictionary |
def as_timedelta(cls, delta):
if isinstance(delta, cls): return delta
return cls(delta.days, delta.seconds, delta.microseconds) | module function_definition identifier parameters identifier identifier block if_statement call identifier argument_list identifier identifier block return_statement identifier return_statement call identifier argument_list attribute identifier identifier attribute identifier identifier attribute identifier identifier | Convert delta into a MyTimedelta object. |
def transform(self, trans):
clone = deepcopy(self)
for n in clone.iter_sections():
n.points[:, 0:3] = trans(n.points[:, 0:3])
return clone | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call identifier argument_list identifier for_statement identifier call attribute identifier identifier argument_list block expression_statement assignment subscript attribute identifier identifier slice slice integer integer call identifier argument_list subscript attribute identifier identifier slice slice integer integer return_statement identifier | Return a copy of this neurite with a 3D transformation applied |
def encode(self, input_str):
inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID]
batch_inputs = np.reshape(inputs, [1, -1, 1, 1])
return batch_inputs | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier binary_operator call attribute subscript attribute identifier identifier string string_start string_content string_end identifier argument_list identifier list identifier expression_statement assignment identifier call attribute identifier identifier argument_list identifier list integer unary_operator integer integer integer return_statement identifier | Input str to features dict, ready for inference. |
def update_record(self, name, address, ttl=60):
record_id = self._get_record(name)
if record_id is None:
return self._create_record(name, address, ttl)
return self._update_record(record_id, name, address, ttl) | module function_definition identifier parameters identifier identifier identifier default_parameter identifier integer block expression_statement assignment identifier call attribute identifier identifier argument_list identifier if_statement comparison_operator identifier none block return_statement call attribute identifier identifier argument_list identifier identifier identifier return_statement call attribute identifier identifier argument_list identifier identifier identifier identifier | Updates a record, creating it if not exists. |
def commit():
session_token = request.headers['session_token']
repository = request.headers['repository']
current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token)
if current_user is False: return fail(user_auth_fail_msg)
repository_path = config['repositories'][repository]['path']
def with_exclusive_lock():
if not varify_user_lock(repository_path, session_token): return fail(lock_fail_msg)
data_store = versioned_storage(repository_path)
if not data_store.have_active_commit(): return fail(no_active_commit_msg)
result = {}
if request.headers['mode'] == 'commit':
new_head = data_store.commit(request.headers['commit_message'], current_user['username'])
result = {'head' : new_head}
else:
data_store.rollback()
update_user_lock(repository_path, None)
return success(result)
return lock_access(repository_path, with_exclusive_lock) | module function_definition identifier parameters block expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier subscript attribute identifier identifier string string_start string_content string_end expression_statement assignment identifier call identifier argument_list subscript attribute identifier identifier string string_start string_content string_end identifier identifier if_statement comparison_operator identifier false block return_statement call identifier argument_list identifier expression_statement assignment identifier subscript subscript subscript identifier string string_start string_content string_end identifier string string_start string_content string_end function_definition identifier parameters block if_statement not_operator call identifier argument_list identifier identifier block return_statement call identifier argument_list identifier expression_statement assignment identifier call identifier argument_list identifier if_statement not_operator call attribute identifier identifier argument_list block return_statement call identifier argument_list identifier expression_statement assignment identifier dictionary if_statement comparison_operator subscript attribute identifier identifier string string_start string_content string_end string string_start string_content string_end block expression_statement assignment identifier call attribute identifier identifier argument_list subscript attribute identifier identifier string string_start string_content string_end subscript identifier string string_start string_content string_end expression_statement assignment identifier dictionary pair string string_start string_content string_end identifier else_clause block expression_statement call attribute identifier identifier argument_list expression_statement call identifier argument_list identifier none return_statement call identifier argument_list identifier return_statement call identifier argument_list identifier identifier | Commit changes and release the write lock |
def _get_aggregated_node_list(self, data):
node_list = []
for node in data:
local_addresses = [node['primary']]
if 'secondary' in node:
local_addresses += node['secondary']
node_list.append(local_addresses)
return node_list | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier list for_statement identifier identifier block expression_statement assignment identifier list subscript identifier string string_start string_content string_end if_statement comparison_operator string string_start string_content string_end identifier block expression_statement augmented_assignment identifier subscript identifier string string_start string_content string_end expression_statement call attribute identifier identifier argument_list identifier return_statement identifier | Returns list of main and secondary mac addresses. |
def machine_info():
import psutil
BYTES_IN_GIG = 1073741824.0
free_bytes = psutil.virtual_memory().total
return [{"memory": float("%.1f" % (free_bytes / BYTES_IN_GIG)), "cores": multiprocessing.cpu_count(),
"name": socket.gethostname()}] | module function_definition identifier parameters block import_statement dotted_name identifier expression_statement assignment identifier float expression_statement assignment identifier attribute call attribute identifier identifier argument_list identifier return_statement list dictionary pair string string_start string_content string_end call identifier argument_list binary_operator string string_start string_content string_end parenthesized_expression binary_operator identifier identifier pair string string_start string_content string_end call attribute identifier identifier argument_list pair string string_start string_content string_end call attribute identifier identifier argument_list | Retrieve core and memory information for the current machine. |
def _build_gadgets(self, gadget_tree_root):
node_list = self._build_gadgets_rec(gadget_tree_root)
return [RawGadget(n) for n in node_list] | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list identifier return_statement list_comprehension call identifier argument_list identifier for_in_clause identifier identifier | Return a gadgets list. |
def add(self, callback_type, callback):
with self.lock:
self.callbacks[callback_type].append(callback) | module function_definition identifier parameters identifier identifier identifier block with_statement with_clause with_item attribute identifier identifier block expression_statement call attribute subscript attribute identifier identifier identifier identifier argument_list identifier | Add a new listener |
def find_all_files(self):
files = self.find_files()
subrepo_files = (
posixpath.join(subrepo.location, filename)
for subrepo in self.subrepos()
for filename in subrepo.find_files()
)
return itertools.chain(files, subrepo_files) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier generator_expression call attribute identifier identifier argument_list attribute identifier identifier identifier for_in_clause identifier call attribute identifier identifier argument_list for_in_clause identifier call attribute identifier identifier argument_list return_statement call attribute identifier identifier argument_list identifier identifier | Find files including those in subrepositories. |
def inputindex(input):
stats = {}
countminmax = "SUM(count) AS count, MIN(day) AS first, MAX(day) AS last"
tables = ("moves", "clicks", "scrolls") if "mouse" == input else ("keys", "combos")
for table in tables:
stats[table] = db.fetchone("counts", countminmax, type=table)
stats[table]["days"] = db.fetch("counts", order="day DESC", type=table)
return bottle.template("input.tpl", locals(), conf=conf) | module function_definition identifier parameters identifier block expression_statement assignment identifier dictionary expression_statement assignment identifier string string_start string_content string_end expression_statement assignment identifier conditional_expression tuple string string_start string_content string_end string string_start string_content string_end string string_start string_content string_end comparison_operator string string_start string_content string_end identifier tuple string string_start string_content string_end string string_start string_content string_end for_statement identifier identifier block expression_statement assignment subscript identifier identifier call attribute identifier identifier argument_list string string_start string_content string_end identifier keyword_argument identifier identifier expression_statement assignment subscript subscript identifier identifier string string_start string_content string_end call attribute identifier identifier argument_list string string_start string_content string_end keyword_argument identifier string string_start string_content string_end keyword_argument identifier identifier return_statement call attribute identifier identifier argument_list string string_start string_content string_end call identifier argument_list keyword_argument identifier identifier | Handler for showing keyboard or mouse page with day and total links. |
def add_record(self, record):
rec = self.get_record(record._record_type, record.host)
if rec:
rec = record
for i,r in enumerate(self._entries):
if r._record_type == record._record_type \
and r.host == record.host:
self._entries[i] = record
else:
self._entries.append(record)
self.sort()
return True | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier call attribute identifier identifier argument_list attribute identifier identifier attribute identifier identifier if_statement identifier block expression_statement assignment identifier identifier for_statement pattern_list identifier identifier call identifier argument_list attribute identifier identifier block if_statement boolean_operator comparison_operator attribute identifier identifier attribute identifier identifier line_continuation comparison_operator attribute identifier identifier attribute identifier identifier block expression_statement assignment subscript attribute identifier identifier identifier identifier else_clause block expression_statement call attribute attribute identifier identifier identifier argument_list identifier expression_statement call attribute identifier identifier argument_list return_statement true | Add or update a given DNS record |
def _get_entry_link(self, entry):
entry_link = None
for link in entry.link:
if '/data/' not in link.href and '/lh/' not in link.href:
entry_link = link.href
break
return entry_link or entry.link[0].href | module function_definition identifier parameters identifier identifier block expression_statement assignment identifier none for_statement identifier attribute identifier identifier block if_statement boolean_operator comparison_operator string string_start string_content string_end attribute identifier identifier comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier attribute identifier identifier break_statement return_statement boolean_operator identifier attribute subscript attribute identifier identifier integer identifier | Returns a unique link for an entry |
def _load(self, element, commentchar):
for child in element:
if "id" in child.attrib:
tline = TemplateLine(child, self, commentchar)
self.order.append(tline.identifier)
self.lines[tline.identifier] = tline
else:
msg.warn("no id element in {}. Ignored. (group._load)".format(child)) | module function_definition identifier parameters identifier identifier identifier block for_statement identifier identifier block if_statement comparison_operator string string_start string_content string_end attribute identifier identifier block expression_statement assignment identifier call identifier argument_list identifier identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list attribute identifier identifier expression_statement assignment subscript attribute identifier identifier attribute identifier 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 | Loads all the child line elements from the XML group element. |
def save_config(
self,
cmd="copy running-config startup-config",
confirm=True,
confirm_response="y",
):
return super(ExtremeNosSSH, self).save_config(
cmd=cmd, confirm=confirm, confirm_response=confirm_response
) | module function_definition identifier parameters identifier default_parameter identifier string string_start string_content string_end default_parameter identifier true default_parameter identifier string string_start string_content string_end block return_statement call attribute call identifier argument_list identifier identifier identifier argument_list keyword_argument identifier identifier keyword_argument identifier identifier keyword_argument identifier identifier | Save Config for Extreme VDX. |
def find_model_by_table_name(name):
for model in ModelBase._decl_class_registry.values():
if hasattr(model, '__table__') and model.__table__.fullname == name:
return model
return None | module function_definition identifier parameters identifier block for_statement identifier call attribute attribute identifier identifier identifier argument_list block if_statement boolean_operator call identifier argument_list identifier string string_start string_content string_end comparison_operator attribute attribute identifier identifier identifier identifier block return_statement identifier return_statement none | Find a model reference by its table name |
def _render_frame(self):
frame = self.frame()
output = '\r{0}'.format(frame)
self.clear()
try:
self._stream.write(output)
except UnicodeEncodeError:
self._stream.write(encode_utf_8_text(output)) | module function_definition identifier parameters identifier block expression_statement assignment identifier call attribute identifier identifier argument_list expression_statement assignment identifier call attribute string string_start string_content escape_sequence string_end identifier argument_list identifier expression_statement call attribute identifier identifier argument_list try_statement block expression_statement call attribute attribute identifier identifier identifier argument_list identifier except_clause identifier block expression_statement call attribute attribute identifier identifier identifier argument_list call identifier argument_list identifier | Renders the frame on the line after clearing it. |
def main(self):
loop = MainLoop(self.view, DEFAULT_PALETTE,
handle_mouse=self.handle_mouse)
self.view.show_graphs()
self.animate_graph(loop)
try:
loop.run()
except (ZeroDivisionError) as err:
logging.debug("Some stat caused divide by zero exception. Exiting")
logging.error(err, exc_info=True)
print(ERROR_MESSAGE)
except (AttributeError) as err:
logging.debug("Catch attribute Error in urwid and restart")
logging.debug(err, exc_info=True)
self.main()
except (psutil.NoSuchProcess) as err:
logging.error("No such process error")
logging.error(err, exc_info=True)
print(ERROR_MESSAGE) | module function_definition identifier parameters identifier block expression_statement assignment identifier call identifier argument_list attribute identifier identifier identifier keyword_argument identifier attribute identifier identifier expression_statement call attribute attribute identifier identifier identifier argument_list expression_statement call attribute identifier identifier argument_list identifier try_statement block expression_statement call attribute identifier identifier argument_list except_clause as_pattern parenthesized_expression identifier as_pattern_target identifier 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 keyword_argument identifier true expression_statement call identifier argument_list identifier except_clause as_pattern parenthesized_expression identifier as_pattern_target identifier 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 keyword_argument identifier true expression_statement call attribute identifier identifier argument_list except_clause as_pattern parenthesized_expression attribute identifier identifier as_pattern_target identifier 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 keyword_argument identifier true expression_statement call identifier argument_list identifier | Starts the main loop and graph animation |
def _import_status(data, item, repo_name, repo_tag):
status = item['status']
try:
if 'Downloading from' in status:
return
elif all(x in string.hexdigits for x in status):
data['Image'] = '{0}:{1}'.format(repo_name, repo_tag)
data['Id'] = status
except (AttributeError, TypeError):
pass | module function_definition identifier parameters identifier identifier identifier identifier block expression_statement assignment identifier subscript identifier string string_start string_content string_end try_statement block if_statement comparison_operator string string_start string_content string_end identifier block return_statement elif_clause call identifier generator_expression comparison_operator identifier attribute identifier identifier for_in_clause identifier identifier block expression_statement assignment subscript identifier string string_start string_content string_end call attribute string string_start string_content string_end identifier argument_list identifier identifier expression_statement assignment subscript identifier string string_start string_content string_end identifier except_clause tuple identifier identifier block pass_statement | Process a status update from docker import, updating the data structure |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.