code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT)
except TypeError:
hint = None # Variable was None, i.e. not set.
except ValueError... | def function[_pyqt4, parameter[]]:
constant[Initialise PyQt4]
import module[sip]
<ast.Try object at 0x7da1b18e7fd0>
for taget[name[api]] in starred[tuple[[<ast.Constant object at 0x7da1b18e5c90>, <ast.Constant object at 0x7da1b18e5900>, <ast.Constant object at 0x7da1b18e5930>, <ast.Constant obje... | keyword[def] identifier[_pyqt4] ():
literal[string]
keyword[import] identifier[sip]
keyword[try] :
identifier[hint] = identifier[int] ( identifier[QT_SIP_API_HINT] )
keyword[except] identifier[TypeError] :
identifier[hint] = keyword[None]
keyword[except] id... | def _pyqt4():
"""Initialise PyQt4"""
import sip
# Validation of envivornment variable. Prevents an error if
# the variable is invalid since it's just a hint.
try:
hint = int(QT_SIP_API_HINT) # depends on [control=['try'], data=[]]
except TypeError:
hint = None # Variable was No... |
def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN,
initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_ge... | def function[turtle_to_texture, parameter[turtle_program, turn_amount, initial_angle, resolution]]:
constant[Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_generator` for more details
... | keyword[def] identifier[turtle_to_texture] ( identifier[turtle_program] , identifier[turn_amount] = identifier[DEFAULT_TURN] ,
identifier[initial_angle] = identifier[DEFAULT_INITIAL_ANGLE] , identifier[resolution] = literal[int] ):
literal[string]
identifier[generator] = identifier[branching_turtle_genera... | def turtle_to_texture(turtle_program, turn_amount=DEFAULT_TURN, initial_angle=DEFAULT_INITIAL_ANGLE, resolution=1):
"""Makes a texture from a turtle program.
Args:
turtle_program (str): a string representing the turtle program; see the
docstring of `branching_turtle_generator` for more deta... |
def write(self, gpio, level):
"""
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
... | def function[write, parameter[self, gpio, level]]:
constant[
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi... | keyword[def] identifier[write] ( identifier[self] , identifier[gpio] , identifier[level] ):
literal[string]
identifier[res] = keyword[yield] keyword[from] identifier[self] . identifier[_pigpio_aio_command] ( identifier[_PI_CMD_WRITE] , identifier[gpio] , identifier[level] )
keyword[retur... | def write(self, gpio, level):
"""
Sets the gpio level.
gpio:= 0-53.
level:= 0, 1.
If PWM or servo pulses are active on the gpio they are
switched off.
...
pi.set_mode(17, pigpio.OUTPUT)
pi.write(17,0)
print(pi.read(17))
0
p... |
def get_og_image_url(self):
"""
:return: URL of the image to use in OG shares
"""
li = self.get_list_image()
if li:
from easy_thumbnails.files import get_thumbnailer
thumb_url = get_thumbnailer(li)['og_image'].url
# TODO: looks like this may fa... | def function[get_og_image_url, parameter[self]]:
constant[
:return: URL of the image to use in OG shares
]
variable[li] assign[=] call[name[self].get_list_image, parameter[]]
if name[li] begin[:]
from relative_module[easy_thumbnails.files] import module[get_thumbnailer]
... | keyword[def] identifier[get_og_image_url] ( identifier[self] ):
literal[string]
identifier[li] = identifier[self] . identifier[get_list_image] ()
keyword[if] identifier[li] :
keyword[from] identifier[easy_thumbnails] . identifier[files] keyword[import] identifier[get_thumb... | def get_og_image_url(self):
"""
:return: URL of the image to use in OG shares
"""
li = self.get_list_image()
if li:
from easy_thumbnails.files import get_thumbnailer
thumb_url = get_thumbnailer(li)['og_image'].url
# TODO: looks like this may fail if SITE_DOMAIN = "acm... |
async def consume_queue(self, subscriber: AbstractSubscriber) -> None:
"""
Subscribe to the queue consuming.
:param subscriber:
:return:
"""
queue_name = subscriber.name
topics = subscriber.requested_topics
if queue_name in self._known_queues:
... | <ast.AsyncFunctionDef object at 0x7da1b15d4160> | keyword[async] keyword[def] identifier[consume_queue] ( identifier[self] , identifier[subscriber] : identifier[AbstractSubscriber] )-> keyword[None] :
literal[string]
identifier[queue_name] = identifier[subscriber] . identifier[name]
identifier[topics] = identifier[subscriber] . identi... | async def consume_queue(self, subscriber: AbstractSubscriber) -> None:
"""
Subscribe to the queue consuming.
:param subscriber:
:return:
"""
queue_name = subscriber.name
topics = subscriber.requested_topics
if queue_name in self._known_queues:
raise exceptions.Co... |
def boolbox(msg="Shall I continue?"
, title=" "
, choices=("Yes","No")
, image=None
):
"""
Display a boolean msgbox.
The default is the first choice.
The returned value is calculated this way::
if the first choice is chosen, or if the dialog is cancelled:
returns 1
... | def function[boolbox, parameter[msg, title, choices, image]]:
constant[
Display a boolean msgbox.
The default is the first choice.
The returned value is calculated this way::
if the first choice is chosen, or if the dialog is cancelled:
returns 1
else:
retur... | keyword[def] identifier[boolbox] ( identifier[msg] = literal[string]
, identifier[title] = literal[string]
, identifier[choices] =( literal[string] , literal[string] )
, identifier[image] = keyword[None]
):
literal[string]
identifier[reply] = identifier[buttonbox] ( identifier[msg] = identifier[msg] , i... | def boolbox(msg='Shall I continue?', title=' ', choices=('Yes', 'No'), image=None):
"""
Display a boolean msgbox.
The default is the first choice.
The returned value is calculated this way::
if the first choice is chosen, or if the dialog is cancelled:
returns 1
else:
... |
def shareable(self, boolean):
"""Pass through helper function for flag function."""
if(boolean):
r = self.flag({
"flag": "make_shareable"
})
else:
r = self.flag({
"flag": "make_not_shareable"
})
r... | def function[shareable, parameter[self, boolean]]:
constant[Pass through helper function for flag function.]
if name[boolean] begin[:]
variable[r] assign[=] call[name[self].flag, parameter[dictionary[[<ast.Constant object at 0x7da18dc99fc0>], [<ast.Constant object at 0x7da18dc98b20>]]]]
... | keyword[def] identifier[shareable] ( identifier[self] , identifier[boolean] ):
literal[string]
keyword[if] ( identifier[boolean] ):
identifier[r] = identifier[self] . identifier[flag] ({
literal[string] : literal[string]
})
keyword[else] :
... | def shareable(self, boolean):
"""Pass through helper function for flag function."""
if boolean:
r = self.flag({'flag': 'make_shareable'}) # depends on [control=['if'], data=[]]
else:
r = self.flag({'flag': 'make_not_shareable'})
return r |
def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
url, _coerce_result = _coerce_args(url)
if '#' in url:
s, n, p, a, q, frag = urlpa... | def function[urldefrag, parameter[url]]:
constant[Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
]
<ast.Tuple object at 0x7da18bcc9000> assign[=] call[name[_coe... | keyword[def] identifier[urldefrag] ( identifier[url] ):
literal[string]
identifier[url] , identifier[_coerce_result] = identifier[_coerce_args] ( identifier[url] )
keyword[if] literal[string] keyword[in] identifier[url] :
identifier[s] , identifier[n] , identifier[p] , identifier[a] , iden... | def urldefrag(url):
"""Removes any existing fragment from URL.
Returns a tuple of the defragmented URL and the fragment. If
the URL contained no fragments, the second element is the
empty string.
"""
(url, _coerce_result) = _coerce_args(url)
if '#' in url:
(s, n, p, a, q, frag) = u... |
def get_repositories_by_composition(self, *args, **kwargs):
"""Pass through to provider CompositionRepositorySession.get_repositories_by_composition"""
# Implemented from kitosid template for -
# osid.resource.ResourceBinSession.get_bins_by_resource
catalogs = self._get_provider_session(... | def function[get_repositories_by_composition, parameter[self]]:
constant[Pass through to provider CompositionRepositorySession.get_repositories_by_composition]
variable[catalogs] assign[=] call[call[name[self]._get_provider_session, parameter[constant[composition_repository_session]]].get_repositories_b... | keyword[def] identifier[get_repositories_by_composition] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[catalogs] = identifier[self] . identifier[_get_provider_session] ( literal[string] ). identifier[get_repositories_by_composition] (*... | def get_repositories_by_composition(self, *args, **kwargs):
"""Pass through to provider CompositionRepositorySession.get_repositories_by_composition"""
# Implemented from kitosid template for -
# osid.resource.ResourceBinSession.get_bins_by_resource
catalogs = self._get_provider_session('composition_rep... |
def primary_key(self):
"""Returns either the primary key value, or a tuple containing the primary key values in the
case of a composite primary key.
"""
pkname = self.primary_key_name
if pkname is None:
return None
elif isinstance(pkname, str):
return getattr(self, pkname)
else:
... | def function[primary_key, parameter[self]]:
constant[Returns either the primary key value, or a tuple containing the primary key values in the
case of a composite primary key.
]
variable[pkname] assign[=] name[self].primary_key_name
if compare[name[pkname] is constant[None]] begin[:]
... | keyword[def] identifier[primary_key] ( identifier[self] ):
literal[string]
identifier[pkname] = identifier[self] . identifier[primary_key_name]
keyword[if] identifier[pkname] keyword[is] keyword[None] :
keyword[return] keyword[None]
keyword[elif] identifier[isinstance] ( identifier[... | def primary_key(self):
"""Returns either the primary key value, or a tuple containing the primary key values in the
case of a composite primary key.
"""
pkname = self.primary_key_name
if pkname is None:
return None # depends on [control=['if'], data=[]]
elif isinstance(pkname, str):
... |
def update_edges(self, elev_fn, dem_proc):
"""
After finishing a calculation, this will update the neighbors and the
todo for that tile
"""
interp = self.build_interpolator(dem_proc)
self.update_edge_todo(elev_fn, dem_proc)
self.set_neighbor_data(elev_fn, dem_proc... | def function[update_edges, parameter[self, elev_fn, dem_proc]]:
constant[
After finishing a calculation, this will update the neighbors and the
todo for that tile
]
variable[interp] assign[=] call[name[self].build_interpolator, parameter[name[dem_proc]]]
call[name[self].u... | keyword[def] identifier[update_edges] ( identifier[self] , identifier[elev_fn] , identifier[dem_proc] ):
literal[string]
identifier[interp] = identifier[self] . identifier[build_interpolator] ( identifier[dem_proc] )
identifier[self] . identifier[update_edge_todo] ( identifier[elev_fn] , i... | def update_edges(self, elev_fn, dem_proc):
"""
After finishing a calculation, this will update the neighbors and the
todo for that tile
"""
interp = self.build_interpolator(dem_proc)
self.update_edge_todo(elev_fn, dem_proc)
self.set_neighbor_data(elev_fn, dem_proc, interp) |
def compute_start_timeperiod(self, process_name, timeperiod):
""" computes lowest *inclusive* timeperiod boundary for job to process
for process with time_grouping == 1, it returns given timeperiod with no change
for process with time_grouping != 1, it computes first timeperiod, not proc... | def function[compute_start_timeperiod, parameter[self, process_name, timeperiod]]:
constant[ computes lowest *inclusive* timeperiod boundary for job to process
for process with time_grouping == 1, it returns given timeperiod with no change
for process with time_grouping != 1, it computes... | keyword[def] identifier[compute_start_timeperiod] ( identifier[self] , identifier[process_name] , identifier[timeperiod] ):
literal[string]
identifier[time_grouping] = identifier[context] . identifier[process_context] [ identifier[process_name] ]. identifier[time_grouping]
keyword[if] id... | def compute_start_timeperiod(self, process_name, timeperiod):
""" computes lowest *inclusive* timeperiod boundary for job to process
for process with time_grouping == 1, it returns given timeperiod with no change
for process with time_grouping != 1, it computes first timeperiod, not processe... |
def BuildFilterFindSpecs(
self, artifact_definitions_path, custom_artifacts_path,
knowledge_base_object, artifact_filter_names=None, filter_file_path=None):
"""Builds find specifications from artifacts or filter file if available.
Args:
artifact_definitions_path (str): path to artifact defini... | def function[BuildFilterFindSpecs, parameter[self, artifact_definitions_path, custom_artifacts_path, knowledge_base_object, artifact_filter_names, filter_file_path]]:
constant[Builds find specifications from artifacts or filter file if available.
Args:
artifact_definitions_path (str): path to artifac... | keyword[def] identifier[BuildFilterFindSpecs] (
identifier[self] , identifier[artifact_definitions_path] , identifier[custom_artifacts_path] ,
identifier[knowledge_base_object] , identifier[artifact_filter_names] = keyword[None] , identifier[filter_file_path] = keyword[None] ):
literal[string]
identifier... | def BuildFilterFindSpecs(self, artifact_definitions_path, custom_artifacts_path, knowledge_base_object, artifact_filter_names=None, filter_file_path=None):
"""Builds find specifications from artifacts or filter file if available.
Args:
artifact_definitions_path (str): path to artifact definitions file.
... |
def convert_to_coarse(data,chan_per_coarse):
'''
Converts a data array with length n_chans to an array of length n_coarse_chans
by averaging over the coarse channels
'''
#find number of coarse channels and reshape array
num_coarse = data.size/chan_per_coarse
data_shaped = np.array(np.reshape... | def function[convert_to_coarse, parameter[data, chan_per_coarse]]:
constant[
Converts a data array with length n_chans to an array of length n_coarse_chans
by averaging over the coarse channels
]
variable[num_coarse] assign[=] binary_operation[name[data].size / name[chan_per_coarse]]
... | keyword[def] identifier[convert_to_coarse] ( identifier[data] , identifier[chan_per_coarse] ):
literal[string]
identifier[num_coarse] = identifier[data] . identifier[size] / identifier[chan_per_coarse]
identifier[data_shaped] = identifier[np] . identifier[array] ( identifier[np] . identifier[res... | def convert_to_coarse(data, chan_per_coarse):
"""
Converts a data array with length n_chans to an array of length n_coarse_chans
by averaging over the coarse channels
"""
#find number of coarse channels and reshape array
num_coarse = data.size / chan_per_coarse
data_shaped = np.array(np.resh... |
def plot(self, numPoints=100):
"""
Specific plotting method for boxes.
Only supports 3-dimensional objects.
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# generate cylinder
x = np.linspace(- self.dimensions[0]/2., self.dimensions[0]/2., numPoints)
y = np.linspa... | def function[plot, parameter[self, numPoints]]:
constant[
Specific plotting method for boxes.
Only supports 3-dimensional objects.
]
variable[fig] assign[=] call[name[plt].figure, parameter[]]
variable[ax] assign[=] call[name[fig].add_subplot, parameter[constant[111]]]
varia... | keyword[def] identifier[plot] ( identifier[self] , identifier[numPoints] = literal[int] ):
literal[string]
identifier[fig] = identifier[plt] . identifier[figure] ()
identifier[ax] = identifier[fig] . identifier[add_subplot] ( literal[int] , identifier[projection] = literal[string] )
identif... | def plot(self, numPoints=100):
"""
Specific plotting method for boxes.
Only supports 3-dimensional objects.
"""
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# generate cylinder
x = np.linspace(-self.dimensions[0] / 2.0, self.dimensions[0] / 2.0, numPoints)
y = np.li... |
def has_length(self, value, q, strict=False):
"""if value has a length of q"""
value = stringify(value)
if value is not None:
if len(value) == q:
return
self.shout('Value %r not matching length %r', strict, value, q) | def function[has_length, parameter[self, value, q, strict]]:
constant[if value has a length of q]
variable[value] assign[=] call[name[stringify], parameter[name[value]]]
if compare[name[value] is_not constant[None]] begin[:]
if compare[call[name[len], parameter[name[value]]] equa... | keyword[def] identifier[has_length] ( identifier[self] , identifier[value] , identifier[q] , identifier[strict] = keyword[False] ):
literal[string]
identifier[value] = identifier[stringify] ( identifier[value] )
keyword[if] identifier[value] keyword[is] keyword[not] keyword[None] :
... | def has_length(self, value, q, strict=False):
"""if value has a length of q"""
value = stringify(value)
if value is not None:
if len(value) == q:
return # depends on [control=['if'], data=[]] # depends on [control=['if'], data=['value']]
self.shout('Value %r not matching length %r'... |
def _insert_and_merge_core(self, pos, direction):
"""
The core part of method _insert_and_merge.
:param int pos: The starting position.
:param str direction: If we are traversing forwards or backwards in the list. It determines where the "sort"
... | def function[_insert_and_merge_core, parameter[self, pos, direction]]:
constant[
The core part of method _insert_and_merge.
:param int pos: The starting position.
:param str direction: If we are traversing forwards or backwards in the list. It determines where the "sort"
... | keyword[def] identifier[_insert_and_merge_core] ( identifier[self] , identifier[pos] , identifier[direction] ):
literal[string]
identifier[bytes_changed] = literal[int]
keyword[if] identifier[direction] == literal[string] :
keyword[if] identifier[pos] == identifier[len] (... | def _insert_and_merge_core(self, pos, direction):
"""
The core part of method _insert_and_merge.
:param int pos: The starting position.
:param str direction: If we are traversing forwards or backwards in the list. It determines where the "sort"
of t... |
def _set_destination(self, v, load=False):
"""
Setter method for destination, mapped from YANG variable /openflow_global/openflow/mirror/destination (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_destination is considered as a private
method. Backends lo... | def function[_set_destination, parameter[self, v, load]]:
constant[
Setter method for destination, mapped from YANG variable /openflow_global/openflow/mirror/destination (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_destination is considered as a privat... | keyword[def] identifier[_set_destination] ( identifier[self] , identifier[v] , identifier[load] = keyword[False] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[v] , literal[string] ):
identifier[v] = identifier[v] . identifier[_utype] ( identifier[v] )
keyword[try] :
id... | def _set_destination(self, v, load=False):
"""
Setter method for destination, mapped from YANG variable /openflow_global/openflow/mirror/destination (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_destination is considered as a private
method. Backends lo... |
def save_offsets(
cls,
consumer_offsets_metadata,
topics_dict,
json_file,
groupid,
):
"""Built offsets for given topic-partitions in required format from current
offsets metadata and write to given json-file.
:param consumer_offsets_metadata: Fetched ... | def function[save_offsets, parameter[cls, consumer_offsets_metadata, topics_dict, json_file, groupid]]:
constant[Built offsets for given topic-partitions in required format from current
offsets metadata and write to given json-file.
:param consumer_offsets_metadata: Fetched consumer offsets fro... | keyword[def] identifier[save_offsets] (
identifier[cls] ,
identifier[consumer_offsets_metadata] ,
identifier[topics_dict] ,
identifier[json_file] ,
identifier[groupid] ,
):
literal[string]
identifier[current_consumer_offsets] = identifier[defaultdict] ( identifier[dict] )
key... | def save_offsets(cls, consumer_offsets_metadata, topics_dict, json_file, groupid):
"""Built offsets for given topic-partitions in required format from current
offsets metadata and write to given json-file.
:param consumer_offsets_metadata: Fetched consumer offsets from kafka.
:param topics_... |
def list(self, root=False, **kwargs):
"""Return a list of groups.
=====API DOCS=====
Retrieve a list of groups.
:param root: Flag that if set, only root groups of a specific inventory will be listed.
:type root: bool
:param parent: Primary key or name of the group whose... | def function[list, parameter[self, root]]:
constant[Return a list of groups.
=====API DOCS=====
Retrieve a list of groups.
:param root: Flag that if set, only root groups of a specific inventory will be listed.
:type root: bool
:param parent: Primary key or name of the ... | keyword[def] identifier[list] ( identifier[self] , identifier[root] = keyword[False] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[kwargs] . identifier[get] ( literal[string] , keyword[None] ):
identifier[self] . identifier[set_child_endpoint] ( identifier[... | def list(self, root=False, **kwargs):
"""Return a list of groups.
=====API DOCS=====
Retrieve a list of groups.
:param root: Flag that if set, only root groups of a specific inventory will be listed.
:type root: bool
:param parent: Primary key or name of the group whose chi... |
def color(self, color):
""" Set group color.
Color is set on a best-effort basis.
:param color: RGB color tuple.
"""
if color == RGB_WHITE:
self.white()
return
self._color = color
self.hue = hue_of_color(color) | def function[color, parameter[self, color]]:
constant[ Set group color.
Color is set on a best-effort basis.
:param color: RGB color tuple.
]
if compare[name[color] equal[==] name[RGB_WHITE]] begin[:]
call[name[self].white, parameter[]]
return[None]
... | keyword[def] identifier[color] ( identifier[self] , identifier[color] ):
literal[string]
keyword[if] identifier[color] == identifier[RGB_WHITE] :
identifier[self] . identifier[white] ()
keyword[return]
identifier[self] . identifier[_color] = identifier[color]
... | def color(self, color):
""" Set group color.
Color is set on a best-effort basis.
:param color: RGB color tuple.
"""
if color == RGB_WHITE:
self.white()
return # depends on [control=['if'], data=[]]
self._color = color
self.hue = hue_of_color(color) |
def calc_log_size(request, calc_id):
"""
Get the current number of lines in the log
"""
try:
response_data = logs.dbcmd('get_log_size', calc_id)
except dbapi.NotFound:
return HttpResponseNotFound()
return HttpResponse(content=json.dumps(response_data), content_type=JSON) | def function[calc_log_size, parameter[request, calc_id]]:
constant[
Get the current number of lines in the log
]
<ast.Try object at 0x7da1b138e320>
return[call[name[HttpResponse], parameter[]]] | keyword[def] identifier[calc_log_size] ( identifier[request] , identifier[calc_id] ):
literal[string]
keyword[try] :
identifier[response_data] = identifier[logs] . identifier[dbcmd] ( literal[string] , identifier[calc_id] )
keyword[except] identifier[dbapi] . identifier[NotFound] :
... | def calc_log_size(request, calc_id):
"""
Get the current number of lines in the log
"""
try:
response_data = logs.dbcmd('get_log_size', calc_id) # depends on [control=['try'], data=[]]
except dbapi.NotFound:
return HttpResponseNotFound() # depends on [control=['except'], data=[]]
... |
def dispatch(self, method_frame):
'''
Dispatch a method for this protocol.
'''
method = self.dispatch_map.get(method_frame.method_id)
if method:
callback = self.channel.clear_synchronous_cb(method)
callback(method_frame)
else:
raise sel... | def function[dispatch, parameter[self, method_frame]]:
constant[
Dispatch a method for this protocol.
]
variable[method] assign[=] call[name[self].dispatch_map.get, parameter[name[method_frame].method_id]]
if name[method] begin[:]
variable[callback] assign[=] call... | keyword[def] identifier[dispatch] ( identifier[self] , identifier[method_frame] ):
literal[string]
identifier[method] = identifier[self] . identifier[dispatch_map] . identifier[get] ( identifier[method_frame] . identifier[method_id] )
keyword[if] identifier[method] :
identifi... | def dispatch(self, method_frame):
"""
Dispatch a method for this protocol.
"""
method = self.dispatch_map.get(method_frame.method_id)
if method:
callback = self.channel.clear_synchronous_cb(method)
callback(method_frame) # depends on [control=['if'], data=[]]
else:
... |
def gen_paula_etree(paula_id):
"""
creates an element tree representation of an empty PAULA XML file.
"""
E = ElementMaker(nsmap=NSMAP)
tree = E('paula', version='1.1')
tree.append(E('header', paula_id=paula_id))
return E, tree | def function[gen_paula_etree, parameter[paula_id]]:
constant[
creates an element tree representation of an empty PAULA XML file.
]
variable[E] assign[=] call[name[ElementMaker], parameter[]]
variable[tree] assign[=] call[name[E], parameter[constant[paula]]]
call[name[tree].append... | keyword[def] identifier[gen_paula_etree] ( identifier[paula_id] ):
literal[string]
identifier[E] = identifier[ElementMaker] ( identifier[nsmap] = identifier[NSMAP] )
identifier[tree] = identifier[E] ( literal[string] , identifier[version] = literal[string] )
identifier[tree] . identifier[append] ... | def gen_paula_etree(paula_id):
"""
creates an element tree representation of an empty PAULA XML file.
"""
E = ElementMaker(nsmap=NSMAP)
tree = E('paula', version='1.1')
tree.append(E('header', paula_id=paula_id))
return (E, tree) |
def get_lr(self, step, nowarn=False):
"""
:param step: which of t_total steps we're on
:param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps
:return: learning rate multiplier for current update
"""
if self.t_total < ... | def function[get_lr, parameter[self, step, nowarn]]:
constant[
:param step: which of t_total steps we're on
:param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps
:return: learning rate multiplier for current update
]
... | keyword[def] identifier[get_lr] ( identifier[self] , identifier[step] , identifier[nowarn] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[t_total] < literal[int] :
keyword[return] literal[int]
identifier[progress] = identifier[float] ( identif... | def get_lr(self, step, nowarn=False):
"""
:param step: which of t_total steps we're on
:param nowarn: set to True to suppress warning regarding training beyond specified 't_total' steps
:return: learning rate multiplier for current update
"""
if self.t_total < 0:
... |
def requires_conversion(cls, fileset, file_format):
"""Checks whether the fileset matches the requested file format"""
if file_format is None:
return False
try:
filset_format = fileset.format
except AttributeError:
return False # Field input
e... | def function[requires_conversion, parameter[cls, fileset, file_format]]:
constant[Checks whether the fileset matches the requested file format]
if compare[name[file_format] is constant[None]] begin[:]
return[constant[False]]
<ast.Try object at 0x7da1b18bb040> | keyword[def] identifier[requires_conversion] ( identifier[cls] , identifier[fileset] , identifier[file_format] ):
literal[string]
keyword[if] identifier[file_format] keyword[is] keyword[None] :
keyword[return] keyword[False]
keyword[try] :
identifier[filset_f... | def requires_conversion(cls, fileset, file_format):
"""Checks whether the fileset matches the requested file format"""
if file_format is None:
return False # depends on [control=['if'], data=[]]
try:
filset_format = fileset.format # depends on [control=['try'], data=[]]
except Attribut... |
def get_pos_hint_y(poshints, sizehinty):
"""Return ``poshints['y']`` if available, or its computed equivalent
otherwise.
"""
if 'y' in poshints:
return poshints['y']
elif sizehinty is not None:
if 'center_y' in poshints:
return (
poshints['center_y'] -
... | def function[get_pos_hint_y, parameter[poshints, sizehinty]]:
constant[Return ``poshints['y']`` if available, or its computed equivalent
otherwise.
]
if compare[constant[y] in name[poshints]] begin[:]
return[call[name[poshints]][constant[y]]] | keyword[def] identifier[get_pos_hint_y] ( identifier[poshints] , identifier[sizehinty] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[poshints] :
keyword[return] identifier[poshints] [ literal[string] ]
keyword[elif] identifier[sizehinty] keyword[is] keyword[not]... | def get_pos_hint_y(poshints, sizehinty):
"""Return ``poshints['y']`` if available, or its computed equivalent
otherwise.
"""
if 'y' in poshints:
return poshints['y'] # depends on [control=['if'], data=['poshints']]
elif sizehinty is not None:
if 'center_y' in poshints:
... |
def url_builder(self, endpoint, *, root=None, params=None, url_params=None):
"""Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
para... | def function[url_builder, parameter[self, endpoint]]:
constant[Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
params: (:py:class:`d... | keyword[def] identifier[url_builder] ( identifier[self] , identifier[endpoint] ,*, identifier[root] = keyword[None] , identifier[params] = keyword[None] , identifier[url_params] = keyword[None] ):
literal[string]
keyword[if] identifier[root] keyword[is] keyword[None] :
identifier[ro... | def url_builder(self, endpoint, *, root=None, params=None, url_params=None):
"""Create a URL for the specified endpoint.
Arguments:
endpoint (:py:class:`str`): The API endpoint to access.
root: (:py:class:`str`, optional): The root URL for the
service API.
params: ... |
def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array."""
ret = {}
for item in l:
for key, value in item.items():
ret.setdefault(key, []).append(value)
for key, value in ret.items():
if key != 'date':
ret[key] = handle_units... | def function[combine_xml_points, parameter[l, units, handle_units]]:
constant[Combine multiple Point tags into an array.]
variable[ret] assign[=] dictionary[[], []]
for taget[name[item]] in starred[name[l]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da1b1061000>, <ast.Name ... | keyword[def] identifier[combine_xml_points] ( identifier[l] , identifier[units] , identifier[handle_units] ):
literal[string]
identifier[ret] ={}
keyword[for] identifier[item] keyword[in] identifier[l] :
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[item] . ide... | def combine_xml_points(l, units, handle_units):
"""Combine multiple Point tags into an array."""
ret = {}
for item in l:
for (key, value) in item.items():
ret.setdefault(key, []).append(value) # depends on [control=['for'], data=[]] # depends on [control=['for'], data=['item']]
for... |
def _bounds_dist(self, p):
"""Get the lower and upper bound distances. Negative is bad."""
prob = self.problem
lb_dist = (p - prob.variable_bounds[0, ]).min()
ub_dist = (prob.variable_bounds[1, ] - p).min()
if prob.bounds.shape[0] > 0:
const = prob.inequalities.dot(... | def function[_bounds_dist, parameter[self, p]]:
constant[Get the lower and upper bound distances. Negative is bad.]
variable[prob] assign[=] name[self].problem
variable[lb_dist] assign[=] call[binary_operation[name[p] - call[name[prob].variable_bounds][tuple[[<ast.Constant object at 0x7da1b0122c... | keyword[def] identifier[_bounds_dist] ( identifier[self] , identifier[p] ):
literal[string]
identifier[prob] = identifier[self] . identifier[problem]
identifier[lb_dist] =( identifier[p] - identifier[prob] . identifier[variable_bounds] [ literal[int] ,]). identifier[min] ()
iden... | def _bounds_dist(self, p):
"""Get the lower and upper bound distances. Negative is bad."""
prob = self.problem
lb_dist = (p - prob.variable_bounds[0,]).min()
ub_dist = (prob.variable_bounds[1,] - p).min()
if prob.bounds.shape[0] > 0:
const = prob.inequalities.dot(p)
const_lb_dist = (... |
def namedTempFileReader(self) -> NamedTempFileReader:
""" Named Temporary File Reader
This provides an object compatible with NamedTemporaryFile, used for reading this
files contents. This will still delete after the object falls out of scope.
This solves the problem on windows where a... | def function[namedTempFileReader, parameter[self]]:
constant[ Named Temporary File Reader
This provides an object compatible with NamedTemporaryFile, used for reading this
files contents. This will still delete after the object falls out of scope.
This solves the problem on windows whe... | keyword[def] identifier[namedTempFileReader] ( identifier[self] )-> identifier[NamedTempFileReader] :
literal[string]
identifier[directory] = identifier[self] . identifier[_directory] ()
keyword[assert] identifier[isinstance] ( identifier[directory] , identifier[Directory] ),(
... | def namedTempFileReader(self) -> NamedTempFileReader:
""" Named Temporary File Reader
This provides an object compatible with NamedTemporaryFile, used for reading this
files contents. This will still delete after the object falls out of scope.
This solves the problem on windows where a Nam... |
def read_block(self, block):
"""Read complete PEB data from file.
Argument:
Obj:block -- Block data is desired for.
"""
self.seek(block.file_offset)
return self._fhandle.read(block.size) | def function[read_block, parameter[self, block]]:
constant[Read complete PEB data from file.
Argument:
Obj:block -- Block data is desired for.
]
call[name[self].seek, parameter[name[block].file_offset]]
return[call[name[self]._fhandle.read, parameter[name[block].size... | keyword[def] identifier[read_block] ( identifier[self] , identifier[block] ):
literal[string]
identifier[self] . identifier[seek] ( identifier[block] . identifier[file_offset] )
keyword[return] identifier[self] . identifier[_fhandle] . identifier[read] ( identifier[block] . identifier[siz... | def read_block(self, block):
"""Read complete PEB data from file.
Argument:
Obj:block -- Block data is desired for.
"""
self.seek(block.file_offset)
return self._fhandle.read(block.size) |
def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training."""
# model
model, vocabulary = nlp.model.get_model(model,
dataset_name=dataset_name,
pretrai... | def function[get_model_loss, parameter[ctx, model, pretrained, dataset_name, dtype, ckpt_dir, start_step]]:
constant[Get model for pre-training.]
<ast.Tuple object at 0x7da1b26ae320> assign[=] call[name[nlp].model.get_model, parameter[name[model]]]
if <ast.UnaryOp object at 0x7da1b26afe50> begin... | keyword[def] identifier[get_model_loss] ( identifier[ctx] , identifier[model] , identifier[pretrained] , identifier[dataset_name] , identifier[dtype] , identifier[ckpt_dir] = keyword[None] , identifier[start_step] = keyword[None] ):
literal[string]
identifier[model] , identifier[vocabulary] = identifi... | def get_model_loss(ctx, model, pretrained, dataset_name, dtype, ckpt_dir=None, start_step=None):
"""Get model for pre-training."""
# model
(model, vocabulary) = nlp.model.get_model(model, dataset_name=dataset_name, pretrained=pretrained, ctx=ctx)
if not pretrained:
model.initialize(init=mx.init.... |
def parse_header(recipe, header="from", remove_header=True):
'''take a recipe, and return the complete header, line. If
remove_header is True, only return the value.
Parameters
==========
recipe: the recipe file
headers: the header key to find and parse
remove_header: if t... | def function[parse_header, parameter[recipe, header, remove_header]]:
constant[take a recipe, and return the complete header, line. If
remove_header is True, only return the value.
Parameters
==========
recipe: the recipe file
headers: the header key to find and parse
... | keyword[def] identifier[parse_header] ( identifier[recipe] , identifier[header] = literal[string] , identifier[remove_header] = keyword[True] ):
literal[string]
identifier[parsed_header] = keyword[None]
identifier[fromline] =[ identifier[x] keyword[for] identifier[x] keyword[in] identifier[recipe... | def parse_header(recipe, header='from', remove_header=True):
"""take a recipe, and return the complete header, line. If
remove_header is True, only return the value.
Parameters
==========
recipe: the recipe file
headers: the header key to find and parse
remove_header: if t... |
def _load_txt(file, devices, channels, header, **kwargs):
"""
Function used for reading .txt files generated by OpenSignals.
----------
Parameters
----------
file : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is
``.gz`` or ``.bz2``... | def function[_load_txt, parameter[file, devices, channels, header]]:
constant[
Function used for reading .txt files generated by OpenSignals.
----------
Parameters
----------
file : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is
... | keyword[def] identifier[_load_txt] ( identifier[file] , identifier[devices] , identifier[channels] , identifier[header] ,** identifier[kwargs] ):
literal[string]
identifier[kwargs_txt] = identifier[_filter_keywords] ( identifier[numpy] . identifier[loadtxt] , identifier[kwargs] )
identifie... | def _load_txt(file, devices, channels, header, **kwargs):
"""
Function used for reading .txt files generated by OpenSignals.
----------
Parameters
----------
file : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is
``.gz`` or ``.bz2``... |
def ua_string(praw_info):
"""Return the user-agent string.
The user-agent string contains PRAW version and platform version info.
"""
if os.environ.get('SERVER_SOFTWARE') is not None:
# Google App Engine information
# https://developers.google.com/appengine/docs... | def function[ua_string, parameter[praw_info]]:
constant[Return the user-agent string.
The user-agent string contains PRAW version and platform version info.
]
if compare[call[name[os].environ.get, parameter[constant[SERVER_SOFTWARE]]] is_not constant[None]] begin[:]
var... | keyword[def] identifier[ua_string] ( identifier[praw_info] ):
literal[string]
keyword[if] identifier[os] . identifier[environ] . identifier[get] ( literal[string] ) keyword[is] keyword[not] keyword[None] :
identifier[info] = identifier[os] . identifier[environ] . i... | def ua_string(praw_info):
"""Return the user-agent string.
The user-agent string contains PRAW version and platform version info.
"""
if os.environ.get('SERVER_SOFTWARE') is not None:
# Google App Engine information
# https://developers.google.com/appengine/docs/python/
... |
def _post(self, uri, data, headers=None):
"""
Simple POST request for a given uri path.
"""
if not headers:
headers = self._get_headers()
logging.debug("URI=" + str(uri))
logging.debug("HEADERS=" + str(headers))
logging.debug("BODY=" + str(data))
... | def function[_post, parameter[self, uri, data, headers]]:
constant[
Simple POST request for a given uri path.
]
if <ast.UnaryOp object at 0x7da204344be0> begin[:]
variable[headers] assign[=] call[name[self]._get_headers, parameter[]]
call[name[logging].debug, para... | keyword[def] identifier[_post] ( identifier[self] , identifier[uri] , identifier[data] , identifier[headers] = keyword[None] ):
literal[string]
keyword[if] keyword[not] identifier[headers] :
identifier[headers] = identifier[self] . identifier[_get_headers] ()
identifier[log... | def _post(self, uri, data, headers=None):
"""
Simple POST request for a given uri path.
"""
if not headers:
headers = self._get_headers() # depends on [control=['if'], data=[]]
logging.debug('URI=' + str(uri))
logging.debug('HEADERS=' + str(headers))
logging.debug('BODY=' + ... |
def _configure_key_pair(config):
"""Configure SSH access, using an existing key pair if possible.
Creates a project-wide ssh key that can be used to access all the instances
unless explicitly prohibited by instance config.
The ssh-keys created by ray are of format:
[USERNAME]:ssh-rsa [KEY_VALUE... | def function[_configure_key_pair, parameter[config]]:
constant[Configure SSH access, using an existing key pair if possible.
Creates a project-wide ssh key that can be used to access all the instances
unless explicitly prohibited by instance config.
The ssh-keys created by ray are of format:
... | keyword[def] identifier[_configure_key_pair] ( identifier[config] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[config] [ literal[string] ]:
keyword[return] identifier[config]
identifier[ssh_user] = identifier[config] [ literal[string] ][ literal[string] ]
... | def _configure_key_pair(config):
"""Configure SSH access, using an existing key pair if possible.
Creates a project-wide ssh key that can be used to access all the instances
unless explicitly prohibited by instance config.
The ssh-keys created by ray are of format:
[USERNAME]:ssh-rsa [KEY_VALUE... |
def avl_new_top(t1, t2, top, direction=0):
"""
if direction == 0:
(t1, t2) is (left, right)
if direction == 1:
(t1, t2) is (right, left)
"""
top.parent = None
assert top.parent is None, str(top.parent.value)
top.set_child(direction, t1)
top.set_child(1 - direction, t2)
... | def function[avl_new_top, parameter[t1, t2, top, direction]]:
constant[
if direction == 0:
(t1, t2) is (left, right)
if direction == 1:
(t1, t2) is (right, left)
]
name[top].parent assign[=] constant[None]
assert[compare[name[top].parent is constant[None]]]
call[n... | keyword[def] identifier[avl_new_top] ( identifier[t1] , identifier[t2] , identifier[top] , identifier[direction] = literal[int] ):
literal[string]
identifier[top] . identifier[parent] = keyword[None]
keyword[assert] identifier[top] . identifier[parent] keyword[is] keyword[None] , identifier[str] (... | def avl_new_top(t1, t2, top, direction=0):
"""
if direction == 0:
(t1, t2) is (left, right)
if direction == 1:
(t1, t2) is (right, left)
"""
top.parent = None
assert top.parent is None, str(top.parent.value)
top.set_child(direction, t1)
top.set_child(1 - direction, t2)
... |
def use_isolated_book_view(self):
"""Pass through to provider CommentLookupSession.use_isolated_book_view"""
self._book_view = ISOLATED
# self._get_provider_session('comment_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
t... | def function[use_isolated_book_view, parameter[self]]:
constant[Pass through to provider CommentLookupSession.use_isolated_book_view]
name[self]._book_view assign[=] name[ISOLATED]
for taget[name[session]] in starred[call[name[self]._get_provider_sessions, parameter[]]] begin[:]
<ast.Try... | keyword[def] identifier[use_isolated_book_view] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_book_view] = identifier[ISOLATED]
keyword[for] identifier[session] keyword[in] identifier[self] . identifier[_get_provider_sessions] ():
keyword[tr... | def use_isolated_book_view(self):
"""Pass through to provider CommentLookupSession.use_isolated_book_view"""
self._book_view = ISOLATED
# self._get_provider_session('comment_lookup_session') # To make sure the session is tracked
for session in self._get_provider_sessions():
try:
sess... |
def sign_execute_cancellation(cancellation_params, key_pair):
"""
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)
Th... | def function[sign_execute_cancellation, parameter[cancellation_params, key_pair]]:
constant[
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_par... | keyword[def] identifier[sign_execute_cancellation] ( identifier[cancellation_params] , identifier[key_pair] ):
literal[string]
identifier[signature] = identifier[sign_transaction] ( identifier[transaction] = identifier[cancellation_params] [ literal[string] ],
identifier[private_key_hex] = identifier[... | def sign_execute_cancellation(cancellation_params, key_pair):
"""
Function to sign the parameters required to execute a cancellation request on the Switcheo Exchange.
Execution of this function is as follows::
sign_execute_cancellation(cancellation_params=signable_params, key_pair=key_pair)
Th... |
def call_mr_transform(data, opt='', path='./',
remove_files=True): # pragma: no cover
r"""Call mr_transform
This method calls the iSAP module mr_transform
Parameters
----------
data : np.ndarray
Input data, 2D array
opt : list or str, optional
Options to ... | def function[call_mr_transform, parameter[data, opt, path, remove_files]]:
constant[Call mr_transform
This method calls the iSAP module mr_transform
Parameters
----------
data : np.ndarray
Input data, 2D array
opt : list or str, optional
Options to be passed to mr_transform... | keyword[def] identifier[call_mr_transform] ( identifier[data] , identifier[opt] = literal[string] , identifier[path] = literal[string] ,
identifier[remove_files] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[import_astropy] :
keyword[raise] identifier[ImportError] ( l... | def call_mr_transform(data, opt='', path='./', remove_files=True): # pragma: no cover
"Call mr_transform\n\n This method calls the iSAP module mr_transform\n\n Parameters\n ----------\n data : np.ndarray\n Input data, 2D array\n opt : list or str, optional\n Options to be passed to mr_... |
def expect_prompt(self, consume=True):
"""
Monitors the data received from the remote host and waits for a
prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt... | def function[expect_prompt, parameter[self, consume]]:
constant[
Monitors the data received from the remote host and waits for a
prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that ... | keyword[def] identifier[expect_prompt] ( identifier[self] , identifier[consume] = keyword[True] ):
literal[string]
keyword[if] identifier[consume] :
identifier[result] = identifier[self] . identifier[expect] ( identifier[self] . identifier[get_prompt] ())
keyword[else] :
... | def expect_prompt(self, consume=True):
"""
Monitors the data received from the remote host and waits for a
prompt in the response. The prompt attempts to use
a sane default that works with many devices running Unix, IOS,
IOS-XR, or Junos and others. If that fails, a custom prompt may... |
def get_distance(node1, node2):
"""
Reports the distance in the machine topology between two nodes.
The factors are a multiple of 10. It returns 0 when the distance cannot be determined. A node has
distance 10 to itself. Reporting the distance requires a Linux kernel version of 2.6.10 or newer.
... | def function[get_distance, parameter[node1, node2]]:
constant[
Reports the distance in the machine topology between two nodes.
The factors are a multiple of 10. It returns 0 when the distance cannot be determined. A node has
distance 10 to itself. Reporting the distance requires a Linux kernel ve... | keyword[def] identifier[get_distance] ( identifier[node1] , identifier[node2] ):
literal[string]
keyword[if] identifier[node1] < literal[int] keyword[or] identifier[node1] > identifier[get_max_node] ():
keyword[raise] identifier[ValueError] ( identifier[node1] )
keyword[if] identifier[no... | def get_distance(node1, node2):
"""
Reports the distance in the machine topology between two nodes.
The factors are a multiple of 10. It returns 0 when the distance cannot be determined. A node has
distance 10 to itself. Reporting the distance requires a Linux kernel version of 2.6.10 or newer.
... |
def aaa_config_aaa_authentication_login_first(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
aaa_config = ET.SubElement(config, "aaa-config", xmlns="urn:brocade.com:mgmt:brocade-aaa")
aaa = ET.SubElement(aaa_config, "aaa")
authentication = ET.Su... | def function[aaa_config_aaa_authentication_login_first, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[aaa_config] assign[=] call[name[ET].SubElement, parameter[name[config], constant[aaa-config]]]
... | keyword[def] identifier[aaa_config_aaa_authentication_login_first] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[aaa_config] = identifier[ET] . identifier[SubElement] ( identifier[config... | def aaa_config_aaa_authentication_login_first(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
aaa_config = ET.SubElement(config, 'aaa-config', xmlns='urn:brocade.com:mgmt:brocade-aaa')
aaa = ET.SubElement(aaa_config, 'aaa')
authentication = ET.SubElement(aaa, 'authe... |
def syscall_noreturn(self, func):
'''
Call a syscall method. A syscall method is executed outside of any routines, directly
in the scheduler loop, which gives it chances to directly operate the event loop.
See :py:method::`vlcp.event.core.Scheduler.syscall`.
'''
matcher =... | def function[syscall_noreturn, parameter[self, func]]:
constant[
Call a syscall method. A syscall method is executed outside of any routines, directly
in the scheduler loop, which gives it chances to directly operate the event loop.
See :py:method::`vlcp.event.core.Scheduler.syscall`.
... | keyword[def] identifier[syscall_noreturn] ( identifier[self] , identifier[func] ):
literal[string]
identifier[matcher] = identifier[self] . identifier[scheduler] . identifier[syscall] ( identifier[func] )
keyword[while] keyword[not] identifier[matcher] :
keyword[yield]
... | def syscall_noreturn(self, func):
"""
Call a syscall method. A syscall method is executed outside of any routines, directly
in the scheduler loop, which gives it chances to directly operate the event loop.
See :py:method::`vlcp.event.core.Scheduler.syscall`.
"""
matcher = self.sc... |
def unregister_model(self, model):
"""
Unregisters the given model.
"""
if model not in self._model_registry:
raise NotRegistered('The model %s is not registered' % model)
del self._model_registry[model] | def function[unregister_model, parameter[self, model]]:
constant[
Unregisters the given model.
]
if compare[name[model] <ast.NotIn object at 0x7da2590d7190> name[self]._model_registry] begin[:]
<ast.Raise object at 0x7da20e957550>
<ast.Delete object at 0x7da20e955c60> | keyword[def] identifier[unregister_model] ( identifier[self] , identifier[model] ):
literal[string]
keyword[if] identifier[model] keyword[not] keyword[in] identifier[self] . identifier[_model_registry] :
keyword[raise] identifier[NotRegistered] ( literal[string] % identifier[model... | def unregister_model(self, model):
"""
Unregisters the given model.
"""
if model not in self._model_registry:
raise NotRegistered('The model %s is not registered' % model) # depends on [control=['if'], data=['model']]
del self._model_registry[model] |
def get_month_start_end_day():
"""
Get the month start date a nd end date
"""
t = date.today()
n = mdays[t.month]
return (date(t.year, t.month, 1), date(t.year, t.month, n)) | def function[get_month_start_end_day, parameter[]]:
constant[
Get the month start date a nd end date
]
variable[t] assign[=] call[name[date].today, parameter[]]
variable[n] assign[=] call[name[mdays]][name[t].month]
return[tuple[[<ast.Call object at 0x7da1b0ab9180>, <ast.Call object ... | keyword[def] identifier[get_month_start_end_day] ():
literal[string]
identifier[t] = identifier[date] . identifier[today] ()
identifier[n] = identifier[mdays] [ identifier[t] . identifier[month] ]
keyword[return] ( identifier[date] ( identifier[t] . identifier[year] , identifier[t] . identifier[m... | def get_month_start_end_day():
"""
Get the month start date a nd end date
"""
t = date.today()
n = mdays[t.month]
return (date(t.year, t.month, 1), date(t.year, t.month, n)) |
def _instance_from_process(self, process):
"""Default converter from psutil.Process to process instance classes for subclassing."""
return ProcessManager(name=process.name(),
pid=process.pid,
process_name=process.name(),
metadata_base... | def function[_instance_from_process, parameter[self, process]]:
constant[Default converter from psutil.Process to process instance classes for subclassing.]
return[call[name[ProcessManager], parameter[]]] | keyword[def] identifier[_instance_from_process] ( identifier[self] , identifier[process] ):
literal[string]
keyword[return] identifier[ProcessManager] ( identifier[name] = identifier[process] . identifier[name] (),
identifier[pid] = identifier[process] . identifier[pid] ,
identifier[process_name... | def _instance_from_process(self, process):
"""Default converter from psutil.Process to process instance classes for subclassing."""
return ProcessManager(name=process.name(), pid=process.pid, process_name=process.name(), metadata_base_dir=self._metadata_base_dir) |
def main(self):
"""
Generates an output string by replacing the keywords in the format
string with the corresponding values from a submission dictionary.
"""
self.manage_submissions()
out_string = self.options['format']
# Pop until we get something which len(titl... | def function[main, parameter[self]]:
constant[
Generates an output string by replacing the keywords in the format
string with the corresponding values from a submission dictionary.
]
call[name[self].manage_submissions, parameter[]]
variable[out_string] assign[=] call[name... | keyword[def] identifier[main] ( identifier[self] ):
literal[string]
identifier[self] . identifier[manage_submissions] ()
identifier[out_string] = identifier[self] . identifier[options] [ literal[string] ]
identifier[length] = identifier[float] ( literal[string] )
... | def main(self):
"""
Generates an output string by replacing the keywords in the format
string with the corresponding values from a submission dictionary.
"""
self.manage_submissions()
out_string = self.options['format']
# Pop until we get something which len(title) <= max-chars
... |
def save_tabs_when_changed(func):
"""Decorator for save-tabs-when-changed
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
log.debug("mom, I've been called: %s %s", func.__name__, func)
# Find me the Guake!
clsname = args[0].__class__.__name__
g = None
... | def function[save_tabs_when_changed, parameter[func]]:
constant[Decorator for save-tabs-when-changed
]
def function[wrapper, parameter[]]:
call[name[func], parameter[<ast.Starred object at 0x7da20c76e590>]]
call[name[log].debug, parameter[constant[mom, I've been calle... | keyword[def] identifier[save_tabs_when_changed] ( identifier[func] ):
literal[string]
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[func] (* identifier[args] ,** identifier[kwargs] )
identifier[log] . identifier[debug] ( literal[string] , iden... | def save_tabs_when_changed(func):
"""Decorator for save-tabs-when-changed
"""
def wrapper(*args, **kwargs):
func(*args, **kwargs)
log.debug("mom, I've been called: %s %s", func.__name__, func)
# Find me the Guake!
clsname = args[0].__class__.__name__
g = None
... |
def pulled_up(self, function):
"""
Returns a bool indicating whether a physical pull-up is attached to
the pin supporting the specified *function*. Either :exc:`PinNoPins`
or :exc:`PinMultiplePins` may be raised if the function is not
associated with a single pin.
:param... | def function[pulled_up, parameter[self, function]]:
constant[
Returns a bool indicating whether a physical pull-up is attached to
the pin supporting the specified *function*. Either :exc:`PinNoPins`
or :exc:`PinMultiplePins` may be raised if the function is not
associated with a ... | keyword[def] identifier[pulled_up] ( identifier[self] , identifier[function] ):
literal[string]
keyword[try] :
identifier[header] , identifier[number] = identifier[self] . identifier[physical_pin] ( identifier[function] )
keyword[except] identifier[PinNoPins] :
k... | def pulled_up(self, function):
"""
Returns a bool indicating whether a physical pull-up is attached to
the pin supporting the specified *function*. Either :exc:`PinNoPins`
or :exc:`PinMultiplePins` may be raised if the function is not
associated with a single pin.
:param str... |
def execute(self, input_data):
''' Execute the VTQuery worker '''
md5 = input_data['meta']['md5']
response = requests.get('http://www.virustotal.com/vtapi/v2/file/report',
params={'apikey':self.apikey,'resource':md5, 'allinfo':1})
# Make sure we got a js... | def function[execute, parameter[self, input_data]]:
constant[ Execute the VTQuery worker ]
variable[md5] assign[=] call[call[name[input_data]][constant[meta]]][constant[md5]]
variable[response] assign[=] call[name[requests].get, parameter[constant[http://www.virustotal.com/vtapi/v2/file/report]]... | keyword[def] identifier[execute] ( identifier[self] , identifier[input_data] ):
literal[string]
identifier[md5] = identifier[input_data] [ literal[string] ][ literal[string] ]
identifier[response] = identifier[requests] . identifier[get] ( literal[string] ,
identifier[params] ={ l... | def execute(self, input_data):
""" Execute the VTQuery worker """
md5 = input_data['meta']['md5']
response = requests.get('http://www.virustotal.com/vtapi/v2/file/report', params={'apikey': self.apikey, 'resource': md5, 'allinfo': 1})
# Make sure we got a json blob back
try:
vt_output = resp... |
def __get_total_response_time(meta_datas_expanded):
""" caculate total response time of all meta_datas
"""
try:
response_time = 0
for meta_data in meta_datas_expanded:
response_time += meta_data["stat"]["response_time_ms"]
return "{:.2f}".format(response_time)
excep... | def function[__get_total_response_time, parameter[meta_datas_expanded]]:
constant[ caculate total response time of all meta_datas
]
<ast.Try object at 0x7da18ede4d60> | keyword[def] identifier[__get_total_response_time] ( identifier[meta_datas_expanded] ):
literal[string]
keyword[try] :
identifier[response_time] = literal[int]
keyword[for] identifier[meta_data] keyword[in] identifier[meta_datas_expanded] :
identifier[response_time] += id... | def __get_total_response_time(meta_datas_expanded):
""" caculate total response time of all meta_datas
"""
try:
response_time = 0
for meta_data in meta_datas_expanded:
response_time += meta_data['stat']['response_time_ms'] # depends on [control=['for'], data=['meta_data']]
... |
def unregister_presence_callback(self, type_, from_):
"""
Unregister a callback previously registered with
:meth:`register_presence_callback`.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender JID to listen for, or :data... | def function[unregister_presence_callback, parameter[self, type_, from_]]:
constant[
Unregister a callback previously registered with
:meth:`register_presence_callback`.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender ... | keyword[def] identifier[unregister_presence_callback] ( identifier[self] , identifier[type_] , identifier[from_] ):
literal[string]
identifier[type_] = identifier[self] . identifier[_coerce_enum] ( identifier[type_] , identifier[structs] . identifier[PresenceType] )
identifier[warnings] . ... | def unregister_presence_callback(self, type_, from_):
"""
Unregister a callback previously registered with
:meth:`register_presence_callback`.
:param type_: Presence type to listen for.
:type type_: :class:`~.PresenceType`
:param from_: Sender JID to listen for, or :data:`No... |
def _process_pubs(self, limit):
"""
Flybase publications.
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph
else:
graph = self.graph
model = Model(graph)
line_counter = 0
raw = '/'.join((self.ra... | def function[_process_pubs, parameter[self, limit]]:
constant[
Flybase publications.
:param limit:
:return:
]
if name[self].test_mode begin[:]
variable[graph] assign[=] name[self].testgraph
variable[model] assign[=] call[name[Model], parameter[na... | keyword[def] identifier[_process_pubs] ( identifier[self] , identifier[limit] ):
literal[string]
keyword[if] identifier[self] . identifier[test_mode] :
identifier[graph] = identifier[self] . identifier[testgraph]
keyword[else] :
identifier[graph] = identifier[se... | def _process_pubs(self, limit):
"""
Flybase publications.
:param limit:
:return:
"""
if self.test_mode:
graph = self.testgraph # depends on [control=['if'], data=[]]
else:
graph = self.graph
model = Model(graph)
line_counter = 0
raw = '/'.join((... |
def send_invoice(token, chat_id, title, description, invoice_payload, provider_token, currency, prices,
start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None,
need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexibl... | def function[send_invoice, parameter[token, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url, photo_size, photo_width, photo_height, need_name, need_phone_number, need_email, need_shipping_address, is_flexible, disable_notification, reply_to_message_id, reply_ma... | keyword[def] identifier[send_invoice] ( identifier[token] , identifier[chat_id] , identifier[title] , identifier[description] , identifier[invoice_payload] , identifier[provider_token] , identifier[currency] , identifier[prices] ,
identifier[start_parameter] , identifier[photo_url] = keyword[None] , identifier[photo... | def send_invoice(token, chat_id, title, description, invoice_payload, provider_token, currency, prices, start_parameter, photo_url=None, photo_size=None, photo_width=None, photo_height=None, need_name=None, need_phone_number=None, need_email=None, need_shipping_address=None, is_flexible=None, disable_notification=None,... |
def order_derived_variables(regime):
"""
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a ... | def function[order_derived_variables, parameter[regime]]:
constant[
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@rais... | keyword[def] identifier[order_derived_variables] ( identifier[regime] ):
literal[string]
identifier[ordering] =[]
identifier[dvs] =[]
identifier[dvsnoexp] =[]
identifier[maxcount] = literal[int]
keyword[for] identifier[dv] keyword[in] identifier[regime] . identifier[derived_variab... | def order_derived_variables(regime):
"""
Finds ordering of derived_variables.
@param regime: Dynamics Regime containing derived variables.
@type regime: lems.model.dynamics.regime
@return: Returns ordered list of derived variables.
@rtype: list(string)
@raise SimBuildError: Raised when a ... |
def set_wrappable_term(self, v, term):
"""Set the Root.Description, possibly splitting long descriptions across multiple terms. """
import textwrap
for t in self['Root'].find(term):
self.remove_term(t)
for l in textwrap.wrap(v, 80):
self['Root'].new_term(term, ... | def function[set_wrappable_term, parameter[self, v, term]]:
constant[Set the Root.Description, possibly splitting long descriptions across multiple terms. ]
import module[textwrap]
for taget[name[t]] in starred[call[call[name[self]][constant[Root]].find, parameter[name[term]]]] begin[:]
... | keyword[def] identifier[set_wrappable_term] ( identifier[self] , identifier[v] , identifier[term] ):
literal[string]
keyword[import] identifier[textwrap]
keyword[for] identifier[t] keyword[in] identifier[self] [ literal[string] ]. identifier[find] ( identifier[term] ):
... | def set_wrappable_term(self, v, term):
"""Set the Root.Description, possibly splitting long descriptions across multiple terms. """
import textwrap
for t in self['Root'].find(term):
self.remove_term(t) # depends on [control=['for'], data=['t']]
for l in textwrap.wrap(v, 80):
self['Root'... |
def writeXML(self, n):
"""
Writes a XML string to the data stream.
@type n: L{ET<xml.ET>}
@param n: The XML Document to be encoded to the AMF3 data stream.
"""
self.stream.write(TYPE_XMLSTRING)
ref = self.context.getObjectReference(n)
if ref != -1:
... | def function[writeXML, parameter[self, n]]:
constant[
Writes a XML string to the data stream.
@type n: L{ET<xml.ET>}
@param n: The XML Document to be encoded to the AMF3 data stream.
]
call[name[self].stream.write, parameter[name[TYPE_XMLSTRING]]]
variable[ref... | keyword[def] identifier[writeXML] ( identifier[self] , identifier[n] ):
literal[string]
identifier[self] . identifier[stream] . identifier[write] ( identifier[TYPE_XMLSTRING] )
identifier[ref] = identifier[self] . identifier[context] . identifier[getObjectReference] ( identifier[n] )
... | def writeXML(self, n):
"""
Writes a XML string to the data stream.
@type n: L{ET<xml.ET>}
@param n: The XML Document to be encoded to the AMF3 data stream.
"""
self.stream.write(TYPE_XMLSTRING)
ref = self.context.getObjectReference(n)
if ref != -1:
self._write... |
def encodeABI(cls, fn_name, args=None, kwargs=None, data=None):
"""
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
"""
fn_abi, fn_selector, fn_arguments = get_f... | def function[encodeABI, parameter[cls, fn_name, args, kwargs, data]]:
constant[
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
]
<ast.Tuple object at 0x7da18f81... | keyword[def] identifier[encodeABI] ( identifier[cls] , identifier[fn_name] , identifier[args] = keyword[None] , identifier[kwargs] = keyword[None] , identifier[data] = keyword[None] ):
literal[string]
identifier[fn_abi] , identifier[fn_selector] , identifier[fn_arguments] = identifier[get_function_... | def encodeABI(cls, fn_name, args=None, kwargs=None, data=None):
"""
Encodes the arguments using the Ethereum ABI for the contract function
that matches the given name and arguments..
:param data: defaults to function selector
"""
(fn_abi, fn_selector, fn_arguments) = get_functio... |
def set_buf_size(fd):
"""Set up os pipe buffer size, if applicable"""
if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'):
fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ) | def function[set_buf_size, parameter[fd]]:
constant[Set up os pipe buffer size, if applicable]
if <ast.BoolOp object at 0x7da20c6c4040> begin[:]
call[name[fcntl].fcntl, parameter[name[fd], name[fcntl].F_SETPIPE_SZ, name[OS_PIPE_SZ]]] | keyword[def] identifier[set_buf_size] ( identifier[fd] ):
literal[string]
keyword[if] identifier[OS_PIPE_SZ] keyword[and] identifier[hasattr] ( identifier[fcntl] , literal[string] ):
identifier[fcntl] . identifier[fcntl] ( identifier[fd] , identifier[fcntl] . identifier[F_SETPIPE_SZ] , identifi... | def set_buf_size(fd):
"""Set up os pipe buffer size, if applicable"""
if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'):
fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ) # depends on [control=['if'], data=[]] |
def _format_id(self, payload):
"""Echos only the id"""
if 'id' in payload:
return str(payload['id'])
if 'results' in payload:
return ' '.join([six.text_type(item['id']) for item in payload['results']])
raise MultipleRelatedError('Could not serialize output with id... | def function[_format_id, parameter[self, payload]]:
constant[Echos only the id]
if compare[constant[id] in name[payload]] begin[:]
return[call[name[str], parameter[call[name[payload]][constant[id]]]]]
if compare[constant[results] in name[payload]] begin[:]
return[call[constant[ ]... | keyword[def] identifier[_format_id] ( identifier[self] , identifier[payload] ):
literal[string]
keyword[if] literal[string] keyword[in] identifier[payload] :
keyword[return] identifier[str] ( identifier[payload] [ literal[string] ])
keyword[if] literal[string] keyword[in... | def _format_id(self, payload):
"""Echos only the id"""
if 'id' in payload:
return str(payload['id']) # depends on [control=['if'], data=['payload']]
if 'results' in payload:
return ' '.join([six.text_type(item['id']) for item in payload['results']]) # depends on [control=['if'], data=['pay... |
def _num_values(self, vdr_dict):
'''
Returns the number of values in a record, using a given VDR
dictionary. Multiplies the dimension sizes of each dimension,
if it is varying.
'''
values = 1
for x in range(0, vdr_dict['num_dims']):
if (vdr_dict['dim_v... | def function[_num_values, parameter[self, vdr_dict]]:
constant[
Returns the number of values in a record, using a given VDR
dictionary. Multiplies the dimension sizes of each dimension,
if it is varying.
]
variable[values] assign[=] constant[1]
for taget[name[x]] ... | keyword[def] identifier[_num_values] ( identifier[self] , identifier[vdr_dict] ):
literal[string]
identifier[values] = literal[int]
keyword[for] identifier[x] keyword[in] identifier[range] ( literal[int] , identifier[vdr_dict] [ literal[string] ]):
keyword[if] ( identifier... | def _num_values(self, vdr_dict):
"""
Returns the number of values in a record, using a given VDR
dictionary. Multiplies the dimension sizes of each dimension,
if it is varying.
"""
values = 1
for x in range(0, vdr_dict['num_dims']):
if vdr_dict['dim_vary'][x] != 0:
... |
def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None):
"""
Render a :class:`~fluent_contents.models.Placeholder` object.
Returns a :class:`~fluent_contents.models.ContentItemOutput` object
which contains th... | def function[render_placeholder, parameter[request, placeholder, parent_object, template_name, cachable, limit_parent_language, fallback_language]]:
constant[
Render a :class:`~fluent_contents.models.Placeholder` object.
Returns a :class:`~fluent_contents.models.ContentItemOutput` object
which conta... | keyword[def] identifier[render_placeholder] ( identifier[request] , identifier[placeholder] , identifier[parent_object] = keyword[None] , identifier[template_name] = keyword[None] , identifier[cachable] = keyword[None] , identifier[limit_parent_language] = keyword[True] , identifier[fallback_language] = keyword[None]... | def render_placeholder(request, placeholder, parent_object=None, template_name=None, cachable=None, limit_parent_language=True, fallback_language=None):
"""
Render a :class:`~fluent_contents.models.Placeholder` object.
Returns a :class:`~fluent_contents.models.ContentItemOutput` object
which contains th... |
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars,
bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass_Union.
"""
# this function is partly based on code from typing module 3.5.2.2
super_args = get_Union_params(superclass)
if... | def function[_issubclass_Union_rec, parameter[subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check]]:
constant[Helper for _issubclass_Union.
]
variable[super_args] assign[=] call[name[get_Union_params], parameter[name[superclass]]]
i... | keyword[def] identifier[_issubclass_Union_rec] ( identifier[subclass] , identifier[superclass] , identifier[bound_Generic] , identifier[bound_typevars] ,
identifier[bound_typevars_readonly] , identifier[follow_fwd_refs] , identifier[_recursion_check] ):
literal[string]
identifier[super_args] = identi... | def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check):
"""Helper for _issubclass_Union.
"""
# this function is partly based on code from typing module 3.5.2.2
super_args = get_Union_params(superclass)
if super_args ... |
def shutdown(name, wait=False, reboot=False):
'''
graceful shutdown sent to the container
:param wait: should we wait for the shutdown to complete?
:param reboot: reboot a container, ignores wait
'''
if not exists(name):
raise ContainerNotExists("The container (%s) does not exist!... | def function[shutdown, parameter[name, wait, reboot]]:
constant[
graceful shutdown sent to the container
:param wait: should we wait for the shutdown to complete?
:param reboot: reboot a container, ignores wait
]
if <ast.UnaryOp object at 0x7da204346200> begin[:]
<ast.Raise objec... | keyword[def] identifier[shutdown] ( identifier[name] , identifier[wait] = keyword[False] , identifier[reboot] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[exists] ( identifier[name] ):
keyword[raise] identifier[ContainerNotExists] ( literal[string] % identifier[nam... | def shutdown(name, wait=False, reboot=False):
"""
graceful shutdown sent to the container
:param wait: should we wait for the shutdown to complete?
:param reboot: reboot a container, ignores wait
"""
if not exists(name):
raise ContainerNotExists('The container (%s) does not exist!' % nam... |
def networks(self):
"""
Return a new raw REST interface to network resources
:rtype: :py:class:`ns1.rest.ipam.Networks`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Networks(self.config) | def function[networks, parameter[self]]:
constant[
Return a new raw REST interface to network resources
:rtype: :py:class:`ns1.rest.ipam.Networks`
]
import module[ns1.rest.ipam]
return[call[name[ns1].rest.ipam.Networks, parameter[name[self].config]]] | keyword[def] identifier[networks] ( identifier[self] ):
literal[string]
keyword[import] identifier[ns1] . identifier[rest] . identifier[ipam]
keyword[return] identifier[ns1] . identifier[rest] . identifier[ipam] . identifier[Networks] ( identifier[self] . identifier[config] ) | def networks(self):
"""
Return a new raw REST interface to network resources
:rtype: :py:class:`ns1.rest.ipam.Networks`
"""
import ns1.rest.ipam
return ns1.rest.ipam.Networks(self.config) |
def computeDelaunayTriangulation(points):
""" Takes a list of point objects (which must have x and y fields).
Returns a list of 3-tuples: the indices of the points that form a
Delaunay triangle.
"""
siteList = SiteList(points)
context = Context()
context.triangulate = True
voron... | def function[computeDelaunayTriangulation, parameter[points]]:
constant[ Takes a list of point objects (which must have x and y fields).
Returns a list of 3-tuples: the indices of the points that form a
Delaunay triangle.
]
variable[siteList] assign[=] call[name[SiteList], parameter[... | keyword[def] identifier[computeDelaunayTriangulation] ( identifier[points] ):
literal[string]
identifier[siteList] = identifier[SiteList] ( identifier[points] )
identifier[context] = identifier[Context] ()
identifier[context] . identifier[triangulate] = keyword[True]
identifier[voronoi] ( i... | def computeDelaunayTriangulation(points):
""" Takes a list of point objects (which must have x and y fields).
Returns a list of 3-tuples: the indices of the points that form a
Delaunay triangle.
"""
siteList = SiteList(points)
context = Context()
context.triangulate = True
vorono... |
def iterativeFetch(query, batchSize=default_batch_size):
"""
Returns rows of a sql fetch query on demand
"""
while True:
rows = query.fetchmany(batchSize)
if not rows:
break
rowDicts = sqliteRowsToDicts(rows)
for rowDict in rowDicts:
yield rowDict | def function[iterativeFetch, parameter[query, batchSize]]:
constant[
Returns rows of a sql fetch query on demand
]
while constant[True] begin[:]
variable[rows] assign[=] call[name[query].fetchmany, parameter[name[batchSize]]]
if <ast.UnaryOp object at 0x7da18ede47... | keyword[def] identifier[iterativeFetch] ( identifier[query] , identifier[batchSize] = identifier[default_batch_size] ):
literal[string]
keyword[while] keyword[True] :
identifier[rows] = identifier[query] . identifier[fetchmany] ( identifier[batchSize] )
keyword[if] keyword[not] identif... | def iterativeFetch(query, batchSize=default_batch_size):
"""
Returns rows of a sql fetch query on demand
"""
while True:
rows = query.fetchmany(batchSize)
if not rows:
break # depends on [control=['if'], data=[]]
rowDicts = sqliteRowsToDicts(rows)
for rowDict... |
def are_checksums_equal(checksum_a_pyxb, checksum_b_pyxb):
"""Determine if checksums are equal.
Args:
checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare.
Returns:
bool
- **True**: The checksums contain the same hexadecimal values calculated with
the same algo... | def function[are_checksums_equal, parameter[checksum_a_pyxb, checksum_b_pyxb]]:
constant[Determine if checksums are equal.
Args:
checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare.
Returns:
bool
- **True**: The checksums contain the same hexadecimal values calculat... | keyword[def] identifier[are_checksums_equal] ( identifier[checksum_a_pyxb] , identifier[checksum_b_pyxb] ):
literal[string]
keyword[if] identifier[checksum_a_pyxb] . identifier[algorithm] != identifier[checksum_b_pyxb] . identifier[algorithm] :
keyword[raise] identifier[ValueError] (
li... | def are_checksums_equal(checksum_a_pyxb, checksum_b_pyxb):
"""Determine if checksums are equal.
Args:
checksum_a_pyxb, checksum_b_pyxb: PyXB Checksum objects to compare.
Returns:
bool
- **True**: The checksums contain the same hexadecimal values calculated with
the same algo... |
def filter_ribo_counts(counts, orf_start=None, orf_stop=None):
"""Filter read counts and return only upstream of orf_start or downstream
of orf_stop.
Keyword arguments:
counts -- Ribo-Seq read counts obtained from get_ribo_counts.
orf_start -- Start position of the longest ORF.
orf_stop -- Sto... | def function[filter_ribo_counts, parameter[counts, orf_start, orf_stop]]:
constant[Filter read counts and return only upstream of orf_start or downstream
of orf_stop.
Keyword arguments:
counts -- Ribo-Seq read counts obtained from get_ribo_counts.
orf_start -- Start position of the longest ORF... | keyword[def] identifier[filter_ribo_counts] ( identifier[counts] , identifier[orf_start] = keyword[None] , identifier[orf_stop] = keyword[None] ):
literal[string]
identifier[filtered_counts] = identifier[dict] . identifier[copy] ( identifier[counts] )
keyword[for] identifier[position] keyword[in] i... | def filter_ribo_counts(counts, orf_start=None, orf_stop=None):
"""Filter read counts and return only upstream of orf_start or downstream
of orf_stop.
Keyword arguments:
counts -- Ribo-Seq read counts obtained from get_ribo_counts.
orf_start -- Start position of the longest ORF.
orf_stop -- Sto... |
def clean(self):
""" Prevents cycles in the tree. """
super(CTENode, self).clean()
if self.parent and self.pk in getattr(self.parent, self._cte_node_path):
raise ValidationError(_("A node cannot be made a descendant of itself.")) | def function[clean, parameter[self]]:
constant[ Prevents cycles in the tree. ]
call[call[name[super], parameter[name[CTENode], name[self]]].clean, parameter[]]
if <ast.BoolOp object at 0x7da2047eb4f0> begin[:]
<ast.Raise object at 0x7da2047e8b20> | keyword[def] identifier[clean] ( identifier[self] ):
literal[string]
identifier[super] ( identifier[CTENode] , identifier[self] ). identifier[clean] ()
keyword[if] identifier[self] . identifier[parent] keyword[and] identifier[self] . identifier[pk] keyword[in] identifier[getattr] ( id... | def clean(self):
""" Prevents cycles in the tree. """
super(CTENode, self).clean()
if self.parent and self.pk in getattr(self.parent, self._cte_node_path):
raise ValidationError(_('A node cannot be made a descendant of itself.')) # depends on [control=['if'], data=[]] |
def plot_projections(x, relative_to=None, autolim=True, axes=None,
subplots_kwargs=dict(), labels=None, plot_function=None,
**kwargs):
"""
Given N-dimensional quantity, ``x``, make a figure containing 2D projections
of all combinations of the axes.
Parameters
... | def function[plot_projections, parameter[x, relative_to, autolim, axes, subplots_kwargs, labels, plot_function]]:
constant[
Given N-dimensional quantity, ``x``, make a figure containing 2D projections
of all combinations of the axes.
Parameters
----------
x : array_like
Array of val... | keyword[def] identifier[plot_projections] ( identifier[x] , identifier[relative_to] = keyword[None] , identifier[autolim] = keyword[True] , identifier[axes] = keyword[None] ,
identifier[subplots_kwargs] = identifier[dict] (), identifier[labels] = keyword[None] , identifier[plot_function] = keyword[None] ,
** identif... | def plot_projections(x, relative_to=None, autolim=True, axes=None, subplots_kwargs=dict(), labels=None, plot_function=None, **kwargs):
"""
Given N-dimensional quantity, ``x``, make a figure containing 2D projections
of all combinations of the axes.
Parameters
----------
x : array_like
A... |
def cql_encode_datetime(self, val):
"""
Converts a :class:`datetime.datetime` object to a (string) integer timestamp
with millisecond precision.
"""
timestamp = calendar.timegm(val.utctimetuple())
return str(long(timestamp * 1e3 + getattr(val, 'microsecond', 0) / 1e3)) | def function[cql_encode_datetime, parameter[self, val]]:
constant[
Converts a :class:`datetime.datetime` object to a (string) integer timestamp
with millisecond precision.
]
variable[timestamp] assign[=] call[name[calendar].timegm, parameter[call[name[val].utctimetuple, parameter... | keyword[def] identifier[cql_encode_datetime] ( identifier[self] , identifier[val] ):
literal[string]
identifier[timestamp] = identifier[calendar] . identifier[timegm] ( identifier[val] . identifier[utctimetuple] ())
keyword[return] identifier[str] ( identifier[long] ( identifier[timestamp... | def cql_encode_datetime(self, val):
"""
Converts a :class:`datetime.datetime` object to a (string) integer timestamp
with millisecond precision.
"""
timestamp = calendar.timegm(val.utctimetuple())
return str(long(timestamp * 1000.0 + getattr(val, 'microsecond', 0) / 1000.0)) |
def _create_pane(self, window=None, command=None, start_directory=None):
"""
Create a new :class:`pymux.arrangement.Pane` instance. (Don't put it in
a window yet.)
:param window: If a window is given, take the CWD of the current
process of that window as the start path for t... | def function[_create_pane, parameter[self, window, command, start_directory]]:
constant[
Create a new :class:`pymux.arrangement.Pane` instance. (Don't put it in
a window yet.)
:param window: If a window is given, take the CWD of the current
process of that window as the star... | keyword[def] identifier[_create_pane] ( identifier[self] , identifier[window] = keyword[None] , identifier[command] = keyword[None] , identifier[start_directory] = keyword[None] ):
literal[string]
keyword[assert] identifier[window] keyword[is] keyword[None] keyword[or] identifier[isinstance] (... | def _create_pane(self, window=None, command=None, start_directory=None):
"""
Create a new :class:`pymux.arrangement.Pane` instance. (Don't put it in
a window yet.)
:param window: If a window is given, take the CWD of the current
process of that window as the start path for this ... |
def description_of(lines, name='stdin'):
"""
Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str
"""
u = Univers... | def function[description_of, parameter[lines, name]]:
constant[
Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str
... | keyword[def] identifier[description_of] ( identifier[lines] , identifier[name] = literal[string] ):
literal[string]
identifier[u] = identifier[UniversalDetector] ()
keyword[for] identifier[line] keyword[in] identifier[lines] :
identifier[line] = identifier[bytearray] ( identifier[line] )
... | def description_of(lines, name='stdin'):
"""
Return a string describing the probable encoding of a file or
list of strings.
:param lines: The lines to get the encoding of.
:type lines: Iterable of bytes
:param name: Name of file or collection of lines
:type name: str
"""
u = Univers... |
def net_graph(block=None, split_state=False):
""" Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest]
Each node can... | def function[net_graph, parameter[block, split_state]]:
constant[ Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest... | keyword[def] identifier[net_graph] ( identifier[block] = keyword[None] , identifier[split_state] = keyword[False] ):
literal[string]
identifier[block] = identifier[working_block] ( identifier[block] )
keyword[from] . identifier[wire] keyword[import] identifier[Register]
identifier[gr... | def net_graph(block=None, split_state=False):
""" Return a graph representation of the current block.
Graph has the following form:
{ node1: { nodeA: edge1A, nodeB: edge1B},
node2: { nodeB: edge2B, nodeC: edge2C},
...
}
aka: edge = graph[source][dest]
Each node can... |
def worksheet(self, title):
"""Returns a worksheet with specified `title`.
:param title: A title of a worksheet. If there're multiple
worksheets with the same title, first one will
be returned.
:type title: int
:returns: an instance of :class... | def function[worksheet, parameter[self, title]]:
constant[Returns a worksheet with specified `title`.
:param title: A title of a worksheet. If there're multiple
worksheets with the same title, first one will
be returned.
:type title: int
:ret... | keyword[def] identifier[worksheet] ( identifier[self] , identifier[title] ):
literal[string]
identifier[sheet_data] = identifier[self] . identifier[fetch_sheet_metadata] ()
keyword[try] :
identifier[item] = identifier[finditem] (
keyword[lambda] identifier[x] : i... | def worksheet(self, title):
"""Returns a worksheet with specified `title`.
:param title: A title of a worksheet. If there're multiple
worksheets with the same title, first one will
be returned.
:type title: int
:returns: an instance of :class:`gs... |
async def _on_message(self, update):
"""Receive a message from a service."""
name = update['service']
message_obj = update['payload']
if name not in self.services:
return
with self._state_lock:
self.services[name].post_message(message_obj['level'], mess... | <ast.AsyncFunctionDef object at 0x7da18fe903a0> | keyword[async] keyword[def] identifier[_on_message] ( identifier[self] , identifier[update] ):
literal[string]
identifier[name] = identifier[update] [ literal[string] ]
identifier[message_obj] = identifier[update] [ literal[string] ]
keyword[if] identifier[name] keyword[not] ... | async def _on_message(self, update):
"""Receive a message from a service."""
name = update['service']
message_obj = update['payload']
if name not in self.services:
return # depends on [control=['if'], data=[]]
with self._state_lock:
self.services[name].post_message(message_obj['leve... |
def communicate(self):
"""Read each request and respond appropriately."""
request_seen = False
try:
while True:
# (re)set req to None so that if something goes wrong in
# the RequestHandlerClass constructor, the error doesn't
# get writ... | def function[communicate, parameter[self]]:
constant[Read each request and respond appropriately.]
variable[request_seen] assign[=] constant[False]
<ast.Try object at 0x7da20c6e6e60> | keyword[def] identifier[communicate] ( identifier[self] ):
literal[string]
identifier[request_seen] = keyword[False]
keyword[try] :
keyword[while] keyword[True] :
identifier[req] = keyword[None]
identi... | def communicate(self):
"""Read each request and respond appropriately."""
request_seen = False
try:
while True:
# (re)set req to None so that if something goes wrong in
# the RequestHandlerClass constructor, the error doesn't
# get written to the previous request.... |
def remove_core_element(self, model):
"""Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return:
"""
assert model.scoped_variable.parent is self.model.state
gui_h... | def function[remove_core_element, parameter[self, model]]:
constant[Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return:
]
assert[compare[name[model].scoped_variable.paren... | keyword[def] identifier[remove_core_element] ( identifier[self] , identifier[model] ):
literal[string]
keyword[assert] identifier[model] . identifier[scoped_variable] . identifier[parent] keyword[is] identifier[self] . identifier[model] . identifier[state]
identifier[gui_helper_state_m... | def remove_core_element(self, model):
"""Remove respective core element of handed scoped variable model
:param ScopedVariableModel model: Scoped variable model which core element should be removed
:return:
"""
assert model.scoped_variable.parent is self.model.state
gui_helper_state_... |
def set_attr(self):
""" set the data for this column """
setattr(self.attrs, self.kind_attr, self.values)
setattr(self.attrs, self.meta_attr, self.meta)
if self.dtype is not None:
setattr(self.attrs, self.dtype_attr, self.dtype) | def function[set_attr, parameter[self]]:
constant[ set the data for this column ]
call[name[setattr], parameter[name[self].attrs, name[self].kind_attr, name[self].values]]
call[name[setattr], parameter[name[self].attrs, name[self].meta_attr, name[self].meta]]
if compare[name[self].dtype ... | keyword[def] identifier[set_attr] ( identifier[self] ):
literal[string]
identifier[setattr] ( identifier[self] . identifier[attrs] , identifier[self] . identifier[kind_attr] , identifier[self] . identifier[values] )
identifier[setattr] ( identifier[self] . identifier[attrs] , identifier[se... | def set_attr(self):
""" set the data for this column """
setattr(self.attrs, self.kind_attr, self.values)
setattr(self.attrs, self.meta_attr, self.meta)
if self.dtype is not None:
setattr(self.attrs, self.dtype_attr, self.dtype) # depends on [control=['if'], data=[]] |
def check_garner(text):
"""Suggest the preferred forms.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = "redundancy.garner"
msg = "Redundancy. Use '{}' instead of '{}'."
redundancies = [
["adequate", ["adequate enough"]],
["ad... | def function[check_garner, parameter[text]]:
constant[Suggest the preferred forms.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
]
variable[err] assign[=] constant[redundancy.garner]
variable[msg] assign[=] constant[Redundancy. Use '{}' instead of '{}'... | keyword[def] identifier[check_garner] ( identifier[text] ):
literal[string]
identifier[err] = literal[string]
identifier[msg] = literal[string]
identifier[redundancies] =[
[ literal[string] ,[ literal[string] ]],
[ literal[string] ,[ literal[string] ]],
[ literal[string] ,[ literal... | def check_garner(text):
"""Suggest the preferred forms.
source: Garner's Modern American Usage
source_url: http://bit.ly/1T4alrY
"""
err = 'redundancy.garner'
msg = "Redundancy. Use '{}' instead of '{}'."
redundancies = [['adequate', ['adequate enough']], ['admitted', ['self-admitted']]... |
def ScanForWindowsVolume(self, source_path):
"""Scans for a Windows volume.
Args:
source_path (str): source path.
Returns:
bool: True if a Windows volume was found.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, ... | def function[ScanForWindowsVolume, parameter[self, source_path]]:
constant[Scans for a Windows volume.
Args:
source_path (str): source path.
Returns:
bool: True if a Windows volume was found.
Raises:
ScannerError: if the source path does not exists, or if the source path
... | keyword[def] identifier[ScanForWindowsVolume] ( identifier[self] , identifier[source_path] ):
literal[string]
identifier[windows_path_specs] = identifier[self] . identifier[GetBasePathSpecs] ( identifier[source_path] )
keyword[if] ( keyword[not] identifier[windows_path_specs] keyword[or]
ident... | def ScanForWindowsVolume(self, source_path):
"""Scans for a Windows volume.
Args:
source_path (str): source path.
Returns:
bool: True if a Windows volume was found.
Raises:
ScannerError: if the source path does not exists, or if the source path
is not a file or directory, ... |
def _warn_about_problematic_credentials(credentials):
"""Determines if the credentials are problematic.
Credentials from the Cloud SDK that are associated with Cloud SDK's project
are problematic because they may not have APIs enabled and have limited
quota. If this is the case, warn about it.
"""
... | def function[_warn_about_problematic_credentials, parameter[credentials]]:
constant[Determines if the credentials are problematic.
Credentials from the Cloud SDK that are associated with Cloud SDK's project
are problematic because they may not have APIs enabled and have limited
quota. If this is th... | keyword[def] identifier[_warn_about_problematic_credentials] ( identifier[credentials] ):
literal[string]
keyword[from] identifier[google] . identifier[auth] keyword[import] identifier[_cloud_sdk]
keyword[if] identifier[credentials] . identifier[client_id] == identifier[_cloud_sdk] . identifier[C... | def _warn_about_problematic_credentials(credentials):
"""Determines if the credentials are problematic.
Credentials from the Cloud SDK that are associated with Cloud SDK's project
are problematic because they may not have APIs enabled and have limited
quota. If this is the case, warn about it.
"""
... |
def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-6, verbose=False):
""" Load an alignment, calculate all pairwise distances and variances
model parameter must be a Substitution model type from phylo_utils """
# Check
if not isinstance(subs_model, phylo_utils.models.Model):
... | def function[pairdists, parameter[alignment, subs_model, alpha, ncat, tolerance, verbose]]:
constant[ Load an alignment, calculate all pairwise distances and variances
model parameter must be a Substitution model type from phylo_utils ]
if <ast.UnaryOp object at 0x7da18bc721a0> begin[:]
... | keyword[def] identifier[pairdists] ( identifier[alignment] , identifier[subs_model] , identifier[alpha] = keyword[None] , identifier[ncat] = literal[int] , identifier[tolerance] = literal[int] , identifier[verbose] = keyword[False] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ... | def pairdists(alignment, subs_model, alpha=None, ncat=4, tolerance=1e-06, verbose=False):
""" Load an alignment, calculate all pairwise distances and variances
model parameter must be a Substitution model type from phylo_utils """
# Check
if not isinstance(subs_model, phylo_utils.models.Model):
... |
def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx):
"""Solves the kriging system by looping over all specified points.
Uses only a certain number of closest points. Not very memory intensive,
but the loop is done in pure Python.
"""
import scipy.linalg.lapack
... | def function[_exec_loop_moving_window, parameter[self, a_all, bd_all, mask, bd_idx]]:
constant[Solves the kriging system by looping over all specified points.
Uses only a certain number of closest points. Not very memory intensive,
but the loop is done in pure Python.
]
import module... | keyword[def] identifier[_exec_loop_moving_window] ( identifier[self] , identifier[a_all] , identifier[bd_all] , identifier[mask] , identifier[bd_idx] ):
literal[string]
keyword[import] identifier[scipy] . identifier[linalg] . identifier[lapack]
identifier[npt] = identifier[bd_all] . ide... | def _exec_loop_moving_window(self, a_all, bd_all, mask, bd_idx):
"""Solves the kriging system by looping over all specified points.
Uses only a certain number of closest points. Not very memory intensive,
but the loop is done in pure Python.
"""
import scipy.linalg.lapack
npt = bd_al... |
def establish(self, call_id, timeout, limit=None,
retry=None, max_retries=None):
"""Waits for the call is accepted by workers and starts to collect the
results.
"""
rejected = 0
retried = 0
results = []
result_queue = self.result_queues[call_id]
... | def function[establish, parameter[self, call_id, timeout, limit, retry, max_retries]]:
constant[Waits for the call is accepted by workers and starts to collect the
results.
]
variable[rejected] assign[=] constant[0]
variable[retried] assign[=] constant[0]
variable[results... | keyword[def] identifier[establish] ( identifier[self] , identifier[call_id] , identifier[timeout] , identifier[limit] = keyword[None] ,
identifier[retry] = keyword[None] , identifier[max_retries] = keyword[None] ):
literal[string]
identifier[rejected] = literal[int]
identifier[retried] =... | def establish(self, call_id, timeout, limit=None, retry=None, max_retries=None):
"""Waits for the call is accepted by workers and starts to collect the
results.
"""
rejected = 0
retried = 0
results = []
result_queue = self.result_queues[call_id]
try:
with Timeout(timeout,... |
def urlunparse(components):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent)."""
scheme, netloc, url, params... | def function[urlunparse, parameter[components]]:
constant[Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent).]
... | keyword[def] identifier[urlunparse] ( identifier[components] ):
literal[string]
identifier[scheme] , identifier[netloc] , identifier[url] , identifier[params] , identifier[query] , identifier[fragment] , identifier[_coerce_result] =(
identifier[_coerce_args] (* identifier[components] ))
keyword[i... | def urlunparse(components):
"""Put a parsed URL back together again. This may result in a
slightly different, but equivalent URL, if the URL that was parsed
originally had redundant delimiters, e.g. a ? with an empty query
(the draft states that these are equivalent)."""
(scheme, netloc, url, param... |
def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
"""Emit an event to the Datadog Event Stream."""
event_dict = {
'timestamp': int(time()),
'source_type_name': self.SOURCE_TYPE_NAME,
'msg_title': title,
'event_type': e... | def function[_send_event, parameter[self, title, text, tags, event_type, aggregation_key, severity]]:
constant[Emit an event to the Datadog Event Stream.]
variable[event_dict] assign[=] dictionary[[<ast.Constant object at 0x7da1b21bb250>, <ast.Constant object at 0x7da1b21bad70>, <ast.Constant object at ... | keyword[def] identifier[_send_event] ( identifier[self] , identifier[title] , identifier[text] , identifier[tags] , identifier[event_type] , identifier[aggregation_key] , identifier[severity] = literal[string] ):
literal[string]
identifier[event_dict] ={
literal[string] : identifier[int] (... | def _send_event(self, title, text, tags, event_type, aggregation_key, severity='info'):
"""Emit an event to the Datadog Event Stream."""
event_dict = {'timestamp': int(time()), 'source_type_name': self.SOURCE_TYPE_NAME, 'msg_title': title, 'event_type': event_type, 'alert_type': severity, 'msg_text': text, 'tag... |
def location(self, x=None, y=None):
''' Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
'''
stream = self._stream
stream.write(self.save_p... | def function[location, parameter[self, x, y]]:
constant[ Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
]
variable[stream] assign[=] name[self]._... | keyword[def] identifier[location] ( identifier[self] , identifier[x] = keyword[None] , identifier[y] = keyword[None] ):
literal[string]
identifier[stream] = identifier[self] . identifier[_stream]
identifier[stream] . identifier[write] ( identifier[self] . identifier[save_pos] )
... | def location(self, x=None, y=None):
""" Temporarily move the cursor, perform work, and return to the
previous location.
::
with screen.location(40, 20):
print('Hello, world!')
"""
stream = self._stream
stream.write(self.save_pos) # curso... |
def cookiestring(self, value):
""""Cookie string setter"""
c = Cookie.SimpleCookie(value)
sc = [(i.key, i.value) for i in c.values()]
self.cookies = dict(sc) | def function[cookiestring, parameter[self, value]]:
constant["Cookie string setter]
variable[c] assign[=] call[name[Cookie].SimpleCookie, parameter[name[value]]]
variable[sc] assign[=] <ast.ListComp object at 0x7da1b2405330>
name[self].cookies assign[=] call[name[dict], parameter[name[sc... | keyword[def] identifier[cookiestring] ( identifier[self] , identifier[value] ):
literal[string]
identifier[c] = identifier[Cookie] . identifier[SimpleCookie] ( identifier[value] )
identifier[sc] =[( identifier[i] . identifier[key] , identifier[i] . identifier[value] ) keyword[for] identif... | def cookiestring(self, value):
""""Cookie string setter"""
c = Cookie.SimpleCookie(value)
sc = [(i.key, i.value) for i in c.values()]
self.cookies = dict(sc) |
def add_streamer(self, streamer):
"""Add a streamer to this sensor graph.
Args:
streamer (DataStreamer): The streamer we want to add
"""
if self._max_streamers is not None and len(self.streamers) >= self._max_streamers:
raise ResourceUsageError("Maximum number o... | def function[add_streamer, parameter[self, streamer]]:
constant[Add a streamer to this sensor graph.
Args:
streamer (DataStreamer): The streamer we want to add
]
if <ast.BoolOp object at 0x7da18fe91090> begin[:]
<ast.Raise object at 0x7da18fe92ad0>
call[name[... | keyword[def] identifier[add_streamer] ( identifier[self] , identifier[streamer] ):
literal[string]
keyword[if] identifier[self] . identifier[_max_streamers] keyword[is] keyword[not] keyword[None] keyword[and] identifier[len] ( identifier[self] . identifier[streamers] )>= identifier[self] . i... | def add_streamer(self, streamer):
"""Add a streamer to this sensor graph.
Args:
streamer (DataStreamer): The streamer we want to add
"""
if self._max_streamers is not None and len(self.streamers) >= self._max_streamers:
raise ResourceUsageError('Maximum number of streamers e... |
def generate_if_then_else(self):
"""
Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else... | def function[generate_if_then_else, parameter[self]]:
constant[
Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
... | keyword[def] identifier[generate_if_then_else] ( identifier[self] ):
literal[string]
keyword[with] identifier[self] . identifier[l] ( literal[string] ):
identifier[self] . identifier[generate_func_code_block] (
identifier[self] . identifier[_definition] [ literal[string] ... | def generate_if_then_else(self):
"""
Implementation of if-then-else.
.. code-block:: python
{
'if': {
'exclusiveMaximum': 0,
},
'then': {
'minimum': -10,
},
'else': {... |
def list(self, platformIdentifier, configuration, libOverrides = {}):
"""
Returns the list of supported UE4-bundled third-party libraries
"""
modules = self._getThirdPartyLibs(platformIdentifier, configuration)
return sorted([m['Name'] for m in modules] + [key for key in libOverrides]) | def function[list, parameter[self, platformIdentifier, configuration, libOverrides]]:
constant[
Returns the list of supported UE4-bundled third-party libraries
]
variable[modules] assign[=] call[name[self]._getThirdPartyLibs, parameter[name[platformIdentifier], name[configuration]]]
return[call[... | keyword[def] identifier[list] ( identifier[self] , identifier[platformIdentifier] , identifier[configuration] , identifier[libOverrides] ={}):
literal[string]
identifier[modules] = identifier[self] . identifier[_getThirdPartyLibs] ( identifier[platformIdentifier] , identifier[configuration] )
keyword[return... | def list(self, platformIdentifier, configuration, libOverrides={}):
"""
Returns the list of supported UE4-bundled third-party libraries
"""
modules = self._getThirdPartyLibs(platformIdentifier, configuration)
return sorted([m['Name'] for m in modules] + [key for key in libOverrides]) |
def validate_comma_separated_emails(value):
"""
Validate every email address in a comma separated list of emails.
"""
if not isinstance(value, (tuple, list)):
raise ValidationError('Email list must be a list/tuple.')
for email in value:
try:
validate_email_with_name(emai... | def function[validate_comma_separated_emails, parameter[value]]:
constant[
Validate every email address in a comma separated list of emails.
]
if <ast.UnaryOp object at 0x7da204347340> begin[:]
<ast.Raise object at 0x7da204347b50>
for taget[name[email]] in starred[name[value]] be... | keyword[def] identifier[validate_comma_separated_emails] ( identifier[value] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[value] ,( identifier[tuple] , identifier[list] )):
keyword[raise] identifier[ValidationError] ( literal[string] )
keyword[for] iden... | def validate_comma_separated_emails(value):
"""
Validate every email address in a comma separated list of emails.
"""
if not isinstance(value, (tuple, list)):
raise ValidationError('Email list must be a list/tuple.') # depends on [control=['if'], data=[]]
for email in value:
try:
... |
def get_source_kernel(gta, name, kernel=None):
"""Get the PDF for the given source."""
sm = []
zs = 0
for c in gta.components:
z = c.model_counts_map(name).data.astype('float')
if kernel is not None:
shape = (z.shape[0],) + kernel.shape
z = np.apply_over_axes(np.... | def function[get_source_kernel, parameter[gta, name, kernel]]:
constant[Get the PDF for the given source.]
variable[sm] assign[=] list[[]]
variable[zs] assign[=] constant[0]
for taget[name[c]] in starred[name[gta].components] begin[:]
variable[z] assign[=] call[call[name[... | keyword[def] identifier[get_source_kernel] ( identifier[gta] , identifier[name] , identifier[kernel] = keyword[None] ):
literal[string]
identifier[sm] =[]
identifier[zs] = literal[int]
keyword[for] identifier[c] keyword[in] identifier[gta] . identifier[components] :
identifier[z] = ... | def get_source_kernel(gta, name, kernel=None):
"""Get the PDF for the given source."""
sm = []
zs = 0
for c in gta.components:
z = c.model_counts_map(name).data.astype('float')
if kernel is not None:
shape = (z.shape[0],) + kernel.shape
z = np.apply_over_axes(np.s... |
def _expand_nbest_translation(translation: Translation) -> List[Translation]:
"""
Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects.
"""
nbest_list = ... | def function[_expand_nbest_translation, parameter[translation]]:
constant[
Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects.
]
variable[nbest... | keyword[def] identifier[_expand_nbest_translation] ( identifier[translation] : identifier[Translation] )-> identifier[List] [ identifier[Translation] ]:
literal[string]
identifier[nbest_list] =[]
keyword[for] identifier[target_ids] , identifier[attention_matrix] , identifier[score] keyword[in] iden... | def _expand_nbest_translation(translation: Translation) -> List[Translation]:
"""
Expand nbest translations in a single Translation object to one Translation
object per nbest translation.
:param translation: A Translation object.
:return: A list of Translation objects.
"""
nbest_list = ... |
def do_handle_log(self, workunit, level, *msg_elements):
"""Implementation of Reporter callback."""
if not self.is_under_main_root(workunit):
return
# If the element is a (msg, detail) pair, we ignore the detail. There's no
# useful way to display it on the console.
elements = [e if isinstanc... | def function[do_handle_log, parameter[self, workunit, level]]:
constant[Implementation of Reporter callback.]
if <ast.UnaryOp object at 0x7da1b2293e50> begin[:]
return[None]
variable[elements] assign[=] <ast.ListComp object at 0x7da1b2290460>
variable[msg] assign[=] binary_operat... | keyword[def] identifier[do_handle_log] ( identifier[self] , identifier[workunit] , identifier[level] ,* identifier[msg_elements] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[is_under_main_root] ( identifier[workunit] ):
keyword[return]
identifier[e... | def do_handle_log(self, workunit, level, *msg_elements):
"""Implementation of Reporter callback."""
if not self.is_under_main_root(workunit):
return # depends on [control=['if'], data=[]]
# If the element is a (msg, detail) pair, we ignore the detail. There's no
# useful way to display it on th... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.