text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _merge_derived_parameters(self,
other_trajectory,
used_runs,
rename_dict,
allowed_translations,
ignore_data):
""" Merges derived... | 0.003784 |
def query(self, analysis_type, params, all_keys=False):
"""
Performs a query using the Keen IO analysis API. A read key must be set first.
"""
if not self._order_by_is_valid_or_none(params):
raise ValueError("order_by given is invalid or is missing required group_by.")
... | 0.008065 |
def _unstack_extension_series(series, level, fill_value):
"""
Unstack an ExtensionArray-backed Series.
The ExtensionDtype is preserved.
Parameters
----------
series : Series
A Series with an ExtensionArray for values
level : Any
The level name or number.
fill_value : An... | 0.000644 |
def createDaemon():
"""Detach a process from the controlling terminal and run it in the
background as a daemon.
"""
try:
# Fork a child process so the parent can exit. This returns control to
# the command-line or shell. It also guarantees that the child will not
# be a process group le... | 0.018977 |
def run_step(context):
"""Set new context keys from formatting expressions with substitutions.
Context is a dictionary or dictionary-like.
context['contextSetf'] must exist. It's a dictionary.
Will iterate context['contextSetf'] and save the values as new keys to the
context.
For example, say ... | 0.00095 |
def _CheckWindowsRegistryKeyPath(
self, filename, artifact_definition, key_path):
"""Checks if a path is a valid Windows Registry key path.
Args:
filename (str): name of the artifacts definition file.
artifact_definition (ArtifactDefinition): artifact definition.
key_path (str): Windows... | 0.004545 |
def set_entry(self, jid, *,
name=_Sentinel,
add_to_groups=frozenset(),
remove_from_groups=frozenset(),
timeout=None):
"""
Set properties of a roster entry or add a new roster entry. The roster
entry is identified by its bare... | 0.002712 |
def feed(self, contents):
'''
feed - Feed contents. Use parseStr or parseFile instead.
@param contents - Contents
'''
contents = stripIEConditionals(contents)
try:
HTMLParser.feed(self, contents)
except MultipleRootNodeException:
... | 0.008909 |
def get_resource(url, subdomain):
"""
Issue a GET request to IASystem with the given url
and return a response in Collection+json format.
:returns: http response with content in json
"""
headers = {"Accept": "application/vnd.collection+json"}
response = IASYSTEM_DAO().getURL(url, headers, su... | 0.001678 |
def __resolveport(self, definitions):
"""
Resolve port_type reference.
@param definitions: A definitions object.
@type definitions: L{Definitions}
"""
ref = qualify(self.type, self.root, definitions.tns)
port_type = definitions.port_types.get(ref)
if por... | 0.002066 |
def _GetNormalizedTimestamp(self):
"""Retrieves the normalized timestamp.
Returns:
decimal.Decimal: normalized timestamp, which contains the number of
seconds since January 1, 1970 00:00:00 and a fraction of second used
for increased precision, or None if the normalized timestamp cann... | 0.004926 |
def remove_monitor(self, handle):
"""Remove a previously registered monitor.
See :meth:`AbstractDeviceAdapter.adjust_monitor`.
"""
action = (handle, "delete", None, None)
if self._currently_notifying:
self._deferred_adjustments.append(action)
else:
... | 0.00554 |
def ageostrophic_wind(heights, f, dx, dy, u, v, dim_order='yx'):
r"""Calculate the ageostrophic wind given from the heights or geopotential.
Parameters
----------
heights : (M, N) ndarray
The height field.
f : array_like
The coriolis parameter. This can be a scalar to be applied
... | 0.004608 |
def _vcf_is_strelka(variant_file, variant_metadata):
"""Return True if variant_file given is in strelka format
"""
if "strelka" in variant_file.lower():
return True
elif "NORMAL" in variant_metadata["sample_info"].keys():
return True
else:
vcf_reader = vcf.Reader(open(variant... | 0.001876 |
def js_prerelease(command, strict=False):
"""decorator for building minified js/css prior to another command"""
class DecoratedCommand(command):
def run(self):
jsdeps = self.distribution.get_command_obj('jsdeps')
if not is_repo and all(exists(t) for t in jsdeps.targets):
... | 0.000947 |
def set_bookmarks(self, bookmarks):
"""
Store the sequence of bookmarks `bookmarks`.
Causes signals to be fired to reflect the changes.
.. note:: This should normally not be used. It does not
mitigate the race condition between clients
concurrently m... | 0.002445 |
def dump_migration_session_state(raw):
"""
Serialize a migration session state to yaml using nicer formatting
Args:
raw: object to serialize
Returns: string (of yaml)
Specifically, this forces the "output" member of state step dicts (e.g.
state[0]['output']) to use block formatting. Fo... | 0.004864 |
def _validate_covars(covars, covariance_type, n_components):
"""Do basic checks on matrix covariance sizes and values."""
from scipy import linalg
if covariance_type == 'spherical':
if len(covars) != n_components:
raise ValueError("'spherical' covars have length n_components")
el... | 0.000536 |
def SetColLabelValue(self, col, value):
"""
Set col label value in dataframe
"""
if len(self.dataframe):
col_name = str(self.dataframe.columns[col])
self.dataframe.rename(columns={col_name: str(value)}, inplace=True)
return None | 0.006849 |
def bring_to_front(self, selector, by=By.CSS_SELECTOR):
""" Updates the Z-index of a page element to bring it into view.
Useful when getting a WebDriverException, such as the one below:
{ Element is not clickable at point (#, #).
Other element would receive the clic... | 0.002148 |
def _polar_to_cartesian(cx, cy, r, theta):
"""
:param cx: X coord of circle
:param cy: Y coord of circle
:param r: Radius of circle
:param theta: Degrees from vertical, clockwise, in radians
:return: (x, y)
"""
return cx - r * math.sin(theta), cy - r * mat... | 0.006024 |
def send_command_block(self, target, command_block):
"""Send an arbitrary file system command block
The primary use for this method is to send multiple file system commands with a single
web service request. This can help to avoid throttling.
:param target: The device(s) to be targete... | 0.006813 |
def split_pred_string(predstr):
"""
Split *predstr* and return the (lemma, pos, sense, suffix) components.
Examples:
>>> Pred.split_pred_string('_dog_n_1_rel')
('dog', 'n', '1', 'rel')
>>> Pred.split_pred_string('quant_rel')
('quant', None, None, 'rel')
"""
predstr =... | 0.00107 |
def count(self) -> "CountQuery":
"""
Return count of objects in queryset instead of objects.
"""
return CountQuery(
db=self._db,
model=self.model,
q_objects=self._q_objects,
annotations=self._annotations,
custom_filters=self._cu... | 0.005831 |
def mac(addr):
'''
Validates a mac address
'''
valid = re.compile(r'''
(^([0-9A-F]{1,2}[-]){5}([0-9A-F]{1,2})$
|^([0-9A-F]{1,2}[:]){5}([0-9A-F]{1,2})$
|^([0-9A-F]{1,2}[.]){5}([0-9A-F]{1,2})$)
''',
... | 0.005115 |
def run(items):
"""Perform detection of structural variations with lumpy.
"""
paired = vcfutils.get_paired(items)
work_dir = _sv_workdir(paired.tumor_data if paired and paired.tumor_data else items[0])
previous_evidence = {}
full_bams, sr_bams, disc_bams = [], [], []
for data in items:
... | 0.002679 |
def expand_details(df, detailCol='detail'):
"""Expands the details column of the given dataframe and returns the
resulting DataFrame.
:df: The input DataFrame.
:detailCol: The detail column name.
:returns: Returns DataFrame with new columns from pbp parsing.
"""
df = copy.deepcopy(df)
d... | 0.001488 |
def _get_help_for_modules(self, modules, prefix, include_special_flags):
"""Returns the help string for a list of modules.
Private to absl.flags package.
Args:
modules: List[str], a list of modules to get the help string for.
prefix: str, a string that is prepended to each generated help line.... | 0.004848 |
def timeit(hosts=None,
stmt=None,
warmup=30,
repeat=None,
duration=None,
concurrency=1,
output_fmt=None,
fail_if=None,
sample_mode='reservoir'):
"""Run the given statement a number of times and return the runtime stats
Args... | 0.001974 |
def map_concepts_to_indicators(
self, n: int = 1, min_temporal_res: Optional[str] = None
):
""" Map each concept node in the AnalysisGraph instance to one or more
tangible quantities, known as 'indicators'.
Args:
n: Number of matches to keep
min_temporal_res:... | 0.001813 |
def os_instance_2_json(self):
"""
transform ariane_clip3 OS Instance object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("OSInstance.os_instance_2_json")
json_obj = {
'osInstanceID': self.id,
'osInstanceName': self.name,
... | 0.002018 |
def run(vrn_info, cnvs_by_name, somatic_info):
"""Run THetA analysis given output from CNV caller on a tumor/normal pair.
"""
cmd = _get_cmd("RunTHeTA.py")
if not cmd:
logger.info("THetA scripts not found in current PATH. Skipping.")
else:
from bcbio.structural import cnvkit
... | 0.006165 |
def find_all(root, path):
"""Get all children that satisfy the path."""
path = parse_path(path)
if len(path) == 1:
yield from get_children(root, path[0])
else:
for child in get_children(root, path[0]):
yield from find_all(child, path[1:]) | 0.022989 |
def get_completeness_adjusted_table(catalogue, completeness, dmag,
offset=1.0E-5, end_year=None, plot=False,
figure_size=(8, 6), filename=None,
filetype='png', dpi=300, ax=None):
"""
Counts the number of ... | 0.000697 |
def _decode_v1(value):
"""
Decode '::' and '$' characters encoded by `_encode`.
"""
decode_colons = value.replace('$::', '::')
decode_dollars = decode_colons.replace('$$', '$')
reencoded = _encode_v1(decode_dollars)
if reencoded != value:
raise ValueError('Ambiguous encoded value, {... | 0.00489 |
def to_python(self, value):
"""Overrides ``models.Field`` method. This is used to convert
bytes (from serialization etc) to an instance of this class"""
if value is None:
return None
elif isinstance(value, oauth2client.client.Credentials):
return value
els... | 0.003378 |
def create(self, name, suffix, description, default_value, display=None):
"""Create a new Metric
:param str name: Name of metric
:param str suffix: Metric unit
:param str description: Description of what the metric is measuring
:param int default_value: Default value to use when... | 0.002509 |
def get_stats_summary(start=None, end=None, **kwargs):
"""
Stats Historical Summary
Reference: https://iexcloud.io/docs/api/#stats-historical-summary
Data Weighting: ``Free``
Parameters
----------
start: datetime.datetime, default None, optional
Start of data retrieval period
e... | 0.001821 |
def _add_blockhash_to_state_changes(storage: SQLiteStorage, cache: BlockHashCache) -> None:
"""Adds blockhash to ContractReceiveXXX and ActionInitChain state changes"""
batch_size = 50
batch_query = storage.batch_query_state_changes(
batch_size=batch_size,
filters=[
('_type', 'r... | 0.003643 |
def urbext(self, year):
"""
Estimate the `urbext2000` parameter for a given year assuming a nation-wide urbanisation curve.
Methodology source: eqn 5.5, report FD1919/TR
:param year: Year to provide estimate for
:type year: float
:return: Urban extent parameter
... | 0.005755 |
def readTFAM(fileName):
"""Reads the TFAM file.
:param fileName: the name of the ``tfam`` file.
:type fileName: str
:returns: a representation the ``tfam`` file (:py:class:`numpy.array`).
"""
# Saving the TFAM file
tfam = None
with open(fileName, 'r') as inputFile:
tfam = [
... | 0.002217 |
def submit_to_queue(self, script_file):
"""
Public API: wraps the concrete implementation _submit_to_queue
Raises:
`self.MaxNumLaunchesError` if we have already tried to submit the job max_num_launches
`self.Error` if generic error
"""
if not os.path.exis... | 0.005824 |
def _calculate_gain(self, cost_base, y_true, X, cost_mat, split):
""" Private function to calculate the gain in cost of using split in the
current node.
Parameters
----------
cost_base : float
Cost of the naive prediction
y_true : array indicator matrix
... | 0.005655 |
def launch_in_notebook(self, port=9095, width=900, height=600):
"""launch the app within an iframe in ipython notebook"""
from IPython.lib import backgroundjobs as bg
from IPython.display import HTML
jobs = bg.BackgroundJobManager()
jobs.new(self.launch, kw=dict(port=port))
... | 0.004132 |
def commit_config(self, message=""):
"""Commit configuration."""
commit_args = {"comment": message} if message else {}
self.device.cu.commit(ignore_warning=self.ignore_warning, **commit_args)
if not self.lock_disable and not self.session_config_lock:
self._unlock() | 0.009709 |
def _mergeFiles(key, chunkCount, outputFile, fields):
"""Merge sorted chunk files into a sorted output file
chunkCount - the number of available chunk files
outputFile the name of the sorted output file
_mergeFiles()
"""
title()
# Open all chun files
files = [FileRecordStream('chunk_%d.csv' % i) for... | 0.016579 |
def init_ui(self, ):
"""Create the tooltip in the sidebar
:returns: None
:rtype: None
:raises: None
"""
self.sidebar = self.get_maya_sidebar()
self.lay = self.sidebar.layout()
self.tool_pb = QtGui.QPushButton("JB Wins")
self.tooltip = JB_WindowToo... | 0.004219 |
def _run_keep_alive(self):
"""
Start a new thread timer to keep the keep_alive_function running
every keep_alive seconds.
"""
threading.Timer(self._keep_alive, self._run_keep_alive).start()
_LOGGER.info("Polling the API")
# This may or may not return something
... | 0.005682 |
async def send_contact(self, chat_id: typing.Union[base.Integer, base.String],
phone_number: base.String, first_name: base.String,
last_name: typing.Union[base.String, None] = None,
vcard: typing.Union[base.String, None] = None,
... | 0.007472 |
def install_package_command(package_name):
'''install python package from pip'''
#TODO refactor python logic
if sys.platform == "win32":
cmds = 'python -m pip install --user {0}'.format(package_name)
else:
cmds = 'python3 -m pip install --user {0}'.format(package_name)
call(cmds, she... | 0.006098 |
def taskfileinfo_path_data(tfi, role):
"""Return the data for path
:param tfi: the :class:`jukeboxcore.filesys.TaskFileInfo` holds the data
:type tfi: :class:`jukeboxcore.filesys.TaskFileInfo`
:param role: item data role
:type role: QtCore.Qt.ItemDataRole
:returns: data for the path
:rtype:... | 0.002105 |
def make_country_matrix(self, loc):
"""
Create features for all possible country labels, return as matrix for keras.
Parameters
----------
loc: dict
one entry from the list of locations and features that come out of make_country_features
Returns
----... | 0.00453 |
def hashkey(*args, **kwargs):
"""Return a cache key for the specified hashable arguments."""
if kwargs:
return _HashedTuple(args + sum(sorted(kwargs.items()), _kwmark))
else:
return _HashedTuple(args) | 0.004367 |
def sendACK(self, blocknumber=None):
"""This method sends an ack packet to the block number specified. If
none is specified, it defaults to the next_block property in the
parent context."""
log.debug("In sendACK, passed blocknumber is %s", blocknumber)
if blocknumber is None:
... | 0.002841 |
def for_property(cls, server, namespace, classname, propname):
# pylint: disable=line-too-long
"""
Factory method that returns a new :class:`~pywbem.ValueMapping`
instance that maps CIM property values to the `Values` qualifier
defined on that property.
If a `Values` qua... | 0.001207 |
async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
"""
Get a value from the cache. Returns default if not found.
:param key: str
:param default: obj to return when key is not found
:param loads_fn: callable alternative to use as loads function
... | 0.005994 |
def write_text(filename: str, text: str) -> None:
"""
Writes text to a file.
"""
with open(filename, 'w') as f: # type: TextIO
print(text, file=f) | 0.005848 |
def fix_config(self, options):
"""
Fixes the options, if necessary. I.e., it adds all required elements to the dictionary.
:param options: the options to fix
:type options: dict
:return: the (potentially) fixed options
:rtype: dict
"""
options = super(Tri... | 0.00678 |
def _CaptureExpression(self, frame, expression):
"""Evalutes the expression and captures it into a Variable object.
Args:
frame: evaluation context.
expression: watched expression to compile and evaluate.
Returns:
Variable object (which will have error status if the expression fails
... | 0.003373 |
def create_query_index(
self,
design_document_id=None,
index_name=None,
index_type='json',
partitioned=False,
**kwargs
):
"""
Creates either a JSON or a text query index in the remote database.
:param str index_type: Th... | 0.001084 |
def check_nonnegative(value):
"""Check that the value is nonnegative."""
if isinstance(value, tf.Tensor):
with tf.control_dependencies([tf.assert_greater_equal(value, 0)]):
value = tf.identity(value)
elif value < 0:
raise ValueError("Value must be non-negative.")
return value | 0.020134 |
def new(self):
# type: () -> None
'''
A method to create a new UDF Logical Volume Header Descriptor.
Parameters:
None.
Returns:
Nothing.
'''
if self._initialized:
raise pycdlibexception.PyCdlibInternalError('UDF Logical Volume Header... | 0.009592 |
def system_greet(input_params={}, always_retry=True, **kwargs):
"""
Invokes the /system/greet API method.
"""
return DXHTTPRequest('/system/greet', input_params, always_retry=always_retry, **kwargs) | 0.009346 |
def osd_tree(conn, cluster):
"""
Check the status of an OSD. Make sure all are up and in
What good output would look like::
{
"epoch": 8,
"num_osds": 1,
"num_up_osds": 1,
"num_in_osds": "1",
"full": "false",
"nearfull": "false... | 0.000824 |
def database_caller_creator(self, host, port, name=None):
'''creates a redis connection object
which will be later used to modify the db
'''
name = name or 0
client = redis.StrictRedis(host=host, port=port, db=name)
pipe = client.pipeline(transaction=False)
retur... | 0.005988 |
def validate_arg(arg, argdef):
"""
Validate an incoming (unicode) string argument according the UPnP spec. Raises UPNPError.
"""
datatype = argdef['datatype']
reasons = set()
ranges = {
'ui1': (int, 0, 255),
'ui2': (int, 0, 65535),
'ui4... | 0.004065 |
def _initialize_hierarchy(self):
""" This function covers the whole initialization routine before executing a hierarchy state.
:return:
"""
logger.debug("Starting execution of {0}{1}".format(self, " (backwards)" if self.backward_execution else ""))
# reset variables
self... | 0.004136 |
def dutyCycle(self, active=False, readOnly=False):
"""Compute/update and return the positive activations duty cycle of
this segment. This is a measure of how often this segment is
providing good predictions.
:param active True if segment just provided a good prediction
:param readOnly If True, c... | 0.003279 |
def lat_from_inc(inc, a95=None):
"""
Calculate paleolatitude from inclination using the dipole equation
Required Parameter
----------
inc: (paleo)magnetic inclination in degrees
Optional Parameter
----------
a95: 95% confidence interval from Fisher mean
Returns
----------
... | 0.001193 |
def setText(self, text):
"""
Sets the text for this button. If it is set to show rich text, then
it will update the label text, leaving the root button text blank,
otherwise it will update the button.
:param text | <str>
"""
self._text = na... | 0.008264 |
def plot(self,
legend=None,
width=1.5,
ladder=True,
aspect=10,
ticks=(1, 10),
match_only=None,
ax=None,
return_fig=False,
colour=None,
cmap='viridis',
default=None,
... | 0.003982 |
def distL2(x1,y1,x2,y2):
"""Compute the L2-norm (Euclidean) distance between two points.
The distance is rounded to the closest integer, for compatibility
with the TSPLIB convention.
The two points are located on coordinates (x1,y1) and (x2,y2),
sent as parameters"""
xdiff = x2 - x1
ydiff ... | 0.010336 |
def main():
"""Main function"""
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--username',
required=True, help='enedis username')
parser.add_argument('-p', '--password',
required=True, help='Password')
args = parser.parse_args()
cl... | 0.001686 |
def pretty_emit(self, record, is_header=False, task_level=None):
"""
Wrapper around the :class:`logging.StreamHandler` emit method to add
some decoration stuff to the message
Args:
record (logging.LogRecord): log record to emit
is_header (bool): if this record is... | 0.001587 |
def getalignedtarget(self, index):
"""Returns target range only if source index aligns to a single consecutive range of target tokens."""
targetindices = []
target = None
foundindex = -1
for sourceindex, targetindex in self.alignment:
if sourceindex == index:
... | 0.005821 |
def build_js_from_template(self, template_file, variables):
"""
Build a JS script from a template and args
@type template_file: str
@param template_file: Script template to implement; can be the name of a built-in script or full filepath to
a js file... | 0.005181 |
def create(cls, paramCount):
"""
Creates a new particle without position, velocity and -inf as fitness
"""
return Particle(numpy.array([[]]*paramCount),
numpy.array([[]]*paramCount),
-numpy.Inf) | 0.015326 |
def get_grades_by_regid_and_term(regid, term):
"""
Returns a StudentGrades model for the regid and term.
"""
url = "{}/{},{},{}.json".format(enrollment_res_url_prefix,
term.year,
term.quarter,
reg... | 0.002618 |
def ArgSpec(*args, **kwargs):
"""
Validate a function based on the given argspec.
# Example:
validations = {
"foo": [ArgSpec("a", "b", c", bar="baz")]
}
def pass_func(a, b, c, bar="baz"):
pass
def fail_func(b, c, a, baz="bar"):
pass
... | 0.002155 |
def readline(self, timeout = 0.1):
"""Try to read a line from the stream queue.
"""
try:
return self._q.get(block = timeout is not None,
timeout = timeout)
except Empty:
return None | 0.029851 |
def AttachUserList(client, ad_group_id, user_list_id):
"""Links the provided ad group and user list.
Args:
client: an AdWordsClient instance.
ad_group_id: an int ad group ID.
user_list_id: an int user list ID.
Returns:
The ad group criterion that was successfully created.
"""
ad_group_criter... | 0.008986 |
def sbesselj_sum(z, N):
"""Tests the Spherical Bessel function jn using the sum:
Inf
sum (2*n+1) * jn(z)**2 = 1
n=0
z: The argument.
N: Large N value that the sum runs too.
Note that the sum only converges to 1 for large N value (i.e. N >> z).
The... | 0.001767 |
def _handle_received_k_element(self, k_element: BeautifulSoup):
"""
The 'k' element appears to be kik's connection-related stanza.
It lets us know if a connection or a login was successful or not.
:param k_element: The XML element we just received from kik.
"""
if k_elem... | 0.003476 |
def display_drilldown_as_ul(category, using='categories.Category'):
"""
Render the category with ancestors and children using the
``categories/ul_tree.html`` template.
Example::
{% display_drilldown_as_ul "/Grandparent/Parent" %}
or ::
{% display_drilldown_as_ul category_obj %}
... | 0.003481 |
def pop(self,
num_items: int,
type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]:
"""
Pop an item off the stack.
Note: This function is optimized for speed over readability.
"""
try:
if num_items == 1:
return n... | 0.009671 |
def match_version_pattern(filename, pattern):
"""
Matches a single version upgrade pattern in the specified *filename*
and returns the match information. Returns a #Match object or #None
if the *pattern* did not match.
"""
if "{VERSION}" not in pattern:
raise ValueError("pattern does not contain a {VER... | 0.019915 |
def _parser_jsonip(text):
"""Parse response text like the one returned by http://jsonip.com/."""
import json
try:
return str(json.loads(text).get("ip"))
except ValueError as exc:
LOG.debug("Text '%s' could not be parsed", exc_info=exc)
return None | 0.003484 |
def add_ubridge_udp_connection(self, bridge_name, source_nio, destination_nio):
"""
Creates an UDP connection in uBridge.
:param bridge_name: bridge name in uBridge
:param source_nio: source NIO instance
:param destination_nio: destination NIO instance
"""
yield... | 0.007736 |
def newmodel(f, G, y0, name='NewModel', modelType=ItoModel):
"""Use the functions f and G to define a new Model class for simulations.
It will take functions f and G from global scope and make a new Model class
out of them. It will automatically gather any globals used in the definition
of f and G and... | 0.003694 |
def grade(PmagRec, ACCEPT, type, data_model=2.5):
"""
Finds the 'grade' (pass/fail; A/F) of a record (specimen,sample,site) given the acceptance criteria
"""
GREATERTHAN = ['specimen_q', 'site_k', 'site_n', 'site_n_lines', 'site_int_n', 'measurement_step_min', 'specimen_int_ptrm_n', 'specimen_fvds', 'sp... | 0.00275 |
def close(self):
"""\
Closes the writer.
This method MUST be called once all vectors are added.
"""
self._mmw.fake_headers(self._num_docs+1, self._num_terms, self._num_nnz)
self._mmw.close() | 0.012552 |
def destination_absent(name, server=None):
'''
Ensures that the JMS Destination doesn't exists
name
Name of the JMS Destination
'''
ret = {'name': name, 'result': None, 'comment': None, 'changes': {}}
jms_ret = _do_element_absent(name, 'admin_object_resource', {}, server)
if not jms... | 0.001284 |
def copy_root_log_to_file(filename: str,
fmt: str = LOG_FORMAT,
datefmt: str = LOG_DATEFMT) -> None:
"""
Copy all currently configured logs to the specified file.
Should ONLY be called from the ``if __name__ == 'main'`` script;
see https://docs.python... | 0.001733 |
def concatenate_table(tup, blen=None, storage=None, create='table', **kwargs):
"""Stack tables in sequence vertically (row-wise)."""
# setup
storage = _util.get_storage(storage)
if not isinstance(tup, (tuple, list)):
raise ValueError('expected tuple or list, found %r' % tup)
if len(tup) < 2... | 0.000926 |
def Run(self, unused_arg):
"""This kills us with no cleanups."""
logging.debug("Disabling service")
msg = "Service disabled."
if hasattr(sys, "frozen"):
grr_binary = os.path.abspath(sys.executable)
elif __file__:
grr_binary = os.path.abspath(__file__)
try:
os.remove(grr_binar... | 0.009045 |
def npz_convert(self, infile, item):
"""Convert a numpy NPZ file to h5features."""
data = np.load(infile)
labels = self._labels(data)
features = data['features']
self._write(item, labels, features) | 0.008439 |
def calculate_iI_correspondence(omega):
r"""Get the correspondance between degenerate and nondegenerate schemes."""
Ne = len(omega[0])
om = omega[0][0]
correspondence = []
I = 0
for i in range(Ne):
if omega[i][0] != om:
om = omega[i][0]
I += 1
corresponden... | 0.007067 |
def models(self):
"""Unhashed"""
models_dict = OrderedDict()
collected = []
for item in standard_types:
if item in self.unordered_models:
new_dict, replacement_dict = unhash_dict(self.unordered_models[item])
models_dict[item] = new_dict
... | 0.00639 |
def run_services(config, *services, **kwargs):
""" Serves a number of services for a contextual block.
The caller can specify a number of service classes then serve them either
stopping (default) or killing them on exiting the contextual block.
Example::
with run_services(config, Foobar, Spam... | 0.00067 |
def cmdline(argv=sys.argv[1:]):
"""
Script for merging different collections of stop words.
"""
parser = ArgumentParser(
description='Create and merge collections of stop words')
parser.add_argument(
'language', help='The language used in the collection')
parser.add_argument('sou... | 0.001218 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.