text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_public_network_ip(ips, public_subnet):
"""
Given a public subnet, chose the one IP from the remote host that exists
within the subnet range.
"""
for ip in ips:
if net.ip_in_subnet(ip, public_subnet):
return ip
msg = "IPs (%s) are not valid for any of subnet specified ... | 0.005208 |
def run(self):
"""
Writes data in JSON format into the task's output target.
The data objects have the following attributes:
* `_id` is the default Elasticsearch id field,
* `text`: the text,
* `date`: the day when the data was created.
"""
today = date... | 0.003413 |
def encode_example(self, example_data):
"""See base class for details."""
np_dtype = np.dtype(self._dtype.as_numpy_dtype)
# Convert to numpy if possible
if not isinstance(example_data, np.ndarray):
example_data = np.array(example_data, dtype=np_dtype)
# Ensure the shape and dtype match
if ... | 0.005706 |
def _interpolate_stream_track_kick(self):
"""Build interpolations of the stream track near the kick"""
if hasattr(self,'_kick_interpolatedThetasTrack'): #pragma: no cover
self._store_closest()
return None #Already did this
# Setup the trackpoints where the kick will be co... | 0.020209 |
def get_recent_matches(self, card_type="micro_card"):
"""
Calling the Recent Matches API.
Arg:
card_type: optional, default to micro_card. Accepted values are
micro_card & summary_card.
Return:
json data
"""
recent_matches_url = self.api... | 0.004049 |
def get_title(self, lang: str=None) -> Literal:
""" Get the title of the object
:param lang: Lang to retrieve
:return: Title string representation
:rtype: Literal
"""
return self.metadata.get_single(key=DC.title, lang=lang) or \
self.metadata.get_single(key=D... | 0.011765 |
def _disconnect_hanging_devices(self):
"""Periodic callback that checks for devices that haven't been used and disconnects them."""
now = monotonic()
for uuid, data in self._connections.items():
if (now - data['last_touch']) > self.client_timeout:
self._logger.info("... | 0.009747 |
def restrict_chat_member(self, *args, **kwargs):
"""See :func:`restrict_chat_member`"""
return restrict_chat_member(*args, **self._merge_overrides(**kwargs)).run() | 0.01676 |
def get_variations(self):
"""Gets the OpenType font variations for the font options object.
See :meth:`set_variations` for details about the
string format.
:return: the font variations for the font options object. The
returned string belongs to the ``options`` and must not be m... | 0.002703 |
def get_keyboard_mapping(conn):
"""
Return a keyboard mapping cookie that can be used to fetch the table of
keysyms in the current X environment.
:rtype: xcb.xproto.GetKeyboardMappingCookie
"""
mn, mx = get_min_max_keycode(conn)
return conn.core.GetKeyboardMapping(mn, mx - mn + 1) | 0.003215 |
def set_node_attributes(G, values, name=None):
"""Set node attributes from dictionary of nodes and values
Parameters
----------
G : DyNetx Graph
name : string
Attribute name
values: dict
Dictionary of attribute values keyed by node. If `values` is not... | 0.00185 |
def request_token(self) -> None:
"""
Requests a new Client Credentials Flow authentication token from the Spotify API
and stores it in the `token` property of the object.
Raises:
requests.HTTPError: If an HTTP error occurred during the request.
"""
response: ... | 0.004399 |
def values(service, id, ranges):
"""Fetch and return spreadsheet cell values with Google sheets API."""
params = {'majorDimension': 'ROWS', 'valueRenderOption': 'UNFORMATTED_VALUE',
'dateTimeRenderOption': 'FORMATTED_STRING'}
params.update(spreadsheetId=id, ranges=ranges)
response = servic... | 0.00489 |
def _stop_scan(self):
"""Stop scanning for BLE devices
"""
try:
response = self._send_command(6, 4, [])
if response.payload[0] != 0:
# Error code 129 means we just were not currently scanning
if response.payload[0] != 129:
... | 0.005298 |
def format_time_point(
time_point_string):
"""
:param str time_point_string: String representation of a time point
to format
:return: Formatted time point
:rtype: str
:raises ValueError: If *time_point_string* is not formatted by
dateutil.parser.parse
See :py:meth:`date... | 0.001613 |
def _inject_target(self, target_adaptor):
"""Inject a target, respecting all sources of dependencies."""
target_cls = self._target_types[target_adaptor.type_alias]
declared_deps = target_adaptor.dependencies
implicit_deps = (Address.parse(s,
relative_to=target_adaptor... | 0.008197 |
def del_application(self, application, sync=True):
"""
delete application from this company
:param application: the subnet to be deleted from this company
:param sync: If sync=True(default) synchronize with Ariane server. If sync=False,
add the application object on list to be re... | 0.004106 |
def nextparent(self, parent, depth):
'''
Add lines to current line by traversing the grandparent object again
and once we reach our current line counting every line that is prefixed
with the parent directory.
'''
if depth > 1: # can't jump to parent of root node!
... | 0.002167 |
def _mic_required(target_info):
"""
Checks the MsvAvFlags field of the supplied TargetInfo structure to determine in the MIC flags is set
:param target_info: The TargetInfo structure to check
:return: a boolean value indicating that the MIC flag is set
"""
if target_info is not None and target_i... | 0.00818 |
def __extract_model_summary_value(model, value):
"""
Extract a model summary field value
"""
field_value = None
if isinstance(value, _precomputed_field):
field_value = value.field
else:
field_value = model._get(value)
if isinstance(field_value, float):
try:
... | 0.004843 |
def activities_list(self, since=None, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/activity_stream#list-activities"
api_path = "/api/v2/activities.json"
api_query = {}
if "query" in kwargs.keys():
api_query.update(kwargs["query"])
del kwargs["query... | 0.00625 |
def plugin(cls, name):
"""
Retrieves the plugin based on the inputted name.
:param name | <str>
:return <Plugin>
"""
cls.loadPlugins()
plugs = getattr(cls, '_%s__plugins' % cls.__name__, {})
return plugs.get(nstr(name)) | 0.012903 |
def arg_type_to_string(arg_type) -> str:
"""
Converts the argument type to a string
:param arg_type:
:return:
String representation of the argument type. Multiple return types are
turned into a comma delimited list of type names
"""
union_params = (
getattr(arg_type, '_... | 0.001546 |
def filter(filter_creator):
"""
Creates a decorator that can be used as a filter.
.. warning::
This is currently not compatible with most other decorators, if
you are using a decorator that isn't part of `hurler` you should
take caution.
"""
filter_func = [None]
def fun... | 0.001271 |
def UNTL_to_encodedUNTL(subject):
"""Normalize a UNTL subject heading to be used in SOLR."""
subject = normalize_UNTL(subject)
subject = subject.replace(' ', '_')
subject = subject.replace('_-_', '/')
return subject | 0.004255 |
def should_compile_incrementally(self, vts, ctx):
"""Check to see if the compile should try to re-use the existing analysis.
Returns true if we should try to compile the target incrementally.
"""
if not vts.is_incremental:
return False
if not self._clear_invalid_analysis:
return True
... | 0.008287 |
def check_network_role(self, public_key):
""" Check the public key of a node on the network to see if they are
permitted to participate. The roles being checked are the
following, from first to last:
"network"
"default"
The first role that is ... | 0.001667 |
def do_delete(self, args):
'''delete the entire contents of the current namespace'''
namespace = self.config['namespace']
if not args.assume_yes:
response = raw_input('Delete everything in {0!r}? Enter namespace: '
.format(namespace))
if ... | 0.005629 |
def addVariantAnnotationSet(self, variantAnnotationSet):
"""
Adds the specified variantAnnotationSet to this dataset.
"""
id_ = variantAnnotationSet.getId()
self._variantAnnotationSetIdMap[id_] = variantAnnotationSet
self._variantAnnotationSetIds.append(id_) | 0.006536 |
def GetCellValueNoFail (self, column, row = None):
""" get a cell, if it does not exist fail
note that column at row START AT 1 same as excel
"""
if row == None:
(row, column) = ParseCellSpec(column)
cell = Get... | 0.02008 |
def exists(path):
"""Determine if a Path or string is an existing path on the file system."""
try:
return path.expanduser().absolute().exists()
except AttributeError:
return os.path.exists(os.path.abspath(os.path.expanduser(str(path)))) | 0.003788 |
def containsTie(self):
"""
Returns True if the underlying weighted majority graph contains a tie between any pair of
candidates and returns False otherwise.
"""
# If a value of 0 is present in the wmgMap, we assume that it represents a tie.
for cand in self.wmgMap.keys()... | 0.009569 |
def matrix(self):
"""Build matrix representation of Householder transformation.
Builds the matrix representation
:math:`H = I - \\beta vv^*`.
**Use with care!** This routine may be helpful for testing purposes but
should not be used in production codes for high dimensions since... | 0.004175 |
def ispercolating(am, inlets, outlets, mode='site'):
r"""
Determines if a percolating clusters exists in the network spanning
the given inlet and outlet sites
Parameters
----------
am : adjacency_matrix
The adjacency matrix with the ``data`` attribute indicating
if a bond is occ... | 0.000765 |
def to_jd(year, month, day):
'''Determine Julian day count from Islamic date'''
return (day + ceil(29.5 * (month - 1)) + (year - 1) * 354 + trunc((3 + (11 * year)) / 30) + EPOCH) - 1 | 0.010526 |
def imread(path, grayscale=False, size=None, interpolate="bilinear",
channel_first=False, as_uint16=False, num_channels=-1, **kwargs):
"""
Read image from ``path``.
If you specify the ``size``, the output array is resized.
Default output shape is (height, width, channel) for RGB image and (he... | 0.005397 |
def script_args(f):
"""single decorator for adding script args"""
args = [
magic_arguments.argument(
'--out', type=str,
help="""The variable in which to store stdout from the script.
If the script is backgrounded, this will be the stdout *pipe*,
instead of... | 0.000832 |
def plot_fit(self, **kwargs):
""" Plots the fit of the model
Returns
----------
None (plots data and the fit)
"""
import matplotlib.pyplot as plt
import seaborn as sns
figsize = kwargs.get('figsize',(10,7))
if self.latent_variables.estimated is ... | 0.010091 |
def indent(s, c=" ", n=4):
"""Indent the string 's' with the character 'c', 'n' times.
Parameters
----------
s : str
String to indent
c : str, default space
String to use as indentation
n : int, default 4
Number of chars to indent
"""
indentation = c * n
re... | 0.005305 |
def _get_commit(self):
"""
:return:
Commit object we point to, works for detached and non-detached
SymbolicReferences. The symbolic reference will be dereferenced recursively."""
obj = self._get_object()
if obj.type == 'tag':
obj = obj.object
#... | 0.007692 |
def get_bandwidth(self, cache_level, read_streams, write_streams, threads_per_core, cores=None):
"""
Return best fitting bandwidth according to number of threads, read and write streams.
:param cache_level: integer of cache (0 is L1, 1 is L2 ...)
:param read_streams: number of read stre... | 0.00424 |
def _encrypt(self, data, recipients,
default_key=None,
passphrase=None,
armor=True,
encrypt=True,
symmetric=False,
always_trust=True,
output=None,
throw_keyids=False,
... | 0.003477 |
def _all_params(arr):
"""
Ensures that the argument is a list that either is empty or contains only GPParamSpec's
:param arr: list
:return:
"""
if not isinstance([], list):
raise TypeError("non-list value found for parameters")
return all(isinstance(x,... | 0.008646 |
def execute(self, raise_on_error=True):
"Execute all the commands in the current pipeline"
stack = self.command_stack
if not stack:
return []
execute = self._execute_pipeline
conn = self.connection
if not conn:
conn = self.connection_pool.get_conn... | 0.002766 |
def get_response_code(url, timeout=10):
'''
Visit the URL and return the HTTP response code in 'int'
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except HTTPError, e:
return e.getcode()
except Exception, _:
fail("Couldn't reach the URL '%s'" % url)
else:
... | 0.005764 |
def value(self):
"""
A tuple of values. This attribute can be set with any iterable; the
iterable is then evaluated into a tuple and stored at the bound field.
Whenever values are written to this attribute, they are passed through
the :meth:`~.AbstractCDataType.coerce` method of... | 0.003231 |
def getmembers(object, predicate=None):
"""Return all members of an object as (name, value) pairs sorted by name.
Optionally, only return members that satisfy a given predicate."""
results = []
for key in dir(object):
value = getattr(object, key)
if not predicate or predicate(value):
... | 0.002532 |
def matrix_and_line_shell(figsize=(5, 12), strip=False):
"""
Helper function to construct an empty figure that has space for a matrix,
a summary line plot directly below it, a colorbar axis, and an optional
"strip" axis that parallels the matrix (and shares its y-axis) where data
can be added to cre... | 0.000576 |
def prime_gen() -> int:
# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra
"""
A generator for prime numbers starting from 2.
"""
D = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = 2 * q
... | 0.002252 |
def get_language_pack(locale):
"""Get/cache a language pack
Returns the langugage pack from cache if it exists, caches otherwise
>>> get_language_pack('fr')['Dashboards']
"Tableaux de bords"
"""
pack = ALL_LANGUAGE_PACKS.get(locale)
if not pack:
filename = DIR + '/{}/LC_MESSAGES/me... | 0.001642 |
def retrieveVals(self):
"""Retrieve values for graphs."""
if self._stats is None:
serverInfo = MemcachedInfo(self._host, self._port, self._socket_file)
stats = serverInfo.getStats()
else:
stats = self._stats
if stats is None:
raise Excepti... | 0.006601 |
def fix_bam_header(job, bamfile, sample_type, univ_options):
"""
This module modified the header in BAMFILE
ARGUMENTS
1. bamfile: <JSid for a bam file>
2. sample_type: string of 'tumor_dna' or 'normal_dna'
3. univ_options: Dict of universal arguments used by almost all tools
univ_optio... | 0.003897 |
def lifetimes(self, dates, include_start_date, country_codes):
"""
Compute a DataFrame representing asset lifetimes for the specified date
range.
Parameters
----------
dates : pd.DatetimeIndex
The dates for which to compute lifetimes.
include_start_da... | 0.000888 |
def get_empty_results(self):
"""
Because the base result type is different depending on the return structure
(e.g. list for flat, dict for object), `get_result_type` initials the
`results` variable to the proper type
"""
assert self.result_type is not None, (
... | 0.006061 |
def get_polygon(self, polygon_id):
"""
Retrieves a named polygon registered on the Agro API.
:param id: the ID of the polygon
:type id: str
:returns: a `pyowm.agro10.polygon.Polygon` object
"""
status, data = self.http_client.get_json(
NAMED_POLYGON_... | 0.004141 |
def pprint_path(path):
"""
print information of a pathlib / os.DirEntry() instance with all "is_*" functions.
"""
print("\n*** %s" % path)
for attrname in sorted(dir(path)):
if attrname.startswith("is_"):
value = getattr(path, attrname)
print("%20s: %s" % (attrname, v... | 0.005917 |
def _chunks(self, iterable, chunk_size):
"""Chunks data into chunk with size<=chunk_size."""
iterator = iter(iterable)
chunk = list(itertools.islice(iterator, 0, chunk_size))
while chunk:
yield chunk
chunk = list(itertools.islice(iterator, 0, chunk_size)) | 0.006431 |
def blank_stim(self,type=None,fill=0):
'''Makes a blank version of stim. If a type is not given, returned as same type as current stim.
If a column stim, will fill in blanks with ``fill``'''
blank = copy.copy(self)
blank.name = 'Blank'
if type==None:
type = self.type(... | 0.016355 |
def send_many(kwargs_list):
"""
Similar to mail.send(), but this function accepts a list of kwargs.
Internally, it uses Django's bulk_create command for efficiency reasons.
Currently send_many() can't be used to send emails with priority = 'now'.
"""
emails = []
for kwargs in kwargs_list:
... | 0.002457 |
def setEmissionClass(self, typeID, clazz):
"""setEmissionClass(string, string) -> None
Sets the emission class of vehicles of this type.
"""
self._connection._sendStringCmd(
tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_EMISSIONCLASS, typeID, clazz) | 0.010417 |
def drag_and_drop(self, source, target):
"""
Holds down the left mouse button on the source element,
then moves to the target element and releases the mouse button.
:Args:
- source: The element to mouse down.
- target: The element to mouse up.
"""
se... | 0.005076 |
def dump_frames(self, frame):
""" dumps frames chain in a representation suitable for serialization
and remote (debugger) client usage.
"""
current_thread = threading.currentThread()
frames = []
frame_browser = frame
# Browse the frame chain as far as... | 0.00522 |
def energy_prolongation_smoother(A, T, Atilde, B, Bf, Cpt_params,
krylov='cg', maxiter=4, tol=1e-8,
degree=1, weighting='local',
prefilter={}, postfilter={}):
"""Minimize the energy of the coarse basis functions (colu... | 0.000305 |
def p_user_add_link(self):
'''
user add link.
'''
if self.check_post_role()['ADD']:
pass
else:
return False
post_data = self.get_post_data()
post_data['user_name'] = self.get_current_user()
cur_uid = tools.get_uudd(2)
whil... | 0.003185 |
def restore_model(self, directory=None, file=None):
"""
Restore TensorFlow model. If no checkpoint file is given, the latest checkpoint is
restored. If no checkpoint directory is given, the model's default saver directory is
used (unless file specifies the entire path).
Args:
... | 0.007722 |
def process_orders(self, orderbook):
''' Default and costant orders processor. Overwrite it for more
sophisticated strategies '''
for stock, alloc in orderbook.iteritems():
self.logger.info('{}: Ordered {} {} stocks'.format(
self.datetime, stock, alloc))
i... | 0.002874 |
def _init_file(self):
"""
Initialize a new password file and set the reference password.
"""
self.keyring_key = self._get_new_password()
# set a reference password, used to check that the password provided
# matches for subsequent checks.
self.set_password('keyri... | 0.002786 |
def handle_special_cases(request, data, baseURI, meta):
"""Handle sepcial cases for returned values by the doAction function"""
if request.method == 'OPTIONS':
r = HttpResponse('')
return r
if data is None:
return gen404(request, baseURI, 'data')
if data.__class__.__name__ == ... | 0.001271 |
def remove_locations(node):
"""
Removes locations from the given AST tree completely
"""
def fix(node):
if 'lineno' in node._attributes and hasattr(node, 'lineno'):
del node.lineno
if 'col_offset' in node._attributes and hasattr(node, 'col_offset'):
del node.col... | 0.002433 |
def _apply_concretization_strategies(self, idx, strategies, action): # pylint: disable=unused-argument
"""
Applies concretization strategies on the index, until one of them succeeds.
"""
for s in strategies:
try:
idxes = s.concretize(self, idx)
ex... | 0.010081 |
def clear_published(self):
"""Removes the published status.
:raise: ``NoAccess`` -- ``Metadata.isRequired()`` is ``true`` or ``Metadata.isReadOnly()`` is ``true``
*compliance: mandatory -- This method must be implemented.*
"""
metadata = Metadata(**settings.METADATA['published... | 0.006579 |
def patches(destination, settings=None, traverse_bases=True,
filter=default_filter, recursive=True, use_decorators=True):
"""Decorator to create a patch for each member of a module or a class.
Parameters
----------
destination : object
Patch destination.
settings : gorilla.Setti... | 0.000507 |
def dump_stream(self, iterator, stream):
"""
Override because Pandas UDFs require a START_ARROW_STREAM before the Arrow stream is sent.
This should be sent after creating the first record batch so in case of an error, it can
be sent back to the JVM before the Arrow stream starts.
... | 0.006313 |
def local_self_attention_layer(hparams, prefix):
"""Create self-attention layer based on hyperparameters."""
return transformer_layers.LocalSelfAttention(
num_heads=hparams.get(prefix + "num_heads"),
num_memory_heads=hparams.get(prefix + "num_memory_heads"),
radius=hparams.local_attention_radius,
... | 0.006316 |
def _encrypt(self, archive):
"""Encrypts the compressed archive using GPG.
If encryption fails for any reason, it should be logged by sos but not
cause execution to stop. The assumption is that the unencrypted archive
would still be of use to the user, and/or that the end user has anoth... | 0.001016 |
def copy_keys(source, destination, keys=None):
"""
Add keys in source to destination
Parameters
----------
source : dict
destination: dict
keys : None | iterable
The keys in source to be copied into destination. If
None, then `keys = destination.keys()`
"""
if keys... | 0.002179 |
def from_email(self, value):
"""The email address of the sender
:param value: The email address of the sender
:type value: From, str, tuple
"""
if isinstance(value, str):
value = From(value, None)
if isinstance(value, tuple):
value = From(value[0]... | 0.005495 |
def get_wrapped_stream(stream):
"""
Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream.
:param stream: A stream instance to wrap
:returns: A new, wrapped stream
:rtype: :class:`StreamWrapper`
"""
if stream is None:
raise TypeError("must provide a st... | 0.003976 |
def num_buttons(self):
"""The number of buttons on a device with
the :attr:`~libinput.constant.DeviceCapability.TABLET_PAD` capability.
Buttons on a pad device are numbered sequentially, see
`Tablet pad button numbers`_ for details.
Returns:
int: The number of buttons supported by the device.
Raises:
... | 0.030769 |
def present(name,
user='root',
minute='*',
hour='*',
daymonth='*',
month='*',
dayweek='*',
comment=None,
commented=False,
identifier=False,
special=None):
'''
Verifies that the specified cron ... | 0.000216 |
def upload_read(infile, table):
"""
Reads a table from a MagIC upload (or downloaded) txt file, puts data in a
list of dictionaries
"""
delim = 'tab'
hold, magic_data, magic_record, magic_keys = [], [], {}, []
f = open(infile, "r")
#
# look for right table
#
line = f.readline()[:-1]
... | 0.000666 |
def unsubscribe(self, destination=None, id=None, headers=None, **keyword_headers):
"""
Unsubscribe from a destination by either id or the destination name.
:param str destination: the name of the topic or queue to unsubscribe from
:param str id: the unique identifier of the topic or que... | 0.008304 |
def normalizeURL(url):
"""Normalize a URL, converting normalization failures to
DiscoveryFailure"""
try:
normalized = urinorm.urinorm(url)
except ValueError as why:
raise DiscoveryFailure('Normalizing identifier: %s' % (why, ), None)
else:
return urllib.parse.urldefrag(normal... | 0.003049 |
def _get_by_index(self, index, path=None):
"""Returns the 2-tuple (node, idx) where node is either a terminal leaf
node containing the value of that index in either it's left or right slot,
or is the most specific node on the path which would contain the index if
it were not pruned."""
... | 0.003339 |
def dict(self):
"""
the python object for rendering json.
It is called dict to be
coherent with the other modules but it actually returns a list
:return: the python object for rendering json
:rtype: list
"""
json_list = []
for step in self.steps... | 0.005181 |
def _values(self):
"""Getter for series values (flattened)"""
if self.interpolate:
return [
val[0] for serie in self.series for val in serie.interpolated
]
else:
return super(Line, self)._values | 0.007407 |
def fit(self):
"""Fit each distribution to `data` and calculate an SSE.
WARNING: significant runtime. (~1min)
"""
# Defaults/anchors
best_sse = np.inf
best_param = (0.0, 1.0)
best_dist = scs.norm
# Compute the histogram of `x`. density=True ... | 0.000923 |
def get_shelveset(self, shelveset_id, request_data=None):
"""GetShelveset.
Get a single deep shelveset.
:param str shelveset_id: Shelveset's unique ID
:param :class:`<TfvcShelvesetRequestData> <azure.devops.v5_0.tfvc.models.TfvcShelvesetRequestData>` request_data: includeDetails, include... | 0.005544 |
def match(tgt, functions=None, opts=None):
'''
Match based on the local data store on the minion
'''
if not opts:
opts = __opts__
if functions is None:
utils = salt.loader.utils(opts)
functions = salt.loader.minion_mods(opts, utils=utils)
comps = tgt.split(':')
if len... | 0.002212 |
def get_port_channel_detail_input_request_type_get_next_request_last_aggregator_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_port_channel_detail = ET.Element("get_port_channel_detail")
config = get_port_channel_detail
input = ET.SubElem... | 0.005457 |
def _phiforce(self,R,phi=0.,t=0.):
"""
NAME:
_phiforce
PURPOSE:
evaluate the azimuthal force for this potential
INPUT:
R - Galactocentric cylindrical radius
phi - azimuth
t - time
OUTPUT:
the azimuthal force
... | 0.009509 |
def zset_score_pairs(response, **options):
"""
If ``withscores`` is specified in the options, return the response as
a list of (value, score) pairs
"""
if not response or not options['withscores']:
return response
score_cast_func = options.get('score_cast_func', float)
it = iter(resp... | 0.00266 |
def _init_auth(self, config):
""" Init authentication
@dict: configuration of ldapcherry
"""
self.auth_mode = self._get_param('auth', 'auth.mode', config)
if self.auth_mode in ['and', 'or', 'none']:
pass
elif self.auth_mode == 'custom':
# load cust... | 0.00203 |
def stop(logfile, time_format):
"stop tracking for the active project"
def save_and_output(records):
records = server.stop(records)
write(records, logfile, time_format)
def output(r):
print "worked on %s" % colored(r[0], attrs=['bold'])
print " from %s" % colored(
server.date_t... | 0.012924 |
async def get(self):
"""Printing runtime statistics in JSON"""
context_data = self.get_context_data()
context_data.update(getattr(self.request.app, "stats", {}))
response = self.json_response(context_data)
return response | 0.007605 |
def _aggregate_func(self, aggregate):
"""
Return a suitable aggregate score function.
"""
funcs = {"sum": add, "min": min, "max": max}
func_name = aggregate.lower() if aggregate else 'sum'
try:
return funcs[func_name]
except KeyError:
raise... | 0.005305 |
def freq_from_str(freq_str):
"""Obtain frequency ranges from input string, either as list or dynamic
notation.
Parameters
----------
freq_str : str
String with frequency ranges, either as a list:
e.g. [[1-3], [3-5], [5-8]];
or with a dynamic definition: (start, stop, width, ... | 0.004332 |
def select_regexes(strings, regexes):
"""
select subset of strings matching a regex
treats strings as a set
"""
strings = set(strings)
select = set()
if isinstance(strings, collections.Iterable):
for r in regexes:
s = set(filter(re.compile('^' + r + '$').search, strings))... | 0.002193 |
def reverseCommit(self):
"""
Reverse the document to the original state.
"""
print(self.after == self.before)
pos = self.qteWidget.textCursor().position()
self.qteWidget.setHtml(self.before)
self.placeCursor(pos) | 0.007463 |
def is_throttled(e):
"""
Determines whether the exception is due to API throttling.
:param e: Exception raised
:return: True if it's a throttling exception else False
"""
return True if (hasattr(e, 'response') and
e.respon... | 0.00578 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.