code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def remover(self, id_model):
"""Remove Model from by the identifier.
:param id_model: Identifier of the Model. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: The identifier of Model is null and invalid.
:raise ModeloEquipamentoNaoExisteError: ... | Remove Model from by the identifier.
:param id_model: Identifier of the Model. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: The identifier of Model is null and invalid.
:raise ModeloEquipamentoNaoExisteError: Model not registered.
:raise Mod... |
def _pip_cmd(self, name=None, prefix=None):
"""Get pip location based on environment `name` or `prefix`."""
if (name and prefix) or not (name or prefix):
raise TypeError("conda pip: exactly one of 'name' ""or 'prefix' "
"required.")
if name and self.envir... | Get pip location based on environment `name` or `prefix`. |
def _get_admin_route_name(model_or_instance):
"""
Get the base name of the admin route for a model or model instance.
For use with :func:`django.urls.reverse`, although it still needs the specific route suffix
appended, for example ``_changelist``.
"""
model = model_or_instance if isinstance(mo... | Get the base name of the admin route for a model or model instance.
For use with :func:`django.urls.reverse`, although it still needs the specific route suffix
appended, for example ``_changelist``. |
def redo(self, channel, image):
"""This method is called when an image is set in a channel."""
self.logger.debug("image set")
chname = channel.name
# get old highlighted thumbs for this channel -- will be
# an empty set or one thumbkey
old_highlight = channel.extdata.thu... | This method is called when an image is set in a channel. |
def newPanelTab(self):
"""
Creates a new panel with a copy of the current widget.
"""
view = self._currentPanel.currentView()
# duplicate the current view
if view:
new_view = view.duplicate(self._currentPanel)
self._currentPanel.addTab(new... | Creates a new panel with a copy of the current widget. |
def snr_series_to_xml(snr_series, document, sngl_inspiral_id):
"""Save an SNR time series into an XML document, in a format compatible
with BAYESTAR.
"""
snr_lal = snr_series.lal()
snr_lal.name = 'snr'
snr_lal.sampleUnits = ''
snr_xml = _build_series(snr_lal, (u'Time', u'Time,Real,Imaginary'... | Save an SNR time series into an XML document, in a format compatible
with BAYESTAR. |
def create_rl_lin_comb_method(op_name, klass, x_roles, y_roles):
"""
Creates a new binary special method with left and right versions, such as
A.__mul__(B) <=> A*B,
A.__rmul__(B) <=> [B*A if B.__mul__(A) fails]
for target class. The method is called __op_name__.
"""
# This function w... | Creates a new binary special method with left and right versions, such as
A.__mul__(B) <=> A*B,
A.__rmul__(B) <=> [B*A if B.__mul__(A) fails]
for target class. The method is called __op_name__. |
def get_size(vm_):
'''
Return the VM's size. Used by create_node().
'''
sizes = avail_sizes()
vm_size = six.text_type(config.get_cloud_config_value(
'size', vm_, __opts__, search_global=False
))
for size in sizes:
if vm_size.lower() == sizes[size]['slug']:
return ... | Return the VM's size. Used by create_node(). |
def RandomNormalInitializer(stddev=1e-2):
"""An initializer function for random normal coefficients."""
def init(shape, rng):
return (stddev * backend.random.normal(rng, shape)).astype('float32')
return init | An initializer function for random normal coefficients. |
def create(self, data, **kwargs):
"""
Create classifitions for specific entity
"""
self.client.post(self.url, data=data) | Create classifitions for specific entity |
def unshare(flags):
"""
Disassociate parts of the process execution context.
:param flags int: A bitmask that specifies which parts of the execution
context should be unshared.
"""
res = lib.unshare(flags)
if res != 0:
_check_error(ffi.errno) | Disassociate parts of the process execution context.
:param flags int: A bitmask that specifies which parts of the execution
context should be unshared. |
def url_name_for_action(self, action):
"""
Returns the reverse name for this action
"""
return "%s.%s_%s" % (self.module_name.lower(), self.model_name.lower(), action) | Returns the reverse name for this action |
def finalize_processes(self):
# type: (_MultiprocessOffload) -> None
"""Finalize processes
:param _MultiprocessOffload self: this
"""
self._term_signal.value = 1
if self._check_thread is not None:
self._check_thread.join()
for proc in self._procs:
... | Finalize processes
:param _MultiprocessOffload self: this |
def copy(self, dst, **kwargs):
"""Copy file to a new destination.
Returns JSON Patch with proposed change pointing to new copy.
"""
_fs, filename = opener.parse(self.uri)
_fs_dst, filename_dst = opener.parse(dst)
copyfile(_fs, filename, _fs_dst, filename_dst, **kwargs)
... | Copy file to a new destination.
Returns JSON Patch with proposed change pointing to new copy. |
def compare_graphs(graph1, mode, graph2=None):
""" Compares graph with saved one which is loaded via networkx' gpickle
Parameters
----------
graph1 : networkx.graph
First Ding0 MV graph for comparison
graph2 : networkx.graph
Second Ding0 MV graph for comparison. If a second graph is... | Compares graph with saved one which is loaded via networkx' gpickle
Parameters
----------
graph1 : networkx.graph
First Ding0 MV graph for comparison
graph2 : networkx.graph
Second Ding0 MV graph for comparison. If a second graph is not provided
it will be laoded from disk with ... |
def _flatten(self, iterator, **filter_options):
'''
iterator here gives as lists of tuples. Method flattens the structure
to a single list of tuples.
'''
resp = list()
for entry in iterator:
for tup in entry:
if self._matches_filter(tup, **filt... | iterator here gives as lists of tuples. Method flattens the structure
to a single list of tuples. |
async def get_attached_modules(request):
"""
On success (including an empty "modules" list if no modules are detected):
// status: 200
{
"modules": [
{
/** name of module */
"name": "string",
/** model identifier (i.e. part number) */
... | On success (including an empty "modules" list if no modules are detected):
// status: 200
{
"modules": [
{
/** name of module */
"name": "string",
/** model identifier (i.e. part number) */
"model": "string",
/**... |
def handle(self, key, value):
'''
Processes a vaild action info request
@param key: The key that matched the request
@param value: The value associated with the key
'''
# the master dict to return
master = {}
master['uuid'] = value
master['total_p... | Processes a vaild action info request
@param key: The key that matched the request
@param value: The value associated with the key |
def predict(self, X=None):
"""Use a trained model to predict correlation data.
first compute the correlation of the input data,
and then normalize across all samples in the list
if there are more than one sample,
and then predict via self.clf.
If X is None, use the simil... | Use a trained model to predict correlation data.
first compute the correlation of the input data,
and then normalize across all samples in the list
if there are more than one sample,
and then predict via self.clf.
If X is None, use the similarity vectors produced in fit
... |
def mime_type(self, path):
"""Get mime-type from filename"""
name, ext = os.path.splitext(path)
return MIME_TYPES[ext] | Get mime-type from filename |
def p_type_def_empty(p):
""" typedef :
""" # Epsilon. Defaults to float
p[0] = make_type(_TYPE(gl.DEFAULT_TYPE).name, p.lexer.lineno, implicit=True) | typedef : |
def _extract_optional_list_field(blob, name):
'''Handle optional fields that can be either a string or a list of
strings.'''
value = _optional_list(typesafe_pop(blob, name, []))
if value is None:
raise ParserError(
'"{}" field must be a string or a list.'.format(name))
return val... | Handle optional fields that can be either a string or a list of
strings. |
def parse(self):
"Parses the *rpc-reply*."
if self._parsed: return
root = self._root = to_ele(self._raw) # The <rpc-reply> element
# Per RFC 4741 an <ok/> tag is sent when there are no errors or warnings
ok = root.find(qualify("ok"))
if ok is None:
# Create RP... | Parses the *rpc-reply*. |
def get_url(self):
# type: () -> STRING_TYPE
"""Sets ``self.name`` if given a **PEP-508** style URL"""
line = self.line
try:
parsed = URI.parse(line)
line = parsed.to_string(escape_password=False, direct=False, strip_ref=True)
except ValueError:
... | Sets ``self.name`` if given a **PEP-508** style URL |
def get_customizationspec_ref(si, customization_spec_name):
'''
Get a reference to a VMware customization spec for the purposes of customizing a clone
si
ServiceInstance for the vSphere or ESXi server (see get_service_instance)
customization_spec_name
Name of the customization spec
... | Get a reference to a VMware customization spec for the purposes of customizing a clone
si
ServiceInstance for the vSphere or ESXi server (see get_service_instance)
customization_spec_name
Name of the customization spec |
def apply_branchset(self, branchset_node, branchset):
"""
See superclass' method for description and signature specification.
Parses branchset node's attribute ``@applyToBranches`` to apply
following branchests to preceding branches selectively. Branching
level can have more tha... | See superclass' method for description and signature specification.
Parses branchset node's attribute ``@applyToBranches`` to apply
following branchests to preceding branches selectively. Branching
level can have more than one branchset exactly for this: different
branchsets can apply t... |
def _get_raw_data(self, name):
"""Find file holding data and return its content."""
# try legacy first, then hdf5
filestem = ''
for filestem, list_fvar in self._files.items():
if name in list_fvar:
break
fieldfile = self.step.sdat.filename(filestem, se... | Find file holding data and return its content. |
def remove_time_words(text_string):
'''
Removes any word associated to time (day, week, month, etc.) within text_string and returns the
new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed
... | Removes any word associated to time (day, week, month, etc.) within text_string and returns the
new string as type str.
Keyword argument:
- text_string: string instance
Exceptions raised:
- InputError: occurs should a non-string argument be passed |
def package_loading(self):
"""Use this around code in your package repository that is loading a
package, for example from file or cache.
"""
t1 = time.time()
yield None
t2 = time.time()
self.package_load_time += t2 - t1 | Use this around code in your package repository that is loading a
package, for example from file or cache. |
def from_json(json):
""" Creates Point instance from JSON representation
Args:
json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float),
time (string in iso format). Example,
{
"lat": 9.3470298,
... | Creates Point instance from JSON representation
Args:
json (:obj:`dict`): Must have at least the following keys: lat (float), lon (float),
time (string in iso format). Example,
{
"lat": 9.3470298,
"lon": 3.79274,
... |
def do_fullscreen(self, line):
"""
Make the current window fullscreen
"""
self.bot.canvas.sink.trigger_fullscreen_action(True)
print(self.response_prompt, file=self.stdout) | Make the current window fullscreen |
def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir):
"""Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genom... | Write torque submission files for running bidirectional blast on a server and print execution command.
Args:
reference (str): Path to "reference" genome, aka your "base strain"
other_genome (str): Path to other genome which will be BLASTed to the reference
dbtype (str): "nucl" or "prot" - w... |
def decode(mode=unicode_errors_default):
"""Configure automatic encoding/decoding of strings."""
def dec(f):
f._nvim_decode = mode
return f
return dec | Configure automatic encoding/decoding of strings. |
def in_use_connection_count(self, address):
""" Count the number of connections currently in use to a given
address.
"""
try:
connections = self.connections[address]
except KeyError:
return 0
else:
return sum(1 if connection.in_use else... | Count the number of connections currently in use to a given
address. |
def set_suspend(self, thread, stop_reason, suspend_other_threads=False, is_pause=False):
'''
:param thread:
The thread which should be suspended.
:param stop_reason:
Reason why the thread was suspended.
:param suspend_other_threads:
Whether to force ... | :param thread:
The thread which should be suspended.
:param stop_reason:
Reason why the thread was suspended.
:param suspend_other_threads:
Whether to force other threads to be suspended (i.e.: when hitting a breakpoint
with a suspend all threads policy)... |
def find_command(cmd, paths=None, pathext=None):
"""Searches the PATH for the given command and returns its path"""
if paths is None:
paths = os.environ.get('PATH', '').split(os.pathsep)
if isinstance(paths, six.string_types):
paths = [paths]
# check if there are funny path extensions fo... | Searches the PATH for the given command and returns its path |
def insert_cols(self, col, no_cols=1):
"""Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed
"""
# Mark content as changed
post_command_event(self.main_window, self.ContentChangedMsg)
tab = self.grid.current_table
self.code_ar... | Adds no_cols columns before col, appends if col > maxcols
and marks grid as changed |
def notify(self, value: Any) -> asyncio.Future:
""" Only notifies subscribers if state has changed. See also
Publisher.notify().
:param value: value to be emitted to subscribers
:returns: a future if at least one subscriber has returned a future,
elsewise None
"""
... | Only notifies subscribers if state has changed. See also
Publisher.notify().
:param value: value to be emitted to subscribers
:returns: a future if at least one subscriber has returned a future,
elsewise None |
def _put_header(self):
""" Standard first line in a PDF. """
self.session._out('%%PDF-%s' % self.pdf_version)
if self.session.compression:
self.session.buffer += '%' + chr(235) + chr(236) + chr(237) + chr(238) + "\n" | Standard first line in a PDF. |
def parseFeed(filename, yesterday):
"""Parse an RSS feed and filter only entries that are newer than yesterday."""
dom = xml.dom.minidom.parse(filename)
getText = lambda node, tag: node.getElementsByTagName(tag)[0].childNodes[0].data
getNode = lambda tag: dom.getElementsByTagName(tag)
content = ge... | Parse an RSS feed and filter only entries that are newer than yesterday. |
def build_detection_class(folder, dataset_filename,
label, sender_known=True):
"""Builds signature detection class.
Signature detection dataset includes patterns for two classes:
* class for positive patterns (goes with label 1)
* class for negative patterns (goes with label -... | Builds signature detection class.
Signature detection dataset includes patterns for two classes:
* class for positive patterns (goes with label 1)
* class for negative patterns (goes with label -1)
The patterns are build of emails from `folder` and appended to
dataset file.
>>> build_signatur... |
def factory(cls, **kwargs):
"""
Factory method that can be used to easily instantiate a class instance
:param cls: The name of the class
:param kwargs: Keyword arguments
:return: An instance of the class or None if the name doesn't match any
known class.
"""
for name, obj in inspect... | Factory method that can be used to easily instantiate a class instance
:param cls: The name of the class
:param kwargs: Keyword arguments
:return: An instance of the class or None if the name doesn't match any
known class. |
def _handle_substatements(self, stmt: Statement, sctx: SchemaContext) -> None:
"""Dispatch actions for substatements of `stmt`."""
for s in stmt.substatements:
if s.prefix:
key = (
sctx.schema_data.modules[sctx.text_mid].prefix_map[s.prefix][0]
... | Dispatch actions for substatements of `stmt`. |
def smembers(self, key, *, encoding=_NOTSET):
"""Get all the members in a set."""
return self.execute(b'SMEMBERS', key, encoding=encoding) | Get all the members in a set. |
def opener(mode='r'):
"""Factory for creating file objects
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the b... | Factory for creating file objects
Keyword Arguments:
- mode -- A string indicating how the file is to be opened. Accepts the
same values as the builtin open() function.
- bufsize -- The file's desired buffer size. Accepts the same values as
the builtin open() function. |
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""
# Init the return message
ret = []
# Only process if display plugin enable...
if not self.stats or self.is_disable():
return ret
# Build the string messa... | Return the dict to display in the curse interface. |
def _get_thumbnail_filename(filename, append_text="-thumbnail"):
"""
Returns a thumbnail version of the file name.
"""
name, ext = os.path.splitext(filename)
return ''.join([name, append_text, ext]) | Returns a thumbnail version of the file name. |
def scalar_term(self, st):
"""Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions"""
if isinstance(st, binary_type):
return _ScalarTermS(st, self._jinja_sub)
elif isinstance(st, text_type):
return _ScalarTermU(st, self._jinja_sub)
... | Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions |
def convert_rtc(cls, timestamp):
"""Convert a number of seconds since 1/1/2000 to UTC time."""
if timestamp & (1 << 31):
timestamp &= ~(1 << 31)
delta = datetime.timedelta(seconds=timestamp)
return cls._Y2KReference + delta | Convert a number of seconds since 1/1/2000 to UTC time. |
def getmtime(self, path, use_sudo=False):
"""
Return the time of last modification of path.
The return value is a number giving the number of seconds since the epoch
Same as :py:func:`os.path.getmtime()`
"""
func = use_sudo and run_as_root or self.run
with self.s... | Return the time of last modification of path.
The return value is a number giving the number of seconds since the epoch
Same as :py:func:`os.path.getmtime()` |
def add_summaries(self, step, *tags_and_values):
"""Adds summaries to the writer and prints a log statement."""
values = []
to_print = []
for tag, value in tags_and_values:
values.append(tf.Summary.Value(tag=tag, simple_value=float(value)))
to_print.append('%s=%g' % (tag, value))
if self... | Adds summaries to the writer and prints a log statement. |
def t_singlequote_end(self, t):
r"'"
t.value = t.lexer.string_value
t.type = 'ID'
t.lexer.string_value = None
t.lexer.pop_state()
return t | r" |
def ldap_server_host_use_vrf(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ldap_server = ET.SubElement(config, "ldap-server", xmlns="urn:brocade.com:mgmt:brocade-aaa")
host = ET.SubElement(ldap_server, "host")
hostname_key = ET.SubElement(host,... | Auto Generated Code |
def receive_subscription_message(self, topic_name, subscription_name,
peek_lock=True, timeout=60):
'''
Receive a message from a subscription for processing.
topic_name:
Name of the topic.
subscription_name:
Name of the subscri... | Receive a message from a subscription for processing.
topic_name:
Name of the topic.
subscription_name:
Name of the subscription.
peek_lock:
Optional. True to retrieve and lock the message. False to read and
delete the message. Default is True (lo... |
def get(self, value, default=None):
"""Return a subtree if exists."""
path = value if isinstance(value, Path) else Path(str(value))
subtree = self
for part in path.parts:
try:
subtree = subtree[part]
except KeyError:
return default
... | Return a subtree if exists. |
def Tags(self):
"""Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary.
"""
return {
TENSORS: list(self.tensors_by_tag.keys()),
# Use a heuristic: if the metagraph is available, but
# graph is not, then we assume the metagra... | Return all tags found in the value stream.
Returns:
A `{tagType: ['list', 'of', 'tags']}` dictionary. |
def _update_inernal(self, varp_list):
"""Make an update of the internal status by gathering the variational posteriors for all the individual models."""
# The probability for the binary variable for the same latent dimension of any of the models is on.
if self.group_spike:
self._b_pr... | Make an update of the internal status by gathering the variational posteriors for all the individual models. |
def write_locked(*args, **kwargs):
"""Acquires & releases a write lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock` object) in the instance ... | Acquires & releases a write lock around call into decorated method.
NOTE(harlowja): if no attribute name is provided then by default the
attribute named '_lock' is looked for (this attribute is expected to be
a :py:class:`.ReaderWriterLock` object) in the instance object this
decorator is attached to. |
def move_phasecenter(d, l1, m1, u, v):
""" Handler function for phaseshift_threaded
"""
logger.info('Rephasing data to (l, m)=(%.4f, %.4f).' % (l1, m1))
data_resamp = numpyview(data_resamp_mem, 'complex64', datashape(d))
rtlib.phaseshift_threaded(data_resamp, d, l1, m1, u, v) | Handler function for phaseshift_threaded |
def sv_variants(institute_id, case_name):
"""Display a list of structural variants."""
page = int(request.form.get('page', 1))
variant_type = request.args.get('variant_type', 'clinical')
institute_obj, case_obj = institute_and_case(store, institute_id, case_name)
form = SvFiltersForm(request.form... | Display a list of structural variants. |
def commit(self):
"""
Put the document into the new state.
"""
if self.after is None:
# If this is the first 'commit' call then do not make
# any changes but store the current document state.
self.after = self.qteWidget.toHtml()
else:
... | Put the document into the new state. |
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the CreateKeyPair response payload and decode it
into its constituent parts.
Args:
input_buffer (stream): A data buffer containing encoded object
data, supportin... | Read the data encoding the CreateKeyPair response payload and decode it
into its constituent parts.
Args:
input_buffer (stream): A data buffer containing encoded object
data, supporting a read method.
kmip_version (KMIPVersion): An enumeration defining the KMIP
... |
def quoted(parser=any_token):
"""Parses as much as possible until it encounters a matching closing quote.
By default matches any_token, but can be provided with a more specific parser if required.
Returns a string
"""
quote_char = quote()
value, _ = many_until(parser, partial(one_of, quote_... | Parses as much as possible until it encounters a matching closing quote.
By default matches any_token, but can be provided with a more specific parser if required.
Returns a string |
def write_inp(mesh, path = None, maxwidth = 40, sections = "solid"):
"""
Exports the mesh to the INP format.
"""
def set_to_inp(sets, keyword):
ss = ""
for sk in sets.keys():
labels = sets[sk].loc[sets[sk]].index.values
labels = list(labels)
labels.sort()
if len(labels)!= 0:
... | Exports the mesh to the INP format. |
def get_snmp_information(self):
"""get_snmp_information() for EOS. Re-written to not use TextFSM"""
# Default values
snmp_dict = {
'chassis_id': '',
'location': '',
'contact': '',
'community': {}
}
commands = [
'show ... | get_snmp_information() for EOS. Re-written to not use TextFSM |
def plot(self, f, lfilter=None, plot_xy=False, **kargs):
"""Applies a function to each packet to get a value that will be plotted
with matplotlib. A list of matplotlib.lines.Line2D is returned.
lfilter: a truth function that decides whether a packet must be plotted
"""
# Python... | Applies a function to each packet to get a value that will be plotted
with matplotlib. A list of matplotlib.lines.Line2D is returned.
lfilter: a truth function that decides whether a packet must be plotted |
def has_mail_attachment(self, name, mail_folder='INBOX', check_regex=False):
"""
Checks the mail folder for mails containing attachments with the given name.
:param name: The name of the attachment that will be searched for.
:type name: str
:param mail_folder: The mail folder wh... | Checks the mail folder for mails containing attachments with the given name.
:param name: The name of the attachment that will be searched for.
:type name: str
:param mail_folder: The mail folder where to look at.
:type mail_folder: str
:param check_regex: Checks the name for a ... |
def process_files(self, path, recursive=False):
"""Apply normalizations over all files in the given directory.
Iterate over all files in a given directory. Normalizations
will be applied to each file, storing the result in a new file.
The extension for the new file will be the one defin... | Apply normalizations over all files in the given directory.
Iterate over all files in a given directory. Normalizations
will be applied to each file, storing the result in a new file.
The extension for the new file will be the one defined in
BATCH_EXTENSION.
Args:
p... |
def GRUCell(units):
"""Builds a traditional GRU cell with dense internal transformations.
Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555
Args:
units: Number of hidden units.
Returns:
A Stax model representing a traditional GRU RNN cell.
"""
return GeneralGRUCell(
candidate_tra... | Builds a traditional GRU cell with dense internal transformations.
Gated Recurrent Unit paper: https://arxiv.org/abs/1412.3555
Args:
units: Number of hidden units.
Returns:
A Stax model representing a traditional GRU RNN cell. |
def _TransmitBreakpointUpdates(self, service):
"""Tries to send pending breakpoint updates to the backend.
Sends all the pending breakpoint updates. In case of transient failures,
the breakpoint is inserted back to the top of the queue. Application
failures are not retried (for example updating breakpo... | Tries to send pending breakpoint updates to the backend.
Sends all the pending breakpoint updates. In case of transient failures,
the breakpoint is inserted back to the top of the queue. Application
failures are not retried (for example updating breakpoint in a final
state).
Each pending breakpoin... |
def _all_create_or_get_groups(self, key, start_hdf5_group=None):
"""Creates new or follows existing group nodes along a given colon separated `key`.
:param key:
Colon separated path along hdf5 file, e.g. `parameters.mobiles.cars`.
:param start_hdf5_group:
HDF5 group f... | Creates new or follows existing group nodes along a given colon separated `key`.
:param key:
Colon separated path along hdf5 file, e.g. `parameters.mobiles.cars`.
:param start_hdf5_group:
HDF5 group from where to start, leave `None` for the trajectory group.
:return:... |
def init(self): # pylint: disable=too-many-branches
"""Called by the daemon broker to initialize the module"""
if not self.enabled:
logger.info(" the module is disabled.")
return True
try:
connections = self.test_connection()
except Exception as exp:... | Called by the daemon broker to initialize the module |
def dispatch_message(self, message_type, client_id, client_storage, args, kwargs):
"""
Calls callback functions
"""
logger.debug("Backend message ({message_type}) : {args} {kwargs}".format(
message_type=dict(MESSAGES_TYPES)[message_type], args=args, kwargs=kwargs))
i... | Calls callback functions |
def main(*args, **kwargs):
""" Simple entry-point that takes the package name and json output"""
parser = argparse.ArgumentParser()
parser.add_argument('package_name', type=str)
parser.add_argument('output_filename', type=str)
parsed_args = parser.parse_args()
# Find all package requirements
... | Simple entry-point that takes the package name and json output |
def add_experiment_choice(experiment, choice):
"""Adds an experiment choice"""
redis = oz.redis.create_connection()
oz.bandit.Experiment(redis, experiment).add_choice(choice) | Adds an experiment choice |
def reconnect(self):
"""Closes the existing database connection and re-opens it."""
conn = _mysql.connect(**self._db_args)
if conn is not None:
self.close()
self._db = conn | Closes the existing database connection and re-opens it. |
def call(method, path, ret_type,
ret_is_list=False, data=None, params=None, api_version=1):
"""
Generic function for calling a resource method and automatically dealing with
serialization of parameters and deserialization of return values.
@param method: method to call (must be bound to a resource;
... | Generic function for calling a resource method and automatically dealing with
serialization of parameters and deserialization of return values.
@param method: method to call (must be bound to a resource;
e.g., "resource_root.get").
@param path: the full path of the API method to call.
@param r... |
def random_codons(peptide, frequency_cutoff=0.0, weighted=False, table=None):
'''Generate randomized codons given a peptide sequence.
:param peptide: Peptide sequence for which to generate randomized
codons.
:type peptide: coral.Peptide
:param frequency_cutoff: Relative codon usage ... | Generate randomized codons given a peptide sequence.
:param peptide: Peptide sequence for which to generate randomized
codons.
:type peptide: coral.Peptide
:param frequency_cutoff: Relative codon usage cutoff - codons that
are rarer will not be used. Frequen... |
def wrap_deepmind_retro(env, scale=True, frame_stack=4):
"""
Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind
"""
env = WarpFrame(env)
env = ClipRewardEnv(env)
if frame_stack > 1:
env = FrameStack(env, frame_stack)
if scale:
... | Configure environment for retro games, using config similar to DeepMind-style Atari in wrap_deepmind |
def build_unit_name(dimensions):
"""Build the name of the unit from its dimensions."""
name = ''
for unit in dimensions:
if unit['power'] < 0:
name += 'per '
power = abs(unit['power'])
if power == 1:
name += unit['base']
elif power == 2:
n... | Build the name of the unit from its dimensions. |
def parameter(self):
"""Return the current best value of a parameter"""
D = {}
for source in PARAM_SOURCE_ORDER:
D.update(self.params[source])
return D | Return the current best value of a parameter |
def pos_tokenize(self: object, fileids: str):
"""
Segments, tokenizes, and POS tag a document in the corpus.
"""
for para in self.paras(fileids):
yield [
self.pos_tagger(word_tokenize(sent))
for sent in sent_tokenize(para)
] | Segments, tokenizes, and POS tag a document in the corpus. |
def mk_dict(results,description):
"""Given a result list and descrition sequence, return a list
of dictionaries"""
rows=[]
for row in results:
row_dict={}
for idx in range(len(row)):
col=description[idx][0]
row_dict[col]=row[idx]
rows.append(row_dict)... | Given a result list and descrition sequence, return a list
of dictionaries |
def prepend_dataset_with_weather(samples, location='Fresno, CA', weather_columns=None, use_cache=True, verbosity=0):
""" Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors
samples[0..N]['target'] should have an index with the date timestamp
If you use_cache for the... | Prepend weather the values specified (e.g. Max TempF) to the samples[0..N]['input'] vectors
samples[0..N]['target'] should have an index with the date timestamp
If you use_cache for the curent year, you may not get the most recent data.
Arguments:
samples (list of dict): {'input': np.array(), 'ta... |
def sfs(dac, n=None):
"""Compute the site frequency spectrum given derived allele counts at
a set of biallelic variants.
Parameters
----------
dac : array_like, int, shape (n_variants,)
Array of derived allele counts.
n : int, optional
The total number of chromosomes called.
... | Compute the site frequency spectrum given derived allele counts at
a set of biallelic variants.
Parameters
----------
dac : array_like, int, shape (n_variants,)
Array of derived allele counts.
n : int, optional
The total number of chromosomes called.
Returns
-------
sfs... |
def explore_show_head(self, uri, check_headers=None):
"""Do HEAD on uri and show infomation.
Will also check headers against any values specified in
check_headers.
"""
print("HEAD %s" % (uri))
if (re.match(r'^\w+:', uri)):
# Looks like a URI
respo... | Do HEAD on uri and show infomation.
Will also check headers against any values specified in
check_headers. |
def shrink(self, src, width=0, max_value=0, filter_method=None,
path=None, flags=0):
"""Shrink sketch
Params:
<Sketch> src_sketch
<int> width
<int> max_value
<lambda> | <function> filter
<str> path
<int> flags
... | Shrink sketch
Params:
<Sketch> src_sketch
<int> width
<int> max_value
<lambda> | <function> filter
<str> path
<int> flags |
def line_received(self, line):
"""
Gets called by data_received() when a complete line is
received.
Inspect the received line and process or queue accordingly.
"""
self._received_lines += 1
self.loop.create_task(self._inform_watchdog())
pattern = r'^(T|B|R... | Gets called by data_received() when a complete line is
received.
Inspect the received line and process or queue accordingly. |
def _get_po_paths(locales=[]):
"""Returns paths to all relevant po files in the current project."""
basedirs = [os.path.join('conf', 'locale'), 'locale']
if os.environ.get('DJANGO_SETTINGS_MODULE'):
from django.conf import settings
basedirs.extend(settings.LOCALE_PATHS)
# Gather existin... | Returns paths to all relevant po files in the current project. |
def to_java_rdd(jsc, features, labels, batch_size):
"""Convert numpy features and labels into a JavaRDD of
DL4J DataSet type.
:param jsc: JavaSparkContext from pyjnius
:param features: numpy array with features
:param labels: numpy array with labels:
:return: JavaRDD<DataSet>
"""
data_s... | Convert numpy features and labels into a JavaRDD of
DL4J DataSet type.
:param jsc: JavaSparkContext from pyjnius
:param features: numpy array with features
:param labels: numpy array with labels:
:return: JavaRDD<DataSet> |
def controls(self, move):
'''Returns a set of attacked/defended squares'''
to_move = self.board.turn
analysis_board = chess.Board(self.board.fen())
analysis_board.push(move)
squares = 0
for square in chess.SQUARES:
if move.to_square in analysis_board.attackers(to_move, square):
squ... | Returns a set of attacked/defended squares |
def next(self):
"""Next point in iteration
"""
while True:
x, y = next(self.scan)
if self.predicate is not None and not self.predicate(x,y):
if self.abort: raise StopIteration("Boundary crossed!")
elif (x < self.minx or
x > self... | Next point in iteration |
def iterations(self, parameter):
"""Returns the iteration each sample occurred at."""
return numpy.arange(0, self.last_iteration(parameter), self.thinned_by) | Returns the iteration each sample occurred at. |
def _apply_concretization_strategies(self, idx, strategies, action): # pylint: disable=unused-argument
"""
Applies concretization strategies on the index, until one of them succeeds.
"""
for s in strategies:
try:
idxes = s.concretize(self, idx)
ex... | Applies concretization strategies on the index, until one of them succeeds. |
def _offset_dt(cls, dt, offset_str):
"""
Return a |datetime| instance that is offset from datetime *dt* by
the timezone offset specified in *offset_str*, a string like
``'-07:00'``.
"""
match = cls._offset_pattern.match(offset_str)
if match is None:
ra... | Return a |datetime| instance that is offset from datetime *dt* by
the timezone offset specified in *offset_str*, a string like
``'-07:00'``. |
def parse_disruptions(self, xml):
"""
Parse the NS API xml result into Disruption objects
@param xml: raw XML result from the NS API
"""
obj = xmltodict.parse(xml)
disruptions = {}
disruptions['unplanned'] = []
disruptions['planned'] = []
if obj['... | Parse the NS API xml result into Disruption objects
@param xml: raw XML result from the NS API |
def difference_update(self, *sets):
"""
Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>... | Update this OrderedSet to remove items from one or more other sets.
Example:
>>> this = OrderedSet([1, 2, 3])
>>> this.difference_update(OrderedSet([2, 4]))
>>> print(this)
OrderedSet([1, 3])
>>> this = OrderedSet([1, 2, 3, 4, 5])
>>> thi... |
def _readline(self, prompt='', callback=None):
""" Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If... | Reads one line of input from the user.
Parameters
----------
prompt : str, optional
The prompt to print before reading the line.
callback : callable, optional
A callback to execute with the read line. If not specified, input is
read *synchronously* a... |
def link_user_account(self, user_id, body):
"""Link user accounts.
Links the account specified in the body (secondary account) to the
account specified by the id param of the URL (primary account).
Args:
id (str): The user_id of the primary identity where you are linking
... | Link user accounts.
Links the account specified in the body (secondary account) to the
account specified by the id param of the URL (primary account).
Args:
id (str): The user_id of the primary identity where you are linking
the secondary account to.
bo... |
def createsuperusers():
"""
Creates all superusers defined in settings.INITIAL_SUPERUSERS.
These superusers do not have any circles. They are plain superusers.
However you may want to signup yourself and make this new user a super user then.
"""
from django.contrib.auth import models as auth_mod... | Creates all superusers defined in settings.INITIAL_SUPERUSERS.
These superusers do not have any circles. They are plain superusers.
However you may want to signup yourself and make this new user a super user then. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.