code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def container_start(name, remote_addr=None,
cert=None, key=None, verify_cert=True):
'''
Start a container
name :
Name of the container to start
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a T... | Start a container
name :
Name of the container to start
remote_addr :
An URL to a remote Server, you also have to give cert and key if
you provide remote_addr and its a TCP Address!
Examples:
https://myserver.lan:8443
/var/lib/mysocket.sock
cert :
... |
def get_command(self, version=2):
"""Return the SSH protocol specific command to connect."""
try:
options = _C['options']
options_str = " -o ".join(options)
if options_str:
options_str = "-o " + options_str + " "
except KeyError:
op... | Return the SSH protocol specific command to connect. |
def get_many(self, content_ids, feature_names=None):
'''Returns an iterable of feature collections.
This efficiently retrieves multiple FCs corresponding to the
list of ids given. Tuples of identifier and feature collection
are yielded. If the feature collection for a given id does not
... | Returns an iterable of feature collections.
This efficiently retrieves multiple FCs corresponding to the
list of ids given. Tuples of identifier and feature collection
are yielded. If the feature collection for a given id does not
exist, then ``None`` is returned as the second element o... |
def reStructuredText_to_html(input, output, css_file):
"""
Outputs a reStructuredText file to html.
:param input: Input reStructuredText file to convert.
:type input: unicode
:param output: Output html file.
:type output: unicode
:param css_file: Css file.
:type css_file: unicode
:r... | Outputs a reStructuredText file to html.
:param input: Input reStructuredText file to convert.
:type input: unicode
:param output: Output html file.
:type output: unicode
:param css_file: Css file.
:type css_file: unicode
:return: Definition success.
:rtype: bool |
def _forward(X, s=1.1, gamma=1., k=5):
"""
Forward dynamic algorithm for burstness automaton HMM, from `Kleinberg
(2002) <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_.
Parameters
----------
X : list
A series of time-gaps between events.
s : float
(default: 1.1) Scaling... | Forward dynamic algorithm for burstness automaton HMM, from `Kleinberg
(2002) <http://www.cs.cornell.edu/home/kleinber/bhs.pdf>`_.
Parameters
----------
X : list
A series of time-gaps between events.
s : float
(default: 1.1) Scaling parameter ( > 1.)that controls graininess of
... |
def seq_dup_levels_plot (self):
""" Create the HTML for the Sequence Duplication Levels plot """
data = dict()
max_dupval = 0
for s_name in self.fastqc_data:
try:
thisdata = {}
for d in self.fastqc_data[s_name]['sequence_duplication_levels']:
... | Create the HTML for the Sequence Duplication Levels plot |
def make_file_path(project_dir, project_name, root, name):
"""
Generates the target path for a file
"""
return path.join(make_dir_path(project_dir, root, project_name), name) | Generates the target path for a file |
def make_mutant_tuples(example_protos, original_feature, index_to_mutate,
viz_params):
"""Return a list of `MutantFeatureValue`s and a list of mutant Examples.
Args:
example_protos: The examples to mutate.
original_feature: A `OriginalFeatureList` that encapsulates the feature to
... | Return a list of `MutantFeatureValue`s and a list of mutant Examples.
Args:
example_protos: The examples to mutate.
original_feature: A `OriginalFeatureList` that encapsulates the feature to
mutate.
index_to_mutate: The index of the int64_list or float_list to mutate.
viz_params: A `VizParams` ... |
def setup(self, services):
"""Service setup."""
super(SchedulerService, self).setup(services)
# Register filesystem event handlers on an FSEventService instance.
self._fs_event_service.register_all_files_handler(self._enqueue_fs_event)
# N.B. We compute the invalidating fileset eagerly at launch wi... | Service setup. |
def imagetransformer_base_8l_8h_big_cond_dr03_dan():
"""big 1d model for conditional image generation.2.99 on cifar10."""
hparams = imagetransformer_sep_channels_8l()
hparams.block_width = 256
hparams.block_length = 256
hparams.hidden_size = 512
hparams.num_heads = 8
hparams.filter_size = 2048
hparams.b... | big 1d model for conditional image generation.2.99 on cifar10. |
def make_processitem_arguments(arguments, condition='contains', negate=False, preserve_case=False):
"""
Create a node for ProcessItem/arguments
:return: A IndicatorItem represented as an Element node
"""
document = 'ProcessItem'
search = 'ProcessItem/arguments'
content_type = 'string'
... | Create a node for ProcessItem/arguments
:return: A IndicatorItem represented as an Element node |
def normalize_url(url):
"""
Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL.
"""
uri = urlparse(url)
query = uri.query or ""
pairs = parse_qsl(query)
decoded_pairs = [(unquote(key)... | Returns the given URL with all query keys properly escaped.
Args:
url (str): The URL to normalize.
Returns:
str: The normalized URL. |
def get_interfaces(self):
"""
Return a list of sham.network.interfaces.NetworkInterface
describing all the interfaces this VM has
"""
interfaces = self.xml.find('devices').iter('interface')
iobjs = []
for interface in interfaces:
_type = interface.attr... | Return a list of sham.network.interfaces.NetworkInterface
describing all the interfaces this VM has |
def get_checksum(self, encoder=base64.b64encode, hasher=hashlib.sha256):
"""Return the b64 encoded sha256 checksum of the archive."""
assert self._closed, "Archive not closed"
with open(self._temp_archive_file.name, 'rb') as fh:
return encoder(checksum(fh, hasher())).decode('ascii') | Return the b64 encoded sha256 checksum of the archive. |
def render(self, template_name, __data=None, **kw):
'''Given a template name and template data.
Renders a template and returns as string'''
return self.template.render(template_name,
**self._vars(__data, **kw)) | Given a template name and template data.
Renders a template and returns as string |
def _group_by_sample_and_batch(samples):
"""Group samples split by QC method back one per sample-batch.
"""
out = collections.defaultdict(list)
for data in samples:
out[(dd.get_sample_name(data), dd.get_align_bam(data), tuple(_get_batches(data)))].append(data)
return [xs[0] for xs in out.val... | Group samples split by QC method back one per sample-batch. |
def add_file(self, **args):
'''
Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for anything.
:pa... | Adds a file's information to the set of files to be
published in this dataset.
:param file_name: Mandatory. The file name (string).
This information will simply be included in the
PID record, but not used for anything.
:param file_handle: Mandatory. The handle (PID) of
... |
def createAllShaders(self):
"Purpose: Creates all the shaders used by HelloVR SDL"
self.m_unSceneProgramID = self.compileGLShader(
"Scene",
# Vertex Shader
dedent("""\
#version 410
uniform mat4 matrix;
layout(location = 0) ... | Purpose: Creates all the shaders used by HelloVR SDL |
def collect(self):
"""
Create some concurrent workers that process the tasks simultaneously.
"""
collected = super(Command, self).collect()
if self.faster:
self.worker_spawn_method()
self.post_processor()
return collected | Create some concurrent workers that process the tasks simultaneously. |
def generate_hash(filepath):
"""Public function that reads a local file and generates a SHA256 hash digest for it"""
fr = FileReader(filepath)
data = fr.read_bin()
return _calculate_sha256(data) | Public function that reads a local file and generates a SHA256 hash digest for it |
def get_portchannel_info_by_intf_output_lacp_receive_machine_state(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_portchannel_info_by_intf = ET.Element("get_portchannel_info_by_intf")
config = get_portchannel_info_by_intf
output = ET.SubElem... | Auto Generated Code |
def setStyles(self, styleUpdatesDict):
'''
setStyles - Sets one or more style params.
This all happens in one shot, so it is much much faster than calling setStyle for every value.
To remove a style, set its value to empty string.
When all styles are... | setStyles - Sets one or more style params.
This all happens in one shot, so it is much much faster than calling setStyle for every value.
To remove a style, set its value to empty string.
When all styles are removed, the "style" attribute will be nullified.
... |
def calculate(self, batch_info):
""" Calculate value of a metric """
value = self._value_function(batch_info)
self.buffer += value | Calculate value of a metric |
def get_event(self, *etypes, timeout=None):
"""
Return a single event object or block until an event is
received and return it.
- etypes(str): If defined, Slack event type(s) not matching
the filter will be ignored. See https://api.slack.com/events for
a listing of... | Return a single event object or block until an event is
received and return it.
- etypes(str): If defined, Slack event type(s) not matching
the filter will be ignored. See https://api.slack.com/events for
a listing of valid event types.
- timeout(int): Max time, in second... |
def qteKillMiniApplet(self):
"""
Remove the mini applet.
If a different applet is to be restored/focused then call
``qteMakeAppletActive`` for that applet *after* calling this
method.
|Args|
* **None**
|Returns|
* **None**
|Raises|
... | Remove the mini applet.
If a different applet is to be restored/focused then call
``qteMakeAppletActive`` for that applet *after* calling this
method.
|Args|
* **None**
|Returns|
* **None**
|Raises|
* **None** |
def cdf_single(z, N, normalization, dH=1, dK=3):
"""Cumulative distribution for the Lomb-Scargle periodogram
Compute the expected cumulative distribution of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the period... | Cumulative distribution for the Lomb-Scargle periodogram
Compute the expected cumulative distribution of the periodogram
for the null hypothesis - i.e. data consisting of Gaussian noise.
Parameters
----------
z : array-like
the periodogram value
N : int
the number of data point... |
def update(self, resource, id_, updates):
"""Update document in index."""
args = self._es_args(resource, refresh=True)
if self._get_retry_on_conflict():
args['retry_on_conflict'] = self._get_retry_on_conflict()
updates.pop('_id', None)
updates.pop('_type', None)
... | Update document in index. |
def waitForVMState(rh, userid, desiredState, maxQueries=90, sleepSecs=5):
"""
Wait for the virtual machine to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'on' or 'off', case sensitive
Maximum attempts to wait for desire... | Wait for the virtual machine to go into the indicated state.
Input:
Request Handle
userid whose state is to be monitored
Desired state, 'on' or 'off', case sensitive
Maximum attempts to wait for desired state before giving up
Sleep duration between waits
Output:
Dicti... |
def loads(self, string):
"Decompress the passed-in compact script and return the result."
script_class = self.get_script_class()
script = self._load(BytesIO(string), self._protocol, self._version)
return script_class(script) | Decompress the passed-in compact script and return the result. |
def ProgChunks(list_, chunksize, nInput=None, **kwargs):
"""
Yeilds an iterator in chunks and computes progress
Progress version of ut.ichunks
Args:
list_ (list):
chunksize (?):
nInput (None): (default = None)
Kwargs:
length, freq
Returns:
ProgressIter:... | Yeilds an iterator in chunks and computes progress
Progress version of ut.ichunks
Args:
list_ (list):
chunksize (?):
nInput (None): (default = None)
Kwargs:
length, freq
Returns:
ProgressIter: progiter_
CommandLine:
python -m utool.util_progress Pr... |
def conv2d_fixed_padding(inputs, filters, kernel_size, strides, data_format):
"""Strided 2-D convolution with explicit padding."""
# The padding is consistent and is based only on `kernel_size`, not on the
# dimensions of `inputs` (as opposed to using `tf.layers.conv2d` alone).
inputs_for_logging = inputs
if... | Strided 2-D convolution with explicit padding. |
def read_file(self, filename):
"""
Guess the filetype and read the file into row sets
"""
#print("Reading file", filename)
try:
fh = open(filename, 'rb')
table_set = any_tableset(fh) # guess the type...
except:
#traceback.print_exc()
... | Guess the filetype and read the file into row sets |
def shell(command, **kwargs):
"""
Runs 'command' on the underlying shell and keeps the stdout and
stderr stream separate.
Returns [stdout, stderr, exitCode]
"""
b_stdoutflush = False
b_stderrflush = False
b_waitForChild = True
for key, val in kwargs.item... | Runs 'command' on the underlying shell and keeps the stdout and
stderr stream separate.
Returns [stdout, stderr, exitCode] |
def set_sgr_code(self, params):
""" Set attributes based on SGR (Select Graphic Rendition) codes.
Parameters
----------
params : sequence of ints
A list of SGR codes for one or more SGR commands. Usually this
sequence will have one element per command, although c... | Set attributes based on SGR (Select Graphic Rendition) codes.
Parameters
----------
params : sequence of ints
A list of SGR codes for one or more SGR commands. Usually this
sequence will have one element per command, although certain
xterm-specific commands r... |
def Negative(other_param, mode="invert", reroll_count_max=2):
"""
Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'rer... | Converts another parameter's results to negative values.
Parameters
----------
other_param : imgaug.parameters.StochasticParameter
Other parameter which's sampled values are to be
modified.
mode : {'invert', 'reroll'}, optional
How to change the signs. Valid values are ``invert... |
def _send_command(self, command):
""" Send a command to the Chromecast on media channel. """
if self.status is None or self.status.media_session_id is None:
self.logger.warning(
"%s command requested but no session is active.",
command[MESSAGE_TYPE])
... | Send a command to the Chromecast on media channel. |
def make_importfrom_alias(queue, body, context, name):
"""
Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of t... | Make an ast.alias node for the names list of an ast.ImportFrom.
Parameters
----------
queue : deque
Instruction Queue
body : list
Current body.
context : DecompilationContext
name : str
Expected name of the IMPORT_FROM node to be popped.
Returns
-------
alia... |
def cal(self, opttype, strike, exp1, exp2):
"""
Metrics for evaluating a calendar spread.
Parameters
------------
opttype : str ('call' or 'put')
Type of option on which to collect data.
strike : numeric
Strike price.
exp1 : date or date s... | Metrics for evaluating a calendar spread.
Parameters
------------
opttype : str ('call' or 'put')
Type of option on which to collect data.
strike : numeric
Strike price.
exp1 : date or date str (e.g. '2015-01-01')
Earlier expiration date.
... |
def embedding_lookup(self, x, means):
"""Compute nearest neighbors and loss for training the embeddings.
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape
[-1, num_blocks, block_dim].
means: Embedding means.
Returns:
The nearest neighbor... | Compute nearest neighbors and loss for training the embeddings.
Args:
x: Batch of encoder continuous latent states sliced/projected into
shape
[-1, num_blocks, block_dim].
means: Embedding means.
Returns:
The nearest neighbor in one hot form, the nearest neighbor
... |
def parse(url_or_path, encoding=None, handler_class=DrillHandler):
"""
:param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML
:rtype: :class:`XmlElement`
"""
handler = handler_class()
parser = expat.ParserCreate(encoding)
parser.buffer_text = 1
parse... | :param url_or_path: A file-like object, a filesystem path, a URL, or a string containing XML
:rtype: :class:`XmlElement` |
def increment(self, counter_name, delta):
"""Increment counter value.
Args:
counter_name: counter name as String.
delta: increment delta as Integer.
Returns:
new counter value.
"""
current_value = self.counters.get(counter_name, 0)
new_value = current_value + delta
self.c... | Increment counter value.
Args:
counter_name: counter name as String.
delta: increment delta as Integer.
Returns:
new counter value. |
def route(self, path_regex, methods=['GET'], doc=True):
"""
Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc struct... | Decorator to register a handler
Parameters:
* path_regex: Request path regex to match against for running the handler
* methods: HTTP methods to use this handler for
* doc: Add to internal doc structure |
def _handle_option_deprecations(options):
"""Issue appropriate warnings when deprecated options are present in the
options dictionary. Removes deprecated option key, value pairs if the
options dictionary is found to also have the renamed option."""
undeprecated_options = _CaseInsensitiveDictionary()
... | Issue appropriate warnings when deprecated options are present in the
options dictionary. Removes deprecated option key, value pairs if the
options dictionary is found to also have the renamed option. |
def waitStarted(self):
"""wait until name server is started."""
ns = None
while not ns:
try:
time.sleep(3)
ns = Pyro.naming.NameServerLocator(
identification=self.identification).getNS()
except Pyro.errors.NamingError as... | wait until name server is started. |
def _list_fields(self):
"""
Get the current settings of the model. The keys depend on the type of
model.
Returns
-------
out : list
A list of fields that can be queried using the ``get`` method.
"""
response = self.__proxy__.list_fields()
... | Get the current settings of the model. The keys depend on the type of
model.
Returns
-------
out : list
A list of fields that can be queried using the ``get`` method. |
def mount_iso_image(self, image, image_name, ins_file_name):
"""
Upload an ISO image and associate it to this Partition
using the HMC operation 'Mount ISO Image'.
When the partition already has an ISO image associated,
the newly uploaded image replaces the current one.
... | Upload an ISO image and associate it to this Partition
using the HMC operation 'Mount ISO Image'.
When the partition already has an ISO image associated,
the newly uploaded image replaces the current one.
Authorization requirements:
* Object-access permission to this Partition... |
def rename_scored_calls(self,change):
"""
Change the names of scored call names, input dictionary change with {<current name>:<new name>} format, new name must not already exist
Args:
change (dict): a dictionary of current name keys and new name values
Returns:
... | Change the names of scored call names, input dictionary change with {<current name>:<new name>} format, new name must not already exist
Args:
change (dict): a dictionary of current name keys and new name values
Returns:
CellDataFrame: The CellDataFrame modified. |
def get_graphs(self, run_key, debug=False):
"""Get the runtime GraphDef protos associated with a run key.
Args:
run_key: A Session.run kay.
debug: Whether the debugger-decoratedgraph is to be retrieved.
Returns:
A `dict` mapping device name to `GraphDef` protos.
"""
graph_dict = ... | Get the runtime GraphDef protos associated with a run key.
Args:
run_key: A Session.run kay.
debug: Whether the debugger-decoratedgraph is to be retrieved.
Returns:
A `dict` mapping device name to `GraphDef` protos. |
def pixel_to_utm(row, column, transform):
""" Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x... | Convert pixel coordinate to UTM coordinate given a transform
:param row: row pixel coordinate
:type row: int or float
:param column: column pixel coordinate
:type column: int or float
:param transform: georeferencing transform of the image, e.g. `(x_upper_left, res_x, 0, y_upper_left, 0, -res_y)`
... |
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):
"""Wrapper for mmap2"""
return self.sys_mmap2(address, size, prot, flags, fd, offset) | Wrapper for mmap2 |
def get_domain(url):
"""
Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org
"""
parse_result = urlparse(url)
domain = "{schema}://{netloc}".format(
schema=parse_result.scheme, netloc=parse_result.netloc)
return domain | Get domain part of an url.
For example: https://www.python.org/doc/ -> https://www.python.org |
def syllabifyTextgrid(isleDict, tg, wordTierName, phoneTierName,
skipLabelList=None, startT=None, stopT=None):
'''
Given a textgrid, syllabifies the phones in the textgrid
skipLabelList allows you to skip labels without generating warnings
(e.g. '', 'sp', etc.)
The te... | Given a textgrid, syllabifies the phones in the textgrid
skipLabelList allows you to skip labels without generating warnings
(e.g. '', 'sp', etc.)
The textgrid must have a word tier and a phone tier.
Returns a textgrid with only two tiers containing syllable information
(syllabificati... |
def get_comment(self, name):
"""
Banana banana
"""
comment = self.__comments.get(name)
if comment:
return comment
aliases = self.__get_aliases(name)
for alias in aliases:
comment = self.__comments.get(alias)
if comment:
... | Banana banana |
def formatted_command(self):
"""Build and return the formatted command for this `Link`.
This is exactly the command as called from the Unix command line.
"""
# FIXME, this isn't really great as it force you to have all the arguments
command_template = self.command_template()
... | Build and return the formatted command for this `Link`.
This is exactly the command as called from the Unix command line. |
def _clone_node(self) -> 'Tag':
"""Need to copy class, not tag.
So need to re-implement copy.
"""
clone = type(self)()
for attr in self.attributes:
clone.setAttribute(attr, self.getAttribute(attr))
for c in self.classList:
clone.addClass(c)
... | Need to copy class, not tag.
So need to re-implement copy. |
def list_dvs(kwargs=None, call=None):
'''
List all the distributed virtual switches for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_dvs my-vmware-config
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_dvs function mu... | List all the distributed virtual switches for this VMware environment
CLI Example:
.. code-block:: bash
salt-cloud -f list_dvs my-vmware-config |
def all(guideids=None, filter=None, order=None):
'''
Fetch all guides.
:param iterable guideids: Only return Guides corresponding to these ids.
:param string filter: Only return guides of this type. Choices:
installation, repair, disassembly, teardown,
... | Fetch all guides.
:param iterable guideids: Only return Guides corresponding to these ids.
:param string filter: Only return guides of this type. Choices:
installation, repair, disassembly, teardown,
technique, maintenance.
:param string ... |
def get_provider(self, provider_name='default'):
"""Fetch provider with the name specified in Configuration file"""
try:
if self._providers is None:
self._providers = self._initialize_providers()
return self._providers[provider_name]
except KeyError:
... | Fetch provider with the name specified in Configuration file |
def _validate_features(features, column_type_map, valid_types, label):
"""
Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column... | Identify the subset of desired `features` that are valid for the Kmeans
model. A warning is emitted for each feature that is excluded.
Parameters
----------
features : list[str]
Desired feature names.
column_type_map : dict[str, type]
Dictionary mapping each column name to the type... |
def _convert_reftype_to_jaeger_reftype(ref):
"""Convert opencensus reference types to jaeger reference types."""
if ref == link_module.Type.CHILD_LINKED_SPAN:
return jaeger.SpanRefType.CHILD_OF
if ref == link_module.Type.PARENT_LINKED_SPAN:
return jaeger.SpanRefType.FOLLOWS_FROM
return N... | Convert opencensus reference types to jaeger reference types. |
def resolve_aonly(self,tables_dict,table_ctor):
"circular depends on pgmock.Table. refactor."
for alias,selectx in self.aonly.items():
table = table_ctor(alias,infer_columns(selectx,tables_dict),None)
table.rows = run_select(selectx,tables_dict,table_ctor)
self.aonly[alias] = table
self.ao... | circular depends on pgmock.Table. refactor. |
def os_application_version_set(package):
'''Set version of application for Juju 2.0 and later'''
application_version = get_upstream_version(package)
# NOTE(jamespage) if not able to figure out package version, fallback to
# openstack codename version detection.
if not application_ver... | Set version of application for Juju 2.0 and later |
def plot_eq(fignum, DIblock, s):
"""
plots directions on eqarea projection
Parameters
__________
fignum : matplotlib figure number
DIblock : nested list of dec/inc pairs
s : specimen name
"""
# make the stereonet
plt.figure(num=fignum)
if len(DIblock) < 1:
return
# pl... | plots directions on eqarea projection
Parameters
__________
fignum : matplotlib figure number
DIblock : nested list of dec/inc pairs
s : specimen name |
def version_check(self):
"""
Check if the version entry is in the proper format
"""
try:
version_info = self['Version']
except KeyError:
raise ValidateError('Config file has to have a Version section')
try:
float(version_info['version']... | Check if the version entry is in the proper format |
def parallelize(self, c, numSlices=None):
"""
Distribute a local Python collection to form an RDD. Using xrange
is recommended if the input represents a range for performance.
>>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()
[[0], [2], [3], [4], [6]]
>>> sc.parall... | Distribute a local Python collection to form an RDD. Using xrange
is recommended if the input represents a range for performance.
>>> sc.parallelize([0, 2, 3, 4, 6], 5).glom().collect()
[[0], [2], [3], [4], [6]]
>>> sc.parallelize(xrange(0, 6, 2), 5).glom().collect()
[[], [0], [... |
def pick(rest):
"Pick between a few options"
question = rest.strip()
choices = util.splitem(question)
if len(choices) == 1:
return "I can't pick if you give me only one choice!"
else:
pick = random.choice(choices)
certainty = random.sample(phrases.certainty_opts, 1)[0]
return "%s... %s %s" % (pick, certain... | Pick between a few options |
def append(self, node):
"""To append a new child."""
if node.parent == self.key and not self.elapsed_time:
self.children.append(node)
else:
# Recursive call
for child in self.children:
if not child.elapsed_time:
child.append... | To append a new child. |
def _email(name, *, allow_unverified=False):
"""
This decorator is used to turn an e function into an email sending function!
The name parameter is the name of the email we're going to be sending (used to
locate the templates on the file system).
The allow_unverified kwarg flags whether we will se... | This decorator is used to turn an e function into an email sending function!
The name parameter is the name of the email we're going to be sending (used to
locate the templates on the file system).
The allow_unverified kwarg flags whether we will send this email to an unverified
email or not. We gener... |
def enabled(name,
skip_verify=False,
**kwargs):
'''
Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead fu... | Ensure that the service is enabled on boot, only use this state if you
don't want to manage the running process, remember that if you want to
enable a running service to use the enable: True option for the running
or dead function.
name
The name of the init or rc script used to manage the servi... |
def expand_param_list(self, paramlist):
""" expands the parameters list according to one of these schemes:
grid: every list item is combined with every other list item
list: every n-th list item of parameter lists are combined
"""
# for one single experiment, still wrap ... | expands the parameters list according to one of these schemes:
grid: every list item is combined with every other list item
list: every n-th list item of parameter lists are combined |
def auth_timeout(self):
"""Handle legacy authentication timeout.
[client only]"""
self.lock.acquire()
try:
self.__logger.debug("Timeout while waiting for jabber:iq:auth result")
if self._auth_methods_left:
self._auth_methods_left.pop(0)
fi... | Handle legacy authentication timeout.
[client only] |
def fly(cls,
conf_path,
docname,
source,
maxdepth=1): # pragma: no cover
"""
Generate toctree directive for rst file.
:param conf_path: conf.py file absolute path
:param docname: the rst file relpath from conf.py directory.
:param... | Generate toctree directive for rst file.
:param conf_path: conf.py file absolute path
:param docname: the rst file relpath from conf.py directory.
:param source: rst content.
:param maxdepth: int, max toc tree depth. |
def get_tok(self, tok):
'''
Return the name associated with the token, or False if the token is
not valid
'''
tdata = self.tokens["{0}.get_token".format(self.opts['eauth_tokens'])](self.opts, tok)
if not tdata:
return {}
rm_tok = False
if 'exp... | Return the name associated with the token, or False if the token is
not valid |
def get_response_structure(name):
"""
Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown
"""
return {
CreateContextName.SMB2_CREATE_DURAB... | Returns the response structure for a know list of create context
responses.
:param name: The constant value above
:return: The response structure or None if unknown |
def trees_to_dataframe(self, fmap=''):
"""Parse a boosted tree model text dump into a pandas DataFrame structure.
This feature is only defined when the decision tree model is chosen as base
learner (`booster in {gbtree, dart}`). It is not defined for other base learner
types, such as li... | Parse a boosted tree model text dump into a pandas DataFrame structure.
This feature is only defined when the decision tree model is chosen as base
learner (`booster in {gbtree, dart}`). It is not defined for other base learner
types, such as linear learners (`booster=gblinear`).
Param... |
def get_token(self):
"""
Gets the authorization token
"""
payload = {'grant_type': 'client_credentials', 'client_id': self.client_id, 'client_secret': self.client_secret}
r = requests.post(OAUTH_ENDPOINT, data=json.dumps(payload), headers={'content-type': 'application/js... | Gets the authorization token |
def _delete_element(name, element_type, data, server=None):
'''
Delete an element
'''
_api_delete('{0}/{1}'.format(element_type, quote(name, safe='')), data, server)
return name | Delete an element |
def mask_from_embedding(emb):
"""Input embeddings -> padding mask.
We have hacked symbol_modality to return all-zero embeddings for padding.
Returns a mask with 0.0 in the padding positions and 1.0 elsewhere.
Args:
emb: a Tensor with shape [batch, width, height, depth].
Returns:
a 0.0/1.0 Tensor wit... | Input embeddings -> padding mask.
We have hacked symbol_modality to return all-zero embeddings for padding.
Returns a mask with 0.0 in the padding positions and 1.0 elsewhere.
Args:
emb: a Tensor with shape [batch, width, height, depth].
Returns:
a 0.0/1.0 Tensor with shape [batch, width, height, 1]. |
def run_loop(self):
"keep rendering until the user says quit"
self.running = True
event = SDL_Event()
try:
while self.running:
while SDL_PollEvent(ctypes.byref(event)) != 0:
f = self._sdl_event_handlers.get(event.type)
if f is not None:
f ( event )
self.render_scene()
exc... | keep rendering until the user says quit |
def in6_iseui64(x):
"""
Return True if provided address has an interface identifier part
created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*).
Otherwise, False is returned. Address must be passed in printable
format.
"""
eui64 = inet_pton(socket.AF_INET6, '::ff:fe00:0')
... | Return True if provided address has an interface identifier part
created in modified EUI-64 format (meaning it matches *::*:*ff:fe*:*).
Otherwise, False is returned. Address must be passed in printable
format. |
def get_degenerate_statements(self):
"""Get all degenerate BEL statements.
Stores the results of the query in self.degenerate_stmts.
"""
logger.info("Checking for 'degenerate' statements...\n")
# Get rules of type protein X -> activity Y
q_stmts = prefixes + """
... | Get all degenerate BEL statements.
Stores the results of the query in self.degenerate_stmts. |
def fetch(self, method, params=None):
"""
Fetch an url.
"""
# Encode params if they exist
if params:
params = urllib.parse.urlencode(params, doseq=True).encode("utf-8")
content = self._make_request(
self.BASE_URI + method,
params,
... | Fetch an url. |
def fit_zyz(target_gate):
"""
Tensorflow eager mode example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate.
"""
assert bk.BACKEND == 'eager'
tf = bk.TL
tfe = bk.tfe
steps = 4000
dev = '/gpu:0' if bk.DEVICE == '... | Tensorflow eager mode example. Given an arbitrary one-qubit gate, use
gradient descent to find corresponding parameters of a universal ZYZ
gate. |
def check_gap(xpub, api_key):
"""Call the 'v2/receive/checkgap' endpoint and returns the callback log
for a given callback URI with parameters.
:param str xpub: extended public key
:param str api_key: Blockchain.info API V2 key
:return: an int
"""
params = {'key': api_key, 'xpub': xpub}
... | Call the 'v2/receive/checkgap' endpoint and returns the callback log
for a given callback URI with parameters.
:param str xpub: extended public key
:param str api_key: Blockchain.info API V2 key
:return: an int |
def query_all_issues(after):
"""Hits the github API for all closed issues after the given date, returns the data."""
page = count(1)
data = []
while True:
page_data = query_issues(next(page), after)
if not page_data:
break
data.extend(page_data)
return data | Hits the github API for all closed issues after the given date, returns the data. |
def remove_filter_set(self, filter_name):
"""
Remove filter set by name
:param filter_name: str
"""
if filter_name in self._filter_sets:
del self._filter_sets[filter_name]
else:
raise ValueError('Unknown filter set name.') | Remove filter set by name
:param filter_name: str |
def _call_multi(self, clients, command, *args):
""" Call multi """
responses, errors = {}, {}
for addr, client in clients.items():
res, err = self._call_single(client, command, *args)
responses[addr] = res
errors[addr] = err
return responses, errors | Call multi |
def from_rotation_matrix(rot, nonorthogonal=True):
"""Convert input 3x3 rotation matrix to unit quaternion
By default, if scipy.linalg is available, this function uses
Bar-Itzhack's algorithm to allow for non-orthogonal matrices.
[J. Guidance, Vol. 23, No. 6, p. 1085 <http://dx.doi.org/10.2514/2.4654>]... | Convert input 3x3 rotation matrix to unit quaternion
By default, if scipy.linalg is available, this function uses
Bar-Itzhack's algorithm to allow for non-orthogonal matrices.
[J. Guidance, Vol. 23, No. 6, p. 1085 <http://dx.doi.org/10.2514/2.4654>]
This will almost certainly be quite a bit slower than... |
def tags(self):
"""Creates a list of all the tags of the contained items
# Returns
`list [str]`
> A list of all the tags
"""
tags = set()
for i in self:
tags |= set(i.keys())
return tags | Creates a list of all the tags of the contained items
# Returns
`list [str]`
> A list of all the tags |
def norm(A):
"""computes the L2-norm along axis 1 (e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1)
"""
return np.sqrt(A.multiply(A).sum(1).A1) if issparse(A) else np.sqrt(np.einsum('ij, ij -> i', A, A)) | computes the L2-norm along axis 1 (e.g. genes or embedding dimensions) equivalent to np.linalg.norm(A, axis=1) |
def ordered_by_replica(self, request_key):
"""
Should be called by each replica when request is ordered or replica is removed.
"""
state = self.get(request_key)
if not state:
return
state.unordered_by_replicas_num -= 1 | Should be called by each replica when request is ordered or replica is removed. |
def add(self, member, score):
"""Add the specified member to the sorted set, or update the score
if it already exist."""
return self.client.zadd(self.name, member, score) | Add the specified member to the sorted set, or update the score
if it already exist. |
def ComplementEquivalence(*args, **kwargs):
"""Change x != y to not(x == y)."""
return ast.Complement(
ast.Equivalence(*args, **kwargs), **kwargs) | Change x != y to not(x == y). |
def validate_xml(file):
"""Validate an XML file."""
max_file_size = current_app.config.get(
'PREVIEWER_MAX_FILE_SIZE_BYTES', 1 * 1024 * 1024)
if file.size > max_file_size:
return False
with file.open() as fp:
try:
content = fp.read().decode('utf-8')
xml.d... | Validate an XML file. |
def _set_status_data(self, userdata):
"""Set status properties from userdata response.
Response values:
d3: On Mask
d4: Off Mask
d5: X10 House Code
d6: X10 Unit
d7: Ramp Rate
d8: On-Level
d9: LED Brightness
... | Set status properties from userdata response.
Response values:
d3: On Mask
d4: Off Mask
d5: X10 House Code
d6: X10 Unit
d7: Ramp Rate
d8: On-Level
d9: LED Brightness
d10: Non-Toggle Mask
d11: LED ... |
def generate_terms(self, ref, root, file_type=None):
"""An generator that yields term objects, handling includes and argument
children.
:param file_type:
:param doc:
:param root:
:param ref:
"""
last_section = root
t = None
if isinstance... | An generator that yields term objects, handling includes and argument
children.
:param file_type:
:param doc:
:param root:
:param ref: |
def get_assessment_part_item_design_session(self, proxy):
"""Gets the ``OsidSession`` associated with the assessment part item design service.
return: (osid.assessment.authoring.AssessmentPartItemDesignSession)
- an ``AssessmentPartItemDesignSession``
raise: OperationFailed - u... | Gets the ``OsidSession`` associated with the assessment part item design service.
return: (osid.assessment.authoring.AssessmentPartItemDesignSession)
- an ``AssessmentPartItemDesignSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_... |
def get_attribute_values_string(self):
"""Retrieves a comparable string of the attribute values.
Returns:
str: comparable string of the attribute values.
"""
attributes = []
for attribute_name, attribute_value in sorted(self.__dict__.items()):
# Not using startswith to improve performanc... | Retrieves a comparable string of the attribute values.
Returns:
str: comparable string of the attribute values. |
def gt_type(self):
"""The type of genotype, returns one of ``HOM_REF``, ``HOM_ALT``, and
``HET``.
"""
if not self.called:
return None # not called
elif all(a == 0 for a in self.gt_alleles):
return HOM_REF
elif len(set(self.gt_alleles)) == 1:
... | The type of genotype, returns one of ``HOM_REF``, ``HOM_ALT``, and
``HET``. |
def begin_tag(self, name: str) -> Node:
"""Save the current index under the given name."""
# Check if we could attach tag cache to current rule_nodes scope
self.tag_cache[name] = Tag(self._stream, self._stream.index)
return True | Save the current index under the given name. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.