code stringlengths 75 104k | code_sememe stringlengths 47 309k | token_type stringlengths 215 214k | code_dependency stringlengths 75 155k |
|---|---|---|---|
def GetSyncMoConfigFilePath():
""" Method returs the path of SyncMoConfig.xml file. """
return os.path.join(os.path.join(os.path.dirname(__file__), "resources"), "SyncMoConfig.xml") | def function[GetSyncMoConfigFilePath, parameter[]]:
constant[ Method returs the path of SyncMoConfig.xml file. ]
return[call[name[os].path.join, parameter[call[name[os].path.join, parameter[call[name[os].path.dirname, parameter[name[__file__]]], constant[resources]]], constant[SyncMoConfig.xml]]]] | keyword[def] identifier[GetSyncMoConfigFilePath] ():
literal[string]
keyword[return] identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[join] ( identifier[os] . identifier[path] . identifier[dirname] ( identifier[__file__] ), literal[string] ), literal[string... | def GetSyncMoConfigFilePath():
""" Method returs the path of SyncMoConfig.xml file. """
return os.path.join(os.path.join(os.path.dirname(__file__), 'resources'), 'SyncMoConfig.xml') |
def _gsa_update_velocity(velocity, acceleration):
"""Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i
"""
# The GSA algorithm specifies that the new velocity for each dimension
# is a sum of a random fraction of its current velocity in that dime... | def function[_gsa_update_velocity, parameter[velocity, acceleration]]:
constant[Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i
]
variable[new_velocity] assign[=] list[[]]
for taget[tuple[[<ast.Name object at 0x7da1b04ca650>, <ast.Na... | keyword[def] identifier[_gsa_update_velocity] ( identifier[velocity] , identifier[acceleration] ):
literal[string]
identifier[new_velocity] =[]
keyword[for] identifier[vel] , identifier[acc] keyword[in] identifier[zip] ( identifier[velocity] , identifier[acceleration] ):
... | def _gsa_update_velocity(velocity, acceleration):
"""Stochastically update velocity given acceleration.
In GSA paper, velocity is v_i, acceleration is a_i
"""
# The GSA algorithm specifies that the new velocity for each dimension
# is a sum of a random fraction of its current velocity in that dimen... |
def array_info(self, dump=None, paths=None, attrs=True,
standardize_dims=True, pwd=None, use_rel_paths=True,
alternative_paths={}, ds_description={'fname', 'store'},
full_ds=True, copy=False, **kwargs):
"""
Get dimension informations on you arrays... | def function[array_info, parameter[self, dump, paths, attrs, standardize_dims, pwd, use_rel_paths, alternative_paths, ds_description, full_ds, copy]]:
constant[
Get dimension informations on you arrays
This method returns a dictionary containing informations on the
array in this instanc... | keyword[def] identifier[array_info] ( identifier[self] , identifier[dump] = keyword[None] , identifier[paths] = keyword[None] , identifier[attrs] = keyword[True] ,
identifier[standardize_dims] = keyword[True] , identifier[pwd] = keyword[None] , identifier[use_rel_paths] = keyword[True] ,
identifier[alternative_path... | def array_info(self, dump=None, paths=None, attrs=True, standardize_dims=True, pwd=None, use_rel_paths=True, alternative_paths={}, ds_description={'fname', 'store'}, full_ds=True, copy=False, **kwargs):
"""
Get dimension informations on you arrays
This method returns a dictionary containing informa... |
def _colorify(self, data):
"""
Retun colored string.
:param data: The string to colorify.
:type data: str
:return: A colored string.
:rtype: str
"""
if self.template in ["Generic", "Less"]:
# The template is in the list of template that need... | def function[_colorify, parameter[self, data]]:
constant[
Retun colored string.
:param data: The string to colorify.
:type data: str
:return: A colored string.
:rtype: str
]
if compare[name[self].template in list[[<ast.Constant object at 0x7da20e9572e0>,... | keyword[def] identifier[_colorify] ( identifier[self] , identifier[data] ):
literal[string]
keyword[if] identifier[self] . identifier[template] keyword[in] [ literal[string] , literal[string] ]:
keyword[if] (
identifier[self] . identifier[data_to_print] [ lite... | def _colorify(self, data):
"""
Retun colored string.
:param data: The string to colorify.
:type data: str
:return: A colored string.
:rtype: str
"""
if self.template in ['Generic', 'Less']:
# The template is in the list of template that need the colorati... |
def _convenienceMatch(self, role, attr, match):
"""Method used by role based convenience functions to find a match"""
kwargs = {}
# If the user supplied some text to search for,
# supply that in the kwargs
if match:
kwargs[attr] = match
return self.findAll(AXR... | def function[_convenienceMatch, parameter[self, role, attr, match]]:
constant[Method used by role based convenience functions to find a match]
variable[kwargs] assign[=] dictionary[[], []]
if name[match] begin[:]
call[name[kwargs]][name[attr]] assign[=] name[match]
return[cal... | keyword[def] identifier[_convenienceMatch] ( identifier[self] , identifier[role] , identifier[attr] , identifier[match] ):
literal[string]
identifier[kwargs] ={}
keyword[if] identifier[match] :
identifier[kwargs] [ identifier[attr] ]= identifier[match]
... | def _convenienceMatch(self, role, attr, match):
"""Method used by role based convenience functions to find a match"""
kwargs = {}
# If the user supplied some text to search for,
# supply that in the kwargs
if match:
kwargs[attr] = match # depends on [control=['if'], data=[]]
return self... |
def apply_t0(self, hits):
"""Apply only t0s"""
if HAVE_NUMBA:
apply_t0_nb(
hits.time, hits.dom_id, hits.channel_id, self._lookup_tables
)
else:
n = len(hits)
cal = np.empty(n)
lookup = self._calib_by_dom_and_channel
... | def function[apply_t0, parameter[self, hits]]:
constant[Apply only t0s]
if name[HAVE_NUMBA] begin[:]
call[name[apply_t0_nb], parameter[name[hits].time, name[hits].dom_id, name[hits].channel_id, name[self]._lookup_tables]]
return[name[hits]] | keyword[def] identifier[apply_t0] ( identifier[self] , identifier[hits] ):
literal[string]
keyword[if] identifier[HAVE_NUMBA] :
identifier[apply_t0_nb] (
identifier[hits] . identifier[time] , identifier[hits] . identifier[dom_id] , identifier[hits] . identifier[channel_id... | def apply_t0(self, hits):
"""Apply only t0s"""
if HAVE_NUMBA:
apply_t0_nb(hits.time, hits.dom_id, hits.channel_id, self._lookup_tables) # depends on [control=['if'], data=[]]
else:
n = len(hits)
cal = np.empty(n)
lookup = self._calib_by_dom_and_channel
for i in range... |
def deprecated(func, solution):
"""
Mark a parser or combiner as deprecated, and give a message of how to fix
this. This will emit a warning in the logs when the function is used.
When combined with modifications to conftest, this causes deprecations to
become fatal errors when testing, so they get... | def function[deprecated, parameter[func, solution]]:
constant[
Mark a parser or combiner as deprecated, and give a message of how to fix
this. This will emit a warning in the logs when the function is used.
When combined with modifications to conftest, this causes deprecations to
become fatal e... | keyword[def] identifier[deprecated] ( identifier[func] , identifier[solution] ):
literal[string]
keyword[def] identifier[get_name_line] ( identifier[src] ):
keyword[for] identifier[line] keyword[in] identifier[src] :
keyword[if] literal[string] keyword[not] keyword[in] identi... | def deprecated(func, solution):
"""
Mark a parser or combiner as deprecated, and give a message of how to fix
this. This will emit a warning in the logs when the function is used.
When combined with modifications to conftest, this causes deprecations to
become fatal errors when testing, so they get... |
def resize_by_area(img, size):
"""image resize function used by quite a few image problems."""
return tf.to_int64(
tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) | def function[resize_by_area, parameter[img, size]]:
constant[image resize function used by quite a few image problems.]
return[call[name[tf].to_int64, parameter[call[name[tf].image.resize_images, parameter[name[img], list[[<ast.Name object at 0x7da18f00f220>, <ast.Name object at 0x7da18f00f040>]], name[tf].... | keyword[def] identifier[resize_by_area] ( identifier[img] , identifier[size] ):
literal[string]
keyword[return] identifier[tf] . identifier[to_int64] (
identifier[tf] . identifier[image] . identifier[resize_images] ( identifier[img] ,[ identifier[size] , identifier[size] ], identifier[tf] . identifier[imag... | def resize_by_area(img, size):
"""image resize function used by quite a few image problems."""
return tf.to_int64(tf.image.resize_images(img, [size, size], tf.image.ResizeMethod.AREA)) |
def keep_vertices(self, indices_to_keep, ret_kept_edges=False):
'''
Keep the given vertices and discard the others, and any edges to which
they may belong.
If `ret_kept_edges` is `True`, return the original indices of the kept
edges. Otherwise return `self` for chaining.
... | def function[keep_vertices, parameter[self, indices_to_keep, ret_kept_edges]]:
constant[
Keep the given vertices and discard the others, and any edges to which
they may belong.
If `ret_kept_edges` is `True`, return the original indices of the kept
edges. Otherwise return `self`... | keyword[def] identifier[keep_vertices] ( identifier[self] , identifier[indices_to_keep] , identifier[ret_kept_edges] = keyword[False] ):
literal[string]
keyword[if] identifier[self] . identifier[v] keyword[is] keyword[None] :
keyword[return]
identifier[initial_num_verts]... | def keep_vertices(self, indices_to_keep, ret_kept_edges=False):
"""
Keep the given vertices and discard the others, and any edges to which
they may belong.
If `ret_kept_edges` is `True`, return the original indices of the kept
edges. Otherwise return `self` for chaining.
"... |
def decipher(self,string):
"""Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintex... | def function[decipher, parameter[self, string]]:
constant[Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The dec... | keyword[def] identifier[decipher] ( identifier[self] , identifier[string] ):
literal[string]
identifier[string] = identifier[self] . identifier[remove_punctuation] ( identifier[string] , identifier[filter] = literal[string] + identifier[self] . identifier[chars] + literal[string] )
identif... | def decipher(self, string):
"""Decipher string using Delastelle cipher according to initialised key.
Example::
plaintext = Delastelle('APCZ WRLFBDKOTYUQGENHXMIVS').decipher(ciphertext)
:param string: The string to decipher.
:returns: The deciphered string. The plaintext w... |
def make_ttv_yaml(corpora, path_to_ttv_file, ttv_ratio=DEFAULT_TTV_RATIO, deterministic=False):
""" Create a test, train, validation from the corpora given and saves it as a YAML filename.
Each set will be subject independent, meaning that no one subject can have data in more than one
set
# Ar... | def function[make_ttv_yaml, parameter[corpora, path_to_ttv_file, ttv_ratio, deterministic]]:
constant[ Create a test, train, validation from the corpora given and saves it as a YAML filename.
Each set will be subject independent, meaning that no one subject can have data in more than one
set
... | keyword[def] identifier[make_ttv_yaml] ( identifier[corpora] , identifier[path_to_ttv_file] , identifier[ttv_ratio] = identifier[DEFAULT_TTV_RATIO] , identifier[deterministic] = keyword[False] ):
literal[string]
identifier[dataset] = identifier[get_dataset] ( identifier[corpora] )
identifier[data_sets... | def make_ttv_yaml(corpora, path_to_ttv_file, ttv_ratio=DEFAULT_TTV_RATIO, deterministic=False):
""" Create a test, train, validation from the corpora given and saves it as a YAML filename.
Each set will be subject independent, meaning that no one subject can have data in more than one
set
# Ar... |
def check_resize(resize):
"""checks resize parameter if illegal value raises exception"""
if resize is None:
return
resize = resize.lower().strip()
if 'x' in resize:
tmp = resize.lower().split('x')
tmp = [x.strip() for x in resize.split('x')]
if len(tmp) == 2 and tmp[0]... | def function[check_resize, parameter[resize]]:
constant[checks resize parameter if illegal value raises exception]
if compare[name[resize] is constant[None]] begin[:]
return[None]
variable[resize] assign[=] call[call[name[resize].lower, parameter[]].strip, parameter[]]
if compare... | keyword[def] identifier[check_resize] ( identifier[resize] ):
literal[string]
keyword[if] identifier[resize] keyword[is] keyword[None] :
keyword[return]
identifier[resize] = identifier[resize] . identifier[lower] (). identifier[strip] ()
keyword[if] literal[string] keyword[in] i... | def check_resize(resize):
"""checks resize parameter if illegal value raises exception"""
if resize is None:
return # depends on [control=['if'], data=[]]
resize = resize.lower().strip()
if 'x' in resize:
tmp = resize.lower().split('x')
tmp = [x.strip() for x in resize.split('x'... |
def order_enum(field, members):
"""
Make an annotation value that can be used to sort by an enum field.
``field``
The name of an EnumChoiceField.
``members``
An iterable of Enum members in the order to sort by.
Use like:
.. code-block:: python
desired_order = [MyEnum... | def function[order_enum, parameter[field, members]]:
constant[
Make an annotation value that can be used to sort by an enum field.
``field``
The name of an EnumChoiceField.
``members``
An iterable of Enum members in the order to sort by.
Use like:
.. code-block:: python
... | keyword[def] identifier[order_enum] ( identifier[field] , identifier[members] ):
literal[string]
identifier[members] = identifier[list] ( identifier[members] )
keyword[return] identifier[Case] (
*( identifier[When] (**{ identifier[field] : identifier[member] , literal[string] : identifier[i] })
... | def order_enum(field, members):
"""
Make an annotation value that can be used to sort by an enum field.
``field``
The name of an EnumChoiceField.
``members``
An iterable of Enum members in the order to sort by.
Use like:
.. code-block:: python
desired_order = [MyEnum... |
def final_spin_from_f0_tau(f0, tau, l=2, m=2):
"""Returns the final spin based on the given frequency and damping time.
.. note::
Currently, only l = m = 2 is supported. Any other indices will raise
a ``KeyError``.
Parameters
----------
f0 : float or array
Frequency of the ... | def function[final_spin_from_f0_tau, parameter[f0, tau, l, m]]:
constant[Returns the final spin based on the given frequency and damping time.
.. note::
Currently, only l = m = 2 is supported. Any other indices will raise
a ``KeyError``.
Parameters
----------
f0 : float or arra... | keyword[def] identifier[final_spin_from_f0_tau] ( identifier[f0] , identifier[tau] , identifier[l] = literal[int] , identifier[m] = literal[int] ):
literal[string]
identifier[f0] , identifier[tau] , identifier[input_is_array] = identifier[ensurearray] ( identifier[f0] , identifier[tau] )
identifi... | def final_spin_from_f0_tau(f0, tau, l=2, m=2):
"""Returns the final spin based on the given frequency and damping time.
.. note::
Currently, only l = m = 2 is supported. Any other indices will raise
a ``KeyError``.
Parameters
----------
f0 : float or array
Frequency of the ... |
def calc_pvalue(self, study_count, study_n, pop_count, pop_n):
"""pvalues are calculated in derived classes."""
fnc_call = "calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})".format(
SCNT=study_count, STOT=study_n, PCNT=pop_count, PTOT=pop_n)
raise Exception("NOT IMPLEMENTED: {FNC_CALL} usi... | def function[calc_pvalue, parameter[self, study_count, study_n, pop_count, pop_n]]:
constant[pvalues are calculated in derived classes.]
variable[fnc_call] assign[=] call[constant[calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})].format, parameter[]]
<ast.Raise object at 0x7da18f811360> | keyword[def] identifier[calc_pvalue] ( identifier[self] , identifier[study_count] , identifier[study_n] , identifier[pop_count] , identifier[pop_n] ):
literal[string]
identifier[fnc_call] = literal[string] . identifier[format] (
identifier[SCNT] = identifier[study_count] , identifier[STOT]... | def calc_pvalue(self, study_count, study_n, pop_count, pop_n):
"""pvalues are calculated in derived classes."""
fnc_call = 'calc_pvalue({SCNT}, {STOT}, {PCNT} {PTOT})'.format(SCNT=study_count, STOT=study_n, PCNT=pop_count, PTOT=pop_n)
raise Exception('NOT IMPLEMENTED: {FNC_CALL} using {FNC}.'.format(FNC_CAL... |
def get(self, sid):
"""
Constructs a InstalledAddOnExtensionContext
:param sid: The unique Extension Sid
:returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext
:rtype: twilio.rest.preview.marketplace.installed_add_on... | def function[get, parameter[self, sid]]:
constant[
Constructs a InstalledAddOnExtensionContext
:param sid: The unique Extension Sid
:returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext
:rtype: twilio.rest.preview.m... | keyword[def] identifier[get] ( identifier[self] , identifier[sid] ):
literal[string]
keyword[return] identifier[InstalledAddOnExtensionContext] (
identifier[self] . identifier[_version] ,
identifier[installed_add_on_sid] = identifier[self] . identifier[_solution] [ literal[string... | def get(self, sid):
"""
Constructs a InstalledAddOnExtensionContext
:param sid: The unique Extension Sid
:returns: twilio.rest.preview.marketplace.installed_add_on.installed_add_on_extension.InstalledAddOnExtensionContext
:rtype: twilio.rest.preview.marketplace.installed_add_on.ins... |
def nmf_ensemble(data, k, n_runs=10, W_list=[], **nmf_params):
"""
Runs an ensemble method on the list of NMF W matrices...
Args:
data: genes x cells array (should be log + cell-normalized)
k: number of classes
n_runs (optional): number of random initializations of state estimation
... | def function[nmf_ensemble, parameter[data, k, n_runs, W_list]]:
constant[
Runs an ensemble method on the list of NMF W matrices...
Args:
data: genes x cells array (should be log + cell-normalized)
k: number of classes
n_runs (optional): number of random initializations of state ... | keyword[def] identifier[nmf_ensemble] ( identifier[data] , identifier[k] , identifier[n_runs] = literal[int] , identifier[W_list] =[],** identifier[nmf_params] ):
literal[string]
identifier[nmf] = identifier[NMF] ( identifier[k] )
keyword[if] identifier[len] ( identifier[W_list] )== literal[int] :
... | def nmf_ensemble(data, k, n_runs=10, W_list=[], **nmf_params):
"""
Runs an ensemble method on the list of NMF W matrices...
Args:
data: genes x cells array (should be log + cell-normalized)
k: number of classes
n_runs (optional): number of random initializations of state estimation
... |
def refreshMinMax(self):
""" Refreshes the min max config values from the axes' state.
Does nothing when self.getRefreshBlocked() returns True.
"""
if self.getRefreshBlocked():
logger.debug("refreshMinMax blocked for {}".format(self.nodeName))
return
... | def function[refreshMinMax, parameter[self]]:
constant[ Refreshes the min max config values from the axes' state.
Does nothing when self.getRefreshBlocked() returns True.
]
if call[name[self].getRefreshBlocked, parameter[]] begin[:]
call[name[logger].debug, parameter[... | keyword[def] identifier[refreshMinMax] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[getRefreshBlocked] ():
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[self] . identifier[nodeName] ))
keyword... | def refreshMinMax(self):
""" Refreshes the min max config values from the axes' state.
Does nothing when self.getRefreshBlocked() returns True.
"""
if self.getRefreshBlocked():
logger.debug('refreshMinMax blocked for {}'.format(self.nodeName))
return # depends on [control=['... |
def serial(self, may_block=True):
""" Get the YubiKey serial number (requires YubiKey 2.2). """
if not self.capabilities.have_serial_number():
raise yubikey_base.YubiKeyVersionError("Serial number unsupported in YubiKey %s" % self.version() )
return self._read_serial(may_block) | def function[serial, parameter[self, may_block]]:
constant[ Get the YubiKey serial number (requires YubiKey 2.2). ]
if <ast.UnaryOp object at 0x7da1b0889f00> begin[:]
<ast.Raise object at 0x7da1b088b130>
return[call[name[self]._read_serial, parameter[name[may_block]]]] | keyword[def] identifier[serial] ( identifier[self] , identifier[may_block] = keyword[True] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[capabilities] . identifier[have_serial_number] ():
keyword[raise] identifier[yubikey_base] . identifier[YubiKeyVersion... | def serial(self, may_block=True):
""" Get the YubiKey serial number (requires YubiKey 2.2). """
if not self.capabilities.have_serial_number():
raise yubikey_base.YubiKeyVersionError('Serial number unsupported in YubiKey %s' % self.version()) # depends on [control=['if'], data=[]]
return self._read_... |
def write_history(self, history):
"""
Write history text into the header
"""
self._FITS.write_history(self._ext+1, str(history)) | def function[write_history, parameter[self, history]]:
constant[
Write history text into the header
]
call[name[self]._FITS.write_history, parameter[binary_operation[name[self]._ext + constant[1]], call[name[str], parameter[name[history]]]]] | keyword[def] identifier[write_history] ( identifier[self] , identifier[history] ):
literal[string]
identifier[self] . identifier[_FITS] . identifier[write_history] ( identifier[self] . identifier[_ext] + literal[int] , identifier[str] ( identifier[history] )) | def write_history(self, history):
"""
Write history text into the header
"""
self._FITS.write_history(self._ext + 1, str(history)) |
def fit(self, **kwargs):
"""Call the fit method of the primitive.
The given keyword arguments will be passed directly to the `fit`
method of the primitive instance specified in the JSON annotation.
If any of the arguments expected by the produce method had been
given during the... | def function[fit, parameter[self]]:
constant[Call the fit method of the primitive.
The given keyword arguments will be passed directly to the `fit`
method of the primitive instance specified in the JSON annotation.
If any of the arguments expected by the produce method had been
... | keyword[def] identifier[fit] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[self] . identifier[fit_method] keyword[is] keyword[not] keyword[None] :
identifier[fit_args] = identifier[self] . identifier[_fit_params] . identifier[copy] ()
... | def fit(self, **kwargs):
"""Call the fit method of the primitive.
The given keyword arguments will be passed directly to the `fit`
method of the primitive instance specified in the JSON annotation.
If any of the arguments expected by the produce method had been
given during the MLB... |
def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
"""
input_dict = su... | def function[to_dict, parameter[self]]:
constant[
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
]... | keyword[def] identifier[to_dict] ( identifier[self] ):
literal[string]
identifier[input_dict] = identifier[super] ( identifier[StdPeriodic] , identifier[self] ). identifier[_save_to_input_dict] ()
identifier[input_dict] [ literal[string] ]= literal[string]
identifier[input_dict]... | def to_dict(self):
"""
Convert the object into a json serializable dictionary.
Note: It uses the private method _save_to_input_dict of the parent.
:return dict: json serializable dictionary containing the needed information to instantiate the object
"""
input_dict = super(StdPe... |
def all(self, data={}, **kwargs):
""""
Fetch all Subscription entities
Returns:
Dictionary of Subscription data
"""
return super(Subscription, self).all(data, **kwargs) | def function[all, parameter[self, data]]:
constant["
Fetch all Subscription entities
Returns:
Dictionary of Subscription data
]
return[call[call[name[super], parameter[name[Subscription], name[self]]].all, parameter[name[data]]]] | keyword[def] identifier[all] ( identifier[self] , identifier[data] ={},** identifier[kwargs] ):
literal[string]
keyword[return] identifier[super] ( identifier[Subscription] , identifier[self] ). identifier[all] ( identifier[data] ,** identifier[kwargs] ) | def all(self, data={}, **kwargs):
""""
Fetch all Subscription entities
Returns:
Dictionary of Subscription data
"""
return super(Subscription, self).all(data, **kwargs) |
def get_apps_menu(self):
"""Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered
"""
menu = {}
for model, model_admin in self.admin_site._registry.items():
if hasattr(model_admin, 'app_config... | def function[get_apps_menu, parameter[self]]:
constant[Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered
]
variable[menu] assign[=] dictionary[[], []]
for taget[tuple[[<ast.Name object at 0x7da1b0b3b2... | keyword[def] identifier[get_apps_menu] ( identifier[self] ):
literal[string]
identifier[menu] ={}
keyword[for] identifier[model] , identifier[model_admin] keyword[in] identifier[self] . identifier[admin_site] . identifier[_registry] . identifier[items] ():
keyword[if] iden... | def get_apps_menu(self):
"""Temporal code, will change to apps.get_app_configs() for django 1.7
Generate a initial menu list using the AppsConfig registered
"""
menu = {}
for (model, model_admin) in self.admin_site._registry.items():
if hasattr(model_admin, 'app_config'):
... |
def update(self, time):
""" Update acceleration. Accounts for the importance and
priority (order) of multiple behaviors. """
# .... I feel this stuff could be done a lot better.
total_acceleration = Vector.null()
max_jerk = self.max_acceleration
for behavior in ... | def function[update, parameter[self, time]]:
constant[ Update acceleration. Accounts for the importance and
priority (order) of multiple behaviors. ]
variable[total_acceleration] assign[=] call[name[Vector].null, parameter[]]
variable[max_jerk] assign[=] name[self].max_acceleration
... | keyword[def] identifier[update] ( identifier[self] , identifier[time] ):
literal[string]
identifier[total_acceleration] = identifier[Vector] . identifier[null] ()
identifier[max_jerk] = identifier[self] . identifier[max_acceleration]
keyword[for] identifier[behavior] ... | def update(self, time):
""" Update acceleration. Accounts for the importance and
priority (order) of multiple behaviors. """
# .... I feel this stuff could be done a lot better.
total_acceleration = Vector.null()
max_jerk = self.max_acceleration
for behavior in self.behaviors:
(accel... |
def to_file(file, array):
"""Wrapper around ndarray.tofile to support any file-like object"""
try:
array.tofile(file)
except (TypeError, IOError, UnsupportedOperation):
# tostring actually returns bytes
file.write(array.tostring()) | def function[to_file, parameter[file, array]]:
constant[Wrapper around ndarray.tofile to support any file-like object]
<ast.Try object at 0x7da20c7c8b80> | keyword[def] identifier[to_file] ( identifier[file] , identifier[array] ):
literal[string]
keyword[try] :
identifier[array] . identifier[tofile] ( identifier[file] )
keyword[except] ( identifier[TypeError] , identifier[IOError] , identifier[UnsupportedOperation] ):
identifier[f... | def to_file(file, array):
"""Wrapper around ndarray.tofile to support any file-like object"""
try:
array.tofile(file) # depends on [control=['try'], data=[]]
except (TypeError, IOError, UnsupportedOperation):
# tostring actually returns bytes
file.write(array.tostring()) # depends ... |
def l2_distance_sq(t1, t2, name=None):
"""Square of l2 distance between t1 and t2.
Args:
t1: A tensor.
t2: A tensor that is the same size as t1.
name: Optional name for this op.
Returns:
The l2 distance between t1 and t2.
"""
with tf.name_scope(name, 'l2_distance_sq', [t1, t2]) as scope:
... | def function[l2_distance_sq, parameter[t1, t2, name]]:
constant[Square of l2 distance between t1 and t2.
Args:
t1: A tensor.
t2: A tensor that is the same size as t1.
name: Optional name for this op.
Returns:
The l2 distance between t1 and t2.
]
with call[name[tf].name_scope, para... | keyword[def] identifier[l2_distance_sq] ( identifier[t1] , identifier[t2] , identifier[name] = keyword[None] ):
literal[string]
keyword[with] identifier[tf] . identifier[name_scope] ( identifier[name] , literal[string] ,[ identifier[t1] , identifier[t2] ]) keyword[as] identifier[scope] :
identifier[t1] ... | def l2_distance_sq(t1, t2, name=None):
"""Square of l2 distance between t1 and t2.
Args:
t1: A tensor.
t2: A tensor that is the same size as t1.
name: Optional name for this op.
Returns:
The l2 distance between t1 and t2.
"""
with tf.name_scope(name, 'l2_distance_sq', [t1, t2]) as scope:
... |
def init_session(self, get_token=True):
"""
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
"""
if (self._client_id is None) or (self._clien... | def function[init_session, parameter[self, get_token]]:
constant[
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
]
if <ast.BoolOp object at... | keyword[def] identifier[init_session] ( identifier[self] , identifier[get_token] = keyword[True] ):
literal[string]
keyword[if] ( identifier[self] . identifier[_client_id] keyword[is] keyword[None] ) keyword[or] ( identifier[self] . identifier[_client_secret] keyword[is] keyword[None] ):
... | def init_session(self, get_token=True):
"""
init a new oauth2 session that is required to access the cloud
:param bool get_token: if True, a token will be obtained, after
the session has been created
"""
if self._client_id is None or self._client_secret is... |
def arctic_setting(setting_name, valid_options=None):
"""
Tries to get a setting from the django settings, if not available defaults
to the one defined in defaults.py
"""
try:
value = getattr(settings, setting_name)
if valid_options and value not in valid_options:
error_m... | def function[arctic_setting, parameter[setting_name, valid_options]]:
constant[
Tries to get a setting from the django settings, if not available defaults
to the one defined in defaults.py
]
<ast.Try object at 0x7da1b0415870>
return[call[name[getattr], parameter[name[settings], name[setting_... | keyword[def] identifier[arctic_setting] ( identifier[setting_name] , identifier[valid_options] = keyword[None] ):
literal[string]
keyword[try] :
identifier[value] = identifier[getattr] ( identifier[settings] , identifier[setting_name] )
keyword[if] identifier[valid_options] keyword[and]... | def arctic_setting(setting_name, valid_options=None):
"""
Tries to get a setting from the django settings, if not available defaults
to the one defined in defaults.py
"""
try:
value = getattr(settings, setting_name)
if valid_options and value not in valid_options:
error_m... |
def on_action_begin(self, action, logs={}):
""" Called at beginning of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_begin', None)):
callback.on_action_begin(action, logs=logs) | def function[on_action_begin, parameter[self, action, logs]]:
constant[ Called at beginning of each action for each callback in callbackList]
for taget[name[callback]] in starred[name[self].callbacks] begin[:]
if call[name[callable], parameter[call[name[getattr], parameter[name[callback]... | keyword[def] identifier[on_action_begin] ( identifier[self] , identifier[action] , identifier[logs] ={}):
literal[string]
keyword[for] identifier[callback] keyword[in] identifier[self] . identifier[callbacks] :
keyword[if] identifier[callable] ( identifier[getattr] ( identifier[cal... | def on_action_begin(self, action, logs={}):
""" Called at beginning of each action for each callback in callbackList"""
for callback in self.callbacks:
if callable(getattr(callback, 'on_action_begin', None)):
callback.on_action_begin(action, logs=logs) # depends on [control=['if'], data=[]]... |
def clean_cable_content(content):
"""\
Removes content like "1. (C)" from the content.
`content`
The content of the cable.
"""
for pattern, subst in _CLEAN_PATTERNS:
content = pattern.sub(subst, content)
return content | def function[clean_cable_content, parameter[content]]:
constant[ Removes content like "1. (C)" from the content.
`content`
The content of the cable.
]
for taget[tuple[[<ast.Name object at 0x7da20c993370>, <ast.Name object at 0x7da20c993520>]]] in starred[name[_CLEAN_PATTERNS]] be... | keyword[def] identifier[clean_cable_content] ( identifier[content] ):
literal[string]
keyword[for] identifier[pattern] , identifier[subst] keyword[in] identifier[_CLEAN_PATTERNS] :
identifier[content] = identifier[pattern] . identifier[sub] ( identifier[subst] , identifier[content] )
keywo... | def clean_cable_content(content):
""" Removes content like "1. (C)" from the content.
`content`
The content of the cable.
"""
for (pattern, subst) in _CLEAN_PATTERNS:
content = pattern.sub(subst, content) # depends on [control=['for'], data=[]]
return content |
def create(self, name, site_element):
"""
Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element fail... | def function[create, parameter[self, name, site_element]]:
constant[
Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElement... | keyword[def] identifier[create] ( identifier[self] , identifier[name] , identifier[site_element] ):
literal[string]
identifier[site_element] = identifier[element_resolver] ( identifier[site_element] )
identifier[json] ={
literal[string] : identifier[name] ,
literal[string... | def create(self, name, site_element):
"""
Create a VPN site for an internal or external gateway
:param str name: name of site
:param list site_element: list of protected networks/hosts
:type site_element: list[str,Element]
:raises CreateElementFailed: create element failed w... |
def is_float(tg_type, inc_array=False):
"""Tells if the given tango type is float
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array: :py:ob... | def function[is_float, parameter[tg_type, inc_array]]:
constant[Tells if the given tango type is float
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
... | keyword[def] identifier[is_float] ( identifier[tg_type] , identifier[inc_array] = keyword[False] ):
literal[string]
keyword[global] identifier[_scalar_float_types] , identifier[_array_float_types]
keyword[if] identifier[tg_type] keyword[in] identifier[_scalar_float_types] :
keyword[retur... | def is_float(tg_type, inc_array=False):
"""Tells if the given tango type is float
:param tg_type: tango type
:type tg_type: :class:`tango.CmdArgType`
:param inc_array: (optional, default is False) determines if include array
in the list of checked types
:type inc_array: :py:ob... |
def additional_options(self, is_pylab=False, is_sympy=False):
"""
Additional options for shell widgets that are not defined
in JupyterWidget config options
"""
options = dict(
pylab=self.get_option('pylab'),
autoload_pylab=self.get_option('pylab/aut... | def function[additional_options, parameter[self, is_pylab, is_sympy]]:
constant[
Additional options for shell widgets that are not defined
in JupyterWidget config options
]
variable[options] assign[=] call[name[dict], parameter[]]
if compare[name[is_pylab] is constant[Tru... | keyword[def] identifier[additional_options] ( identifier[self] , identifier[is_pylab] = keyword[False] , identifier[is_sympy] = keyword[False] ):
literal[string]
identifier[options] = identifier[dict] (
identifier[pylab] = identifier[self] . identifier[get_option] ( literal[string] ),
... | def additional_options(self, is_pylab=False, is_sympy=False):
"""
Additional options for shell widgets that are not defined
in JupyterWidget config options
"""
options = dict(pylab=self.get_option('pylab'), autoload_pylab=self.get_option('pylab/autoload'), sympy=self.get_option('symbolic... |
def _resolve_path(self, create=False):
"""
Returns a tuple of a reference to the last container in the path, and
the last component in the key path.
For example, with a self._value like this:
{
'thing': {
'another': {
'some_leaf':... | def function[_resolve_path, parameter[self, create]]:
constant[
Returns a tuple of a reference to the last container in the path, and
the last component in the key path.
For example, with a self._value like this:
{
'thing': {
'another': {
... | keyword[def] identifier[_resolve_path] ( identifier[self] , identifier[create] = keyword[False] ):
literal[string]
keyword[if] identifier[type] ( identifier[self] . identifier[_path] )== identifier[str] :
identifier[key_path] = identifier[self] . identifier[_path] . identifie... | def _resolve_path(self, create=False):
"""
Returns a tuple of a reference to the last container in the path, and
the last component in the key path.
For example, with a self._value like this:
{
'thing': {
'another': {
'some_leaf': 5,
... |
def _manifest(self):
"""Return manifest content."""
if self._manifest_cache is None:
self._manifest_cache = self._storage_broker.get_manifest()
return self._manifest_cache | def function[_manifest, parameter[self]]:
constant[Return manifest content.]
if compare[name[self]._manifest_cache is constant[None]] begin[:]
name[self]._manifest_cache assign[=] call[name[self]._storage_broker.get_manifest, parameter[]]
return[name[self]._manifest_cache] | keyword[def] identifier[_manifest] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_manifest_cache] keyword[is] keyword[None] :
identifier[self] . identifier[_manifest_cache] = identifier[self] . identifier[_storage_broker] . identifier[get_manifest] ... | def _manifest(self):
"""Return manifest content."""
if self._manifest_cache is None:
self._manifest_cache = self._storage_broker.get_manifest() # depends on [control=['if'], data=[]]
return self._manifest_cache |
def validate_token(self, token, expected_data=None):
"""Validate secret link token.
:param token: Token value.
:param expected_data: A dictionary of key/values that must be present
in the data part of the token (i.e. included via ``extra_data`` in
``create_token``).
... | def function[validate_token, parameter[self, token, expected_data]]:
constant[Validate secret link token.
:param token: Token value.
:param expected_data: A dictionary of key/values that must be present
in the data part of the token (i.e. included via ``extra_data`` in
`... | keyword[def] identifier[validate_token] ( identifier[self] , identifier[token] , identifier[expected_data] = keyword[None] ):
literal[string]
keyword[try] :
identifier[data] = identifier[self] . identifier[load_token] ( identifier[token] )
keyword[if... | def validate_token(self, token, expected_data=None):
"""Validate secret link token.
:param token: Token value.
:param expected_data: A dictionary of key/values that must be present
in the data part of the token (i.e. included via ``extra_data`` in
``create_token``).
... |
def from_cryptography(cls, crypto_crl):
"""
Construct based on a ``cryptography`` *crypto_crl*.
:param crypto_crl: A ``cryptography`` certificate revocation list
:type crypto_crl: ``cryptography.x509.CertificateRevocationList``
:rtype: CRL
.. versionadded:: 17.1.0
... | def function[from_cryptography, parameter[cls, crypto_crl]]:
constant[
Construct based on a ``cryptography`` *crypto_crl*.
:param crypto_crl: A ``cryptography`` certificate revocation list
:type crypto_crl: ``cryptography.x509.CertificateRevocationList``
:rtype: CRL
..... | keyword[def] identifier[from_cryptography] ( identifier[cls] , identifier[crypto_crl] ):
literal[string]
keyword[if] keyword[not] identifier[isinstance] ( identifier[crypto_crl] , identifier[x509] . identifier[CertificateRevocationList] ):
keyword[raise] identifier[TypeError] ( lite... | def from_cryptography(cls, crypto_crl):
"""
Construct based on a ``cryptography`` *crypto_crl*.
:param crypto_crl: A ``cryptography`` certificate revocation list
:type crypto_crl: ``cryptography.x509.CertificateRevocationList``
:rtype: CRL
.. versionadded:: 17.1.0
... |
def format_field(self, value: Any, spec: str) -> str:
"""Method of string.Formatter that specifies the output of format()."""
from cirq import ops # HACK: avoids cyclic dependency.
if isinstance(value, (float, int)):
if isinstance(value, float):
value = round(value, ... | def function[format_field, parameter[self, value, spec]]:
constant[Method of string.Formatter that specifies the output of format().]
from relative_module[cirq] import module[ops]
if call[name[isinstance], parameter[name[value], tuple[[<ast.Name object at 0x7da1b1f48a30>, <ast.Name object at 0x7da1b... | keyword[def] identifier[format_field] ( identifier[self] , identifier[value] : identifier[Any] , identifier[spec] : identifier[str] )-> identifier[str] :
literal[string]
keyword[from] identifier[cirq] keyword[import] identifier[ops]
keyword[if] identifier[isinstance] ( identifier[valu... | def format_field(self, value: Any, spec: str) -> str:
"""Method of string.Formatter that specifies the output of format()."""
from cirq import ops # HACK: avoids cyclic dependency.
if isinstance(value, (float, int)):
if isinstance(value, float):
value = round(value, self.precision) # d... |
def close(self):
"""End the report."""
endpoint = self.endpoint.replace("/api/v1/spans", "")
logger.debug("Zipkin trace may be located at this URL {}/traces/{}".format(endpoint, self.trace_id)) | def function[close, parameter[self]]:
constant[End the report.]
variable[endpoint] assign[=] call[name[self].endpoint.replace, parameter[constant[/api/v1/spans], constant[]]]
call[name[logger].debug, parameter[call[constant[Zipkin trace may be located at this URL {}/traces/{}].format, parameter[... | keyword[def] identifier[close] ( identifier[self] ):
literal[string]
identifier[endpoint] = identifier[self] . identifier[endpoint] . identifier[replace] ( literal[string] , literal[string] )
identifier[logger] . identifier[debug] ( literal[string] . identifier[format] ( identifier[endpoint] , identi... | def close(self):
"""End the report."""
endpoint = self.endpoint.replace('/api/v1/spans', '')
logger.debug('Zipkin trace may be located at this URL {}/traces/{}'.format(endpoint, self.trace_id)) |
def step(h, logy=None, axes=None, **kwargs):
"""
Make a matplotlib step plot from a ROOT histogram.
Parameters
----------
h : Hist
A rootpy Hist
logy : bool, optional (default=None)
If True then clip the y range between 1E-300 and 1E300.
If None (the default) then auto... | def function[step, parameter[h, logy, axes]]:
constant[
Make a matplotlib step plot from a ROOT histogram.
Parameters
----------
h : Hist
A rootpy Hist
logy : bool, optional (default=None)
If True then clip the y range between 1E-300 and 1E300.
If None (the default... | keyword[def] identifier[step] ( identifier[h] , identifier[logy] = keyword[None] , identifier[axes] = keyword[None] ,** identifier[kwargs] ):
literal[string]
keyword[if] identifier[axes] keyword[is] keyword[None] :
identifier[axes] = identifier[plt] . identifier[gca] ()
keyword[if] identi... | def step(h, logy=None, axes=None, **kwargs):
"""
Make a matplotlib step plot from a ROOT histogram.
Parameters
----------
h : Hist
A rootpy Hist
logy : bool, optional (default=None)
If True then clip the y range between 1E-300 and 1E300.
If None (the default) then auto... |
def pgcd(numa, numb):
"""
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5... | def function[pgcd, parameter[numa, numb]]:
constant[
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>... | keyword[def] identifier[pgcd] ( identifier[numa] , identifier[numb] ):
literal[string]
identifier[int_args] =( identifier[int] ( identifier[numa] )== identifier[numa] ) keyword[and] ( identifier[int] ( identifier[numb] )== identifier[numb] )
identifier[fraction_args] = identifier[isinstance]... | def pgcd(numa, numb):
"""
Calculate the greatest common divisor (GCD) of two numbers.
:param numa: First number
:type numa: number
:param numb: Second number
:type numb: number
:rtype: number
For example:
>>> import pmisc, fractions
>>> pmisc.pgcd(10, 15)
5... |
def get_agenda_for_sentence(self, sentence: str) -> List[str]:
"""
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point... | def function[get_agenda_for_sentence, parameter[self, sentence]]:
constant[
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at t... | keyword[def] identifier[get_agenda_for_sentence] ( identifier[self] , identifier[sentence] : identifier[str] )-> identifier[List] [ identifier[str] ]:
literal[string]
identifier[agenda] =[]
identifier[sentence] = identifier[sentence] . identifier[lower] ()
keyword[if] identifier[... | def get_agenda_for_sentence(self, sentence: str) -> List[str]:
"""
Given a ``sentence``, returns a list of actions the sentence triggers as an ``agenda``. The
``agenda`` can be used while by a parser to guide the decoder. sequences as possible. This
is a simplistic mapping at this point, an... |
def create_as(access_token, subscription_id, resource_group, as_name,
update_domains, fault_domains, location):
'''Create availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azu... | def function[create_as, parameter[access_token, subscription_id, resource_group, as_name, update_domains, fault_domains, location]]:
constant[Create availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource... | keyword[def] identifier[create_as] ( identifier[access_token] , identifier[subscription_id] , identifier[resource_group] , identifier[as_name] ,
identifier[update_domains] , identifier[fault_domains] , identifier[location] ):
literal[string]
identifier[endpoint] = literal[string] . identifier[join] ([ ide... | def create_as(access_token, subscription_id, resource_group, as_name, update_domains, fault_domains, location):
"""Create availability set.
Args:
access_token (str): A valid Azure authentication token.
subscription_id (str): Azure subscription id.
resource_group (str): Azure resource gr... |
def _ic_matrix(ics, ic_i):
"""Store the previously computed pointwise predictive accuracy values (ics) in a 2D matrix."""
cols, _ = ics.shape
rows = len(ics[ic_i].iloc[0])
ic_i_val = np.zeros((rows, cols))
for idx, val in enumerate(ics.index):
ic = ics.loc[val][ic_i]
if len(ic) != ... | def function[_ic_matrix, parameter[ics, ic_i]]:
constant[Store the previously computed pointwise predictive accuracy values (ics) in a 2D matrix.]
<ast.Tuple object at 0x7da1b1c65b40> assign[=] name[ics].shape
variable[rows] assign[=] call[name[len], parameter[call[call[name[ics]][name[ic_i]].il... | keyword[def] identifier[_ic_matrix] ( identifier[ics] , identifier[ic_i] ):
literal[string]
identifier[cols] , identifier[_] = identifier[ics] . identifier[shape]
identifier[rows] = identifier[len] ( identifier[ics] [ identifier[ic_i] ]. identifier[iloc] [ literal[int] ])
identifier[ic_i_val] = ... | def _ic_matrix(ics, ic_i):
"""Store the previously computed pointwise predictive accuracy values (ics) in a 2D matrix."""
(cols, _) = ics.shape
rows = len(ics[ic_i].iloc[0])
ic_i_val = np.zeros((rows, cols))
for (idx, val) in enumerate(ics.index):
ic = ics.loc[val][ic_i]
if len(ic) !... |
def build_caching_info_message(job_spec,
job_id,
workflow_workspace,
workflow_json,
result_path):
"""Build the caching info message with correct formatting."""
caching_info_message = {
... | def function[build_caching_info_message, parameter[job_spec, job_id, workflow_workspace, workflow_json, result_path]]:
constant[Build the caching info message with correct formatting.]
variable[caching_info_message] assign[=] dictionary[[<ast.Constant object at 0x7da1b0400b20>, <ast.Constant object at 0... | keyword[def] identifier[build_caching_info_message] ( identifier[job_spec] ,
identifier[job_id] ,
identifier[workflow_workspace] ,
identifier[workflow_json] ,
identifier[result_path] ):
literal[string]
identifier[caching_info_message] ={
literal[string] : identifier[job_spec] ,
literal[string... | def build_caching_info_message(job_spec, job_id, workflow_workspace, workflow_json, result_path):
"""Build the caching info message with correct formatting."""
caching_info_message = {'job_spec': job_spec, 'job_id': job_id, 'workflow_workspace': workflow_workspace, 'workflow_json': workflow_json, 'result_path':... |
def get_subfolder_queries(store, label_store, folders, fid, sid):
'''Returns [unicode].
This returns a list of queries that can be passed on to "other"
search engines. The list of queries is derived from the subfolder
identified by ``fid/sid``.
'''
queries = []
for cid, subid, url, stype, ... | def function[get_subfolder_queries, parameter[store, label_store, folders, fid, sid]]:
constant[Returns [unicode].
This returns a list of queries that can be passed on to "other"
search engines. The list of queries is derived from the subfolder
identified by ``fid/sid``.
]
variable[quer... | keyword[def] identifier[get_subfolder_queries] ( identifier[store] , identifier[label_store] , identifier[folders] , identifier[fid] , identifier[sid] ):
literal[string]
identifier[queries] =[]
keyword[for] identifier[cid] , identifier[subid] , identifier[url] , identifier[stype] , identifier[data] ... | def get_subfolder_queries(store, label_store, folders, fid, sid):
"""Returns [unicode].
This returns a list of queries that can be passed on to "other"
search engines. The list of queries is derived from the subfolder
identified by ``fid/sid``.
"""
queries = []
for (cid, subid, url, stype, ... |
def get_project_versions(self, key, expand=None):
"""
Contains a full representation of a the specified project's versions.
:param key:
:param expand: the parameters to expand
:return:
"""
params = {}
if expand is not None:
params['expand'] = e... | def function[get_project_versions, parameter[self, key, expand]]:
constant[
Contains a full representation of a the specified project's versions.
:param key:
:param expand: the parameters to expand
:return:
]
variable[params] assign[=] dictionary[[], []]
i... | keyword[def] identifier[get_project_versions] ( identifier[self] , identifier[key] , identifier[expand] = keyword[None] ):
literal[string]
identifier[params] ={}
keyword[if] identifier[expand] keyword[is] keyword[not] keyword[None] :
identifier[params] [ literal[string] ]=... | def get_project_versions(self, key, expand=None):
"""
Contains a full representation of a the specified project's versions.
:param key:
:param expand: the parameters to expand
:return:
"""
params = {}
if expand is not None:
params['expand'] = expand # depends... |
def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... | def function[is_hitachi, parameter[dicom_input]]:
constant[
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
]
variable[header] assign[=] call[name[dicom_input]][constant[0]]
if <ast.BoolOp... | keyword[def] identifier[is_hitachi] ( identifier[dicom_input] ):
literal[string]
identifier[header] = identifier[dicom_input] [ literal[int] ]
keyword[if] literal[string] keyword[not] keyword[in] identifier[header] keyword[or] literal[string] keyword[not] keyword[in] identifier[header] ... | def is_hitachi(dicom_input):
"""
Use this function to detect if a dicom series is a hitachi dataset
:param dicom_input: directory with dicom files for 1 scan of a dicom_header
"""
# read dicom header
header = dicom_input[0]
if 'Manufacturer' not in header or 'Modality' not in header:
... |
def info(self):
"""
Print information about the annotation file.
:return:
"""
for key, value in self.dataset['info'].items():
print('{}: {}'.format(key, value)) | def function[info, parameter[self]]:
constant[
Print information about the annotation file.
:return:
]
for taget[tuple[[<ast.Name object at 0x7da1b1ef1660>, <ast.Name object at 0x7da1b1ef1930>]]] in starred[call[call[name[self].dataset][constant[info]].items, parameter[]]] begin[... | keyword[def] identifier[info] ( identifier[self] ):
literal[string]
keyword[for] identifier[key] , identifier[value] keyword[in] identifier[self] . identifier[dataset] [ literal[string] ]. identifier[items] ():
identifier[print] ( literal[string] . identifier[format] ( identifier[ke... | def info(self):
"""
Print information about the annotation file.
:return:
"""
for (key, value) in self.dataset['info'].items():
print('{}: {}'.format(key, value)) # depends on [control=['for'], data=[]] |
def reorder_keys(self, keys):
'''Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.'''
if len(keys) != len(self._set):
raise ValueError('The supplied number of keys does not match.')
if set(ke... | def function[reorder_keys, parameter[self, keys]]:
constant[Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys.]
if compare[call[name[len], parameter[name[keys]]] not_equal[!=] call[name[len], parameter[name[self]... | keyword[def] identifier[reorder_keys] ( identifier[self] , identifier[keys] ):
literal[string]
keyword[if] identifier[len] ( identifier[keys] )!= identifier[len] ( identifier[self] . identifier[_set] ):
keyword[raise] identifier[ValueError] ( literal[string] )
keyword[if] i... | def reorder_keys(self, keys):
"""Accepts a :keys: parameter, an iterable of keys in the
desired new order. The :keys: parameter must contain all
existing keys."""
if len(keys) != len(self._set):
raise ValueError('The supplied number of keys does not match.') # depends on [control=['if']... |
def present(
name,
policy_document=None,
policy_document_from_pillars=None,
path=None,
policies=None,
policies_from_pillars=None,
managed_policies=None,
create_instance_profile=True,
region=None,
key=None,
keyid=None,
profil... | def function[present, parameter[name, policy_document, policy_document_from_pillars, path, policies, policies_from_pillars, managed_policies, create_instance_profile, region, key, keyid, profile, delete_policies]]:
constant[
Ensure the IAM role exists.
name
Name of the IAM role.
policy_doc... | keyword[def] identifier[present] (
identifier[name] ,
identifier[policy_document] = keyword[None] ,
identifier[policy_document_from_pillars] = keyword[None] ,
identifier[path] = keyword[None] ,
identifier[policies] = keyword[None] ,
identifier[policies_from_pillars] = keyword[None] ,
identifier[managed_policie... | def present(name, policy_document=None, policy_document_from_pillars=None, path=None, policies=None, policies_from_pillars=None, managed_policies=None, create_instance_profile=True, region=None, key=None, keyid=None, profile=None, delete_policies=True):
"""
Ensure the IAM role exists.
name
Name of ... |
def findViewWithAttributeThatMatches(self, attr, regex, root="ROOT"):
'''
Finds the list of Views with the specified attribute matching
regex
'''
return self.__findViewWithAttributeInTreeThatMatches(attr, regex, root) | def function[findViewWithAttributeThatMatches, parameter[self, attr, regex, root]]:
constant[
Finds the list of Views with the specified attribute matching
regex
]
return[call[name[self].__findViewWithAttributeInTreeThatMatches, parameter[name[attr], name[regex], name[root]]]] | keyword[def] identifier[findViewWithAttributeThatMatches] ( identifier[self] , identifier[attr] , identifier[regex] , identifier[root] = literal[string] ):
literal[string]
keyword[return] identifier[self] . identifier[__findViewWithAttributeInTreeThatMatches] ( identifier[attr] , identifier[regex... | def findViewWithAttributeThatMatches(self, attr, regex, root='ROOT'):
"""
Finds the list of Views with the specified attribute matching
regex
"""
return self.__findViewWithAttributeInTreeThatMatches(attr, regex, root) |
def pipelines(self):
"""
Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines.
:rtype: yagocd.resources.pipeline.PipelineManager
"""
if self._pipeline_manager is None:
self._pipeline_manager = PipelineManager(session=self._sessi... | def function[pipelines, parameter[self]]:
constant[
Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines.
:rtype: yagocd.resources.pipeline.PipelineManager
]
if compare[name[self]._pipeline_manager is constant[None]] begin[:]
... | keyword[def] identifier[pipelines] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_pipeline_manager] keyword[is] keyword[None] :
identifier[self] . identifier[_pipeline_manager] = identifier[PipelineManager] ( identifier[session] = identifier[self] .... | def pipelines(self):
"""
Property for accessing :class:`PipelineManager` instance, which is used to manage pipelines.
:rtype: yagocd.resources.pipeline.PipelineManager
"""
if self._pipeline_manager is None:
self._pipeline_manager = PipelineManager(session=self._session) # depen... |
def get(which):
"DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead."
if isinstance(which, str):
pattern = ('H| %6s' % which).encode('ascii')
for star in load(lambda line: line.startswith(pattern)):
return star
else:
patterns = set(id.encode('as... | def function[get, parameter[which]]:
constant[DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead.]
if call[name[isinstance], parameter[name[which], name[str]]] begin[:]
variable[pattern] assign[=] call[binary_operation[constant[H| %6s] <ast.Mod object at 0x7da2... | keyword[def] identifier[get] ( identifier[which] ):
literal[string]
keyword[if] identifier[isinstance] ( identifier[which] , identifier[str] ):
identifier[pattern] =( literal[string] % identifier[which] ). identifier[encode] ( literal[string] )
keyword[for] identifier[star] keyword[in]... | def get(which):
"""DEPRECATED; see :func:`~skyfield.data.hipparcos.load_dataframe() instead."""
if isinstance(which, str):
pattern = ('H| %6s' % which).encode('ascii')
for star in load(lambda line: line.startswith(pattern)):
return star # depends on [control=['for'], data=['sta... |
def chooseForm_slot(self, element, element_old):
"""Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List ... | def function[chooseForm_slot, parameter[self, element, element_old]]:
constant[Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is t... | keyword[def] identifier[chooseForm_slot] ( identifier[self] , identifier[element] , identifier[element_old] ):
literal[string]
identifier[self] . identifier[current_slot] = keyword[None]
keyword[if] ( identifier[verbose] ):
identifier[print] ( identifier[self] . id... | def chooseForm_slot(self, element, element_old):
"""Calling this slot chooses the form to be shown
:param element: an object that has *_id* and *classname* attributes
:param element_old: an object that has *_id* and *classname* attributes
This slot is typically connected to List clas... |
def derivative(self, rate):
"""Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
Returns:
A unit ... | def function[derivative, parameter[self, rate]]:
constant[Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
R... | keyword[def] identifier[derivative] ( identifier[self] , identifier[rate] ):
literal[string]
identifier[rate] = identifier[self] . identifier[_validate_number_sequence] ( identifier[rate] , literal[int] )
keyword[return] literal[int] * identifier[self] * identifier[Quaternion] ( identifie... | def derivative(self, rate):
"""Get the instantaneous quaternion derivative representing a quaternion rotating at a 3D rate vector `rate`
Params:
rate: numpy 3-array (or array-like) describing rotation rates about the global x, y and z axes respectively.
Returns:
A unit quat... |
def _create_rubber_bands_action(self):
"""Create action for toggling rubber bands."""
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(
QIcon(icon),
self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
... | def function[_create_rubber_bands_action, parameter[self]]:
constant[Create action for toggling rubber bands.]
variable[icon] assign[=] call[name[resources_path], parameter[constant[img], constant[icons], constant[toggle-rubber-bands.svg]]]
name[self].action_toggle_rubberbands assign[=] call[nam... | keyword[def] identifier[_create_rubber_bands_action] ( identifier[self] ):
literal[string]
identifier[icon] = identifier[resources_path] ( literal[string] , literal[string] , literal[string] )
identifier[self] . identifier[action_toggle_rubberbands] = identifier[QAction] (
identif... | def _create_rubber_bands_action(self):
"""Create action for toggling rubber bands."""
icon = resources_path('img', 'icons', 'toggle-rubber-bands.svg')
self.action_toggle_rubberbands = QAction(QIcon(icon), self.tr('Toggle Scenario Outlines'), self.iface.mainWindow())
message = self.tr('Toggle rubber band... |
async def on_raw_313(self, message):
""" WHOIS operator info. """
target, nickname = message.params[:2]
info = {
'oper': True
}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) | <ast.AsyncFunctionDef object at 0x7da1b2347cd0> | keyword[async] keyword[def] identifier[on_raw_313] ( identifier[self] , identifier[message] ):
literal[string]
identifier[target] , identifier[nickname] = identifier[message] . identifier[params] [: literal[int] ]
identifier[info] ={
literal[string] : keyword[True]
}
... | async def on_raw_313(self, message):
""" WHOIS operator info. """
(target, nickname) = message.params[:2]
info = {'oper': True}
if nickname in self._pending['whois']:
self._whois_info[nickname].update(info) # depends on [control=['if'], data=['nickname']] |
def _reconstruct_matrix(data_list):
"""Reconstructs a matrix from a list containing sparse matrix extracted properties
`data_list` needs to be formatted as the first result of
:func:`~pypet.parameter.SparseParameter._serialize_matrix`
"""
matrix_format = data_list[0]
da... | def function[_reconstruct_matrix, parameter[data_list]]:
constant[Reconstructs a matrix from a list containing sparse matrix extracted properties
`data_list` needs to be formatted as the first result of
:func:`~pypet.parameter.SparseParameter._serialize_matrix`
]
variable[matri... | keyword[def] identifier[_reconstruct_matrix] ( identifier[data_list] ):
literal[string]
identifier[matrix_format] = identifier[data_list] [ literal[int] ]
identifier[data] = identifier[data_list] [ literal[int] ]
identifier[is_empty] = identifier[isinstance] ( identifier[data] , i... | def _reconstruct_matrix(data_list):
"""Reconstructs a matrix from a list containing sparse matrix extracted properties
`data_list` needs to be formatted as the first result of
:func:`~pypet.parameter.SparseParameter._serialize_matrix`
"""
matrix_format = data_list[0]
data = data_li... |
def createService(self, createServiceParameter,
description=None,
tags="Feature Service",
snippet=None):
"""
The Create Service operation allows users to create a hosted
feature service. You can use the API to create an empty host... | def function[createService, parameter[self, createServiceParameter, description, tags, snippet]]:
constant[
The Create Service operation allows users to create a hosted
feature service. You can use the API to create an empty hosted
feaure service from feature service metadata JSON.
... | keyword[def] identifier[createService] ( identifier[self] , identifier[createServiceParameter] ,
identifier[description] = keyword[None] ,
identifier[tags] = literal[string] ,
identifier[snippet] = keyword[None] ):
literal[string]
identifier[url] = literal[string] % identifier[self] . identifier... | def createService(self, createServiceParameter, description=None, tags='Feature Service', snippet=None):
"""
The Create Service operation allows users to create a hosted
feature service. You can use the API to create an empty hosted
feaure service from feature service metadata JSON.
... |
def from_corpus(cls, corpus):
"""
Create a new modifiable corpus from any other CorpusView.
This for example can be used to create a independent modifiable corpus from a subview.
Args:
corpus (CorpusView): The corpus to create a copy from.
Returns:
Corpu... | def function[from_corpus, parameter[cls, corpus]]:
constant[
Create a new modifiable corpus from any other CorpusView.
This for example can be used to create a independent modifiable corpus from a subview.
Args:
corpus (CorpusView): The corpus to create a copy from.
... | keyword[def] identifier[from_corpus] ( identifier[cls] , identifier[corpus] ):
literal[string]
identifier[ds] = identifier[Corpus] ()
identifier[tracks] = identifier[copy] . identifier[deepcopy] ( identifier[list] ( identifier[corpus] . identifier[tracks] . identifier[values] ()... | def from_corpus(cls, corpus):
"""
Create a new modifiable corpus from any other CorpusView.
This for example can be used to create a independent modifiable corpus from a subview.
Args:
corpus (CorpusView): The corpus to create a copy from.
Returns:
Corpus: A... |
def cli(ctx, cmd):
"""Execute commands using Apio packages."""
exit_code = util.call(cmd)
ctx.exit(exit_code) | def function[cli, parameter[ctx, cmd]]:
constant[Execute commands using Apio packages.]
variable[exit_code] assign[=] call[name[util].call, parameter[name[cmd]]]
call[name[ctx].exit, parameter[name[exit_code]]] | keyword[def] identifier[cli] ( identifier[ctx] , identifier[cmd] ):
literal[string]
identifier[exit_code] = identifier[util] . identifier[call] ( identifier[cmd] )
identifier[ctx] . identifier[exit] ( identifier[exit_code] ) | def cli(ctx, cmd):
"""Execute commands using Apio packages."""
exit_code = util.call(cmd)
ctx.exit(exit_code) |
def disconnect(self):
"""
Closes connection to Scratch
"""
try: # connection may already be disconnected, so catch exceptions
self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect
except socket.error:
pass
self.socket.close()
self.co... | def function[disconnect, parameter[self]]:
constant[
Closes connection to Scratch
]
<ast.Try object at 0x7da1b10c6350>
call[name[self].socket.close, parameter[]]
name[self].connected assign[=] constant[False] | keyword[def] identifier[disconnect] ( identifier[self] ):
literal[string]
keyword[try] :
identifier[self] . identifier[socket] . identifier[shutdown] ( identifier[socket] . identifier[SHUT_RDWR] )
keyword[except] identifier[socket] . identifier[error] :
keyword[p... | def disconnect(self):
"""
Closes connection to Scratch
"""
try: # connection may already be disconnected, so catch exceptions
self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect # depends on [control=['try'], data=[]]
except socket.error:
pass # depends on [contr... |
def _def_check(self):
"""
Checks that the definition provided contains only valid arguments for a
text index.
"""
if self._def != dict():
for key, val in iteritems_(self._def):
if key not in list(TEXT_INDEX_ARGS.keys()):
raise Cloud... | def function[_def_check, parameter[self]]:
constant[
Checks that the definition provided contains only valid arguments for a
text index.
]
if compare[name[self]._def not_equal[!=] call[name[dict], parameter[]]] begin[:]
for taget[tuple[[<ast.Name object at 0x7da20... | keyword[def] identifier[_def_check] ( identifier[self] ):
literal[string]
keyword[if] identifier[self] . identifier[_def] != identifier[dict] ():
keyword[for] identifier[key] , identifier[val] keyword[in] identifier[iteritems_] ( identifier[self] . identifier[_def] ):
... | def _def_check(self):
"""
Checks that the definition provided contains only valid arguments for a
text index.
"""
if self._def != dict():
for (key, val) in iteritems_(self._def):
if key not in list(TEXT_INDEX_ARGS.keys()):
raise CloudantArgumentError(1... |
def _parse_btrfs_info(data):
'''
Parse BTRFS device info data.
'''
ret = {}
for line in [line for line in data.split("\n") if line][:-1]:
if line.startswith("Label:"):
line = re.sub(r"Label:\s+", "", line)
label, uuid_ = [tkn.strip() for tkn in line.split("uuid:")]
... | def function[_parse_btrfs_info, parameter[data]]:
constant[
Parse BTRFS device info data.
]
variable[ret] assign[=] dictionary[[], []]
for taget[name[line]] in starred[call[<ast.ListComp object at 0x7da1b2096500>][<ast.Slice object at 0x7da1b20947f0>]] begin[:]
if call[na... | keyword[def] identifier[_parse_btrfs_info] ( identifier[data] ):
literal[string]
identifier[ret] ={}
keyword[for] identifier[line] keyword[in] [ identifier[line] keyword[for] identifier[line] keyword[in] identifier[data] . identifier[split] ( literal[string] ) keyword[if] identifier[line] ][:- ... | def _parse_btrfs_info(data):
"""
Parse BTRFS device info data.
"""
ret = {}
for line in [line for line in data.split('\n') if line][:-1]:
if line.startswith('Label:'):
line = re.sub('Label:\\s+', '', line)
(label, uuid_) = [tkn.strip() for tkn in line.split('uuid:')]
... |
def events(self, year, simple=False, keys=False):
"""
Get a list of events in a given year.
:param year: Year to get events from.
:param keys: Get only keys of the events rather than full data.
:param simple: Get only vital data.
:return: List of string event keys or Eve... | def function[events, parameter[self, year, simple, keys]]:
constant[
Get a list of events in a given year.
:param year: Year to get events from.
:param keys: Get only keys of the events rather than full data.
:param simple: Get only vital data.
:return: List of string ev... | keyword[def] identifier[events] ( identifier[self] , identifier[year] , identifier[simple] = keyword[False] , identifier[keys] = keyword[False] ):
literal[string]
keyword[if] identifier[keys] :
keyword[return] identifier[self] . identifier[_get] ( literal[string] % identifier[year] )... | def events(self, year, simple=False, keys=False):
"""
Get a list of events in a given year.
:param year: Year to get events from.
:param keys: Get only keys of the events rather than full data.
:param simple: Get only vital data.
:return: List of string event keys or Event o... |
def get_deployments(self, project, definition_id=None, definition_environment_id=None, created_by=None, min_modified_time=None, max_modified_time=None, deployment_status=None, operation_status=None, latest_attempts_only=None, query_order=None, top=None, continuation_token=None, created_for=None, min_started_time=None, ... | def function[get_deployments, parameter[self, project, definition_id, definition_environment_id, created_by, min_modified_time, max_modified_time, deployment_status, operation_status, latest_attempts_only, query_order, top, continuation_token, created_for, min_started_time, max_started_time, source_branch]]:
co... | keyword[def] identifier[get_deployments] ( identifier[self] , identifier[project] , identifier[definition_id] = keyword[None] , identifier[definition_environment_id] = keyword[None] , identifier[created_by] = keyword[None] , identifier[min_modified_time] = keyword[None] , identifier[max_modified_time] = keyword[None]... | def get_deployments(self, project, definition_id=None, definition_environment_id=None, created_by=None, min_modified_time=None, max_modified_time=None, deployment_status=None, operation_status=None, latest_attempts_only=None, query_order=None, top=None, continuation_token=None, created_for=None, min_started_time=None, ... |
def copy_files_to(src_fpath_list, dst_dpath=None, dst_fpath_list=None,
overwrite=False, verbose=True, veryverbose=False):
"""
parallel copier
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import *
>>> import utool as ut
>>> overwrite = False
... | def function[copy_files_to, parameter[src_fpath_list, dst_dpath, dst_fpath_list, overwrite, verbose, veryverbose]]:
constant[
parallel copier
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import *
>>> import utool as ut
>>> overwrite = False
>>> veryver... | keyword[def] identifier[copy_files_to] ( identifier[src_fpath_list] , identifier[dst_dpath] = keyword[None] , identifier[dst_fpath_list] = keyword[None] ,
identifier[overwrite] = keyword[False] , identifier[verbose] = keyword[True] , identifier[veryverbose] = keyword[False] ):
literal[string]
keyword[from... | def copy_files_to(src_fpath_list, dst_dpath=None, dst_fpath_list=None, overwrite=False, verbose=True, veryverbose=False):
"""
parallel copier
Example:
>>> # DISABLE_DOCTEST
>>> from utool.util_path import *
>>> import utool as ut
>>> overwrite = False
>>> veryverbose... |
def fit(self, X, C):
"""
Fit one weighted classifier per class
Parameters
----------
X : array (n_samples, n_features)
The data on which to fit a cost-sensitive classifier.
C : array (n_samples, n_classes)
The cost of predicting each label... | def function[fit, parameter[self, X, C]]:
constant[
Fit one weighted classifier per class
Parameters
----------
X : array (n_samples, n_features)
The data on which to fit a cost-sensitive classifier.
C : array (n_samples, n_classes)
The co... | keyword[def] identifier[fit] ( identifier[self] , identifier[X] , identifier[C] ):
literal[string]
identifier[X] , identifier[C] = identifier[_check_fit_input] ( identifier[X] , identifier[C] )
identifier[C] = identifier[np] . identifier[asfortranarray] ( identifier[C] )
identifie... | def fit(self, X, C):
"""
Fit one weighted classifier per class
Parameters
----------
X : array (n_samples, n_features)
The data on which to fit a cost-sensitive classifier.
C : array (n_samples, n_classes)
The cost of predicting each label for... |
def update_firmware(node):
"""Performs SUM based firmware update on the node.
This method performs SUM firmware update by mounting the
SPP ISO on the node. It performs firmware update on all or
some of the firmware components.
:param node: A node object of type dict.
:returns: Operation Status... | def function[update_firmware, parameter[node]]:
constant[Performs SUM based firmware update on the node.
This method performs SUM firmware update by mounting the
SPP ISO on the node. It performs firmware update on all or
some of the firmware components.
:param node: A node object of type dict.... | keyword[def] identifier[update_firmware] ( identifier[node] ):
literal[string]
identifier[sum_update_iso] = identifier[node] [ literal[string] ][ literal[string] ]. identifier[get] ( literal[string] )
keyword[try] :
identifier[utils] . identifier[validate_href] ( identifier[sum_update_i... | def update_firmware(node):
"""Performs SUM based firmware update on the node.
This method performs SUM firmware update by mounting the
SPP ISO on the node. It performs firmware update on all or
some of the firmware components.
:param node: A node object of type dict.
:returns: Operation Status... |
def list_(formatter, value, name, option, format):
"""Repeats the items of an array.
Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}`
Example::
>>> fruits = [u'apple', u'banana', u'coconut']
>>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits)
u'apple, bana... | def function[list_, parameter[formatter, value, name, option, format]]:
constant[Repeats the items of an array.
Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}`
Example::
>>> fruits = [u'apple', u'banana', u'coconut']
>>> smart.format(u'{fruits:list:{}|, |, and | and }', frui... | keyword[def] identifier[list_] ( identifier[formatter] , identifier[value] , identifier[name] , identifier[option] , identifier[format] ):
literal[string]
keyword[if] keyword[not] identifier[format] :
keyword[return]
keyword[if] keyword[not] identifier[hasattr] ( identifier[value] , lite... | def list_(formatter, value, name, option, format):
"""Repeats the items of an array.
Spec: `{:[l[ist]:]item|spacer[|final_spacer[|two_spacer]]}`
Example::
>>> fruits = [u'apple', u'banana', u'coconut']
>>> smart.format(u'{fruits:list:{}|, |, and | and }', fruits=fruits)
u'apple, bana... |
def sample(self, frame):
"""Samples the given frame."""
frames = self.frame_stack(frame)
if frames:
frames.pop()
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void)
stats = parent_stats.ensure_child(f... | def function[sample, parameter[self, frame]]:
constant[Samples the given frame.]
variable[frames] assign[=] call[name[self].frame_stack, parameter[name[frame]]]
if name[frames] begin[:]
call[name[frames].pop, parameter[]]
variable[parent_stats] assign[=] name[self].stats
... | keyword[def] identifier[sample] ( identifier[self] , identifier[frame] ):
literal[string]
identifier[frames] = identifier[self] . identifier[frame_stack] ( identifier[frame] )
keyword[if] identifier[frames] :
identifier[frames] . identifier[pop] ()
identifier[parent_... | def sample(self, frame):
"""Samples the given frame."""
frames = self.frame_stack(frame)
if frames:
frames.pop() # depends on [control=['if'], data=[]]
parent_stats = self.stats
for f in frames:
parent_stats = parent_stats.ensure_child(f.f_code, void) # depends on [control=['for'],... |
def render(self, name, value, attrs=None, renderer=None):
"""
Render the default widget and initialize select2.
"""
output = [super(TagAutoComplete, self).render(name, value, attrs)]
output.append('<script type="text/javascript">')
output.append('(function($) {')
... | def function[render, parameter[self, name, value, attrs, renderer]]:
constant[
Render the default widget and initialize select2.
]
variable[output] assign[=] list[[<ast.Call object at 0x7da1b1d766b0>]]
call[name[output].append, parameter[constant[<script type="text/javascript">]]... | keyword[def] identifier[render] ( identifier[self] , identifier[name] , identifier[value] , identifier[attrs] = keyword[None] , identifier[renderer] = keyword[None] ):
literal[string]
identifier[output] =[ identifier[super] ( identifier[TagAutoComplete] , identifier[self] ). identifier[render] ( id... | def render(self, name, value, attrs=None, renderer=None):
"""
Render the default widget and initialize select2.
"""
output = [super(TagAutoComplete, self).render(name, value, attrs)]
output.append('<script type="text/javascript">')
output.append('(function($) {')
output.append(' $(d... |
def get_blockdata(self, x, z):
"""
Return the decompressed binary data representing a chunk.
May raise a RegionFileFormatError().
If decompression of the data succeeds, all available data is returned,
even if it is shorter than what is specified in the header (e.g. in c... | def function[get_blockdata, parameter[self, x, z]]:
constant[
Return the decompressed binary data representing a chunk.
May raise a RegionFileFormatError().
If decompression of the data succeeds, all available data is returned,
even if it is shorter than what is specifi... | keyword[def] identifier[get_blockdata] ( identifier[self] , identifier[x] , identifier[z] ):
literal[string]
identifier[m] = identifier[self] . identifier[metadata] [ identifier[x] , identifier[z] ]
keyword[if] identifier[m] . identifier[status] == identifier[STATUS_CHUNK_NOT_CRE... | def get_blockdata(self, x, z):
"""
Return the decompressed binary data representing a chunk.
May raise a RegionFileFormatError().
If decompression of the data succeeds, all available data is returned,
even if it is shorter than what is specified in the header (e.g. in case
... |
def get_interpolated_value(self, energy, integrated=False):
"""
Returns the COHP for a particular energy.
Args:
energy: Energy to return the COHP value for.
"""
inter = {}
for spin in self.cohp:
if not integrated:
inter[spin] = get... | def function[get_interpolated_value, parameter[self, energy, integrated]]:
constant[
Returns the COHP for a particular energy.
Args:
energy: Energy to return the COHP value for.
]
variable[inter] assign[=] dictionary[[], []]
for taget[name[spin]] in starred[n... | keyword[def] identifier[get_interpolated_value] ( identifier[self] , identifier[energy] , identifier[integrated] = keyword[False] ):
literal[string]
identifier[inter] ={}
keyword[for] identifier[spin] keyword[in] identifier[self] . identifier[cohp] :
keyword[if] keyword[no... | def get_interpolated_value(self, energy, integrated=False):
"""
Returns the COHP for a particular energy.
Args:
energy: Energy to return the COHP value for.
"""
inter = {}
for spin in self.cohp:
if not integrated:
inter[spin] = get_linear_interpolated... |
def get_items_from_uuid(uuid, enrich_backend, ocean_backend):
""" Get all items that include uuid """
# logger.debug("Getting items for merged uuid %s " % (uuid))
uuid_fields = enrich_backend.get_fields_uuid()
terms = "" # all terms with uuids in the enriched item
for field in uuid_fields:
... | def function[get_items_from_uuid, parameter[uuid, enrich_backend, ocean_backend]]:
constant[ Get all items that include uuid ]
variable[uuid_fields] assign[=] call[name[enrich_backend].get_fields_uuid, parameter[]]
variable[terms] assign[=] constant[]
for taget[name[field]] in starred[na... | keyword[def] identifier[get_items_from_uuid] ( identifier[uuid] , identifier[enrich_backend] , identifier[ocean_backend] ):
literal[string]
identifier[uuid_fields] = identifier[enrich_backend] . identifier[get_fields_uuid] ()
identifier[terms] = literal[string]
keyword[for] identifier[... | def get_items_from_uuid(uuid, enrich_backend, ocean_backend):
""" Get all items that include uuid """
# logger.debug("Getting items for merged uuid %s " % (uuid))
uuid_fields = enrich_backend.get_fields_uuid()
terms = '' # all terms with uuids in the enriched item
for field in uuid_fields:
... |
def getDMCparam(fn: Path, xyPix, xyBin,
FrameIndReq=None, ut1req=None, kineticsec=None, startUTC=None, nHeadBytes=4, verbose=0):
"""
nHeadBytes=4 for 2013-2016 data
nHeadBytes=0 for 2011 data
"""
Nmetadata = nHeadBytes // 2 # FIXME for DMCdata version 1 only
if not fn.is_file()... | def function[getDMCparam, parameter[fn, xyPix, xyBin, FrameIndReq, ut1req, kineticsec, startUTC, nHeadBytes, verbose]]:
constant[
nHeadBytes=4 for 2013-2016 data
nHeadBytes=0 for 2011 data
]
variable[Nmetadata] assign[=] binary_operation[name[nHeadBytes] <ast.FloorDiv object at 0x7da2590d6bc... | keyword[def] identifier[getDMCparam] ( identifier[fn] : identifier[Path] , identifier[xyPix] , identifier[xyBin] ,
identifier[FrameIndReq] = keyword[None] , identifier[ut1req] = keyword[None] , identifier[kineticsec] = keyword[None] , identifier[startUTC] = keyword[None] , identifier[nHeadBytes] = literal[int] , ide... | def getDMCparam(fn: Path, xyPix, xyBin, FrameIndReq=None, ut1req=None, kineticsec=None, startUTC=None, nHeadBytes=4, verbose=0):
"""
nHeadBytes=4 for 2013-2016 data
nHeadBytes=0 for 2011 data
"""
Nmetadata = nHeadBytes // 2 # FIXME for DMCdata version 1 only
if not fn.is_file(): # leave this h... |
def planck(wave, temp, wavelength=True):
"""The Planck radiation or Blackbody radiation as a function of wavelength
or wavenumber. SI units.
_planck(wave, temperature, wavelength=True)
wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1)
temp = Temperature (scalar) or a... | def function[planck, parameter[wave, temp, wavelength]]:
constant[The Planck radiation or Blackbody radiation as a function of wavelength
or wavenumber. SI units.
_planck(wave, temperature, wavelength=True)
wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1)
temp =... | keyword[def] identifier[planck] ( identifier[wave] , identifier[temp] , identifier[wavelength] = keyword[True] ):
literal[string]
identifier[units] =[ literal[string] , literal[string] ]
keyword[if] identifier[wavelength] :
identifier[LOG] . identifier[debug] ( literal[string] . identifier[f... | def planck(wave, temp, wavelength=True):
"""The Planck radiation or Blackbody radiation as a function of wavelength
or wavenumber. SI units.
_planck(wave, temperature, wavelength=True)
wave = Wavelength/wavenumber or a sequence of wavelengths/wavenumbers (m or m^-1)
temp = Temperature (scalar) or a... |
def _is_readable(self, obj):
"""Check if the argument is a readable file-like object."""
try:
read = getattr(obj, 'read')
except AttributeError:
return False
else:
return is_method(read, max_arity=1) | def function[_is_readable, parameter[self, obj]]:
constant[Check if the argument is a readable file-like object.]
<ast.Try object at 0x7da1b0e63010> | keyword[def] identifier[_is_readable] ( identifier[self] , identifier[obj] ):
literal[string]
keyword[try] :
identifier[read] = identifier[getattr] ( identifier[obj] , literal[string] )
keyword[except] identifier[AttributeError] :
keyword[return] keyword[False] ... | def _is_readable(self, obj):
"""Check if the argument is a readable file-like object."""
try:
read = getattr(obj, 'read') # depends on [control=['try'], data=[]]
except AttributeError:
return False # depends on [control=['except'], data=[]]
else:
return is_method(read, max_arit... |
def init_hmm(observations, nstates, lag=1, output=None, reversible=True):
"""Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
ou... | def function[init_hmm, parameter[observations, nstates, lag, output, reversible]]:
constant[Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The numbe... | keyword[def] identifier[init_hmm] ( identifier[observations] , identifier[nstates] , identifier[lag] = literal[int] , identifier[output] = keyword[None] , identifier[reversible] = keyword[True] ):
literal[string]
keyword[if] identifier[output] keyword[is] keyword[None] :
identifier[output]... | def init_hmm(observations, nstates, lag=1, output=None, reversible=True):
"""Use a heuristic scheme to generate an initial model.
Parameters
----------
observations : list of ndarray((T_i))
list of arrays of length T_i with observation data
nstates : int
The number of states.
ou... |
def from_archive(archive_filename, py_interpreter=sys.executable):
"""extract metadata from a given sdist archive file
:param archive_filename: a sdist archive file
:param py_interpreter: The full path to the used python interpreter
:returns: a json blob with metadata
"""
with _extract_to_tempdir(... | def function[from_archive, parameter[archive_filename, py_interpreter]]:
constant[extract metadata from a given sdist archive file
:param archive_filename: a sdist archive file
:param py_interpreter: The full path to the used python interpreter
:returns: a json blob with metadata
]
with ca... | keyword[def] identifier[from_archive] ( identifier[archive_filename] , identifier[py_interpreter] = identifier[sys] . identifier[executable] ):
literal[string]
keyword[with] identifier[_extract_to_tempdir] ( identifier[archive_filename] ) keyword[as] identifier[root_dir] :
identifier[data] = ide... | def from_archive(archive_filename, py_interpreter=sys.executable):
"""extract metadata from a given sdist archive file
:param archive_filename: a sdist archive file
:param py_interpreter: The full path to the used python interpreter
:returns: a json blob with metadata
"""
with _extract_to_tempdir(... |
def update(self, is_reserved=values.unset):
"""
Update the ShortCodeInstance
:param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only
:returns: Updated ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCo... | def function[update, parameter[self, is_reserved]]:
constant[
Update the ShortCodeInstance
:param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only
:returns: Updated ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.shor... | keyword[def] identifier[update] ( identifier[self] , identifier[is_reserved] = identifier[values] . identifier[unset] ):
literal[string]
identifier[data] = identifier[values] . identifier[of] ({ literal[string] : identifier[is_reserved] ,})
identifier[payload] = identifier[self] . identif... | def update(self, is_reserved=values.unset):
"""
Update the ShortCodeInstance
:param bool is_reserved: Whether the short code should be reserved for manual assignment to participants only
:returns: Updated ShortCodeInstance
:rtype: twilio.rest.proxy.v1.service.short_code.ShortCodeIn... |
def get(self, record_id):
"""
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
"""
record_url = self.record_url(record... | def function[get, parameter[self, record_id]]:
constant[
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
]
variable[record_url] a... | keyword[def] identifier[get] ( identifier[self] , identifier[record_id] ):
literal[string]
identifier[record_url] = identifier[self] . identifier[record_url] ( identifier[record_id] )
keyword[return] identifier[self] . identifier[_get] ( identifier[record_url] ) | def get(self, record_id):
"""
Retrieves a record by its id
>>> record = airtable.get('recwPQIfs4wKPyc9D')
Args:
record_id(``str``): Airtable record id
Returns:
record (``dict``): Record
"""
record_url = self.record_url(record_id)
return self... |
def qos_map_dscp_mutation_dscp_mutation_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
qos = ET.SubElement(config, "qos", xmlns="urn:brocade.com:mgmt:brocade-qos")
map = ET.SubElement(qos, "map")
dscp_mutation = ET.SubElement(map, "dscp... | def function[qos_map_dscp_mutation_dscp_mutation_map_name, parameter[self]]:
constant[Auto Generated Code
]
variable[config] assign[=] call[name[ET].Element, parameter[constant[config]]]
variable[qos] assign[=] call[name[ET].SubElement, parameter[name[config], constant[qos]]]
var... | keyword[def] identifier[qos_map_dscp_mutation_dscp_mutation_map_name] ( identifier[self] ,** identifier[kwargs] ):
literal[string]
identifier[config] = identifier[ET] . identifier[Element] ( literal[string] )
identifier[qos] = identifier[ET] . identifier[SubElement] ( identifier[config] , ... | def qos_map_dscp_mutation_dscp_mutation_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element('config')
qos = ET.SubElement(config, 'qos', xmlns='urn:brocade.com:mgmt:brocade-qos')
map = ET.SubElement(qos, 'map')
dscp_mutation = ET.SubElement(map, 'dscp-mutation')
dscp... |
def handle(self, *arguments, **options):
"""
Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions().
"""
self.arguments = arguments
self.optio... | def function[handle, parameter[self]]:
constant[
Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions().
]
name[self].arguments assign[=] name[argumen... | keyword[def] identifier[handle] ( identifier[self] ,* identifier[arguments] ,** identifier[options] ):
literal[string]
identifier[self] . identifier[arguments] = identifier[arguments]
identifier[self] . identifier[options] = identifier[options]
identifier[self] . identifier[argu... | def handle(self, *arguments, **options):
"""
Parses arguments and options, runs validate_<action> for each action
named by self.get_actions(), then runs handle_<action> for each action
named by self.get_actions().
"""
self.arguments = arguments
self.options = options... |
def find_srvs_by_hostname(self, host_name):
"""Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
"""
if hasattr(self, 'ho... | def function[find_srvs_by_hostname, parameter[self, host_name]]:
constant[Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
]
... | keyword[def] identifier[find_srvs_by_hostname] ( identifier[self] , identifier[host_name] ):
literal[string]
keyword[if] identifier[hasattr] ( identifier[self] , literal[string] ):
identifier[host] = identifier[self] . identifier[hosts] . identifier[find_by_name] ( identifier[host_nam... | def find_srvs_by_hostname(self, host_name):
"""Get all services from a host based on a host_name
:param host_name: the host name we want services
:type host_name: str
:return: list of services
:rtype: list[alignak.objects.service.Service]
"""
if hasattr(self, 'hosts'):
... |
def diff_files(left, right, diff_options=None, formatter=None):
"""Takes two filenames or streams, and diffs the XML in those files"""
return _diff(etree.parse, left, right,
diff_options=diff_options, formatter=formatter) | def function[diff_files, parameter[left, right, diff_options, formatter]]:
constant[Takes two filenames or streams, and diffs the XML in those files]
return[call[name[_diff], parameter[name[etree].parse, name[left], name[right]]]] | keyword[def] identifier[diff_files] ( identifier[left] , identifier[right] , identifier[diff_options] = keyword[None] , identifier[formatter] = keyword[None] ):
literal[string]
keyword[return] identifier[_diff] ( identifier[etree] . identifier[parse] , identifier[left] , identifier[right] ,
identifie... | def diff_files(left, right, diff_options=None, formatter=None):
"""Takes two filenames or streams, and diffs the XML in those files"""
return _diff(etree.parse, left, right, diff_options=diff_options, formatter=formatter) |
def get_gpu_requirements(gpus_reqs):
"""
Extracts the GPU from a dictionary requirements as list of GPURequirements.
:param gpus_reqs: A dictionary {'count': <count>} or a list [{min_vram: <min_vram>}, {min_vram: <min_vram>}, ...]
:return: A list of GPURequirements
"""
requirements = []
if... | def function[get_gpu_requirements, parameter[gpus_reqs]]:
constant[
Extracts the GPU from a dictionary requirements as list of GPURequirements.
:param gpus_reqs: A dictionary {'count': <count>} or a list [{min_vram: <min_vram>}, {min_vram: <min_vram>}, ...]
:return: A list of GPURequirements
]
... | keyword[def] identifier[get_gpu_requirements] ( identifier[gpus_reqs] ):
literal[string]
identifier[requirements] =[]
keyword[if] identifier[gpus_reqs] :
keyword[if] identifier[type] ( identifier[gpus_reqs] ) keyword[is] identifier[dict] :
identifier[count] = identifier[gpus_... | def get_gpu_requirements(gpus_reqs):
"""
Extracts the GPU from a dictionary requirements as list of GPURequirements.
:param gpus_reqs: A dictionary {'count': <count>} or a list [{min_vram: <min_vram>}, {min_vram: <min_vram>}, ...]
:return: A list of GPURequirements
"""
requirements = []
if ... |
def deep_exponential_family(data_size, feature_size, units, shape):
"""A multi-layered topic model over a documents-by-terms matrix."""
w2 = ed.Gamma(0.1, 0.3, sample_shape=[units[2], units[1]], name="w2")
w1 = ed.Gamma(0.1, 0.3, sample_shape=[units[1], units[0]], name="w1")
w0 = ed.Gamma(0.1, 0.3, sample_shape... | def function[deep_exponential_family, parameter[data_size, feature_size, units, shape]]:
constant[A multi-layered topic model over a documents-by-terms matrix.]
variable[w2] assign[=] call[name[ed].Gamma, parameter[constant[0.1], constant[0.3]]]
variable[w1] assign[=] call[name[ed].Gamma, parame... | keyword[def] identifier[deep_exponential_family] ( identifier[data_size] , identifier[feature_size] , identifier[units] , identifier[shape] ):
literal[string]
identifier[w2] = identifier[ed] . identifier[Gamma] ( literal[int] , literal[int] , identifier[sample_shape] =[ identifier[units] [ literal[int] ], iden... | def deep_exponential_family(data_size, feature_size, units, shape):
"""A multi-layered topic model over a documents-by-terms matrix."""
w2 = ed.Gamma(0.1, 0.3, sample_shape=[units[2], units[1]], name='w2')
w1 = ed.Gamma(0.1, 0.3, sample_shape=[units[1], units[0]], name='w1')
w0 = ed.Gamma(0.1, 0.3, samp... |
def replace_suffixes_2(self, word):
"""
Find the longest suffix among the ones specified
and perform the required action.
"""
has_vowel = False
if word.endswith('eed'):
if len(word) >= self.r1:
word = word[:-3] + 'ee'
return word
... | def function[replace_suffixes_2, parameter[self, word]]:
constant[
Find the longest suffix among the ones specified
and perform the required action.
]
variable[has_vowel] assign[=] constant[False]
if call[name[word].endswith, parameter[constant[eed]]] begin[:]
... | keyword[def] identifier[replace_suffixes_2] ( identifier[self] , identifier[word] ):
literal[string]
identifier[has_vowel] = keyword[False]
keyword[if] identifier[word] . identifier[endswith] ( literal[string] ):
keyword[if] identifier[len] ( identifier[word] )>= identifie... | def replace_suffixes_2(self, word):
"""
Find the longest suffix among the ones specified
and perform the required action.
"""
has_vowel = False
if word.endswith('eed'):
if len(word) >= self.r1:
word = word[:-3] + 'ee' # depends on [control=['if'], data=[]]
... |
def pages_admin_menu(context, page):
"""Render the admin table of pages."""
request = context.get('request', None)
expanded = False
if request and "tree_expanded" in request.COOKIES:
cookie_string = urllib.unquote(request.COOKIES['tree_expanded'])
if cookie_string:
ids = [in... | def function[pages_admin_menu, parameter[context, page]]:
constant[Render the admin table of pages.]
variable[request] assign[=] call[name[context].get, parameter[constant[request], constant[None]]]
variable[expanded] assign[=] constant[False]
if <ast.BoolOp object at 0x7da1b26ac160> beg... | keyword[def] identifier[pages_admin_menu] ( identifier[context] , identifier[page] ):
literal[string]
identifier[request] = identifier[context] . identifier[get] ( literal[string] , keyword[None] )
identifier[expanded] = keyword[False]
keyword[if] identifier[request] keyword[and] literal[str... | def pages_admin_menu(context, page):
"""Render the admin table of pages."""
request = context.get('request', None)
expanded = False
if request and 'tree_expanded' in request.COOKIES:
cookie_string = urllib.unquote(request.COOKIES['tree_expanded'])
if cookie_string:
ids = [int... |
def decodeElem(self, bytes, index, raw=False):
"""Decodes a single element at array[index] from a sequence bytes
that contain data for the entire array.
"""
self._assertIndex(index)
start = index * self.type.nbytes
stop = start + self.type.nbytes
if stop > len(b... | def function[decodeElem, parameter[self, bytes, index, raw]]:
constant[Decodes a single element at array[index] from a sequence bytes
that contain data for the entire array.
]
call[name[self]._assertIndex, parameter[name[index]]]
variable[start] assign[=] binary_operation[name[in... | keyword[def] identifier[decodeElem] ( identifier[self] , identifier[bytes] , identifier[index] , identifier[raw] = keyword[False] ):
literal[string]
identifier[self] . identifier[_assertIndex] ( identifier[index] )
identifier[start] = identifier[index] * identifier[self] . identifier[type]... | def decodeElem(self, bytes, index, raw=False):
"""Decodes a single element at array[index] from a sequence bytes
that contain data for the entire array.
"""
self._assertIndex(index)
start = index * self.type.nbytes
stop = start + self.type.nbytes
if stop > len(bytes):
msg = '... |
def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.
"""
if not self.visible:
# Simple visibility check, has to be tested to see if it works properly
... | def function[draw, parameter[self]]:
constant[
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.
]
if <ast.UnaryOp object at 0x7da1b0240af0> begin[:]
return[None]
if <ast.Un... | keyword[def] identifier[draw] ( identifier[self] ):
literal[string]
keyword[if] keyword[not] identifier[self] . identifier[visible] :
keyword[return]
keyword[if] keyword[not] identifier[isinstance] ( identifier[self] . identifier[submenu] , identifier[Container]... | def draw(self):
"""
Draws the submenu and its background.
Note that this leaves the OpenGL state set to 2d drawing and may modify the scissor settings.
"""
if not self.visible:
# Simple visibility check, has to be tested to see if it works properly
return # depe... |
def _send_autocommit_mode(self):
"""Set whether or not to commit after every execute()"""
self._execute_command(COMMAND.COM_QUERY, "SET AUTOCOMMIT = %s" %
self.escape(self.autocommit_mode))
self._read_ok_packet() | def function[_send_autocommit_mode, parameter[self]]:
constant[Set whether or not to commit after every execute()]
call[name[self]._execute_command, parameter[name[COMMAND].COM_QUERY, binary_operation[constant[SET AUTOCOMMIT = %s] <ast.Mod object at 0x7da2590d6920> call[name[self].escape, parameter[name... | keyword[def] identifier[_send_autocommit_mode] ( identifier[self] ):
literal[string]
identifier[self] . identifier[_execute_command] ( identifier[COMMAND] . identifier[COM_QUERY] , literal[string] %
identifier[self] . identifier[escape] ( identifier[self] . identifier[autocommit_mode] ))
... | def _send_autocommit_mode(self):
"""Set whether or not to commit after every execute()"""
self._execute_command(COMMAND.COM_QUERY, 'SET AUTOCOMMIT = %s' % self.escape(self.autocommit_mode))
self._read_ok_packet() |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | def function[get_mean_and_stddevs, parameter[self, sites, rup, dists, imt, stddev_types]]:
constant[
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
]
variable[C] assign[=] call[name[self].COEFFS]... | keyword[def] identifier[get_mean_and_stddevs] ( identifier[self] , identifier[sites] , identifier[rup] , identifier[dists] , identifier[imt] , identifier[stddev_types] ):
literal[string]
identifier[C] = identifier[self] . identifier[COEFFS] [ identifier[imt] ]
identifier... | def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
# intensity m... |
def sanity_check_memory_sync(self, wire_src_dict=None):
""" Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the ind... | def function[sanity_check_memory_sync, parameter[self, wire_src_dict]]:
constant[ Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you wan... | keyword[def] identifier[sanity_check_memory_sync] ( identifier[self] , identifier[wire_src_dict] = keyword[None] ):
literal[string]
identifier[sync_mems] = identifier[set] ( identifier[m] keyword[for] identifier[m] keyword[in] identifier[self] . identifier[logic_subset] ( literal[string] ) keyw... | def sanity_check_memory_sync(self, wire_src_dict=None):
""" Check that all memories are synchronous unless explicitly specified as async.
While the semantics of 'm' memories reads is asynchronous, if you want your design
to use a block ram (on an FPGA or otherwise) you want to make sure the index i... |
def open_in_browser(doc, encoding=None):
"""
Open the HTML document in a web browser, saving it to a temporary
file to open it. Note that this does not delete the file after
use. This is mainly meant for debugging.
"""
import os
import webbrowser
import tempfile
if not isinstance(d... | def function[open_in_browser, parameter[doc, encoding]]:
constant[
Open the HTML document in a web browser, saving it to a temporary
file to open it. Note that this does not delete the file after
use. This is mainly meant for debugging.
]
import module[os]
import module[webbrowser]
... | keyword[def] identifier[open_in_browser] ( identifier[doc] , identifier[encoding] = keyword[None] ):
literal[string]
keyword[import] identifier[os]
keyword[import] identifier[webbrowser]
keyword[import] identifier[tempfile]
keyword[if] keyword[not] identifier[isinstance] ( identifier... | def open_in_browser(doc, encoding=None):
"""
Open the HTML document in a web browser, saving it to a temporary
file to open it. Note that this does not delete the file after
use. This is mainly meant for debugging.
"""
import os
import webbrowser
import tempfile
if not isinstance(d... |
def _uniform_correlation_like_matrix(num_rows, batch_shape, dtype, seed):
"""Returns a uniformly random `Tensor` of "correlation-like" matrices.
A "correlation-like" matrix is a symmetric square matrix with all entries
between -1 and 1 (inclusive) and 1s on the main diagonal. Of these,
the ones that are posit... | def function[_uniform_correlation_like_matrix, parameter[num_rows, batch_shape, dtype, seed]]:
constant[Returns a uniformly random `Tensor` of "correlation-like" matrices.
A "correlation-like" matrix is a symmetric square matrix with all entries
between -1 and 1 (inclusive) and 1s on the main diagonal. Of... | keyword[def] identifier[_uniform_correlation_like_matrix] ( identifier[num_rows] , identifier[batch_shape] , identifier[dtype] , identifier[seed] ):
literal[string]
identifier[num_entries] = identifier[num_rows] *( identifier[num_rows] + literal[int] )/ literal[int]
identifier[ones] = identifier[tf] . iden... | def _uniform_correlation_like_matrix(num_rows, batch_shape, dtype, seed):
"""Returns a uniformly random `Tensor` of "correlation-like" matrices.
A "correlation-like" matrix is a symmetric square matrix with all entries
between -1 and 1 (inclusive) and 1s on the main diagonal. Of these,
the ones that are pos... |
def handle_exceptions(*args):
"""
| Handles exceptions.
| It's possible to specify an user defined exception handler,
if not, :func:`base_exception_handler` handler will be used.
| The decorator uses given exceptions objects
or the default Python `Exception <http://docs.python.org/librar... | def function[handle_exceptions, parameter[]]:
constant[
| Handles exceptions.
| It's possible to specify an user defined exception handler,
if not, :func:`base_exception_handler` handler will be used.
| The decorator uses given exceptions objects
or the default Python `Exception <htt... | keyword[def] identifier[handle_exceptions] (* identifier[args] ):
literal[string]
identifier[exceptions] = identifier[tuple] ( identifier[filter] ( keyword[lambda] identifier[x] : identifier[issubclass] ( identifier[x] , identifier[Exception] ),
identifier[filter] ( keyword[lambda] identifier[x] : ... | def handle_exceptions(*args):
"""
| Handles exceptions.
| It's possible to specify an user defined exception handler,
if not, :func:`base_exception_handler` handler will be used.
| The decorator uses given exceptions objects
or the default Python `Exception <http://docs.python.org/librar... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.