code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def _listen_inbox_messages(self):
"""Start listening to messages, using a separate thread."""
# Collect messages in a queue
inbox_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs inbox threads
for i ... | def function[_listen_inbox_messages, parameter[self]]:
constant[Start listening to messages, using a separate thread.]
variable[inbox_queue] assign[=] call[name[Queue], parameter[]]
variable[threads] assign[=] list[[]]
<ast.Try object at 0x7da1b1d21cf0> | keyword[def] identifier[_listen_inbox_messages] ( identifier[self] ):
literal[string]
identifier[inbox_queue] = identifier[Queue] ( identifier[maxsize] = identifier[self] . identifier[_n_jobs] * literal[int] )
identifier[threads] =[]
keyword[try] :
... | def _listen_inbox_messages(self):
"""Start listening to messages, using a separate thread."""
# Collect messages in a queue
inbox_queue = Queue(maxsize=self._n_jobs * 4)
threads = [] # type: List[BotQueueWorker]
try:
# Create n_jobs inbox threads
for i in range(self._n_jobs):
... |
def getFileFormat(self, name, args):
""" Récupération du contenu d'un fichier via la configuration
et interprétation des variables données en argument """
# récupération du nom du fichier
template_pathname = self.get(name, "--")
if not os.path.isfile(template_pathname):
return False
# configuration
c... | def function[getFileFormat, parameter[self, name, args]]:
constant[ Récupération du contenu d'un fichier via la configuration
et interprétation des variables données en argument ]
variable[template_pathname] assign[=] call[name[self].get, parameter[name[name], constant[--]]]
if <ast.UnaryOp o... | keyword[def] identifier[getFileFormat] ( identifier[self] , identifier[name] , identifier[args] ):
literal[string]
identifier[template_pathname] = identifier[self] . identifier[get] ( identifier[name] , literal[string] )
keyword[if] keyword[not] identifier[os] . identifier[path] . identifier[isfile] ( ... | def getFileFormat(self, name, args):
""" Récupération du contenu d'un fichier via la configuration
et interprétation des variables données en argument """ # récupération du nom du fichier
template_pathname = self.get(name, '--')
if not os.path.isfile(template_pathname):
return False # depends o... |
def counts_to_dicts(df, column):
"""
convert (values, counts) as returned by aggregate.aggregate_counts() to dicts
makes expand_counts much faster
"""
# index where there are counts and they aren't null
d = df[column].apply(lambda c: pd.notnull(c) and len(c[0]) > 0)
return df.loc[d, column].... | def function[counts_to_dicts, parameter[df, column]]:
constant[
convert (values, counts) as returned by aggregate.aggregate_counts() to dicts
makes expand_counts much faster
]
variable[d] assign[=] call[call[name[df]][name[column]].apply, parameter[<ast.Lambda object at 0x7da1b23514e0>]]
... | keyword[def] identifier[counts_to_dicts] ( identifier[df] , identifier[column] ):
literal[string]
identifier[d] = identifier[df] [ identifier[column] ]. identifier[apply] ( keyword[lambda] identifier[c] : identifier[pd] . identifier[notnull] ( identifier[c] ) keyword[and] identifier[len] ( identifie... | def counts_to_dicts(df, column):
"""
convert (values, counts) as returned by aggregate.aggregate_counts() to dicts
makes expand_counts much faster
"""
# index where there are counts and they aren't null
d = df[column].apply(lambda c: pd.notnull(c) and len(c[0]) > 0)
return df.loc[d, column].... |
def prefixed(self, identifier, version):
"""
Whether or not the identifier will be prefixed.
Strings that require the prefix are generally not recommended.
"""
invalid_starting = ['Mn', 'Mc', 'Nd', 'Pc']
if identifier.startswith('_'): return True
return((identifi... | def function[prefixed, parameter[self, identifier, version]]:
constant[
Whether or not the identifier will be prefixed.
Strings that require the prefix are generally not recommended.
]
variable[invalid_starting] assign[=] list[[<ast.Constant object at 0x7da18dc079a0>, <ast.Consta... | keyword[def] identifier[prefixed] ( identifier[self] , identifier[identifier] , identifier[version] ):
literal[string]
identifier[invalid_starting] =[ literal[string] , literal[string] , literal[string] , literal[string] ]
keyword[if] identifier[identifier] . identifier[startswith] ( lite... | def prefixed(self, identifier, version):
"""
Whether or not the identifier will be prefixed.
Strings that require the prefix are generally not recommended.
"""
invalid_starting = ['Mn', 'Mc', 'Nd', 'Pc']
if identifier.startswith('_'):
return True # depends on [control=['if']... |
def show_grid(cells, data):
"""!
@brief Show CLIQUE blocks as a grid in data space.
@details Each block contains points and according to this density is displayed. CLIQUE grid helps to visualize
grid that was used for clustering process.
@param[in] cells (list): ... | def function[show_grid, parameter[cells, data]]:
constant[!
@brief Show CLIQUE blocks as a grid in data space.
@details Each block contains points and according to this density is displayed. CLIQUE grid helps to visualize
grid that was used for clustering process.
@par... | keyword[def] identifier[show_grid] ( identifier[cells] , identifier[data] ):
literal[string]
identifier[dimension] = identifier[cells] [ literal[int] ]. identifier[dimensions]
identifier[amount_canvases] = literal[int]
keyword[if] identifier[dimension] > literal[int] :
... | def show_grid(cells, data):
"""!
@brief Show CLIQUE blocks as a grid in data space.
@details Each block contains points and according to this density is displayed. CLIQUE grid helps to visualize
grid that was used for clustering process.
@param[in] cells (list): List of ce... |
def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
... | def function[findParent, parameter[self, name, attrs]]:
constant[Returns the closest parent of this Tag that matches the given
criteria.]
variable[r] assign[=] constant[None]
variable[l] assign[=] call[name[self].findParents, parameter[name[name], name[attrs], constant[1]]]
if na... | keyword[def] identifier[findParent] ( identifier[self] , identifier[name] = keyword[None] , identifier[attrs] ={},** identifier[kwargs] ):
literal[string]
identifier[r] = keyword[None]
identifier[l] = identifier[self] . identifier[findParents] ( identifier[name] , identi... | def findParent(self, name=None, attrs={}, **kwargs):
"""Returns the closest parent of this Tag that matches the given
criteria."""
# NOTE: We can't use _findOne because findParents takes a different
# set of arguments.
r = None
l = self.findParents(name, attrs, 1)
if l:
r = l[0] ... |
def autocut_params_changed_cb(self, paramObj, ac_obj):
"""This callback is called when the user changes the attributes of
an object via the paramSet.
"""
args, kwdargs = paramObj.get_params()
params = list(kwdargs.items())
self.t_.set(autocut_params=params) | def function[autocut_params_changed_cb, parameter[self, paramObj, ac_obj]]:
constant[This callback is called when the user changes the attributes of
an object via the paramSet.
]
<ast.Tuple object at 0x7da1b0d55cc0> assign[=] call[name[paramObj].get_params, parameter[]]
variable[... | keyword[def] identifier[autocut_params_changed_cb] ( identifier[self] , identifier[paramObj] , identifier[ac_obj] ):
literal[string]
identifier[args] , identifier[kwdargs] = identifier[paramObj] . identifier[get_params] ()
identifier[params] = identifier[list] ( identifier[kwdargs] . ident... | def autocut_params_changed_cb(self, paramObj, ac_obj):
"""This callback is called when the user changes the attributes of
an object via the paramSet.
"""
(args, kwdargs) = paramObj.get_params()
params = list(kwdargs.items())
self.t_.set(autocut_params=params) |
def center_widget_on_screen(widget, screen=None):
"""
Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool
"""
screen = screen and screen or... | def function[center_widget_on_screen, parameter[widget, screen]]:
constant[
Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool
]
va... | keyword[def] identifier[center_widget_on_screen] ( identifier[widget] , identifier[screen] = keyword[None] ):
literal[string]
identifier[screen] = identifier[screen] keyword[and] identifier[screen] keyword[or] identifier[QApplication] . identifier[desktop] (). identifier[primaryScreen] ()
identif... | def center_widget_on_screen(widget, screen=None):
"""
Centers given Widget on the screen.
:param widget: Current Widget.
:type widget: QWidget
:param screen: Screen used for centering.
:type screen: int
:return: Definition success.
:rtype: bool
"""
screen = screen and screen or ... |
def create_inputhook_qt5(mgr, app=None):
"""Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, an... | def function[create_inputhook_qt5, parameter[mgr, app]]:
constant[Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
exist... | keyword[def] identifier[create_inputhook_qt5] ( identifier[mgr] , identifier[app] = keyword[None] ):
literal[string]
keyword[if] identifier[app] keyword[is] keyword[None] :
identifier[app] = identifier[QtCore] . identifier[QCoreApplication] . identifier[instance] ()
keyword[if] ident... | def create_inputhook_qt5(mgr, app=None):
"""Create an input hook for running the Qt5 application event loop.
Parameters
----------
mgr : an InputHookManager
app : Qt Application, optional.
Running application to use. If not given, we probe Qt for an
existing application object, an... |
def setup(app):
"""Initialize Sphinx extension."""
app.setup_extension('nbsphinx')
app.add_source_suffix('.nblink', 'linked_jupyter_notebook')
app.add_source_parser(LinkedNotebookParser)
app.add_config_value('nbsphinx_link_target_root', None, rebuild='env')
return {'version': __version__, 'para... | def function[setup, parameter[app]]:
constant[Initialize Sphinx extension.]
call[name[app].setup_extension, parameter[constant[nbsphinx]]]
call[name[app].add_source_suffix, parameter[constant[.nblink], constant[linked_jupyter_notebook]]]
call[name[app].add_source_parser, parameter[name[L... | keyword[def] identifier[setup] ( identifier[app] ):
literal[string]
identifier[app] . identifier[setup_extension] ( literal[string] )
identifier[app] . identifier[add_source_suffix] ( literal[string] , literal[string] )
identifier[app] . identifier[add_source_parser] ( identifier[LinkedNotebookPa... | def setup(app):
"""Initialize Sphinx extension."""
app.setup_extension('nbsphinx')
app.add_source_suffix('.nblink', 'linked_jupyter_notebook')
app.add_source_parser(LinkedNotebookParser)
app.add_config_value('nbsphinx_link_target_root', None, rebuild='env')
return {'version': __version__, 'paral... |
def get_collection(cls, request_args):
r"""
Used to fetch a collection of resource object of type 'cls' in response to a GET request\
. get_resource_or_collection should only be invoked on a resource when the client specifies a GET request.
:param request_args: The query parameters supp... | def function[get_collection, parameter[cls, request_args]]:
constant[
Used to fetch a collection of resource object of type 'cls' in response to a GET request\
. get_resource_or_collection should only be invoked on a resource when the client specifies a GET request.
:param request_args:... | keyword[def] identifier[get_collection] ( identifier[cls] , identifier[request_args] ):
literal[string]
keyword[try] :
keyword[if] identifier[request_args] . identifier[get] ( literal[string] ):
keyword[raise] identifier[ParameterNotSupported]
identifi... | def get_collection(cls, request_args):
"""
Used to fetch a collection of resource object of type 'cls' in response to a GET request\\
. get_resource_or_collection should only be invoked on a resource when the client specifies a GET request.
:param request_args: The query parameters supplied... |
def volume_percentage_used(self, volume):
"""Total used size in percentage for volume"""
volume = self._get_volume(volume)
if volume is not None:
total = int(volume["size"]["total"])
used = int(volume["size"]["used"])
if used is not None and used > 0 a... | def function[volume_percentage_used, parameter[self, volume]]:
constant[Total used size in percentage for volume]
variable[volume] assign[=] call[name[self]._get_volume, parameter[name[volume]]]
if compare[name[volume] is_not constant[None]] begin[:]
variable[total] assign[=] cal... | keyword[def] identifier[volume_percentage_used] ( identifier[self] , identifier[volume] ):
literal[string]
identifier[volume] = identifier[self] . identifier[_get_volume] ( identifier[volume] )
keyword[if] identifier[volume] keyword[is] keyword[not] keyword[None] :
ide... | def volume_percentage_used(self, volume):
"""Total used size in percentage for volume"""
volume = self._get_volume(volume)
if volume is not None:
total = int(volume['size']['total'])
used = int(volume['size']['used'])
if used is not None and used > 0 and (total is not None) and (tota... |
def _sinusoid(x, p, L, y):
""" Return the sinusoid cont func evaluated at input x for the continuum.
Parameters
----------
x: float or np.array
data, input to function
p: ndarray
coefficients of fitting function
L: float
width of x data
y: float or np.array
... | def function[_sinusoid, parameter[x, p, L, y]]:
constant[ Return the sinusoid cont func evaluated at input x for the continuum.
Parameters
----------
x: float or np.array
data, input to function
p: ndarray
coefficients of fitting function
L: float
width of x data
... | keyword[def] identifier[_sinusoid] ( identifier[x] , identifier[p] , identifier[L] , identifier[y] ):
literal[string]
identifier[N] = identifier[int] ( identifier[len] ( identifier[p] )/ literal[int] )
identifier[n] = identifier[np] . identifier[linspace] ( literal[int] , identifier[N] , identifier[N]... | def _sinusoid(x, p, L, y):
""" Return the sinusoid cont func evaluated at input x for the continuum.
Parameters
----------
x: float or np.array
data, input to function
p: ndarray
coefficients of fitting function
L: float
width of x data
y: float or np.array
... |
def compose(self, file_path, velocity_mean=None, velocity_std=None):
'''
Compose by learned model.
Args:
file_path: Path to generated MIDI file.
velocity_mean: Mean of velocity.
This class samples the velocity from a Gaussian di... | def function[compose, parameter[self, file_path, velocity_mean, velocity_std]]:
constant[
Compose by learned model.
Args:
file_path: Path to generated MIDI file.
velocity_mean: Mean of velocity.
This class samples the velocity from a Ga... | keyword[def] identifier[compose] ( identifier[self] , identifier[file_path] , identifier[velocity_mean] = keyword[None] , identifier[velocity_std] = keyword[None] ):
literal[string]
identifier[generated_arr] = identifier[self] . identifier[__generative_model] . identifier[draw] ()
ident... | def compose(self, file_path, velocity_mean=None, velocity_std=None):
"""
Compose by learned model.
Args:
file_path: Path to generated MIDI file.
velocity_mean: Mean of velocity.
This class samples the velocity from a Gaussian distribution o... |
def get_git_status(git_path='git'):
"""Returns the state of the git working copy
"""
status_output = subprocess.call((git_path, 'diff-files', '--quiet'))
if status_output != 0:
return 'UNCLEAN: Modified working tree'
else:
# check index for changes
status_output = subprocess.... | def function[get_git_status, parameter[git_path]]:
constant[Returns the state of the git working copy
]
variable[status_output] assign[=] call[name[subprocess].call, parameter[tuple[[<ast.Name object at 0x7da204621c90>, <ast.Constant object at 0x7da204621780>, <ast.Constant object at 0x7da204623940>... | keyword[def] identifier[get_git_status] ( identifier[git_path] = literal[string] ):
literal[string]
identifier[status_output] = identifier[subprocess] . identifier[call] (( identifier[git_path] , literal[string] , literal[string] ))
keyword[if] identifier[status_output] != literal[int] :
key... | def get_git_status(git_path='git'):
"""Returns the state of the git working copy
"""
status_output = subprocess.call((git_path, 'diff-files', '--quiet'))
if status_output != 0:
return 'UNCLEAN: Modified working tree' # depends on [control=['if'], data=[]]
else:
# check index for cha... |
def get_chasm_context(tri_nuc):
"""Returns the mutation context acording to CHASM.
For more information about CHASM's mutation context, look
at http://wiki.chasmsoftware.org/index.php/CHASM_Overview.
Essentially CHASM uses a few specified di-nucleotide contexts
followed by single nucleotide context... | def function[get_chasm_context, parameter[tri_nuc]]:
constant[Returns the mutation context acording to CHASM.
For more information about CHASM's mutation context, look
at http://wiki.chasmsoftware.org/index.php/CHASM_Overview.
Essentially CHASM uses a few specified di-nucleotide contexts
follow... | keyword[def] identifier[get_chasm_context] ( identifier[tri_nuc] ):
literal[string]
keyword[if] identifier[len] ( identifier[tri_nuc] )!= literal[int] :
keyword[raise] identifier[ValueError] ( literal[string]
literal[string] . identifier[format] ( identifier[tri_nuc] ))
... | def get_chasm_context(tri_nuc):
"""Returns the mutation context acording to CHASM.
For more information about CHASM's mutation context, look
at http://wiki.chasmsoftware.org/index.php/CHASM_Overview.
Essentially CHASM uses a few specified di-nucleotide contexts
followed by single nucleotide context... |
def intersection (set1, set2):
""" Removes from set1 any items which don't appear in set2 and returns the result.
"""
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append (v)
return result | def function[intersection, parameter[set1, set2]]:
constant[ Removes from set1 any items which don't appear in set2 and returns the result.
]
assert[call[name[is_iterable], parameter[name[set1]]]]
assert[call[name[is_iterable], parameter[name[set2]]]]
variable[result] assign[=] list[[]]
... | keyword[def] identifier[intersection] ( identifier[set1] , identifier[set2] ):
literal[string]
keyword[assert] identifier[is_iterable] ( identifier[set1] )
keyword[assert] identifier[is_iterable] ( identifier[set2] )
identifier[result] =[]
keyword[for] identifier[v] keyword[in] identifi... | def intersection(set1, set2):
""" Removes from set1 any items which don't appear in set2 and returns the result.
"""
assert is_iterable(set1)
assert is_iterable(set2)
result = []
for v in set1:
if v in set2:
result.append(v) # depends on [control=['if'], data=['v']] # depen... |
def _load(self):
"""Load data from a pickle file. """
with open(self._pickle_file, 'rb') as source:
pickler = pickle.Unpickler(source)
for attribute in self._pickle_attributes:
pickle_data = pickler.load()
setattr(self, attribute, pickle_data) | def function[_load, parameter[self]]:
constant[Load data from a pickle file. ]
with call[name[open], parameter[name[self]._pickle_file, constant[rb]]] begin[:]
variable[pickler] assign[=] call[name[pickle].Unpickler, parameter[name[source]]]
for taget[name[attribute]] in ... | keyword[def] identifier[_load] ( identifier[self] ):
literal[string]
keyword[with] identifier[open] ( identifier[self] . identifier[_pickle_file] , literal[string] ) keyword[as] identifier[source] :
identifier[pickler] = identifier[pickle] . identifier[Unpickler] ( identifier[source]... | def _load(self):
"""Load data from a pickle file. """
with open(self._pickle_file, 'rb') as source:
pickler = pickle.Unpickler(source)
for attribute in self._pickle_attributes:
pickle_data = pickler.load()
setattr(self, attribute, pickle_data) # depends on [control=['for... |
def parse_default_property_value(property_name, property_type_id, default_value_string):
"""Parse the default value string into its proper form given the property type ID.
Args:
property_name: string, the name of the property whose default value is being parsed.
Used primarily to... | def function[parse_default_property_value, parameter[property_name, property_type_id, default_value_string]]:
constant[Parse the default value string into its proper form given the property type ID.
Args:
property_name: string, the name of the property whose default value is being parsed.
... | keyword[def] identifier[parse_default_property_value] ( identifier[property_name] , identifier[property_type_id] , identifier[default_value_string] ):
literal[string]
keyword[if] identifier[property_type_id] == identifier[PROPERTY_TYPE_EMBEDDED_SET_ID] keyword[and] identifier[default_value_string] == li... | def parse_default_property_value(property_name, property_type_id, default_value_string):
"""Parse the default value string into its proper form given the property type ID.
Args:
property_name: string, the name of the property whose default value is being parsed.
Used primarily to... |
def start(self):
"""Start this gateway agent."""
self._prepare()
self._disconnector = tornado.ioloop.PeriodicCallback(self._disconnect_hanging_devices, 1000, self._loop)
self._disconnector.start() | def function[start, parameter[self]]:
constant[Start this gateway agent.]
call[name[self]._prepare, parameter[]]
name[self]._disconnector assign[=] call[name[tornado].ioloop.PeriodicCallback, parameter[name[self]._disconnect_hanging_devices, constant[1000], name[self]._loop]]
call[name[s... | keyword[def] identifier[start] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_prepare] ()
identifier[self] . identifier[_disconnector] = identifier[tornado] . identifier[ioloop] . identifier[PeriodicCallback] ( identifier[self] . identifier[_disconnect_hanging_devic... | def start(self):
"""Start this gateway agent."""
self._prepare()
self._disconnector = tornado.ioloop.PeriodicCallback(self._disconnect_hanging_devices, 1000, self._loop)
self._disconnector.start() |
def _bin(g):
"""Applies the BIN rule to 'g' (see top comment)."""
new_rules = []
for rule in g.rules:
if len(rule.rhs) > 2:
new_rules += _split(rule)
else:
new_rules.append(rule)
return Grammar(new_rules) | def function[_bin, parameter[g]]:
constant[Applies the BIN rule to 'g' (see top comment).]
variable[new_rules] assign[=] list[[]]
for taget[name[rule]] in starred[name[g].rules] begin[:]
if compare[call[name[len], parameter[name[rule].rhs]] greater[>] constant[2]] begin[:]
... | keyword[def] identifier[_bin] ( identifier[g] ):
literal[string]
identifier[new_rules] =[]
keyword[for] identifier[rule] keyword[in] identifier[g] . identifier[rules] :
keyword[if] identifier[len] ( identifier[rule] . identifier[rhs] )> literal[int] :
identifier[new_rules] +=... | def _bin(g):
"""Applies the BIN rule to 'g' (see top comment)."""
new_rules = []
for rule in g.rules:
if len(rule.rhs) > 2:
new_rules += _split(rule) # depends on [control=['if'], data=[]]
else:
new_rules.append(rule) # depends on [control=['for'], data=['rule']]
... |
def list(self, **kwargs):
"""
Returns a list of items in the database. Encrypted attributes are not
decrypted when listing items.
"""
response = self._new_response()
if self._check_supported_op('list', response):
self._call_ddb_method(self.table.scan, {}, res... | def function[list, parameter[self]]:
constant[
Returns a list of items in the database. Encrypted attributes are not
decrypted when listing items.
]
variable[response] assign[=] call[name[self]._new_response, parameter[]]
if call[name[self]._check_supported_op, parameter... | keyword[def] identifier[list] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[response] = identifier[self] . identifier[_new_response] ()
keyword[if] identifier[self] . identifier[_check_supported_op] ( literal[string] , identifier[response] ):
identif... | def list(self, **kwargs):
"""
Returns a list of items in the database. Encrypted attributes are not
decrypted when listing items.
"""
response = self._new_response()
if self._check_supported_op('list', response):
self._call_ddb_method(self.table.scan, {}, response)
i... |
def read_loop(self):
"""
Infinite loop that reads messages off of the socket while not closed.
When a message is received its corresponding pending Future is set
to have the message as its result.
This is never used directly and is fired as a separate callback on the
I/... | def function[read_loop, parameter[self]]:
constant[
Infinite loop that reads messages off of the socket while not closed.
When a message is received its corresponding pending Future is set
to have the message as its result.
This is never used directly and is fired as a separate... | keyword[def] identifier[read_loop] ( identifier[self] ):
literal[string]
keyword[while] keyword[not] identifier[self] . identifier[closing] :
keyword[try] :
identifier[xid] , identifier[zxid] , identifier[response] = keyword[yield] identifier[self] . identifier[read... | def read_loop(self):
"""
Infinite loop that reads messages off of the socket while not closed.
When a message is received its corresponding pending Future is set
to have the message as its result.
This is never used directly and is fired as a separate callback on the
I/O lo... |
def receive_subscription_message(self, topic_name, subscription_name,
peek_lock=True, timeout=60):
'''
Receive a message from a subscription for processing.
topic_name:
Name of the topic.
subscription_name:
Name of the subscri... | def function[receive_subscription_message, parameter[self, topic_name, subscription_name, peek_lock, timeout]]:
constant[
Receive a message from a subscription for processing.
topic_name:
Name of the topic.
subscription_name:
Name of the subscription.
pee... | keyword[def] identifier[receive_subscription_message] ( identifier[self] , identifier[topic_name] , identifier[subscription_name] ,
identifier[peek_lock] = keyword[True] , identifier[timeout] = literal[int] ):
literal[string]
keyword[if] identifier[peek_lock] :
keyword[return] ident... | def receive_subscription_message(self, topic_name, subscription_name, peek_lock=True, timeout=60):
"""
Receive a message from a subscription for processing.
topic_name:
Name of the topic.
subscription_name:
Name of the subscription.
peek_lock:
Opt... |
def filter(self, media_type, **params):
"""
iterate all the accept media types that match media_type
media_type -- string -- the media type to filter by
**params -- dict -- further filter by key: val
return -- generator -- yields all matching media type info things
"""
... | def function[filter, parameter[self, media_type]]:
constant[
iterate all the accept media types that match media_type
media_type -- string -- the media type to filter by
**params -- dict -- further filter by key: val
return -- generator -- yields all matching media type info th... | keyword[def] identifier[filter] ( identifier[self] , identifier[media_type] ,** identifier[params] ):
literal[string]
identifier[mtype] , identifier[msubtype] = identifier[self] . identifier[_split_media_type] ( identifier[media_type] )
keyword[for] identifier[x] keyword[in] identifier[... | def filter(self, media_type, **params):
"""
iterate all the accept media types that match media_type
media_type -- string -- the media type to filter by
**params -- dict -- further filter by key: val
return -- generator -- yields all matching media type info things
"""
... |
def getJobStore(cls, locator):
"""
Create an instance of the concrete job store implementation that matches the given locator.
:param str locator: The location of the job store to be represent by the instance
:return: an instance of a concrete subclass of AbstractJobStore
:rtyp... | def function[getJobStore, parameter[cls, locator]]:
constant[
Create an instance of the concrete job store implementation that matches the given locator.
:param str locator: The location of the job store to be represent by the instance
:return: an instance of a concrete subclass of Abs... | keyword[def] identifier[getJobStore] ( identifier[cls] , identifier[locator] ):
literal[string]
identifier[name] , identifier[rest] = identifier[cls] . identifier[parseLocator] ( identifier[locator] )
keyword[if] identifier[name] == literal[string] :
keyword[from] identifier... | def getJobStore(cls, locator):
"""
Create an instance of the concrete job store implementation that matches the given locator.
:param str locator: The location of the job store to be represent by the instance
:return: an instance of a concrete subclass of AbstractJobStore
:rtype: t... |
def modify_document(self, doc):
''' Execute the configured ``main.py`` or ``main.ipynb`` to modify the
document.
This method will also search the app directory for any theme or
template files, and automatically configure the document with them
if they are found.
'''
... | def function[modify_document, parameter[self, doc]]:
constant[ Execute the configured ``main.py`` or ``main.ipynb`` to modify the
document.
This method will also search the app directory for any theme or
template files, and automatically configure the document with them
if they ... | keyword[def] identifier[modify_document] ( identifier[self] , identifier[doc] ):
literal[string]
keyword[if] identifier[self] . identifier[_lifecycle_handler] . identifier[failed] :
keyword[return]
keyword[if] identifier[self] . identifier[_theme] ... | def modify_document(self, doc):
""" Execute the configured ``main.py`` or ``main.ipynb`` to modify the
document.
This method will also search the app directory for any theme or
template files, and automatically configure the document with them
if they are found.
"""
if ... |
def as_dict(self, *args, **kwargs):
"""Return ClinVarAllele data as dict object."""
self_as_dict = super(ClinVarAllele, self).as_dict(*args, **kwargs)
self_as_dict['hgvs'] = self.hgvs
self_as_dict['clnalleleid'] = self.clnalleleid
self_as_dict['clnsig'] = self.clnsig
self... | def function[as_dict, parameter[self]]:
constant[Return ClinVarAllele data as dict object.]
variable[self_as_dict] assign[=] call[call[name[super], parameter[name[ClinVarAllele], name[self]]].as_dict, parameter[<ast.Starred object at 0x7da1afe7abc0>]]
call[name[self_as_dict]][constant[hgvs]] ass... | keyword[def] identifier[as_dict] ( identifier[self] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[self_as_dict] = identifier[super] ( identifier[ClinVarAllele] , identifier[self] ). identifier[as_dict] (* identifier[args] ,** identifier[kwargs] )
identifier[self_... | def as_dict(self, *args, **kwargs):
"""Return ClinVarAllele data as dict object."""
self_as_dict = super(ClinVarAllele, self).as_dict(*args, **kwargs)
self_as_dict['hgvs'] = self.hgvs
self_as_dict['clnalleleid'] = self.clnalleleid
self_as_dict['clnsig'] = self.clnsig
self_as_dict['clndn'] = self... |
def update_interface(self, other_interface, ignore_mgmt=True):
"""
Update an existing interface by comparing values between two
interfaces. If a VLAN interface is defined in the other interface
and it doesn't exist on the existing interface, it will be created.
:param ot... | def function[update_interface, parameter[self, other_interface, ignore_mgmt]]:
constant[
Update an existing interface by comparing values between two
interfaces. If a VLAN interface is defined in the other interface
and it doesn't exist on the existing interface, it will be created.
... | keyword[def] identifier[update_interface] ( identifier[self] , identifier[other_interface] , identifier[ignore_mgmt] = keyword[True] ):
literal[string]
identifier[base_updated] = identifier[self] . identifier[_update_interface] ( identifier[other_interface] )
identifier[mgmt] =( literal[s... | def update_interface(self, other_interface, ignore_mgmt=True):
"""
Update an existing interface by comparing values between two
interfaces. If a VLAN interface is defined in the other interface
and it doesn't exist on the existing interface, it will be created.
:param other_... |
def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
file... | def function[relpath_to_modname, parameter[relpath]]:
constant[Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify di... | keyword[def] identifier[relpath_to_modname] ( identifier[relpath] ):
literal[string]
identifier[p] = identifier[pathlib] . identifier[Path] ( identifier[relpath] )
keyword[if] identifier[p] . identifier[name] == literal[string] :
identifier[p] = identifier[p] . identifier[parent]
... | def relpath_to_modname(relpath):
"""Convert relative path to module name
Within a project, a path to the source file is uniquely identified with a
module name. Relative paths of the form 'foo/bar' are *not* converted to
module names 'foo.bar', because (1) they identify directories, not regular
file... |
def getEmpTraitCorrCoef(self):
"""
Returns the empirical trait correlation matrix
"""
cov = self.getEmpTraitCovar()
stds=SP.sqrt(cov.diagonal())[:,SP.newaxis]
RV = cov/stds/stds.T
return RV | def function[getEmpTraitCorrCoef, parameter[self]]:
constant[
Returns the empirical trait correlation matrix
]
variable[cov] assign[=] call[name[self].getEmpTraitCovar, parameter[]]
variable[stds] assign[=] call[call[name[SP].sqrt, parameter[call[name[cov].diagonal, parameter[]]]... | keyword[def] identifier[getEmpTraitCorrCoef] ( identifier[self] ):
literal[string]
identifier[cov] = identifier[self] . identifier[getEmpTraitCovar] ()
identifier[stds] = identifier[SP] . identifier[sqrt] ( identifier[cov] . identifier[diagonal] ())[:, identifier[SP] . identifier[newaxis] ... | def getEmpTraitCorrCoef(self):
"""
Returns the empirical trait correlation matrix
"""
cov = self.getEmpTraitCovar()
stds = SP.sqrt(cov.diagonal())[:, SP.newaxis]
RV = cov / stds / stds.T
return RV |
def add_var_arg(self, arg):
"""
Add a variable (or macro) argument to the condor job. The argument is
added to the submit file and a different value of the argument can be set
for each node in the DAG.
@param arg: name of option to add.
"""
self.__args.append(arg)
self.__job.add_var_arg(... | def function[add_var_arg, parameter[self, arg]]:
constant[
Add a variable (or macro) argument to the condor job. The argument is
added to the submit file and a different value of the argument can be set
for each node in the DAG.
@param arg: name of option to add.
]
call[name[self].__... | keyword[def] identifier[add_var_arg] ( identifier[self] , identifier[arg] ):
literal[string]
identifier[self] . identifier[__args] . identifier[append] ( identifier[arg] )
identifier[self] . identifier[__job] . identifier[add_var_arg] ( identifier[self] . identifier[__arg_index] )
identifier[self... | def add_var_arg(self, arg):
"""
Add a variable (or macro) argument to the condor job. The argument is
added to the submit file and a different value of the argument can be set
for each node in the DAG.
@param arg: name of option to add.
"""
self.__args.append(arg)
self.__job.add_var_arg(... |
def _unique_names():
"""Generates unique sequences of bytes.
"""
characters = ("abcdefghijklmnopqrstuvwxyz"
"0123456789")
characters = [characters[i:i + 1] for i in irange(len(characters))]
rng = random.Random()
while True:
letters = [rng.choice(characters) for i in ira... | def function[_unique_names, parameter[]]:
constant[Generates unique sequences of bytes.
]
variable[characters] assign[=] constant[abcdefghijklmnopqrstuvwxyz0123456789]
variable[characters] assign[=] <ast.ListComp object at 0x7da1b10229b0>
variable[rng] assign[=] call[name[random].Ran... | keyword[def] identifier[_unique_names] ():
literal[string]
identifier[characters] =( literal[string]
literal[string] )
identifier[characters] =[ identifier[characters] [ identifier[i] : identifier[i] + literal[int] ] keyword[for] identifier[i] keyword[in] identifier[irange] ( identifier[len] ... | def _unique_names():
"""Generates unique sequences of bytes.
"""
characters = 'abcdefghijklmnopqrstuvwxyz0123456789'
characters = [characters[i:i + 1] for i in irange(len(characters))]
rng = random.Random()
while True:
letters = [rng.choice(characters) for i in irange(10)]
yield ... |
def gaussian(shape, sd=1.0):
"""Sample a multivariate Gaussian pdf, normalised to have unit sum.
Parameters
----------
shape : tuple
Shape of output array.
sd : float, optional (default 1.0)
Standard deviation of Gaussian pdf.
Returns
-------
gc : ndarray
Sampled Gaus... | def function[gaussian, parameter[shape, sd]]:
constant[Sample a multivariate Gaussian pdf, normalised to have unit sum.
Parameters
----------
shape : tuple
Shape of output array.
sd : float, optional (default 1.0)
Standard deviation of Gaussian pdf.
Returns
-------
gc :... | keyword[def] identifier[gaussian] ( identifier[shape] , identifier[sd] = literal[int] ):
literal[string]
identifier[gfn] = keyword[lambda] identifier[x] , identifier[sd] : identifier[np] . identifier[exp] (-( identifier[x] ** literal[int] )/( literal[int] * identifier[sd] ** literal[int] ))/( identifier[... | def gaussian(shape, sd=1.0):
"""Sample a multivariate Gaussian pdf, normalised to have unit sum.
Parameters
----------
shape : tuple
Shape of output array.
sd : float, optional (default 1.0)
Standard deviation of Gaussian pdf.
Returns
-------
gc : ndarray
Sampled Gaus... |
def get_features_by_ids(self, ids=None, threshold=0.0001, func=np.mean,
get_weights=False):
''' Returns features for which the mean loading across all specified
studies (in ids) is >= threshold. '''
weights = self.data.ix[ids].apply(func, 0)
above_thresh = wei... | def function[get_features_by_ids, parameter[self, ids, threshold, func, get_weights]]:
constant[ Returns features for which the mean loading across all specified
studies (in ids) is >= threshold. ]
variable[weights] assign[=] call[call[name[self].data.ix][name[ids]].apply, parameter[name[func], ... | keyword[def] identifier[get_features_by_ids] ( identifier[self] , identifier[ids] = keyword[None] , identifier[threshold] = literal[int] , identifier[func] = identifier[np] . identifier[mean] ,
identifier[get_weights] = keyword[False] ):
literal[string]
identifier[weights] = identifier[self] . ide... | def get_features_by_ids(self, ids=None, threshold=0.0001, func=np.mean, get_weights=False):
""" Returns features for which the mean loading across all specified
studies (in ids) is >= threshold. """
weights = self.data.ix[ids].apply(func, 0)
above_thresh = weights[weights >= threshold]
return ab... |
def package(*args: str) -> str:
"""
Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting
"""
return c... | def function[package, parameter[]]:
constant[
Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting
]
... | keyword[def] identifier[package] (* identifier[args] : identifier[str] )-> identifier[str] :
literal[string]
keyword[return] identifier[clean] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), literal[string] ,* iden... | def package(*args: str) -> str:
"""
Creates an absolute path to a file or folder within the cauldron package
using the relative path elements specified by the args.
:param args:
Zero or more relative path elements that describe a file or folder
within the reporting
"""
return cl... |
def checksum(self):
"""Grab checksum string
"""
md5sum, md5sum64, = [], []
for line in self.SLACKBUILDS_TXT.splitlines():
if line.startswith(self.line_name):
sbo_name = line[17:].strip()
if line.startswith(self.line_md5_64):
if sbo_... | def function[checksum, parameter[self]]:
constant[Grab checksum string
]
<ast.Tuple object at 0x7da204963070> assign[=] tuple[[<ast.List object at 0x7da204963dc0>, <ast.List object at 0x7da2049632e0>]]
for taget[name[line]] in starred[call[name[self].SLACKBUILDS_TXT.splitlines, parameter... | keyword[def] identifier[checksum] ( identifier[self] ):
literal[string]
identifier[md5sum] , identifier[md5sum64] ,=[],[]
keyword[for] identifier[line] keyword[in] identifier[self] . identifier[SLACKBUILDS_TXT] . identifier[splitlines] ():
keyword[if] identifier[line] . id... | def checksum(self):
"""Grab checksum string
"""
(md5sum, md5sum64) = ([], [])
for line in self.SLACKBUILDS_TXT.splitlines():
if line.startswith(self.line_name):
sbo_name = line[17:].strip() # depends on [control=['if'], data=[]]
if line.startswith(self.line_md5_64):
... |
def select_as_tabledata(
self, table_name, columns=None, where=None, extra=None, type_hints=None
):
"""
Get data in the database and return fetched data as a
:py:class:`tabledata.TableData` instance.
:param str table_name: |arg_select_table_name|
:param list columns:... | def function[select_as_tabledata, parameter[self, table_name, columns, where, extra, type_hints]]:
constant[
Get data in the database and return fetched data as a
:py:class:`tabledata.TableData` instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_s... | keyword[def] identifier[select_as_tabledata] (
identifier[self] , identifier[table_name] , identifier[columns] = keyword[None] , identifier[where] = keyword[None] , identifier[extra] = keyword[None] , identifier[type_hints] = keyword[None]
):
literal[string]
keyword[if] identifier[columns] key... | def select_as_tabledata(self, table_name, columns=None, where=None, extra=None, type_hints=None):
"""
Get data in the database and return fetched data as a
:py:class:`tabledata.TableData` instance.
:param str table_name: |arg_select_table_name|
:param list columns: |arg_select_as_xx... |
def start_monitor(redis_address,
stdout_file=None,
stderr_file=None,
autoscaling_config=None,
redis_password=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is li... | def function[start_monitor, parameter[redis_address, stdout_file, stderr_file, autoscaling_config, redis_password]]:
constant[Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is listening on.
stdout_file: A file handle opened for wri... | keyword[def] identifier[start_monitor] ( identifier[redis_address] ,
identifier[stdout_file] = keyword[None] ,
identifier[stderr_file] = keyword[None] ,
identifier[autoscaling_config] = keyword[None] ,
identifier[redis_password] = keyword[None] ):
literal[string]
identifier[monitor_path] = identifier[o... | def start_monitor(redis_address, stdout_file=None, stderr_file=None, autoscaling_config=None, redis_password=None):
"""Run a process to monitor the other processes.
Args:
redis_address (str): The address that the Redis server is listening on.
stdout_file: A file handle opened for writing to red... |
def append_all_agent_batch_to_update_buffer(self, key_list=None, batch_size=None, training_length=None):
"""
Appends the buffer of all agents to the update buffer.
:param key_list: The fields that must be added. If None: all fields will be appended.
:param batch_size: The number of eleme... | def function[append_all_agent_batch_to_update_buffer, parameter[self, key_list, batch_size, training_length]]:
constant[
Appends the buffer of all agents to the update buffer.
:param key_list: The fields that must be added. If None: all fields will be appended.
:param batch_size: The num... | keyword[def] identifier[append_all_agent_batch_to_update_buffer] ( identifier[self] , identifier[key_list] = keyword[None] , identifier[batch_size] = keyword[None] , identifier[training_length] = keyword[None] ):
literal[string]
keyword[for] identifier[agent_id] keyword[in] identifier[self] . id... | def append_all_agent_batch_to_update_buffer(self, key_list=None, batch_size=None, training_length=None):
"""
Appends the buffer of all agents to the update buffer.
:param key_list: The fields that must be added. If None: all fields will be appended.
:param batch_size: The number of elements ... |
def brpop(self, keys, timeout=0):
"""
RPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to RPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeo... | def function[brpop, parameter[self, keys, timeout]]:
constant[
RPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to RPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the... | keyword[def] identifier[brpop] ( identifier[self] , identifier[keys] , identifier[timeout] = literal[int] ):
literal[string]
keyword[if] identifier[timeout] keyword[is] keyword[None] :
identifier[timeout] = literal[int]
identifier[keys] = identifier[list_or_args] ( identif... | def brpop(self, keys, timeout=0):
"""
RPOP a value off of the first non-empty list
named in the ``keys`` list.
If none of the lists in ``keys`` has a value to RPOP, then block
for ``timeout`` seconds, or until a value gets pushed on to one
of the lists.
If timeout i... |
def create(self):
"""
Calls various methods sequentially in order to fully build the
database.
"""
# Calls each of these methods in order. _populate_from_lines and
# _update_relations must be implemented in subclasses.
self._init_tables()
self._populate_f... | def function[create, parameter[self]]:
constant[
Calls various methods sequentially in order to fully build the
database.
]
call[name[self]._init_tables, parameter[]]
call[name[self]._populate_from_lines, parameter[name[self].iterator]]
call[name[self]._update_rel... | keyword[def] identifier[create] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_init_tables] ()
identifier[self] . identifier[_populate_from_lines] ( identifier[self] . identifier[iterator] )
identifier[self] . identifier[_update_relations] (... | def create(self):
"""
Calls various methods sequentially in order to fully build the
database.
"""
# Calls each of these methods in order. _populate_from_lines and
# _update_relations must be implemented in subclasses.
self._init_tables()
self._populate_from_lines(self.itera... |
def plot_heatmap(data, title='Heatmap', show_legend=True,
show_labels=True, label_fmt='.2f',
vmin=None, vmax=None,
figsize=None, label_color='w',
cmap='RdBu', **kwargs):
"""
Plot a heatmap using matplotlib's pcolor.
Args:
* data (D... | def function[plot_heatmap, parameter[data, title, show_legend, show_labels, label_fmt, vmin, vmax, figsize, label_color, cmap]]:
constant[
Plot a heatmap using matplotlib's pcolor.
Args:
* data (DataFrame): DataFrame to plot. Usually small matrix (ex.
correlation matrix).
* ... | keyword[def] identifier[plot_heatmap] ( identifier[data] , identifier[title] = literal[string] , identifier[show_legend] = keyword[True] ,
identifier[show_labels] = keyword[True] , identifier[label_fmt] = literal[string] ,
identifier[vmin] = keyword[None] , identifier[vmax] = keyword[None] ,
identifier[figsize] = ... | def plot_heatmap(data, title='Heatmap', show_legend=True, show_labels=True, label_fmt='.2f', vmin=None, vmax=None, figsize=None, label_color='w', cmap='RdBu', **kwargs):
"""
Plot a heatmap using matplotlib's pcolor.
Args:
* data (DataFrame): DataFrame to plot. Usually small matrix (ex.
... |
def send(self, *args):
"""Sends a single raw message to the IRC server.
Arguments are automatically joined by spaces. No newlines are allowed.
"""
msg = " ".join(a.nick if isinstance(a, User) else str(a) for a in args)
if "\n" in msg:
raise ValueError("Cannot send() ... | def function[send, parameter[self]]:
constant[Sends a single raw message to the IRC server.
Arguments are automatically joined by spaces. No newlines are allowed.
]
variable[msg] assign[=] call[constant[ ].join, parameter[<ast.GeneratorExp object at 0x7da207f00760>]]
if compare[... | keyword[def] identifier[send] ( identifier[self] ,* identifier[args] ):
literal[string]
identifier[msg] = literal[string] . identifier[join] ( identifier[a] . identifier[nick] keyword[if] identifier[isinstance] ( identifier[a] , identifier[User] ) keyword[else] identifier[str] ( identifier[a] ) ... | def send(self, *args):
"""Sends a single raw message to the IRC server.
Arguments are automatically joined by spaces. No newlines are allowed.
"""
msg = ' '.join((a.nick if isinstance(a, User) else str(a) for a in args))
if '\n' in msg:
raise ValueError('Cannot send() a newline. Arg... |
def build_pub_dates(article, pub_dates):
"convert pub_dates into ArticleDate objects and add them to article"
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type'),
... | def function[build_pub_dates, parameter[article, pub_dates]]:
constant[convert pub_dates into ArticleDate objects and add them to article]
for taget[name[pub_date]] in starred[name[pub_dates]] begin[:]
if call[name[pub_date].get, parameter[constant[date-type]]] begin[:]
... | keyword[def] identifier[build_pub_dates] ( identifier[article] , identifier[pub_dates] ):
literal[string]
keyword[for] identifier[pub_date] keyword[in] identifier[pub_dates] :
keyword[if] identifier[pub_date] . identifier[get] ( literal[string] ):
identifier[date_instance] = ... | def build_pub_dates(article, pub_dates):
"""convert pub_dates into ArticleDate objects and add them to article"""
for pub_date in pub_dates:
# always want a date type, take it from pub-type if must
if pub_date.get('date-type'):
date_instance = ea.ArticleDate(pub_date.get('date-type')... |
def live_neighbours(self, i, j):
""" Count the number of live neighbours around point (i, j). """
s = 0 # The total number of live neighbours.
# Loop over all the neighbours.
for x in [i - 1, i, i + 1]:
for y in [j - 1, j, j + 1]:
if (x == i and y == j):
... | def function[live_neighbours, parameter[self, i, j]]:
constant[ Count the number of live neighbours around point (i, j). ]
variable[s] assign[=] constant[0]
for taget[name[x]] in starred[list[[<ast.BinOp object at 0x7da20c990fd0>, <ast.Name object at 0x7da20c9900d0>, <ast.BinOp object at 0x7da20... | keyword[def] identifier[live_neighbours] ( identifier[self] , identifier[i] , identifier[j] ):
literal[string]
identifier[s] = literal[int]
keyword[for] identifier[x] keyword[in] [ identifier[i] - literal[int] , identifier[i] , identifier[i] + literal[int] ]:
keywo... | def live_neighbours(self, i, j):
""" Count the number of live neighbours around point (i, j). """
s = 0 # The total number of live neighbours.
# Loop over all the neighbours.
for x in [i - 1, i, i + 1]:
for y in [j - 1, j, j + 1]:
if x == i and y == j:
continue # Sk... |
def mark_data_dirty(self):
""" Called from item to indicate its data or metadata has changed."""
self.__cache.set_cached_value_dirty(self.__display_item, self.__cache_property_name)
self.__initialize_cache()
self.__cached_value_dirty = True | def function[mark_data_dirty, parameter[self]]:
constant[ Called from item to indicate its data or metadata has changed.]
call[name[self].__cache.set_cached_value_dirty, parameter[name[self].__display_item, name[self].__cache_property_name]]
call[name[self].__initialize_cache, parameter[]]
... | keyword[def] identifier[mark_data_dirty] ( identifier[self] ):
literal[string]
identifier[self] . identifier[__cache] . identifier[set_cached_value_dirty] ( identifier[self] . identifier[__display_item] , identifier[self] . identifier[__cache_property_name] )
identifier[self] . identifier[... | def mark_data_dirty(self):
""" Called from item to indicate its data or metadata has changed."""
self.__cache.set_cached_value_dirty(self.__display_item, self.__cache_property_name)
self.__initialize_cache()
self.__cached_value_dirty = True |
def generate_datasets_summary(self, catalog, export_path=None):
"""Genera un informe sobre los datasets presentes en un catálogo,
indicando para cada uno:
- Índice en la lista catalog["dataset"]
- Título
- Identificador
- Cantidad de distribuciones
... | def function[generate_datasets_summary, parameter[self, catalog, export_path]]:
constant[Genera un informe sobre los datasets presentes en un catálogo,
indicando para cada uno:
- Índice en la lista catalog["dataset"]
- Título
- Identificador
- Cantidad de ... | keyword[def] identifier[generate_datasets_summary] ( identifier[self] , identifier[catalog] , identifier[export_path] = keyword[None] ):
literal[string]
identifier[catalog] = identifier[readers] . identifier[read_catalog] ( identifier[catalog] )
keyword[if] literal[stri... | def generate_datasets_summary(self, catalog, export_path=None):
"""Genera un informe sobre los datasets presentes en un catálogo,
indicando para cada uno:
- Índice en la lista catalog["dataset"]
- Título
- Identificador
- Cantidad de distribuciones
... |
def isgood(name):
""" Whether name should be installed """
if not isbad(name):
if name.endswith('.py') or name.endswith('.json') or name.endswith('.tar'):
return True
return False | def function[isgood, parameter[name]]:
constant[ Whether name should be installed ]
if <ast.UnaryOp object at 0x7da18dc9af80> begin[:]
if <ast.BoolOp object at 0x7da18dc99330> begin[:]
return[constant[True]]
return[constant[False]] | keyword[def] identifier[isgood] ( identifier[name] ):
literal[string]
keyword[if] keyword[not] identifier[isbad] ( identifier[name] ):
keyword[if] identifier[name] . identifier[endswith] ( literal[string] ) keyword[or] identifier[name] . identifier[endswith] ( literal[string] ) keyword[or] id... | def isgood(name):
""" Whether name should be installed """
if not isbad(name):
if name.endswith('.py') or name.endswith('.json') or name.endswith('.tar'):
return True # depends on [control=['if'], data=[]] # depends on [control=['if'], data=[]]
return False |
def Levenshtein_Distance(w1, w2):
"""
Computes Levenshtein Distance between two words
Args:
:param w1: str
:param w2: str
:return: int
Examples:
>>> Levenshtein.Levenshtein_Distance('noctis', 'noctem')
2
>>> Leve... | def function[Levenshtein_Distance, parameter[w1, w2]]:
constant[
Computes Levenshtein Distance between two words
Args:
:param w1: str
:param w2: str
:return: int
Examples:
>>> Levenshtein.Levenshtein_Distance('noctis', 'noctem')
... | keyword[def] identifier[Levenshtein_Distance] ( identifier[w1] , identifier[w2] ):
literal[string]
identifier[m] , identifier[n] = identifier[len] ( identifier[w1] ), identifier[len] ( identifier[w2] )
identifier[v1] =[ identifier[i] keyword[for] identifier[i] keyword[in] identifier[ra... | def Levenshtein_Distance(w1, w2):
"""
Computes Levenshtein Distance between two words
Args:
:param w1: str
:param w2: str
:return: int
Examples:
>>> Levenshtein.Levenshtein_Distance('noctis', 'noctem')
2
>>> Levensht... |
def _normalize_server_url(self, server):
"""
Check if the server URL starts with a HTTP or HTTPS scheme, fall back to http if not present
"""
server = server if server.startswith(("http://", "https://")) else "http://{}".format(server)
return server | def function[_normalize_server_url, parameter[self, server]]:
constant[
Check if the server URL starts with a HTTP or HTTPS scheme, fall back to http if not present
]
variable[server] assign[=] <ast.IfExp object at 0x7da20c7ca5c0>
return[name[server]] | keyword[def] identifier[_normalize_server_url] ( identifier[self] , identifier[server] ):
literal[string]
identifier[server] = identifier[server] keyword[if] identifier[server] . identifier[startswith] (( literal[string] , literal[string] )) keyword[else] literal[string] . identifier[format] ( i... | def _normalize_server_url(self, server):
"""
Check if the server URL starts with a HTTP or HTTPS scheme, fall back to http if not present
"""
server = server if server.startswith(('http://', 'https://')) else 'http://{}'.format(server)
return server |
def get_fields_with_environment_context(self, db_name, table_name, environment_context):
"""
Parameters:
- db_name
- table_name
- environment_context
"""
self.send_get_fields_with_environment_context(db_name, table_name, environment_context)
return self.recv_get_fields_with_environmen... | def function[get_fields_with_environment_context, parameter[self, db_name, table_name, environment_context]]:
constant[
Parameters:
- db_name
- table_name
- environment_context
]
call[name[self].send_get_fields_with_environment_context, parameter[name[db_name], name[table_name], n... | keyword[def] identifier[get_fields_with_environment_context] ( identifier[self] , identifier[db_name] , identifier[table_name] , identifier[environment_context] ):
literal[string]
identifier[self] . identifier[send_get_fields_with_environment_context] ( identifier[db_name] , identifier[table_name] , identi... | def get_fields_with_environment_context(self, db_name, table_name, environment_context):
"""
Parameters:
- db_name
- table_name
- environment_context
"""
self.send_get_fields_with_environment_context(db_name, table_name, environment_context)
return self.recv_get_fields_with_environmen... |
def satisfaction_rating_show(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#show-satisfaction-rating"
api_path = "/api/v2/satisfaction_ratings/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) | def function[satisfaction_rating_show, parameter[self, id]]:
constant[https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#show-satisfaction-rating]
variable[api_path] assign[=] constant[/api/v2/satisfaction_ratings/{id}.json]
variable[api_path] assign[=] call[name[api_path].for... | keyword[def] identifier[satisfaction_rating_show] ( identifier[self] , identifier[id] ,** identifier[kwargs] ):
literal[string]
identifier[api_path] = literal[string]
identifier[api_path] = identifier[api_path] . identifier[format] ( identifier[id] = identifier[id] )
keyword[retu... | def satisfaction_rating_show(self, id, **kwargs):
"""https://developer.zendesk.com/rest_api/docs/core/satisfaction_ratings#show-satisfaction-rating"""
api_path = '/api/v2/satisfaction_ratings/{id}.json'
api_path = api_path.format(id=id)
return self.call(api_path, **kwargs) |
def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:]
cli = CommandLineTool()
return cli.run(argv) | def function[main, parameter[argv]]:
constant[Main command line interface.]
if compare[name[argv] is constant[None]] begin[:]
variable[argv] assign[=] call[name[sys].argv][<ast.Slice object at 0x7da18c4cf280>]
variable[cli] assign[=] call[name[CommandLineTool], parameter[]]
r... | keyword[def] identifier[main] ( identifier[argv] = keyword[None] ):
literal[string]
keyword[if] identifier[argv] keyword[is] keyword[None] :
identifier[argv] = identifier[sys] . identifier[argv] [ literal[int] :]
identifier[cli] = identifier[CommandLineTool] ()
keyword[return] iden... | def main(argv=None):
"""Main command line interface."""
if argv is None:
argv = sys.argv[1:] # depends on [control=['if'], data=['argv']]
cli = CommandLineTool()
return cli.run(argv) |
def _get_set(self, key, operation, create=False):
"""
Get (and maybe create) a set by name.
"""
return self._get_by_type(key, operation, create, b'set', set()) | def function[_get_set, parameter[self, key, operation, create]]:
constant[
Get (and maybe create) a set by name.
]
return[call[name[self]._get_by_type, parameter[name[key], name[operation], name[create], constant[b'set'], call[name[set], parameter[]]]]] | keyword[def] identifier[_get_set] ( identifier[self] , identifier[key] , identifier[operation] , identifier[create] = keyword[False] ):
literal[string]
keyword[return] identifier[self] . identifier[_get_by_type] ( identifier[key] , identifier[operation] , identifier[create] , literal[string] , ide... | def _get_set(self, key, operation, create=False):
"""
Get (and maybe create) a set by name.
"""
return self._get_by_type(key, operation, create, b'set', set()) |
def _mcmc_fit(self, scale=1.0, nsims=10000, printer=True, method="M-H",
cov_matrix=None, map_start=True, quiet_progress=False, **kwargs):
""" Performs random walk Metropolis-Hastings
Parameters
----------
scale : float
Default starting scale
nsims : int
... | def function[_mcmc_fit, parameter[self, scale, nsims, printer, method, cov_matrix, map_start, quiet_progress]]:
constant[ Performs random walk Metropolis-Hastings
Parameters
----------
scale : float
Default starting scale
nsims : int
Number of simulation... | keyword[def] identifier[_mcmc_fit] ( identifier[self] , identifier[scale] = literal[int] , identifier[nsims] = literal[int] , identifier[printer] = keyword[True] , identifier[method] = literal[string] ,
identifier[cov_matrix] = keyword[None] , identifier[map_start] = keyword[True] , identifier[quiet_progress] = keyw... | def _mcmc_fit(self, scale=1.0, nsims=10000, printer=True, method='M-H', cov_matrix=None, map_start=True, quiet_progress=False, **kwargs):
""" Performs random walk Metropolis-Hastings
Parameters
----------
scale : float
Default starting scale
nsims : int
Numb... |
def bus_remove_match_action(self, rule, func, user_data, error = None) :
"removes a message filter previously installed with bus_add_match_action."
rulekey = format_rule(rule)
rule = unformat_rule(rule)
self._match_actions[rulekey].actions.remove(_MatchActionEntry._Action(func, user_data... | def function[bus_remove_match_action, parameter[self, rule, func, user_data, error]]:
constant[removes a message filter previously installed with bus_add_match_action.]
variable[rulekey] assign[=] call[name[format_rule], parameter[name[rule]]]
variable[rule] assign[=] call[name[unformat_rule], p... | keyword[def] identifier[bus_remove_match_action] ( identifier[self] , identifier[rule] , identifier[func] , identifier[user_data] , identifier[error] = keyword[None] ):
literal[string]
identifier[rulekey] = identifier[format_rule] ( identifier[rule] )
identifier[rule] = identifier[unformat... | def bus_remove_match_action(self, rule, func, user_data, error=None):
"""removes a message filter previously installed with bus_add_match_action."""
rulekey = format_rule(rule)
rule = unformat_rule(rule)
self._match_actions[rulekey].actions.remove(_MatchActionEntry._Action(func, user_data))
if len(s... |
def memory_usage(method):
"""Log memory usage before and after a method."""
def wrapper(*args, **kwargs):
logging.info('Memory before method %s is %s.',
method.__name__, runtime.memory_usage().current())
result = method(*args, **kwargs)
logging.info('Memory after method %s is %s',
... | def function[memory_usage, parameter[method]]:
constant[Log memory usage before and after a method.]
def function[wrapper, parameter[]]:
call[name[logging].info, parameter[constant[Memory before method %s is %s.], name[method].__name__, call[call[name[runtime].memory_usage, parameter[]].... | keyword[def] identifier[memory_usage] ( identifier[method] ):
literal[string]
keyword[def] identifier[wrapper] (* identifier[args] ,** identifier[kwargs] ):
identifier[logging] . identifier[info] ( literal[string] ,
identifier[method] . identifier[__name__] , identifier[runtime] . identifier[memory_... | def memory_usage(method):
"""Log memory usage before and after a method."""
def wrapper(*args, **kwargs):
logging.info('Memory before method %s is %s.', method.__name__, runtime.memory_usage().current())
result = method(*args, **kwargs)
logging.info('Memory after method %s is %s', metho... |
def managed(name, passphrase, entries, force_remove=False):
'''
Create or manage a java keystore.
name
The path to the keystore file
passphrase
The password to the keystore
entries
A list containing an alias, certificate, and optional private_key.
The certificate a... | def function[managed, parameter[name, passphrase, entries, force_remove]]:
constant[
Create or manage a java keystore.
name
The path to the keystore file
passphrase
The password to the keystore
entries
A list containing an alias, certificate, and optional private_key.
... | keyword[def] identifier[managed] ( identifier[name] , identifier[passphrase] , identifier[entries] , identifier[force_remove] = keyword[False] ):
literal[string]
identifier[ret] ={ literal[string] :{},
literal[string] : literal[string] ,
literal[string] : identifier[name] ,
literal[string] :... | def managed(name, passphrase, entries, force_remove=False):
"""
Create or manage a java keystore.
name
The path to the keystore file
passphrase
The password to the keystore
entries
A list containing an alias, certificate, and optional private_key.
The certificate a... |
def same_guid(post, parameter=DEFAULT_SIMILARITY_TIMESPAN):
'''Skip posts with exactly same GUID.
Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).'''
from feedjack.models import Post
if isinstance(parameter, types.StringTypes): parameter = int(parameter.strip())
similar = Post.objects.filtere... | def function[same_guid, parameter[post, parameter]]:
constant[Skip posts with exactly same GUID.
Parameter: comparison timespan, seconds (int, 0 = inf, default: {0}).]
from relative_module[feedjack.models] import module[Post]
if call[name[isinstance], parameter[name[parameter], name[types].StringT... | keyword[def] identifier[same_guid] ( identifier[post] , identifier[parameter] = identifier[DEFAULT_SIMILARITY_TIMESPAN] ):
literal[string]
keyword[from] identifier[feedjack] . identifier[models] keyword[import] identifier[Post]
keyword[if] identifier[isinstance] ( identifier[parameter] , identifier[types]... | def same_guid(post, parameter=DEFAULT_SIMILARITY_TIMESPAN):
"""Skip posts with exactly same GUID.
Parameter: comparison timespan, seconds (int, 0 = inf, default: {0})."""
from feedjack.models import Post
if isinstance(parameter, types.StringTypes):
parameter = int(parameter.strip()) # depends on ... |
def _update_viewport_margins(self):
"""Update viewport margins."""
top = 0
left = 0
right = 0
bottom = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if panel.isVisible():
width = panel.sizeHint().width()
left += widt... | def function[_update_viewport_margins, parameter[self]]:
constant[Update viewport margins.]
variable[top] assign[=] constant[0]
variable[left] assign[=] constant[0]
variable[right] assign[=] constant[0]
variable[bottom] assign[=] constant[0]
for taget[name[panel]] in star... | keyword[def] identifier[_update_viewport_margins] ( identifier[self] ):
literal[string]
identifier[top] = literal[int]
identifier[left] = literal[int]
identifier[right] = literal[int]
identifier[bottom] = literal[int]
keyword[for] identifier[panel] keyword[... | def _update_viewport_margins(self):
"""Update viewport margins."""
top = 0
left = 0
right = 0
bottom = 0
for panel in self.panels_for_zone(Panel.Position.LEFT):
if panel.isVisible():
width = panel.sizeHint().width()
left += width # depends on [control=['if'], dat... |
def load_operator(self, operator):
"""|coro|
Loads the players stats for the operator
Parameters
----------
operator : str
the name of the operator
Returns
-------
:class:`Operator`
the operator object found"""
location =... | def function[load_operator, parameter[self, operator]]:
constant[|coro|
Loads the players stats for the operator
Parameters
----------
operator : str
the name of the operator
Returns
-------
:class:`Operator`
the operator object ... | keyword[def] identifier[load_operator] ( identifier[self] , identifier[operator] ):
literal[string]
identifier[location] = keyword[yield] keyword[from] identifier[self] . identifier[auth] . identifier[get_operator_index] ( identifier[operator] )
keyword[if] identifier[location] keyword... | def load_operator(self, operator):
"""|coro|
Loads the players stats for the operator
Parameters
----------
operator : str
the name of the operator
Returns
-------
:class:`Operator`
the operator object found"""
location = (yield ... |
def host_info_getter(func, name=None):
"""
The decorated function is added to the process of collecting the host_info.
This just adds the decorated function to the global
``sacred.host_info.host_info_gatherers`` dictionary.
The functions from that dictionary are used when collecting the host info
... | def function[host_info_getter, parameter[func, name]]:
constant[
The decorated function is added to the process of collecting the host_info.
This just adds the decorated function to the global
``sacred.host_info.host_info_gatherers`` dictionary.
The functions from that dictionary are used when ... | keyword[def] identifier[host_info_getter] ( identifier[func] , identifier[name] = keyword[None] ):
literal[string]
identifier[name] = identifier[name] keyword[or] identifier[func] . identifier[__name__]
identifier[host_info_gatherers] [ identifier[name] ]= identifier[func]
keyword[return] id... | def host_info_getter(func, name=None):
"""
The decorated function is added to the process of collecting the host_info.
This just adds the decorated function to the global
``sacred.host_info.host_info_gatherers`` dictionary.
The functions from that dictionary are used when collecting the host info
... |
def connect(self, timeout=None):
""" Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
Sometimes there is more than one address specified for a server or client.
After trying to connect to all available addresses for this client and assuming
... | def function[connect, parameter[self, timeout]]:
constant[ Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
Sometimes there is more than one address specified for a server or client.
After trying to connect to all available addresses for this clien... | keyword[def] identifier[connect] ( identifier[self] , identifier[timeout] = keyword[None] ):
literal[string]
identifier[cls] = identifier[PlexServer] keyword[if] literal[string] keyword[in] identifier[self] . identifier[provides] keyword[else] identifier[PlexClient]
identifier[lista... | def connect(self, timeout=None):
""" Returns a new :class:`~plexapi.client.PlexClient` or :class:`~plexapi.server.PlexServer`
Sometimes there is more than one address specified for a server or client.
After trying to connect to all available addresses for this client and assuming
... |
def sort_columns(self, column, key=None, reverse=False):
"""
Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for the sort
... | def function[sort_columns, parameter[self, column, key, reverse]]:
constant[
Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for... | keyword[def] identifier[sort_columns] ( identifier[self] , identifier[column] , identifier[key] = keyword[None] , identifier[reverse] = keyword[False] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[column] ,( identifier[list] , identifier[blist] )):
keyword[raise] ... | def sort_columns(self, column, key=None, reverse=False):
"""
Sort the DataFrame by one of the columns. The sort modifies the DataFrame inplace. The key and reverse
parameters have the same meaning as for the built-in sort() function.
:param column: column name to use for the sort
:p... |
def filter_indices(self, options, verbosity, *args, **kwargs):
"""Filter indices and execute an action for each index."""
index_name_map = {
index.__class__.__name__: index
for index in index_builder.indexes
}
# Process includes.
if options['index']:
... | def function[filter_indices, parameter[self, options, verbosity]]:
constant[Filter indices and execute an action for each index.]
variable[index_name_map] assign[=] <ast.DictComp object at 0x7da1b1a29330>
if call[name[options]][constant[index]] begin[:]
variable[indices] assign[=... | keyword[def] identifier[filter_indices] ( identifier[self] , identifier[options] , identifier[verbosity] ,* identifier[args] ,** identifier[kwargs] ):
literal[string]
identifier[index_name_map] ={
identifier[index] . identifier[__class__] . identifier[__name__] : identifier[index]
... | def filter_indices(self, options, verbosity, *args, **kwargs):
"""Filter indices and execute an action for each index."""
index_name_map = {index.__class__.__name__: index for index in index_builder.indexes}
# Process includes.
if options['index']:
indices = set(options['index']) # depends on [... |
def recv(self, bfd_pkt):
"""
BFD packet receiver.
"""
LOG.debug("[BFD][%s][RECV] BFD Control received: %s",
hex(self._local_discr), six.binary_type(bfd_pkt))
self._remote_discr = bfd_pkt.my_discr
self._remote_state = bfd_pkt.state
self._remote_de... | def function[recv, parameter[self, bfd_pkt]]:
constant[
BFD packet receiver.
]
call[name[LOG].debug, parameter[constant[[BFD][%s][RECV] BFD Control received: %s], call[name[hex], parameter[name[self]._local_discr]], call[name[six].binary_type, parameter[name[bfd_pkt]]]]]
name[sel... | keyword[def] identifier[recv] ( identifier[self] , identifier[bfd_pkt] ):
literal[string]
identifier[LOG] . identifier[debug] ( literal[string] ,
identifier[hex] ( identifier[self] . identifier[_local_discr] ), identifier[six] . identifier[binary_type] ( identifier[bfd_pkt] ))
ide... | def recv(self, bfd_pkt):
"""
BFD packet receiver.
"""
LOG.debug('[BFD][%s][RECV] BFD Control received: %s', hex(self._local_discr), six.binary_type(bfd_pkt))
self._remote_discr = bfd_pkt.my_discr
self._remote_state = bfd_pkt.state
self._remote_demand_mode = bfd_pkt.flags & bfd.BFD_FL... |
def postmap(self, path, valuemap=None, query=None):
"""
Performs a POST request as per post() but the response content type
is required to be "application/json" and is processed as with getmap().
"""
code, data, ctype = self.post(path, valuemap, query)
if ctype != 'applicatio... | def function[postmap, parameter[self, path, valuemap, query]]:
constant[
Performs a POST request as per post() but the response content type
is required to be "application/json" and is processed as with getmap().
]
<ast.Tuple object at 0x7da18bc72380> assign[=] call[name[self].post, ... | keyword[def] identifier[postmap] ( identifier[self] , identifier[path] , identifier[valuemap] = keyword[None] , identifier[query] = keyword[None] ):
literal[string]
identifier[code] , identifier[data] , identifier[ctype] = identifier[self] . identifier[post] ( identifier[path] , identifier[valuemap... | def postmap(self, path, valuemap=None, query=None):
"""
Performs a POST request as per post() but the response content type
is required to be "application/json" and is processed as with getmap().
"""
(code, data, ctype) = self.post(path, valuemap, query)
if ctype != 'application/json':
... |
def granted(self, lock):
'''Return True if a previously requested lock has been granted'''
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if ts and self.grants.get(unit, {}).get(lock) == ts:
return True
return False | def function[granted, parameter[self, lock]]:
constant[Return True if a previously requested lock has been granted]
variable[unit] assign[=] call[name[hookenv].local_unit, parameter[]]
variable[ts] assign[=] call[call[name[self].requests][name[unit]].get, parameter[name[lock]]]
if <ast.B... | keyword[def] identifier[granted] ( identifier[self] , identifier[lock] ):
literal[string]
identifier[unit] = identifier[hookenv] . identifier[local_unit] ()
identifier[ts] = identifier[self] . identifier[requests] [ identifier[unit] ]. identifier[get] ( identifier[lock] )
keyword[... | def granted(self, lock):
"""Return True if a previously requested lock has been granted"""
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if ts and self.grants.get(unit, {}).get(lock) == ts:
return True # depends on [control=['if'], data=[]]
return False |
def write_layout(_path):
"""
Write a valid gentoo layout file to :path:.
Args:
path - The output path of the layout.conf
"""
path.mkdir_uchroot("/etc/portage/metadata")
path.mkfile_uchroot("/etc/portage/metadata/layout.conf")
with open(_path, 'w') as layoutconf:
lines = '''... | def function[write_layout, parameter[_path]]:
constant[
Write a valid gentoo layout file to :path:.
Args:
path - The output path of the layout.conf
]
call[name[path].mkdir_uchroot, parameter[constant[/etc/portage/metadata]]]
call[name[path].mkfile_uchroot, parameter[constant... | keyword[def] identifier[write_layout] ( identifier[_path] ):
literal[string]
identifier[path] . identifier[mkdir_uchroot] ( literal[string] )
identifier[path] . identifier[mkfile_uchroot] ( literal[string] )
keyword[with] identifier[open] ( identifier[_path] , literal[string] ) keyword[as] ide... | def write_layout(_path):
"""
Write a valid gentoo layout file to :path:.
Args:
path - The output path of the layout.conf
"""
path.mkdir_uchroot('/etc/portage/metadata')
path.mkfile_uchroot('/etc/portage/metadata/layout.conf')
with open(_path, 'w') as layoutconf:
lines = 'mas... |
def end_y(self):
"""
Return the Y-position of the end point of this connector, in English
Metric Units (as a |Length| object).
"""
cxnSp = self._element
y, cy, flipV = cxnSp.y, cxnSp.cy, cxnSp.flipV
end_y = y if flipV else y+cy
return Emu(end_y) | def function[end_y, parameter[self]]:
constant[
Return the Y-position of the end point of this connector, in English
Metric Units (as a |Length| object).
]
variable[cxnSp] assign[=] name[self]._element
<ast.Tuple object at 0x7da204963bb0> assign[=] tuple[[<ast.Attribute o... | keyword[def] identifier[end_y] ( identifier[self] ):
literal[string]
identifier[cxnSp] = identifier[self] . identifier[_element]
identifier[y] , identifier[cy] , identifier[flipV] = identifier[cxnSp] . identifier[y] , identifier[cxnSp] . identifier[cy] , identifier[cxnSp] . identifier[fli... | def end_y(self):
"""
Return the Y-position of the end point of this connector, in English
Metric Units (as a |Length| object).
"""
cxnSp = self._element
(y, cy, flipV) = (cxnSp.y, cxnSp.cy, cxnSp.flipV)
end_y = y if flipV else y + cy
return Emu(end_y) |
def read_element_using_argtuple(self, argtuple):
"""
takes a tuple of keys
returns node found in cfg_dict
found by traversing cfg_dict by successive
application of keys from element_path
"""
# doesn't support DELIMITED, only dict-based formats
if self.format == FMT_DELIMITED:
return None
node = ... | def function[read_element_using_argtuple, parameter[self, argtuple]]:
constant[
takes a tuple of keys
returns node found in cfg_dict
found by traversing cfg_dict by successive
application of keys from element_path
]
if compare[name[self].format equal[==] name[FMT_DELIMITED]] begin[:]
... | keyword[def] identifier[read_element_using_argtuple] ( identifier[self] , identifier[argtuple] ):
literal[string]
keyword[if] identifier[self] . identifier[format] == identifier[FMT_DELIMITED] :
keyword[return] keyword[None]
identifier[node] = identifier[self] . identifier[cfg_dict]
keyword[... | def read_element_using_argtuple(self, argtuple):
"""
takes a tuple of keys
returns node found in cfg_dict
found by traversing cfg_dict by successive
application of keys from element_path
""" # doesn't support DELIMITED, only dict-based formats
if self.format == FMT_DELIMITED:
return None # ... |
def with_config(loop=None):
"""
:return: an instance of the txaio API with the given
configuration. This won't affect anything using the 'gloabl'
config nor other instances created using this function.
If you need to customize txaio configuration separately (e.g. to
use multiple event-l... | def function[with_config, parameter[loop]]:
constant[
:return: an instance of the txaio API with the given
configuration. This won't affect anything using the 'gloabl'
config nor other instances created using this function.
If you need to customize txaio configuration separately (e.g. t... | keyword[def] identifier[with_config] ( identifier[loop] = keyword[None] ):
literal[string]
identifier[cfg] = identifier[_Config] ()
keyword[if] identifier[loop] keyword[is] keyword[not] keyword[None] :
identifier[cfg] . identifier[loop] = identifier[loop]
keyword[return] identifier... | def with_config(loop=None):
"""
:return: an instance of the txaio API with the given
configuration. This won't affect anything using the 'gloabl'
config nor other instances created using this function.
If you need to customize txaio configuration separately (e.g. to
use multiple event-l... |
def rhyme_scheme(self):
"""
Calculates the rhyme scheme of a given stanza. It doesn't yet support
phonetical rhyming (homophones) and thus is still error-prone
Example:
>>> stanza = ['Ein rîchiu küneginne, frou Uote ir muoter hiez.', 'ir vater der hiez Dancrât, der in diu er... | def function[rhyme_scheme, parameter[self]]:
constant[
Calculates the rhyme scheme of a given stanza. It doesn't yet support
phonetical rhyming (homophones) and thus is still error-prone
Example:
>>> stanza = ['Ein rîchiu küneginne, frou Uote ir muoter hiez.', 'ir vater der ... | keyword[def] identifier[rhyme_scheme] ( identifier[self] ):
literal[string]
identifier[rhymes] = identifier[dict] ()
identifier[i] = literal[int]
identifier[strs] = literal[string]
keyword[for] identifier[line] keyword[in] identifier[self] . identifier[syllabified] ... | def rhyme_scheme(self):
"""
Calculates the rhyme scheme of a given stanza. It doesn't yet support
phonetical rhyming (homophones) and thus is still error-prone
Example:
>>> stanza = ['Ein rîchiu küneginne, frou Uote ir muoter hiez.', 'ir vater der hiez Dancrât, der in diu erbe l... |
def sphrec(r, colat, lon):
"""
Convert from spherical coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html
:param r: Distance of a point from the origin.
:type r: float
:param colat: Angle of the point from the positive Z-axis.
:type... | def function[sphrec, parameter[r, colat, lon]]:
constant[
Convert from spherical coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html
:param r: Distance of a point from the origin.
:type r: float
:param colat: Angle of the point from... | keyword[def] identifier[sphrec] ( identifier[r] , identifier[colat] , identifier[lon] ):
literal[string]
identifier[r] = identifier[ctypes] . identifier[c_double] ( identifier[r] )
identifier[colat] = identifier[ctypes] . identifier[c_double] ( identifier[colat] )
identifier[lon] = identifier[cty... | def sphrec(r, colat, lon):
"""
Convert from spherical coordinates to rectangular coordinates.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/sphrec_c.html
:param r: Distance of a point from the origin.
:type r: float
:param colat: Angle of the point from the positive Z-axis.
:type... |
def change(ui, repo, *pats, **opts):
"""create, edit or delete a change list
Create, edit or delete a change list.
A change list is a group of files to be reviewed and submitted together,
plus a textual description of the change.
Change lists are referred to by simple alphanumeric names.
Changes must be reviewe... | def function[change, parameter[ui, repo]]:
constant[create, edit or delete a change list
Create, edit or delete a change list.
A change list is a group of files to be reviewed and submitted together,
plus a textual description of the change.
Change lists are referred to by simple alphanumeric names.
Chan... | keyword[def] identifier[change] ( identifier[ui] , identifier[repo] ,* identifier[pats] ,** identifier[opts] ):
literal[string]
keyword[if] identifier[codereview_disabled] :
keyword[raise] identifier[hg_util] . identifier[Abort] ( identifier[codereview_disabled] )
identifier[dirty] ={}
keyword[if] id... | def change(ui, repo, *pats, **opts):
"""create, edit or delete a change list
Create, edit or delete a change list.
A change list is a group of files to be reviewed and submitted together,
plus a textual description of the change.
Change lists are referred to by simple alphanumeric names.
Changes must be revi... |
def notify_listeners(self, data: Optional[_ListenableDataType]=_NO_DATA_MARKER):
"""
Notify event listeners, passing them the given data (if any).
:param data: the data to pass to the event listeners
"""
for listener in self._listeners:
if data is not Listenable._NO_D... | def function[notify_listeners, parameter[self, data]]:
constant[
Notify event listeners, passing them the given data (if any).
:param data: the data to pass to the event listeners
]
for taget[name[listener]] in starred[name[self]._listeners] begin[:]
if compare[na... | keyword[def] identifier[notify_listeners] ( identifier[self] , identifier[data] : identifier[Optional] [ identifier[_ListenableDataType] ]= identifier[_NO_DATA_MARKER] ):
literal[string]
keyword[for] identifier[listener] keyword[in] identifier[self] . identifier[_listeners] :
keywor... | def notify_listeners(self, data: Optional[_ListenableDataType]=_NO_DATA_MARKER):
"""
Notify event listeners, passing them the given data (if any).
:param data: the data to pass to the event listeners
"""
for listener in self._listeners:
if data is not Listenable._NO_DATA_MARKER:
... |
def serialize(cls, **properties):
"""
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
"""
obj = cls()
for k, v in properties.iteritems():
log.debug("%s.%s = %r", cls.__name__, k, v)
... | def function[serialize, parameter[cls]]:
constant[
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
]
variable[obj] assign[=] call[name[cls], parameter[]]
for taget[tuple[[<ast.Na... | keyword[def] identifier[serialize] ( identifier[cls] ,** identifier[properties] ):
literal[string]
identifier[obj] = identifier[cls] ()
keyword[for] identifier[k] , identifier[v] keyword[in] identifier[properties] . identifier[iteritems] ():
identifier[log] . identifier[debug] ( literal[st... | def serialize(cls, **properties):
"""
With a Protobuf class and properties as keyword arguments, sets all the
properties on a new instance of the class and serializes the resulting
value.
"""
obj = cls()
for (k, v) in properties.iteritems():
log.debug('%s.%s = %r', cls.__name__, k, v... |
def validate(self):
"""
Validates the given Amazon S3 file with :attr:`validators`. If errors
occur they are appended to :attr:`errors`. If the file is valid and a
`AWS_UNVALIDATED_PREFIX` config is present, its value will be removed
from the file key.
:return: a boolean... | def function[validate, parameter[self]]:
constant[
Validates the given Amazon S3 file with :attr:`validators`. If errors
occur they are appended to :attr:`errors`. If the file is valid and a
`AWS_UNVALIDATED_PREFIX` config is present, its value will be removed
from the file key.
... | keyword[def] identifier[validate] ( identifier[self] ):
literal[string]
keyword[for] identifier[validator] keyword[in] identifier[self] . identifier[validators] :
keyword[try] :
identifier[validator] ( identifier[self] . identifier[obj] )
keyword[except... | def validate(self):
"""
Validates the given Amazon S3 file with :attr:`validators`. If errors
occur they are appended to :attr:`errors`. If the file is valid and a
`AWS_UNVALIDATED_PREFIX` config is present, its value will be removed
from the file key.
:return: a boolean ind... |
def _insert_timestamp(self, slug, max_length=255):
"""Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
"""
timestamp = str(int(time.time()))
ts_len = len(timestamp) + 1
while len(slug) + ts_len > max_length:
... | def function[_insert_timestamp, parameter[self, slug, max_length]]:
constant[Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
]
variable[timestamp] assign[=] call[name[str], parameter[call[name[int], parameter[call[name[time].t... | keyword[def] identifier[_insert_timestamp] ( identifier[self] , identifier[slug] , identifier[max_length] = literal[int] ):
literal[string]
identifier[timestamp] = identifier[str] ( identifier[int] ( identifier[time] . identifier[time] ()))
identifier[ts_len] = identifier[len] ( identifier... | def _insert_timestamp(self, slug, max_length=255):
"""Appends a timestamp integer to the given slug, yet ensuring the
result is less than the specified max_length.
"""
timestamp = str(int(time.time()))
ts_len = len(timestamp) + 1
while len(slug) + ts_len > max_length:
slug = '-'.... |
def health_check(self):
"""
Get health status
https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html
:return:
"""
# check as Troubleshooting & Support Tools Plugin
response = self.get('rest/troubleshooting/1.0/ch... | def function[health_check, parameter[self]]:
constant[
Get health status
https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html
:return:
]
variable[response] assign[=] call[name[self].get, parameter[constant[rest/trouble... | keyword[def] identifier[health_check] ( identifier[self] ):
literal[string]
identifier[response] = identifier[self] . identifier[get] ( literal[string] )
keyword[if] keyword[not] identifier[response] :
identifier[response] = identifier[self] . identifier[ge... | def health_check(self):
"""
Get health status
https://confluence.atlassian.com/jirakb/how-to-retrieve-health-check-results-using-rest-api-867195158.html
:return:
"""
# check as Troubleshooting & Support Tools Plugin
response = self.get('rest/troubleshooting/1.0/check/')
i... |
def generateImplicitParameters(cls, obj):
"""
Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
"""
if not hasattr(obj, 'version'):
obj.add(ContentLine('VERSION'... | def function[generateImplicitParameters, parameter[cls, obj]]:
constant[
Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
]
if <ast.UnaryOp object at 0x7da18fe93b50> begin[... | keyword[def] identifier[generateImplicitParameters] ( identifier[cls] , identifier[obj] ):
literal[string]
keyword[if] keyword[not] identifier[hasattr] ( identifier[obj] , literal[string] ):
identifier[obj] . identifier[add] ( identifier[ContentLine] ( literal[string] ,[], identifier... | def generateImplicitParameters(cls, obj):
"""
Create PRODID, VERSION, and VTIMEZONEs if needed.
VTIMEZONEs will need to exist whenever TZID parameters exist or when
datetimes with tzinfo exist.
"""
if not hasattr(obj, 'version'):
obj.add(ContentLine('VERSION', [], cls.ve... |
def passwordLogin(self, username):
"""
Generate a new challenge for the given username.
"""
self.challenge = secureRandom(16)
self.username = username
return {'challenge': self.challenge} | def function[passwordLogin, parameter[self, username]]:
constant[
Generate a new challenge for the given username.
]
name[self].challenge assign[=] call[name[secureRandom], parameter[constant[16]]]
name[self].username assign[=] name[username]
return[dictionary[[<ast.Constant ... | keyword[def] identifier[passwordLogin] ( identifier[self] , identifier[username] ):
literal[string]
identifier[self] . identifier[challenge] = identifier[secureRandom] ( literal[int] )
identifier[self] . identifier[username] = identifier[username]
keyword[return] { literal[string... | def passwordLogin(self, username):
"""
Generate a new challenge for the given username.
"""
self.challenge = secureRandom(16)
self.username = username
return {'challenge': self.challenge} |
def connect_fps(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.connection.F... | def function[connect_fps, parameter[aws_access_key_id, aws_secret_access_key]]:
constant[
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.c... | keyword[def] identifier[connect_fps] ( identifier[aws_access_key_id] = keyword[None] , identifier[aws_secret_access_key] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[from] identifier[boto] . identifier[fps] . identifier[connection] keyword[import] identifier[FPSConnection]
key... | def connect_fps(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.fps.connection.F... |
def fprocess(infilep,outfilep):
"""
Scans an input file for LA equations between double square brackets,
e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression
with a comment containing the equation followed by nested function calls
that implement the equation as C code. A trailin... | def function[fprocess, parameter[infilep, outfilep]]:
constant[
Scans an input file for LA equations between double square brackets,
e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression
with a comment containing the equation followed by nested function calls
that implement the e... | keyword[def] identifier[fprocess] ( identifier[infilep] , identifier[outfilep] ):
literal[string]
identifier[pattern] = literal[string]
identifier[eqn] = identifier[re] . identifier[compile] ( identifier[pattern] , identifier[re] . identifier[DOTALL] )
identifier[s] = identifier[infilep] . ident... | def fprocess(infilep, outfilep):
"""
Scans an input file for LA equations between double square brackets,
e.g. [[ M3_mymatrix = M3_anothermatrix^-1 ]], and replaces the expression
with a comment containing the equation followed by nested function calls
that implement the equation as C code. A trailing s... |
def _get_element_by_names(source, names):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute names
"""
if source is Non... | def function[_get_element_by_names, parameter[source, names]]:
constant[
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute name... | keyword[def] identifier[_get_element_by_names] ( identifier[source] , identifier[names] ):
literal[string]
keyword[if] identifier[source] keyword[is] keyword[None] :
keyword[return] identifier[source]
keyword[else] :
keyword[if] identifier[names] :
identifier[hea... | def _get_element_by_names(source, names):
"""
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve
the specified element.
Args:
source (dict): set of nested objects in which the data will be searched
path (list): list of attribute names
"""
if source is None... |
async def post(self, public_key):
"""Writes contents review
"""
if settings.SIGNATURE_VERIFICATION:
super().verify()
try:
body = json.loads(self.request.body)
except:
self.set_status(400)
self.write({"error":400, "reason":"Unexpected data format. JSON required"})
raise tornado.web.Finish
... | <ast.AsyncFunctionDef object at 0x7da1b2344a30> | keyword[async] keyword[def] identifier[post] ( identifier[self] , identifier[public_key] ):
literal[string]
keyword[if] identifier[settings] . identifier[SIGNATURE_VERIFICATION] :
identifier[super] (). identifier[verify] ()
keyword[try] :
identifier[body] = identifier[json] . identifier[loads] ( ... | async def post(self, public_key):
"""Writes contents review
"""
if settings.SIGNATURE_VERIFICATION:
super().verify() # depends on [control=['if'], data=[]]
try:
body = json.loads(self.request.body) # depends on [control=['try'], data=[]]
except:
self.set_status(400)
s... |
def assign_from_list(obj: T,
fieldlist: Sequence[str],
valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != len(valuelist):
raise AssertionError("assign_from_list: ... | def function[assign_from_list, parameter[obj, fieldlist, valuelist]]:
constant[Within "obj", assigns the values from the value list to the fields in
the fieldlist.]
if compare[call[name[len], parameter[name[fieldlist]]] not_equal[!=] call[name[len], parameter[name[valuelist]]]] begin[:]
<ast... | keyword[def] identifier[assign_from_list] ( identifier[obj] : identifier[T] ,
identifier[fieldlist] : identifier[Sequence] [ identifier[str] ],
identifier[valuelist] : identifier[Sequence] [ identifier[any] ])-> keyword[None] :
literal[string]
keyword[if] identifier[len] ( identifier[fieldlist] )!= iden... | def assign_from_list(obj: T, fieldlist: Sequence[str], valuelist: Sequence[any]) -> None:
"""Within "obj", assigns the values from the value list to the fields in
the fieldlist."""
if len(fieldlist) != len(valuelist):
raise AssertionError('assign_from_list: fieldlist and valuelist of different lengt... |
def stringify(data):
"""Turns all dictionary values into strings"""
if isinstance(data, dict):
for key, value in data.items():
data[key] = stringify(value)
elif isinstance(data, list):
return [stringify(item) for item in data]
else:
return smart_text(data)
return... | def function[stringify, parameter[data]]:
constant[Turns all dictionary values into strings]
if call[name[isinstance], parameter[name[data], name[dict]]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da20c6a8d60>, <ast.Name object at 0x7da20c6aae90>]]] in starred[call[name[data].items... | keyword[def] identifier[stringify] ( identifier[data] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[data] , identifier[dict] ):
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[data] . identifier[items] ():
identifier[data] [ identifier[... | def stringify(data):
"""Turns all dictionary values into strings"""
if isinstance(data, dict):
for (key, value) in data.items():
data[key] = stringify(value) # depends on [control=['for'], data=[]] # depends on [control=['if'], data=[]]
elif isinstance(data, list):
return [stri... |
def group_for_policy(self, policy=None):
"""
Lookup the collective.workspace usergroup corresponding to the
given policy
:param policy: The value of the policy to lookup, defaults to the
current policy
:type policy: str
"""
if policy is Non... | def function[group_for_policy, parameter[self, policy]]:
constant[
Lookup the collective.workspace usergroup corresponding to the
given policy
:param policy: The value of the policy to lookup, defaults to the
current policy
:type policy: str
]
... | keyword[def] identifier[group_for_policy] ( identifier[self] , identifier[policy] = keyword[None] ):
literal[string]
keyword[if] identifier[policy] keyword[is] keyword[None] :
identifier[policy] = identifier[self] . identifier[context] . identifier[participant_policy]
keyw... | def group_for_policy(self, policy=None):
"""
Lookup the collective.workspace usergroup corresponding to the
given policy
:param policy: The value of the policy to lookup, defaults to the
current policy
:type policy: str
"""
if policy is None:
... |
def work_peer_add(self, address, port):
"""
Add specific **IP address** and **port** as work peer for node until
restart
.. enable_control required
.. version 8.0 required
:param address: IP address of work peer to add
:type address: str
:param port: Po... | def function[work_peer_add, parameter[self, address, port]]:
constant[
Add specific **IP address** and **port** as work peer for node until
restart
.. enable_control required
.. version 8.0 required
:param address: IP address of work peer to add
:type address: s... | keyword[def] identifier[work_peer_add] ( identifier[self] , identifier[address] , identifier[port] ):
literal[string]
identifier[address] = identifier[self] . identifier[_process_value] ( identifier[address] , literal[string] )
identifier[port] = identifier[self] . identifier[_process_val... | def work_peer_add(self, address, port):
"""
Add specific **IP address** and **port** as work peer for node until
restart
.. enable_control required
.. version 8.0 required
:param address: IP address of work peer to add
:type address: str
:param port: Port w... |
def getBottomLeft(self):
"""
Retrieves a tuple with the x,y coordinates of the lower left point of the circle.
Requires the radius and the coordinates to be numbers
"""
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) - float(self.get_r())) | def function[getBottomLeft, parameter[self]]:
constant[
Retrieves a tuple with the x,y coordinates of the lower left point of the circle.
Requires the radius and the coordinates to be numbers
]
return[tuple[[<ast.BinOp object at 0x7da18f722650>, <ast.BinOp object at 0x7da18f722830>]... | keyword[def] identifier[getBottomLeft] ( identifier[self] ):
literal[string]
keyword[return] ( identifier[float] ( identifier[self] . identifier[get_cx] ())- identifier[float] ( identifier[self] . identifier[get_r] ()), identifier[float] ( identifier[self] . identifier[get_cy] ())- identifier[float... | def getBottomLeft(self):
"""
Retrieves a tuple with the x,y coordinates of the lower left point of the circle.
Requires the radius and the coordinates to be numbers
"""
return (float(self.get_cx()) - float(self.get_r()), float(self.get_cy()) - float(self.get_r())) |
def send(self, s):
"""
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
"""
self._print_header('======== Sending ({0}) ========'.format(len(s)))
self._log_send(s)
out = len(s)
while s:
s = s[self._send(s):]
... | def function[send, parameter[self, s]]:
constant[
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
]
call[name[self]._print_header, parameter[call[constant[======== Sending ({0}) ========].format, parameter[call[name[len], parameter[name[s]]]]]]]
... | keyword[def] identifier[send] ( identifier[self] , identifier[s] ):
literal[string]
identifier[self] . identifier[_print_header] ( literal[string] . identifier[format] ( identifier[len] ( identifier[s] )))
identifier[self] . identifier[_log_send] ( identifier[s] )
identifier[out]... | def send(self, s):
"""
Sends all the given data to the socket.
Aliases: write, put, sendall, send_all
"""
self._print_header('======== Sending ({0}) ========'.format(len(s)))
self._log_send(s)
out = len(s)
while s:
s = s[self._send(s):] # depends on [control=['while... |
def traverse(self, index=0):
""" This is used to produce a list of lists where each each item
in that list is a diffrent combination of items from the lists
within with every combination of such values.
Args:
index (int) : the index at witch to start the list.
... | def function[traverse, parameter[self, index]]:
constant[ This is used to produce a list of lists where each each item
in that list is a diffrent combination of items from the lists
within with every combination of such values.
Args:
index (int) : the index at witch to start... | keyword[def] identifier[traverse] ( identifier[self] , identifier[index] = literal[int] ):
literal[string]
keyword[if] identifier[index] < identifier[len] ( identifier[self] . identifier[nodes] ):
keyword[for] identifier[entity] keyword[in] identifier[self] . identifier[nodes] [ id... | def traverse(self, index=0):
""" This is used to produce a list of lists where each each item
in that list is a diffrent combination of items from the lists
within with every combination of such values.
Args:
index (int) : the index at witch to start the list.
No... |
def formatter(color, s):
""" Formats a string with color """
if no_coloring:
return s
return "{begin}{s}{reset}".format(begin=color, s=s, reset=Colors.RESET) | def function[formatter, parameter[color, s]]:
constant[ Formats a string with color ]
if name[no_coloring] begin[:]
return[name[s]]
return[call[constant[{begin}{s}{reset}].format, parameter[]]] | keyword[def] identifier[formatter] ( identifier[color] , identifier[s] ):
literal[string]
keyword[if] identifier[no_coloring] :
keyword[return] identifier[s]
keyword[return] literal[string] . identifier[format] ( identifier[begin] = identifier[color] , identifier[s] = identifier[s] , iden... | def formatter(color, s):
""" Formats a string with color """
if no_coloring:
return s # depends on [control=['if'], data=[]]
return '{begin}{s}{reset}'.format(begin=color, s=s, reset=Colors.RESET) |
def get_node_text(self, goid, goobj):
"""Return a string to be printed in a GO term box."""
txt = []
# Header line: "GO:0036464 L04 D06"
txt.append(self.get_hdr(goid, goobj))
# GO name line: "cytoplamic ribonucleoprotein"
if 'no_name' not in self.present:
txt.... | def function[get_node_text, parameter[self, goid, goobj]]:
constant[Return a string to be printed in a GO term box.]
variable[txt] assign[=] list[[]]
call[name[txt].append, parameter[call[name[self].get_hdr, parameter[name[goid], name[goobj]]]]]
if compare[constant[no_name] <ast.NotIn ob... | keyword[def] identifier[get_node_text] ( identifier[self] , identifier[goid] , identifier[goobj] ):
literal[string]
identifier[txt] =[]
identifier[txt] . identifier[append] ( identifier[self] . identifier[get_hdr] ( identifier[goid] , identifier[goobj] ))
keyword... | def get_node_text(self, goid, goobj):
"""Return a string to be printed in a GO term box."""
txt = []
# Header line: "GO:0036464 L04 D06"
txt.append(self.get_hdr(goid, goobj))
# GO name line: "cytoplamic ribonucleoprotein"
if 'no_name' not in self.present:
txt.append(self._get_go_name(goo... |
def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
... | def function[decipher, parameter[self, string]]:
constant[Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' ... | keyword[def] identifier[decipher] ( identifier[self] , identifier[string] ):
literal[string]
identifier[string] = identifier[self] . identifier[remove_punctuation] ( identifier[string] )
keyword[if] identifier[len] ( identifier[string] )% literal[int] == literal[int] :
identi... | def decipher(self, string):
"""Decipher string using Playfair cipher according to initialised key. Punctuation and whitespace
are removed from the input. The ciphertext should be an even number of characters. If the input ciphertext is not an even number of characters, an 'X' will be appended.
Exam... |
def volume(self) -> float:
"""
Volume of the unit cell.
"""
m = self._matrix
return float(abs(dot(np.cross(m[0], m[1]), m[2]))) | def function[volume, parameter[self]]:
constant[
Volume of the unit cell.
]
variable[m] assign[=] name[self]._matrix
return[call[name[float], parameter[call[name[abs], parameter[call[name[dot], parameter[call[name[np].cross, parameter[call[name[m]][constant[0]], call[name[m]][constan... | keyword[def] identifier[volume] ( identifier[self] )-> identifier[float] :
literal[string]
identifier[m] = identifier[self] . identifier[_matrix]
keyword[return] identifier[float] ( identifier[abs] ( identifier[dot] ( identifier[np] . identifier[cross] ( identifier[m] [ literal[int] ], i... | def volume(self) -> float:
"""
Volume of the unit cell.
"""
m = self._matrix
return float(abs(dot(np.cross(m[0], m[1]), m[2]))) |
def getcomments(object):
"""Get lines of comments immediately preceding an object's source code."""
try: lines, lnum = findsource(object)
except IOError: return None
if ismodule(object):
# Look for a comment block at the top of the file.
start = 0
if lines and lines[0][:2] == '#... | def function[getcomments, parameter[object]]:
constant[Get lines of comments immediately preceding an object's source code.]
<ast.Try object at 0x7da1b08d93c0>
if call[name[ismodule], parameter[name[object]]] begin[:]
variable[start] assign[=] constant[0]
if <ast.Bool... | keyword[def] identifier[getcomments] ( identifier[object] ):
literal[string]
keyword[try] : identifier[lines] , identifier[lnum] = identifier[findsource] ( identifier[object] )
keyword[except] identifier[IOError] : keyword[return] keyword[None]
keyword[if] identifier[ismodule] ( identifier[o... | def getcomments(object):
"""Get lines of comments immediately preceding an object's source code."""
try:
(lines, lnum) = findsource(object) # depends on [control=['try'], data=[]]
except IOError:
return None # depends on [control=['except'], data=[]]
if ismodule(object):
# Look... |
def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"""
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site... | def function[egg_link_path, parameter[dist]]:
constant[
Return the path for the .egg-link file if it exists, otherwise, None.
There's 3 scenarios:
1) not in a virtualenv
try to find in site.USER_SITE, then site_packages
2) in a no-global virtualenv
try to find in site_packages
... | keyword[def] identifier[egg_link_path] ( identifier[dist] ):
literal[string]
identifier[sites] =[]
keyword[if] identifier[running_under_virtualenv] ():
keyword[if] identifier[virtualenv_no_global] ():
identifier[sites] . identifier[append] ( identifier[site_packages] )
... | def egg_link_path(dist):
# type: (Distribution) -> Optional[str]
"\n Return the path for the .egg-link file if it exists, otherwise, None.\n\n There's 3 scenarios:\n 1) not in a virtualenv\n try to find in site.USER_SITE, then site_packages\n 2) in a no-global virtualenv\n try to find in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.