text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _get_ukko_report():
'''Get Ukko's report from the fixed URL.
'''
with urllib.request.urlopen(URL_UKKO_REPORT) as response:
ret = str(response.read())
return ret | 0.005319 |
def pick(self, connections):
"""Picks a connection with the earliest backoff time.
As a result, the first connection is picked
for as long as it has no backoff time.
Otherwise, the connections are tried in a round robin fashion.
Args:
connections (:obj:list... | 0.002937 |
def joinCSVs(csvFilePaths, column, ouputFileName, separator = ',') :
"""csvFilePaths should be an iterable. Joins all CSVs according to the values in the column 'column'. Write the results in a new file 'ouputFileName' """
res = ''
legend = []
csvs = []
for f in csvFilePaths :
c = CSVFile()
c.parse(f)
cs... | 0.063041 |
def set_heartbeat(self, state):
""" Set Screen Heartbeat Display Mode """
if state in ["on", "off", "open"]:
self.heartbeat = state
self.server.request("screen_set %s heartbeat %s" % (self.ref, self.heartbeat)) | 0.011952 |
def ostype_2_json(self):
"""
transform ariane_clip3 OS Type object to Ariane server JSON obj
:return: Ariane JSON obj
"""
LOGGER.debug("OSType.ostype_2_json")
json_obj = {
'osTypeID': self.id,
'osTypeName': self.name,
'osTypeArchitectur... | 0.004132 |
def add(self, watch_key, tensor_value):
"""Add a tensor value.
Args:
watch_key: A string representing the debugger tensor watch, e.g.,
'Dense_1/BiasAdd:0:DebugIdentity'.
tensor_value: The value of the tensor as a numpy.ndarray.
"""
if watch_key not in self._tensor_data:
self._... | 0.004132 |
def render_form(form, exclude=None, **kwargs):
"""Render an entire form with Semantic UI wrappers for each field
Args:
form (form): Django Form
exclude (string): exclude fields by name, separated by commas
kwargs (dict): other attributes will be passed to fields
Returns:
string: HTML of Django F... | 0.03207 |
def start_fileoutput (self):
"""Needed to make file descriptor color aware."""
init_color = self.fd is None
super(TextLogger, self).start_fileoutput()
if init_color:
self.fd = ansicolor.Colorizer(self.fd) | 0.012097 |
def child_cardinality(self, child):
""" Return the cardinality of a child element
:param child: The name of the child element
:return: The cardinality as a 2-tuple (min, max).
The max value is either a number or the string "unbounded".
The min value is always a number.
... | 0.002247 |
def download(url):
"""输入文件url,下载该文件"""
file_name = os.path.split(url)[1]
file = urlopen(url)
with open(file_name, 'wb') as f:
f.write(file.read())
print("文件下载成功:%s " % file_name) | 0.004762 |
def is_collapsed(self, pos):
"""checks if given position is currently collapsed"""
collapsed = self._initially_collapsed(pos)
if pos in self._divergent_positions:
collapsed = not collapsed
return collapsed | 0.008032 |
def add_pre(h,sec_list,section,order_list=None,branch_order=None):
"""
A helper function that traverses a neuron's morphology (or a sub-tree)
of the morphology in pre-order. This is usually not necessary for the
user to import.
"""
sec_list.append(section)
sref = h.SectionRef(sec=section)
... | 0.018051 |
def sign(self, data, b64=True):
"""Sign data with the private key and return the signed data.
The signed data will be Base64 encoded if b64 is True.
"""
padder = padding.PKCS1v15()
signer = self.private_key.signer(padder, None)
if not isinstance(data, six.binary_type):
... | 0.00396 |
def findViewsWithAttribute(self, attr, val, root="ROOT"):
'''
Finds the Views with the specified attribute and value.
This allows you to see all items that match your criteria in the view hierarchy
Usage:
buttons = v.findViewsWithAttribute("class", "android.widget.Button")
... | 0.007538 |
def fetch_by_name(self, name):
"""
Get service for given ``name`` from memory storage.
"""
service = self.name_index.get(name)
if not service:
raise ServiceNotFound
return Service(service) | 0.008065 |
def get_anki_phrases(lang='english', limit=None):
""" Retrieve as many anki paired-statement corpora as you can for the requested language
If `ankis` (requested languages) is more than one, then get the english texts associated with those languages.
TODO: improve modularity: def function that takes a sing... | 0.005195 |
def get_code(results):
"""Determines the exit status code to be returned from a script by
inspecting the results returned from validating file(s).
Status codes are binary OR'd together, so exit codes can communicate
multiple error conditions.
"""
status = EXIT_SUCCESS
for file_result in re... | 0.003373 |
def _get_handled_methods(self, actions_map):
""" Get names of HTTP methods that can be used at requested URI.
Arguments:
:actions_map: Map of actions. Must have the same structure as
self._item_actions and self._collection_actions
"""
methods = ('OPTIONS',)
... | 0.002558 |
def project(self, id=None, *args, **kwargs):
"""
Adds a projection stage at the query
:param id: Specifies if the id is in selected fields default value is None
:param args: The list of the fields that will be project
:param kwargs: The fields that will be generated
:retu... | 0.004622 |
def vsenqueue(trg_queue, item_s, args, **kwargs):
'''Enqueue a string, or string-like object to queue with arbitrary
arguments, vsenqueue is to venqueue what vsprintf is to vprintf,
vsenqueue is to senqueue what vsprintf is to sprintf.
'''
charset = kwargs.get('charset', _c.FSQ_CHARSET)
if... | 0.003501 |
def clip_action(action, space):
"""Called to clip actions to the specified range of this policy.
Arguments:
action: Single action.
space: Action space the actions should be present in.
Returns:
Clipped batch of actions.
"""
if isinstance(space, gym.spaces.Box):
ret... | 0.001385 |
def check_smtp_domain (self, mail):
"""
Check a single mail address.
"""
from dns.exception import DNSException
log.debug(LOG_CHECK, "checking mail address %r", mail)
mail = strformat.ascii_safe(mail)
username, domain = mail.rsplit('@', 1)
log.debug(LOG_CH... | 0.003735 |
def preflightInfo(info):
"""
Returns a dict containing two items. The value for each
item will be a list of info attribute names.
================== ===
missingRequired Required data that is missing.
missingRecommended Recommended data that is missing.
================== ===
"""
... | 0.002653 |
def add(setname=None, entry=None, family='ipv4', **kwargs):
'''
Append an entry to the specified set.
CLI Example:
.. code-block:: bash
salt '*' ipset.add setname 192.168.1.26
salt '*' ipset.add setname 192.168.0.3,AA:BB:CC:DD:EE:FF
'''
if not setname:
return 'Error:... | 0.002533 |
def __get_function_or_ex_function(self, func_name):
"""
Check if a function (or an 'extended' function) exists for a key on a driver, and if it does, return it.
:param func_name: name of the function
:return: a callable or none
"""
# try function name as given
try... | 0.003881 |
def next(self):
'''
Progress to the next identifier, and return the current one.
'''
val = self._current
self._current = self.readfunc()
return val | 0.010256 |
def zip_dict(*dicts):
"""Iterate over items of dictionaries grouped by their keys."""
for key in set(itertools.chain(*dicts)): # set merge all keys
# Will raise KeyError if the dict don't have the same keys
yield key, tuple(d[key] for d in dicts) | 0.011583 |
def _validate_j2k_colorspace(self, cparams, colorspace):
"""
Cannot specify a colorspace with J2K.
"""
if cparams.codec_fmt == opj2.CODEC_J2K and colorspace is not None:
msg = 'Do not specify a colorspace when writing a raw codestream.'
raise IOError(msg) | 0.006431 |
def _get_redditor_listing(subpath=''):
"""Return function to generate Redditor listings."""
def _listing(self, sort='new', time='all', *args, **kwargs):
"""Return a get_content generator for some RedditContentObject type.
:param sort: Specify the sort order of the results if applicable
... | 0.000988 |
def update(cls, resource, params, background=False):
""" Update this IP """
cls.echo('Updating your IP')
result = cls.call('hosting.ip.update', cls.usable_id(resource),
params)
if not background:
cls.display_progress(result)
return result | 0.006329 |
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types):
"""
Returns the mean and standard deviations
"""
# Return Distance Tables
imls = self._return_tables(rctx.mag, imt, "IMLs")
# Get distance vector for the given magnitude
idx = numpy.searchsorted(... | 0.00183 |
def merge_from_obj(self, obj, lists_only=False):
"""
Merges a configuration object into this one.
See :meth:`ConfigurationObject.merge` for details.
:param obj: Values to update the ConfigurationObject with.
:type obj: ConfigurationObject
:param lists_only: Ignore singl... | 0.004357 |
def replace_header(self, _name, _value):
"""Replace a header.
Replace the first matching header found in the message, retaining
header order and case. If no matching header was found, a KeyError is
raised.
"""
_name = _name.lower()
for i, (k, v) in zip(range(len... | 0.003738 |
def convert(self, argument):
"""Returns the int value of argument."""
if _is_integer_type(argument):
return argument
elif isinstance(argument, six.string_types):
base = 10
if len(argument) > 2 and argument[0] == '0':
if argument[1] == 'o':
base = 8
elif argument[1... | 0.016032 |
def spec_fn(spec_dir='.'):
"""
Return the filename for a .spec file in this directory.
"""
specs = [f for f in os.listdir(spec_dir)
if os.path.isfile(f) and f.endswith('.spec')]
if not specs:
raise exception.SpecFileNotFound()
if len(specs) != 1:
raise exception.Mult... | 0.002778 |
def solid_angle(center, coords):
"""
Helper method to calculate the solid angle of a set of coords from the
center.
Args:
center (3x1 array): Center to measure solid angle from.
coords (Nx3 array): List of coords to determine solid angle.
Returns:
The solid angle.
"""
... | 0.003373 |
def list_motors(name_pattern=Motor.SYSTEM_DEVICE_NAME_CONVENTION, **kwargs):
"""
This is a generator function that enumerates all tacho motors that match
the provided arguments.
Parameters:
name_pattern: pattern that device name should match.
For example, 'motor*'. Default value: '*... | 0.002395 |
def memcpy_dtoh(self, dest, src):
"""perform a device to host memory copy
:param dest: A numpy array in host memory to store the data
:type dest: numpy.ndarray
:param src: An OpenCL Buffer to copy data from
:type src: pyopencl.Buffer
"""
if isinstance(src, cl.Bu... | 0.005305 |
def get_form_kwargs(self):
"""
Returns the keyword arguments for instantiating the form.
"""
kwargs = super(FormAcceptsRequestMixin, self).get_form_kwargs()
if self.form_accepts_request:
kwargs.update({'request': self.request})
return kwargs | 0.006645 |
def symlink(real_path, link_path, overwrite=False, on_error='raise',
verbose=2):
"""
Attempt to create a symbolic link.
TODO:
Can this be fixed on windows?
Args:
path (str): path to real file or directory
link_path (str): path to desired location for symlink
... | 0.000903 |
def multi_mask_sequences(records, slices):
"""
Replace characters sliced by slices with gap characters.
"""
for record in records:
record_indices = list(range(len(record)))
keep_indices = reduce(lambda i, s: i - frozenset(record_indices[s]),
slices, frozense... | 0.00198 |
def create(self, resource_id=None, attributes=None):
"""
Creates a resource with the given ID (optional) and attributes.
"""
if attributes is None:
attributes = {}
result = None
if not resource_id:
result = self.client._post(
self... | 0.002621 |
def cholesky(spatial_cov, cross_corr):
"""
Decompose the spatial covariance and cross correlation matrices.
:param spatial_cov: array of shape (M, N, N)
:param cross_corr: array of shape (M, M)
:returns: a triangular matrix of shape (M * N, M * N)
"""
M, N = spatial_cov.shape[:2]
L = nu... | 0.001344 |
def describe(self):
"""
Return basic statistics about the curve.
"""
stats = {}
stats['samples'] = self.shape[0]
stats['nulls'] = self[np.isnan(self)].shape[0]
stats['mean'] = float(np.nanmean(self.real))
stats['min'] = float(np.nanmin(self.real))
... | 0.005222 |
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
... | 0.004138 |
def save(self):
"""Save this object to the database. Behaves very similarly to
whatever collection.save(document) would, ie. does upserts on _id
presence. If methods ``pre_save`` or ``post_save`` are defined, those
are called. If there is a spec document, then the document is
... | 0.005658 |
def server(self, value):
"""
Set the connection's server property.
Args:
value: New server. String.
Returns:
Nothing.
"""
self._server = value
self._connectionXML.set('server', value) | 0.007491 |
def get_range(self, process_err_pct=0.05):
"""
Returns slant range to the object. Call once for each
new measurement at dt time from last call.
"""
vel = self.vel + 5 * randn()
alt = self.alt + 10 * randn()
self.pos += vel*self.dt
err = (self.pos * proc... | 0.004706 |
def str_def(self):
"""
:term:`string`: The exception as a string in a Python definition-style
format, e.g. for parsing by scripts:
.. code-block:: text
classname={}; read_timeout={}; read_retries={}; message={};
"""
return "classname={!r}; read_timeout={!r};... | 0.00409 |
def get_eol(self):
"""Read the next token and raise an exception if it isn't EOL or
EOF.
@raises dns.exception.SyntaxError:
@rtype: string
"""
token = self.get()
if not token.is_eol_or_eof():
raise dns.exception.SyntaxError('expected EOL or EOF, got ... | 0.007792 |
def _writeToTransport(self, data):
'''Frame the array-like thing and write it.'''
self.transport.writeData(data)
self.heartbeater.schedule() | 0.012195 |
def _set_overlay_policy_map(self, v, load=False):
"""
Setter method for overlay_policy_map, mapped from YANG variable /overlay_policy_map (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_overlay_policy_map is considered as a private
method. Backends looking to ... | 0.003335 |
def snake_case_backend_name(self):
""" CamelCase -> camel_case
"""
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', type(self).__name__)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | 0.009174 |
def _add_header_client_encryption_key(api_context, key, custom_headers):
"""
:type api_context: bunq.sdk.context.ApiContext
:type key: bytes
:type custom_headers: dict[str, str]
:rtype: None
"""
public_key_server = api_context.installation_context.public_key_server
key_cipher = PKCS1_v... | 0.001859 |
def gradient_crossplot(self, analytes=None, win=15, lognorm=True,
bins=25, filt=False, samples=None,
subset=None, figsize=(12, 12), save=False,
colourful=True, mode='hist2d', recalc=True, **kwargs):
"""
Plot analyte gradien... | 0.004637 |
def __feed_arthur(self):
""" Feed Ocean with backend data collected from arthur redis queue"""
with self.ARTHUR_FEED_LOCK:
# This is a expensive operation so don't do it always
if (time.time() - self.ARTHUR_LAST_MEMORY_CHECK) > 5 * self.ARTHUR_LAST_MEMORY_CHECK_TIME:
... | 0.004339 |
def get_instance(self, payload):
"""
Build an instance of WorkersRealTimeStatisticsInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_real_time_statistics.WorkersRealTimeStatisticsInstance
:rtype: twilio.rest... | 0.006745 |
def retryable_transaction(attempts=3, exceptions=(OperationalError,)):
"""Decorator retries a function when expected exceptions are raised."""
assert len(exceptions) > 0
assert attempts > 0
def wrapper(f):
@functools.wraps(f)
def wrapped(*args, **kwargs):
for i in xrange(att... | 0.001307 |
def binary_cross_entropy_with_logits(input_,
target,
name=PROVIDED,
loss_weight=None,
per_example_weights=None,
per_output_weights=None... | 0.004175 |
def pin_verify(self, path, *paths, **kwargs):
"""Verify that recursive pins are complete.
Scan the repo for pinned object graphs and check their integrity.
Issues will be reported back with a helpful human-readable error
message to aid in error recovery. This is useful to help recover
... | 0.001777 |
def _prev_month(self):
"""Updated calendar to show the previous month."""
self._canvas.place_forget()
self._date = self._date - self.timedelta(days=1)
self._date = self.datetime(self._date.year, self._date.month, 1)
self._build_calendar() | 0.007168 |
def _split_input_from_namespace(cls, app, namespace, entity_kind,
shard_count):
"""Helper for _split_input_from_params.
If there are not enough Entities to make all of the given shards, the
returned list of KeyRanges will include Nones. The returned list will
contain K... | 0.004612 |
def remove_hop_by_hop_headers(headers):
"""Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or
:class:`Headers` object. This operation works in-place.
.. versionadded:: 0.5
:param headers: a list or :class:`Headers` object.
"""
headers[:] = [
(key, value) for key, value in headers... | 0.002786 |
def _get_port_center_position(self, width):
"""Calculates the center position of the port rectangle
The port itself can be positioned in the corner, the center of the port rectangle however is restricted by
the width of the rectangle. This method therefore calculates the center, depending on th... | 0.003876 |
def resolve_group_to_version(self, name, value=None):
""" Pick a version from a routing group using a random or provided value
A routing group looks like (weight, version):
{"APP": [[29431330, 'A'], [82426238, 'B'], [101760716, 'C'], [118725487, 'D'], [122951927, 'E']]}
"""
... | 0.005487 |
def density_matrix(self):
"""Returns the density matrix at this step in the simulation.
The density matrix that is stored in this result is returned in the
computational basis with these basis states defined by the qubit_map.
In particular the value in the qubit_map is the index of the ... | 0.002045 |
def _build_tree_by_level(self, time_qualifier, collection_name, since):
""" method iterated thru all documents in all job collections and builds a tree of known system state"""
invalid_tree_records = dict()
invalid_tq_records = dict()
try:
job_records = self.job_dao.get_all(... | 0.006028 |
def parse_cookies(self, req, name, field):
"""Pull a value from the header data."""
cookie = req.cookies.get(name)
if cookie is not None:
return [cookie.value] if core.is_multiple(field) else cookie.value
else:
return [] if core.is_multiple(field) else None | 0.006369 |
def fix_trim_curves(obj):
""" Fixes direction, connectivity and similar issues of the trim curves.
This function works for surface trim curves consisting of a single curve.
:param obj: input surface
:type obj: abstract.Surface
"""
# Validate input
if obj.pdimension != 2:
raise Geom... | 0.000923 |
def get_db_version(session):
"""
:param session: actually it is a sqlalchemy session
:return: version number
"""
value = session.query(ProgramInformation.value).filter(ProgramInformation.name == "db_version").scalar()
return int(value) | 0.007722 |
def triangular_membership(bin_center, bin_width, smoothness = 0.5):
r"""
Create a triangular membership function for a fuzzy histogram bin.
Parameters
----------
bin_center : number
The center of the bin of which to compute the membership function.
bin_width : number
The wid... | 0.012048 |
def collapse_nodes(self, min_dist=1e-6, min_support=0):
"""
Returns a copy of the tree where internal nodes with dist <= min_dist
are deleted, resulting in a collapsed tree. e.g.:
newtre = tre.collapse_nodes(min_dist=0.001)
newtre = tre.collapse_nodes(min_support=50)
"""... | 0.003384 |
def prepare_url(self, url, params):
"""Prepares the given HTTP URL."""
url = to_native_string(url)
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and... | 0.001453 |
def __make_http_query(self, params, topkey=''):
"""
Function to covert params into url encoded query string
:param dict params: Json string sent by Authy.
:param string topkey: params key
:return string: url encoded Query.
"""
if len(params) == 0:
ret... | 0.001142 |
def baremetal(self):
"""Returns an baremetal service client"""
# TODO(d0ugal): When the ironicclient has it's own OSC plugin, the
# following client handling code should be removed in favor of the
# upstream version.
if self._baremetal is not None:
return self._bare... | 0.002663 |
def set_fact_cache(self, host, data):
'''
Set the entire fact cache data only if the fact_cache_type is 'jsonfile'
'''
if self.config.fact_cache_type != 'jsonfile':
raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ... | 0.006547 |
def value_from_object(self, obj):
"""Return value dumped to string."""
val = super(JSONField, self).value_from_object(obj)
return self.get_prep_value(val) | 0.011236 |
def disassemble(code, origin=None):
"""
Disassemble python bytecode into a series of :class:`Op` and
:class:`Label` instances.
Arguments:
code(bytes): The bytecode (a code object's ``co_code`` property). You
can also provide a function.
origin(dict): The opcode specification... | 0.000484 |
def mse(vref, vcmp):
"""
Compute Mean Squared Error (MSE) between two images.
Parameters
----------
vref : array_like
Reference image
vcmp : array_like
Comparison image
Returns
-------
x : float
MSE between `vref` and `vcmp`
"""
r = np.asarray(vref, dtype... | 0.002336 |
def emit(self, tup, **kwargs):
"""Modified emit that will not return task IDs after emitting.
See :class:`pystorm.component.Bolt` for more information.
:returns: ``None``.
"""
kwargs["need_task_ids"] = False
return super(BatchingBolt, self).emit(tup, **kwargs) | 0.006452 |
def to_backward_slashes(data):
"""
Converts forward slashes to backward slashes.
Usage::
>>> to_backward_slashes("/Users/JohnDoe/Documents")
u'\\Users\\JohnDoe\\Documents'
:param data: Data to convert.
:type data: unicode
:return: Converted path.
:rtype: unicode
"""
... | 0.002288 |
def dependencies(self, deps_dict):
"""Generate graph file with depenndencies map tree
"""
try:
import pygraphviz as pgv
except ImportError:
graph_easy, comma = "", ""
if (self.image == "ascii" and
not os.path.isfile("/usr/bin/graph-... | 0.001878 |
def compute(self):
"""
Run an iteration of this anomaly classifier
"""
result = self._constructClassificationRecord()
# Classify this point after waiting the classification delay
if result.ROWID >= self._autoDetectWaitRecords:
self._updateState(result)
# Save new classification recor... | 0.006048 |
def split_input(cls, job_config):
"""Inherit doc."""
shard_count = job_config.shard_count
params = job_config.input_reader_params
query_spec = cls._get_query_spec(params)
namespaces = None
if query_spec.ns is not None:
k_ranges = cls._to_key_ranges_by_shard(
query_spec.app, [que... | 0.007164 |
def get(self, sid):
"""
Constructs a QueryContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.query.QueryContext
:rtype: twilio.rest.autopilot.v1.assistant.query.QueryContext
"""
return QueryContext(sel... | 0.007712 |
def find_gaps(self, index=False):
"""
Finds gaps in a striplog.
Args:
index (bool): If True, returns indices of intervals with
gaps after them.
Returns:
Striplog: A striplog of all the gaps. A sort of anti-striplog.
"""
return self.__... | 0.00545 |
def getRandomWhatIf():
""" Returns a randomly generated :class:`WhatIf` object, using the Python standard library
random number generator to select the object. The object is returned
from the dictionary produced by :func:`getWhatIfArchive`; like the other What If
routines, this function is called first in order ... | 0.026923 |
def vehicle_registration_code(self, locale: Optional[str] = None) -> str:
"""Get vehicle registration code of country.
:param locale: Registration code for locale (country).
:return: Vehicle registration code.
"""
if locale:
return VRC_BY_LOCALES[locale]
ret... | 0.005682 |
def pre_scan(self):
""" Prepare string for scanning. """
escape_re = re.compile(r'\\\n[\t ]+')
self.source = escape_re.sub('', self.source) | 0.01227 |
def appendImport(self, statement):
'''append additional import statement(s).
import_stament -- tuple or list or str
'''
if type(statement) in (list,tuple):
self.extras += statement
else:
self.extras.append(statement) | 0.014235 |
def _validate_parameters(self):
"""Validate Connection Parameters.
:return:
"""
if not compatibility.is_string(self.parameters['hostname']):
raise AMQPInvalidArgument('hostname should be a string')
elif not compatibility.is_integer(self.parameters['port']):
... | 0.001818 |
def _compile_qt_resources():
"""
Compiles PyQT resources file
"""
if config.QT_RES_SRC():
epab.utils.ensure_exe('pyrcc5')
LOGGER.info('compiling Qt resources')
elib_run.run(f'pyrcc5 {config.QT_RES_SRC()} -o {config.QT_RES_TGT()}') | 0.003704 |
def get_image_file_path(instance, filename):
"""Returns a unique filename for images."""
ext = filename.split('.')[-1]
filename = '%s.%s' % (uuid.uuid4(), ext)
return os.path.join(
'user_media', str(instance.user.pk), 'images', filename) | 0.003831 |
def _ltu16(ins):
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand < 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
'''
output = _16bit_oper(ins.quad[2], ins.quad[3])
output.append('or a')
output.append(... | 0.002439 |
def _homogenize_waves(wave_a, wave_b):
"""
Generate combined independent variable vector.
The combination is from two waveforms and the (possibly interpolated)
dependent variable vectors of these two waveforms
"""
indep_vector = _get_indep_vector(wave_a, wave_b)
dep_vector_a = _interp_dep_v... | 0.002169 |
def duration(start, end=None):
"""
Returns duration in seconds since supplied time.
Note: time_delta.total_seconds() only available in python 2.7+
:param start: datetime object
:param end: Optional end datetime, None = now
:returns: Seconds as decimal since start
"""
if not end:
... | 0.002174 |
def get_utm_epsg(longitude, latitude, crs=None):
"""Return epsg code of the utm zone according to X, Y coordinates.
By default, the CRS is EPSG:4326. If the CRS is provided, first X,Y will
be reprojected from the input CRS to WGS84.
The code is based on the code:
http://gis.stackexchange.com/quest... | 0.00084 |
def dump(value: Any, **kwargs) -> Any:
"""
Quick function to dump a data structure into
something that is compatible with json or
other programs and languages.
It is useful to avoid creating the Dumper object,
in case only the default parameters are used.
"""
from . import datadumper
... | 0.002577 |
def sato(target, mol_weight='pore.molecular_weight',
boiling_temperature='pore.boiling_point',
temperature='pore.temperature',
critical_temperature='pore.critical_temperature'):
r"""
Uses Sato et al. model to estimate thermal conductivity for pure liquids
from first principles at ... | 0.000781 |
def get_declared_fields(mcs, klass, *args, **kwargs):
"""Updates declared fields with fields converted from the
Mongoengine model passed as the `model` class Meta option.
"""
declared_fields = kwargs.get('dict_class', dict)()
# Generate the fields provided through inheritance
... | 0.001552 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.