code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def distance_to_line(a, b, p):
return distance(closest_point(a, b, p), p) | Closest distance between a line segment and a point
Args:
a ([float, float]): x and y coordinates. Line start
b ([float, float]): x and y coordinates. Line end
p ([float, float]): x and y coordinates. Point to compute the distance
Returns:
float |
def group_tasks(self):
tasks = set()
for node in walk_tree(self):
for ctrl in node.controllers.values():
tasks.update(ctrl.tasks)
return tasks | All tasks in the hierarchy, affected by this group. |
def getDynMeth(name):
cname, fname = name.rsplit('.', 1)
clas = getDynLocal(cname)
if clas is None:
return None
return getattr(clas, fname, None) | Retrieve and return an unbound method by python path. |
def continuous_partition_data(data, bins='auto', n_bins=10):
if bins == 'uniform':
bins = np.linspace(start=np.min(data), stop=np.max(data), num=n_bins+1)
elif bins == 'ntile':
bins = np.percentile(data, np.linspace(
start=0, stop=100, num=n_bins+1))
elif bins != 'auto':
... | Convenience method for building a partition object on continuous data
Args:
data (list-like): The data from which to construct the estimate.
bins (string): One of 'uniform' (for uniformly spaced bins), 'ntile' (for percentile-spaced bins), or 'auto' (for automatically spaced bins)
n_bins (i... |
def _create_models_for_relation_step(self, rel_model_name,
rel_key, rel_value, model):
model = get_model(model)
lookup = {rel_key: rel_value}
rel_model = get_model(rel_model_name).objects.get(**lookup)
data = guess_types(self.hashes)
for hash_ in data:
ha... | Create a new model linked to the given model.
Syntax:
And `model` with `field` "`value`" has `new model` in the database:
Example:
.. code-block:: gherkin
And project with name "Ball Project" has goals in the database:
| description |
... |
def serverdefaults(self, force_reload=False):
if not self._server_defaults or force_reload:
request = client_proto.GetServerDefaultsRequestProto()
response = self.service.getServerDefaults(request).serverDefaults
self._server_defaults = {'blockSize': response.blockSize, 'byte... | Get server defaults, caching the results. If there are no results saved, or the force_reload flag is True,
it will query the HDFS server for its default parameter values. Otherwise, it will simply return the results
it has already queried.
Note: This function returns a copy of the results loade... |
def extract_subject_from_dn(cert_obj):
return ",".join(
"{}={}".format(
OID_TO_SHORT_NAME_DICT.get(v.oid.dotted_string, v.oid.dotted_string),
rdn_escape(v.value),
)
for v in reversed(list(cert_obj.subject))
) | Serialize a DN to a DataONE subject string.
Args:
cert_obj: cryptography.Certificate
Returns:
str:
Primary subject extracted from the certificate DN.
The certificate DN (DistinguishedName) is a sequence of RDNs
(RelativeDistinguishedName). Each RDN is a set of AVAs (AttributeValue... |
def put_admin_metadata(self, admin_metadata):
logger.debug("Putting admin metdata")
text = json.dumps(admin_metadata)
key = self.get_admin_metadata_key()
self.put_text(key, text) | Store the admin metadata. |
def connect_apps(self):
if self._connect_apps is None:
self._connect_apps = ConnectAppList(self._version, account_sid=self._solution['sid'], )
return self._connect_apps | Access the connect_apps
:returns: twilio.rest.api.v2010.account.connect_app.ConnectAppList
:rtype: twilio.rest.api.v2010.account.connect_app.ConnectAppList |
def add_segments(self, segments):
self.tracks.update([seg.track for seg in segments])
self.segments.extend(segments) | Add a list of segments to the composition
:param segments: Segments to add to composition
:type segments: list of :py:class:`radiotool.composer.Segment` |
def p_current_col(self):
"Return currnet column in line"
prefix = self.input[:self.pos]
nlidx = prefix.rfind('\n')
if nlidx == -1:
return self.pos
return self.pos - nlidx | Return currnet column in line |
def _make_win(n, mono=False):
if mono:
win = np.hanning(n) + 0.00001
else:
win = np.array([np.hanning(n) + 0.00001, np.hanning(n) + 0.00001])
win = np.transpose(win)
return win | Generate a window for a given length.
:param n: an integer for the length of the window.
:param mono: True for a mono window, False for a stereo window.
:return: an numpy array containing the window value. |
def remove(self, uid, filename=None):
if not filename:
filename = self._filename
elif filename not in self._reminders:
return
uid = uid.split('@')[0]
with self._lock:
rem = open(filename).readlines()
for (index, line) in enumerate(rem):
... | Remove the Remind command with the uid from the file |
def set_monitor_timeout(timeout, power='ac', scheme=None):
return _set_powercfg_value(
scheme=scheme,
sub_group='SUB_VIDEO',
setting_guid='VIDEOIDLE',
power=power,
value=timeout) | Set the monitor timeout in minutes for the given power scheme
Args:
timeout (int):
The amount of time in minutes before the monitor will timeout
power (str):
Set the value for AC or DC power. Default is ``ac``. Valid options
are:
- ``ac`` (AC Po... |
def _fastfood_build(args):
written_files, cookbook = food.build_cookbook(
args.config_file, args.template_pack,
args.cookbooks, args.force)
if len(written_files) > 0:
print("%s: %s files written" % (cookbook,
len(written_files)))
else:
... | Run on `fastfood build`. |
def handle_errors(f):
import traceback
from plone.jsonapi.core.helpers import error
def decorator(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception:
var = traceback.format_exc()
return error(var)
return decorator | simple JSON error handler |
def cache_control_expires(num_hours):
num_seconds = int(num_hours * 60 * 60)
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
response = func(request, *args, **kwargs)
patch_response_headers(response, num_seconds)
return response
... | Set the appropriate Cache-Control and Expires headers for the given
number of hours. |
def normalize_column_name(name):
if not isinstance(name, six.string_types):
raise ValueError('%r is not a valid column name.' % name)
name = name.strip()[:63]
if isinstance(name, six.text_type):
while len(name.encode('utf-8')) >= 64:
name = name[:len(name) - 1]
if not len(nam... | Check if a string is a reasonable thing to use as a column name. |
def get_authorization_vault_session(self):
if not self.supports_authorization_vault():
raise errors.Unimplemented()
return sessions.AuthorizationVaultSession(runtime=self._runtime) | Gets the session for retrieving authorization to vault mappings.
return: (osid.authorization.AuthorizationVaultSession) - an
``AuthorizationVaultSession``
raise: OperationFailed - unable to complete request
raise: Unimplemented - ``supports_authorization_vault()`` is
... |
def delete_operation(self, name, options=None):
request = operations_pb2.DeleteOperationRequest(name=name)
self._delete_operation(request, options) | Deletes a long-running operation. This method indicates that the client is
no longer interested in the operation result. It does not cancel the
operation. If the server doesn't support this method, it returns
``google.rpc.Code.UNIMPLEMENTED``.
Example:
>>> from google.gapic.lo... |
def builtin_info(builtin):
help_obj = load_template_help(builtin)
if help_obj.get('name') and help_obj.get('help'):
print("The %s template" % (help_obj['name']))
print(help_obj['help'])
else:
print("No help for %s" % builtin)
if help_obj.get('args'):
for arg, arg_help in ... | Show information on a particular builtin template |
def connect(self, *args, **kwargs):
self.connection = DynamoDBConnection.connect(*args, **kwargs)
self._session = kwargs.get("session")
if self._session is None:
self._session = botocore.session.get_session() | Proxy to DynamoDBConnection.connect. |
def prefixes(self, key):
res = []
index = self.dct.ROOT
if not isinstance(key, bytes):
key = key.encode('utf8')
pos = 1
for ch in key:
index = self.dct.follow_char(int_from_byte(ch), index)
if not index:
break
if sel... | Returns a list with keys of this DAWG that are prefixes of the ``key``. |
def start(backdate=None):
if f.s.cum:
raise StartError("Already have stamps, can't start again (must reset).")
if f.t.subdvsn_awaiting or f.t.par_subdvsn_awaiting:
raise StartError("Already have subdivisions, can't start again (must reset).")
if f.t.stopped:
raise StoppedError("Timer... | Mark the start of timing, overwriting the automatic start data written on
import, or the automatic start at the beginning of a subdivision.
Notes:
Backdating: For subdivisions only. Backdate time must be in the past
but more recent than the latest stamp in the parent timer.
Args:
... |
def element_exists(self, element):
if not self.__elements:
return False
for item in foundations.walkers.dictionaries_walker(self.__elements):
path, key, value = item
if key == element:
LOGGER.debug("> '{0}' attribute exists.".format(element))
... | Checks if given element exists.
Usage::
>>> plist_file_parser = PlistFileParser("standard.plist")
>>> plist_file_parser.parse()
True
>>> plist_file_parser.element_exists("String A")
True
>>> plist_file_parser.element_exists("String Nemo")... |
def _load_script(self):
script_text = filesystem.read_file(self.path, self.filename)
if not script_text:
raise IOError("Script file could not be opened or was empty: {0}"
"".format(os.path.join(self.path, self.filename)))
self.script = script_text | Loads the script from the filesystem
:raises exceptions.IOError: if the script file could not be opened |
def CountHuntResultsByType(self, hunt_id, cursor=None):
hunt_id_int = db_utils.HuntIDToInt(hunt_id)
query = ("SELECT type, COUNT(*) FROM flow_results "
"WHERE hunt_id = %s GROUP BY type")
cursor.execute(query, [hunt_id_int])
return dict(cursor.fetchall()) | Counts number of hunts results per type. |
def inserir(
self,
nome,
protegida,
descricao,
id_ligacao_front,
id_ligacao_back,
id_equipamento,
tipo=None,
vlan=None):
interface_map = dict()
interface_map['nome'] = nome
interface_map['... | Insert new interface for an equipment.
:param nome: Interface name.
:param protegida: Indication of protected ('0' or '1').
:param descricao: Interface description.
:param id_ligacao_front: Front end link interface identifier.
:param id_ligacao_back: Back end link interface iden... |
def week_date(self, start: int = 2017, end: int = 2018) -> str:
year = self.year(start, end)
week = self.random.randint(1, 52)
return '{year}-W{week}'.format(
year=year,
week=week,
) | Get week number with year.
:param start: From start.
:param end: To end.
:return: Week number. |
def asd(M1, M2):
from scipy.fftpack import fft2
spectra1 = np.abs(fft2(M1))
spectra2 = np.abs(fft2(M2))
return np.linalg.norm(spectra2 - spectra1) | Compute a Fourier transform based distance
between two matrices.
Inspired from Galiez et al., 2015
(https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4535829/) |
def xmltreefromstring(s):
if sys.version < '3':
if isinstance(s,unicode):
s = s.encode('utf-8')
try:
return ElementTree.parse(StringIO(s), ElementTree.XMLParser(collect_ids=False))
except TypeError:
return ElementTree.parse(StringIO(s), ElementTree.XMLPars... | Internal function, deals with different Python versions, unicode strings versus bytes, and with the leak bug in lxml |
def fit(self, data):
jmodel = callMLlibFunc("fitChiSqSelector", self.selectorType, self.numTopFeatures,
self.percentile, self.fpr, self.fdr, self.fwe, data)
return ChiSqSelectorModel(jmodel) | Returns a ChiSquared feature selector.
:param data: an `RDD[LabeledPoint]` containing the labeled dataset
with categorical features. Real-valued features will be
treated as categorical for each distinct value.
Apply feature discretizer before using... |
def validate_conversion_arguments(to_wrap):
@functools.wraps(to_wrap)
def wrapper(*args, **kwargs):
_assert_one_val(*args, **kwargs)
if kwargs:
_validate_supported_kwarg(kwargs)
if len(args) == 0 and "primitive" not in kwargs:
_assert_hexstr_or_text_kwarg_is_text_... | Validates arguments for conversion functions.
- Only a single argument is present
- Kwarg must be 'primitive' 'hexstr' or 'text'
- If it is 'hexstr' or 'text' that it is a text type |
def alias_activity(self, activity_id, alias_id):
self._alias_id(primary_id=activity_id, equivalent_id=alias_id) | Adds an ``Id`` to an ``Activity`` for the purpose of creating compatibility.
The primary ``Id`` of the ``Activity`` is determined by the
provider. The new ``Id`` performs as an alias to the primary
``Id``. If the alias is a pointer to another activity, it is
reassigned to the given acti... |
def CreateTypes(self, allTypes):
enumTypes, dataTypes, managedTypes = self._ConvertAllTypes(allTypes)
self._CreateAllTypes(enumTypes, dataTypes, managedTypes) | Create pyVmomi types from vmodl.reflect.DynamicTypeManager.AllTypeInfo |
def getAllNodes(self):
ret = TagCollection()
for rootNode in self.getRootNodes():
ret.append(rootNode)
ret += rootNode.getAllChildNodes()
return ret | getAllNodes - Get every element
@return TagCollection<AdvancedTag> |
def get_as_boolean(self, key):
value = self.get(key)
return BooleanConverter.to_boolean(value) | Converts map element into a boolean or returns false if conversion is not possible.
:param key: an index of element to get.
:return: boolean value ot the element or false if conversion is not supported. |
def api_params(service, file_id, owner_token, download_limit):
service += 'api/params/%s' % file_id
r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit})
r.raise_for_status()
if r.text == 'OK':
return True
return False | Change the download limit for a file hosted on a Send Server |
def __recordFmt(self):
if not self.numRecords:
self.__dbfHeader()
fmt = ''.join(['%ds' % fieldinfo[2] for fieldinfo in self.fields])
fmtSize = calcsize(fmt)
return (fmt, fmtSize) | Calculates the size of a .shp geometry record. |
def Uptime():
uptime = ''
try:
uptime = check_output(['uptime'], close_fds=True).decode('utf-8')[1:]
except Exception as e:
logger.error('Could not get current uptime ' + str(e))
return uptime | Get the current uptime information |
def add_field(self, fieldname, fieldspec=whoosh_module_fields.TEXT):
self._whoosh.add_field(fieldname, fieldspec)
return self._whoosh.schema | Add a field in the index of the model.
Args:
fieldname (Text): This parameters register a new field in specified model.
fieldspec (Name, optional): This option adds various options as were described before.
Returns:
TYPE: The new schema after deleted is returned. |
def restart_agent(self, agent_id, **kwargs):
host_medium = self.get_medium('host_agent')
agent = host_medium.get_agent()
d = host_medium.get_document(agent_id)
d.addCallback(
lambda desc: agent.start_agent(desc.doc_id, **kwargs))
return d | tells the host agent running in this agency to restart the agent. |
def summary(self, scoring):
if scoring == 'class_confusion':
print('*' * 50)
print(' Confusion Matrix ')
print('x-axis: ' + ' | '.join(list(self.class_dictionary.keys())))
print('y-axis: ' + ' | '.join(self.truth_classes))
print(self.confusion_matrix(... | Prints out the summary of validation for giving scoring function. |
def namedb_get_account_history(cur, address, offset=None, count=None):
sql = 'SELECT * FROM accounts WHERE address = ? ORDER BY block_id DESC, vtxindex DESC'
args = (address,)
if count is not None:
sql += ' LIMIT ?'
args += (count,)
if offset is not None:
sql += ' OFFSET ?'
... | Get the history of an account's tokens |
def GetPythonLibraryDirectoryPath():
path = sysconfig.get_python_lib(True)
_, _, path = path.rpartition(sysconfig.PREFIX)
if path.startswith(os.sep):
path = path[1:]
return path | Retrieves the Python library directory path. |
def _make_request_data(self, teststep_dict, entry_json):
method = entry_json["request"].get("method")
if method in ["POST", "PUT", "PATCH"]:
postData = entry_json["request"].get("postData", {})
mimeType = postData.get("mimeType")
if "text" in postData:
... | parse HAR entry request data, and make teststep request data
Args:
entry_json (dict):
{
"request": {
"method": "POST",
"postData": {
"mimeType": "application/x-www-form-urlencoded; charse... |
def in6_6to4ExtractAddr(addr):
try:
addr = inet_pton(socket.AF_INET6, addr)
except:
return None
if addr[:2] != b" \x02":
return None
return inet_ntop(socket.AF_INET, addr[2:6]) | Extract IPv4 address embbeded in 6to4 address. Passed address must be
a 6to4 addrees. None is returned on error. |
def set_cache_impl(self, cache_impl, maxsize, **kwargs):
new_cache = self._get_cache_impl(cache_impl, maxsize, **kwargs)
self._populate_new_cache(new_cache)
self.cache = new_cache | Change cache implementation. The contents of the old cache will
be transferred to the new one.
:param cache_impl: Name of cache implementation, must exist in AVAILABLE_CACHES |
def hide_announcement_view(request):
if request.method == "POST":
announcement_id = request.POST.get("announcement_id")
if announcement_id:
announcement = Announcement.objects.get(id=announcement_id)
try:
announcement.user_map.users_hidden.add(request.user)
... | Hide an announcement for the logged-in user.
announcements_hidden in the user model is the related_name for
"users_hidden" in the announcement model. |
def get_buildfile_path(settings):
base = os.path.basename(settings.build_url)
return os.path.join(BUILDS_ROOT, base) | Path to which a build tarball should be downloaded. |
def transfer(self, receiver_address, amount, sender_account):
self._keeper.token.token_approve(receiver_address, amount,
sender_account)
self._keeper.token.transfer(receiver_address, amount, sender_account) | Transfer a number of tokens from `sender_account` to `receiver_address`
:param receiver_address: hex str ethereum address to receive this transfer of tokens
:param amount: int number of tokens to transfer
:param sender_account: Account instance to take the tokens from
:return: bool |
def get_filter(filetypes, ext):
if not ext:
return ALL_FILTER
for title, ftypes in filetypes:
if ext in ftypes:
return _create_filter(title, ftypes)
else:
return '' | Return filter associated to file extension |
def purview_state(self, direction):
return {
Direction.CAUSE: self.before_state,
Direction.EFFECT: self.after_state
}[direction] | The state of the purview when we are computing coefficients in
``direction``.
For example, if we are computing the cause coefficient of a mechanism
in ``after_state``, the direction is``CAUSE`` and the ``purview_state``
is ``before_state``. |
def IterateAllClientSnapshots(self, min_last_ping=None, batch_size=50000):
all_client_ids = self.ReadAllClientIDs(min_last_ping=min_last_ping)
for batch in collection.Batch(all_client_ids, batch_size):
res = self.MultiReadClientSnapshot(batch)
for snapshot in itervalues(res):
if snapshot:
... | Iterates over all available clients and yields client snapshot objects.
Args:
min_last_ping: If provided, only snapshots for clients with last-ping
timestamps newer than (or equal to) the given value will be returned.
batch_size: Always reads <batch_size> snapshots at a time.
Yields:
... |
def run(self):
try:
threading.Thread.run(self)
except Exception:
t, v, tb = sys.exc_info()
error = traceback.format_exception_only(t, v)[0][:-1]
tback = (self.name + ' Traceback (most recent call last):\n' +
''.join(traceback.format_tb... | Version of run that traps Exceptions and stores
them in the fifo |
def search_games(self, query, live=True):
r = self.kraken_request('GET', 'search/games',
params={'query': query,
'type': 'suggest',
'live': live})
games = models.Game.wrap_search(r)
fo... | Search for games that are similar to the query
:param query: the query string
:type query: :class:`str`
:param live: If true, only returns games that are live on at least one
channel
:type live: :class:`bool`
:returns: A list of games
:rtype: :class:... |
def _print_quota(self, conn):
quota = conn.get_send_quota()
quota = quota['GetSendQuotaResponse']['GetSendQuotaResult']
print "--- SES Quota ---"
print " 24 Hour Quota: %s" % quota['Max24HourSend']
print " Sent (Last 24 hours): %s" % quota['SentLast24Hours']
print " Ma... | Prints some basic quota statistics. |
def show_deployment(name, namespace='default', **kwargs):
cfg = _setup_conn(**kwargs)
try:
api_instance = kubernetes.client.ExtensionsV1beta1Api()
api_response = api_instance.read_namespaced_deployment(name, namespace)
return api_response.to_dict()
except (ApiException, HTTPError) as... | Return the kubernetes deployment defined by name and namespace
CLI Examples::
salt '*' kubernetes.show_deployment my-nginx default
salt '*' kubernetes.show_deployment name=my-nginx namespace=default |
def set_date_bounds(self, date):
if date is not None:
split = date.split('~')
if len(split) == 1:
self._lbound = ts2dt(date)
self._rbound = ts2dt(date)
elif len(split) == 2:
if split[0] != '':
self._lbound = ... | Pass in the date used in the original query.
:param date: Date (date range) that was queried:
date -> 'd', '~d', 'd~', 'd~d'
d -> '%Y-%m-%d %H:%M:%S,%f', '%Y-%m-%d %H:%M:%S', '%Y-%m-%d' |
def has_next_page(self):
return self.current_page < math.ceil(self.total_count / self.per_page) | Whether there is a next page or not
:getter: Return true if there is a next page |
def chunk_iter(iterable, n):
assert n > 0
iterable = iter(iterable)
chunk = tuple(itertools.islice(iterable, n))
while chunk:
yield chunk
chunk = tuple(itertools.islice(iterable, n)) | Yields an iterator in chunks
For example you can do
for a, b in chunk_iter([1, 2, 3, 4, 5, 6], 2):
print('{} {}'.format(a, b))
# Prints
# 1 2
# 3 4
# 5 6
Args:
iterable - Some iterable
n - Chunk size (must be greater than 0) |
def last_timestamp(self, sid, epoch=False):
timestamp, value = self.last_datapoint(sid, epoch)
return timestamp | Get the theoretical last timestamp for a sensor
Parameters
----------
sid : str
SensorID
epoch : bool
default False
If True return as epoch
If False return as pd.Timestamp
Returns
-------
pd.Timestamp | int |
def set_comment(self,c):
c = ' '+c.replace('-','').strip()+' '
self.node.insert(0,etree.Comment(c)) | Sets the comment for the element
@type c: string
@param c: comment for the element |
def set_rules(rules, overwrite=True, use_conf=False):
init(use_conf=False)
_ENFORCER.set_rules(rules, overwrite, use_conf) | Set rules based on the provided dict of rules.
Note:
Used in tests only.
:param rules: New rules to use. It should be an instance of dict
:param overwrite: Whether to overwrite current rules or update them
with the new rules.
:param use_conf: Whether to reload rules from ... |
def get_manual_classification_line(self):
try:
text_log_error = TextLogError.objects.get(step__job=self)
except (TextLogError.DoesNotExist, TextLogError.MultipleObjectsReturned):
return None
from treeherder.model.error_summary import get_useful_search_results
sear... | If this Job has a single TextLogError line, return that TextLogError.
Some Jobs only have one related [via TextLogStep] TextLogError. This
method checks if this Job is one of those (returning None if not) by:
* checking the number of related TextLogErrors
* counting the number of searc... |
def _get_sorted_mosaics(dicom_input):
sorted_mosaics = sorted(dicom_input, key=lambda x: x.AcquisitionNumber)
for index in range(0, len(sorted_mosaics) - 1):
if sorted_mosaics[index].AcquisitionNumber >= sorted_mosaics[index + 1].AcquisitionNumber:
raise ConversionValidationError("INCONSISTE... | Search all mosaics in the dicom directory, sort and validate them |
def generate_phase_2(phase_1, dim = 40):
phase_2 = []
for i in range(dim):
indices = [numpy.random.randint(0, dim) for i in range(4)]
phase_2.append(numpy.prod([phase_1[i] for i in indices]))
return phase_2 | The second step in creating datapoints in the Poirazi & Mel model.
This takes a phase 1 vector, and creates a phase 2 vector where each point
is the product of four elements of the phase 1 vector, randomly drawn with
replacement. |
def _create_dynamic_subplots(self, key, items, ranges, **init_kwargs):
length = self.style_grouping
group_fn = lambda x: (x.type.__name__, x.last.group, x.last.label)
for i, (k, obj) in enumerate(items):
vmap = self.hmap.clone([(key, obj)])
self.map_lengths[group_fn(vmap)... | Handles the creation of new subplots when a DynamicMap returns
a changing set of elements in an Overlay. |
def apply_replacements(cfile, replacements):
if not replacements:
return cfile
for rep in replacements:
if not rep.get('with_extension', False):
cfile, cext = os.path.splitext(cfile)
else:
cfile = cfile
cext = ''
if 'is_regex' in rep and rep['i... | Applies custom replacements.
mapping(dict), where each dict contains:
'match' - filename match pattern to check against, the filename
replacement is applied.
'replacement' - string used to replace the matched part of the filename
'is_regex' - if True, the pattern is treated as a
... |
def show_dropped(self):
ctx = _find_context(self.broker)
if ctx and ctx.all_files:
ds = self.broker.get_by_type(datasource)
vals = []
for v in ds.values():
if isinstance(v, list):
vals.extend(d.path for d in v)
else:... | Show dropped files |
def encode_async_options(async):
options = copy.deepcopy(async._options)
options['_type'] = reference_to_path(async.__class__)
eta = options.get('task_args', {}).get('eta')
if eta:
options['task_args']['eta'] = time.mktime(eta.timetuple())
callbacks = async._options.get('callbacks')
if c... | Encode Async options for JSON encoding. |
def calcWeightedAvg(data,weights):
data_avg = np.mean(data,axis=1)
weighted_sum = np.dot(data_avg,weights)
return weighted_sum | Generates a weighted average of simulated data. The Nth row of data is averaged
and then weighted by the Nth element of weights in an aggregate average.
Parameters
----------
data : numpy.array
An array of data with N rows of J floats
weights : numpy.array
A length N array of weigh... |
def remove(self, method: Method):
self._table = [fld for fld in self._table if fld is not method] | Removes a `method` from the table by identity. |
def _update_from_api_repr(self, resource):
self.destination = resource["destination"]
self.filter_ = resource.get("filter")
self._writer_identity = resource.get("writerIdentity") | Helper for API methods returning sink resources. |
def connect(sock, addr):
try:
sock.connect(addr)
except ssl.SSLError as e:
return (ssl.SSLError, e.strerror if e.strerror else e.message)
except socket.herror as (_, msg):
return (socket.herror, msg)
except socket.gaierror as (_, msg):
return (socket.gaierror, msg)
ex... | Connect to some addr. |
def reverse_toctree(app, doctree, docname):
if docname == "changes":
for node in doctree.traverse():
if node.tagname == "toctree" and node.get("glob"):
node["entries"].reverse()
break | Reverse the order of entries in the root toctree if 'glob' is used. |
def get_ip(request):
if getsetting('LOCAL_GEOLOCATION_IP'):
return getsetting('LOCAL_GEOLOCATION_IP')
forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if not forwarded_for:
return UNKNOWN_IP
for ip in forwarded_for.split(','):
ip = ip.strip()
if not ip.startswith(... | Return the IP address inside the HTTP_X_FORWARDED_FOR var inside
the `request` object.
The return of this function can be overrided by the
`LOCAL_GEOLOCATION_IP` variable in the `conf` module.
This function will skip local IPs (starting with 10. and equals to
127.0.0.1). |
def parse_xml_node(self, node):
self.sequence = int(node.getAttributeNS(RTS_NS, 'sequence'))
c = node.getElementsByTagNameNS(RTS_NS, 'TargetComponent')
if c.length != 1:
raise InvalidParticipantNodeError
self.target_component = TargetExecutionContext().parse_xml_node(c[0])
... | Parse an xml.dom Node object representing a condition into this
object. |
def _perform_power_op(self, oper):
power_settings = {"Action": "Reset",
"ResetType": oper}
systems_uri = "/rest/v1/Systems/1"
status, headers, response = self._rest_post(systems_uri, None,
power_settings)
if st... | Perform requested power operation.
:param oper: Type of power button press to simulate.
Supported values: 'ON', 'ForceOff', 'ForceRestart' and
'Nmi'
:raises: IloError, on an error from iLO. |
def create_profile(self, user, save=False, **kwargs):
profile = self.get_model()(user=user, **kwargs)
if save:
profile.save()
return profile | Create a profile model.
:param user: A user object
:param save: If this is set, the profile will
be saved to DB straight away
:type save: bool |
def a1_to_rowcol(label):
m = CELL_ADDR_RE.match(label)
if m:
column_label = m.group(1).upper()
row = int(m.group(2))
col = 0
for i, c in enumerate(reversed(column_label)):
col += (ord(c) - MAGIC_NUMBER) * (26 ** i)
else:
raise IncorrectCellLabel(label)
... | Translates a cell's address in A1 notation to a tuple of integers.
:param label: A cell label in A1 notation, e.g. 'B1'.
Letter case is ignored.
:type label: str
:returns: a tuple containing `row` and `column` numbers. Both indexed
from 1 (one).
Example:
>>> a1_to... |
def btc_tx_extend(partial_tx_hex, new_inputs, new_outputs, **blockchain_opts):
tx = btc_tx_deserialize(partial_tx_hex)
tx_inputs, tx_outputs = tx['ins'], tx['outs']
locktime, version = tx['locktime'], tx['version']
tx_inputs += new_inputs
tx_outputs += new_outputs
new_tx = {
'ins': tx_in... | Given an unsigned serialized transaction, add more inputs and outputs to it.
@new_inputs and @new_outputs will be virtualchain-formatted:
* new_inputs[i] will have {'outpoint': {'index':..., 'hash':...}, 'script':..., 'witness_script': ...}
* new_outputs[i] will have {'script':..., 'value':... (in fundament... |
def getEthernetLinkStatus(self, wanInterfaceId=1, timeout=1):
namespace = Wan.getServiceType("getEthernetLinkStatus") + str(wanInterfaceId)
uri = self.getControlURL(namespace)
results = self.execute(uri, namespace, "GetEthernetLinkStatus", timeout=timeout)
return results["NewEthernetLink... | Execute GetEthernetLinkStatus action to get the status of the ethernet link.
:param int wanInterfaceId: the id of the WAN device
:param float timeout: the timeout to wait for the action to be executed
:return: status of the ethernet link
:rtype: str |
def json_hash(obj, digest=None, encoder=None):
json_str = json.dumps(obj, ensure_ascii=True, allow_nan=False, sort_keys=True, cls=encoder)
return hash_all(json_str, digest=digest) | Hashes `obj` by dumping to JSON.
:param obj: An object that can be rendered to json using the given `encoder`.
:param digest: An optional `hashlib` compatible message digest. Defaults to `hashlib.sha1`.
:param encoder: An optional custom json encoder.
:type encoder: :class:`json.JSONEncoder`
:returns: A hash... |
def _verbose(self, msg, level=log.debug):
if self.opts.get('verbose', False) is True:
self.ui.status(msg)
level(msg) | Display verbose information |
def spliced_offset(self, position):
assert type(position) == int, \
"Position argument must be an integer, got %s : %s" % (
position, type(position))
if position < self.start or position > self.end:
raise ValueError(
"Invalid position: %d (must be ... | Convert from an absolute chromosomal position to the offset into
this transcript"s spliced mRNA.
Position must be inside some exon (otherwise raise exception). |
def _normalize_address(self, region_id, relative_address, target_region=None):
if self._stack_region_map.is_empty and self._generic_region_map.is_empty:
return AddressWrapper(region_id, 0, relative_address, False, None)
if region_id.startswith('stack_'):
absolute_address = self._... | If this is a stack address, we convert it to a correct region and address
:param region_id: a string indicating which region the address is relative to
:param relative_address: an address that is relative to the region parameter
:param target_region: the ideal target region that address is norm... |
def _transform_state_to_string(self, state: State) -> str:
return ''.join(str(state[gene]) for gene in self.model.genes) | Private method which transform a state to a string.
Examples
--------
The model contains 2 genes: operon = {0, 1, 2}
mucuB = {0, 1}
>>> graph._transform_state_to_string({operon: 1, mucuB: 0})
"10"
>>> graph._transform_state_to_string... |
def put_ops(self, key, time, ops):
if self._store.get(key) is None:
self._store[key] = ops | Put an ops only if not already there, otherwise it's a no op. |
def dead_code_elimination(graph, du, ud):
for node in graph.rpo:
for i, ins in node.get_loc_with_ins():
reg = ins.get_lhs()
if reg is not None:
if (reg, i) not in du:
if ins.is_call():
ins.remove_defined_var()
... | Run a dead code elimination pass.
Instructions are checked to be dead. If it is the case, we remove them and
we update the DU & UD chains of its variables to check for further dead
instructions. |
def current_item(self):
if self._history and self._index >= 0:
self._check_index()
return self._history[self._index] | Return the current element. |
def rereference(self):
selectedItems = self.idx_l0.selectedItems()
chan_to_plot = []
for selected in selectedItems:
chan_to_plot.append(selected.text())
self.highlight_channels(self.idx_l1, chan_to_plot) | Automatically highlight channels to use as reference, based on
selected channels. |
def get_token_from_authorization_code(self,
authorization_code, redirect_uri):
token_dict = {
"client_id": self._key,
"client_secret": self._secret,
"grant_type": "authorization_code",
"code": authorization_code,
... | Like `get_token`, but using an OAuth 2 authorization code.
Use this method if you run a webserver that serves as an endpoint for
the redirect URI. The webserver can retrieve the authorization code
from the URL that is requested by ORCID.
Parameters
----------
:param red... |
def from_string(cls, xml_string, validate=True):
return xmlmap.load_xmlobject_from_string(xml_string, xmlclass=cls, validate=validate) | Creates a Python object from a XML string
:param xml_string: XML string
:param validate: XML should be validated against the embedded XSD definition
:type validate: Boolean
:returns: the Python object |
def convert(values):
dtype = values.dtype
if is_categorical_dtype(values):
return values
elif is_object_dtype(dtype):
return values.ravel().tolist()
if needs_i8_conversion(dtype):
values = values.view('i8')
v = values.ravel()
if compressor == 'zlib':
_check_zlib()... | convert the numpy values to a list |
def GetMessage(self, log_source, lcid, message_identifier):
event_log_provider_key = self._GetEventLogProviderKey(log_source)
if not event_log_provider_key:
return None
generator = self._GetMessageFileKeys(event_log_provider_key)
if not generator:
return None
message_string = None
fo... | Retrieves a specific message for a specific Event Log source.
Args:
log_source (str): Event Log source.
lcid (int): language code identifier (LCID).
message_identifier (int): message identifier.
Returns:
str: message string or None if not available. |
def remove(self, address):
recipients = []
if isinstance(address, str):
address = {address}
elif isinstance(address, (list, tuple)):
address = set(address)
for recipient in self._recipients:
if recipient.address not in address:
recipien... | Remove an address or multiple addresses
:param address: list of addresses to remove
:type address: str or list[str] |
def _updateNamespace(item, new_namespace):
temp_item = ''
i = item.tag.find('}')
if i >= 0:
temp_item = item.tag[i+1:]
else:
temp_item = item.tag
item.tag = '{{{0}}}{1}'.format(new_namespace, temp_item)
for child in item.getiterator():
if isinstance(child.tag, six.string_... | helper function to recursively update the namespaces of an item |
def conv_cond_concat(x, y):
x_shapes = x.get_shape()
y_shapes = y.get_shape()
return tf.concat(3, [x, y*tf.ones([x_shapes[0], x_shapes[1], x_shapes[2], y_shapes[3]])]) | Concatenate conditioning vector on feature map axis. |
def naturaltime(val):
val = val.replace(tzinfo=pytz.utc) \
if isinstance(val, datetime) else parse(val)
now = datetime.utcnow().replace(tzinfo=pytz.utc)
return humanize.naturaltime(now - val) | Get humanized version of time. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.