code stringlengths 51 2.38k | docstring stringlengths 4 15.2k |
|---|---|
def pop(self):
method_frame, header, body = self.server.basic_get(queue=self.key)
if body:
return self._decode_request(body) | Pop a request |
def should_exclude(self, filename) -> bool:
for skip_glob in self.skip_globs:
if self.filename_matches_glob(filename, skip_glob):
return True
return False | Should we exclude this file from consideration? |
def get_forces(self):
forces = []
for f in self.service.request('GET', 'forces'):
forces.append(Force(self, id=f['id'], name=f['name']))
return forces | Get a list of all police forces. Uses the forces_ API call.
.. _forces: https://data.police.uk/docs/method/forces/
:rtype: list
:return: A list of :class:`forces.Force` objects (one for each police
force represented in the API) |
def get_geostationary_mask(area):
h = area.proj_dict['h']
xmax, ymax = get_geostationary_angle_extent(area)
xmax *= h
ymax *= h
x, y = area.get_proj_coords_dask()
return ((x / xmax) ** 2 + (y / ymax) ** 2) <= 1 | Compute a mask of the earth's shape as seen by a geostationary satellite
Args:
area (pyresample.geometry.AreaDefinition) : Corresponding area
definition
Returns:
Boolean mask, True inside the earth's shape, False outside. |
def bool_from_string(value):
if isinstance(value, six.string_types):
value = six.text_type(value)
else:
msg = "Unable to interpret non-string value '%s' as boolean" % (value)
raise ValueError(msg)
value = value.strip().lower()
if value in ['y', 'yes', 'true', 't', 'on']:
... | Interpret string value as boolean.
Returns True if value translates to True otherwise False. |
def multiget(self, keys, r=None, pr=None, timeout=None,
basic_quorum=None, notfound_ok=None,
head_only=False):
bkeys = [(self.bucket_type.name, self.name, key) for key in keys]
return self._client.multiget(bkeys, r=r, pr=pr, timeout=timeout,
... | Retrieves a list of keys belonging to this bucket in parallel.
:param keys: the keys to fetch
:type keys: list
:param r: R-Value for the requests (defaults to bucket's R)
:type r: integer
:param pr: PR-Value for the requests (defaults to bucket's PR)
:type pr: integer
... |
def colorize(string, stack):
codes = optimize(stack)
if len(codes):
prefix = SEQ % ';'.join(map(str, codes))
suffix = SEQ % STYLE.reset
return prefix + string + suffix
else:
return string | Apply optimal ANSI escape sequences to the string. |
def get_missing_languages(self, field_name, db_table):
db_table_fields = self.get_table_fields(db_table)
for lang_code in AVAILABLE_LANGUAGES:
if build_localized_fieldname(field_name, lang_code) not in db_table_fields:
yield lang_code | Gets only missings fields. |
def safe_cast_to_index(array: Any) -> pd.Index:
if isinstance(array, pd.Index):
index = array
elif hasattr(array, 'to_index'):
index = array.to_index()
else:
kwargs = {}
if hasattr(array, 'dtype') and array.dtype.kind == 'O':
kwargs['dtype'] = object
index... | Given an array, safely cast it to a pandas.Index.
If it is already a pandas.Index, return it unchanged.
Unlike pandas.Index, if the array has dtype=object or dtype=timedelta64,
this function will not attempt to do automatic type conversion but will
always return an index with dtype=object. |
def _to_key(d):
as_str = json.dumps(d, sort_keys=True)
return as_str.replace('"{{', '{{').replace('}}"', '}}') | Convert dict to str and enable Jinja2 template syntax. |
def encode(value, encoding='utf-8', encoding_errors='strict'):
if isinstance(value, bytes):
return value
if not isinstance(value, basestring):
value = str(value)
if isinstance(value, unicode):
value = value.encode(encoding, encoding_errors)
return value | Return a bytestring representation of the value. |
def validate(self, *args, **kwargs):
return super(ParameterValidator, self)._validate(*args, **kwargs) | Validate a parameter dict against a parameter schema from an ocrd-tool.json
Args:
obj (dict):
schema (dict): |
def add_val(self, val):
if not isinstance(val, type({})):
raise ValueError(type({}))
self.read()
self.config.update(val)
self.save() | add value in form of dict |
def set_log_type_flags(self, logType, stdoutFlag, fileFlag):
assert logType in self.__logTypeStdoutFlags.keys(), "logType '%s' not defined" %logType
assert isinstance(stdoutFlag, bool), "stdoutFlag must be boolean"
assert isinstance(fileFlag, bool), "fileFlag must be boolean"
self.__logT... | Set a defined log type flags.
:Parameters:
#. logType (string): A defined logging type.
#. stdoutFlag (boolean): Whether to log to the standard output stream.
#. fileFlag (boolean): Whether to log to to file. |
def get_attribute(json, attr):
res = [json[entry][attr] for entry, _ in enumerate(json)]
logger.debug('{0}s (from JSON):\n{1}'.format(attr, res))
return res | Gets the values of an attribute from JSON
Args:
json: JSON data as a list of dict dates, where the keys are
the raw market statistics.
attr: String of attribute in JSON file to collect.
Returns:
List of values of specified attribute from JSON |
def new_children(self, **kwargs):
for k, v in kwargs.items():
self.new_child(k, v)
return self | Create new children from kwargs |
def query(self, query_data, k=10, queue_size=5.0):
query_data = np.asarray(query_data).astype(np.float32)
init = initialise_search(
self._rp_forest,
self._raw_data,
query_data,
int(k * queue_size),
self._random_init,
self._tree_init... | Query the training data for the k nearest neighbors
Parameters
----------
query_data: array-like, last dimension self.dim
An array of points to query
k: integer (default = 10)
The number of nearest neighbors to return
queue_size: float (default 5.0)
... |
def register_interaction(key=None):
def wrap(interaction):
name = key if key is not None else interaction.__module__ + \
interaction.__name__
interaction.types[name] = interaction
return interaction
return wrap | Decorator registering an interaction class in the registry.
If no key is provided, the class name is used as a key. A key is provided
for each core bqplot interaction type so that the frontend can use this
key regardless of the kernal language. |
def value(self):
try:
res = self.properties.device.properties.network.read(
"{} {} {} presentValue".format(
self.properties.device.properties.address,
self.properties.type,
str(self.properties.address),
)
... | Read the value from BACnet network |
def opendocs(where='index', how='default'):
import webbrowser
docs_dir = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'docs')
index = os.path.join(docs_dir, '_build/html/%s.html' % where)
builddocs('html')
url = 'file://%s' % os.path.abspath(index)
if how in ('d', 'd... | Rebuild documentation and opens it in your browser.
Use the first argument to specify how it should be opened:
`d` or `default`: Open in new tab or new window, using the default
method of your browser.
`t` or `tab`: Open documentation in new tab.
`n`, `w` or `window`: Open docume... |
def _get_title(self, prop, main_infos, info_dict):
result = main_infos.get('label')
if result is None:
result = info_dict.get('colanderalchemy', {}).get('title')
if result is None:
result = prop.key
return result | Return the title configured as in colanderalchemy |
def _ReferenceFromSerialized(serialized):
if not isinstance(serialized, basestring):
raise TypeError('serialized must be a string; received %r' % serialized)
elif isinstance(serialized, unicode):
serialized = serialized.encode('utf8')
return entity_pb.Reference(serialized) | Construct a Reference from a serialized Reference. |
def set_text(self, text="YEAH."):
s = str(text)
if not s == self.get_text(): self._widget.setText(str(text))
return self | Sets the current value of the text box. |
def set_computer_name(name):
if six.PY2:
name = _to_unicode(name)
if windll.kernel32.SetComputerNameExW(
win32con.ComputerNamePhysicalDnsHostname, name):
ret = {'Computer Name': {'Current': get_computer_name()}}
pending = get_pending_computer_name()
if pending not in ... | Set the Windows computer name
Args:
name (str):
The new name to give the computer. Requires a reboot to take effect.
Returns:
dict:
Returns a dictionary containing the old and new names if successful.
``False`` if not.
CLI Example:
.. code-block::... |
async def delete(
self, name: str, *, force: bool = False, noprune: bool = False
) -> List:
params = {"force": force, "noprune": noprune}
response = await self.docker._query_json(
"images/{name}".format(name=name), "DELETE", params=params
)
return response | Remove an image along with any untagged parent
images that were referenced by that image
Args:
name: name/id of the image to delete
force: remove the image even if it is being used
by stopped containers or has other tags
noprune: don't delete untag... |
def rename_db_ref(stmts_in, ns_from, ns_to, **kwargs):
logger.info('Remapping "%s" to "%s" in db_refs on %d statements...' %
(ns_from, ns_to, len(stmts_in)))
stmts_out = [deepcopy(st) for st in stmts_in]
for stmt in stmts_out:
for agent in stmt.agent_list():
if agent is n... | Rename an entry in the db_refs of each Agent.
This is particularly useful when old Statements in pickle files
need to be updated after a namespace was changed such as
'BE' to 'FPLX'.
Parameters
----------
stmts_in : list[indra.statements.Statement]
A list of statements whose Agents' db... |
def page_should_contain_element(self, locator, loglevel='INFO'):
if not self._is_element_present(locator):
self.log_source(loglevel)
raise AssertionError("Page should have contained element '%s' "
"but did not" % locator)
self._info("Current ... | Verifies that current page contains `locator` element.
If this keyword fails, it automatically logs the page source
using the log level specified with the optional `loglevel` argument.
Giving `NONE` as level disables logging. |
def transform_using_this_method(original_sample):
new_sample = original_sample.copy()
new_data = new_sample.data
new_data['Y2-A'] = log(new_data['Y2-A'])
new_data = new_data.dropna()
new_sample.data = new_data
return new_sample | This function implements a log transformation on the data. |
def snapshot_agents(self, force=False):
for agent in self._agents:
agent.check_if_should_snapshot(force) | snapshot agents if number of entries from last snapshot if greater
than 1000. Use force=True to override. |
def react_to_event(self, event):
if not react_to_event(self.view, self.view.editor, event):
return False
if not rafcon.gui.singleton.state_machine_manager_model.selected_state_machine_id == \
self.model.state_machine.state_machine_id:
return False
return T... | Check whether the given event should be handled
Checks, whether the editor widget has the focus and whether the selected state machine corresponds to the
state machine of this editor.
:param event: GTK event object
:return: True if the event should be handled, else False
:rtype... |
def _pidExists(pid):
assert pid > 0
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
return False
else:
raise
else:
return True | This will return True if the process associated with pid is still running on the machine.
This is based on stackoverflow question 568271.
:param int pid: ID of the process to check for
:return: True/False
:rtype: bool |
def get_user_subadmin_groups(self, user_name):
res = self._make_ocs_request(
'GET',
self.OCS_SERVICE_CLOUD,
'users/' + user_name + '/subadmins',
)
if res.status_code == 200:
tree = ET.fromstring(res.content)
self._check_ocs_status(tree,... | Get a list of subadmin groups associated to a user.
:param user_name: name of user
:returns: list of subadmin groups
:raises: HTTPResponseError in case an HTTP error status was returned |
def set(self, varname, value, idx=0, units=None):
if not varname in self.mapping.vars:
raise fgFDMError('Unknown variable %s' % varname)
if idx >= self.mapping.vars[varname].arraylength:
raise fgFDMError('index of %s beyond end of array idx=%u arraylength=%u' % (
... | set a variable value |
def scan(self, t, dt=None, aggfunc=None):
idx = (np.abs(self.index - t)).argmin()
if dt is None:
mz_abn = self.values[idx, :].copy()
else:
en_idx = (np.abs(self.index - t - dt)).argmin()
idx, en_idx = min(idx, en_idx), max(idx, en_idx)
if aggfunc i... | Returns the spectrum from a specific time.
Parameters
----------
t : float
dt : float |
def scrape(url, params=None, user_agent=None):
headers = {}
if user_agent:
headers['User-Agent'] = user_agent
data = params and six.moves.urllib.parse.urlencode(params) or None
req = six.moves.urllib.request.Request(url, data=data, headers=headers)
f = six.moves.urllib.request.urlopen(req)
... | Scrape a URL optionally with parameters.
This is effectively a wrapper around urllib2.urlopen. |
async def workerType(self, *args, **kwargs):
return await self._makeApiCall(self.funcinfo["workerType"], *args, **kwargs) | Get Worker Type
Retrieve a copy of the requested worker type definition.
This copy contains a lastModified field as well as the worker
type name. As such, it will require manipulation to be able to
use the results of this method to submit date to the update
method.
Thi... |
def register(self, name, asymmetric=False):
def register_func(func):
if asymmetric:
self._asymmetric.append(name)
self.store[name] = func
return func
return register_func | Decorator for registering a measure with PyPhi.
Args:
name (string): The name of the measure.
Keyword Args:
asymmetric (boolean): ``True`` if the measure is asymmetric. |
def stop(self):
res = self.send_request('manager/stop', post=True)
if res.status_code != 200:
raise UnexpectedResponse(
'Attempted to stop manager. {res_code}: {res_text}'.format(
res_code=res.status_code,
res_text=res.text,
... | If the manager is running, tell it to stop its process |
def _extractErrorString(request):
errorStr = ""
tag = None
try:
root = ET.fromstring(request.text.encode('utf-8'))
tag = root[0][0]
except:
return errorStr
for element in tag.getiterator():
tagName = element.tag.lower()
... | Extract error string from a failed UPnP call.
:param request: the failed request result
:type request: requests.Response
:return: an extracted error text or empty str
:rtype: str |
def getEmailTemplate(request):
if request.method != 'POST':
return HttpResponse(_('Error, no POST data.'))
if not hasattr(request,'user'):
return HttpResponse(_('Error, not authenticated.'))
template_id = request.POST.get('template')
if not template_id:
return HttpResponse... | This function handles the Ajax call made when a user wants a specific email template |
def update_text(self, mapping):
found = False
for node in self._page.iter("*"):
if node.text or node.tail:
for old, new in mapping.items():
if node.text and old in node.text:
node.text = node.text.replace(old, new)
... | Iterate over nodes, replace text with mapping |
def style(theme=None, context='paper', grid=True, gridlines=u'-', ticks=False, spines=True, fscale=1.2, figsize=(8., 7.)):
rcdict = set_context(context=context, fscale=fscale, figsize=figsize)
if theme is None:
theme = infer_theme()
set_style(rcdict, theme=theme, grid=grid, gridlines=gridlines, tick... | main function for styling matplotlib according to theme
::Arguments::
theme (str): 'oceans16', 'grade3', 'chesterish', 'onedork', 'monokai', 'solarizedl', 'solarizedd'. If no theme name supplied the currently installed notebook theme will be used.
context (str): 'paper' (Default), 'notebook', 'tal... |
def is_subdir(a, b):
a, b = map(os.path.abspath, [a, b])
return os.path.commonpath([a, b]) == b | Return true if a is a subdirectory of b |
def _state_invalid(self):
for statemanager, conditions in self.statetransition.transitions.items():
current_state = getattr(self.obj, statemanager.propname)
if conditions['from'] is None:
state_valid = True
else:
mstate = conditions['from'].get... | If the state is invalid for the transition, return details on what didn't match
:return: Tuple of (state manager, current state, label for current state) |
def getfieldindex(data, commdct, objkey, fname):
objindex = data.dtls.index(objkey)
objcomm = commdct[objindex]
for i_index, item in enumerate(objcomm):
try:
if item['field'] == [fname]:
break
except KeyError as err:
pass
return i_index | given objkey and fieldname, return its index |
def __parseParameters(self):
self.__parameters = []
for parameter in self.__data['parameters']:
self.__parameters.append(Parameter(parameter)) | Parses the parameters of data. |
def validate(self):
msg = list()
previously_seen = set()
currently_seen = set([1])
problemset = set()
while currently_seen:
node = currently_seen.pop()
if node in previously_seen:
problemset.add(node)
else:
previ... | Simulataneously checks for loops and unreachable nodes |
def _cast_to_pod(val):
bools = {"True": True, "False": False}
if val in bools:
return bools[val]
try:
return int(val)
except ValueError:
try:
return float(val)
except ValueError:
return tf.compat.as_text(val) | Try cast to int, float, bool, str, in that order. |
def add_model(self, model):
if model.identity not in self._models.keys():
self._models[model.identity] = model
else:
raise ValueError("{} has already been defined".format(model.identity)) | Add a model to the document |
def get_full_url(self, url):
request = Request('GET', url)
preparedrequest = self.session.prepare_request(request)
return preparedrequest.url | Get full url including any additional parameters
Args:
url (str): URL for which to get full url
Returns:
str: Full url including any additional parameters |
def os_info():
stype = ""
slack, ver = slack_ver()
mir = mirror()
if mir:
if "current" in mir:
stype = "Current"
else:
stype = "Stable"
info = (
"User: {0}\n"
"OS: {1}\n"
"Version: {2}\n"
"Type: {3}\n"
"Arch: {4}\n"
... | Get OS info |
def downsample_with_striding(array, factor):
return array[tuple(np.s_[::f] for f in factor)] | Downsample x by factor using striding.
@return: The downsampled array, of the same type as x. |
def search_text(self, text, encoding = "utf-16le",
caseSensitive = False,
minAddr = None,
maxAddr = None):
pattern = TextPattern(text, encoding, caseSensitive)
matches = Search.search_process(self, pattern, m... | Search for the given text within the process memory.
@type text: str or compat.unicode
@param text: Text to search for.
@type encoding: str
@param encoding: (Optional) Encoding for the text parameter.
Only used when the text to search for is a Unicode string.
... |
def join(self, *args):
call_args = list(args)
joiner = call_args.pop(0)
self.random.shuffle(call_args)
return joiner.join(call_args) | Returns the arguments in the list joined by STR.
FIRST,JOIN_BY,ARG_1,...,ARG_N
%{JOIN: ,A,...,F} -> 'A B C ... F' |
def is_processed(self, db_versions):
return self.number in (v.number for v in db_versions if v.date_done) | Check if version is already applied in the database.
:param db_versions: |
def load():
plugins = []
for filename in os.listdir(PLUGINS_PATH):
if not filename.endswith(".py") or filename.startswith("_"):
continue
if not os.path.isfile(os.path.join(PLUGINS_PATH, filename)):
continue
plugin = filename[:-3]
if plugin in FAILED_PLUGIN... | Check available plugins and attempt to import them |
def get_prefix_envname(self, name, log=False):
prefix = None
if name == 'root':
prefix = self.ROOT_PREFIX
envs = self.get_envs()
for p in envs:
if basename(p) == name:
prefix = p
return prefix | Return full prefix path of environment defined by `name`. |
def check_config(config):
essential_keys = ['number_earthquakes']
for key in essential_keys:
if key not in config:
raise ValueError('For Kijko Nonparametric Gaussian the key %s '
'needs to be set in the configuation' % key)
if config.get('tolerance', 0.0) <= ... | Check config file inputs and overwrite bad values with the defaults |
def get(self, key):
upload = None
files_states = self.backend.get(key)
files = MultiValueDict()
if files_states:
for name, state in files_states.items():
f = BytesIO()
f.write(state['content'])
if state['size'] > settings.FILE_U... | Regenerates a MultiValueDict instance containing the files related to all file states
stored for the given key. |
def rename_tabs_after_change(self, given_name):
client = self.get_current_client()
repeated = False
for cl in self.get_clients():
if id(client) != id(cl) and given_name == cl.given_name:
repeated = True
break
if client.allow_rename and n... | Rename tabs after a change in name. |
def longest_run(da, dim='time'):
d = rle(da, dim=dim)
rl_long = d.max(dim=dim)
return rl_long | Return the length of the longest consecutive run of True values.
Parameters
----------
arr : N-dimensional array (boolean)
Input array
dim : Xarray dimension (default = 'time')
Dimension along which to calculate consecutive run
Returns
-------
... |
def get_piis(query_str):
dates = range(1960, datetime.datetime.now().year)
all_piis = flatten([get_piis_for_date(query_str, date) for date in dates])
return all_piis | Search ScienceDirect through the API for articles and return PIIs.
Note that ScienceDirect has a limitation in which a maximum of 6,000
PIIs can be retrieved for a given search and therefore this call is
internally broken up into multiple queries by a range of years and the
results are combined.
P... |
def _get_string_match_value(self, string, string_match_type):
if string_match_type == Type(**get_type_data('EXACT')):
return string
elif string_match_type == Type(**get_type_data('IGNORECASE')):
return re.compile('^' + string, re.I)
elif string_match_type == Type(**get_ty... | Gets the match value |
def validate_json(f):
@wraps(f)
def wrapper(*args, **kw):
instance = args[0]
try:
if request.get_json() is None:
ret_dict = instance._create_ret_object(instance.FAILURE,
None, True,
... | Validate that the call is JSON. |
def _parse_ipmi_nic_capacity(nic_out):
if (("Device not present" in nic_out)
or ("Unknown FRU header" in nic_out) or not nic_out):
return None
capacity = None
product_name = None
data = nic_out.split('\n')
for item in data:
fields = item.split(':')
if len(fields) > 1:
... | Parse the FRU output for NIC capacity
Parses the FRU output. Seraches for the key "Product Name"
in FRU output and greps for maximum speed supported by the
NIC adapter.
:param nic_out: the FRU output for NIC adapter.
:returns: the max capacity supported by the NIC adapter. |
def make_hash_id():
today = datetime.datetime.now().strftime(DATETIME_FORMAT)
return hashlib.sha1(today.encode('utf-8')).hexdigest() | Compute the `datetime.now` based SHA-1 hash of a string.
:return: Returns the sha1 hash as a string.
:rtype: str |
def replace_model(refwcs, newcoeffs):
print('WARNING:')
print(' Replacing existing distortion model with one')
print(' not necessarily matched to the observation!')
wcslin = stwcs.distortion.utils.undistortWCS(refwcs)
outwcs = refwcs.deepcopy()
outwcs.wcs.cd = wcslin.wcs.cd
outwcs.wcs.... | Replace the distortion model in a current WCS with a new model
Start by creating linear WCS, then run |
def disablingBuidCache(self):
self.buidcache = s_cache.LruDict(0)
yield
self.buidcache = s_cache.LruDict(BUID_CACHE_SIZE) | Disable and invalidate the layer buid cache for migration |
def _fold_line(self, line):
if len(line) <= self._cols:
self._output_file.write(line)
self._output_file.write(self._line_sep)
else:
pos = self._cols
self._output_file.write(line[0:self._cols])
self._output_file.write(self._line_sep)
... | Write string line as one or more folded lines. |
def event_return(events):
conn = _get_conn()
if conn is None:
return None
cur = conn.cursor()
for event in events:
tag = event.get('tag', '')
data = event.get('data', '')
sql =
cur.execute(sql, (tag, salt.utils.json.dumps(data), __opts__['id']))
_close_conn(co... | Return event to a postgres server
Require that configuration be enabled via 'event_return'
option in master config. |
def get_snippet_content(snippet_name, **format_kwargs):
filename = snippet_name + '.snippet'
snippet_file = os.path.join(SNIPPETS_ROOT, filename)
if not os.path.isfile(snippet_file):
raise ValueError('could not find snippet with name ' + filename)
ret = helpers.get_file_content(snippet_file)
... | Load the content from a snippet file which exists in SNIPPETS_ROOT |
def from_array(array):
if array is None or not array:
return None
assert_type_or_raise(array, dict, parameter_name="array")
from ..receivable.media import Location
from ..receivable.peer import User
data = {}
data['result_id'] = u(array.get('result_id'))
... | Deserialize a new ChosenInlineResult from a given dictionary.
:return: new ChosenInlineResult instance.
:rtype: ChosenInlineResult |
def get_files(dirname=None, pattern='*.*', recursive=True):
if dirname is None:
from FlowCytometryTools.gui import dialogs
dirname = dialogs.select_directory_dialog('Select a directory')
if recursive:
matches = []
for root, dirnames, filenames in os.walk(dirname):
for... | Get all file names within a given directory those names match a
given pattern.
Parameters
----------
dirname : str | None
Directory containing the datafiles.
If None is given, open a dialog box.
pattern : str
Return only files whose names match the specified pattern.
rec... |
def printAllElements(self):
cnt = 1
print("{id:<3s}: {name:<12s} {type:<10s} {classname:<10s}"
.format(id='ID', name='Name', type='Type', classname='Class Name'))
for e in self._lattice_eleobjlist:
print("{cnt:>03d}: {name:<12s} {type:<10s} {classname:<10s}"
... | print out all modeled elements |
def find_nearest(self, hex_code, system, filter_set=None):
if system not in self._colors_by_system_hex:
raise ValueError(
"%r is not a registered color system. Try one of %r"
% (system, self._colors_by_system_hex.keys())
)
hex_code = hex_code.lower... | Find a color name that's most similar to a given sRGB hex code.
In normalization terms, this method implements "normalize an arbitrary sRGB value
to a well-defined color name".
Args:
system (string): The color system. Currently, `"en"`` is the only default
system.
... |
def filter(self, filter_fn=None, desc=None, **kwargs):
if filter_fn is not None and kwargs:
raise TypeError('Must supply either a filter_fn or attribute filter parameters to filter(), but not both.')
if filter_fn is None and not kwargs:
raise TypeError('Must supply one of filter_... | Return a copy of this query, with some values removed.
Example usages:
.. code:: python
# Returns a query that matches even numbers
q.filter(filter_fn=lambda x: x % 2)
# Returns a query that matches elements with el.description == "foo"
q.filter(descri... |
def _update_transforms(self):
if len(self._fb_stack) == 0:
fb_size = fb_rect = None
else:
fb, origin, fb_size = self._fb_stack[-1]
fb_rect = origin + fb_size
if len(self._vp_stack) == 0:
viewport = None
else:
viewport = self._vp... | Update the canvas's TransformSystem to correct for the current
canvas size, framebuffer, and viewport. |
def _get_v4_signed_headers(self):
if self.aws_session is None:
boto_session = session.Session()
creds = boto_session.get_credentials()
else:
creds = self.aws_session.get_credentials()
if creds is None:
raise CerberusClientException("Unable to locat... | Returns V4 signed get-caller-identity request headers |
def quoteattrs(data):
items = []
for key, value in data.items():
items.append('{}={}'.format(key, quoteattr(value)))
return ' '.join(items) | Takes dict of attributes and returns their HTML representation |
def send(self, filenames=None):
try:
with self.ssh_client.connect() as ssh_conn:
with self.sftp_client.connect(ssh_conn) as sftp_conn:
for filename in filenames:
sftp_conn.copy(filename=filename)
self.archive(filenam... | Sends the file to the remote host and archives
the sent file locally. |
def edit(self, pk):
resp = super(TableModelView, self).edit(pk)
if isinstance(resp, str):
return resp
return redirect('/superset/explore/table/{}/'.format(pk)) | Simple hack to redirect to explore view after saving |
def display_upstream_structure(structure_dict):
graph = _create_graph(structure_dict)
plt = Image(graph.create_png())
display(plt) | Displays pipeline structure in the jupyter notebook.
Args:
structure_dict (dict): dict returned by
:func:`~steppy.base.Step.upstream_structure`. |
def get_ticket(self, ticket_id):
url = 'tickets/%d' % ticket_id
ticket = self._api._get(url)
return Ticket(**ticket) | Fetches the ticket for the given ticket ID |
def schedule(identifier, **kwargs):
source = actions.schedule(identifier, **kwargs)
msg = 'Scheduled {source.name} with the following crontab: {cron}'
log.info(msg.format(source=source, cron=source.periodic_task.crontab)) | Schedule a harvest job to run periodically |
def get_word_under_cursor(self):
if not re.match(r"^\w+$", foundations.strings.to_string(self.get_previous_character())):
return QString()
cursor = self.textCursor()
cursor.movePosition(QTextCursor.PreviousWord, QTextCursor.MoveAnchor)
cursor.movePosition(QTextCursor.EndOfWor... | Returns the document word under cursor.
:return: Word under cursor.
:rtype: QString |
def instances(cls):
l = [i for i in cls.allinstances() if isinstance(i, cls)]
return l | Return all instances of this class and subclasses
:returns: all instances of the current class and subclasses
:rtype: list
:raises: None |
def get_dock_json(self):
env_json = self.build_json['spec']['strategy']['customStrategy']['env']
try:
p = [env for env in env_json if env["name"] == "ATOMIC_REACTOR_PLUGINS"]
except TypeError:
raise RuntimeError("\"env\" is not iterable")
if len(p) <= 0:
... | return dock json from existing build json |
def run_migration_list(self, path, migrations, pretend=False):
if not migrations:
self._note("<info>Nothing to migrate</info>")
return
batch = self._repository.get_next_batch_number()
for f in migrations:
self._run_up(path, f, batch, pretend) | Run a list of migrations.
:type migrations: list
:type pretend: bool |
def lookupByName(self, name):
res = yield queue.executeInThread(self.connection.lookupByName, name)
return self.DomainClass(self, res) | I lookup an existing predefined domain |
def clipandmerge_general_stats_table(self):
headers = OrderedDict()
headers['percentage'] = {
'title': '% Merged',
'description': 'Percentage of reads merged',
'min': 0,
'max': 100,
'suffix': '%',
'scale': 'Greens',
'for... | Take the parsed stats from the ClipAndMerge report and add it to the
basic stats table at the top of the report |
def keep_everything_scorer(checked_ids):
result = checked_ids.keys()
for i in checked_ids.values():
result.extend(i.keys())
return dict.fromkeys(result).keys() | Returns every query and every match in checked_ids, with best score. |
def trailing_stop_loss(self, accountID, **kwargs):
return self.create(
accountID,
order=TrailingStopLossOrderRequest(**kwargs)
) | Shortcut to create a Trailing Stop Loss Order in an Account
Args:
accountID : The ID of the Account
kwargs : The arguments to create a TrailingStopLossOrderRequest
Returns:
v20.response.Response containing the results from submitting
the request |
def mouse_button_callback(self, window, button, action, mods):
button += 1
if button not in [1, 2]:
return
xpos, ypos = glfw.get_cursor_pos(self.window)
if action == glfw.PRESS:
self.example.mouse_press_event(xpos, ypos, button)
else:
s... | Handle mouse button events and forward them to the example |
def readPhenoFile(pfile,idx=None):
usecols = None
if idx!=None:
usecols = [int(x) for x in idx.split(',')]
phenoFile = pfile+'.phe'
assert os.path.exists(phenoFile), '%s is missing.'%phenoFile
Y = SP.loadtxt(phenoFile,usecols=usecols)
if (usecols is not None) and (len(usecols)==1): Y = Y... | reading in phenotype file
pfile root of the file containing the phenotypes as NxP matrix
(N=number of samples, P=number of traits) |
def static_filename(self, repo: str, branch: str, relative_path: Union[str, Path], *,
depth: DepthDefinitionType=1,
reference: ReferenceDefinitionType=None
) -> Path:
self.validate_repo_url(repo)
depth = self.validate_depth(depth)
... | Returns an absolute path to where a file from the repo was cloned to.
:param repo: Repo URL
:param branch: Branch name
:param relative_path: Relative path to the requested file
:param depth: See :meth:`run`
:param reference: See :meth:`run`
:return: Absolute path to the... |
def recent_update_frequencies(self):
return list(reversed([(1.0 / p) for p in numpy.diff(self._recent_updates)])) | Returns the 10 most recent update frequencies.
The given frequencies are computed as short-term frequencies!
The 0th element of the list corresponds to the most recent frequency. |
def _from_dict(cls, _dict):
args = {}
if 'section_titles' in _dict:
args['section_titles'] = [
SectionTitles._from_dict(x)
for x in (_dict.get('section_titles'))
]
if 'leading_sentences' in _dict:
args['leading_sentences'] = [
... | Initialize a DocStructure object from a json dictionary. |
def tasks(self):
tasks_response = self.get_request('tasks/')
return [Task(self, tjson['task']) for tjson in tasks_response] | Generates a list of all Tasks. |
def ensure_default_namespace(self) -> Namespace:
namespace = self.get_namespace_by_keyword_version(BEL_DEFAULT_NAMESPACE, BEL_DEFAULT_NAMESPACE_VERSION)
if namespace is None:
namespace = Namespace(
name='BEL Default Namespace',
contact='charles.hoyt@scai.fraun... | Get or create the BEL default namespace. |
def address(self) -> str:
fmt = self._data['address_fmt']
st_num = self.street_number()
st_name = self.street_name()
if self.locale in SHORTENED_ADDRESS_FMT:
return fmt.format(
st_num=st_num,
st_name=st_name,
)
if self.local... | Generate a random full address.
:return: Full address. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.