code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def _set_session_cookie(self):
LOGGER.debug('Setting session cookie for %s', self.session.id)
self.set_secure_cookie(name=self._session_cookie_name,
value=self.session.id,
expires=self._cookie_expiration) | Set the session data cookie. |
def _resolve_attribute(self, attribute):
value = self.attributes[attribute]
if not value:
return None
resolved_value = re.sub('\$\((.*?)\)',self._resolve_attribute_match, value)
return resolved_value | Recursively replaces references to other attributes with their value.
Args:
attribute (str): The name of the attribute to resolve.
Returns:
str: The resolved value of 'attribute'. |
def get_help_width():
if not sys.stdout.isatty() or termios is None or fcntl is None:
return _DEFAULT_HELP_WIDTH
try:
data = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, '1234')
columns = struct.unpack('hh', data)[1]
if columns >= _MIN_HELP_WIDTH:
return columns
return int(os.getenv('COLUMN... | Returns the integer width of help lines that is used in TextWrap. |
def parse_column_filters(*definitions):
fltrs = []
for def_ in _flatten(definitions):
if is_filter_tuple(def_):
fltrs.append(def_)
else:
for splitdef in DELIM_REGEX.split(def_)[::2]:
fltrs.extend(parse_column_filter(splitdef))
return fltrs | Parse multiple compound column filter definitions
Examples
--------
>>> parse_column_filters('snr > 10', 'frequency < 1000')
[('snr', <function operator.gt>, 10.), ('frequency', <function operator.lt>, 1000.)]
>>> parse_column_filters('snr > 10 && frequency < 1000')
[('snr', <function operator.... |
def _attach_new(self, records, current, touch=True):
changes = {
'attached': [],
'updated': []
}
for id, attributes in records.items():
if id not in current:
self.attach(id, attributes, touch)
changes['attached'].append(id)
... | Attach all of the IDs that aren't in the current dict. |
def match_host (host, domainlist):
if not host:
return False
for domain in domainlist:
if domain.startswith('.'):
if host.endswith(domain):
return True
elif host == domain:
return True
return False | Return True if host matches an entry in given domain list. |
def restart_user(self, subid):
if os.path.exists(self.data_base):
data_base = "%s/%s" %(self.data_base, subid)
for ext in ['revoked','finished']:
folder = "%s_%s" % (data_base, ext)
if os.path.exists(folder):
os.rename(folder, data_base)
self.l... | restart user will remove any "finished" or "revoked" extensions from
the user folder to restart the session. This command always comes from
the client users function, so we know subid does not start with the
study identifer first |
def get_me(self):
response = self.request_json(self.config['me'])
user = objects.Redditor(self, response['name'], response)
user.__class__ = objects.LoggedInRedditor
return user | Return a LoggedInRedditor object.
Note: This function is only intended to be used with an 'identity'
providing OAuth2 grant. |
def license_name(self, license_name):
allowed_values = ["CC0-1.0", "CC-BY-SA-4.0", "GPL-2.0", "ODbL-1.0", "CC-BY-NC-SA-4.0", "unknown", "DbCL-1.0", "CC-BY-SA-3.0", "copyright-authors", "other", "reddit-api", "world-bank"]
if license_name not in allowed_values:
raise ValueError(
... | Sets the license_name of this DatasetNewRequest.
The license that should be associated with the dataset # noqa: E501
:param license_name: The license_name of this DatasetNewRequest. # noqa: E501
:type: str |
def plot_eeg_erp_topo(all_epochs, colors=None):
all_evokeds = eeg_to_all_evokeds(all_epochs)
data = {}
for participant, epochs in all_evokeds.items():
for cond, epoch in epochs.items():
data[cond] = []
for participant, epochs in all_evokeds.items():
for cond, epoch in epochs.... | Plot butterfly plot.
DOCS INCOMPLETE :( |
def cl_mutect(self, params, tmp_dir):
gatk_jar = self._get_jar("muTect", ["mutect"])
jvm_opts = config_utils.adjust_opts(self._jvm_opts,
{"algorithm": {"memory_adjust":
{"magnitude": 1.1, "direction": ... | Define parameters to run the mutect paired algorithm. |
def _post_analysis(self):
self._make_completed_functions()
new_changes = self._iteratively_analyze_function_features()
functions_do_not_return = new_changes['functions_do_not_return']
self._update_function_callsites(functions_do_not_return)
for _, edges in self._pending_edges.ite... | Post-CFG-construction.
:return: None |
def scale_rc(self, servo, min, max, param):
min_pwm = self.get_mav_param('%s_MIN' % param, 0)
max_pwm = self.get_mav_param('%s_MAX' % param, 0)
if min_pwm == 0 or max_pwm == 0:
return 0
if max_pwm == min_pwm:
p = 0.0
else:
p = (servo-min_pw... | scale a PWM value |
def is_instance_throughput_too_low(self, inst_id):
r = self.instance_throughput_ratio(inst_id)
if r is None:
logger.debug("{} instance {} throughput is not "
"measurable.".format(self, inst_id))
return None
too_low = r < self.Delta
if too_... | Return whether the throughput of the master instance is greater than the
acceptable threshold |
def simplices(self):
return [Simplex([self.points[i] for i in v]) for v in self.vertices] | Returns the simplices of the triangulation. |
def run_tasks(tasks, max_workers=None, use_processes=False):
futures = set()
if use_processes:
get_executor = concurrent.futures.ProcessPoolExecutor
else:
get_executor = concurrent.futures.ThreadPoolExecutor
with get_executor(max_workers) as executor:
def execute(function, name):... | Run an iterable of tasks.
tasks: The iterable of tasks
max_workers: (optional, None) The maximum number of workers to use.
As of Python 3.5, if None is passed to the thread executor will
default to 5 * the number of processors and the process executor
will default to the number of proce... |
def get_topic_keyword_dictionary():
topic_keyword_dictionary = dict()
file_row_gen = get_file_row_generator(get_package_path() + "/twitter/res/topics/topic_keyword_mapping" + ".txt",
",",
"utf-8")
for file_row in file_row_ge... | Opens the topic-keyword map resource file and returns the corresponding python dictionary.
- Input: - file_path: The path pointing to the topic-keyword map resource file.
- Output: - topic_set: A topic to keyword python dictionary. |
def _overlap_slices(self, shape):
if len(shape) != 2:
raise ValueError('input shape must have 2 elements.')
xmin = self.bbox.ixmin
xmax = self.bbox.ixmax
ymin = self.bbox.iymin
ymax = self.bbox.iymax
if xmin >= shape[1] or ymin >= shape[0] or xmax <= 0 or ymax... | Calculate the slices for the overlapping part of the bounding
box and an array of the given shape.
Parameters
----------
shape : tuple of int
The ``(ny, nx)`` shape of array where the slices are to be
applied.
Returns
-------
slices_large... |
def get_project_endpoint_from_env(project_id=None, host=None):
project_id = project_id or os.getenv(_DATASTORE_PROJECT_ID_ENV)
if not project_id:
raise ValueError('project_id was not provided. Either pass it in '
'directly or set DATASTORE_PROJECT_ID.')
if os.getenv(_DATASTORE_HOST_ENV):
... | Get Datastore project endpoint from environment variables.
Args:
project_id: The Cloud project, defaults to the environment
variable DATASTORE_PROJECT_ID.
host: The Cloud Datastore API host to use.
Returns:
the endpoint to use, for example
https://datastore.googleapis.com/v1/projects/my-pr... |
def view(self, dtype=None):
return self._constructor(self._values.view(dtype),
index=self.index).__finalize__(self) | Create a new view of the Series.
This function will return a new Series with a view of the same
underlying values in memory, optionally reinterpreted with a new data
type. The new data type must preserve the same size in bytes as to not
cause index misalignment.
Parameters
... |
def normalized(a, axis=-1, order=2):
import numpy
l2 = numpy.atleast_1d(numpy.linalg.norm(a, order, axis))
l2[l2==0] = 1
return a / numpy.expand_dims(l2, axis) | Return normalized vector for arbitrary axis
Args
----
a: ndarray (n,3)
Tri-axial vector data
axis: int
Axis index to overwhich to normalize
order: int
Order of nomalization to calculate
Notes
-----
This function was adapted from the following StackOverflow answe... |
def _sample_weight(kappa, dim):
dim = dim - 1
b = dim / (np.sqrt(4. * kappa ** 2 + dim ** 2) + 2 * kappa)
x = (1. - b) / (1. + b)
c = kappa * x + dim * np.log(1 - x ** 2)
while True:
z = np.random.beta(dim / 2., dim / 2.)
w = (1. - (1. + b) * z) / (1. - (1. - b) * z)
u = np.r... | Rejection sampling scheme for sampling distance from center on
surface of the sphere. |
def request_vms_info(self, payload):
agent = payload.get('agent')
LOG.debug('request_vms_info: Getting VMs info for %s', agent)
req = dict(host=payload.get('agent'))
instances = self.get_vms_for_this_req(**req)
vm_info = []
for vm in instances:
vm_info.append(... | Get the VMs from the database and send the info to the agent. |
def insert_option_group(self, idx, *args, **kwargs):
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group | Insert an OptionGroup at a given position. |
def NormalizeRelativePath(path):
path_components = path.split('/')
normalized_components = []
for component in path_components:
if re.match(r'{[A-Za-z0-9_]+}$', component):
normalized_components.append(
'{%s}' % Names.CleanName(component[1:-1]))
... | Normalize camelCase entries in path. |
def GetAll(self, interface_name, *args, **kwargs):
self.log('GetAll ' + interface_name)
if not interface_name:
interface_name = self.interface
try:
return self.props[interface_name]
except KeyError:
raise dbus.exceptions.DBusException(
... | Standard D-Bus API for getting all property values |
def add(self, text, name, field, type='term', size=None, params=None):
func = None
if type == 'completion':
func = self.add_completion
elif type == 'phrase':
func = self.add_phrase
elif type == 'term':
func = self.add_term
else:
rai... | Set the suggester of given type.
:param text: text
:param name: name of suggest
:param field: field to be used
:param type: type of suggester to add, available types are: completion,
phrase, term
:param size: number of phrases
:param params: dict of ... |
def optimizer_tensor(self) -> Union[tf.Tensor, tf.Operation]:
return _get_attr(self, _optimizer_tensor=None) | The `optimizer_tensor` is an attribute for getting optimization's
optimizer tensor. |
def recv(self, timeout=None):
start = time()
time_left = timeout
while True:
msg, already_filtered = self._recv_internal(timeout=time_left)
if msg and (already_filtered or self._matches_filters(msg)):
LOG.log(self.RECV_LOGGING_LEVEL, 'Received: %s', msg)
... | Block waiting for a message from the Bus.
:type timeout: float or None
:param timeout:
seconds to wait for a message or None to wait indefinitely
:rtype: can.Message or None
:return:
None on timeout or a :class:`can.Message` object.
:raises can.CanError:... |
def parse(self):
self.tokenize()
if self.debug: print("Tokens found: %s"%self.token_list)
try:
parse_tree = self.parse2()
except Exception as e:
raise e
return parse_tree | Tokenizes and parses an arithmetic expression into a parse tree.
@return: Returns a token string.
@rtype: lems.parser.expr.ExprNode |
def FromFile(cls, filename, mime_type=None, auto_transfer=True,
gzip_encoded=False, **kwds):
path = os.path.expanduser(filename)
if not os.path.exists(path):
raise exceptions.NotFoundError('Could not find file %s' % path)
if not mime_type:
mime_type, _ = ... | Create a new Upload object from a filename. |
def got_scheduler_module_type_defined(self, module_type):
for scheduler_link in self.schedulers:
for module in scheduler_link.modules:
if module.is_a_module(module_type):
return True
return False | Check if a module type is defined in one of the schedulers
:param module_type: module type to search for
:type module_type: str
:return: True if mod_type is found else False
:rtype: bool
TODO: Factorize it with got_broker_module_type_defined |
def height_to_geopotential(height):
r
geopot = mpconsts.G * mpconsts.me * ((1 / mpconsts.Re) - (1 / (mpconsts.Re + height)))
return geopot | r"""Compute geopotential for a given height.
Parameters
----------
height : `pint.Quantity`
Height above sea level (array_like)
Returns
-------
`pint.Quantity`
The corresponding geopotential value(s)
Examples
--------
>>> from metpy.constants import g, G, me, Re
... |
def remove(self, position):
if position <= 0:
return self.remove_first()
if position >= self.length() - 1:
return self.remove_last()
counter = 0
last_node = self.head
current_node = self.head
while current_node is not None and counter <= position:
... | Removes at index
:param position: Index of removal
:return: bool: True iff removal completed successfully |
def _find_update_fields(cls, field, doc):
def find_partial_matches():
for key in doc:
if len(key) > len(field):
if key.startswith(field) and key[len(field)] == ".":
yield [key], doc[key]
elif len(key) < len(field):
... | Find the fields in the update document which match the given field.
Both the field and the top level keys in the doc may be in dot
notation, eg "a.b.c". Returns a list of tuples (path, field_value) or
the empty list if the field is not present. |
def _obtain_lock_or_raise(self):
if self._has_lock():
return
lock_file = self._lock_file_path()
if os.path.isfile(lock_file):
raise IOError("Lock for file %r did already exist, delete %r in case the lock is illegal" % (self._file_path, lock_file))
try:
... | Create a lock file as flag for other instances, mark our instance as lock-holder
:raise IOError: if a lock was already present or a lock file could not be written |
def search(self, dsl, params):
query_parameters = []
for key, value in params:
query_parameters.append(self.CITEDBY_THRIFT.kwargs(str(key), str(value)))
try:
result = self.client.search(dsl, query_parameters)
except self.CITEDBY_THRIFT.ServerError:
rai... | Free queries to ES index.
dsl (string): with DSL query
params (list): [(key, value), (key, value)]
where key is a query parameter, and value is the value required for parameter, ex: [('size', '0'), ('search_type', 'count')] |
def line(x_fn, y_fn, *, options={}, **interact_params):
fig = options.get('_fig', False) or _create_fig(options=options)
[line] = (_create_marks(fig=fig, marks=[bq.Lines], options=options))
_add_marks(fig, [line])
def wrapped(**interact_params):
x_data = util.maybe_call(x_fn, interact_params, pr... | Generates an interactive line chart that allows users to change the
parameters of the inputs x_fn and y_fn.
Args:
x_fn (Array | (*args -> Array str | Array int | Array float)):
If array, uses array values for x-coordinates.
If function, must take parameters to interact with and... |
def serialized(self, prepend_date=True):
name = self.serialized_name()
datetime = self.serialized_time(prepend_date)
return "%s %s" % (datetime, name) | Return a string fully representing the fact. |
def eeg_name_frequencies(freqs):
freqs = list(freqs)
freqs_names = []
for freq in freqs:
if freq < 1:
freqs_names.append("UltraLow")
elif freq <= 3:
freqs_names.append("Delta")
elif freq <= 7:
freqs_names.append("Theta")
elif freq <= 9:
... | Name frequencies according to standart classifications.
Parameters
----------
freqs : list or numpy.array
list of floats containing frequencies to classify.
Returns
----------
freqs_names : list
Named frequencies
Example
----------
>>> import neurokit as nk
>>>... |
def csv_to_pickle(path=ROOT / "raw", clean=False):
for file in os.listdir(path):
base, ext = os.path.splitext(file)
if ext != ".csv":
continue
LOG(f"converting {file} to pickle")
df = pd.read_csv(path / file, low_memory=True)
WRITE_DF(df, path / (base + "." + FILE... | Convert all CSV files in path to pickle. |
def angle_to_cartesian(lon, lat):
theta = np.array(np.pi / 2. - lat)
return np.vstack((np.sin(theta) * np.cos(lon),
np.sin(theta) * np.sin(lon),
np.cos(theta))).T | Convert spherical coordinates to cartesian unit vectors. |
def settings(cls):
from bernard.platforms.management import get_platform_settings
for platform in get_platform_settings():
candidate = import_class(platform['class'])
if candidate == cls:
return platform.get('settings', {}) | Find the settings for the current class inside the platforms
configuration. |
def complete_from_dir(directory):
global currDirModule
if currDirModule is not None:
if len(sys.path) > 0 and sys.path[0] == currDirModule:
del sys.path[0]
currDirModule = directory
sys.path.insert(0, directory) | This is necessary so that we get the imports from the same directory where the file
we are completing is located. |
def _extract_when(body):
when = body.get('timestamp', body.get('_context_timestamp'))
if when:
return Datatype.datetime.convert(when)
return utcnow() | Extract the generated datetime from the notification. |
def fqname_to_id(self, fq_name, type):
data = {
"type": type,
"fq_name": list(fq_name)
}
return self.post_json(self.make_url("/fqname-to-id"), data)["uuid"] | Return uuid for fq_name
:param fq_name: resource fq name
:type fq_name: FQName
:param type: resource type
:type type: str
:rtype: UUIDv4 str
:raises HttpError: fq_name not found |
def get_option_columns(self, typ, element):
inter = self.get_typ_interface(typ)
return inter.get_option_columns(element) | Return the column of the model to show for each level
Because each level might be displayed in a combobox. So you might want to provide the column
to show.
:param typ: the typ of options. E.g. Asset, Alembic, Camera etc
:type typ: str
:param element: The element for wich the op... |
def junk_folder(self):
return self.folder_constructor(parent=self, name='Junk',
folder_id=OutlookWellKnowFolderNames
.JUNK.value) | Shortcut to get Junk Folder instance
:rtype: mailbox.Folder |
def right_click_high_equalarea(self, event):
if event.LeftIsDown():
return
elif self.high_EA_setting == "Zoom":
self.high_EA_setting = "Pan"
try:
self.toolbar4.pan('off')
except TypeError:
pass
elif self.high_EA_sett... | toggles between zoom and pan effects for the high equal area on
right click
Parameters
----------
event : the wx.MouseEvent that triggered the call of this function
Alters
------
high_EA_setting, toolbar4 setting |
def plot(x, y, units='absolute', axis=None, **kwargs):
r
if axis is None:
axis = plt.gca()
if units.lower() == 'relative':
x = rel2abs_x(x, axis)
y = rel2abs_y(y, axis)
return axis.plot(x, y, **kwargs) | r'''
Plot.
:arguments:
**x, y** (``list``)
Coordinates.
:options:
**units** ([``'absolute'``] | ``'relative'``)
The type of units in which the coordinates are specified. Relative coordinates correspond to a
fraction of the relevant axis. If you use relative coordinates, be sure to set the limits and... |
def set_id_format(portal, format):
bs = portal.bika_setup
if 'portal_type' not in format:
return
logger.info("Applying format {} for {}".format(format.get('form', ''),
format.get(
'portal_type')... | Sets the id formatting in setup for the format provided |
def get_int_from_user(self, title="Enter integer value",
cond_func=lambda i: i is not None):
is_integer = False
while not is_integer:
dlg = wx.TextEntryDialog(None, title, title)
if dlg.ShowModal() == wx.ID_OK:
result = dlg.GetValue()
... | Opens an integer entry dialog and returns integer
Parameters
----------
title: String
\tDialog title
cond_func: Function
\tIf cond_func of int(<entry_value> then result is returned.
\tOtherwise the dialog pops up again. |
def _get_rh_methods(rh):
for k, v in vars(rh).items():
if all([
k in HTTP_METHODS,
is_method(v),
hasattr(v, "input_schema")
]):
yield (k, v) | Yield all HTTP methods in ``rh`` that are decorated
with schema.validate |
def generate(env):
global GhostscriptAction
try:
if GhostscriptAction is None:
GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
from SCons.Tool import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ps', GhostscriptAction)
... | Add Builders and construction variables for Ghostscript to an
Environment. |
def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None):
path = {}
data = {}
params = {}
path["group_category_id"] = group_category_id
if search_term is not None:
params["search_term"] = search_term
if unassigned is ... | List users in group category.
Returns a list of users in the group category. |
def remote_get(cwd,
remote='origin',
user=None,
password=None,
redact_auth=True,
ignore_retcode=False,
output_encoding=None):
cwd = _expand_path(cwd, user)
all_remotes = remotes(cwd,
user=user,
... | Get the fetch and push URL for a specific remote
cwd
The path to the git checkout
remote : origin
Name of the remote to query
user
User under which to run the git command. By default, the command is run
by the user under which the minion is running.
password
W... |
def solve(self, value, filter_):
try:
return value[filter_.slice or filter_.index]
except IndexError:
return None | Get slice or entry defined by an index from the given value.
Arguments
---------
value : ?
A value to solve in combination with the given filter.
filter_ : dataql.resource.SliceFilter
An instance of ``SliceFilter``to solve with the given value.
Example
... |
def tag(self, image, repository, tag=None, force=False):
params = {
'tag': tag,
'repo': repository,
'force': 1 if force else 0
}
url = self._url("/images/{0}/tag", image)
res = self._post(url, params=params)
self._raise_for_status(res)
... | Tag an image into a repository. Similar to the ``docker tag`` command.
Args:
image (str): The image to tag
repository (str): The repository to set for the tag
tag (str): The tag name
force (bool): Force
Returns:
(bool): ``True`` if successful... |
def name_without_zeroes(name):
first_zero = name.find(b'\0')
if first_zero == -1:
return name
else:
return str(name[:first_zero]) | Return a human-readable name without LSDJ's trailing zeroes.
:param name: the name from which to strip zeroes
:rtype: the name, without trailing zeroes |
def bisect(func, a, b, xtol=1e-12, maxiter=100):
fa = func(a)
if fa == 0.:
return a
fb = func(b)
if fb == 0.:
return b
assert sign(fa) != sign(fb)
for i in xrange(maxiter):
c = (a + b) / 2.
fc = func(c)
if fc == 0. or abs(b - a) / 2. < xtol:
re... | Finds the root of `func` using the bisection method.
Requirements
------------
- func must be continuous function that accepts a single number input
and returns a single number
- `func(a)` and `func(b)` must have opposite sign
Parameters
----------
func : function
the functio... |
def setup_block_and_grid(problem_size, grid_div, params, block_size_names=None):
threads = get_thread_block_dimensions(params, block_size_names)
current_problem_size = get_problem_size(problem_size, params)
grid = get_grid_dimensions(current_problem_size, params, grid_div, block_size_names)
return threa... | compute problem size, thread block and grid dimensions for this kernel |
async def print_what_is_playing(loop):
print('Discovering devices on network...')
atvs = await pyatv.scan_for_apple_tvs(loop, timeout=5)
if not atvs:
print('no device found', file=sys.stderr)
return
print('Connecting to {0}'.format(atvs[0].address))
atv = pyatv.connect_to_apple_tv(at... | Find a device and print what is playing. |
def generate_docs(app):
config = app.config
config_dir = app.env.srcdir
source_root = os.path.join(config_dir, config.apidoc_source_root)
output_root = os.path.join(config_dir, config.apidoc_output_root)
execution_dir = os.path.join(config_dir, '..')
cleanup(output_root)
command = ['sphinx-a... | Run sphinx-apidoc to generate Python API documentation for the project. |
def get_frame(self, in_data, frame_count, time_info, status):
while self.keep_listening:
try:
frame = self.queue.get(False, timeout=queue_timeout)
return (frame, pyaudio.paContinue)
except Empty:
pass
return (None, pyaudio.paComplete) | Callback function for the pyaudio stream. Don't use directly. |
def _ExtractContentFromDataStream(
self, mediator, file_entry, data_stream_name):
self.processing_status = definitions.STATUS_INDICATOR_EXTRACTING
if self._processing_profiler:
self._processing_profiler.StartTiming('extracting')
self._event_extractor.ParseDataStream(
mediator, file_entry... | Extracts content from a data stream.
Args:
mediator (ParserMediator): mediates the interactions between
parsers and other components, such as storage and abort signals.
file_entry (dfvfs.FileEntry): file entry to extract its content.
data_stream_name (str): name of the data stream whose... |
def commit_signal(data_id):
if not getattr(settings, 'FLOW_MANAGER_DISABLE_AUTO_CALLS', False):
immediate = getattr(settings, 'FLOW_MANAGER_SYNC_AUTO_CALLS', False)
async_to_sync(manager.communicate)(data_id=data_id, save_settings=False, run_sync=immediate) | Nudge manager at the end of every Data object save event. |
def is_git_repo():
cmd = "git", "rev-parse", "--git-dir"
try:
subprocess.run(cmd, stdout=subprocess.DEVNULL, check=True)
return True
except subprocess.CalledProcessError:
return False | Check whether the current folder is a Git repo. |
def set_value(*args, **kwargs):
global _config
if _config is None:
raise ValueError('configuration not set; must run figgypy.set_config first')
return _config.set_value(*args, **kwargs) | Set value in the global Config object. |
async def send(self, payload='', action_type='', channel=None, **kwds):
channel = channel or self.producer_channel
message = serialize_action(action_type=action_type, payload=payload, **kwds)
return await self._producer.send(channel, message.encode()) | This method sends a message over the kafka stream. |
def from_dict(cls, data: Dict[str, Union[str, int]]):
assert isinstance(data, dict)
if 'ensembl_id' not in data:
raise ValueError('An "ensembl_id" key is missing!')
data = dict(data)
for attr in ['name', 'chromosome', 'position', 'length',
'type', 'source... | Generate an `ExpGene` object from a dictionary.
Parameters
----------
data : dict
A dictionary with keys corresponding to attribute names.
Attributes with missing keys will be assigned `None`.
Returns
-------
`ExpGene`
The gene. |
def with_args(self, **kwargs):
new_info = mutablerecords.CopyRecord(self)
new_info.options = new_info.options.format_strings(**kwargs)
new_info.extra_kwargs.update(kwargs)
new_info.measurements = [m.with_args(**kwargs) for m in self.measurements]
return new_info | Send these keyword-arguments to the phase when called. |
def fit(self, x, fudge=1e-18):
assert x.ndim == 2
ns, nc = x.shape
x_cov = np.cov(x, rowvar=0)
assert x_cov.shape == (nc, nc)
d, v = np.linalg.eigh(x_cov)
d = np.diag(1. / np.sqrt(d + fudge))
w = np.dot(np.dot(v, d), v.T)
self._matrix = w
return w | Compute the whitening matrix.
Parameters
----------
x : array
An `(n_samples, n_channels)` array. |
def add_sub_directory(self, key, path):
sub_dir_path = os.path.join(self.results_root, path)
os.makedirs(sub_dir_path, exist_ok=True)
self._directories[key] = sub_dir_path
return sub_dir_path | Adds a sub-directory to the results directory.
Parameters
----------
key: str
A look-up key for the directory path.
path: str
The relative path from the root of the results directory to the sub-directory.
Returns
-------
str:
... |
def list(self, prefix='', delimiter='', marker='', headers=None):
return BucketListResultSet(self, prefix, delimiter, marker, headers) | List key objects within a bucket. This returns an instance of an
BucketListResultSet that automatically handles all of the result
paging, etc. from S3. You just need to keep iterating until
there are no more results.
Called with no arguments, this will return an iterator objec... |
def get_app_state():
if not hasattr(g, 'app_state'):
model = get_model()
g.app_state = {
'app_title': APP_TITLE,
'model_name': type(model).__name__,
'latest_ckpt_name': model.latest_ckpt_name,
'latest_ckpt_time': model.latest_ckpt_time
}
re... | Get current status of application in context
Returns:
:obj:`dict` of application status |
def running(opts):
ret = []
proc_dir = os.path.join(opts['cachedir'], 'proc')
if not os.path.isdir(proc_dir):
return ret
for fn_ in os.listdir(proc_dir):
path = os.path.join(proc_dir, fn_)
try:
data = _read_proc_file(path, opts)
if data is not None:
... | Return the running jobs on this minion |
def setImembPtr(self):
jseg = 0
for sec in list(self.secs.values()):
hSec = sec['hObj']
for iseg, seg in enumerate(hSec):
self.imembPtr.pset(jseg, seg._ref_i_membrane_)
jseg += 1 | Set PtrVector to point to the i_membrane_ |
def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True,
encoding=None):
root = get_etree_root(xml_file, encoding=encoding)
if check_root:
self._check_root_tag(root)
if check_version:
self._check_version(root)
entity_class... | Creates a STIX binding object from the supplied xml file.
Args:
xml_file: A filename/path or a file-like object representing a STIX
instance document
check_version: Inspect the version before parsing.
check_root: Inspect the root element before parsing.
... |
def pct_positive(self, threshold=0.0):
return np.count_nonzero(self[self > threshold]) / self.count() | Pct. of periods in which `self` is greater than `threshold.`
Parameters
----------
threshold : {float, TSeries, pd.Series}, default 0.
Returns
-------
float |
def html_error_template():
import mako.template
return mako.template.Template(r
, output_encoding=sys.getdefaultencoding(),
encoding_errors='htmlentityreplace') | Provides a template that renders a stack trace in an HTML format,
providing an excerpt of code as well as substituting source template
filenames, line numbers and code for that of the originating source
template, as applicable.
The template's default ``encoding_errors`` value is
``'htmlentityreplac... |
def trim_join_unit(join_unit, length):
if 0 not in join_unit.indexers:
extra_indexers = join_unit.indexers
if join_unit.block is None:
extra_block = None
else:
extra_block = join_unit.block.getitem_block(slice(length, None))
join_unit.block = join_unit.blo... | Reduce join_unit's shape along item axis to length.
Extra items that didn't fit are returned as a separate block. |
def info(self, section='default'):
if not section:
raise ValueError("invalid section")
fut = self.execute(b'INFO', section, encoding='utf-8')
return wait_convert(fut, parse_info) | Get information and statistics about the server.
If called without argument will return default set of sections.
For available sections, see http://redis.io/commands/INFO
:raises ValueError: if section is invalid |
def auto_slug(self):
slug = self.name
if slug is not None:
slug = slugify(slug, separator=self.SLUG_SEPARATOR)
session = sa.orm.object_session(self)
if not session:
return None
query = session.query(Entity.slug).filter(
Enti... | This property is used to auto-generate a slug from the name
attribute.
It can be customized by subclasses. |
def socket_monitor_loop(self):
try:
while True:
gevent.socket.wait_read(self.socket.fileno())
self._handle_log_rotations()
self.capture_packet()
finally:
self.clean_up() | Monitor the socket and log captured data. |
def get(self, sid):
return ApplicationContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) | Constructs a ApplicationContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.application.ApplicationContext
:rtype: twilio.rest.api.v2010.account.application.ApplicationContext |
def encode_constructor_arguments(self, args):
if self.constructor_data is None:
raise ValueError(
"The contract interface didn't have a constructor")
return encode_abi(self.constructor_data['encode_types'], args) | Return the encoded constructor call. |
def _get_geom_type(type_bytes):
high_byte = type_bytes[0]
if six.PY3:
high_byte = bytes([high_byte])
has_srid = high_byte == b'\x20'
if has_srid:
type_bytes = as_bin_str(b'\x00' + type_bytes[1:])
else:
type_bytes = as_bin_str(type_bytes)
geom_type = _BINARY_TO_GEOM_TYPE.g... | Get the GeoJSON geometry type label from a WKB type byte string.
:param type_bytes:
4 byte string in big endian byte order containing a WKB type number.
It may also contain a "has SRID" flag in the high byte (the first type,
since this is big endian byte order), indicated as 0x20. If the SR... |
def to_sky(self, wcs, origin=_DEFAULT_WCS_ORIGIN, mode=_DEFAULT_WCS_MODE):
return SkyCoord.from_pixel(
xp=self.x, yp=self.y, wcs=wcs,
origin=origin, mode=mode,
) | Convert this `PixCoord` to `~astropy.coordinates.SkyCoord`.
Calls :meth:`astropy.coordinates.SkyCoord.from_pixel`.
See parameter description there. |
def _normalize_numpy_indices(i):
if isinstance(i, np.ndarray):
if i.dtype == bool:
i = tuple(j.tolist() for j in i.nonzero())
elif i.dtype == int:
i = i.tolist()
return i | Normalize the index in case it is a numpy integer or boolean
array. |
def choose(n, k):
import scipy.misc
return scipy.misc.comb(n, k, exact=True, repetition=False) | N choose k
binomial combination (without replacement)
scipy.special.binom |
def docx_table_from_xml_node(table_node: ElementTree.Element,
level: int,
config: TextProcessingConfig) -> str:
table = CustomDocxTable()
for row_node in table_node:
if row_node.tag != DOCX_TABLE_ROW:
continue
table.new_row()
... | Converts an XML node representing a DOCX table into a textual
representation.
Args:
table_node: XML node
level: current level in XML hierarchy (used for recursion; start level
is 0)
config: :class:`TextProcessingConfig` control object
Returns:
string representat... |
def resize(self, size):
result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self,
data={ "size": size }))
self._populate(result.json)
return True | Resizes this Volume |
def get_client_settings_config_file(**kwargs):
config_files = ['/etc/softlayer.conf', '~/.softlayer']
if kwargs.get('config_file'):
config_files.append(kwargs.get('config_file'))
config_files = [os.path.expanduser(f) for f in config_files]
config = utils.configparser.RawConfigParser({
'u... | Retrieve client settings from the possible config file locations.
:param \\*\\*kwargs: Arguments that are passed into the client instance |
def get(cls, bucket, key, version_id=None):
filters = [
cls.bucket_id == as_bucket_id(bucket),
cls.key == key,
]
if version_id:
filters.append(cls.version_id == version_id)
else:
filters.append(cls.is_head.is_(True))
filters.app... | Fetch a specific object.
By default the latest object version is returned, if
``version_id`` is not set.
:param bucket: The bucket (instance or id) to get the object from.
:param key: Key of object.
:param version_id: Specific version of an object. |
def tvdb_login(api_key):
url = "https://api.thetvdb.com/login"
body = {"apikey": api_key}
status, content = _request_json(url, body=body, cache=False)
if status == 401:
raise MapiProviderException("invalid api key")
elif status != 200 or not content.get("token"):
raise MapiNetworkExc... | Logs into TVDb using the provided api key
Note: You can register for a free TVDb key at thetvdb.com/?tab=apiregister
Online docs: api.thetvdb.com/swagger#!/Authentication/post_login= |
def ValidateChildren(self, problems):
assert self._schedule, "Trip must be in a schedule to ValidateChildren"
self.ValidateNoDuplicateStopSequences(problems)
stoptimes = self.GetStopTimes(problems)
stoptimes.sort(key=lambda x: x.stop_sequence)
self.ValidateTripStartAndEndTimes(problems, stoptimes)
... | Validate StopTimes and headways of this trip. |
def serve_forever(self, poll_interval=0.5):
self.serial_port.timeout = poll_interval
while not self._shutdown_request:
try:
self.serve_once()
except (CRCError, struct.error) as e:
log.error('Can\'t handle request: {0}'.format(e))
except... | Wait for incomming requests. |
def trunc(text, length):
if length < 1:
raise ValueError("length should be 1 or larger")
text = text.strip()
text_length = wcswidth(text)
if text_length <= length:
return text
chars_to_truncate = 0
trunc_length = 0
for char in reversed(text):
chars_to_truncate += 1
... | Truncates text to given length, taking into account wide characters.
If truncated, the last char is replaced by an elipsis. |
def replace_ext(filename, ext):
if ext.startswith('.'):
ext = ext[1:]
stem, _ = os.path.splitext(filename)
return (stem + '.' + ext) | Return new pathname formed by replacing extension in `filename` with `ext`. |
def get_accuracy(targets, outputs, k=1, ignore_index=None):
n_correct = 0.0
for target, output in zip(targets, outputs):
if not torch.is_tensor(target) or is_scalar(target):
target = torch.LongTensor([target])
if not torch.is_tensor(output) or is_scalar(output):
output = ... | Get the accuracy top-k accuracy between two tensors.
Args:
targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure
saccuracy
outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector
ignore_index (int, optional): Specifies a target index that is ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.