code stringlengths 51 2.34k | docstring stringlengths 11 171 |
|---|---|
def clean_new_password2(self):
password1 = self.cleaned_data.get('new_password1')
password2 = self.cleaned_data.get('new_password2')
try:
directory = APPLICATION.default_account_store_mapping.account_store
directory.password_policy.strength.validate_password(password2)
... | Check if passwords match and are valid. |
def process_result_value(self, value, dialect):
if value is not None:
with BytesIO(value) as stream:
with GzipFile(fileobj=stream, mode="rb") as file_handle:
value = json.loads(file_handle.read().decode("utf-8"))
return value | Convert a JSON encoded string to a dictionary structure. |
def update_stale(self):
for etype, echannels in self.event_states.items():
for eprop in echannels:
if eprop[3] is not None:
sec_elap = ((datetime.datetime.now()-eprop[3])
.total_seconds())
if sec_elap > 5 and epr... | Update stale active statuses |
def on_backward_end(self, **kwargs:Any)->None:
"Convert the gradients back to FP32 and divide them by the scale."
if self.dynamic and grad_overflow(self.model_params) and self.loss_scale > 1:
self.loss_scale /= 2
self.noskip = 0
else:
model_g2master_g(self.mod... | Convert the gradients back to FP32 and divide them by the scale. |
def request(self, method, path, params=None, headers=None, body=None):
if not headers:
headers = {}
if not params:
params = {}
headers["Accept"] = "application/json"
headers["Accept-Version"] = "^1.15.0"
if self.auth_token:
headers["Authorizati... | Base method for making a Losant API request |
def _create_credentials(self, n):
if not n:
return n
elif isinstance(n, SecurityCreds):
return n
elif isinstance(n, dict):
return SecurityCreds(**n)
else:
raise TypeError("%s is not a valid security configuration"
... | Create security credentials, if necessary. |
def restore_watched(plex, opts):
with open(opts.filepath, 'r') as handle:
source = json.load(handle)
differences = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Finding differences in %s..' % section.title)
skey = section.title.lower()
for item... | Restore watched status from the specified filepath. |
def find_best_periods(self, n_periods=5, return_scores=False):
return self.optimizer.find_best_periods(self, n_periods,
return_scores=return_scores) | Find the top several best periods for the model |
def parse_in_line(txt: str, units: Units) -> typing.Dict[str, str]:
retwx = {}
wxdata = txt.split(' ')
wxdata, _, retwx['wind_shear'] = core.sanitize_report_list(wxdata)
wxdata, retwx['type'], retwx['start_time'], retwx['end_time'] = core.get_type_and_times(wxdata)
wxdata, retwx['wind_direction'], r... | Parser for the International TAF forcast varient |
def _get_masses(fitnesses):
best_fitness = max(fitnesses)
worst_fitness = min(fitnesses)
fitness_range = best_fitness - worst_fitness
raw_masses = []
for fitness in fitnesses:
raw_masses.append((fitness - worst_fitness) / (fitness_range + EPSILON)
+ EPSILON)
tot... | Convert fitnesses into masses, as given by GSA algorithm. |
def attach_core_filters(cls):
opts = cls._meta
base_filters = cls.base_filters.copy()
cls.base_filters.clear()
for name, filter_ in six.iteritems(base_filters):
if isinstance(filter_, AutoFilters):
field = filterset.get_model_field(opts.model, filter_.name)
... | Attach core filters to filterset |
def _irc_lower(self, in_string):
conv_string = self._translate(in_string)
if self._lower_trans is not None:
conv_string = conv_string.translate(self._lower_trans)
return str.lower(conv_string) | Convert us to our lower-case equivalent, given our std. |
def make_keys_safe(dct):
result = {}
for key, val in dct.items():
key = key.replace('-', '_')
if key in keyword.kwlist:
key = key + '_'
result[key] = val
return result | Modify the keys in |dct| to be valid attribute names. |
def check_section_oversized(self):
total_image_size = self.pefile_handle.OPTIONAL_HEADER.SizeOfImage
for section in self.pefile_handle.sections:
if section.PointerToRawData + section.SizeOfRawData > total_image_size:
return {'description': 'Oversized section, storing addition... | Checking if any of the sections go past the total size of the image |
def list_lbaas_healthmonitors(self, retrieve_all=True, **_params):
return self.list('healthmonitors', self.lbaas_healthmonitors_path,
retrieve_all, **_params) | Fetches a list of all lbaas_healthmonitors for a project. |
def write(self, message, autoerase=True):
super(Animation, self).write(message)
self.last_message = message
if autoerase:
time.sleep(self.interval)
self.erase(message) | Send something for stdout and erased after delay |
def format(item, **params):
encoding = params.get('charset', 'UTF-8')
return json.dumps(item, encoding=encoding) | Truns a python object into a JSON structure. |
def in_subnet(cidr, addrs=None):
for address in addrs:
if ip_in_subnet(address, cidr):
return True
return False | Returns True if host is within specified subnet, otherwise False |
def prepare(self):
self.target = self.fn
self.targetheader = reader.get_tsv_header(self.target)
self.decoyheader = reader.get_tsv_header(self.decoyfn) | No percolator XML for protein tables |
def encode_inputs(self):
litmap = dict()
nvars = 0
for i, v in enumerate(self.inputs, start=1):
litmap[v] = i
litmap[~v] = -i
litmap[i] = v
litmap[-i] = ~v
nvars += 1
return litmap, nvars | Return a compact encoding for input variables. |
def reset(self):
if not self.leds:
return
self.animate_stop()
for group in self.led_groups:
self.set_color(group, LED_DEFAULT_COLOR) | Put all LEDs back to their default color |
def _get_seqprop_to_seqprop_alignment(self, seqprop1, seqprop2):
if isinstance(seqprop1, str):
seqprop1_id = seqprop1
else:
seqprop1_id = seqprop1.id
if isinstance(seqprop2, str):
seqprop2_id = seqprop2
else:
seqprop2_id = seqprop2.id
... | Return the alignment stored in self.sequence_alignments given a seqprop + another seqprop |
def search(table: LdapObjectClass, query: Optional[Q] = None,
database: Optional[Database] = None, base_dn: Optional[str] = None) -> Iterator[LdapObject]:
fields = table.get_fields()
db_fields = {
name: field
for name, field in fields.items()
if field.db_field
}
databa... | Search for a object of given type in the database. |
def addstr(self, h, w, text, attrs=0):
self.update_window_size()
if h > self.height or w > self.width:
return
try:
self.window.addstr(h, w, text, attrs)
except Exception as e:
pass | A safe addstr wrapper |
def _rescan(self, skip_to_end = True):
paths = []
for single_glob in self._globspec:
paths.extend(glob.glob(single_glob))
for path in self._tailedfiles.keys():
if path not in paths:
self._tailedfiles[path]._close()
del self._tailedfiles[path]
for path i... | Check for new files, deleted files, and rotated files. |
def _options_dir(name):
_check_portname(name)
_root = '/var/db/ports'
new_dir = os.path.join(_root, name.replace('/', '_'))
old_dir = os.path.join(_root, name.split('/')[-1])
if os.path.isdir(old_dir):
return old_dir
return new_dir | Retrieve the path to the dir containing OPTIONS file for a given port |
def pretty_date(the_datetime):
diff = datetime.utcnow() - the_datetime
if diff.days > 7 or diff.days < 0:
return the_datetime.strftime('%A %B %d, %Y')
elif diff.days == 1:
return '1 day ago'
elif diff.days > 1:
return '{0} days ago'.format(diff.days)
elif diff.seconds <= 1:
... | Attempt to return a human-readable time delta string. |
def _with_rotation(self, w, h):
res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation))
res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation))
return res_w, res_h | calculate the actual dimensions after rotation |
def resourcetypes(rid, model):
types = []
for o, r, t, a in model.match(rid, VTYPE_REL):
types.append(t)
return types | Return a list of Versa types for a resource |
def benchmark(store, n=10000):
x = UpdatableItem(store=store, count=0)
for _ in xrange(n):
x.count += 1 | Increments an integer count n times. |
def walk_preorder(self):
yield self
for child in self._children():
for descendant in child.walk_preorder():
yield descendant | Iterates the program tree starting from this object, going down. |
def lee_yeast_ChIP(data_set='lee_yeast_ChIP'):
if not data_available(data_set):
download_data(data_set)
from pandas import read_csv
dir_path = os.path.join(data_path, data_set)
filename = os.path.join(dir_path, 'binding_by_gene.tsv')
S = read_csv(filename, header=1, index_col=0, sep='\t')
... | Yeast ChIP data from Lee et al. |
def rollback(self):
if not self._in_transaction:
raise NotInTransaction
self._init_cache()
self._in_transaction = False | Drop changes from current transaction. |
def _get_redis_keys_opts():
return {
'bank_prefix': __opts__.get('cache.redis.bank_prefix', _BANK_PREFIX),
'bank_keys_prefix': __opts__.get('cache.redis.bank_keys_prefix', _BANK_KEYS_PREFIX),
'key_prefix': __opts__.get('cache.redis.key_prefix', _KEY_PREFIX),
'separator': __opts__.get... | Build the key opts based on the user options. |
def takeFromTree(self):
tree = self.treeWidget()
parent = self.parent()
if parent:
parent.takeChild(parent.indexOfChild(self))
else:
tree.takeTopLevelItem(tree.indexOfTopLevelItem(self)) | Takes this item from the tree. |
def close(self):
try:
logger.debug('%s - closing', self._resource_name,
extra=self._logging_extra)
self.before_close()
self.visalib.close(self.session)
logger.debug('%s - is closed', self._resource_name,
extra=self... | Closes the VISA session and marks the handle as invalid. |
def frame_msg(body, header=None, raw_body=False):
framed_msg = {}
if header is None:
header = {}
framed_msg['head'] = header
framed_msg['body'] = body
return salt.utils.msgpack.dumps(framed_msg) | Frame the given message with our wire protocol |
def _validate(self):
for c, m in self.atom_to_seqres_sequence_maps.iteritems():
if self.seqres_to_uniparc_sequence_maps.keys():
atom_uniparc_keys = set(self.atom_to_uniparc_sequence_maps.get(c, {}).keys())
atom_seqres_keys = set(self.atom_to_seqres_sequence_maps.get(c... | Tests that the maps agree through composition. |
def create_unsigned_transaction(cls,
*,
nonce: int,
gas_price: int,
gas: int,
to: Address,
value: int,
... | Proxy for instantiating an unsigned transaction for this VM. |
def add_song(self, new_song, verbose=True):
if any([song.title == new_song.title for song in self._songs]):
if verbose:
print('{s} already in {a}, not adding song.'.format(s=new_song.title,
a=self.name))
... | Add a Song object to the Artist object |
def lists(self):
with open(self.filelist, 'w') as filelist:
with open(self.reportlist, 'w') as reportlist:
for sample in self.runmetadata.samples:
if self.extension == 'fastq':
try:
status = sample.run.Descriptio... | Prepare the list of files to be processed |
async def move_camera_spatial(self, position: Union[Point2, Point3]):
from s2clientprotocol import spatial_pb2 as spatial_pb
assert isinstance(position, (Point2, Point3))
action = sc_pb.Action(
action_render=spatial_pb.ActionSpatial(
camera_move=spatial_pb.ActionSpati... | Moves camera to the target position using the spatial aciton interface |
def from_file(fn, **options):
if hasattr(fn, 'read'):
return TableFu(fn, **options)
with open(fn) as f:
return TableFu(f, **options) | Creates a new TableFu instance from a file or path |
def render_to_png(self, filename=None, dpi=72, **kwargs):
import cairosvg
return cairosvg.svg2png(
bytestring=self.render(**kwargs), write_to=filename, dpi=dpi
) | Render the graph, convert it to png and write it to filename |
def add_cell(self, keypath, cell):
keypath = keypath[:]
inner = self
cellname = keypath
assert keypath not in self, "Already exists: %s " % (str(keypath))
if isinstance(keypath, list):
while len(keypath) > 1:
cellname = keypath.pop(0)
i... | Adds a new cell to the end of `keypath` of type `cell` |
def stop(self):
_logger.debug("Emitting quit signal for connections.")
self.__quit_ev.set()
_logger.info("Waiting for connection manager to stop.")
self.__manage_g.join() | Stop all of the connections. |
def remove_namespace(self, namespace):
params = (namespace, )
execute = self.cursor.execute
execute('DELETE FROM gauged_data WHERE namespace = %s', params)
execute('DELETE FROM gauged_statistics WHERE namespace = %s', params)
execute('DELETE FROM gauged_keys WHERE namespace = %s'... | Remove all data associated with the current namespace |
def _init_go_sources(self, go_sources_arg, go2obj_arg):
gos_user = set(go_sources_arg)
if 'children' in self.kws and self.kws['children']:
gos_user |= get_leaf_children(gos_user, go2obj_arg)
gos_godag = set(go2obj_arg)
gos_source = gos_user.intersection(gos_godag)
gos... | Return GO sources which are present in GODag. |
def create_folder(self, folder):
if folder.endswith("/"):
folder = folder[:-1]
if len(folder) < 1:
raise Exception("Minimum folder name length = 1.")
if not os.path.exists(folder):
try:
os.makedirs(folder)
except Exception:
... | Creates a folder of the given name if it doesn't already exist. |
def runtime_paths(self):
runtimepath = self._vim.options['runtimepath']
plugin = "ensime-vim"
paths = []
for path in runtimepath.split(','):
if plugin in path:
paths.append(os.path.expanduser(path))
return paths | All the runtime paths of ensime-vim plugin files. |
def write_int(self, value):
format = '!I'
self.data.append(struct.pack(format, int(value)))
self.size += 4 | Writes an unsigned integer to the packet |
def get(self, timeout=None):
result = None
for stage in self._output_stages:
result = stage.get(timeout)
return result | Return result from the pipeline. |
def _list_directory(self, folder_id=''):
title = '%s._list_directory' % self.__class__.__name__
file_list = []
list_kwargs = {
'spaces': self.drive_space,
'fields': 'nextPageToken, files(id, name, parents, mimeType)'
}
if folder_id:
list_kwargs... | a generator method for listing the contents of a directory |
def _print_stats(cls, stats: Statistics, human_format_speed: bool=True):
time_length = datetime.timedelta(
seconds=int(stats.stop_time - stats.start_time)
)
file_size = wpull.string.format_size(stats.size)
if stats.bandwidth_meter.num_samples:
speed = stats.bandwi... | Log the final statistics to the user. |
def on_exists(fname):
if os.path.isfile(fname):
newfile = fname + ".old"
print("{} -> {}".format(fname, newfile))
os.rename(fname, newfile) | Callback example when we try to overwrite an existing screenshot. |
def make_analysator(f):
def text_analyse(text):
try:
rv = f(text)
except Exception:
return 0.0
if not rv:
return 0.0
try:
return min(1.0, max(0.0, float(rv)))
except (ValueError, TypeError):
return 0.0
text_analy... | Return a static text analyser function that returns float values. |
def off(self, name, callback, once=False):
if name not in self.event_listeners:
return
self.event_listeners[name].remove((callback, once)) | Removes callback to the event specified by name |
def complete_object_value(
exe_context,
return_type,
field_asts,
info,
path,
result,
):
if return_type.is_type_of and not return_type.is_type_of(result, info):
raise GraphQLError(
u'Expected value of type "{}" but got: {}.'.format(
return_type, type(result... | Complete an Object value by evaluating all sub-selections. |
def _generate_name(self, space, service_name, plan_name):
return str.join('-', [space, service_name, plan_name]).lower() | Can generate a name based on the space, service name and plan. |
def from_jd(jd):
jd = trunc(jd) + 0.5
g = gregorian.from_jd(jd)
gy = g[0]
bstarty = EPOCH_GREGORIAN_YEAR
if jd <= gregorian.to_jd(gy, 3, 20):
x = 1
else:
x = 0
bys = gy - (bstarty + (((gregorian.to_jd(gy, 1, 1) <= jd) and x)))
year = bys + 1
days = jd - to_jd(year, 1,... | Calculate Bahai date from Julian day |
def width_radius_changed_cb(self, widget, val):
self.width_radius = val
self.redraw_cuts()
self.replot_all()
return True | Callback executed when the Width radius is changed. |
def analysis_of_prot_lig_interactions(self):
self.hbonds = HBonds(self.topol_data,self.trajectory,self.start,self.end,self.skip,self.analysis_cutoff,distance=3)
self.pistacking = PiStacking(self.topol_data,self.trajectory,self.start,self.end,self.skip, self.analysis_cutoff)
self.sasa = SASA(self... | The classes and function that deal with protein-ligand interaction analysis. |
def _push_status(data, item):
status = item['status'].lower()
if 'id' in item:
if 'already pushed' in status or 'already exists' in status:
already_pushed = data.setdefault('Layers', {}).setdefault(
'Already_Pushed', [])
already_pushed.append(item['id'])
e... | Process a status update from a docker push, updating the data structure |
def check_postconditions(f, return_value):
f = getattr(f, 'wrapped_fn', f)
if f and hasattr(f, 'postconditions'):
for cond in f.postconditions:
cond(return_value) | Runs all of the postconditions. |
def time_since(self, mtype):
if not mtype in self.messages:
return time.time() - self.start_time
return time.time() - self.messages[mtype]._timestamp | return the time since the last message of type mtype was received |
def list_i2str(ilist):
slist = []
for el in ilist:
slist.append(str(el))
return slist | Convert an integer list into a string list. |
def main(args=None):
streamsx._streams._version._mismatch_check('streamsx.topology.context')
try:
sr = run_cmd(args)
sr['return_code'] = 0
except:
sr = {'return_code':1, 'error': sys.exc_info()}
return sr | Performs an action against a Streaming Analytics service. |
def dump_ckan(m):
doc = MetapackDoc(cache=m.cache)
doc.new_section('Groups', 'Title Description Id Image_url'.split())
doc.new_section('Organizations', 'Title Description Id Image_url'.split())
c = RemoteCKAN(m.ckan_url, apikey=m.api_key)
for g in c.action.group_list(all_fields=True):
... | Create a groups and organization file |
def _get_deltas(event):
delta_x = round(event.deltaX())
delta_y = round(event.deltaY())
delta_z = round(event.deltaZ())
return delta_x, delta_y, delta_z | Get the changes from the appkit event. |
def make_client(api_version, session=None,
endpoint=None, service_type='monitoring'):
client_cls = utils.get_client_class('monitoring', api_version, VERSION_MAP)
c = client_cls(
session=session,
service_type=service_type,
endpoint=endpoint,
app_name='monascaclient... | Returns an monitoring API client. |
def ca_main_axis(self):
try:
ca_ind = self.dim_types.index(DT.CA_SUBVAR)
return 1 - ca_ind
except ValueError:
return None | For univariate CA, the main axis is the categorical axis |
def minizinc_version():
vs = _run_minizinc('--version')
m = re.findall('version ([\d\.]+)', vs)
if not m:
raise RuntimeError('MiniZinc executable not found.')
return m[0] | Returns the version of the found minizinc executable. |
def parents(self, node):
return [
parent for parent in
getattr( node, 'parents', [] )
if getattr(parent, 'tree', self.TREE) == self.TREE
] | Determine all parents of node in our tree |
def parse(cls, string):
match = re.match(r'^(?P<name>[A-Za-z0-9\.\-_]+)\s+' +
'(?P<value>[0-9\.]+)\s+' +
'(?P<timestamp>[0-9\.]+)(\n?)$',
string)
try:
groups = match.groupdict()
return Metric(groups['name'... | Parse a string and create a metric |
def post(self, path, payload):
body = json.dumps(payload)
return self._request(path, 'POST', body) | Make a POST request from the API. |
def weighted_choice(population):
random_number = random.betavariate(1, 2.5)
ind = int(random_number*len(population))
ind = min(max(ind, 0), len(population)-1)
return population[ind][0] | Randomly select, fitness determines probability of being selected |
def region_name(self, language=DEFAULT_LANGUAGE, min_score: int=75) -> str:
return self._get_name('region', language, min_score) | Describe the region part of the language tag in a natural language. |
def _subst_libs(env, libs):
if SCons.Util.is_String(libs):
libs = env.subst(libs)
if SCons.Util.is_String(libs):
libs = libs.split()
elif SCons.Util.is_Sequence(libs):
_libs = []
for l in libs:
_libs += _subst_libs(env, l)
libs = _libs
else:
... | Substitute environment variables and split into list. |
def widgetSubCheckBoxRect(widget, option):
opt = QtWidgets.QStyleOption()
opt.initFrom(widget)
style = widget.style()
return style.subElementRect(QtWidgets.QStyle.SE_ViewItemCheckIndicator, opt, widget) | Returns the rectangle of a check box drawn as a sub element of widget |
def facade(factory):
wrapper = FacadeDescriptor(factory.__name__, factory)
return update_wrapper(wrapper, factory) | Declare a method as a facade factory. |
def _get_cursor(self):
_options = self._get_options()
conn = psycopg2.connect(host=_options['host'],
user=_options['user'],
password=_options['pass'],
dbname=_options['db'],
po... | Yield a POSTGRES cursor |
def approle_token(vault_client, role_id, secret_id):
resp = vault_client.auth_approle(role_id, secret_id)
if 'auth' in resp and 'client_token' in resp['auth']:
return resp['auth']['client_token']
else:
raise aomi.exceptions.AomiCredentials('invalid approle') | Returns a vault token based on the role and seret id |
def close_all_pages(self):
state_machine_m_list = [tab['state_machine_m'] for tab in self.tabs.values()]
for state_machine_m in state_machine_m_list:
self.on_close_clicked(None, state_machine_m, None, force=True) | Closes all tabs of the state machines editor. |
def _select_md5sum_arch(self, md5sum, md5sum64):
if md5sum and md5sum64:
if self.meta.arch == "x86_64":
return md5sum64
else:
return md5sum
if md5sum:
return md5sum
else:
return md5sum64 | Return checksums by arch |
def delete(self):
with self._qpart:
for cursor in self.cursors():
if cursor.hasSelection():
cursor.deleteChar() | Del or Backspace pressed. Delete selection |
def _parse_fail(name, var_type, value, values):
raise ValueError(
'Could not parse hparam \'%s\' of type \'%s\' with value \'%s\' in %s' %
(name, var_type.__name__, value, values)) | Helper function for raising a value error for bad assignment. |
def dict(self):
try:
skewness = self.skewness
kurtosis = self.kurtosis
except ZeroDivisionError:
skewness = kurtosis = float('nan')
base_cols = [
('name', self.column_name),
('flags', self.flags),
('type', self.type.__name__... | Return a dict that can be passed into the ColumnStats constructor |
def apply_selector(objs, selector):
out = []
for obj in objs:
timer.log('Applying selector: %s' % selector)
out += list(jsonselect.match(selector, objs))
timer.log('done applying selector')
return out | Returns a list of objects which match the selector in any of objs. |
def delete(self, id):
path = partial(_path, self.adapter)
path = path(id)
return self._delete(path) | delete a time entry. |
def restart(self):
version = self.get_version()
command = [
"haproxy",
"-f", self.config_file_path, "-p", self.pid_file_path
]
if version and version >= (1, 5, 0):
command.extend(["-L", self.peer.name])
if os.path.exists(self.pid_file_path):
... | Performs a soft reload of the HAProxy process. |
def _register_parser(cls):
assert cls.cls_msg_type is not None
assert cls.cls_msg_type not in _MSG_PARSERS
_MSG_PARSERS[cls.cls_msg_type] = cls.parser
return cls | class decorator to register msg parser |
def _typedef_code(t, base=0, refs=None, kind=_kind_static, heap=False):
v = _Typedef(base=_basicsize(t, base=base),
refs=refs,
both=False, kind=kind, type=t)
v.save(t, base=base, heap=heap)
return v | Add new typedef for code only. |
def fgmc(log_fg_ratios, mu_log_vt, sigma_log_vt, Rf, maxfg):
Lb = np.random.uniform(0., maxfg, len(Rf))
pquit = 0
while pquit < 0.1:
nsamp = len(Lb)
Rf_sel = np.random.choice(Rf, nsamp)
vt = np.random.lognormal(mu_log_vt, sigma_log_vt, len(Rf_sel))
Lf = Rf_sel * vt
lo... | Function to fit the likelihood Fixme |
def save_to_folders(self, parameter_space, folder_name, runs):
self.space_to_folders(self.db.get_results(), {}, parameter_space, runs,
folder_name) | Save results to a folder structure. |
def bk_default(cls):
"Make the current background color the default."
wAttributes = cls._get_text_attributes()
wAttributes &= ~win32.BACKGROUND_MASK
wAttributes &= ~win32.BACKGROUND_INTENSITY
cls._set_text_attributes(wAttributes) | Make the current background color the default. |
def import_gpg_key(key):
if not key:
raise CryptoritoError('Invalid GPG Key')
key_fd, key_filename = mkstemp("cryptorito-gpg-import")
key_handle = os.fdopen(key_fd, 'w')
key_handle.write(polite_string(key))
key_handle.close()
cmd = flatten([gnupg_bin(), gnupg_home(), "--import", key_file... | Imports a GPG key |
def _apply_mask(
data: np.ndarray,
encoded_fill_values: list,
decoded_fill_value: Any,
dtype: Any,
) -> np.ndarray:
data = np.asarray(data, dtype=dtype)
condition = False
for fv in encoded_fill_values:
condition |= data == fv
return np.where(condition, decoded_fill_value, data) | Mask all matching values in a NumPy arrays. |
def define_plugin_entry(name, module_name):
if isinstance(name, tuple):
entry, name = name
else:
entry = name
return '%s = %s:%s' % (entry, module_name, name) | helper to produce lines suitable for setup.py's entry_points |
def trips_process_xml():
if request.method == 'OPTIONS':
return {}
response = request.body.read().decode('utf-8')
body = json.loads(response)
xml_str = body.get('xml_str')
tp = trips.process_xml(xml_str)
return _stmts_from_proc(tp) | Process TRIPS EKB XML and return INDRA Statements. |
def currency_multiplier(src_currency, dest_currency):
'returns equivalent value in USD for an amt of currency_code'
if src_currency == 'USD':
return 1.0
usd_mult = currency_rates()[src_currency]
if dest_currency == 'USD':
return usd_mult
return usd_mult/currency_rates()[dest_currency... | returns equivalent value in USD for an amt of currency_code |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.