code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def set_ports(self, port0 = 0x00, port1 = 0x00):
'Writes specified value to the pins defined as output by method. Writing to input pins has no effect.'
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0)
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1)
retu... | def function[set_ports, parameter[self, port0, port1]]:
constant[Writes specified value to the pins defined as output by method. Writing to input pins has no effect.]
call[name[self].bus.write_byte_data, parameter[name[self].address, name[self].CONTROL_PORT0, name[port0]]]
call[name[self].bus.wr... | keyword[def] identifier[set_ports] ( identifier[self] , identifier[port0] = literal[int] , identifier[port1] = literal[int] ):
literal[string]
identifier[self] . identifier[bus] . identifier[write_byte_data] ( identifier[self] . identifier[address] , identifier[self] . identifier[CONTROL_PORT0] , i... | def set_ports(self, port0=0, port1=0):
"""Writes specified value to the pins defined as output by method. Writing to input pins has no effect."""
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port0)
self.bus.write_byte_data(self.address, self.CONTROL_PORT0, port1)
return |
def init_app(self, app):
"""Initialize a :class:`~flask.Flask` application for use with
this extension.
"""
self._jobs = []
if not hasattr(app, 'extensions'):
app.extensions = {}
app.extensions['restpoints'] = self
app.restpoints_instance = self
... | def function[init_app, parameter[self, app]]:
constant[Initialize a :class:`~flask.Flask` application for use with
this extension.
]
name[self]._jobs assign[=] list[[]]
if <ast.UnaryOp object at 0x7da1afe8b4f0> begin[:]
name[app].extensions assign[=] dictionary[[]... | keyword[def] identifier[init_app] ( identifier[self] , identifier[app] ):
literal[string]
identifier[self] . identifier[_jobs] =[]
keyword[if] keyword[not] identifier[hasattr] ( identifier[app] , literal[string] ):
identifier[app] . identifier[extensions] ={}
iden... | def init_app(self, app):
"""Initialize a :class:`~flask.Flask` application for use with
this extension.
"""
self._jobs = []
if not hasattr(app, 'extensions'):
app.extensions = {} # depends on [control=['if'], data=[]]
app.extensions['restpoints'] = self
app.restpoints_instan... |
def load_results(root_dir_or_dirs, enable_progress=True, enable_monitor=True, verbose=False):
'''
load summaries of runs from a list of directories (including subdirectories)
Arguments:
enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logger). Default: T... | def function[load_results, parameter[root_dir_or_dirs, enable_progress, enable_monitor, verbose]]:
constant[
load summaries of runs from a list of directories (including subdirectories)
Arguments:
enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logg... | keyword[def] identifier[load_results] ( identifier[root_dir_or_dirs] , identifier[enable_progress] = keyword[True] , identifier[enable_monitor] = keyword[True] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[import] identifier[re]
keyword[if] identifier[isinstance] ( identifier[ro... | def load_results(root_dir_or_dirs, enable_progress=True, enable_monitor=True, verbose=False):
"""
load summaries of runs from a list of directories (including subdirectories)
Arguments:
enable_progress: bool - if True, will attempt to load data from progress.csv files (data saved by logger). Default: T... |
def interpolate_P(self, T, P, name):
r'''Method to perform interpolation on a given tabular data set
previously added via `set_tabular_data_P`. This method will create the
interpolators the first time it is used on a property set, and store
them for quick future use.
Interpolati... | def function[interpolate_P, parameter[self, T, P, name]]:
constant[Method to perform interpolation on a given tabular data set
previously added via `set_tabular_data_P`. This method will create the
interpolators the first time it is used on a property set, and store
them for quick future... | keyword[def] identifier[interpolate_P] ( identifier[self] , identifier[T] , identifier[P] , identifier[name] ):
literal[string]
identifier[key] =( identifier[name] , identifier[self] . identifier[interpolation_T] , identifier[self] . identifier[interpolation_P] , identifier[self] . identifier[inter... | def interpolate_P(self, T, P, name):
"""Method to perform interpolation on a given tabular data set
previously added via `set_tabular_data_P`. This method will create the
interpolators the first time it is used on a property set, and store
them for quick future use.
Interpolation is... |
def executor(self, max_workers=1):
"""single global executor"""
cls = self.__class__
if cls._executor is None:
cls._executor = ThreadPoolExecutor(max_workers)
return cls._executor | def function[executor, parameter[self, max_workers]]:
constant[single global executor]
variable[cls] assign[=] name[self].__class__
if compare[name[cls]._executor is constant[None]] begin[:]
name[cls]._executor assign[=] call[name[ThreadPoolExecutor], parameter[name[max_workers]]... | keyword[def] identifier[executor] ( identifier[self] , identifier[max_workers] = literal[int] ):
literal[string]
identifier[cls] = identifier[self] . identifier[__class__]
keyword[if] identifier[cls] . identifier[_executor] keyword[is] keyword[None] :
identifier[cls] . ide... | def executor(self, max_workers=1):
"""single global executor"""
cls = self.__class__
if cls._executor is None:
cls._executor = ThreadPoolExecutor(max_workers) # depends on [control=['if'], data=[]]
return cls._executor |
def geometry_range(crd_range, elev, crd_type):
"""
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict:
"""
d = OrderedDict(... | def function[geometry_range, parameter[crd_range, elev, crd_type]]:
constant[
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict... | keyword[def] identifier[geometry_range] ( identifier[crd_range] , identifier[elev] , identifier[crd_type] ):
literal[string]
identifier[d] = identifier[OrderedDict] ()
identifier[coordinates] =[[] keyword[for] identifier[i] keyword[in] identifier[range] ( identifier[len] ( identifier[crd_range] ))... | def geometry_range(crd_range, elev, crd_type):
"""
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict:
"""
d = OrderedDict()... |
def recompute_tabs_titles(self):
"""Updates labels on all tabs. This is required when `self.abbreviate`
changes
"""
use_vte_titles = self.settings.general.get_boolean("use-vte-titles")
if not use_vte_titles:
return
# TODO NOTEBOOK this code only works if ther... | def function[recompute_tabs_titles, parameter[self]]:
constant[Updates labels on all tabs. This is required when `self.abbreviate`
changes
]
variable[use_vte_titles] assign[=] call[name[self].settings.general.get_boolean, parameter[constant[use-vte-titles]]]
if <ast.UnaryOp objec... | keyword[def] identifier[recompute_tabs_titles] ( identifier[self] ):
literal[string]
identifier[use_vte_titles] = identifier[self] . identifier[settings] . identifier[general] . identifier[get_boolean] ( literal[string] )
keyword[if] keyword[not] identifier[use_vte_titles] :
... | def recompute_tabs_titles(self):
"""Updates labels on all tabs. This is required when `self.abbreviate`
changes
"""
use_vte_titles = self.settings.general.get_boolean('use-vte-titles')
if not use_vte_titles:
return # depends on [control=['if'], data=[]]
# TODO NOTEBOOK this code... |
def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_enode_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
fcoe_get_interface = ET.Element("fcoe_get_interface")
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, ... | def function[fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_enode_mac_address, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[fcoe_get_interface] assign[=] call[name[ET].Element, parameter[const... | keyword[def] identifier[fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_enode_mac_address] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[fcoe_get_interface] = identifier[ET] . identif... | def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_enode_mac_address(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
fcoe_get_interface = ET.Element('fcoe_get_interface')
config = fcoe_get_interface
output = ET.SubElement(fcoe_get_interface, 'output')
fcoe_i... |
def _close(self, fd):
"""
Close the descriptor used for a path regardless
of mode.
"""
if self._mode == WF_INOTIFYX:
try: pynotifyx.rm_watch(self._inx_fd, fd)
except: pass
else:
try: os.close(fd)
except: pass | def function[_close, parameter[self, fd]]:
constant[
Close the descriptor used for a path regardless
of mode.
]
if compare[name[self]._mode equal[==] name[WF_INOTIFYX]] begin[:]
<ast.Try object at 0x7da2049604f0> | keyword[def] identifier[_close] ( identifier[self] , identifier[fd] ):
literal[string]
keyword[if] identifier[self] . identifier[_mode] == identifier[WF_INOTIFYX] :
keyword[try] : identifier[pynotifyx] . identifier[rm_watch] ( identifier[self] . identifier[_inx_fd] , identifier[fd] )
... | def _close(self, fd):
"""
Close the descriptor used for a path regardless
of mode.
"""
if self._mode == WF_INOTIFYX:
try:
pynotifyx.rm_watch(self._inx_fd, fd) # depends on [control=['try'], data=[]]
except:
pass # depends on [control=['except'], data... |
def add_stream(self, policy):
"""
Add a stream to the SRTP session, applying the given `policy`
to the stream.
:param policy: :class:`Policy`
"""
_srtp_assert(lib.srtp_add_stream(self._srtp[0], policy._policy)) | def function[add_stream, parameter[self, policy]]:
constant[
Add a stream to the SRTP session, applying the given `policy`
to the stream.
:param policy: :class:`Policy`
]
call[name[_srtp_assert], parameter[call[name[lib].srtp_add_stream, parameter[call[name[self]._srtp][... | keyword[def] identifier[add_stream] ( identifier[self] , identifier[policy] ):
literal[string]
identifier[_srtp_assert] ( identifier[lib] . identifier[srtp_add_stream] ( identifier[self] . identifier[_srtp] [ literal[int] ], identifier[policy] . identifier[_policy] )) | def add_stream(self, policy):
"""
Add a stream to the SRTP session, applying the given `policy`
to the stream.
:param policy: :class:`Policy`
"""
_srtp_assert(lib.srtp_add_stream(self._srtp[0], policy._policy)) |
def _do_bgread(stream, blockSizeLimit, pollTime, closeStream, results):
'''
_do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData>
'''
# Put the whole function in a try instead of just the... | def function[_do_bgread, parameter[stream, blockSizeLimit, pollTime, closeStream, results]]:
constant[
_do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData>
]
<ast.Try object at 0x7da1... | keyword[def] identifier[_do_bgread] ( identifier[stream] , identifier[blockSizeLimit] , identifier[pollTime] , identifier[closeStream] , identifier[results] ):
literal[string]
keyword[try] :
keyword[while] keyword[True] :
identifier[nextData] = identifier[nonblock_read] ( ident... | def _do_bgread(stream, blockSizeLimit, pollTime, closeStream, results):
"""
_do_bgread - Worker functon for the background read thread.
@param stream <object> - Stream to read until closed
@param results <BackgroundReadData>
"""
# Put the whole function in a try instead of just the ... |
def key(string):
"""Return a Czech sort key for the given string
:param string: string (unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order, i.e.
``key(s1) < key(s2)`` <=> ``s1`` comes before ``s... | def function[key, parameter[string]]:
constant[Return a Czech sort key for the given string
:param string: string (unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order, i.e.
``key(s1) < key(s2)`... | keyword[def] identifier[key] ( identifier[string] ):
literal[string]
identifier[subkeys] =[],[],[],[]
identifier[add_alphabet] = identifier[subkeys] [ literal[int] ]. identifie... | def key(string):
"""Return a Czech sort key for the given string
:param string: string (unicode in Python 2)
Comparing the sort keys of two strings will give the result according
to how the strings would compare in Czech collation order, i.e.
``key(s1) < key(s2)`` <=> ``s1`` comes before ``s... |
def _wavGetInfo(f:Union[IO, str]) -> Tuple[SndInfo, Dict[str, Any]]:
"""
Read the info of a wav file. taken mostly from scipy.io.wavfile
if extended: returns also fsize and bigendian
"""
if isinstance(f, (str, bytes)):
f = open(f, 'rb')
needsclosing = True
else:
needsclo... | def function[_wavGetInfo, parameter[f]]:
constant[
Read the info of a wav file. taken mostly from scipy.io.wavfile
if extended: returns also fsize and bigendian
]
if call[name[isinstance], parameter[name[f], tuple[[<ast.Name object at 0x7da20c993700>, <ast.Name object at 0x7da20c991540>]]]]... | keyword[def] identifier[_wavGetInfo] ( identifier[f] : identifier[Union] [ identifier[IO] , identifier[str] ])-> identifier[Tuple] [ identifier[SndInfo] , identifier[Dict] [ identifier[str] , identifier[Any] ]]:
literal[string]
keyword[if] identifier[isinstance] ( identifier[f] ,( identifier[str] , identi... | def _wavGetInfo(f: Union[IO, str]) -> Tuple[SndInfo, Dict[str, Any]]:
"""
Read the info of a wav file. taken mostly from scipy.io.wavfile
if extended: returns also fsize and bigendian
"""
if isinstance(f, (str, bytes)):
f = open(f, 'rb')
needsclosing = True # depends on [control=['... |
def _make_map(self, limit):
""" Make vegas grid that is adapted to the pdf. """
ny = 2000
y = numpy.random.uniform(0., 1., (ny,1))
limit = numpy.arctan(limit)
m = AdaptiveMap([[-limit, limit]], ninc=100)
theta = numpy.empty(y.shape, float)
jac = numpy.empty(y.shap... | def function[_make_map, parameter[self, limit]]:
constant[ Make vegas grid that is adapted to the pdf. ]
variable[ny] assign[=] constant[2000]
variable[y] assign[=] call[name[numpy].random.uniform, parameter[constant[0.0], constant[1.0], tuple[[<ast.Name object at 0x7da1b04d8070>, <ast.Constant ... | keyword[def] identifier[_make_map] ( identifier[self] , identifier[limit] ):
literal[string]
identifier[ny] = literal[int]
identifier[y] = identifier[numpy] . identifier[random] . identifier[uniform] ( literal[int] , literal[int] ,( identifier[ny] , literal[int] ))
identifier[lim... | def _make_map(self, limit):
""" Make vegas grid that is adapted to the pdf. """
ny = 2000
y = numpy.random.uniform(0.0, 1.0, (ny, 1))
limit = numpy.arctan(limit)
m = AdaptiveMap([[-limit, limit]], ninc=100)
theta = numpy.empty(y.shape, float)
jac = numpy.empty(y.shape[0], float)
for itn ... |
def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() | def function[start, parameter[self]]:
constant[
Starts the connection
]
name[self].__stop assign[=] constant[False]
call[name[self]._queue.start, parameter[]]
call[name[self]._zk.start, parameter[]] | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__stop] = keyword[False]
identifier[self] . identifier[_queue] . identifier[start] ()
identifier[self] . identifier[_zk] . identifier[start] () | def start(self):
"""
Starts the connection
"""
self.__stop = False
self._queue.start()
self._zk.start() |
def _heartbeat(self):
"""Heartbeat callback"""
if self.handler is not None:
self.handler.send_pack(proto.HEARTBEAT)
else:
self.stop_heartbeat() | def function[_heartbeat, parameter[self]]:
constant[Heartbeat callback]
if compare[name[self].handler is_not constant[None]] begin[:]
call[name[self].handler.send_pack, parameter[name[proto].HEARTBEAT]] | keyword[def] identifier[_heartbeat] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[handler] keyword[is] keyword[not] keyword[None] :
identifier[self] . identifier[handler] . identifier[send_pack] ( identifier[proto] . identifier[HEARTBEAT] )
... | def _heartbeat(self):
"""Heartbeat callback"""
if self.handler is not None:
self.handler.send_pack(proto.HEARTBEAT) # depends on [control=['if'], data=[]]
else:
self.stop_heartbeat() |
def WriteEventBody(self, event):
"""Writes the body of an event object to the spreadsheet.
Args:
event (EventObject): event.
"""
for field_name in self._fields:
if field_name == 'datetime':
output_value = self._FormatDateTime(event)
else:
output_value = self._dynamic_f... | def function[WriteEventBody, parameter[self, event]]:
constant[Writes the body of an event object to the spreadsheet.
Args:
event (EventObject): event.
]
for taget[name[field_name]] in starred[name[self]._fields] begin[:]
if compare[name[field_name] equal[==] constant[date... | keyword[def] identifier[WriteEventBody] ( identifier[self] , identifier[event] ):
literal[string]
keyword[for] identifier[field_name] keyword[in] identifier[self] . identifier[_fields] :
keyword[if] identifier[field_name] == literal[string] :
identifier[output_value] = identifier[self] ... | def WriteEventBody(self, event):
"""Writes the body of an event object to the spreadsheet.
Args:
event (EventObject): event.
"""
for field_name in self._fields:
if field_name == 'datetime':
output_value = self._FormatDateTime(event) # depends on [control=['if'], data=[]]
... |
def get_dict_for_forms(self):
"""
Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribut... | def function[get_dict_for_forms, parameter[self]]:
constant[
Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchabl... | keyword[def] identifier[get_dict_for_forms] ( identifier[self] ):
literal[string]
identifier[magic_dico] = identifier[field_to_dict] ( identifier[self] . identifier[searchable_fields] )
identifier[dico] ={}
keyword[def] identifier[dict_from_fields_r] ( identifier[mini_dict] , id... | def get_dict_for_forms(self):
"""
Build a dictionnary where searchable_fields are
next to their model to be use in modelform_factory
dico = {
"str(model)" : {
"model" : Model,
"fields" = [] #searchable_fields which are attribute of... |
def finalize_backreferences(seen_backrefs, gallery_conf):
"""Replace backref files only if necessary."""
logger = sphinx_compatibility.getLogger('sphinx-gallery')
if gallery_conf['backreferences_dir'] is None:
return
for backref in seen_backrefs:
path = os.path.join(gallery_conf['src_di... | def function[finalize_backreferences, parameter[seen_backrefs, gallery_conf]]:
constant[Replace backref files only if necessary.]
variable[logger] assign[=] call[name[sphinx_compatibility].getLogger, parameter[constant[sphinx-gallery]]]
if compare[call[name[gallery_conf]][constant[backreferences... | keyword[def] identifier[finalize_backreferences] ( identifier[seen_backrefs] , identifier[gallery_conf] ):
literal[string]
identifier[logger] = identifier[sphinx_compatibility] . identifier[getLogger] ( literal[string] )
keyword[if] identifier[gallery_conf] [ literal[string] ] keyword[is] keyword[No... | def finalize_backreferences(seen_backrefs, gallery_conf):
"""Replace backref files only if necessary."""
logger = sphinx_compatibility.getLogger('sphinx-gallery')
if gallery_conf['backreferences_dir'] is None:
return # depends on [control=['if'], data=[]]
for backref in seen_backrefs:
p... |
def _create_related(args):
# type: (Dict) -> None
"""Create related field from `_embed` arguments."""
if '_embed' in request.args:
embeds = request.args.getlist('_embed')
args['related'] = ','.join(embeds)
del args['_embed'] | def function[_create_related, parameter[args]]:
constant[Create related field from `_embed` arguments.]
if compare[constant[_embed] in name[request].args] begin[:]
variable[embeds] assign[=] call[name[request].args.getlist, parameter[constant[_embed]]]
call[name[args]][co... | keyword[def] identifier[_create_related] ( identifier[args] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[request] . identifier[args] :
identifier[embeds] = identifier[request] . identifier[args] . identifier[getlist] ( literal[string] )
identi... | def _create_related(args):
# type: (Dict) -> None
'Create related field from `_embed` arguments.'
if '_embed' in request.args:
embeds = request.args.getlist('_embed')
args['related'] = ','.join(embeds)
del args['_embed'] # depends on [control=['if'], data=[]] |
async def load(self, turn_context: TurnContext, force: bool = False) -> None:
"""
Reads in the current state object and caches it in the context object for this turm.
:param turn_context: The context object for this turn.
:param force: Optional. True to bypass the cache.
"""
... | <ast.AsyncFunctionDef object at 0x7da1b05fbdf0> | keyword[async] keyword[def] identifier[load] ( identifier[self] , identifier[turn_context] : identifier[TurnContext] , identifier[force] : identifier[bool] = keyword[False] )-> keyword[None] :
literal[string]
keyword[if] identifier[turn_context] == keyword[None] :
keyword[raise] ide... | async def load(self, turn_context: TurnContext, force: bool=False) -> None:
"""
Reads in the current state object and caches it in the context object for this turm.
:param turn_context: The context object for this turn.
:param force: Optional. True to bypass the cache.
"""
if tu... |
def get_inner_template(self, language, template_type, indentation, key, val):
"""
Gets the requested template for the given language.
Args:
language: string, the language of the template to look for.
template_type: string, 'iterable' or 'singular'.
An itera... | def function[get_inner_template, parameter[self, language, template_type, indentation, key, val]]:
constant[
Gets the requested template for the given language.
Args:
language: string, the language of the template to look for.
template_type: string, 'iterable' or 'singu... | keyword[def] identifier[get_inner_template] ( identifier[self] , identifier[language] , identifier[template_type] , identifier[indentation] , identifier[key] , identifier[val] ):
literal[string]
identifier[inner_templates] ={ literal[string] :{
literal[string] : literal[string] %(... | def get_inner_template(self, language, template_type, indentation, key, val):
"""
Gets the requested template for the given language.
Args:
language: string, the language of the template to look for.
template_type: string, 'iterable' or 'singular'.
An iterable ... |
def _CheckIsDirectory(self, file_entry):
"""Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DIRECTORY not in self._file_entry_typ... | def function[_CheckIsDirectory, parameter[self, file_entry]]:
constant[Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
]
if compare[name[definitions].FILE_E... | keyword[def] identifier[_CheckIsDirectory] ( identifier[self] , identifier[file_entry] ):
literal[string]
keyword[if] identifier[definitions] . identifier[FILE_ENTRY_TYPE_DIRECTORY] keyword[not] keyword[in] identifier[self] . identifier[_file_entry_types] :
keyword[return] keyword[False]
... | def _CheckIsDirectory(self, file_entry):
"""Checks the is_directory find specification.
Args:
file_entry (FileEntry): file entry.
Returns:
bool: True if the file entry matches the find specification, False if not.
"""
if definitions.FILE_ENTRY_TYPE_DIRECTORY not in self._file_entry_typ... |
def get_collection(self, collection_id=None, nav="children", page=None):
""" Makes a call on the Collection API
:param collection_id: Id of the collection to retrieve
:param nav: Direction of the navigation
:param page: Page to retrieve
:return: Response
:rtype: requests... | def function[get_collection, parameter[self, collection_id, nav, page]]:
constant[ Makes a call on the Collection API
:param collection_id: Id of the collection to retrieve
:param nav: Direction of the navigation
:param page: Page to retrieve
:return: Response
:rtype: re... | keyword[def] identifier[get_collection] ( identifier[self] , identifier[collection_id] = keyword[None] , identifier[nav] = literal[string] , identifier[page] = keyword[None] ):
literal[string]
keyword[return] identifier[self] . identifier[call] (
literal[string] ,
{
liter... | def get_collection(self, collection_id=None, nav='children', page=None):
""" Makes a call on the Collection API
:param collection_id: Id of the collection to retrieve
:param nav: Direction of the navigation
:param page: Page to retrieve
:return: Response
:rtype: requests.Res... |
def use(self, tube):
"""Start producing jobs into the given tube.
:param tube: Name of the tube to USE
Subsequent calls to :func:`put_job` insert jobs into this tube.
"""
with self._sock_ctx() as socket:
if self.current_tube != tube:
self.desired_tub... | def function[use, parameter[self, tube]]:
constant[Start producing jobs into the given tube.
:param tube: Name of the tube to USE
Subsequent calls to :func:`put_job` insert jobs into this tube.
]
with call[name[self]._sock_ctx, parameter[]] begin[:]
if compare[n... | keyword[def] identifier[use] ( identifier[self] , identifier[tube] ):
literal[string]
keyword[with] identifier[self] . identifier[_sock_ctx] () keyword[as] identifier[socket] :
keyword[if] identifier[self] . identifier[current_tube] != identifier[tube] :
identifier[... | def use(self, tube):
"""Start producing jobs into the given tube.
:param tube: Name of the tube to USE
Subsequent calls to :func:`put_job` insert jobs into this tube.
"""
with self._sock_ctx() as socket:
if self.current_tube != tube:
self.desired_tube = tube
... |
def delete_request(profile, resource):
"""Do a DELETE request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
... | def function[delete_request, parameter[profile, resource]]:
constant[Do a DELETE request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ... | keyword[def] identifier[delete_request] ( identifier[profile] , identifier[resource] ):
literal[string]
identifier[url] = identifier[get_url] ( identifier[profile] , identifier[resource] )
identifier[headers] = identifier[get_headers] ( identifier[profile] )
keyword[return] identifier[requests] ... | def delete_request(profile, resource):
"""Do a DELETE request to Github's API.
Args:
profile
A profile generated from ``simplygithub.authentication.profile``.
Such profiles tell this module (i) the ``repo`` to connect to,
and (ii) the ``token`` to connect with.
... |
def _get_complex_type_production(complex_type: ComplexType,
multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]:
"""
Takes a complex type (without any placeholders), gets its return values, and returns productions
(perhaps each with multiple arguments) tha... | def function[_get_complex_type_production, parameter[complex_type, multi_match_mapping]]:
constant[
Takes a complex type (without any placeholders), gets its return values, and returns productions
(perhaps each with multiple arguments) that produce the return values. This method also takes
care of ... | keyword[def] identifier[_get_complex_type_production] ( identifier[complex_type] : identifier[ComplexType] ,
identifier[multi_match_mapping] : identifier[Dict] [ identifier[Type] , identifier[List] [ identifier[Type] ]])-> identifier[List] [ identifier[Tuple] [ identifier[Type] , identifier[str] ]]:
literal[str... | def _get_complex_type_production(complex_type: ComplexType, multi_match_mapping: Dict[Type, List[Type]]) -> List[Tuple[Type, str]]:
"""
Takes a complex type (without any placeholders), gets its return values, and returns productions
(perhaps each with multiple arguments) that produce the return values. Thi... |
def is_valid_channel(self,
channel,
conda_url='https://conda.anaconda.org',
non_blocking=True):
"""Check if a conda channel is valid."""
logger.debug(str((channel, conda_url)))
if non_blocking:
method = self._... | def function[is_valid_channel, parameter[self, channel, conda_url, non_blocking]]:
constant[Check if a conda channel is valid.]
call[name[logger].debug, parameter[call[name[str], parameter[tuple[[<ast.Name object at 0x7da1b27b7eb0>, <ast.Name object at 0x7da1b27b5120>]]]]]]
if name[non_blocking]... | keyword[def] identifier[is_valid_channel] ( identifier[self] ,
identifier[channel] ,
identifier[conda_url] = literal[string] ,
identifier[non_blocking] = keyword[True] ):
literal[string]
identifier[logger] . identifier[debug] ( identifier[str] (( identifier[channel] , identifier[conda_url] )))
... | def is_valid_channel(self, channel, conda_url='https://conda.anaconda.org', non_blocking=True):
"""Check if a conda channel is valid."""
logger.debug(str((channel, conda_url)))
if non_blocking:
method = self._is_valid_channel
return self._create_worker(method, channel, conda_url) # depends ... |
def add_element(self, tag):
'''Record that `tag` has been seen at this depth.
If `tag` is :class:`TextElement`, it records a text node.
'''
# Collapse adjacent text nodes
if tag is TextElement and self.last_tag is TextElement:
return
self.last_tag = tag
... | def function[add_element, parameter[self, tag]]:
constant[Record that `tag` has been seen at this depth.
If `tag` is :class:`TextElement`, it records a text node.
]
if <ast.BoolOp object at 0x7da2054a44f0> begin[:]
return[None]
name[self].last_tag assign[=] name[tag]
... | keyword[def] identifier[add_element] ( identifier[self] , identifier[tag] ):
literal[string]
keyword[if] identifier[tag] keyword[is] identifier[TextElement] keyword[and] identifier[self] . identifier[last_tag] keyword[is] identifier[TextElement] :
keyword[return]
... | def add_element(self, tag):
"""Record that `tag` has been seen at this depth.
If `tag` is :class:`TextElement`, it records a text node.
"""
# Collapse adjacent text nodes
if tag is TextElement and self.last_tag is TextElement:
return # depends on [control=['if'], data=[]]
self... |
def approx_count_distinct(col, rsd=None):
"""Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_coun... | def function[approx_count_distinct, parameter[col, rsd]]:
constant[Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
... | keyword[def] identifier[approx_count_distinct] ( identifier[col] , identifier[rsd] = keyword[None] ):
literal[string]
identifier[sc] = identifier[SparkContext] . identifier[_active_spark_context]
keyword[if] identifier[rsd] keyword[is] keyword[None] :
identifier[jc] = identifier[sc] . ide... | def approx_count_distinct(col, rsd=None):
"""Aggregate function: returns a new :class:`Column` for approximate distinct count of
column `col`.
:param rsd: maximum estimation error allowed (default = 0.05). For rsd < 0.01, it is more
efficient to use :func:`countDistinct`
>>> df.agg(approx_coun... |
def member_absent(ip, port, balancer_id, profile, **libcloud_kwargs):
'''
Ensure a load balancer member is absent, based on IP and Port
:param ip: IP address for the member
:type ip: ``str``
:param port: Port for the member
:type port: ``int``
:param balancer_id: id of a load balancer y... | def function[member_absent, parameter[ip, port, balancer_id, profile]]:
constant[
Ensure a load balancer member is absent, based on IP and Port
:param ip: IP address for the member
:type ip: ``str``
:param port: Port for the member
:type port: ``int``
:param balancer_id: id of a loa... | keyword[def] identifier[member_absent] ( identifier[ip] , identifier[port] , identifier[balancer_id] , identifier[profile] ,** identifier[libcloud_kwargs] ):
literal[string]
identifier[existing_members] = identifier[__salt__] [ literal[string] ]( identifier[balancer_id] , identifier[profile] )
keyword... | def member_absent(ip, port, balancer_id, profile, **libcloud_kwargs):
"""
Ensure a load balancer member is absent, based on IP and Port
:param ip: IP address for the member
:type ip: ``str``
:param port: Port for the member
:type port: ``int``
:param balancer_id: id of a load balancer y... |
def setup_mpi_gpus():
"""
Set CUDA_VISIBLE_DEVICES to MPI rank if not already set
"""
if 'CUDA_VISIBLE_DEVICES' not in os.environ:
if sys.platform == 'darwin': # This Assumes if you're on OSX you're just
ids = [] # doing a smoke test and don't want GPUs
else:
... | def function[setup_mpi_gpus, parameter[]]:
constant[
Set CUDA_VISIBLE_DEVICES to MPI rank if not already set
]
if compare[constant[CUDA_VISIBLE_DEVICES] <ast.NotIn object at 0x7da2590d7190> name[os].environ] begin[:]
if compare[name[sys].platform equal[==] constant[darwin]] begin... | keyword[def] identifier[setup_mpi_gpus] ():
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[os] . identifier[environ] :
keyword[if] identifier[sys] . identifier[platform] == literal[string] :
identifier[ids] =[]
keyword[else] :
... | def setup_mpi_gpus():
"""
Set CUDA_VISIBLE_DEVICES to MPI rank if not already set
"""
if 'CUDA_VISIBLE_DEVICES' not in os.environ:
if sys.platform == 'darwin': # This Assumes if you're on OSX you're just
ids = [] # doing a smoke test and don't want GPUs # depends on [control=['if'... |
def del_node(self, char, node):
"""Remove a node from a character."""
del self._real.character[char].node[node]
for cache in (
self._char_nodes_rulebooks_cache,
self._node_stat_cache,
self._node_successors_cache
):
try:
... | def function[del_node, parameter[self, char, node]]:
constant[Remove a node from a character.]
<ast.Delete object at 0x7da1b0b819c0>
for taget[name[cache]] in starred[tuple[[<ast.Attribute object at 0x7da1b0b804f0>, <ast.Attribute object at 0x7da1b0b81480>, <ast.Attribute object at 0x7da1b0b82b90>]]... | keyword[def] identifier[del_node] ( identifier[self] , identifier[char] , identifier[node] ):
literal[string]
keyword[del] identifier[self] . identifier[_real] . identifier[character] [ identifier[char] ]. identifier[node] [ identifier[node] ]
keyword[for] identifier[cache] keyword[in] ... | def del_node(self, char, node):
"""Remove a node from a character."""
del self._real.character[char].node[node]
for cache in (self._char_nodes_rulebooks_cache, self._node_stat_cache, self._node_successors_cache):
try:
del cache[char][node] # depends on [control=['try'], data=[]]
... |
def submit(recaptcha_challenge_field,
recaptcha_response_field,
private_key,
remoteip,
use_ssl=False):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_fi... | def function[submit, parameter[recaptcha_challenge_field, recaptcha_response_field, private_key, remoteip, use_ssl]]:
constant[
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_field
from the fo... | keyword[def] identifier[submit] ( identifier[recaptcha_challenge_field] ,
identifier[recaptcha_response_field] ,
identifier[private_key] ,
identifier[remoteip] ,
identifier[use_ssl] = keyword[False] ):
literal[string]
keyword[if] keyword[not] ( identifier[recaptcha_response_field] keyword[and] iden... | def submit(recaptcha_challenge_field, recaptcha_response_field, private_key, remoteip, use_ssl=False):
"""
Submits a reCAPTCHA request for verification. Returns RecaptchaResponse
for the request
recaptcha_challenge_field -- The value of recaptcha_challenge_field
from the form
recaptcha_response... |
def render_to_message(self, extra_context=None, *args, **kwargs):
"""
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional co... | def function[render_to_message, parameter[self, extra_context]]:
constant[
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any addition... | keyword[def] identifier[render_to_message] ( identifier[self] , identifier[extra_context] = keyword[None] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[message] = identifier[super] ( identifier[TemplatedHTMLEmailMessageView] , identifier[self] ). identifier[render_to_mess... | def render_to_message(self, extra_context=None, *args, **kwargs):
"""
Renders and returns an unsent message with the given context.
Any extra keyword arguments passed will be passed through as keyword
arguments to the message constructor.
:param extra_context: Any additional contex... |
def _get_params_for_optimizer(self, prefix, named_parameters):
"""Parse kwargs configuration for the optimizer identified by
the given prefix. Supports param group assignment using wildcards:
optimizer__lr=0.05,
optimizer__param_groups=[
('rnn*.period', {'lr': 0.... | def function[_get_params_for_optimizer, parameter[self, prefix, named_parameters]]:
constant[Parse kwargs configuration for the optimizer identified by
the given prefix. Supports param group assignment using wildcards:
optimizer__lr=0.05,
optimizer__param_groups=[
... | keyword[def] identifier[_get_params_for_optimizer] ( identifier[self] , identifier[prefix] , identifier[named_parameters] ):
literal[string]
identifier[kwargs] = identifier[self] . identifier[_get_params_for] ( identifier[prefix] )
identifier[params] = identifier[list] ( identifier[named_p... | def _get_params_for_optimizer(self, prefix, named_parameters):
"""Parse kwargs configuration for the optimizer identified by
the given prefix. Supports param group assignment using wildcards:
optimizer__lr=0.05,
optimizer__param_groups=[
('rnn*.period', {'lr': 0.3, '... |
def translate_style(style, colormode, colorpalette):
"""
Translate the given style to an ANSI escape code
sequence.
``style`` examples are:
* green
* bold
* red_on_black
* bold_green
* italic_yellow_on_cyan
:param str style: the style to translate
:param int colormode: the... | def function[translate_style, parameter[style, colormode, colorpalette]]:
constant[
Translate the given style to an ANSI escape code
sequence.
``style`` examples are:
* green
* bold
* red_on_black
* bold_green
* italic_yellow_on_cyan
:param str style: the style to translat... | keyword[def] identifier[translate_style] ( identifier[style] , identifier[colormode] , identifier[colorpalette] ):
literal[string]
identifier[style_parts] = identifier[iter] ( identifier[style] . identifier[split] ( literal[string] ))
identifier[ansi_start_sequence] =[]
identifier[ansi_end_seque... | def translate_style(style, colormode, colorpalette):
"""
Translate the given style to an ANSI escape code
sequence.
``style`` examples are:
* green
* bold
* red_on_black
* bold_green
* italic_yellow_on_cyan
:param str style: the style to translate
:param int colormode: the... |
def diff(cwd,
item1=None,
item2=None,
opts='',
git_opts='',
user=None,
password=None,
no_index=False,
cached=False,
paths=None,
output_encoding=None):
'''
.. versionadded:: 2015.8.12,2016.3.3,2016.11.0
Interface to `g... | def function[diff, parameter[cwd, item1, item2, opts, git_opts, user, password, no_index, cached, paths, output_encoding]]:
constant[
.. versionadded:: 2015.8.12,2016.3.3,2016.11.0
Interface to `git-diff(1)`_
cwd
The path to the git checkout
item1 and item2
Revision(s) to pass... | keyword[def] identifier[diff] ( identifier[cwd] ,
identifier[item1] = keyword[None] ,
identifier[item2] = keyword[None] ,
identifier[opts] = literal[string] ,
identifier[git_opts] = literal[string] ,
identifier[user] = keyword[None] ,
identifier[password] = keyword[None] ,
identifier[no_index] = keyword[False]... | def diff(cwd, item1=None, item2=None, opts='', git_opts='', user=None, password=None, no_index=False, cached=False, paths=None, output_encoding=None):
"""
.. versionadded:: 2015.8.12,2016.3.3,2016.11.0
Interface to `git-diff(1)`_
cwd
The path to the git checkout
item1 and item2
Re... |
def _l_cv_weight(self, donor_catchment):
"""
Return L-CV weighting for a donor catchment.
Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a
"""
try:
dist = donor_catchment.similarity_dist
except AttributeError:
dist = self._similari... | def function[_l_cv_weight, parameter[self, donor_catchment]]:
constant[
Return L-CV weighting for a donor catchment.
Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a
]
<ast.Try object at 0x7da20e9b1060>
variable[b] assign[=] binary_operation[binary_operation[... | keyword[def] identifier[_l_cv_weight] ( identifier[self] , identifier[donor_catchment] ):
literal[string]
keyword[try] :
identifier[dist] = identifier[donor_catchment] . identifier[similarity_dist]
keyword[except] identifier[AttributeError] :
identifier[dist] = ... | def _l_cv_weight(self, donor_catchment):
"""
Return L-CV weighting for a donor catchment.
Methodology source: Science Report SC050050, eqn. 6.18 and 6.22a
"""
try:
dist = donor_catchment.similarity_dist # depends on [control=['try'], data=[]]
except AttributeError:
... |
def setMaximumWidth(self, width):
"""
Sets the maximum width value to the inputed width and emits the \
sizeConstraintChanged signal.
:param width | <int>
"""
super(XView, self).setMaximumWidth(width)
if ( not self.signalsBlocked() ):
... | def function[setMaximumWidth, parameter[self, width]]:
constant[
Sets the maximum width value to the inputed width and emits the sizeConstraintChanged signal.
:param width | <int>
]
call[call[name[super], parameter[name[XView], name[self]]].setMaximumWidth, ... | keyword[def] identifier[setMaximumWidth] ( identifier[self] , identifier[width] ):
literal[string]
identifier[super] ( identifier[XView] , identifier[self] ). identifier[setMaximumWidth] ( identifier[width] )
keyword[if] ( keyword[not] identifier[self] . identifier[signalsBlocked] ()):
... | def setMaximumWidth(self, width):
"""
Sets the maximum width value to the inputed width and emits the sizeConstraintChanged signal.
:param width | <int>
"""
super(XView, self).setMaximumWidth(width)
if not self.signalsBlocked():
self.sizeConstraintChange... |
def get_link(self, path, method, callback, view):
"""
Return a `coreapi.Link` instance for the given endpoint.
"""
fields = self.get_path_fields(path, method, callback, view)
fields += self.get_serializer_fields(path, method, callback, view)
fields += self.get_pagination_... | def function[get_link, parameter[self, path, method, callback, view]]:
constant[
Return a `coreapi.Link` instance for the given endpoint.
]
variable[fields] assign[=] call[name[self].get_path_fields, parameter[name[path], name[method], name[callback], name[view]]]
<ast.AugAssign obje... | keyword[def] identifier[get_link] ( identifier[self] , identifier[path] , identifier[method] , identifier[callback] , identifier[view] ):
literal[string]
identifier[fields] = identifier[self] . identifier[get_path_fields] ( identifier[path] , identifier[method] , identifier[callback] , identifier[v... | def get_link(self, path, method, callback, view):
"""
Return a `coreapi.Link` instance for the given endpoint.
"""
fields = self.get_path_fields(path, method, callback, view)
fields += self.get_serializer_fields(path, method, callback, view)
fields += self.get_pagination_fields(path, met... |
def create_stream(self, stream_id, sandbox=None):
"""
Create the stream
:param stream_id: The stream identifier
:param sandbox: The sandbox for this stream
:return: None
:raises: NotImplementedError
"""
if sandbox is not None:
raise No... | def function[create_stream, parameter[self, stream_id, sandbox]]:
constant[
Create the stream
:param stream_id: The stream identifier
:param sandbox: The sandbox for this stream
:return: None
:raises: NotImplementedError
]
if compare[name[sandbox]... | keyword[def] identifier[create_stream] ( identifier[self] , identifier[stream_id] , identifier[sandbox] = keyword[None] ):
literal[string]
keyword[if] identifier[sandbox] keyword[is] keyword[not] keyword[None] :
keyword[raise] identifier[NotImplementedError]
identifier[... | def create_stream(self, stream_id, sandbox=None):
"""
Create the stream
:param stream_id: The stream identifier
:param sandbox: The sandbox for this stream
:return: None
:raises: NotImplementedError
"""
if sandbox is not None:
raise NotImplemented... |
def available_add_ons(self):
"""
:rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList
"""
if self._available_add_ons is None:
self._available_add_ons = AvailableAddOnList(self)
return self._available_add_ons | def function[available_add_ons, parameter[self]]:
constant[
:rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList
]
if compare[name[self]._available_add_ons is constant[None]] begin[:]
name[self]._available_add_ons assign[=] call[name[AvailableAddOnL... | keyword[def] identifier[available_add_ons] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_available_add_ons] keyword[is] keyword[None] :
identifier[self] . identifier[_available_add_ons] = identifier[AvailableAddOnList] ( identifier[self] )
... | def available_add_ons(self):
"""
:rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnList
"""
if self._available_add_ons is None:
self._available_add_ons = AvailableAddOnList(self) # depends on [control=['if'], data=[]]
return self._available_add_ons |
def __get_sigmas(self):
"""will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes"""
stack_sigma = {}
_stack = self.stack
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_... | def function[__get_sigmas, parameter[self]]:
constant[will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes]
variable[stack_sigma] assign[=] dictionary[[], []]
variable[_stack] assign[=] name[self].stack
variable[_file_... | keyword[def] identifier[__get_sigmas] ( identifier[self] ):
literal[string]
identifier[stack_sigma] ={}
identifier[_stack] = identifier[self] . identifier[stack]
identifier[_file_path] = identifier[os] . identifier[path] . identifier[abspath] ( identifier[os] . identifier[path] ... | def __get_sigmas(self):
"""will populate the stack_sigma dictionary with the energy and sigma array
for all the compound/element and isotopes"""
stack_sigma = {}
_stack = self.stack
_file_path = os.path.abspath(os.path.dirname(__file__))
_database_folder = os.path.join(_file_path, 'reference... |
def write(url, object_, **args):
"""Writes an object to a data URI."""
default_content_type = ('text/plain', {'charset': 'US-ASCII'})
content_encoding = args.get('content_encoding', 'base64')
content_type, params = args.get('content_type', default_content_type)
data = content_types.get(content_type)... | def function[write, parameter[url, object_]]:
constant[Writes an object to a data URI.]
variable[default_content_type] assign[=] tuple[[<ast.Constant object at 0x7da1b26ad900>, <ast.Dict object at 0x7da1b26afd60>]]
variable[content_encoding] assign[=] call[name[args].get, parameter[constant[cont... | keyword[def] identifier[write] ( identifier[url] , identifier[object_] ,** identifier[args] ):
literal[string]
identifier[default_content_type] =( literal[string] ,{ literal[string] : literal[string] })
identifier[content_encoding] = identifier[args] . identifier[get] ( literal[string] , literal[strin... | def write(url, object_, **args):
"""Writes an object to a data URI."""
default_content_type = ('text/plain', {'charset': 'US-ASCII'})
content_encoding = args.get('content_encoding', 'base64')
(content_type, params) = args.get('content_type', default_content_type)
data = content_types.get(content_typ... |
def SendMessage(self, statement):
"""Here we're actually capturing messages and putting them into our output"""
# The way messages are 'encapsulated' by Rekall is questionable, 99% of the
# time it's way better to have a dictionary...shrug...
message_type = statement[0]
... | def function[SendMessage, parameter[self, statement]]:
constant[Here we're actually capturing messages and putting them into our output]
variable[message_type] assign[=] call[name[statement]][constant[0]]
variable[message_data] assign[=] call[name[statement]][constant[1]]
call[name[self]... | keyword[def] identifier[SendMessage] ( identifier[self] , identifier[statement] ):
literal[string]
identifier[message_type] = identifier[statement] [ literal[int] ]
identifier[message_data] = identifier[statement] [ literal[int] ]
identifier[self] . identifier[o... | def SendMessage(self, statement):
"""Here we're actually capturing messages and putting them into our output"""
# The way messages are 'encapsulated' by Rekall is questionable, 99% of the
# time it's way better to have a dictionary...shrug...
message_type = statement[0]
message_data = statement[1]
... |
def get_observations(params: Dict) -> Dict[str, Any]:
"""Search observations, see: http://api.inaturalist.org/v1/docs/#!/Observations/get_observations.
Returns the parsed JSON returned by iNaturalist (observations in r['results'], a list of dicts)
"""
r = make_inaturalist_api_get_call('observations', ... | def function[get_observations, parameter[params]]:
constant[Search observations, see: http://api.inaturalist.org/v1/docs/#!/Observations/get_observations.
Returns the parsed JSON returned by iNaturalist (observations in r['results'], a list of dicts)
]
variable[r] assign[=] call[name[make_inatu... | keyword[def] identifier[get_observations] ( identifier[params] : identifier[Dict] )-> identifier[Dict] [ identifier[str] , identifier[Any] ]:
literal[string]
identifier[r] = identifier[make_inaturalist_api_get_call] ( literal[string] , identifier[params] = identifier[params] )
keyword[return] identi... | def get_observations(params: Dict) -> Dict[str, Any]:
"""Search observations, see: http://api.inaturalist.org/v1/docs/#!/Observations/get_observations.
Returns the parsed JSON returned by iNaturalist (observations in r['results'], a list of dicts)
"""
r = make_inaturalist_api_get_call('observations', p... |
def CreateGRRTempFile(filename=None, lifetime=0, mode="w+b", suffix=""):
"""Open file with GRR prefix in directory to allow easy deletion.
Missing parent dirs will be created. If an existing directory is specified
its permissions won't be modified to avoid breaking system functionality.
Permissions on the dest... | def function[CreateGRRTempFile, parameter[filename, lifetime, mode, suffix]]:
constant[Open file with GRR prefix in directory to allow easy deletion.
Missing parent dirs will be created. If an existing directory is specified
its permissions won't be modified to avoid breaking system functionality.
Permis... | keyword[def] identifier[CreateGRRTempFile] ( identifier[filename] = keyword[None] , identifier[lifetime] = literal[int] , identifier[mode] = literal[string] , identifier[suffix] = literal[string] ):
literal[string]
identifier[directory] = identifier[GetDefaultGRRTempDirectory] ()
identifier[EnsureTempDirIs... | def CreateGRRTempFile(filename=None, lifetime=0, mode='w+b', suffix=''):
"""Open file with GRR prefix in directory to allow easy deletion.
Missing parent dirs will be created. If an existing directory is specified
its permissions won't be modified to avoid breaking system functionality.
Permissions on the de... |
def flatten(*sequence):
"""Flatten nested sequences into one."""
result = []
for entry in sequence:
if isinstance(entry, list):
result += Select.flatten(*entry)
elif isinstance(entry, tuple):
result += Select.flatten(*entry)
els... | def function[flatten, parameter[]]:
constant[Flatten nested sequences into one.]
variable[result] assign[=] list[[]]
for taget[name[entry]] in starred[name[sequence]] begin[:]
if call[name[isinstance], parameter[name[entry], name[list]]] begin[:]
<ast.AugAssign object... | keyword[def] identifier[flatten] (* identifier[sequence] ):
literal[string]
identifier[result] =[]
keyword[for] identifier[entry] keyword[in] identifier[sequence] :
keyword[if] identifier[isinstance] ( identifier[entry] , identifier[list] ):
identifier[res... | def flatten(*sequence):
"""Flatten nested sequences into one."""
result = []
for entry in sequence:
if isinstance(entry, list):
result += Select.flatten(*entry) # depends on [control=['if'], data=[]]
elif isinstance(entry, tuple):
result += Select.flatten(*entry) # ... |
def init_core(app):
"""Init core objects."""
from rio import models # noqa
db.init_app(app)
celery.init_app(app)
redis.init_app(app)
cache.init_app(app)
sentry.init_app(app)
graph.init_app(app)
setup_migrate(app)
setup_user_manager(app) | def function[init_core, parameter[app]]:
constant[Init core objects.]
from relative_module[rio] import module[models]
call[name[db].init_app, parameter[name[app]]]
call[name[celery].init_app, parameter[name[app]]]
call[name[redis].init_app, parameter[name[app]]]
call[name[cac... | keyword[def] identifier[init_core] ( identifier[app] ):
literal[string]
keyword[from] identifier[rio] keyword[import] identifier[models]
identifier[db] . identifier[init_app] ( identifier[app] )
identifier[celery] . identifier[init_app] ( identifier[app] )
identifier[redis] . identifier[... | def init_core(app):
"""Init core objects."""
from rio import models # noqa
db.init_app(app)
celery.init_app(app)
redis.init_app(app)
cache.init_app(app)
sentry.init_app(app)
graph.init_app(app)
setup_migrate(app)
setup_user_manager(app) |
def add_device(self, **kwargs):
"""Add a new device to catalog.
.. code-block:: python
device = {
"mechanism": "connector",
"certificate_fingerprint": "<certificate>",
"name": "New device name",
"certificate_issuer_id": "<id>"... | def function[add_device, parameter[self]]:
constant[Add a new device to catalog.
.. code-block:: python
device = {
"mechanism": "connector",
"certificate_fingerprint": "<certificate>",
"name": "New device name",
"certificate_i... | keyword[def] identifier[add_device] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[api] = identifier[self] . identifier[_get_api] ( identifier[device_directory] . identifier[DefaultApi] )
identifier[device] = identifier[Device] . identifier[_create_request_map] ( i... | def add_device(self, **kwargs):
"""Add a new device to catalog.
.. code-block:: python
device = {
"mechanism": "connector",
"certificate_fingerprint": "<certificate>",
"name": "New device name",
"certificate_issuer_id": "<id>"
... |
def gaussian_prior_model_for_arguments(self, arguments):
"""
Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
models with new arguments.
Parameters
----------
arguments: dict
A dictionary mapping_mat... | def function[gaussian_prior_model_for_arguments, parameter[self, arguments]]:
constant[
Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
models with new arguments.
Parameters
----------
arguments: dict
... | keyword[def] identifier[gaussian_prior_model_for_arguments] ( identifier[self] , identifier[arguments] ):
literal[string]
identifier[new_model] = identifier[copy] . identifier[deepcopy] ( identifier[self] )
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[filter]... | def gaussian_prior_model_for_arguments(self, arguments):
"""
Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
models with new arguments.
Parameters
----------
arguments: dict
A dictionary mapping_matrix ... |
def get_code(self):
"""Return the code embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed. This
should always match the 'http_response'."""
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_CODE]
... | def function[get_code, parameter[self]]:
constant[Return the code embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed. This
should always match the 'http_response'.]
variable[result] assign[=] constant[]
if compare[name[self]._data_struct i... | keyword[def] identifier[get_code] ( identifier[self] ):
literal[string]
identifier[result] = literal[string]
keyword[if] identifier[self] . identifier[_data_struct] keyword[is] keyword[not] keyword[None] :
identifier[result] = identifier[self] . identifier[_data_struct] ... | def get_code(self):
"""Return the code embedded in the JSON error response body,
or an empty string if the JSON couldn't be parsed. This
should always match the 'http_response'."""
result = ''
if self._data_struct is not None:
result = self._data_struct[KEY_CODE] # depends on [contr... |
def unwrap_self_for_multiprocessing(arg):
""" You can not call methods with multiprocessing, but free functions,
If you want to call inst.method(arg0, arg1),
unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1))
does the trick.
"""
(inst, method_name, args) = arg
r... | def function[unwrap_self_for_multiprocessing, parameter[arg]]:
constant[ You can not call methods with multiprocessing, but free functions,
If you want to call inst.method(arg0, arg1),
unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1))
does the trick.
]
<ast... | keyword[def] identifier[unwrap_self_for_multiprocessing] ( identifier[arg] ):
literal[string]
( identifier[inst] , identifier[method_name] , identifier[args] )= identifier[arg]
keyword[return] identifier[getattr] ( identifier[inst] , identifier[method_name] )(* identifier[args] ) | def unwrap_self_for_multiprocessing(arg):
""" You can not call methods with multiprocessing, but free functions,
If you want to call inst.method(arg0, arg1),
unwrap_self_for_multiprocessing(inst, "method", (arg0, arg1))
does the trick.
"""
(inst, method_name, args) = arg
r... |
def split_key_string(key):
"""Splits a key string (of the form, e.g. ``'C# major'``), into a tuple of
``(key, mode)`` where ``key`` is is an integer representing the semitone
distance from C.
Parameters
----------
key : str
String representing a key.
Returns
-------
key : i... | def function[split_key_string, parameter[key]]:
constant[Splits a key string (of the form, e.g. ``'C# major'``), into a tuple of
``(key, mode)`` where ``key`` is is an integer representing the semitone
distance from C.
Parameters
----------
key : str
String representing a key.
... | keyword[def] identifier[split_key_string] ( identifier[key] ):
literal[string]
identifier[key] , identifier[mode] = identifier[key] . identifier[split] ()
keyword[return] identifier[KEY_TO_SEMITONE] [ identifier[key] . identifier[lower] ()], identifier[mode] | def split_key_string(key):
"""Splits a key string (of the form, e.g. ``'C# major'``), into a tuple of
``(key, mode)`` where ``key`` is is an integer representing the semitone
distance from C.
Parameters
----------
key : str
String representing a key.
Returns
-------
key : i... |
def _get_cmap(kwargs: dict) -> colors.Colormap:
"""Get the colour map for plots that support it.
Parameters
----------
cmap : str or colors.Colormap or list of colors
A map or an instance of cmap. This can also be a seaborn palette
(if seaborn is installed).
"""
from matplotlib.... | def function[_get_cmap, parameter[kwargs]]:
constant[Get the colour map for plots that support it.
Parameters
----------
cmap : str or colors.Colormap or list of colors
A map or an instance of cmap. This can also be a seaborn palette
(if seaborn is installed).
]
from relativ... | keyword[def] identifier[_get_cmap] ( identifier[kwargs] : identifier[dict] )-> identifier[colors] . identifier[Colormap] :
literal[string]
keyword[from] identifier[matplotlib] . identifier[colors] keyword[import] identifier[ListedColormap]
identifier[cmap] = identifier[kwargs] . identifier[pop] (... | def _get_cmap(kwargs: dict) -> colors.Colormap:
"""Get the colour map for plots that support it.
Parameters
----------
cmap : str or colors.Colormap or list of colors
A map or an instance of cmap. This can also be a seaborn palette
(if seaborn is installed).
"""
from matplotlib.... |
def locale_first_weekday():
"""figure if week starts on monday or sunday"""
first_weekday = 6 #by default settle on monday
try:
process = os.popen("locale first_weekday week-1stday")
week_offset, week_start = process.read().split('\n')[:2]
process.close()
week_start = dt.dat... | def function[locale_first_weekday, parameter[]]:
constant[figure if week starts on monday or sunday]
variable[first_weekday] assign[=] constant[6]
<ast.Try object at 0x7da2049617b0>
return[name[first_weekday]] | keyword[def] identifier[locale_first_weekday] ():
literal[string]
identifier[first_weekday] = literal[int]
keyword[try] :
identifier[process] = identifier[os] . identifier[popen] ( literal[string] )
identifier[week_offset] , identifier[week_start] = identifier[process] . identifier... | def locale_first_weekday():
"""figure if week starts on monday or sunday"""
first_weekday = 6 #by default settle on monday
try:
process = os.popen('locale first_weekday week-1stday')
(week_offset, week_start) = process.read().split('\n')[:2]
process.close()
week_start = dt.d... |
def clean():
"""remove build artifacts"""
shutil.rmtree('{PROJECT_NAME}.egg-info'.format(PROJECT_NAME=PROJECT_NAME), ignore_errors=True)
shutil.rmtree('build', ignore_errors=True)
shutil.rmtree('dist', ignore_errors=True)
shutil.rmtree('htmlcov', ignore_errors=True)
shutil.rmtree('__pycache__', ... | def function[clean, parameter[]]:
constant[remove build artifacts]
call[name[shutil].rmtree, parameter[call[constant[{PROJECT_NAME}.egg-info].format, parameter[]]]]
call[name[shutil].rmtree, parameter[constant[build]]]
call[name[shutil].rmtree, parameter[constant[dist]]]
call[nam... | keyword[def] identifier[clean] ():
literal[string]
identifier[shutil] . identifier[rmtree] ( literal[string] . identifier[format] ( identifier[PROJECT_NAME] = identifier[PROJECT_NAME] ), identifier[ignore_errors] = keyword[True] )
identifier[shutil] . identifier[rmtree] ( literal[string] , identifier[... | def clean():
"""remove build artifacts"""
shutil.rmtree('{PROJECT_NAME}.egg-info'.format(PROJECT_NAME=PROJECT_NAME), ignore_errors=True)
shutil.rmtree('build', ignore_errors=True)
shutil.rmtree('dist', ignore_errors=True)
shutil.rmtree('htmlcov', ignore_errors=True)
shutil.rmtree('__pycache__', ... |
def safe(self, parentheses=True):
"""
Returns a string representation with special characters
replaced by safer characters for use in file names.
"""
if not self:
return ""
string = str(self)
string = string.replace("**", "_pow_")
string = stri... | def function[safe, parameter[self, parentheses]]:
constant[
Returns a string representation with special characters
replaced by safer characters for use in file names.
]
if <ast.UnaryOp object at 0x7da1b11bf220> begin[:]
return[constant[]]
variable[string] assign[... | keyword[def] identifier[safe] ( identifier[self] , identifier[parentheses] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] :
keyword[return] literal[string]
identifier[string] = identifier[str] ( identifier[self] )
identifier[string] =... | def safe(self, parentheses=True):
"""
Returns a string representation with special characters
replaced by safer characters for use in file names.
"""
if not self:
return '' # depends on [control=['if'], data=[]]
string = str(self)
string = string.replace('**', '_pow_')
... |
def maybe_rate_limit(client, headers, atexit=False):
"""Optionally pause the process based on suggested rate interval."""
# pylint: disable=fixme
# pylint: disable=global-statement
# FIXME: Yes, I know this is not great. We'll fix it later. :-)
global LAST_CLIENT, LAST_HEADERS
if LAST_CLIENT an... | def function[maybe_rate_limit, parameter[client, headers, atexit]]:
constant[Optionally pause the process based on suggested rate interval.]
<ast.Global object at 0x7da1b19c0d30>
if <ast.BoolOp object at 0x7da1b19c0490> begin[:]
call[name[rate_limit], parameter[name[LAST_CLIENT], nam... | keyword[def] identifier[maybe_rate_limit] ( identifier[client] , identifier[headers] , identifier[atexit] = keyword[False] ):
literal[string]
keyword[global] identifier[LAST_CLIENT] , identifier[LAST_HEADERS]
keyword[if] identifier[LAST_CLIENT] keyword[and] identifier[LAST_HEADERS... | def maybe_rate_limit(client, headers, atexit=False):
"""Optionally pause the process based on suggested rate interval."""
# pylint: disable=fixme
# pylint: disable=global-statement
# FIXME: Yes, I know this is not great. We'll fix it later. :-)
global LAST_CLIENT, LAST_HEADERS
if LAST_CLIENT and... |
async def rename(self, name):
"""Rename this conversation.
Hangouts only officially supports renaming group conversations, so
custom names for one-to-one conversations may or may not appear in all
first party clients.
Args:
name (str): New name.
Raises:
... | <ast.AsyncFunctionDef object at 0x7da20c6c5210> | keyword[async] keyword[def] identifier[rename] ( identifier[self] , identifier[name] ):
literal[string]
keyword[await] identifier[self] . identifier[_client] . identifier[rename_conversation] (
identifier[hangouts_pb2] . identifier[RenameConversationRequest] (
identifier[request... | async def rename(self, name):
"""Rename this conversation.
Hangouts only officially supports renaming group conversations, so
custom names for one-to-one conversations may or may not appear in all
first party clients.
Args:
name (str): New name.
Raises:
... |
def assign_complex_to_samples(items):
"""Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach he... | def function[assign_complex_to_samples, parameter[items]]:
constant[Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
... | keyword[def] identifier[assign_complex_to_samples] ( identifier[items] ):
literal[string]
identifier[extract_fns] ={( literal[string] , literal[string] ): identifier[_get_vcf_samples] ,
( literal[string] ,): identifier[_get_bam_samples] }
identifier[complex] ={ identifier[k] :{} keyword[for] iden... | def assign_complex_to_samples(items):
"""Assign complex inputs like variants and align outputs to samples.
Handles list inputs to record conversion where we have inputs from multiple
locations and need to ensure they are properly assigned to samples in many
environments.
The unpleasant approach he... |
def auto_cleaned_path_uuid4(instance, filename: str) -> str:
"""
Gets upload path in this format: {MODEL_NAME}/{SAFE_UPLOADED_FILENAME}{SEPARATOR}{UUID4}{SUFFIX}.
Use this function to prevent any collisions with existing files in same folder.
:param instance: Instance of model or model class.
:para... | def function[auto_cleaned_path_uuid4, parameter[instance, filename]]:
constant[
Gets upload path in this format: {MODEL_NAME}/{SAFE_UPLOADED_FILENAME}{SEPARATOR}{UUID4}{SUFFIX}.
Use this function to prevent any collisions with existing files in same folder.
:param instance: Instance of model or mod... | keyword[def] identifier[auto_cleaned_path_uuid4] ( identifier[instance] , identifier[filename] : identifier[str] )-> identifier[str] :
literal[string]
identifier[stem] , identifier[suffix] = identifier[parse_filename] ( identifier[filename] )
identifier[base_dir] = identifier[get_base_dir_from_object]... | def auto_cleaned_path_uuid4(instance, filename: str) -> str:
"""
Gets upload path in this format: {MODEL_NAME}/{SAFE_UPLOADED_FILENAME}{SEPARATOR}{UUID4}{SUFFIX}.
Use this function to prevent any collisions with existing files in same folder.
:param instance: Instance of model or model class.
:para... |
def _byte_pad(data, bound=4):
"""
GLTF wants chunks aligned with 4- byte boundaries
so this function will add padding to the end of a
chunk of bytes so that it aligns with a specified
boundary size
Parameters
--------------
data : bytes
Data to be padded
bound : int
Leng... | def function[_byte_pad, parameter[data, bound]]:
constant[
GLTF wants chunks aligned with 4- byte boundaries
so this function will add padding to the end of a
chunk of bytes so that it aligns with a specified
boundary size
Parameters
--------------
data : bytes
Data to be padd... | keyword[def] identifier[_byte_pad] ( identifier[data] , identifier[bound] = literal[int] ):
literal[string]
identifier[bound] = identifier[int] ( identifier[bound] )
keyword[if] identifier[len] ( identifier[data] )% identifier[bound] != literal[int] :
identifier[pad] = identifier[bytes] ( id... | def _byte_pad(data, bound=4):
"""
GLTF wants chunks aligned with 4- byte boundaries
so this function will add padding to the end of a
chunk of bytes so that it aligns with a specified
boundary size
Parameters
--------------
data : bytes
Data to be padded
bound : int
Leng... |
def run_experiment(self):
"""Sign up, run the ``participate`` method, then sign off and close
the driver."""
try:
self.sign_up()
self.participate()
if self.sign_off():
self.complete_experiment("worker_complete")
else:
... | def function[run_experiment, parameter[self]]:
constant[Sign up, run the ``participate`` method, then sign off and close
the driver.]
<ast.Try object at 0x7da1b0380910> | keyword[def] identifier[run_experiment] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[sign_up] ()
identifier[self] . identifier[participate] ()
keyword[if] identifier[self] . identifier[sign_off] ():
ident... | def run_experiment(self):
"""Sign up, run the ``participate`` method, then sign off and close
the driver."""
try:
self.sign_up()
self.participate()
if self.sign_off():
self.complete_experiment('worker_complete') # depends on [control=['if'], data=[]]
else:
... |
def get_likes(self, offset=0, limit=50):
""" Get user's likes. """
response = self.client.get(
self.client.USER_LIKES % (self.name, offset, limit))
return self._parse_response(response, strack) | def function[get_likes, parameter[self, offset, limit]]:
constant[ Get user's likes. ]
variable[response] assign[=] call[name[self].client.get, parameter[binary_operation[name[self].client.USER_LIKES <ast.Mod object at 0x7da2590d6920> tuple[[<ast.Attribute object at 0x7da1b0a84cd0>, <ast.Name object at ... | keyword[def] identifier[get_likes] ( identifier[self] , identifier[offset] = literal[int] , identifier[limit] = literal[int] ):
literal[string]
identifier[response] = identifier[self] . identifier[client] . identifier[get] (
identifier[self] . identifier[client] . identifier[USER_LIKES] %(... | def get_likes(self, offset=0, limit=50):
""" Get user's likes. """
response = self.client.get(self.client.USER_LIKES % (self.name, offset, limit))
return self._parse_response(response, strack) |
def __update_paths(self, settings):
"""
Set custom paths if necessary
"""
if not isinstance(settings, dict):
return
if 'custom_base_path' in settings:
base_path = settings['custom_base_path']
base_path = join(dirname(__file__), base_path)
... | def function[__update_paths, parameter[self, settings]]:
constant[
Set custom paths if necessary
]
if <ast.UnaryOp object at 0x7da1b19509a0> begin[:]
return[None]
if compare[constant[custom_base_path] in name[settings]] begin[:]
variable[base_path] assign[... | keyword[def] identifier[__update_paths] ( identifier[self] , identifier[settings] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[settings] , identifier[dict] ):
keyword[return]
keyword[if] literal[string] keyword[in] identifier[settings]... | def __update_paths(self, settings):
"""
Set custom paths if necessary
"""
if not isinstance(settings, dict):
return # depends on [control=['if'], data=[]]
if 'custom_base_path' in settings:
base_path = settings['custom_base_path']
base_path = join(dirname(__file__), ... |
def vbreak(image, mask=None, iterations=1):
'''Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1
'''
global vbreak_table
if mask is None:
masked_image = image
else:
masked_image = image.astype(bool).copy()
masked_image[... | def function[vbreak, parameter[image, mask, iterations]]:
constant[Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1
]
<ast.Global object at 0x7da20c6e7e80>
if compare[name[mask] is constant[None]] begin[:]
variable[masked_... | keyword[def] identifier[vbreak] ( identifier[image] , identifier[mask] = keyword[None] , identifier[iterations] = literal[int] ):
literal[string]
keyword[global] identifier[vbreak_table]
keyword[if] identifier[mask] keyword[is] keyword[None] :
identifier[masked_image] = identifier[image]... | def vbreak(image, mask=None, iterations=1):
"""Remove horizontal breaks
1 1 1 1 1 1
0 1 0 -> 0 0 0 (this case only)
1 1 1 1 1 1
"""
global vbreak_table
if mask is None:
masked_image = image # depends on [control=['if'], data=[]]
else:
masked_image = image.a... |
def status(self, external_id, **params):
"""
Retrieves the verification result for an App Verify transaction by external_id. To ensure a secure verification
flow you must check the status using TeleSign's servers on your backend. Do not rely on the SDK alone to
indicate a successful veri... | def function[status, parameter[self, external_id]]:
constant[
Retrieves the verification result for an App Verify transaction by external_id. To ensure a secure verification
flow you must check the status using TeleSign's servers on your backend. Do not rely on the SDK alone to
indicate ... | keyword[def] identifier[status] ( identifier[self] , identifier[external_id] ,** identifier[params] ):
literal[string]
keyword[return] identifier[self] . identifier[get] ( identifier[APPVERIFY_STATUS_RESOURCE] . identifier[format] ( identifier[external_id] = identifier[external_id] ),
** i... | def status(self, external_id, **params):
"""
Retrieves the verification result for an App Verify transaction by external_id. To ensure a secure verification
flow you must check the status using TeleSign's servers on your backend. Do not rely on the SDK alone to
indicate a successful verifica... |
def read_config():
""" Read the configuration file and parse the different environments.
Returns: ConfigParser object
"""
if not os.path.isfile(CONFIG):
with open(CONFIG, "w"):
pass
parser = ConfigParser()
parser.read(CONFIG)
return parser | def function[read_config, parameter[]]:
constant[ Read the configuration file and parse the different environments.
Returns: ConfigParser object
]
if <ast.UnaryOp object at 0x7da20e954a30> begin[:]
with call[name[open], parameter[name[CONFIG], constant[w]]] begin[:]
... | keyword[def] identifier[read_config] ():
literal[string]
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( identifier[CONFIG] ):
keyword[with] identifier[open] ( identifier[CONFIG] , literal[string] ):
keyword[pass]
identifier[parser] = identi... | def read_config():
""" Read the configuration file and parse the different environments.
Returns: ConfigParser object
"""
if not os.path.isfile(CONFIG):
with open(CONFIG, 'w'):
pass # depends on [control=['with'], data=[]] # depends on [control=['if'], data=[]]
parser = Co... |
def set_end_date(self, date):
"""Sets the end date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null``
*compliance: mand... | def function[set_end_date, parameter[self, date]]:
constant[Sets the end date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null`... | keyword[def] identifier[set_end_date] ( identifier[self] , identifier[date] ):
literal[string]
keyword[if] identifier[self] . identifier[get_end_date_metadata] (). identifier[is_read_only] ():
keyword[raise] identifier[errors] . identifier[NoAccess] ()
keyword[if] keyword[n... | def set_end_date(self, date):
"""Sets the end date.
arg: date (osid.calendaring.DateTime): the new date
raise: InvalidArgument - ``date`` is invalid
raise: NoAccess - ``Metadata.isReadOnly()`` is ``true``
raise: NullArgument - ``date`` is ``null``
*compliance: mandator... |
def get_completions(self, document, complete_event):
# Get word/text before cursor.
if self.sentence:
word_before_cursor = document.text_before_cursor
else:
word_before_cursor = document.get_word_before_cursor(WORD=self.WORD)
if self.ignore_case:
word... | def function[get_completions, parameter[self, document, complete_event]]:
if name[self].sentence begin[:]
variable[word_before_cursor] assign[=] name[document].text_before_cursor
if name[self].ignore_case begin[:]
variable[word_before_cursor] assign[=] call[name[word_befo... | keyword[def] identifier[get_completions] ( identifier[self] , identifier[document] , identifier[complete_event] ):
keyword[if] identifier[self] . identifier[sentence] :
identifier[word_before_cursor] = identifier[document] . identifier[text_before_cursor]
keyword[else] :
... | def get_completions(self, document, complete_event):
# Get word/text before cursor.
if self.sentence:
word_before_cursor = document.text_before_cursor # depends on [control=['if'], data=[]]
else:
word_before_cursor = document.get_word_before_cursor(WORD=self.WORD)
if self.ignore_case:
... |
def list(self, **params):
"""
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which repres... | def function[list, parameter[self]]:
constant[
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style acc... | keyword[def] identifier[list] ( identifier[self] ,** identifier[params] ):
literal[string]
identifier[_] , identifier[_] , identifier[text_messages] = identifier[self] . identifier[http_client] . identifier[get] ( literal[string] , identifier[params] = identifier[params] )
keyword[return]... | def list(self, **params):
"""
Retrieve text messages
Returns Text Messages, according to the parameters provided
:calls: ``get /text_messages``
:param dict params: (optional) Search options.
:return: List of dictionaries that support attriubte-style access, which represent ... |
def load_log(args):
"""Load a `logging.Logger` object.
Arguments
---------
args : `argparse.Namespace` object
Namespace containing required settings:
{`args.debug`, `args.verbose`, and `args.log_filename`}.
Returns
-------
log : `logging.Logger` object
"""
from ast... | def function[load_log, parameter[args]]:
constant[Load a `logging.Logger` object.
Arguments
---------
args : `argparse.Namespace` object
Namespace containing required settings:
{`args.debug`, `args.verbose`, and `args.log_filename`}.
Returns
-------
log : `logging.Logge... | keyword[def] identifier[load_log] ( identifier[args] ):
literal[string]
keyword[from] identifier[astrocats] . identifier[catalog] . identifier[utils] keyword[import] identifier[logger]
identifier[log_stream_level] = keyword[None]
keyword[if] identifier[args] . identifier[debug] :
... | def load_log(args):
"""Load a `logging.Logger` object.
Arguments
---------
args : `argparse.Namespace` object
Namespace containing required settings:
{`args.debug`, `args.verbose`, and `args.log_filename`}.
Returns
-------
log : `logging.Logger` object
"""
from ast... |
def timer(self, stat, tags=None):
"""Contextmanager for easily computing timings.
:arg string stat: A period delimited alphanumeric key.
:arg list-of-strings tags: Each string in the tag consists of a key and
a value separated by a colon. Tags can make it easier to break down
... | def function[timer, parameter[self, stat, tags]]:
constant[Contextmanager for easily computing timings.
:arg string stat: A period delimited alphanumeric key.
:arg list-of-strings tags: Each string in the tag consists of a key and
a value separated by a colon. Tags can make it easi... | keyword[def] identifier[timer] ( identifier[self] , identifier[stat] , identifier[tags] = keyword[None] ):
literal[string]
keyword[if] identifier[six] . identifier[PY3] :
identifier[start_time] = identifier[time] . identifier[perf_counter] ()
keyword[else] :
iden... | def timer(self, stat, tags=None):
"""Contextmanager for easily computing timings.
:arg string stat: A period delimited alphanumeric key.
:arg list-of-strings tags: Each string in the tag consists of a key and
a value separated by a colon. Tags can make it easier to break down
... |
def param_load(self):
"""
Queries the server for the parameter information and other metadata associated with
this task
"""
escaped_uri = urllib.parse.quote(self.uri)
request = urllib.request.Request(self.server_data.url + '/rest/v1/tasks/' + escaped_uri)
if self.... | def function[param_load, parameter[self]]:
constant[
Queries the server for the parameter information and other metadata associated with
this task
]
variable[escaped_uri] assign[=] call[name[urllib].parse.quote, parameter[name[self].uri]]
variable[request] assign[=] call[... | keyword[def] identifier[param_load] ( identifier[self] ):
literal[string]
identifier[escaped_uri] = identifier[urllib] . identifier[parse] . identifier[quote] ( identifier[self] . identifier[uri] )
identifier[request] = identifier[urllib] . identifier[request] . identifier[Request] ( ident... | def param_load(self):
"""
Queries the server for the parameter information and other metadata associated with
this task
"""
escaped_uri = urllib.parse.quote(self.uri)
request = urllib.request.Request(self.server_data.url + '/rest/v1/tasks/' + escaped_uri)
if self.server_data.auth... |
def configure(self, *args, **kwargs):
"""Configures a SWAG manager. Overrides existing configuration."""
self.version = kwargs['schema_version']
self.namespace = kwargs['namespace']
self.backend = get(kwargs['type'])(*args, **kwargs)
self.context = kwargs.pop('schema_context', {... | def function[configure, parameter[self]]:
constant[Configures a SWAG manager. Overrides existing configuration.]
name[self].version assign[=] call[name[kwargs]][constant[schema_version]]
name[self].namespace assign[=] call[name[kwargs]][constant[namespace]]
name[self].backend assign[=] c... | keyword[def] identifier[configure] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self] . identifier[version] = identifier[kwargs] [ literal[string] ]
identifier[self] . identifier[namespace] = identifier[kwargs] [ literal[string] ]
id... | def configure(self, *args, **kwargs):
"""Configures a SWAG manager. Overrides existing configuration."""
self.version = kwargs['schema_version']
self.namespace = kwargs['namespace']
self.backend = get(kwargs['type'])(*args, **kwargs)
self.context = kwargs.pop('schema_context', {}) |
def splitDataset(dataset, groupby):
"""
Split the given dataset into multiple datasets grouped by the given groupby
function. For example::
# Split mnist dataset into 10 datasets, one dataset for each label
splitDataset(mnist, groupby=lambda x: x[1])
# Split mnist dataset into 5 datasets, one ... | def function[splitDataset, parameter[dataset, groupby]]:
constant[
Split the given dataset into multiple datasets grouped by the given groupby
function. For example::
# Split mnist dataset into 10 datasets, one dataset for each label
splitDataset(mnist, groupby=lambda x: x[1])
# Split mn... | keyword[def] identifier[splitDataset] ( identifier[dataset] , identifier[groupby] ):
literal[string]
identifier[indicesByGroup] = identifier[collections] . identifier[defaultdict] ( identifier[list] )
keyword[for] identifier[k] , identifier[g] keyword[in] identifier[itertools] . identifier[groupby] (... | def splitDataset(dataset, groupby):
"""
Split the given dataset into multiple datasets grouped by the given groupby
function. For example::
# Split mnist dataset into 10 datasets, one dataset for each label
splitDataset(mnist, groupby=lambda x: x[1])
# Split mnist dataset into 5 datasets, on... |
def matrix_from_basis_coefficients(expansion: value.LinearDict[str],
basis: Dict[str, np.ndarray]) -> np.ndarray:
"""Computes linear combination of basis vectors with given coefficients."""
some_element = next(iter(basis.values()))
result = np.zeros_like(some_element, dtyp... | def function[matrix_from_basis_coefficients, parameter[expansion, basis]]:
constant[Computes linear combination of basis vectors with given coefficients.]
variable[some_element] assign[=] call[name[next], parameter[call[name[iter], parameter[call[name[basis].values, parameter[]]]]]]
variable[res... | keyword[def] identifier[matrix_from_basis_coefficients] ( identifier[expansion] : identifier[value] . identifier[LinearDict] [ identifier[str] ],
identifier[basis] : identifier[Dict] [ identifier[str] , identifier[np] . identifier[ndarray] ])-> identifier[np] . identifier[ndarray] :
literal[string]
identi... | def matrix_from_basis_coefficients(expansion: value.LinearDict[str], basis: Dict[str, np.ndarray]) -> np.ndarray:
"""Computes linear combination of basis vectors with given coefficients."""
some_element = next(iter(basis.values()))
result = np.zeros_like(some_element, dtype=np.complex128)
for (name, coe... |
def rename_channels(self, *, verbose=True, **kwargs):
"""Rename a set of channels.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
verbose : boolean (optional)
Toggle talkback. Default is True
"""
# ensure that it... | def function[rename_channels, parameter[self]]:
constant[Rename a set of channels.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
verbose : boolean (optional)
Toggle talkback. Default is True
]
variable[changed] ... | keyword[def] identifier[rename_channels] ( identifier[self] ,*, identifier[verbose] = keyword[True] ,** identifier[kwargs] ):
literal[string]
identifier[changed] = identifier[kwargs] . identifier[keys] ()
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[kwargs]... | def rename_channels(self, *, verbose=True, **kwargs):
"""Rename a set of channels.
Parameters
----------
kwargs
Keyword arguments of the form current:'new'.
verbose : boolean (optional)
Toggle talkback. Default is True
"""
# ensure that items will... |
def parse_blocks(lines): # type: (List[str]) -> List[List[str]]
"""Parse and return all possible blocks, popping off the start of `lines`.
:param lines: list of lines
:return: list of blocks, where each block is a list of lines
"""
blocks = []
while lines:
if lines[0] == '':
... | def function[parse_blocks, parameter[lines]]:
constant[Parse and return all possible blocks, popping off the start of `lines`.
:param lines: list of lines
:return: list of blocks, where each block is a list of lines
]
variable[blocks] assign[=] list[[]]
while name[lines] begin[:]
... | keyword[def] identifier[parse_blocks] ( identifier[lines] ):
literal[string]
identifier[blocks] =[]
keyword[while] identifier[lines] :
keyword[if] identifier[lines] [ literal[int] ]== literal[string] :
identifier[lines] . identifier[pop] ( literal[int] )
keyword[else]... | def parse_blocks(lines): # type: (List[str]) -> List[List[str]]
'Parse and return all possible blocks, popping off the start of `lines`.\n\n :param lines: list of lines\n :return: list of blocks, where each block is a list of lines\n '
blocks = []
while lines:
if lines[0] == '':
... |
def getEvents(self, min_nr=1, nr=None, timeout=None):
"""
Returns a list of event data from submitted IO blocks.
min_nr (int, None)
When timeout is None, minimum number of events to collect before
returning.
If None, waits for all submitted events.
nr... | def function[getEvents, parameter[self, min_nr, nr, timeout]]:
constant[
Returns a list of event data from submitted IO blocks.
min_nr (int, None)
When timeout is None, minimum number of events to collect before
returning.
If None, waits for all submitted eve... | keyword[def] identifier[getEvents] ( identifier[self] , identifier[min_nr] = literal[int] , identifier[nr] = keyword[None] , identifier[timeout] = keyword[None] ):
literal[string]
keyword[if] identifier[min_nr] keyword[is] keyword[None] :
identifier[min_nr] = identifier[len] ( ident... | def getEvents(self, min_nr=1, nr=None, timeout=None):
"""
Returns a list of event data from submitted IO blocks.
min_nr (int, None)
When timeout is None, minimum number of events to collect before
returning.
If None, waits for all submitted events.
nr (in... |
def play_Track(self, track, channel=1, bpm=120):
"""Play a Track object."""
self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel'
: channel, 'bpm': bpm})
for bar in track:
res = self.play_Bar(bar, channel, bpm)
if res != {}:
... | def function[play_Track, parameter[self, track, channel, bpm]]:
constant[Play a Track object.]
call[name[self].notify_listeners, parameter[name[self].MSG_PLAY_TRACK, dictionary[[<ast.Constant object at 0x7da1b1304700>, <ast.Constant object at 0x7da1b1306fb0>, <ast.Constant object at 0x7da1b1307a30>], [<... | keyword[def] identifier[play_Track] ( identifier[self] , identifier[track] , identifier[channel] = literal[int] , identifier[bpm] = literal[int] ):
literal[string]
identifier[self] . identifier[notify_listeners] ( identifier[self] . identifier[MSG_PLAY_TRACK] ,{ literal[string] : identifier[track] ... | def play_Track(self, track, channel=1, bpm=120):
"""Play a Track object."""
self.notify_listeners(self.MSG_PLAY_TRACK, {'track': track, 'channel': channel, 'bpm': bpm})
for bar in track:
res = self.play_Bar(bar, channel, bpm)
if res != {}:
bpm = res['bpm'] # depends on [control=... |
def GetMemMappedMB(self):
'''Retrieves the amount of memory that is allocated to the virtual machine.
Memory that is ballooned, swapped, or has never been accessed is
excluded.'''
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemMappedMB(self.handle.value, byref(counter... | def function[GetMemMappedMB, parameter[self]]:
constant[Retrieves the amount of memory that is allocated to the virtual machine.
Memory that is ballooned, swapped, or has never been accessed is
excluded.]
variable[counter] assign[=] call[name[c_uint], parameter[]]
variable[... | keyword[def] identifier[GetMemMappedMB] ( identifier[self] ):
literal[string]
identifier[counter] = identifier[c_uint] ()
identifier[ret] = identifier[vmGuestLib] . identifier[VMGuestLib_GetMemMappedMB] ( identifier[self] . identifier[handle] . identifier[value] , identifier[byref] ( ident... | def GetMemMappedMB(self):
"""Retrieves the amount of memory that is allocated to the virtual machine.
Memory that is ballooned, swapped, or has never been accessed is
excluded."""
counter = c_uint()
ret = vmGuestLib.VMGuestLib_GetMemMappedMB(self.handle.value, byref(counter))
if re... |
def clamp(color, min_v, max_v):
"""
Clamps a color such that the value is between min_v and max_v.
"""
h, s, v = rgb_to_hsv(*map(down_scale, color))
min_v, max_v = map(down_scale, (min_v, max_v))
v = min(max(min_v, v), max_v)
return tuple(map(up_scale, hsv_to_rgb(h, s, v))) | def function[clamp, parameter[color, min_v, max_v]]:
constant[
Clamps a color such that the value is between min_v and max_v.
]
<ast.Tuple object at 0x7da18dc99de0> assign[=] call[name[rgb_to_hsv], parameter[<ast.Starred object at 0x7da18dc9b400>]]
<ast.Tuple object at 0x7da18dc997e0> as... | keyword[def] identifier[clamp] ( identifier[color] , identifier[min_v] , identifier[max_v] ):
literal[string]
identifier[h] , identifier[s] , identifier[v] = identifier[rgb_to_hsv] (* identifier[map] ( identifier[down_scale] , identifier[color] ))
identifier[min_v] , identifier[max_v] = identifier[map... | def clamp(color, min_v, max_v):
"""
Clamps a color such that the value is between min_v and max_v.
"""
(h, s, v) = rgb_to_hsv(*map(down_scale, color))
(min_v, max_v) = map(down_scale, (min_v, max_v))
v = min(max(min_v, v), max_v)
return tuple(map(up_scale, hsv_to_rgb(h, s, v))) |
def show(cls, msg=None):
"""
Show the log interface on the page.
"""
if msg:
cls.add(msg)
cls.overlay.show()
cls.overlay.el.bind("click", lambda x: cls.hide())
cls.el.style.display = "block"
cls.bind() | def function[show, parameter[cls, msg]]:
constant[
Show the log interface on the page.
]
if name[msg] begin[:]
call[name[cls].add, parameter[name[msg]]]
call[name[cls].overlay.show, parameter[]]
call[name[cls].overlay.el.bind, parameter[constant[click], <a... | keyword[def] identifier[show] ( identifier[cls] , identifier[msg] = keyword[None] ):
literal[string]
keyword[if] identifier[msg] :
identifier[cls] . identifier[add] ( identifier[msg] )
identifier[cls] . identifier[overlay] . identifier[show] ()
identifier[cls] . ide... | def show(cls, msg=None):
"""
Show the log interface on the page.
"""
if msg:
cls.add(msg) # depends on [control=['if'], data=[]]
cls.overlay.show()
cls.overlay.el.bind('click', lambda x: cls.hide())
cls.el.style.display = 'block'
cls.bind() |
def delete(ctx, opts, owner_repo_identifier, yes):
"""
Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your... | def function[delete, parameter[ctx, opts, owner_repo_identifier, yes]]:
constant[
Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
... | keyword[def] identifier[delete] ( identifier[ctx] , identifier[opts] , identifier[owner_repo_identifier] , identifier[yes] ):
literal[string]
identifier[owner] , identifier[repo] , identifier[identifier] = identifier[owner_repo_identifier]
identifier[delete_args] ={
literal[string] : identifier... | def delete(ctx, opts, owner_repo_identifier, yes):
"""
Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your... |
def make_movie(structures, output_filename="movie.mp4", zoom=1.0, fps=20,
bitrate="10000k", quality=1, **kwargs):
"""
Generate a movie from a sequence of structures using vtk and ffmpeg.
Args:
structures ([Structure]): sequence of structures
output_filename (str): filename fo... | def function[make_movie, parameter[structures, output_filename, zoom, fps, bitrate, quality]]:
constant[
Generate a movie from a sequence of structures using vtk and ffmpeg.
Args:
structures ([Structure]): sequence of structures
output_filename (str): filename for structure output. defa... | keyword[def] identifier[make_movie] ( identifier[structures] , identifier[output_filename] = literal[string] , identifier[zoom] = literal[int] , identifier[fps] = literal[int] ,
identifier[bitrate] = literal[string] , identifier[quality] = literal[int] ,** identifier[kwargs] ):
literal[string]
identifier[... | def make_movie(structures, output_filename='movie.mp4', zoom=1.0, fps=20, bitrate='10000k', quality=1, **kwargs):
"""
Generate a movie from a sequence of structures using vtk and ffmpeg.
Args:
structures ([Structure]): sequence of structures
output_filename (str): filename for structure out... |
def query_alternative_short_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CV... | def function[query_alternative_short_name, parameter[]]:
constant[
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative... | keyword[def] identifier[query_alternative_short_name] ():
literal[string]
identifier[args] = identifier[get_args] (
identifier[request_args] = identifier[request] . identifier[args] ,
identifier[allowed_str_args] =[ literal[string] , literal[string] ],
identifier[allowed_int_args] =[ litera... | def query_alternative_short_name():
"""
Returns list of alternative short name by query query parameters
---
tags:
- Query functions
parameters:
- name: name
in: query
type: string
required: false
description: Alternative short name
default: CV... |
def rpoplpush(self, source, destination):
"""Emulate rpoplpush"""
transfer_item = self.rpop(source)
if transfer_item is not None:
self.lpush(destination, transfer_item)
return transfer_item | def function[rpoplpush, parameter[self, source, destination]]:
constant[Emulate rpoplpush]
variable[transfer_item] assign[=] call[name[self].rpop, parameter[name[source]]]
if compare[name[transfer_item] is_not constant[None]] begin[:]
call[name[self].lpush, parameter[name[destina... | keyword[def] identifier[rpoplpush] ( identifier[self] , identifier[source] , identifier[destination] ):
literal[string]
identifier[transfer_item] = identifier[self] . identifier[rpop] ( identifier[source] )
keyword[if] identifier[transfer_item] keyword[is] keyword[not] keyword[None] :
... | def rpoplpush(self, source, destination):
"""Emulate rpoplpush"""
transfer_item = self.rpop(source)
if transfer_item is not None:
self.lpush(destination, transfer_item) # depends on [control=['if'], data=['transfer_item']]
return transfer_item |
def list(self, device=values.unset, sim=values.unset, status=values.unset,
direction=values.unset, limit=None, page_size=None):
"""
Lists CommandInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before... | def function[list, parameter[self, device, sim, status, direction, limit, page_size]]:
constant[
Lists CommandInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
:param unicode device: The ... | keyword[def] identifier[list] ( identifier[self] , identifier[device] = identifier[values] . identifier[unset] , identifier[sim] = identifier[values] . identifier[unset] , identifier[status] = identifier[values] . identifier[unset] ,
identifier[direction] = identifier[values] . identifier[unset] , identifier[limit] ... | def list(self, device=values.unset, sim=values.unset, status=values.unset, direction=values.unset, limit=None, page_size=None):
"""
Lists CommandInstance records from the API as a list.
Unlike stream(), this operation is eager and will load `limit` records into
memory before returning.
... |
def copy(self, source_path, dest_path, account=None, group_name=None):
"""Copy file from a path to another path. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
source_path(str): The path of the file to be copied.
dest_path(str): The d... | def function[copy, parameter[self, source_path, dest_path, account, group_name]]:
constant[Copy file from a path to another path. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
source_path(str): The path of the file to be copied.
dest... | keyword[def] identifier[copy] ( identifier[self] , identifier[source_path] , identifier[dest_path] , identifier[account] = keyword[None] , identifier[group_name] = keyword[None] ):
literal[string]
keyword[if] literal[string] keyword[not] keyword[in] identifier[source_path] keyword[and] litera... | def copy(self, source_path, dest_path, account=None, group_name=None):
"""Copy file from a path to another path. The azure url format is https://myaccount.blob.core.windows.net/mycontainer/myblob.
Args:
source_path(str): The path of the file to be copied.
dest_path(str): The desti... |
def show_management_certificate(kwargs=None, conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgo... | def function[show_management_certificate, parameter[kwargs, conn, call]]:
constant[
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \
... | keyword[def] identifier[show_management_certificate] ( identifier[kwargs] = keyword[None] , identifier[conn] = keyword[None] , identifier[call] = keyword[None] ):
literal[string]
keyword[if] identifier[call] != literal[string] :
keyword[raise] identifier[SaltCloudSystemExit] (
literal[s... | def show_management_certificate(kwargs=None, conn=None, call=None):
"""
.. versionadded:: 2015.8.0
Return information about a management_certificate
CLI Example:
.. code-block:: bash
salt-cloud -f get_management_certificate my-azure name=my_management_certificate \\
thumbalgo... |
def from_edge_pairs(cls, vertices, edge_pairs):
"""
Create a DirectedGraph from a collection of vertices
and a collection of pairs giving links between the vertices.
"""
vertices = set(vertices)
edges = set()
heads = {}
tails = {}
# Number the ed... | def function[from_edge_pairs, parameter[cls, vertices, edge_pairs]]:
constant[
Create a DirectedGraph from a collection of vertices
and a collection of pairs giving links between the vertices.
]
variable[vertices] assign[=] call[name[set], parameter[name[vertices]]]
vari... | keyword[def] identifier[from_edge_pairs] ( identifier[cls] , identifier[vertices] , identifier[edge_pairs] ):
literal[string]
identifier[vertices] = identifier[set] ( identifier[vertices] )
identifier[edges] = identifier[set] ()
identifier[heads] ={}
identifier[tails] ={}... | def from_edge_pairs(cls, vertices, edge_pairs):
"""
Create a DirectedGraph from a collection of vertices
and a collection of pairs giving links between the vertices.
"""
vertices = set(vertices)
edges = set()
heads = {}
tails = {}
# Number the edges arbitrarily.
edge... |
def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm p... | def function[set_message_last_post, parameter[cr, uid, pool, models]]:
constant[
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPE... | keyword[def] identifier[set_message_last_post] ( identifier[cr] , identifier[uid] , identifier[pool] , identifier[models] ):
literal[string]
keyword[if] identifier[type] ( identifier[models] ) keyword[is] keyword[not] identifier[list] :
identifier[models] =[ identifier[models] ]
keyword[fo... | def set_message_last_post(cr, uid, pool, models):
"""
Given a list of models, set their 'message_last_post' fields to an
estimated last post datetime.
To be called in post-migration scripts
:param cr: database cursor
:param uid: user id, assumed to be openerp.SUPERUSER_ID
:param pool: orm p... |
def write(self, path=None):
"""
Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts
"""
written_count = 0
comments_written = 0
blanks_written = 0
ipv4_entries_writt... | def function[write, parameter[self, path]]:
constant[
Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts
]
variable[written_count] assign[=] constant[0]
variable[comments_written]... | keyword[def] identifier[write] ( identifier[self] , identifier[path] = keyword[None] ):
literal[string]
identifier[written_count] = literal[int]
identifier[comments_written] = literal[int]
identifier[blanks_written] = literal[int]
identifier[ipv4_entries_written] = lit... | def write(self, path=None):
"""
Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts
"""
written_count = 0
comments_written = 0
blanks_written = 0
ipv4_entries_written = 0
ipv6_entr... |
def decode_string(data, encoding='hex'):
'''
Decode string
:param data: string to decode
:param encoding: encoding to use (default: 'hex')
:return: decoded string
'''
if six.PY2:
return data.decode(encoding)
else:
return codecs.decode(data.encode('ascii'), encoding) | def function[decode_string, parameter[data, encoding]]:
constant[
Decode string
:param data: string to decode
:param encoding: encoding to use (default: 'hex')
:return: decoded string
]
if name[six].PY2 begin[:]
return[call[name[data].decode, parameter[name[encoding]]]] | keyword[def] identifier[decode_string] ( identifier[data] , identifier[encoding] = literal[string] ):
literal[string]
keyword[if] identifier[six] . identifier[PY2] :
keyword[return] identifier[data] . identifier[decode] ( identifier[encoding] )
keyword[else] :
keyword[return] iden... | def decode_string(data, encoding='hex'):
"""
Decode string
:param data: string to decode
:param encoding: encoding to use (default: 'hex')
:return: decoded string
"""
if six.PY2:
return data.decode(encoding) # depends on [control=['if'], data=[]]
else:
return codecs.dec... |
def _get_all_group_items(network_id):
"""
Get all the resource group items in the network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id
"""
base_qry = db.DBSession.query(ResourceGroupItem)
item_qry = base_qry.join(Scenario).filter(Scenario.network_id==... | def function[_get_all_group_items, parameter[network_id]]:
constant[
Get all the resource group items in the network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id
]
variable[base_qry] assign[=] call[name[db].DBSession.query, parameter[name[ResourceG... | keyword[def] identifier[_get_all_group_items] ( identifier[network_id] ):
literal[string]
identifier[base_qry] = identifier[db] . identifier[DBSession] . identifier[query] ( identifier[ResourceGroupItem] )
identifier[item_qry] = identifier[base_qry] . identifier[join] ( identifier[Scenario] ). identi... | def _get_all_group_items(network_id):
"""
Get all the resource group items in the network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id
"""
base_qry = db.DBSession.query(ResourceGroupItem)
item_qry = base_qry.join(Scenario).filter(Scenario.network_id ==... |
async def destroy_tournament(self, t: Tournament):
""" completely removes a tournament from Challonge
|methcoro|
Note:
|from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care!
Raises:
APIException
"""
... | <ast.AsyncFunctionDef object at 0x7da2054a7e20> | keyword[async] keyword[def] identifier[destroy_tournament] ( identifier[self] , identifier[t] : identifier[Tournament] ):
literal[string]
keyword[await] identifier[self] . identifier[connection] ( literal[string] , literal[string] . identifier[format] ( identifier[t] . identifier[id] ))
... | async def destroy_tournament(self, t: Tournament):
""" completely removes a tournament from Challonge
|methcoro|
Note:
|from_api| Deletes a tournament along with all its associated records. There is no undo, so use with care!
Raises:
APIException
"""
a... |
def _setup(self):
"""
Prepare the system for using ``ansible-galaxy`` and returns None.
:return: None
"""
role_directory = os.path.join(self._config.scenario.directory,
self.options['roles-path'])
if not os.path.isdir(role_directory)... | def function[_setup, parameter[self]]:
constant[
Prepare the system for using ``ansible-galaxy`` and returns None.
:return: None
]
variable[role_directory] assign[=] call[name[os].path.join, parameter[name[self]._config.scenario.directory, call[name[self].options][constant[roles... | keyword[def] identifier[_setup] ( identifier[self] ):
literal[string]
identifier[role_directory] = identifier[os] . identifier[path] . identifier[join] ( identifier[self] . identifier[_config] . identifier[scenario] . identifier[directory] ,
identifier[self] . identifier[options] [ literal... | def _setup(self):
"""
Prepare the system for using ``ansible-galaxy`` and returns None.
:return: None
"""
role_directory = os.path.join(self._config.scenario.directory, self.options['roles-path'])
if not os.path.isdir(role_directory):
os.makedirs(role_directory) # depends o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.