code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def create_report(self, report_type, account_id, term_id=None, params={}):
"""
Generates a report instance for the canvas account id.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.create
"""
if term_id is not None:
params["enrollm... | def function[create_report, parameter[self, report_type, account_id, term_id, params]]:
constant[
Generates a report instance for the canvas account id.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.create
]
if compare[name[term_id] is_not co... | keyword[def] identifier[create_report] ( identifier[self] , identifier[report_type] , identifier[account_id] , identifier[term_id] = keyword[None] , identifier[params] ={}):
literal[string]
keyword[if] identifier[term_id] keyword[is] keyword[not] keyword[None] :
identifier[params] ... | def create_report(self, report_type, account_id, term_id=None, params={}):
"""
Generates a report instance for the canvas account id.
https://canvas.instructure.com/doc/api/account_reports.html#method.account_reports.create
"""
if term_id is not None:
params['enrollment_term_id'... |
def cropcenter(sz, img=None):
"""
if no img, then return crop function
:param sz:
:param img:
:return:
"""
l = len(sz)
sz = np.array(sz)
def wrapped(im):
imsz = np.array(im.shape)
s = (imsz[:l] - sz) / 2 # start index
to = s + sz # end index
# img[... | def function[cropcenter, parameter[sz, img]]:
constant[
if no img, then return crop function
:param sz:
:param img:
:return:
]
variable[l] assign[=] call[name[len], parameter[name[sz]]]
variable[sz] assign[=] call[name[np].array, parameter[name[sz]]]
def function[wrap... | keyword[def] identifier[cropcenter] ( identifier[sz] , identifier[img] = keyword[None] ):
literal[string]
identifier[l] = identifier[len] ( identifier[sz] )
identifier[sz] = identifier[np] . identifier[array] ( identifier[sz] )
keyword[def] identifier[wrapped] ( identifier[im] ):
ident... | def cropcenter(sz, img=None):
"""
if no img, then return crop function
:param sz:
:param img:
:return:
"""
l = len(sz)
sz = np.array(sz)
def wrapped(im):
imsz = np.array(im.shape)
s = (imsz[:l] - sz) / 2 # start index
to = s + sz # end index
# img[s... |
def _print_foreign_repetition_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
assert(isinstance(idset1, idset_with_reference))
assert(isinstance(idset2, idset))
reps = idset2.get_repetitions()
if len(reps) < 1:
return
... | def function[_print_foreign_repetition_table, parameter[self, idset1, idset2]]:
constant[
:param idset1:
:param idset2:
]
assert[call[name[isinstance], parameter[name[idset1], name[idset_with_reference]]]]
assert[call[name[isinstance], parameter[name[idset2], name[idset]]]]
... | keyword[def] identifier[_print_foreign_repetition_table] ( identifier[self] , identifier[idset1] , identifier[idset2] ):
literal[string]
keyword[assert] ( identifier[isinstance] ( identifier[idset1] , identifier[idset_with_reference] ))
keyword[assert] ( identifier[isinstance] ( identifie... | def _print_foreign_repetition_table(self, idset1, idset2):
"""
:param idset1:
:param idset2:
"""
assert isinstance(idset1, idset_with_reference)
assert isinstance(idset2, idset)
reps = idset2.get_repetitions()
if len(reps) < 1:
return # depends on [control=['if'], da... |
def _serve_process(self, slaveFd, serverPid):
"""
Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket.
"""
self.serverPid = serverPid
if sys.s... | def function[_serve_process, parameter[self, slaveFd, serverPid]]:
constant[
Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket.
]
name[self].serverP... | keyword[def] identifier[_serve_process] ( identifier[self] , identifier[slaveFd] , identifier[serverPid] ):
literal[string]
identifier[self] . identifier[serverPid] = identifier[serverPid]
keyword[if] identifier[sys] . identifier[stdin] . identifier[isatty] ():
identifier[se... | def _serve_process(self, slaveFd, serverPid):
"""
Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket.
"""
self.serverPid = serverPid
if sys.stdin.isatty(... |
def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'),
'sky_' + self.sky_state + '_z' + str(
... | def function[update_filenames, parameter[self]]:
constant[Does nothing currently. May not need this method]
name[self].sky_file assign[=] call[name[os].path.abspath, parameter[call[name[os].path.join, parameter[call[name[os].path.join, parameter[name[self].input_path, constant[sky_files]]], binary_oper... | keyword[def] identifier[update_filenames] ( identifier[self] ):
literal[string]
identifier[self] . identifier[sky_file] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[join] ( identifie... | def update_filenames(self):
"""Does nothing currently. May not need this method"""
self.sky_file = os.path.abspath(os.path.join(os.path.join(self.input_path, 'sky_files'), 'sky_' + self.sky_state + '_z' + str(self.sky_zenith) + '_a' + str(self.sky_azimuth) + '_' + str(self.num_bands) + '_' + self.ds_code)) |
def getSoname(filename):
"""
Return the soname of a library.
"""
cmd = ["objdump", "-p", "-j", ".dynamic", filename]
m = re.search(r'\s+SONAME\s+([^\s]+)', compat.exec_command(*cmd))
if m:
return m.group(1) | def function[getSoname, parameter[filename]]:
constant[
Return the soname of a library.
]
variable[cmd] assign[=] list[[<ast.Constant object at 0x7da1b0e47d30>, <ast.Constant object at 0x7da1b0e443d0>, <ast.Constant object at 0x7da1b0e47940>, <ast.Constant object at 0x7da1b0e472e0>, <ast.Name ob... | keyword[def] identifier[getSoname] ( identifier[filename] ):
literal[string]
identifier[cmd] =[ literal[string] , literal[string] , literal[string] , literal[string] , identifier[filename] ]
identifier[m] = identifier[re] . identifier[search] ( literal[string] , identifier[compat] . identifier[exec_co... | def getSoname(filename):
"""
Return the soname of a library.
"""
cmd = ['objdump', '-p', '-j', '.dynamic', filename]
m = re.search('\\s+SONAME\\s+([^\\s]+)', compat.exec_command(*cmd))
if m:
return m.group(1) # depends on [control=['if'], data=[]] |
def get_endpoint(self, session, **kwargs):
"""Get the HubiC storage endpoint uri.
If the current session has not been authenticated, this will trigger a
new authentication to the HubiC OAuth service.
:param keystoneclient.Session session: The session object to use for
... | def function[get_endpoint, parameter[self, session]]:
constant[Get the HubiC storage endpoint uri.
If the current session has not been authenticated, this will trigger a
new authentication to the HubiC OAuth service.
:param keystoneclient.Session session: The session object to use for
... | keyword[def] identifier[get_endpoint] ( identifier[self] , identifier[session] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[endpoint] keyword[is] keyword[None] :
keyword[try] :
identifier[self] . identifier[_refresh_tokens] ( ... | def get_endpoint(self, session, **kwargs):
"""Get the HubiC storage endpoint uri.
If the current session has not been authenticated, this will trigger a
new authentication to the HubiC OAuth service.
:param keystoneclient.Session session: The session object to use for
... |
def local_variable_action(self, text, loc, var):
"""Code executed after recognising a local variable"""
exshared.setpos(loc, text)
if DEBUG > 0:
print("LOCAL_VAR:",var, var.name, var.type)
if DEBUG == 2: self.symtab.display()
if DEBUG > 2: return
... | def function[local_variable_action, parameter[self, text, loc, var]]:
constant[Code executed after recognising a local variable]
call[name[exshared].setpos, parameter[name[loc], name[text]]]
if compare[name[DEBUG] greater[>] constant[0]] begin[:]
call[name[print], parameter[const... | keyword[def] identifier[local_variable_action] ( identifier[self] , identifier[text] , identifier[loc] , identifier[var] ):
literal[string]
identifier[exshared] . identifier[setpos] ( identifier[loc] , identifier[text] )
keyword[if] identifier[DEBUG] > literal[int] :
iden... | def local_variable_action(self, text, loc, var):
"""Code executed after recognising a local variable"""
exshared.setpos(loc, text)
if DEBUG > 0:
print('LOCAL_VAR:', var, var.name, var.type)
if DEBUG == 2:
self.symtab.display() # depends on [control=['if'], data=[]]
if DE... |
def check_pin_trust(self, environ):
"""Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so that appropriate action can be... | def function[check_pin_trust, parameter[self, environ]]:
constant[Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so tha... | keyword[def] identifier[check_pin_trust] ( identifier[self] , identifier[environ] ):
literal[string]
keyword[if] identifier[self] . identifier[pin] keyword[is] keyword[None] :
keyword[return] keyword[True]
identifier[val] = identifier[parse_cookie] ( identifier[environ] )... | def check_pin_trust(self, environ):
"""Checks if the request passed the pin test. This returns `True` if the
request is trusted on a pin/cookie basis and returns `False` if not.
Additionally if the cookie's stored pin hash is wrong it will return
`None` so that appropriate action can be tak... |
def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
super().seek(self._total_offset + pos, *args, **kwargs) | def function[seek_in_frame, parameter[self, pos]]:
constant[
Seeks relative to the total offset of the current contextual frames.
]
call[call[name[super], parameter[]].seek, parameter[binary_operation[name[self]._total_offset + name[pos]], <ast.Starred object at 0x7da2044c2830>]] | keyword[def] identifier[seek_in_frame] ( identifier[self] , identifier[pos] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[super] (). identifier[seek] ( identifier[self] . identifier[_total_offset] + identifier[pos] ,* identifier[args] ,** identifier[kwargs] ) | def seek_in_frame(self, pos, *args, **kwargs):
"""
Seeks relative to the total offset of the current contextual frames.
"""
super().seek(self._total_offset + pos, *args, **kwargs) |
def make_box_pixel_mask_from_col_row(column, row, default=0, value=1):
'''Generate box shaped mask from column and row lists. Takes the minimum and maximum value from each list.
Parameters
----------
column : iterable, int
List of colums values.
row : iterable, int
List of r... | def function[make_box_pixel_mask_from_col_row, parameter[column, row, default, value]]:
constant[Generate box shaped mask from column and row lists. Takes the minimum and maximum value from each list.
Parameters
----------
column : iterable, int
List of colums values.
row : iterable, in... | keyword[def] identifier[make_box_pixel_mask_from_col_row] ( identifier[column] , identifier[row] , identifier[default] = literal[int] , identifier[value] = literal[int] ):
literal[string]
identifier[col_array] = identifier[np] . identifier[array] ( identifier[column] )- literal[int]
identifi... | def make_box_pixel_mask_from_col_row(column, row, default=0, value=1):
"""Generate box shaped mask from column and row lists. Takes the minimum and maximum value from each list.
Parameters
----------
column : iterable, int
List of colums values.
row : iterable, int
List of row value... |
def insert(self, node, before=None):
"""Insert a new node in the list.
If *before* is specified, the new node is inserted before this node.
Otherwise, the node is inserted at the end of the list.
"""
node._list = self
if self._first is None:
self._first = sel... | def function[insert, parameter[self, node, before]]:
constant[Insert a new node in the list.
If *before* is specified, the new node is inserted before this node.
Otherwise, the node is inserted at the end of the list.
]
name[node]._list assign[=] name[self]
if compare[na... | keyword[def] identifier[insert] ( identifier[self] , identifier[node] , identifier[before] = keyword[None] ):
literal[string]
identifier[node] . identifier[_list] = identifier[self]
keyword[if] identifier[self] . identifier[_first] keyword[is] keyword[None] :
identifier[se... | def insert(self, node, before=None):
"""Insert a new node in the list.
If *before* is specified, the new node is inserted before this node.
Otherwise, the node is inserted at the end of the list.
"""
node._list = self
if self._first is None:
self._first = self._last = node ... |
def get_changes(self, dest_attr, new_name=None, resources=None,
task_handle=taskhandle.NullTaskHandle()):
"""Return the changes needed for this refactoring
Parameters:
- `dest_attr`: the name of the destination attribute
- `new_name`: the name of the new method; if ... | def function[get_changes, parameter[self, dest_attr, new_name, resources, task_handle]]:
constant[Return the changes needed for this refactoring
Parameters:
- `dest_attr`: the name of the destination attribute
- `new_name`: the name of the new method; if `None` uses
the old n... | keyword[def] identifier[get_changes] ( identifier[self] , identifier[dest_attr] , identifier[new_name] = keyword[None] , identifier[resources] = keyword[None] ,
identifier[task_handle] = identifier[taskhandle] . identifier[NullTaskHandle] ()):
literal[string]
identifier[changes] = identifier[Chang... | def get_changes(self, dest_attr, new_name=None, resources=None, task_handle=taskhandle.NullTaskHandle()):
"""Return the changes needed for this refactoring
Parameters:
- `dest_attr`: the name of the destination attribute
- `new_name`: the name of the new method; if `None` uses
th... |
def get(self, key, recursive=False, sorted=False, quorum=False,
timeout=None):
"""Gets a value of key."""
return self.adapter.get(key, recursive=recursive, sorted=sorted,
quorum=quorum, timeout=timeout) | def function[get, parameter[self, key, recursive, sorted, quorum, timeout]]:
constant[Gets a value of key.]
return[call[name[self].adapter.get, parameter[name[key]]]] | keyword[def] identifier[get] ( identifier[self] , identifier[key] , identifier[recursive] = keyword[False] , identifier[sorted] = keyword[False] , identifier[quorum] = keyword[False] ,
identifier[timeout] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[adapter] . ... | def get(self, key, recursive=False, sorted=False, quorum=False, timeout=None):
"""Gets a value of key."""
return self.adapter.get(key, recursive=recursive, sorted=sorted, quorum=quorum, timeout=timeout) |
def clean_fails(self):
"""
Check if there are any fails that were not subsequently retried.
:return: Boolean
"""
for item in self.data:
if item.failure and not item.retries_left > 0:
return True
return False | def function[clean_fails, parameter[self]]:
constant[
Check if there are any fails that were not subsequently retried.
:return: Boolean
]
for taget[name[item]] in starred[name[self].data] begin[:]
if <ast.BoolOp object at 0x7da1b0c36080> begin[:]
retu... | keyword[def] identifier[clean_fails] ( identifier[self] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[self] . identifier[data] :
keyword[if] identifier[item] . identifier[failure] keyword[and] keyword[not] identifier[item] . identifier[retries_left] > l... | def clean_fails(self):
"""
Check if there are any fails that were not subsequently retried.
:return: Boolean
"""
for item in self.data:
if item.failure and (not item.retries_left > 0):
return True # depends on [control=['if'], data=[]] # depends on [control=['for']... |
def run_once(self):
"""
Execute the worker once.
This method will return after a file change is detected.
"""
self._capture_signals()
self._start_monitor()
try:
self._run_worker()
except KeyboardInterrupt:
return
finally:
... | def function[run_once, parameter[self]]:
constant[
Execute the worker once.
This method will return after a file change is detected.
]
call[name[self]._capture_signals, parameter[]]
call[name[self]._start_monitor, parameter[]]
<ast.Try object at 0x7da1b1152e60> | keyword[def] identifier[run_once] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_capture_signals] ()
identifier[self] . identifier[_start_monitor] ()
keyword[try] :
identifier[self] . identifier[_run_worker] ()
keyword[except] identifie... | def run_once(self):
"""
Execute the worker once.
This method will return after a file change is detected.
"""
self._capture_signals()
self._start_monitor()
try:
self._run_worker() # depends on [control=['try'], data=[]]
except KeyboardInterrupt:
return # d... |
def exists(self, client=None):
"""Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Opt... | def function[exists, parameter[self, client]]:
constant[Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
... | keyword[def] identifier[exists] ( identifier[self] , identifier[client] = keyword[None] ):
literal[string]
identifier[client] = identifier[self] . identifier[_require_client] ( identifier[client] )
identifier[query_params] = identifier[self] . identifier[_query_params]
... | def exists(self, client=None):
"""Determines whether or not this blob exists.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optiona... |
def _process_delivery(self, pn_delivery):
"""Check if the delivery can be processed."""
if pn_delivery.readable and not pn_delivery.partial:
data = self._pn_link.recv(pn_delivery.pending)
msg = proton.Message()
msg.decode(data)
self._pn_link.advance()
... | def function[_process_delivery, parameter[self, pn_delivery]]:
constant[Check if the delivery can be processed.]
if <ast.BoolOp object at 0x7da1b01a4160> begin[:]
variable[data] assign[=] call[name[self]._pn_link.recv, parameter[name[pn_delivery].pending]]
variable[msg] a... | keyword[def] identifier[_process_delivery] ( identifier[self] , identifier[pn_delivery] ):
literal[string]
keyword[if] identifier[pn_delivery] . identifier[readable] keyword[and] keyword[not] identifier[pn_delivery] . identifier[partial] :
identifier[data] = identifier[self] . iden... | def _process_delivery(self, pn_delivery):
"""Check if the delivery can be processed."""
if pn_delivery.readable and (not pn_delivery.partial):
data = self._pn_link.recv(pn_delivery.pending)
msg = proton.Message()
msg.decode(data)
self._pn_link.advance()
if self._handler:
... |
def from_stored(self, key):
"""
Set the current collection as based on a stored one. The key argument
is the key off the stored collection.
"""
# only one stored key allowed
if self.stored_key:
raise ValueError('This collection is already based on a stored one... | def function[from_stored, parameter[self, key]]:
constant[
Set the current collection as based on a stored one. The key argument
is the key off the stored collection.
]
if name[self].stored_key begin[:]
<ast.Raise object at 0x7da1b2524940>
name[self].stored_key as... | keyword[def] identifier[from_stored] ( identifier[self] , identifier[key] ):
literal[string]
keyword[if] identifier[self] . identifier[stored_key] :
keyword[raise] identifier[ValueError] ( literal[string] )
identifier[self] . identifier[stored_key] = i... | def from_stored(self, key):
"""
Set the current collection as based on a stored one. The key argument
is the key off the stored collection.
"""
# only one stored key allowed
if self.stored_key:
raise ValueError('This collection is already based on a stored one') # depends on... |
async def shuffle(self, state: Optional[bool] = None, *, device: Optional[SomeDevice] = None):
"""shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s pla... | <ast.AsyncFunctionDef object at 0x7da2041db820> | keyword[async] keyword[def] identifier[shuffle] ( identifier[self] , identifier[state] : identifier[Optional] [ identifier[bool] ]= keyword[None] ,*, identifier[device] : identifier[Optional] [ identifier[SomeDevice] ]= keyword[None] ):
literal[string]
keyword[await] identifier[self] . identifier... | async def shuffle(self, state: Optional[bool]=None, *, device: Optional[SomeDevice]=None):
"""shuffle on or off for user’s playback.
Parameters
----------
state : Optional[bool]
if `True` then Shuffle user’s playback.
else if `False` do not shuffle user’s playback.
... |
def add_sample(self, samp_name, site_name=None, er_data=None, pmag_data=None):
"""
Create a Sample object and add it to self.samples.
If a site name is provided, add the sample to site.samples as well.
"""
if site_name:
site = self.find_by_name(site_name, self.sites)
... | def function[add_sample, parameter[self, samp_name, site_name, er_data, pmag_data]]:
constant[
Create a Sample object and add it to self.samples.
If a site name is provided, add the sample to site.samples as well.
]
if name[site_name] begin[:]
variable[site] assig... | keyword[def] identifier[add_sample] ( identifier[self] , identifier[samp_name] , identifier[site_name] = keyword[None] , identifier[er_data] = keyword[None] , identifier[pmag_data] = keyword[None] ):
literal[string]
keyword[if] identifier[site_name] :
identifier[site] = identifier[sel... | def add_sample(self, samp_name, site_name=None, er_data=None, pmag_data=None):
"""
Create a Sample object and add it to self.samples.
If a site name is provided, add the sample to site.samples as well.
"""
if site_name:
site = self.find_by_name(site_name, self.sites)
if n... |
def _dirdiffcopyandupdate(self, dir1, dir2):
"""
Private function which does directory diff, copy and update (synchro)
"""
self._dowork(dir1, dir2, self._copy, self._update) | def function[_dirdiffcopyandupdate, parameter[self, dir1, dir2]]:
constant[
Private function which does directory diff, copy and update (synchro)
]
call[name[self]._dowork, parameter[name[dir1], name[dir2], name[self]._copy, name[self]._update]] | keyword[def] identifier[_dirdiffcopyandupdate] ( identifier[self] , identifier[dir1] , identifier[dir2] ):
literal[string]
identifier[self] . identifier[_dowork] ( identifier[dir1] , identifier[dir2] , identifier[self] . identifier[_copy] , identifier[self] . identifier[_update] ) | def _dirdiffcopyandupdate(self, dir1, dir2):
"""
Private function which does directory diff, copy and update (synchro)
"""
self._dowork(dir1, dir2, self._copy, self._update) |
def fit(self, X, chunks):
"""Learn the RCA model.
Parameters
----------
data : (n x d) data matrix
Each row corresponds to a single instance
chunks : (n,) array of ints
When ``chunks[i] == -1``, point i doesn't belong to any chunklet.
When ``chunks[i] == j``, point i belongs... | def function[fit, parameter[self, X, chunks]]:
constant[Learn the RCA model.
Parameters
----------
data : (n x d) data matrix
Each row corresponds to a single instance
chunks : (n,) array of ints
When ``chunks[i] == -1``, point i doesn't belong to any chunklet.
When ``ch... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[chunks] ):
literal[string]
identifier[X] = identifier[self] . identifier[_prepare_inputs] ( identifier[X] , identifier[ensure_min_samples] = literal[int] )
keyword[if] identifier[self] . identifier[pca_comps] keyword[... | def fit(self, X, chunks):
"""Learn the RCA model.
Parameters
----------
data : (n x d) data matrix
Each row corresponds to a single instance
chunks : (n,) array of ints
When ``chunks[i] == -1``, point i doesn't belong to any chunklet.
When ``chunks[i] == j``, point i belongs... |
def polling(self, system_code=0xffff, request_code=0, time_slots=0):
"""Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to acquire. A
... | def function[polling, parameter[self, system_code, request_code, time_slots]]:
constant[Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to... | keyword[def] identifier[polling] ( identifier[self] , identifier[system_code] = literal[int] , identifier[request_code] = literal[int] , identifier[time_slots] = literal[int] ):
literal[string]
identifier[log] . identifier[debug] ( literal[string] . identifier[format] ( identifier[system_code] ))
... | def polling(self, system_code=65535, request_code=0, time_slots=0):
"""Aquire and identify a card.
The Polling command is used to detect the Type 3 Tags in the
field. It is also used for initialization and anti-collision.
The *system_code* identifies the card system to acquire. A
c... |
def _get_host_only_ip():
"""Determine the host-only IP of the Dusty VM through Virtualbox and SSH
directly, bypassing Docker Machine. We do this because Docker Machine is
much slower, taking about 600ms total. We are basically doing the same
flow Docker Machine does in its own code."""
mac = _get_ho... | def function[_get_host_only_ip, parameter[]]:
constant[Determine the host-only IP of the Dusty VM through Virtualbox and SSH
directly, bypassing Docker Machine. We do this because Docker Machine is
much slower, taking about 600ms total. We are basically doing the same
flow Docker Machine does in its... | keyword[def] identifier[_get_host_only_ip] ():
literal[string]
identifier[mac] = identifier[_get_host_only_mac_address] ()
identifier[ip_addr_show] = identifier[check_output_demoted] ([ literal[string] , literal[string] , literal[string] ,
literal[string] , literal[string] ,
literal[string] ... | def _get_host_only_ip():
"""Determine the host-only IP of the Dusty VM through Virtualbox and SSH
directly, bypassing Docker Machine. We do this because Docker Machine is
much slower, taking about 600ms total. We are basically doing the same
flow Docker Machine does in its own code."""
mac = _get_ho... |
def _get_user_info(self, cmd, section, required=True,
accept_just_who=False):
"""Parse a user section."""
line = self.next_line()
if line.startswith(section + b' '):
return self._who_when(line[len(section + b' '):], cmd, section,
accept_just_who=accept_just_wh... | def function[_get_user_info, parameter[self, cmd, section, required, accept_just_who]]:
constant[Parse a user section.]
variable[line] assign[=] call[name[self].next_line, parameter[]]
if call[name[line].startswith, parameter[binary_operation[name[section] + constant[b' ']]]] begin[:]
re... | keyword[def] identifier[_get_user_info] ( identifier[self] , identifier[cmd] , identifier[section] , identifier[required] = keyword[True] ,
identifier[accept_just_who] = keyword[False] ):
literal[string]
identifier[line] = identifier[self] . identifier[next_line] ()
keyword[if] identifie... | def _get_user_info(self, cmd, section, required=True, accept_just_who=False):
"""Parse a user section."""
line = self.next_line()
if line.startswith(section + b' '):
return self._who_when(line[len(section + b' '):], cmd, section, accept_just_who=accept_just_who) # depends on [control=['if'], data=[... |
def find(self, collection, selector={}):
"""Find data in a collection
Arguments:
collection - collection to search
Keyword Arguments:
selector - the query (default returns all items in a collection)"""
results = []
for _id, doc in self.collection_data.data.get(c... | def function[find, parameter[self, collection, selector]]:
constant[Find data in a collection
Arguments:
collection - collection to search
Keyword Arguments:
selector - the query (default returns all items in a collection)]
variable[results] assign[=] list[[]]
f... | keyword[def] identifier[find] ( identifier[self] , identifier[collection] , identifier[selector] ={}):
literal[string]
identifier[results] =[]
keyword[for] identifier[_id] , identifier[doc] keyword[in] identifier[self] . identifier[collection_data] . identifier[data] . identifier[get] (... | def find(self, collection, selector={}):
"""Find data in a collection
Arguments:
collection - collection to search
Keyword Arguments:
selector - the query (default returns all items in a collection)"""
results = []
for (_id, doc) in self.collection_data.data.get(collection,... |
def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1):
"""
Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float, int, List[str]], List[flo... | def function[prepare_all_data, parameter[data_dir, block_pct_tokens_thresh]]:
constant[
Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float... | keyword[def] identifier[prepare_all_data] ( identifier[data_dir] , identifier[block_pct_tokens_thresh] = literal[int] ):
literal[string]
identifier[gs_blocks_dir] = identifier[os] . identifier[path] . identifier[join] ( identifier[data_dir] , identifier[GOLD_STANDARD_BLOCKS_DIRNAME] )
identifier[gs_bl... | def prepare_all_data(data_dir, block_pct_tokens_thresh=0.1):
"""
Prepare data for all HTML + gold standard blocks examples in ``data_dir``.
Args:
data_dir (str)
block_pct_tokens_thresh (float): must be in [0.0, 1.0]
Returns:
List[Tuple[str, List[float, int, List[str]], List[flo... |
def hilite(s, ok=True, bold=False):
"""Return an highlighted version of 'string'."""
if not term_supports_colors():
return s
attr = []
if ok is None: # no color
pass
elif ok: # green
attr.append('32')
else: # red
attr.append('31')
if bold:
attr.ap... | def function[hilite, parameter[s, ok, bold]]:
constant[Return an highlighted version of 'string'.]
if <ast.UnaryOp object at 0x7da18f09fbb0> begin[:]
return[name[s]]
variable[attr] assign[=] list[[]]
if compare[name[ok] is constant[None]] begin[:]
pass
if name[bol... | keyword[def] identifier[hilite] ( identifier[s] , identifier[ok] = keyword[True] , identifier[bold] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[term_supports_colors] ():
keyword[return] identifier[s]
identifier[attr] =[]
keyword[if] identifier[ok] keywor... | def hilite(s, ok=True, bold=False):
"""Return an highlighted version of 'string'."""
if not term_supports_colors():
return s # depends on [control=['if'], data=[]]
attr = []
if ok is None: # no color
pass # depends on [control=['if'], data=[]]
elif ok: # green
attr.append... |
def drop_file(self, filename, **kwargs):
""" removes the passed in file from the connected triplestore
args:
filename: the filename to remove
"""
log.setLevel(kwargs.get("log_level", self.log_level))
conn = self.__get_conn__(**kwargs)
result = conn.update_que... | def function[drop_file, parameter[self, filename]]:
constant[ removes the passed in file from the connected triplestore
args:
filename: the filename to remove
]
call[name[log].setLevel, parameter[call[name[kwargs].get, parameter[constant[log_level], name[self].log_level]]]]
... | keyword[def] identifier[drop_file] ( identifier[self] , identifier[filename] ,** identifier[kwargs] ):
literal[string]
identifier[log] . identifier[setLevel] ( identifier[kwargs] . identifier[get] ( literal[string] , identifier[self] . identifier[log_level] ))
identifier[conn] = identifier... | def drop_file(self, filename, **kwargs):
""" removes the passed in file from the connected triplestore
args:
filename: the filename to remove
"""
log.setLevel(kwargs.get('log_level', self.log_level))
conn = self.__get_conn__(**kwargs)
result = conn.update_query('DROP GRAPH %... |
def check_requirements_file(req_file, skip_packages):
"""Return list of outdated requirements.
Args:
req_file (str): Filename of requirements file
skip_packages (list): List of package names to ignore.
"""
reqs = read_requirements(req_file)
if skip_packages is not None:
reqs... | def function[check_requirements_file, parameter[req_file, skip_packages]]:
constant[Return list of outdated requirements.
Args:
req_file (str): Filename of requirements file
skip_packages (list): List of package names to ignore.
]
variable[reqs] assign[=] call[name[read_requirem... | keyword[def] identifier[check_requirements_file] ( identifier[req_file] , identifier[skip_packages] ):
literal[string]
identifier[reqs] = identifier[read_requirements] ( identifier[req_file] )
keyword[if] identifier[skip_packages] keyword[is] keyword[not] keyword[None] :
identifier[reqs] ... | def check_requirements_file(req_file, skip_packages):
"""Return list of outdated requirements.
Args:
req_file (str): Filename of requirements file
skip_packages (list): List of package names to ignore.
"""
reqs = read_requirements(req_file)
if skip_packages is not None:
reqs... |
def _prop(self, T, rho, fav):
"""Thermodynamic properties of humid air
Parameters
----------
T : float
Temperature, [K]
rho : float
Density, [kg/m³]
fav : dict
dictionary with helmholtz energy and derivatives
Returns
-... | def function[_prop, parameter[self, T, rho, fav]]:
constant[Thermodynamic properties of humid air
Parameters
----------
T : float
Temperature, [K]
rho : float
Density, [kg/m³]
fav : dict
dictionary with helmholtz energy and derivatives... | keyword[def] identifier[_prop] ( identifier[self] , identifier[T] , identifier[rho] , identifier[fav] ):
literal[string]
identifier[prop] ={}
identifier[prop] [ literal[string] ]= identifier[rho] ** literal[int] * identifier[fav] [ literal[string] ]/ literal[int]
identifier[prop]... | def _prop(self, T, rho, fav):
"""Thermodynamic properties of humid air
Parameters
----------
T : float
Temperature, [K]
rho : float
Density, [kg/m³]
fav : dict
dictionary with helmholtz energy and derivatives
Returns
-----... |
def set_reboot_required_witnessed():
r'''
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function relies on the salt-minion's ability to
create the following volatile registry key in the *HKLM* hive:
*SYSTEM\\CurrentControlSet\\Services\\... | def function[set_reboot_required_witnessed, parameter[]]:
constant[
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function relies on the salt-minion's ability to
create the following volatile registry key in the *HKLM* hive:
*SYSTEM\... | keyword[def] identifier[set_reboot_required_witnessed] ():
literal[string]
keyword[return] identifier[__utils__] [ literal[string] ](
identifier[hive] = literal[string] ,
identifier[key] = identifier[MINION_VOLATILE_KEY] ,
identifier[volatile] = keyword[True] ,
identifier[vname] = iden... | def set_reboot_required_witnessed():
"""
This function is used to remember that an event indicating that a reboot is
required was witnessed. This function relies on the salt-minion's ability to
create the following volatile registry key in the *HKLM* hive:
*SYSTEM\\\\CurrentControlSet\\\\Service... |
def system_monitor_cid_card_threshold_marginal_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
system_monitor = ET.SubElement(config, "system-monitor", xmlns="urn:brocade.com:mgmt:brocade-system-monitor")
cid_card = ET.SubElement(system_monitor... | def function[system_monitor_cid_card_threshold_marginal_threshold, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[system_monitor] assign[=] call[name[ET].SubElement, parameter[name[config], constant... | keyword[def] identifier[system_monitor_cid_card_threshold_marginal_threshold] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[system_monitor] = identifier[ET] . identifier[SubElement] ( id... | def system_monitor_cid_card_threshold_marginal_threshold(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
system_monitor = ET.SubElement(config, 'system-monitor', xmlns='urn:brocade.com:mgmt:brocade-system-monitor')
cid_card = ET.SubElement(system_monitor, 'cid-card')
... |
def purge(self):
"""Submit purge request(s) to the CCU API
Since a purge call may require multiple API requests and may trigger rate-limiting
this method uses a generator to provide the results of each request, allowing you to
communicate request progress or implement a custom rate-limi... | def function[purge, parameter[self]]:
constant[Submit purge request(s) to the CCU API
Since a purge call may require multiple API requests and may trigger rate-limiting
this method uses a generator to provide the results of each request, allowing you to
communicate request progress or i... | keyword[def] identifier[purge] ( identifier[self] ):
literal[string]
identifier[purge_url] = identifier[urljoin] ( literal[string] % identifier[self] . identifier[host] , literal[string] %( identifier[self] . identifier[action] , identifier[self] . identifier[network] ))
keyword[while] ... | def purge(self):
"""Submit purge request(s) to the CCU API
Since a purge call may require multiple API requests and may trigger rate-limiting
this method uses a generator to provide the results of each request, allowing you to
communicate request progress or implement a custom rate-limiting... |
def _serialize_iterable(obj):
"""
Only for serializing list and tuples and stuff.
Dicts and Strings/Unicode is treated differently.
String/Unicode normally don't need further serialization and it would cause
a max recursion error trying to do so.
:param obj:
:return:
"""
if isinstanc... | def function[_serialize_iterable, parameter[obj]]:
constant[
Only for serializing list and tuples and stuff.
Dicts and Strings/Unicode is treated differently.
String/Unicode normally don't need further serialization and it would cause
a max recursion error trying to do so.
:param obj:
:r... | keyword[def] identifier[_serialize_iterable] ( identifier[obj] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[obj] ,( identifier[tuple] , identifier[set] )):
identifier[obj] = identifier[list] ( identifier[obj] )
keyword[for] identifier[item] keyword[in] identifie... | def _serialize_iterable(obj):
"""
Only for serializing list and tuples and stuff.
Dicts and Strings/Unicode is treated differently.
String/Unicode normally don't need further serialization and it would cause
a max recursion error trying to do so.
:param obj:
:return:
"""
if isinstanc... |
def GroupsSensorsGet(self, group_id, parameters):
"""
Retrieve sensors shared within the group.
@param group_id (int) - Id of the group to retrieve sensors from
@param parameters (dictionary) - Additional parameters for the call
@r... | def function[GroupsSensorsGet, parameter[self, group_id, parameters]]:
constant[
Retrieve sensors shared within the group.
@param group_id (int) - Id of the group to retrieve sensors from
@param parameters (dictionary) - Additional parameters for the call
... | keyword[def] identifier[GroupsSensorsGet] ( identifier[self] , identifier[group_id] , identifier[parameters] ):
literal[string]
keyword[if] identifier[self] . identifier[__SenseApiCall] ( literal[string] . identifier[format] ( identifier[group_id] ), literal[string] , identifier[parameters] = id... | def GroupsSensorsGet(self, group_id, parameters):
"""
Retrieve sensors shared within the group.
@param group_id (int) - Id of the group to retrieve sensors from
@param parameters (dictionary) - Additional parameters for the call
@return (bool... |
def angles(self):
'''List of angles for rotational degrees of freedom.'''
return [self.ode_obj.getAngle(i) for i in range(self.ADOF)] | def function[angles, parameter[self]]:
constant[List of angles for rotational degrees of freedom.]
return[<ast.ListComp object at 0x7da1b00482e0>] | keyword[def] identifier[angles] ( identifier[self] ):
literal[string]
keyword[return] [ identifier[self] . identifier[ode_obj] . identifier[getAngle] ( identifier[i] ) keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[self] . identifier[ADOF] )] | def angles(self):
"""List of angles for rotational degrees of freedom."""
return [self.ode_obj.getAngle(i) for i in range(self.ADOF)] |
def parse_doc(obj: dict) -> BioCDocument:
"""Deserialize a dict obj to a BioCDocument object"""
doc = BioCDocument()
doc.id = obj['id']
doc.infons = obj['infons']
for passage in obj['passages']:
doc.add_passage(parse_passage(passage))
for annotation in obj['annotations']:
... | def function[parse_doc, parameter[obj]]:
constant[Deserialize a dict obj to a BioCDocument object]
variable[doc] assign[=] call[name[BioCDocument], parameter[]]
name[doc].id assign[=] call[name[obj]][constant[id]]
name[doc].infons assign[=] call[name[obj]][constant[infons]]
for t... | keyword[def] identifier[parse_doc] ( identifier[obj] : identifier[dict] )-> identifier[BioCDocument] :
literal[string]
identifier[doc] = identifier[BioCDocument] ()
identifier[doc] . identifier[id] = identifier[obj] [ literal[string] ]
identifier[doc] . identifier[infons] = identifier[obj] [ ... | def parse_doc(obj: dict) -> BioCDocument:
"""Deserialize a dict obj to a BioCDocument object"""
doc = BioCDocument()
doc.id = obj['id']
doc.infons = obj['infons']
for passage in obj['passages']:
doc.add_passage(parse_passage(passage)) # depends on [control=['for'], data=['passage']]
for... |
def MultiListChildren(self, urns):
"""Lists children of a bunch of given urns. Results are cached."""
result = {}
not_listed_urns = []
for urn in urns:
try:
result[urn] = self._children_lists_cache[urn]
except KeyError:
not_listed_urns.append(urn)
if not_listed_urns:
... | def function[MultiListChildren, parameter[self, urns]]:
constant[Lists children of a bunch of given urns. Results are cached.]
variable[result] assign[=] dictionary[[], []]
variable[not_listed_urns] assign[=] list[[]]
for taget[name[urn]] in starred[name[urns]] begin[:]
<ast.Try ... | keyword[def] identifier[MultiListChildren] ( identifier[self] , identifier[urns] ):
literal[string]
identifier[result] ={}
identifier[not_listed_urns] =[]
keyword[for] identifier[urn] keyword[in] identifier[urns] :
keyword[try] :
identifier[result] [ identifier[urn] ]= identif... | def MultiListChildren(self, urns):
"""Lists children of a bunch of given urns. Results are cached."""
result = {}
not_listed_urns = []
for urn in urns:
try:
result[urn] = self._children_lists_cache[urn] # depends on [control=['try'], data=[]]
except KeyError:
not... |
def default(self, interface, vrid):
"""Defaults a vrrp instance from an interface
Note:
This method will attempt to default the vrrp on the node's
operational config. Default results in the deletion of the
specified vrrp . If the vrrp does not exist on the
... | def function[default, parameter[self, interface, vrid]]:
constant[Defaults a vrrp instance from an interface
Note:
This method will attempt to default the vrrp on the node's
operational config. Default results in the deletion of the
specified vrrp . If the vrrp does ... | keyword[def] identifier[default] ( identifier[self] , identifier[interface] , identifier[vrid] ):
literal[string]
identifier[vrrp_str] = literal[string] % identifier[vrid]
keyword[return] identifier[self] . identifier[configure_interface] ( identifier[interface] , identifier[vrrp_str] ) | def default(self, interface, vrid):
"""Defaults a vrrp instance from an interface
Note:
This method will attempt to default the vrrp on the node's
operational config. Default results in the deletion of the
specified vrrp . If the vrrp does not exist on the
in... |
def _print_errs(self):
"""
Prints the errors trace with tracebacks
"""
i = 0
for error in self.errors:
print(self._errmsg(error, tb=True, i=i))
# for spacing
if self.errs_traceback is False:
print()
i += 1 | def function[_print_errs, parameter[self]]:
constant[
Prints the errors trace with tracebacks
]
variable[i] assign[=] constant[0]
for taget[name[error]] in starred[name[self].errors] begin[:]
call[name[print], parameter[call[name[self]._errmsg, parameter[name[erro... | keyword[def] identifier[_print_errs] ( identifier[self] ):
literal[string]
identifier[i] = literal[int]
keyword[for] identifier[error] keyword[in] identifier[self] . identifier[errors] :
identifier[print] ( identifier[self] . identifier[_errmsg] ( identifier[error] , ident... | def _print_errs(self):
"""
Prints the errors trace with tracebacks
"""
i = 0
for error in self.errors:
print(self._errmsg(error, tb=True, i=i))
# for spacing
if self.errs_traceback is False:
print() # depends on [control=['if'], data=[]]
i += 1 #... |
def create(lr, betas=(0.9, 0.999), weight_decay=0, epsilon=1e-8, layer_groups=False):
""" Vel factory function """
return AdamFactory(lr=lr, betas=betas, weight_decay=weight_decay, eps=epsilon, layer_groups=layer_groups) | def function[create, parameter[lr, betas, weight_decay, epsilon, layer_groups]]:
constant[ Vel factory function ]
return[call[name[AdamFactory], parameter[]]] | keyword[def] identifier[create] ( identifier[lr] , identifier[betas] =( literal[int] , literal[int] ), identifier[weight_decay] = literal[int] , identifier[epsilon] = literal[int] , identifier[layer_groups] = keyword[False] ):
literal[string]
keyword[return] identifier[AdamFactory] ( identifier[lr] = iden... | def create(lr, betas=(0.9, 0.999), weight_decay=0, epsilon=1e-08, layer_groups=False):
""" Vel factory function """
return AdamFactory(lr=lr, betas=betas, weight_decay=weight_decay, eps=epsilon, layer_groups=layer_groups) |
def first_match(predicate, lst):
"""
returns the first value of predicate applied to list, which
does not return None
>>>
>>> def return_if_even(x):
... if x % 2 is 0:
... return x
... return None
>>>
>>> first_match(return_if_even, [1, 3, 4, 7])
4
>>> fi... | def function[first_match, parameter[predicate, lst]]:
constant[
returns the first value of predicate applied to list, which
does not return None
>>>
>>> def return_if_even(x):
... if x % 2 is 0:
... return x
... return None
>>>
>>> first_match(return_if_even,... | keyword[def] identifier[first_match] ( identifier[predicate] , identifier[lst] ):
literal[string]
keyword[for] identifier[item] keyword[in] identifier[lst] :
identifier[val] = identifier[predicate] ( identifier[item] )
keyword[if] identifier[val] keyword[is] keyword[not] keyword[No... | def first_match(predicate, lst):
"""
returns the first value of predicate applied to list, which
does not return None
>>>
>>> def return_if_even(x):
... if x % 2 is 0:
... return x
... return None
>>>
>>> first_match(return_if_even, [1, 3, 4, 7])
4
>>> fi... |
def normalize_route(route: str) -> str:
"""Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/'
"""
normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
normalized_route = normalized_route.replace('<... | def function[normalize_route, parameter[route]]:
constant[Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/'
]
variable[normalized_route] assign[=] call[call[call[call[name[str], parameter[name[route]]].lst... | keyword[def] identifier[normalize_route] ( identifier[route] : identifier[str] )-> identifier[str] :
literal[string]
identifier[normalized_route] = identifier[str] ( identifier[route] ). identifier[lstrip] ( literal[string] ). identifier[rstrip] ( literal[string] ). identifier[rstrip] ( literal[string] )
... | def normalize_route(route: str) -> str:
"""Strip some of the ugly regexp characters from the given pattern.
>>> normalize_route('^/user/<user_id:int>/?$')
u'/user/(user_id:int)/'
"""
normalized_route = str(route).lstrip('^').rstrip('$').rstrip('?')
normalized_route = normalized_route.replace('<... |
def render(self, sources, config, out=sys.stdout):
"""Render the documentation as defined in config Object
"""
logger = logging.getLogger()
template = self.env.get_template(self.input)
output = template.render(sources=sources, layout=config["output"]["layout"], config=config["out... | def function[render, parameter[self, sources, config, out]]:
constant[Render the documentation as defined in config Object
]
variable[logger] assign[=] call[name[logging].getLogger, parameter[]]
variable[template] assign[=] call[name[self].env.get_template, parameter[name[self].input]]
... | keyword[def] identifier[render] ( identifier[self] , identifier[sources] , identifier[config] , identifier[out] = identifier[sys] . identifier[stdout] ):
literal[string]
identifier[logger] = identifier[logging] . identifier[getLogger] ()
identifier[template] = identifier[self] . identifier... | def render(self, sources, config, out=sys.stdout):
"""Render the documentation as defined in config Object
"""
logger = logging.getLogger()
template = self.env.get_template(self.input)
output = template.render(sources=sources, layout=config['output']['layout'], config=config['output'])
if se... |
def get_frames(self, channels=2):
"""Get numpy array of frames corresponding to the segment.
:param integer channels: Number of channels in output array
:returns: Array of frames in the segment
:rtype: numpy array
"""
tmp_frame = self.track.current_frame
self.tr... | def function[get_frames, parameter[self, channels]]:
constant[Get numpy array of frames corresponding to the segment.
:param integer channels: Number of channels in output array
:returns: Array of frames in the segment
:rtype: numpy array
]
variable[tmp_frame] assign[=]... | keyword[def] identifier[get_frames] ( identifier[self] , identifier[channels] = literal[int] ):
literal[string]
identifier[tmp_frame] = identifier[self] . identifier[track] . identifier[current_frame]
identifier[self] . identifier[track] . identifier[current_frame] = identifier[self] . id... | def get_frames(self, channels=2):
"""Get numpy array of frames corresponding to the segment.
:param integer channels: Number of channels in output array
:returns: Array of frames in the segment
:rtype: numpy array
"""
tmp_frame = self.track.current_frame
self.track.current_... |
def get_asset_temporal_assignment_session_for_repository(self, repository_id, proxy):
"""Gets the session for assigning temporal coverage of an asset for
the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
... | def function[get_asset_temporal_assignment_session_for_repository, parameter[self, repository_id, proxy]]:
constant[Gets the session for assigning temporal coverage of an asset for
the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.pro... | keyword[def] identifier[get_asset_temporal_assignment_session_for_repository] ( identifier[self] , identifier[repository_id] , identifier[proxy] ):
literal[string]
keyword[if] keyword[not] identifier[repository_id] :
keyword[raise] identifier[NullArgument] ()
keyword[if] k... | def get_asset_temporal_assignment_session_for_repository(self, repository_id, proxy):
"""Gets the session for assigning temporal coverage of an asset for
the given repository.
arg: repository_id (osid.id.Id): the Id of the repository
arg proxy (osid.proxy.Proxy): a proxy
retu... |
def exchange_bind_to_queue(self, type, exchange_name, routing_key, queue):
"""
Declare exchange and bind queue to exchange
:param type: The type of exchange
:param exchange_name: The name of exchange
:param routing_key: The key of exchange bind to queue
:param queue: queu... | def function[exchange_bind_to_queue, parameter[self, type, exchange_name, routing_key, queue]]:
constant[
Declare exchange and bind queue to exchange
:param type: The type of exchange
:param exchange_name: The name of exchange
:param routing_key: The key of exchange bind to queue... | keyword[def] identifier[exchange_bind_to_queue] ( identifier[self] , identifier[type] , identifier[exchange_name] , identifier[routing_key] , identifier[queue] ):
literal[string]
identifier[self] . identifier[_channel] . identifier[exchange_declare] ( identifier[exchange] = identifier[exchange_name... | def exchange_bind_to_queue(self, type, exchange_name, routing_key, queue):
"""
Declare exchange and bind queue to exchange
:param type: The type of exchange
:param exchange_name: The name of exchange
:param routing_key: The key of exchange bind to queue
:param queue: queue na... |
def _is_undefok(arg, undefok_names):
"""Returns whether we can ignore arg based on a set of undefok flag names."""
if not arg.startswith('-'):
return False
if arg.startswith('--'):
arg_without_dash = arg[2:]
else:
arg_without_dash = arg[1:]
if '=' in arg_without_dash:
name, _ = arg_without_das... | def function[_is_undefok, parameter[arg, undefok_names]]:
constant[Returns whether we can ignore arg based on a set of undefok flag names.]
if <ast.UnaryOp object at 0x7da1b19ce0e0> begin[:]
return[constant[False]]
if call[name[arg].startswith, parameter[constant[--]]] begin[:]
... | keyword[def] identifier[_is_undefok] ( identifier[arg] , identifier[undefok_names] ):
literal[string]
keyword[if] keyword[not] identifier[arg] . identifier[startswith] ( literal[string] ):
keyword[return] keyword[False]
keyword[if] identifier[arg] . identifier[startswith] ( literal[string] ):
... | def _is_undefok(arg, undefok_names):
"""Returns whether we can ignore arg based on a set of undefok flag names."""
if not arg.startswith('-'):
return False # depends on [control=['if'], data=[]]
if arg.startswith('--'):
arg_without_dash = arg[2:] # depends on [control=['if'], data=[]]
... |
def templates(self) -> List['Template']:
"""Return a list of templates as template objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [
Template(_lststr, _type_to_spans, span, 'Template')
for span in self._subspans('Template')] | def function[templates, parameter[self]]:
constant[Return a list of templates as template objects.]
variable[_lststr] assign[=] name[self]._lststr
variable[_type_to_spans] assign[=] name[self]._type_to_spans
return[<ast.ListComp object at 0x7da1b05cabc0>] | keyword[def] identifier[templates] ( identifier[self] )-> identifier[List] [ literal[string] ]:
literal[string]
identifier[_lststr] = identifier[self] . identifier[_lststr]
identifier[_type_to_spans] = identifier[self] . identifier[_type_to_spans]
keyword[return] [
iden... | def templates(self) -> List['Template']:
"""Return a list of templates as template objects."""
_lststr = self._lststr
_type_to_spans = self._type_to_spans
return [Template(_lststr, _type_to_spans, span, 'Template') for span in self._subspans('Template')] |
def execute(self, query, until_zero=False):
"""
Execute a query
:param query: query to execute
:param until_zero: should query be called until returns 0
:return:
"""
if self._conn.closed:
self._conn = psycopg2.connect(self._connection_string, connecti... | def function[execute, parameter[self, query, until_zero]]:
constant[
Execute a query
:param query: query to execute
:param until_zero: should query be called until returns 0
:return:
]
if name[self]._conn.closed begin[:]
name[self]._conn assign[=] ... | keyword[def] identifier[execute] ( identifier[self] , identifier[query] , identifier[until_zero] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[_conn] . identifier[closed] :
identifier[self] . identifier[_conn] = identifier[psycopg2] . identifier[connec... | def execute(self, query, until_zero=False):
"""
Execute a query
:param query: query to execute
:param until_zero: should query be called until returns 0
:return:
"""
if self._conn.closed:
self._conn = psycopg2.connect(self._connection_string, connection_factory=pg... |
def initialize_ui(self):
"""
Initializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__))
self.__model = ComponentsModel(self, horizontal_headers=self.__headers)
... | def function[initialize_ui, parameter[self]]:
constant[
Initializes the Component ui.
:return: Method success.
:rtype: bool
]
call[name[LOGGER].debug, parameter[call[constant[> Initializing '{0}' Component ui.].format, parameter[name[self].__class__.__name__]]]]
... | keyword[def] identifier[initialize_ui] ( identifier[self] ):
literal[string]
identifier[LOGGER] . identifier[debug] ( literal[string] . identifier[format] ( identifier[self] . identifier[__class__] . identifier[__name__] ))
identifier[self] . identifier[__model] = identifier[ComponentsMo... | def initialize_ui(self):
"""
Initializes the Component ui.
:return: Method success.
:rtype: bool
"""
LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__))
self.__model = ComponentsModel(self, horizontal_headers=self.__headers)
self.set_compon... |
def fuzzyfinder(text, collection):
"""https://github.com/amjith/fuzzyfinder"""
suggestions = []
if not isinstance(text, six.text_type):
text = six.u(text)
pat = '.*?'.join(map(re.escape, text))
regex = re.compile(pat, flags=re.IGNORECASE)
for item in collection:
r = regex.search(... | def function[fuzzyfinder, parameter[text, collection]]:
constant[https://github.com/amjith/fuzzyfinder]
variable[suggestions] assign[=] list[[]]
if <ast.UnaryOp object at 0x7da20c9903d0> begin[:]
variable[text] assign[=] call[name[six].u, parameter[name[text]]]
variable[p... | keyword[def] identifier[fuzzyfinder] ( identifier[text] , identifier[collection] ):
literal[string]
identifier[suggestions] =[]
keyword[if] keyword[not] identifier[isinstance] ( identifier[text] , identifier[six] . identifier[text_type] ):
identifier[text] = identifier[six] . identifier[u] ... | def fuzzyfinder(text, collection):
"""https://github.com/amjith/fuzzyfinder"""
suggestions = []
if not isinstance(text, six.text_type):
text = six.u(text) # depends on [control=['if'], data=[]]
pat = '.*?'.join(map(re.escape, text))
regex = re.compile(pat, flags=re.IGNORECASE)
for item ... |
def plot_variance_explained(self, cumulative=False, xtick_start=1,
xtick_spacing=1, num_pc=None):
"""
Plot amount of variance explained by each principal component.
Parameters
----------
num_pc : int
Number of principal components... | def function[plot_variance_explained, parameter[self, cumulative, xtick_start, xtick_spacing, num_pc]]:
constant[
Plot amount of variance explained by each principal component.
Parameters
----------
num_pc : int
Number of principal components to plot. If None, p... | keyword[def] identifier[plot_variance_explained] ( identifier[self] , identifier[cumulative] = keyword[False] , identifier[xtick_start] = literal[int] ,
identifier[xtick_spacing] = literal[int] , identifier[num_pc] = keyword[None] ):
literal[string]
keyword[import] identifier[matplotlib] . identi... | def plot_variance_explained(self, cumulative=False, xtick_start=1, xtick_spacing=1, num_pc=None):
"""
Plot amount of variance explained by each principal component.
Parameters
----------
num_pc : int
Number of principal components to plot. If None, plot all.
... |
def signal_handler_mapping(self):
"""A dict mapping (signal number) -> (a method handling the signal)."""
# Could use an enum here, but we never end up doing any matching on the specific signal value,
# instead just iterating over the registered signals to set handlers, so a dict is probably
# better.
... | def function[signal_handler_mapping, parameter[self]]:
constant[A dict mapping (signal number) -> (a method handling the signal).]
return[dictionary[[<ast.Attribute object at 0x7da1b1ead870>, <ast.Attribute object at 0x7da1b1eac7c0>, <ast.Attribute object at 0x7da1b1eae2c0>], [<ast.Attribute object at 0x7da... | keyword[def] identifier[signal_handler_mapping] ( identifier[self] ):
literal[string]
keyword[return] {
identifier[signal] . identifier[SIGINT] : identifier[self] . identifier[handle_sigint] ,
identifier[signal] . identifier[SIGQUIT] : identifier[self] . identifier[handle_sigquit] ... | def signal_handler_mapping(self):
"""A dict mapping (signal number) -> (a method handling the signal)."""
# Could use an enum here, but we never end up doing any matching on the specific signal value,
# instead just iterating over the registered signals to set handlers, so a dict is probably
# better.
... |
def init(module, db):
"""
Initialize the models.
"""
for model in farine.discovery.import_models(module):
model._meta.database = db | def function[init, parameter[module, db]]:
constant[
Initialize the models.
]
for taget[name[model]] in starred[call[name[farine].discovery.import_models, parameter[name[module]]]] begin[:]
name[model]._meta.database assign[=] name[db] | keyword[def] identifier[init] ( identifier[module] , identifier[db] ):
literal[string]
keyword[for] identifier[model] keyword[in] identifier[farine] . identifier[discovery] . identifier[import_models] ( identifier[module] ):
identifier[model] . identifier[_meta] . identifier[database] = identif... | def init(module, db):
"""
Initialize the models.
"""
for model in farine.discovery.import_models(module):
model._meta.database = db # depends on [control=['for'], data=['model']] |
def write(s, path, encoding="utf-8"):
"""Write string to text file.
"""
is_gzip = is_gzip_file(path)
with open(path, "wb") as f:
if is_gzip:
f.write(zlib.compress(s.encode(encoding)))
else:
f.write(s.encode(encoding)) | def function[write, parameter[s, path, encoding]]:
constant[Write string to text file.
]
variable[is_gzip] assign[=] call[name[is_gzip_file], parameter[name[path]]]
with call[name[open], parameter[name[path], constant[wb]]] begin[:]
if name[is_gzip] begin[:]
... | keyword[def] identifier[write] ( identifier[s] , identifier[path] , identifier[encoding] = literal[string] ):
literal[string]
identifier[is_gzip] = identifier[is_gzip_file] ( identifier[path] )
keyword[with] identifier[open] ( identifier[path] , literal[string] ) keyword[as] identifier[f] :
... | def write(s, path, encoding='utf-8'):
"""Write string to text file.
"""
is_gzip = is_gzip_file(path)
with open(path, 'wb') as f:
if is_gzip:
f.write(zlib.compress(s.encode(encoding))) # depends on [control=['if'], data=[]]
else:
f.write(s.encode(encoding)) # dep... |
def save_sql_to_files(overwrite=False):
"""
Executes every .sql files in /data/scripts/ using salic db vpn and
then saves pickle files into /data/raw/
"""
ext_size = len(SQL_EXTENSION)
path = DATA_PATH / 'scripts'
save_dir = DATA_PATH / "raw"
for file in os.listdir(path):
if fil... | def function[save_sql_to_files, parameter[overwrite]]:
constant[
Executes every .sql files in /data/scripts/ using salic db vpn and
then saves pickle files into /data/raw/
]
variable[ext_size] assign[=] call[name[len], parameter[name[SQL_EXTENSION]]]
variable[path] assign[=] binary_o... | keyword[def] identifier[save_sql_to_files] ( identifier[overwrite] = keyword[False] ):
literal[string]
identifier[ext_size] = identifier[len] ( identifier[SQL_EXTENSION] )
identifier[path] = identifier[DATA_PATH] / literal[string]
identifier[save_dir] = identifier[DATA_PATH] / literal[string]
... | def save_sql_to_files(overwrite=False):
"""
Executes every .sql files in /data/scripts/ using salic db vpn and
then saves pickle files into /data/raw/
"""
ext_size = len(SQL_EXTENSION)
path = DATA_PATH / 'scripts'
save_dir = DATA_PATH / 'raw'
for file in os.listdir(path):
if file... |
def close_state_machine(self, widget, page_number, event=None):
"""Triggered when the close button in the tab is clicked
"""
page = widget.get_nth_page(page_number)
for tab_info in self.tabs.values():
if tab_info['page'] is page:
state_machine_m = tab_info['st... | def function[close_state_machine, parameter[self, widget, page_number, event]]:
constant[Triggered when the close button in the tab is clicked
]
variable[page] assign[=] call[name[widget].get_nth_page, parameter[name[page_number]]]
for taget[name[tab_info]] in starred[call[name[self].tab... | keyword[def] identifier[close_state_machine] ( identifier[self] , identifier[widget] , identifier[page_number] , identifier[event] = keyword[None] ):
literal[string]
identifier[page] = identifier[widget] . identifier[get_nth_page] ( identifier[page_number] )
keyword[for] identifier[tab_in... | def close_state_machine(self, widget, page_number, event=None):
"""Triggered when the close button in the tab is clicked
"""
page = widget.get_nth_page(page_number)
for tab_info in self.tabs.values():
if tab_info['page'] is page:
state_machine_m = tab_info['state_machine_m']
... |
def histogram(
arg, nbins=None, binwidth=None, base=None, closed='left', aux_hash=None
):
"""
Compute a histogram with fixed width bins
Parameters
----------
arg : numeric array expression
nbins : int, default None
If supplied, will be used to compute the binwidth
binwidth : numbe... | def function[histogram, parameter[arg, nbins, binwidth, base, closed, aux_hash]]:
constant[
Compute a histogram with fixed width bins
Parameters
----------
arg : numeric array expression
nbins : int, default None
If supplied, will be used to compute the binwidth
binwidth : number,... | keyword[def] identifier[histogram] (
identifier[arg] , identifier[nbins] = keyword[None] , identifier[binwidth] = keyword[None] , identifier[base] = keyword[None] , identifier[closed] = literal[string] , identifier[aux_hash] = keyword[None]
):
literal[string]
identifier[op] = identifier[Histogram] (
... | def histogram(arg, nbins=None, binwidth=None, base=None, closed='left', aux_hash=None):
"""
Compute a histogram with fixed width bins
Parameters
----------
arg : numeric array expression
nbins : int, default None
If supplied, will be used to compute the binwidth
binwidth : number, def... |
def _pack_output(self, ans):
"""
Packs the output of a minimization in a
:class:`~symfit.core.fit_results.FitResults`.
:param ans: The output of a minimization as produced by
:func:`scipy.optimize.minimize`
:returns: :class:`~symfit.core.fit_results.FitResults`
... | def function[_pack_output, parameter[self, ans]]:
constant[
Packs the output of a minimization in a
:class:`~symfit.core.fit_results.FitResults`.
:param ans: The output of a minimization as produced by
:func:`scipy.optimize.minimize`
:returns: :class:`~symfit.core.fi... | keyword[def] identifier[_pack_output] ( identifier[self] , identifier[ans] ):
literal[string]
identifier[infodic] ={
literal[string] : identifier[ans] . identifier[nfev] ,
}
identifier[best_vals] =[]
identifier[found] = identifier[iter] ( identifier[np] ... | def _pack_output(self, ans):
"""
Packs the output of a minimization in a
:class:`~symfit.core.fit_results.FitResults`.
:param ans: The output of a minimization as produced by
:func:`scipy.optimize.minimize`
:returns: :class:`~symfit.core.fit_results.FitResults`
"... |
def _parse_json(self, response, exactly_one=True):
"""
Parse responses as JSON objects.
"""
if not len(response):
return None
if exactly_one:
return self._format_structured_address(response[0])
else:
return [self._format_structured_addr... | def function[_parse_json, parameter[self, response, exactly_one]]:
constant[
Parse responses as JSON objects.
]
if <ast.UnaryOp object at 0x7da20c7c85b0> begin[:]
return[constant[None]]
if name[exactly_one] begin[:]
return[call[name[self]._format_structured_addres... | keyword[def] identifier[_parse_json] ( identifier[self] , identifier[response] , identifier[exactly_one] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[len] ( identifier[response] ):
keyword[return] keyword[None]
keyword[if] identifier[exactly_one]... | def _parse_json(self, response, exactly_one=True):
"""
Parse responses as JSON objects.
"""
if not len(response):
return None # depends on [control=['if'], data=[]]
if exactly_one:
return self._format_structured_address(response[0]) # depends on [control=['if'], data=[]]
... |
def canonicalize_path(cwd, path):
"""
Canonicalizes a path relative to a given working directory. That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.
:param cwd: The working directory.
:param path: The path to canonicalize.
... | def function[canonicalize_path, parameter[cwd, path]]:
constant[
Canonicalizes a path relative to a given working directory. That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.
:param cwd: The working directory.
:param path... | keyword[def] identifier[canonicalize_path] ( identifier[cwd] , identifier[path] ):
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isabs] ( identifier[path] ):
identifier[path] = identifier[os] . identifier[path] . identifier[join] ( identifier[cwd] , ide... | def canonicalize_path(cwd, path):
"""
Canonicalizes a path relative to a given working directory. That
is, the path, if not absolute, is interpreted relative to the
working directory, then converted to absolute form.
:param cwd: The working directory.
:param path: The path to canonicalize.
... |
def list_by_claim(self, claim):
"""
Returns a list of all the messages from this queue that have been
claimed by the specified claim. The claim can be either a claim ID or a
QueueClaim object.
"""
if not isinstance(claim, QueueClaim):
claim = self._claim_manag... | def function[list_by_claim, parameter[self, claim]]:
constant[
Returns a list of all the messages from this queue that have been
claimed by the specified claim. The claim can be either a claim ID or a
QueueClaim object.
]
if <ast.UnaryOp object at 0x7da18bcc8970> begin[:]... | keyword[def] identifier[list_by_claim] ( identifier[self] , identifier[claim] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[claim] , identifier[QueueClaim] ):
identifier[claim] = identifier[self] . identifier[_claim_manager] . identifier[get] ( ident... | def list_by_claim(self, claim):
"""
Returns a list of all the messages from this queue that have been
claimed by the specified claim. The claim can be either a claim ID or a
QueueClaim object.
"""
if not isinstance(claim, QueueClaim):
claim = self._claim_manager.get(claim... |
async def delete(self, request, resource=None, **kwargs):
"""Delete a resource.
Supports batch delete.
"""
if resource:
resources = [resource]
else:
data = await self.parse(request)
if data:
resources = list(self.collection.whe... | <ast.AsyncFunctionDef object at 0x7da1b0b3a170> | keyword[async] keyword[def] identifier[delete] ( identifier[self] , identifier[request] , identifier[resource] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[resource] :
identifier[resources] =[ identifier[resource] ]
keyword[else] :
... | async def delete(self, request, resource=None, **kwargs):
"""Delete a resource.
Supports batch delete.
"""
if resource:
resources = [resource] # depends on [control=['if'], data=[]]
else:
data = await self.parse(request)
if data:
resources = list(self.co... |
def set_address(self, address):
"""
Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param ad... | def function[set_address, parameter[self, address]]:
constant[
Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type addres... | keyword[def] identifier[set_address] ( identifier[self] , identifier[address] ):
literal[string]
keyword[if] identifier[is_ip] ( identifier[address] ):
identifier[self] . identifier[address] = identifier[clean_ip] ( identifier[address] )
keyword[else] :
identifie... | def set_address(self, address):
"""
Set the address of the remote host the is contacted, without
changing hostname, username, password, protocol, and TCP port
number.
This is the actual address that is used to open the connection.
:type address: string
:param addres... |
def _get_parsed_args(command_name, doc, argv):
# type: (str, str, typing.List[str]) -> typing.Dict[str, typing.Any]
"""Parse the docstring with docopt.
Args:
command_name: The name of the subcommand to parse.
doc: A docopt-parseable string.
argv: The list of arguments to pass to doc... | def function[_get_parsed_args, parameter[command_name, doc, argv]]:
constant[Parse the docstring with docopt.
Args:
command_name: The name of the subcommand to parse.
doc: A docopt-parseable string.
argv: The list of arguments to pass to docopt during parsing.
Returns:
... | keyword[def] identifier[_get_parsed_args] ( identifier[command_name] , identifier[doc] , identifier[argv] ):
literal[string]
identifier[_LOGGER] . identifier[debug] ( literal[string] , identifier[doc] , identifier[argv] )
identifier[args] = identifier[docopt] ( identifier[doc] , identifier[argv] = id... | def _get_parsed_args(command_name, doc, argv):
# type: (str, str, typing.List[str]) -> typing.Dict[str, typing.Any]
'Parse the docstring with docopt.\n\n Args:\n command_name: The name of the subcommand to parse.\n doc: A docopt-parseable string.\n argv: The list of arguments to pass to ... |
def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
... | def function[getCiphertextLen, parameter[self, ciphertext]]:
constant[Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
]
variable[plaintext_length] assign[=] call[name[self].getPlaintextLen, parameter[name[ciphertext]]]
v... | keyword[def] identifier[getCiphertextLen] ( identifier[self] , identifier[ciphertext] ):
literal[string]
identifier[plaintext_length] = identifier[self] . identifier[getPlaintextLen] ( identifier[ciphertext] )
identifier[ciphertext_length] = identifier[plaintext_length] + identifier[Encry... | def getCiphertextLen(self, ciphertext):
"""Given a ``ciphertext`` with a valid header, returns the length of the ciphertext inclusive of ciphertext expansion.
"""
plaintext_length = self.getPlaintextLen(ciphertext)
ciphertext_length = plaintext_length + Encrypter._CTXT_EXPANSION
return ciphertex... |
def get_info(df, group, info=['mean', 'std']):
"""
Aggregate mean and std with the given group.
"""
agg = df.groupby(group).agg(info)
agg.columns = agg.columns.droplevel(0)
return agg | def function[get_info, parameter[df, group, info]]:
constant[
Aggregate mean and std with the given group.
]
variable[agg] assign[=] call[call[name[df].groupby, parameter[name[group]]].agg, parameter[name[info]]]
name[agg].columns assign[=] call[name[agg].columns.droplevel, parameter[con... | keyword[def] identifier[get_info] ( identifier[df] , identifier[group] , identifier[info] =[ literal[string] , literal[string] ]):
literal[string]
identifier[agg] = identifier[df] . identifier[groupby] ( identifier[group] ). identifier[agg] ( identifier[info] )
identifier[agg] . identifier[columns] = ... | def get_info(df, group, info=['mean', 'std']):
"""
Aggregate mean and std with the given group.
"""
agg = df.groupby(group).agg(info)
agg.columns = agg.columns.droplevel(0)
return agg |
def plot(
self,
ax=None,
title=None,
figsize=None,
with_candidates=False,
candidate_alpha=None,
temp_range=None,
):
""" Plot a model fit.
Parameters
----------
ax : :any:`matplotlib.axes.Axes`, optional
Existing axe... | def function[plot, parameter[self, ax, title, figsize, with_candidates, candidate_alpha, temp_range]]:
constant[ Plot a model fit.
Parameters
----------
ax : :any:`matplotlib.axes.Axes`, optional
Existing axes to plot on.
title : :any:`str`, optional
Char... | keyword[def] identifier[plot] (
identifier[self] ,
identifier[ax] = keyword[None] ,
identifier[title] = keyword[None] ,
identifier[figsize] = keyword[None] ,
identifier[with_candidates] = keyword[False] ,
identifier[candidate_alpha] = keyword[None] ,
identifier[temp_range] = keyword[None] ,
):
literal... | def plot(self, ax=None, title=None, figsize=None, with_candidates=False, candidate_alpha=None, temp_range=None):
""" Plot a model fit.
Parameters
----------
ax : :any:`matplotlib.axes.Axes`, optional
Existing axes to plot on.
title : :any:`str`, optional
Char... |
def patch_cluster_custom_object_scale(self, group, version, plural, name, body, **kwargs): # noqa: E501
"""patch_cluster_custom_object_scale # noqa: E501
partially update scale of the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by default.... | def function[patch_cluster_custom_object_scale, parameter[self, group, version, plural, name, body]]:
constant[patch_cluster_custom_object_scale # noqa: E501
partially update scale of the specified cluster scoped custom object # noqa: E501
This method makes a synchronous HTTP request by defau... | keyword[def] identifier[patch_cluster_custom_object_scale] ( identifier[self] , identifier[group] , identifier[version] , identifier[plural] , identifier[name] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] i... | def patch_cluster_custom_object_scale(self, group, version, plural, name, body, **kwargs): # noqa: E501
"patch_cluster_custom_object_scale # noqa: E501\n\n partially update scale of the specified cluster scoped custom object # noqa: E501\n This method makes a synchronous HTTP request by default. To... |
def has_u_umlaut(word: str) -> bool:
"""
Does the word have an u-umlaut?
>>> has_u_umlaut("höfn")
True
>>> has_u_umlaut("börnum")
True
>>> has_u_umlaut("barn")
False
:param word: Old Norse word
:return: has an u-umlaut occurred?
"""
word_syl = s.syllabify_ssp(word)
... | def function[has_u_umlaut, parameter[word]]:
constant[
Does the word have an u-umlaut?
>>> has_u_umlaut("höfn")
True
>>> has_u_umlaut("börnum")
True
>>> has_u_umlaut("barn")
False
:param word: Old Norse word
:return: has an u-umlaut occurred?
]
variable[word_s... | keyword[def] identifier[has_u_umlaut] ( identifier[word] : identifier[str] )-> identifier[bool] :
literal[string]
identifier[word_syl] = identifier[s] . identifier[syllabify_ssp] ( identifier[word] )
identifier[s_word_syl] =[ identifier[Syllable] ( identifier[syl] , identifier[VOWELS] , identifier[CON... | def has_u_umlaut(word: str) -> bool:
"""
Does the word have an u-umlaut?
>>> has_u_umlaut("höfn")
True
>>> has_u_umlaut("börnum")
True
>>> has_u_umlaut("barn")
False
:param word: Old Norse word
:return: has an u-umlaut occurred?
"""
word_syl = s.syllabify_ssp(word)
... |
def _set_label(label, mark, dim, **kwargs):
"""Helper function to set labels for an axis
"""
if mark is None:
mark = _context['last_mark']
if mark is None:
return {}
fig = kwargs.get('figure', current_figure())
scales = mark.scales
scale_metadata = mark.scales_metadata.get(di... | def function[_set_label, parameter[label, mark, dim]]:
constant[Helper function to set labels for an axis
]
if compare[name[mark] is constant[None]] begin[:]
variable[mark] assign[=] call[name[_context]][constant[last_mark]]
if compare[name[mark] is constant[None]] begin[:]
... | keyword[def] identifier[_set_label] ( identifier[label] , identifier[mark] , identifier[dim] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[mark] keyword[is] keyword[None] :
identifier[mark] = identifier[_context] [ literal[string] ]
keyword[if] identifier[mark] keyword... | def _set_label(label, mark, dim, **kwargs):
"""Helper function to set labels for an axis
"""
if mark is None:
mark = _context['last_mark'] # depends on [control=['if'], data=['mark']]
if mark is None:
return {} # depends on [control=['if'], data=[]]
fig = kwargs.get('figure', curre... |
def _transfer_data(self, remote_path, data):
"""
Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others.
"""
if isinstance(data, dict):
data = jsonify(data)
if not isinstance(data, bytes):
data = to_... | def function[_transfer_data, parameter[self, remote_path, data]]:
constant[
Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others.
]
if call[name[isinstance], parameter[name[data], name[dict]]] begin[:]
variable[da... | keyword[def] identifier[_transfer_data] ( identifier[self] , identifier[remote_path] , identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ):
identifier[data] = identifier[jsonify] ( identifier[data] )
keyword[if] keyw... | def _transfer_data(self, remote_path, data):
"""
Used by the base _execute_module(), and in <2.4 also by the template
action module, and probably others.
"""
if isinstance(data, dict):
data = jsonify(data) # depends on [control=['if'], data=[]]
if not isinstance(data, bytes)... |
def run_hooks(self, packet):
"""
Run any additional functions that want to process this type of packet.
These can be internal parser hooks, or external hooks that process
information
"""
if packet.__class__ in self.internal_hooks:
self.internal_hooks[packet._... | def function[run_hooks, parameter[self, packet]]:
constant[
Run any additional functions that want to process this type of packet.
These can be internal parser hooks, or external hooks that process
information
]
if compare[name[packet].__class__ in name[self].internal_hoo... | keyword[def] identifier[run_hooks] ( identifier[self] , identifier[packet] ):
literal[string]
keyword[if] identifier[packet] . identifier[__class__] keyword[in] identifier[self] . identifier[internal_hooks] :
identifier[self] . identifier[internal_hooks] [ identifier[packet] . iden... | def run_hooks(self, packet):
"""
Run any additional functions that want to process this type of packet.
These can be internal parser hooks, or external hooks that process
information
"""
if packet.__class__ in self.internal_hooks:
self.internal_hooks[packet.__class__](pac... |
def validate(self):
"""
Validate the headers and body with the message schema, if any.
In addition to the user-provided schema, all messages are checked against
the base schema which requires certain message headers and the that body
be a JSON object.
.. warning:: This ... | def function[validate, parameter[self]]:
constant[
Validate the headers and body with the message schema, if any.
In addition to the user-provided schema, all messages are checked against
the base schema which requires certain message headers and the that body
be a JSON object.
... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
keyword[for] identifier[schema] keyword[in] ( identifier[self] . identifier[headers_schema] , identifier[Message] . identifier[headers_schema] ):
identifier[_log] . identifier[debug] (
literal[string... | def validate(self):
"""
Validate the headers and body with the message schema, if any.
In addition to the user-provided schema, all messages are checked against
the base schema which requires certain message headers and the that body
be a JSON object.
.. warning:: This meth... |
def newkeys(nbits=1024):
"""
Create a new pair of public and private key pair to use.
"""
pubkey, privkey = rsa.newkeys(nbits, poolsize=1)
return pubkey, privkey | def function[newkeys, parameter[nbits]]:
constant[
Create a new pair of public and private key pair to use.
]
<ast.Tuple object at 0x7da1b15f5030> assign[=] call[name[rsa].newkeys, parameter[name[nbits]]]
return[tuple[[<ast.Name object at 0x7da1b15f6f50>, <ast.Name object at 0x7da1b1... | keyword[def] identifier[newkeys] ( identifier[nbits] = literal[int] ):
literal[string]
identifier[pubkey] , identifier[privkey] = identifier[rsa] . identifier[newkeys] ( identifier[nbits] , identifier[poolsize] = literal[int] )
keyword[return] identifier[pubkey] , identifier[privkey] | def newkeys(nbits=1024):
"""
Create a new pair of public and private key pair to use.
"""
(pubkey, privkey) = rsa.newkeys(nbits, poolsize=1)
return (pubkey, privkey) |
def parse_stdout(self, filelike):
"""Parse the formulae from the content written by the script to standard out.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
"""
from aiida.orm import Dict
formulae = {}
con... | def function[parse_stdout, parameter[self, filelike]]:
constant[Parse the formulae from the content written by the script to standard out.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
]
from relative_module[aiida.orm] import m... | keyword[def] identifier[parse_stdout] ( identifier[self] , identifier[filelike] ):
literal[string]
keyword[from] identifier[aiida] . identifier[orm] keyword[import] identifier[Dict]
identifier[formulae] ={}
identifier[content] = identifier[filelike] . identifier[read] (). ide... | def parse_stdout(self, filelike):
"""Parse the formulae from the content written by the script to standard out.
:param filelike: filelike object of stdout
:returns: an exit code in case of an error, None otherwise
"""
from aiida.orm import Dict
formulae = {}
content = filelike.r... |
def stream(
self,
accountID,
**kwargs
):
"""
Get a stream of Transactions for an Account starting from when the
request is made.
Args:
accountID:
Account Identifier
Returns:
v20.response.Response containing the... | def function[stream, parameter[self, accountID]]:
constant[
Get a stream of Transactions for an Account starting from when the
request is made.
Args:
accountID:
Account Identifier
Returns:
v20.response.Response containing the results from... | keyword[def] identifier[stream] (
identifier[self] ,
identifier[accountID] ,
** identifier[kwargs]
):
literal[string]
identifier[request] = identifier[Request] (
literal[string] ,
literal[string]
)
identifier[request] . identifier[set_path_param] (
... | def stream(self, accountID, **kwargs):
"""
Get a stream of Transactions for an Account starting from when the
request is made.
Args:
accountID:
Account Identifier
Returns:
v20.response.Response containing the results from submitting the
... |
def _stash_user(cls, user):
"""Now, be aware, the following is quite ugly, let me explain:
Even if the user credentials match, the authentication can fail because
Django's default ModelBackend calls user_can_authenticate(), which
checks `is_active`. Now, earlier versions of allauth did ... | def function[_stash_user, parameter[cls, user]]:
constant[Now, be aware, the following is quite ugly, let me explain:
Even if the user credentials match, the authentication can fail because
Django's default ModelBackend calls user_can_authenticate(), which
checks `is_active`. Now, earli... | keyword[def] identifier[_stash_user] ( identifier[cls] , identifier[user] ):
literal[string]
keyword[global] identifier[_stash]
identifier[ret] = identifier[getattr] ( identifier[_stash] , literal[string] , keyword[None] )
identifier[_stash] . identifier[user] = identifier[user]... | def _stash_user(cls, user):
"""Now, be aware, the following is quite ugly, let me explain:
Even if the user credentials match, the authentication can fail because
Django's default ModelBackend calls user_can_authenticate(), which
checks `is_active`. Now, earlier versions of allauth did not ... |
def paintEvent(self, event):
"""
Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
:type event: QEvent
"""
super(type(self), self).paintEvent(event)
show_message = True
model = self.model()
if issubclass(type(model), GraphModel... | def function[paintEvent, parameter[self, event]]:
constant[
Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
:type event: QEvent
]
call[call[name[super], parameter[call[name[type], parameter[name[self]]], name[self]]].paintEvent, parameter[name[event]]... | keyword[def] identifier[paintEvent] ( identifier[self] , identifier[event] ):
literal[string]
identifier[super] ( identifier[type] ( identifier[self] ), identifier[self] ). identifier[paintEvent] ( identifier[event] )
identifier[show_message] = keyword[True]
identifier[model] =... | def paintEvent(self, event):
"""
Reimplements the :meth:`*.paintEvent` method.
:param event: QEvent.
:type event: QEvent
"""
super(type(self), self).paintEvent(event)
show_message = True
model = self.model()
if issubclass(type(model), GraphModel):
if model.ha... |
def patch_namespaced_resource_quota_status(self, name, namespace, body, **kwargs): # noqa: E501
"""patch_namespaced_resource_quota_status # noqa: E501
partially update status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | def function[patch_namespaced_resource_quota_status, parameter[self, name, namespace, body]]:
constant[patch_namespaced_resource_quota_status # noqa: E501
partially update status of the specified ResourceQuota # noqa: E501
This method makes a synchronous HTTP request by default. To make an
... | keyword[def] identifier[patch_namespaced_resource_quota_status] ( identifier[self] , identifier[name] , identifier[namespace] , identifier[body] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs] [ literal[string] ]= keyword[True]
keyword[if] identifier[kwargs] . identifier[get... | def patch_namespaced_resource_quota_status(self, name, namespace, body, **kwargs): # noqa: E501
"patch_namespaced_resource_quota_status # noqa: E501\n\n partially update status of the specified ResourceQuota # noqa: E501\n This method makes a synchronous HTTP request by default. To make an\n ... |
def process_docstring(app, what, name, obj, options, lines):
"""Enable markdown syntax in docstrings"""
markdown = "\n".join(lines)
# ast = cm_parser.parse(markdown)
# html = cm_renderer.render(ast)
rest = m2r(markdown)
rest.replace("\r\n", "\n")
del lines[:]
lines.extend(rest.spl... | def function[process_docstring, parameter[app, what, name, obj, options, lines]]:
constant[Enable markdown syntax in docstrings]
variable[markdown] assign[=] call[constant[
].join, parameter[name[lines]]]
variable[rest] assign[=] call[name[m2r], parameter[name[markdown]]]
call[name[rest]... | keyword[def] identifier[process_docstring] ( identifier[app] , identifier[what] , identifier[name] , identifier[obj] , identifier[options] , identifier[lines] ):
literal[string]
identifier[markdown] = literal[string] . identifier[join] ( identifier[lines] )
identifier[rest] = identifier[m2... | def process_docstring(app, what, name, obj, options, lines):
"""Enable markdown syntax in docstrings"""
markdown = '\n'.join(lines)
# ast = cm_parser.parse(markdown)
# html = cm_renderer.render(ast)
rest = m2r(markdown)
rest.replace('\r\n', '\n')
del lines[:]
lines.extend(rest.split('\n'... |
def format_dateaxis(subplot, freq, index):
"""
Pretty-formats the date axis (x-axis).
Major and minor ticks are automatically set for the frequency of the
current underlying series. As the dynamic mode is activated by
default, changing the limits of the x axis will intelligently change
the pos... | def function[format_dateaxis, parameter[subplot, freq, index]]:
constant[
Pretty-formats the date axis (x-axis).
Major and minor ticks are automatically set for the frequency of the
current underlying series. As the dynamic mode is activated by
default, changing the limits of the x axis will i... | keyword[def] identifier[format_dateaxis] ( identifier[subplot] , identifier[freq] , identifier[index] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[index] , identifier[ABCPeriodIndex] ):
identifier[majlocator] = identifier[TimeSeries_DateLocator] ( identifier... | def format_dateaxis(subplot, freq, index):
"""
Pretty-formats the date axis (x-axis).
Major and minor ticks are automatically set for the frequency of the
current underlying series. As the dynamic mode is activated by
default, changing the limits of the x axis will intelligently change
the pos... |
def digest_manifest(self, manifest, java_algorithm="SHA-256"):
"""
Create a main section checksum and sub-section checksums based off
of the data from an existing manifest using an algorithm given
by Java-style name.
"""
# pick a line separator for creating checksums of ... | def function[digest_manifest, parameter[self, manifest, java_algorithm]]:
constant[
Create a main section checksum and sub-section checksums based off
of the data from an existing manifest using an algorithm given
by Java-style name.
]
variable[linesep] assign[=] <ast.Boo... | keyword[def] identifier[digest_manifest] ( identifier[self] , identifier[manifest] , identifier[java_algorithm] = literal[string] ):
literal[string]
identifier[linesep] = identifier[manifest] . identifier[linesep] keyword[or] identifier[os] . identifier[linesep]
... | def digest_manifest(self, manifest, java_algorithm='SHA-256'):
"""
Create a main section checksum and sub-section checksums based off
of the data from an existing manifest using an algorithm given
by Java-style name.
"""
# pick a line separator for creating checksums of the manif... |
def zscore(self, weighted=True, prune=False, hs_dims=None):
"""Return ndarray with slices's standardized residuals (Z-scores).
(Only applicable to a 2D contingency tables.) The Z-score or
standardized residual is the difference between observed and expected
cell counts if row and column... | def function[zscore, parameter[self, weighted, prune, hs_dims]]:
constant[Return ndarray with slices's standardized residuals (Z-scores).
(Only applicable to a 2D contingency tables.) The Z-score or
standardized residual is the difference between observed and expected
cell counts if row... | keyword[def] identifier[zscore] ( identifier[self] , identifier[weighted] = keyword[True] , identifier[prune] = keyword[False] , identifier[hs_dims] = keyword[None] ):
literal[string]
identifier[counts] = identifier[self] . identifier[as_array] ( identifier[weighted] = identifier[weighted] )
... | def zscore(self, weighted=True, prune=False, hs_dims=None):
"""Return ndarray with slices's standardized residuals (Z-scores).
(Only applicable to a 2D contingency tables.) The Z-score or
standardized residual is the difference between observed and expected
cell counts if row and column var... |
def updateConfig(self, eleobj, config, type='simu'):
""" write new configuration to element
:param eleobj: define element object
:param config: new configuration for element, string or dict
:param type: 'simu' by default, could be online, misc, comm, ctrl
"""
... | def function[updateConfig, parameter[self, eleobj, config, type]]:
constant[ write new configuration to element
:param eleobj: define element object
:param config: new configuration for element, string or dict
:param type: 'simu' by default, could be online, misc, comm, ctrl... | keyword[def] identifier[updateConfig] ( identifier[self] , identifier[eleobj] , identifier[config] , identifier[type] = literal[string] ):
literal[string]
identifier[eleobj] . identifier[setConf] ( identifier[config] , identifier[type] = identifier[type] ) | def updateConfig(self, eleobj, config, type='simu'):
""" write new configuration to element
:param eleobj: define element object
:param config: new configuration for element, string or dict
:param type: 'simu' by default, could be online, misc, comm, ctrl
"""
eleobj.... |
def list(self, limit=None, offset=None):
"""Gets a list of all domains, or optionally a page of domains."""
uri = "/%s%s" % (self.uri_base, self._get_pagination_qs(limit, offset))
return self._list(uri) | def function[list, parameter[self, limit, offset]]:
constant[Gets a list of all domains, or optionally a page of domains.]
variable[uri] assign[=] binary_operation[constant[/%s%s] <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b0558190>, <ast.Call object at 0x7da1b0559060>]]]
... | keyword[def] identifier[list] ( identifier[self] , identifier[limit] = keyword[None] , identifier[offset] = keyword[None] ):
literal[string]
identifier[uri] = literal[string] %( identifier[self] . identifier[uri_base] , identifier[self] . identifier[_get_pagination_qs] ( identifier[limit] , identif... | def list(self, limit=None, offset=None):
"""Gets a list of all domains, or optionally a page of domains."""
uri = '/%s%s' % (self.uri_base, self._get_pagination_qs(limit, offset))
return self._list(uri) |
def _fill_scalar_list_of(xmldoc, element_type, parent_xml_element_name,
xml_element_name):
'''Converts an xml fragment into a list of scalar types. The parent xml
element contains a flat list of xml elements which are converted into the
specified scalar type and add... | def function[_fill_scalar_list_of, parameter[xmldoc, element_type, parent_xml_element_name, xml_element_name]]:
constant[Converts an xml fragment into a list of scalar types. The parent xml
element contains a flat list of xml elements which are converted into the
specified scalar type and added... | keyword[def] identifier[_fill_scalar_list_of] ( identifier[xmldoc] , identifier[element_type] , identifier[parent_xml_element_name] ,
identifier[xml_element_name] ):
literal[string]
identifier[xmlelements] = identifier[_MinidomXmlToObject] . identifier[get_child_nodes] ( identifier[xmldoc] , ident... | def _fill_scalar_list_of(xmldoc, element_type, parent_xml_element_name, xml_element_name):
"""Converts an xml fragment into a list of scalar types. The parent xml
element contains a flat list of xml elements which are converted into the
specified scalar type and added to the list.
Example:
... |
def build_namespace(self):
"""Build out the directory skeleton and python namespace files:
dbt/
__init__.py
adapters/
${adapter_name}
__init__.py
include/
${adapter_name}
... | def function[build_namespace, parameter[self]]:
constant[Build out the directory skeleton and python namespace files:
dbt/
__init__.py
adapters/
${adapter_name}
__init__.py
include/
${adapter... | keyword[def] identifier[build_namespace] ( identifier[self] ):
literal[string]
identifier[os] . identifier[makedirs] ( identifier[self] . identifier[adapters_path] )
identifier[os] . identifier[makedirs] ( identifier[pj] ( identifier[self] . identifier[include_path] , literal[string] ))
... | def build_namespace(self):
"""Build out the directory skeleton and python namespace files:
dbt/
__init__.py
adapters/
${adapter_name}
__init__.py
include/
${adapter_name}
__in... |
def logging_levels(name, remote=None, local=None):
'''
Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module f... | def function[logging_levels, parameter[name, remote, local]]:
constant[
Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The... | keyword[def] identifier[logging_levels] ( identifier[name] , identifier[remote] = keyword[None] , identifier[local] = keyword[None] ):
literal[string]
identifier[ret] = identifier[_default_ret] ( identifier[name] )
identifier[syslog_conf] = identifier[__salt__] [ literal[string] ]()
identifier... | def logging_levels(name, remote=None, local=None):
"""
Ensures that the logging levels are set on the device. The logging levels
must match the following options: emergency, alert, critical, error, warning,
notice, informational, debug.
.. versionadded:: 2019.2.0
name: The name of the module f... |
def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
... | def function[rgb2short, parameter[rgb]]:
constant[ Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('... | keyword[def] identifier[rgb2short] ( identifier[rgb] ):
literal[string]
identifier[incs] =( literal[int] , literal[int] , literal[int] , literal[int] , literal[int] , literal[int] )
identifier[parts] =[ identifier[int] ( identifier[h] , literal[int] ) keyword[for] identifier[h] keyword[in] ide... | def rgb2short(rgb):
""" Find the closest xterm-256 approximation to the given RGB value.
@param rgb: Hex code representing an RGB value, eg, 'abcdef'
@returns: String between 0 and 255, compatible with xterm.
>>> rgb2short('123456')
('23', '005f5f')
>>> rgb2short('ffffff')
('231', 'ffffff')
... |
def complete(self):
"""
Complete current task
:return:
:rtype: requests.models.Response
"""
return self._post_request(
data='',
endpoint=self.ENDPOINT + '/' + str(self.id) + '/complete'
) | def function[complete, parameter[self]]:
constant[
Complete current task
:return:
:rtype: requests.models.Response
]
return[call[name[self]._post_request, parameter[]]] | keyword[def] identifier[complete] ( identifier[self] ):
literal[string]
keyword[return] identifier[self] . identifier[_post_request] (
identifier[data] = literal[string] ,
identifier[endpoint] = identifier[self] . identifier[ENDPOINT] + literal[string] + identifier[str] ( identif... | def complete(self):
"""
Complete current task
:return:
:rtype: requests.models.Response
"""
return self._post_request(data='', endpoint=self.ENDPOINT + '/' + str(self.id) + '/complete') |
def worker_pids(cls):
"""Returns an array of all pids (as strings) of the workers on
this machine. Used when pruning dead workers."""
cmd = "ps -A -o pid,command | grep pyres_worker | grep -v grep"
output = commands.getoutput(cmd)
if output:
return map(lambda l: l.st... | def function[worker_pids, parameter[cls]]:
constant[Returns an array of all pids (as strings) of the workers on
this machine. Used when pruning dead workers.]
variable[cmd] assign[=] constant[ps -A -o pid,command | grep pyres_worker | grep -v grep]
variable[output] assign[=] call[name[c... | keyword[def] identifier[worker_pids] ( identifier[cls] ):
literal[string]
identifier[cmd] = literal[string]
identifier[output] = identifier[commands] . identifier[getoutput] ( identifier[cmd] )
keyword[if] identifier[output] :
keyword[return] identifier[map] ( keyw... | def worker_pids(cls):
"""Returns an array of all pids (as strings) of the workers on
this machine. Used when pruning dead workers."""
cmd = 'ps -A -o pid,command | grep pyres_worker | grep -v grep'
output = commands.getoutput(cmd)
if output:
return map(lambda l: l.strip().split(' ')[0],... |
def nas_auto_qos_set_dscp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
nas = ET.SubElement(config, "nas", xmlns="urn:brocade.com:mgmt:brocade-qos")
auto_qos = ET.SubElement(nas, "auto-qos")
set = ET.SubElement(auto_qos, "set")
dscp = E... | def function[nas_auto_qos_set_dscp, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[nas] assign[=] call[name[ET].SubElement, parameter[name[config], constant[nas]]]
variable[auto_qos] assign[... | keyword[def] identifier[nas_auto_qos_set_dscp] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[nas] = identifier[ET] . identifier[SubElement] ( identifier[config] , literal[string] , ident... | def nas_auto_qos_set_dscp(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
nas = ET.SubElement(config, 'nas', xmlns='urn:brocade.com:mgmt:brocade-qos')
auto_qos = ET.SubElement(nas, 'auto-qos')
set = ET.SubElement(auto_qos, 'set')
dscp = ET.SubElement(set, 'dscp'... |
def _apply_color(code, content):
"""
Apply a color code to text
"""
normal = u'\x1B[0m'
seq = u'\x1B[%sm' % code
# Replace any normal sequences with this sequence to support nested colors
return seq + (normal + seq).join(content.split(normal)) + normal | def function[_apply_color, parameter[code, content]]:
constant[
Apply a color code to text
]
variable[normal] assign[=] constant[[0m]
variable[seq] assign[=] binary_operation[constant[[%sm] <ast.Mod object at 0x7da2590d6920> name[code]]
return[binary_operation[binary_operat... | keyword[def] identifier[_apply_color] ( identifier[code] , identifier[content] ):
literal[string]
identifier[normal] = literal[string]
identifier[seq] = literal[string] % identifier[code]
keyword[return] identifier[seq] +( identifier[normal] + identifier[seq] ). iden... | def _apply_color(code, content):
"""
Apply a color code to text
"""
normal = u'\x1b[0m'
seq = u'\x1b[%sm' % code
# Replace any normal sequences with this sequence to support nested colors
return seq + (normal + seq).join(content.split(normal)) + normal |
def _set_mac_address(self, v, load=False):
"""
Setter method for mac_address, mapped from YANG variable /bridge_domain/mac_address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address is considered as a private
method. Backends looking to populate ... | def function[_set_mac_address, parameter[self, v, load]]:
constant[
Setter method for mac_address, mapped from YANG variable /bridge_domain/mac_address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address is considered as a private
method. Back... | keyword[def] identifier[_set_mac_address] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
id... | def _set_mac_address(self, v, load=False):
"""
Setter method for mac_address, mapped from YANG variable /bridge_domain/mac_address (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_mac_address is considered as a private
method. Backends looking to populate ... |
def group_info(name, expand=False):
'''
.. versionadded:: 2014.1.0
.. versionchanged:: 2016.3.0,2015.8.4,2015.5.10
The return data has changed. A new key ``type`` has been added to
distinguish environment groups from package groups. Also, keys for the
group name and group ID have bee... | def function[group_info, parameter[name, expand]]:
constant[
.. versionadded:: 2014.1.0
.. versionchanged:: 2016.3.0,2015.8.4,2015.5.10
The return data has changed. A new key ``type`` has been added to
distinguish environment groups from package groups. Also, keys for the
group n... | keyword[def] identifier[group_info] ( identifier[name] , identifier[expand] = keyword[False] ):
literal[string]
identifier[pkgtypes] =( literal[string] , literal[string] , literal[string] , literal[string] )
identifier[ret] ={}
keyword[for] identifier[pkgtype] keyword[in] identifier[pkgtypes] ... | def group_info(name, expand=False):
"""
.. versionadded:: 2014.1.0
.. versionchanged:: 2016.3.0,2015.8.4,2015.5.10
The return data has changed. A new key ``type`` has been added to
distinguish environment groups from package groups. Also, keys for the
group name and group ID have bee... |
def DbGetAliasDevice(self, argin):
""" Get device name from its alias.
:param argin: Alias name
:type: tango.DevString
:return: Device name
:rtype: tango.DevString """
self._log.debug("In DbGetAliasDevice()")
if not argin:
argin = "%"
else:
... | def function[DbGetAliasDevice, parameter[self, argin]]:
constant[ Get device name from its alias.
:param argin: Alias name
:type: tango.DevString
:return: Device name
:rtype: tango.DevString ]
call[name[self]._log.debug, parameter[constant[In DbGetAliasDevice()]]]
... | keyword[def] identifier[DbGetAliasDevice] ( identifier[self] , identifier[argin] ):
literal[string]
identifier[self] . identifier[_log] . identifier[debug] ( literal[string] )
keyword[if] keyword[not] identifier[argin] :
identifier[argin] = literal[string]
keyword[... | def DbGetAliasDevice(self, argin):
""" Get device name from its alias.
:param argin: Alias name
:type: tango.DevString
:return: Device name
:rtype: tango.DevString """
self._log.debug('In DbGetAliasDevice()')
if not argin:
argin = '%' # depends on [control=['if'], d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.