content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def op_lessthan(this):
"""
Stack operations make this flipped!
"""
if this.pop() > this.pop():
this.push(1)
else:
this.push(0)
| 7,200 |
def test_safe_print_string():
"""[Utils] safe_print: accepts flush and stream name as string."""
with open(os.devnull, 'w') as f, redirect_stdout(f):
utils.safe_print('test', flush=True, file="stdout")
| 7,201 |
def p(*args, **kwargs):
"""
Pretty print the object for debug
:param kwargs:
:param args:
:return:
"""
(frame, filename, line_number,
function_name, lines, index) = inspect.getouterframes(inspect.currentframe())[1]
print(':: [%s] => %s:%s' % (path.basename(filename), function_name, line_number))
if not args:
pass
first = True
for obj in args:
if obj is None:
print('None')
if first and isinstance(obj, str) and len(args) > 1:
print('%s: ' % obj)
first = False
continue
first = False
if isinstance(obj, QuerySet) or isinstance(obj, list) or \
(ValuesQuerySet is not None and isinstance(obj, ValuesQuerySet)):
result = '[ len=%s\n' % len(obj)
index = 0
for o in obj:
o = pprint.pformat(o, indent=1, compact=False).strip()
result += ' [%s] %s,\n' % (index, o)
index += 1
result += ']\n'
print(result)
elif isinstance(obj, dict) or type(obj) == OrderedDict:
result = '{ len=%s\n' % len(obj)
index = 0
for k, o in obj.items():
o = pprint.pformat(o, indent=1, compact=False).strip()
result += ' [%s] \'%s\': %s,\n' % (index, k, o)
index += 1
result += '}\n'
print(result)
else:
opts = {
'indent': 1,
}
opts.update(kwargs)
pprint.pprint(obj, **opts)
| 7,202 |
def calc_dof(model):
"""
Calculate degrees of freedom.
Parameters
----------
model : Model
Model.
Returns
-------
int
DoF.
"""
p = len(model.vars['observed'])
return p * (p + 1) // 2 - len(model.param_vals)
| 7,203 |
def parse_event_export_xls(
file: StrOrBytesPath, parsing_elements: list[str] = _ALL_PARSING_ELEMENTS
) -> ParsedEventResultXlsFile:
"""Parse a Hytek MeetManager .hy3 file.
Args:
file (StrOrBytesPath): A path to the file to parse.
parsing_elements (Sequence[str]): Elements to extract from the file.
Valid elements: 'name', 'age', 'team', 'seed time',
'prelim time', 'finals time'
Returns:
ParsedEventHyvFile: The parsed file.
"""
book = xlrd.open_workbook(file)
sheet = book.sheet_by_index(0)
# Get event name
event_name = str(sheet.cell_value(1, 0))
# Extract the header row
# This should be one with "Name" as it's first element
for rx in range(sheet.nrows):
row = sheet.row(rx)
if str(row[0].value).lower() == "name":
header_row = [str(e.value).lower() for e in row]
header_row_index = rx
break
# Make sure we have a header row
if header_row is None:
raise ExportXlsParseError("Could not find header row.")
first_row_index = get_first_row_index(sheet, header_row_index)
# Only parse times in the header row
if "seed time" in parsing_elements and "seed time" not in header_row:
parsing_elements.pop(parsing_elements.index("seed time"))
if "prelim time" in parsing_elements and "prelim time" not in header_row:
parsing_elements.pop(parsing_elements.index("prelim time"))
if "finals time" in parsing_elements and "finals time" not in header_row:
parsing_elements.pop(parsing_elements.index("finals time"))
# Determine offsets to extract from
offsets = get_offsets_from_header(
sheet, header_row, first_row_index, parsing_elements
)
# Start parsing rows
results = []
rx = first_row_index
while rx < sheet.nrows and sheet.cell_value(rx, 0).strip() != "":
row = sheet.row(rx)
place = safe_cast(int, row[0].value, -1)
if place == -1 and row[0].value != "---":
rx += 1
continue
name = extract_plain_value("name", row, offsets)
age = extract_plain_value("age", row, offsets, cast_to=int)
team = extract_plain_value("team", row, offsets)
seed_time, seed_time_extra, seed_time_qualifications = extract_time_value(
"seed time", row, offsets
)
prelim_time, prelim_time_extra, prelim_time_qualifications = extract_time_value(
"prelim time", row, offsets
)
finals_time, finals_time_extra, finals_time_qualifications = extract_time_value(
"finals time", row, offsets
)
results.append(
EventResultEntry(
place=place,
swimmer_name=name,
swimmer_age=age,
swimmer_team=team,
seed_time=seed_time,
seed_time_extra=seed_time_extra,
seed_time_qualifications=seed_time_qualifications,
prelim_time=prelim_time,
prelim_time_extra=prelim_time_extra,
prelim_time_qualifications=prelim_time_qualifications,
finals_time=finals_time,
finals_time_extra=finals_time_extra,
finals_time_qualifications=finals_time_qualifications,
)
)
rx += 1
return ParsedEventResultXlsFile(
event_name=event_name, parsing_elements=tuple(parsing_elements), results=results
)
| 7,204 |
def test_expected_values(runner):
"""The generate_sample method should return a dictionary containing all expected values"""
all_results = [runner.result] + [other_runner.result for other_runner in runner.race.active_runners if other_runner['_id'] != runner['_id']]
raw_query_data = []
for key in ('barrier', 'number', 'weight'):
raw_query_data.append(runner[key])
for key in ('age', 'carrying', 'races_per_year', 'spell', 'up'):
raw_query_data.append(getattr(runner, key))
for key1 in ('at_distance', 'at_distance_on_track', 'at_up', 'career', 'last_10', 'last_12_months', 'on_firm', 'on_good', 'on_heavy', 'on_soft', 'on_synthetic', 'on_track', 'on_turf', 'since_rest', 'with_jockey'):
raw_query_data.extend(runner.calculate_expected_times(key1))
performance_list = getattr(runner, key1)
for key2 in ('earnings', 'earnings_potential', 'fourth_pct', 'result_potential', 'roi', 'second_pct', 'starts', 'third_pct', 'win_pct'):
raw_query_data.append(getattr(performance_list, key2))
raw_query_data.extend(performance_list.starting_prices)
expected_values = {
'raw_query_data': raw_query_data,
'imputed_query_data': None,
'normalized_query_data': None,
'regression_result': sklearn.preprocessing.normalize(numpy.array(all_results).reshape(1, -1))[0, 0],
'classification_result': runner.result if runner.result is not None and 1 <= runner.result <= 4 else 5,
'weight': runner.race.total_value,
'predictor_version': predictive_punter.__version__
}
generated_values = predictive_punter.Sample.generate_sample(runner)
for key in expected_values:
assert generated_values[key] == expected_values[key]
| 7,205 |
def create_form(request, *args, **kwargs):
"""
Create a :py:class:`deform.Form` instance for this request.
This request method creates a :py:class:`deform.Form` object which (by
default) will use the renderer configured in the :py:mod:`h.form` module.
"""
env = request.registry[ENVIRONMENT_KEY]
renderer = Jinja2Renderer(env, {
'feature': request.feature,
})
kwargs.setdefault('renderer', renderer)
return deform.Form(*args, **kwargs)
| 7,206 |
def get_lsl_inlets(streams=None, with_source_ids=('',), with_types=('',),
max_chunklen=0):
"""Return LSL stream inlets for given/discovered LSL streams.
If `streams` is not given, will automatically discover all available
streams.
Args:
streams: List of `pylsl.StreamInfo` or source/type mapping.
See `streams_dict_from_streams` for additional documentation
of the difference between the two data types.
with_source_id (Iterable[str]): Return only inlets whose source ID
contains one of these strings.
Case-sensitive; e.g. "Muse" might work if "muse" doesn't.
with_type (Iterable[str]): Return only inlets with these stream types.
Returns:
dict[str, dict[str, pylsl.StreamInlet]]: LSL inlet objects.
Keys are the source IDs; values are dicts where the keys are stream
types and values are stream inlets.
TODO:
* Try leveraging lsl.resolve_byprop or lsl.resolve_bypred
* inlet time_correction necessary for remotely generated timestamps?
"""
if streams is None:
streams = get_lsl_streams()
else:
# ensure streams is in streams_dict format
try: # quack
streams.keys()
list(streams.values())[0].keys()
except AttributeError:
streams = streams_dict_from_streams(streams)
streams_dict = streams
inlets = dict.fromkeys(streams_dict.keys(), {})
for source_id, streams in streams_dict.items():
if any(id_str in source_id for id_str in with_source_ids):
for stream_type, stream in streams.items():
if any(type_str in stream_type for type_str in with_types):
inlets[source_id][stream_type] = lsl.StreamInlet(stream)
# make sure no empty devices are included following inclusion rules
inlets = {source_id: inlets for source_id, inlets in inlets.items()
if not inlets == {}}
if inlets == {}:
print("No inlets created based on the available streams/given rules")
return inlets
| 7,207 |
def from_dtw2dict(alignment):
"""Auxiliar function which transform useful information of the dtw function
applied in R using rpy2 to python formats.
"""
dtw_keys = list(alignment.names)
bool_traceback = 'index1' in dtw_keys and 'index2' in dtw_keys
bool_traceback = bool_traceback and 'stepsTaken' in dtw_keys
## Creating a dict to save all the information in python format
dtw_dict = {}
# Transformation into a dict
dtw_dict['stepPattern'] = ri2numpy(alignment.rx('stepPattern'))
dtw_dict['N'] = alignment.rx('N')[0]
dtw_dict['M'] = alignment.rx('M')[0]
dtw_dict['call'] = alignment.rx('call')
dtw_dict['openEnd'] = alignment.rx('openEnd')[0]
dtw_dict['openBegin'] = alignment.rx('openBegin')[0]
dtw_dict['windowFunction'] = alignment.rx('windowFunction')
dtw_dict['jmin'] = alignment.rx('jmin')[0]
dtw_dict['distance'] = alignment.rx('distance')[0]
dtw_dict['normalizedDistance'] = alignment.rx('normalizedDistance')[0]
if bool_traceback:
aux = np.array(ri2numpy(alignment.rx('index1')).astype(int))
dtw_dict['index1'] = aux
aux = np.array(ri2numpy(alignment.rx('index2')).astype(int))
dtw_dict['index2'] = aux
dtw_dict['stepsTaken'] = ri2numpy(alignment.rx('stepsTaken'))
elif 'localCostMatrix' in dtw_keys:
aux = np.array(ri2numpy(alignment.rx('localCostMatrix')))
dtw_dict['localCostMatrix'] = aux
elif 'reference' in dtw_keys and 'query' in dtw_keys:
dtw_dict['reference'] = alignment.rx('reference')
dtw_dict['query'] = alignment.rx('query')
return dtw_dict
| 7,208 |
def fix_bad_symbols(text):
"""
HTML formatting of characters
"""
text = text.replace("è", "è")
text = text.replace("ä", "ä")
text = text.replace("Ã", "Ä")
text = text.replace("Ã", "Ä")
text = text.replace("ö", "ö")
text = text.replace("é", "é")
text = text.replace("Ã¥", "å")
text = text.replace("Ã
", "Å")
text = text.strip()
return text
| 7,209 |
def _level2partition(A, j):
"""Return views into A used by the unblocked algorithms"""
# diagonal element d is A[j,j]
# we access [j, j:j+1] to get a view instead of a copy.
rr = A[j, :j] # row
dd = A[j, j:j+1] # scalar on diagonal / \
B = A[j+1:, :j] # Block in corner | r d |
cc = A[j+1:, j] # column \ B c /
return rr, dd, B, cc
| 7,210 |
def _null_or_int(val: Optional[str]) -> Optional[int]:
"""Nullify unknown elements and convert ints"""
if not isinstance(val, str) or is_unknown(val):
return None
return int(val)
| 7,211 |
def stackset_exists(stackset_name, cf_client):
"""Check if a stack exists or not
Args:
stackset_name: The stackset name to check
cf_client: Boto3 CloudFormation client
Returns:
True or False depending on whether the stack exists
Raises:
Any exceptions raised .describe_stack_set() besides that
the stackset doesn't exist.
"""
try:
logger.info(f"Checking if StackSet {stackset_name} exits.")
cf_client.describe_stack_set(StackSetName=stackset_name, CallAs=call_as)
return True
except Exception as e:
if f"{stackset_name} not found" in str(e) or f"{stackset_name} does not exist" in str(e):
logger.info(f"StackSet {stackset_name} does not exist.")
return False
else:
raise e
| 7,212 |
def main(argv):
"""
Main function for optimization demo
"""
# Get the arguments
cfg_file, RobotWrapper, with_lqr = parse_arguments(argv)
print RobotWrapper
# Compute the motion
(motion_planner, optimized_kin_plan,
optimized_motion_eff,
optimized_dyn_plan,
dynamics_feedback,
planner_setting,
time_vector) = build_and_optimize_motion(cfg_file, RobotWrapper, with_lqr)
# Display the motion
display = True
if(display): # Display the Center of mass motion
motion_planner.plot_com_motion(optimized_dyn_plan.dynamics_states, optimized_kin_plan.kinematics_states)
# for i in range(len(time_vector)):
# print "\n t:",time_vector[i],"\n"
# print dynamics_feedback.forceGain(i)
# motion_planner.plot_centroidal()
# Create configuration and velocity file from motion plan for dynamic graph
try:
print("Replay the kinematics.")
motion_planner.replay_kinematics()
except:
"gepetto not initialized..."
# Dump the computed trajectory in a files (should follow the dynamic graph format)
motion_planner.save_files()
if(display): # plot trajectories
motion_planner.plot_foot_traj()
motion_planner.plot_joint_trajecory()
motion_planner.plot_com_motion(optimized_dyn_plan.dynamics_states, optimized_kin_plan.kinematics_states)
#motion_planner.plot_base_trajecory()
# Potentially simulate the motion
simulation = False
if simulation:
motion_executor = MotionExecutor(optimized_kin_plan, optimized_dyn_plan, dynamics_feedback, planner_setting, time_vector)
motion_executor.execute_motion(plotting=False, tune_online=False)
print('Done...')
| 7,213 |
def convert_l_hertz_to_bins(L_p_Hz, Fs=22050, N=1024, H=512):
"""Convert filter length parameter from Hertz to frequency bins
Notebook: C8/C8S1_HPS.ipynb
Args:
L_p_Hz (float): Filter length (in Hertz)
Fs (scalar): Sample rate (Default value = 22050)
N (int): Window size (Default value = 1024)
H (int): Hop size (Default value = 512)
Returns:
L_p (int): Filter length (in frequency bins)
"""
L_p = int(np.ceil(L_p_Hz * N / Fs))
return L_p
| 7,214 |
def write_cluster_summary(summary_fn, isoforms_fa, hq_fa=None, lq_fa=None):
"""Extract number of consensus isoforms predicted, and total
number of bases in all consensuus isoforms from isoforms_fa and write
the two attributes to summary_fn.
if hq_fa (polished high-quality isoforms) is not None, report
the number of polished hq clusters
if lq_fa (polished high-quality isoforms) is not None, report
the number of polished hq clusters
"""
try:
summary = ClusterSummary()
dataset_uuids = []
with ContigSet(isoforms_fa) as reader:
for r in reader:
summary.num_consensus_isoforms += 1
summary.num_total_bases += len(r.sequence[:])
dataset_uuids.append(reader.uuid)
if hq_fa is not None and op.getsize(hq_fa) > 0:
summary.num_polished_hq_isoforms = 0
with ContigSet(hq_fa) as reader:
for r in reader:
summary.num_polished_hq_isoforms += 1
dataset_uuids.append(reader.uuid)
if lq_fa is not None and op.getsize(lq_fa) > 0:
summary.num_polished_lq_isoforms = 0
with ContigSet(lq_fa) as reader:
for r in reader:
summary.num_polished_lq_isoforms += 1
dataset_uuids.append(reader.uuid)
summary.write(summary_fn, dataset_uuids=dataset_uuids)
except ZeroDivisionError:
errMsg = "No consensus isoforms predicted."
logging.error(errMsg)
raise RuntimeError(errMsg)
| 7,215 |
def macrostate_to_dnf(macrostate, simplify = True):
""" Returns a macrostate in disjunctive normal form (i.e. an OR of ANDs).
Note that this may lead to exponential explosion in the number of terms.
However it is necessary when creating Multistrand Macrostates, which can
only be represented in this way. Also, we don't try to simplify much
so the expressions may be inefficient/redundant. Adding simplifications of the
logical expression using (e.g.) De Morgan's laws is a future optimization. """
from macrostate import Macrostate
if macrostate.type != Macrostate.types['conjunction'] and macrostate.type != Macrostate.types['disjunction']:
dnf_macrostates = [Macrostate(type='conjunction', macrostates=[macrostate])]
elif macrostate.type == Macrostate.types['conjunction']:
clauses = [macrostate_to_dnf(m, simplify=False) for m in macrostate.macrostates]
dnf_macrostates = clauses[0].macrostates
for clause in clauses[1:]:
# multiply two dnf clauses
dnf_macrostates = [Macrostate(type='conjunction', macrostates=m1.macrostates+m2.macrostates) for m1,m2 in it.product(dnf_macrostates, clause.macrostates)]
elif macrostate.type == Macrostate.types['disjunction']:
clauses = [macrostate_to_dnf(m, simplify=False) for m in macrostate.macrostates]
dnf_macrostates = []
for clause in clauses:
# add two dnf clauses
dnf_macrostates += clause.macrostates
# The most basic simplification. We just subsitute AND/OR expressions with only one operand
# with just that operand.
if simplify:
for i,m in enumerate(dnf_macrostates):
if len(m.macrostates) == 1: dnf_macrostates[i]=m.macrostates[0]
if simplify and len(dnf_macrostates)==1:
dnf = dnf_macrostates[0]
else:
dnf = Macrostate(type='disjunction', macrostates=dnf_macrostates)
return dnf
| 7,216 |
def construct_features(all_data):
# type: (pd.DataFrame) -> pd.DataFrame
"""
Create the features for the model
:param all_data: combined processed df
:return: df with features
"""
feature_constructor = FeatureConstructor(all_data)
return feature_constructor.construct_all_features()
| 7,217 |
def tree_viewer(treefolder):
"""
DESCRIPTION:
A function to create the representation of the tree with ete. Given the folder with the files in the tree folder it
creates the tree representation in the media folder.
:param treefolder: [pathlib] route to the subfolder in the tree folder which contains the data of the inference.
:return: None. It writes the image in the media folder.
"""
filename = os.path.basename(os.path.normpath(treefolder)) + '.txt.treefile'
imagefile = os.path.basename(os.path.normpath(treefolder)) + '.png'
treeroute = treefolder / filename
file = open(treeroute, 'r')
tree = file.read()
file.close()
tree = Tree(tree)
circular_style = TreeStyle()
circular_style.mode = "c"
circular_style.scale = 20
tree.render(str(MEDIA_DIR / imagefile), w=1024, units='mm', tree_style=circular_style)
| 7,218 |
def restore_ckpt_from_path(ckpt_path: Text, state: Optional[TrainState] = None):
"""Load a checkpoint from a path."""
if not gfile.exists(ckpt_path):
raise ValueError('Could not find checkpoint: {}'.format(ckpt_path))
logging.info('Restoring checkpoint from %s', ckpt_path)
with gfile.GFile(ckpt_path, 'rb') as fp:
if state is None:
# Returns a dict in MsgPack format. This is useful when the loaded
# checkpoint needs to be sliced and diced to extract only relevant
# parameters.
# E.g. The optimizer state may be ignored when loading from a pretrained
# model.
return serialization.msgpack_restore(fp.read())
else:
return serialization.from_bytes(state, fp.read())
| 7,219 |
def _GetChannelData():
"""Look up the channel data from omahaproxy.appspot.com.
Returns:
A string representing the CSV data describing the Chrome channels. None is
returned if reading from the omahaproxy URL fails.
"""
for unused_i in range(_LOOKUP_RETRIES):
try:
channel_csv = urllib2.urlopen(_OMAHAPROXY_URL)
return channel_csv.read()
except (urllib2.URLError, urllib2.HTTPError):
logging.exception('Exception on reading from the omahaproxy URL.')
return None
| 7,220 |
def look(direction=Dir.HERE):
"""
Looks in a given direction and returns the object found there.
"""
if direction in Dir:
# Issue the command and let the Obj enumeration find out which object is
# in the reply
# Don't use formatted strings in order to stay compatible to Python 3.4
reply = _issue_request("?_look_{0}".format(direction.value))
return Obj.from_str(reply)
else:
raise ValueError("look(...) erlaubt nur eine der Dir-Konstanten.")
| 7,221 |
def test_fixed_grid_meso():
""" This is equivalent to running the following bash script, which produces
GLM grids with split events on the fixed grid at 2 km resolution in a
sector defined by a center lon/lat point and a width and height given by
using the mesoscale lookup.
python make_GLM_grids.py -o /path/to/output/
--fixed_grid --split_events \
--goes_position east --goes_sector meso \
--dx=2.0 --dy=2.0 \
--ctr_lon=-101.5 --ctr_lat=33.5 \
OR_GLM-L2-LCFA_G16_s20181830433000_e20181830433200_c20181830433231.nc \
OR_GLM-L2-LCFA_G16_s20181830433200_e20181830433400_c20181830433424.nc \
OR_GLM-L2-LCFA_G16_s20181830433400_e20181830434000_c20181830434029.nc \
start and end are determined from the filenames.
"""
grid_spec = ["--fixed_grid", "--split_events",
"--goes_position", "east", "--goes_sector", "meso",
"--dx=2.0", "--dy=2.0",
"--ctr_lat=33.5", "--ctr_lon=-101.5",
"--ellipse=0",
]
output_sizes = {
'GLM-00-00_20180702_043300_60_1src_056urad-dx_flash_extent.nc':26370,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_flash_centroid.nc':21052,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_footprint.nc':23939,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_group_area.nc':25637,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_group_extent.nc':27053,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_group_centroid.nc':21305,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_event.nc':26926,
'GLM-00-00_20180702_043300_60_1src_056urad-dx_total_energy.nc':27501,
'OR_GLM-L2-GLMC-M3_G16_s20181830433000_e20181830434000_c20182551446.nc':101023,
'total_energy':total_energy_in_L2(samples),
}
grid_sample_data(grid_spec, output_sizes, dirname='meso'
,save='/data/tmp/glmtest/meso')
| 7,222 |
def process_debug_data(debug_data, model):
"""Process the raw debug data into pandas objects that make visualization easy.
Args:
debug_data (dict): Dictionary containing the following entries (
and potentially others which are not modified):
- filtered_states (list): List of arrays. Each array has shape (n_obs,
n_mixtures, n_states) and contains the filtered states after each Kalman
update. The list has length n_updates.
- initial_states (jax.numpy.array): Array of shape (n_obs, n_mixtures, n_states)
with the state estimates before the first Kalman update.
- residuals (list): List of arrays. Each array has shape (n_obs, n_mixtures)
and contains the residuals of a Kalman update. The list has length
n_updates.
- residual_sds (list): List of arrays. Each array has shape (n_obs, n_mixtures)
and contains the theoretical standard deviation of the residuals. The list
has length n_updates.
- all_contributions (jax.numpy.array): Array of shape (n_updates, n_obs) with
the likelihood contributions per update and individual.
model (dict): Processed model dictionary.
Returns:
dict: Dictionary with processed debug data. It has the following entries:
- pre_update_states (pd.DataFrame): Tidy DataFrame with filtered states before
each update. Columns are factor names, "mixture", "period", "measurement".
and "id". "period" and "measurement" identify the next measurement that
will be incorporated.
- post_update_states (pd.DataFrame). As pre_update_states but "period" and
"measurement" identify the last measurement that was incorporated.
- filtered_states (pd.DataFrame). Tidy DataFrame with filtered states
after the last update of each period. The columns are the factor names,
"period" and "id"
- state_ranges (dict): The keys are the names of the latent factors.
The values are DataFrames with the columns "period", "minimum", "maximum".
Note that this aggregates over mixture distributions.
- residuals (pd.DataFrame): Tidy DataFrame with residuals of each Kalman update.
Columns are "residual", "mixture", "period", "measurement" and "id".
"period" and "measurement" identify the Kalman update to which the residual
belongs.
- residual_sds (pd.DataFrame): As residuals but containing the theoretical
standard deviation of the corresponding residual.
- all_contributions (pd.DataFrame): Tidy DataFrame with log likelihood
contribution per individual and Kalman Update. The columns are
"contribution", "period", "measurement" and "id". "period" and "measurement"
identify the Kalman Update to which the likelihood contribution corresponds.
"""
update_info = model["update_info"]
factors = model["labels"]["factors"]
pre_update_states = _create_pre_update_states(
debug_data["initial_states"],
debug_data["filtered_states"],
factors,
update_info,
)
post_update_states = _create_post_update_states(
debug_data["filtered_states"], factors, update_info
)
filtered_states = _create_filtered_states(post_update_states, update_info)
state_ranges = create_state_ranges(filtered_states, factors)
residuals = _process_residuals(debug_data["residuals"], update_info)
residual_sds = _process_residual_sds(debug_data["residual_sds"], update_info)
all_contributions = _process_all_contributions(
debug_data["all_contributions"], update_info
)
res = {
"pre_update_states": pre_update_states,
"post_update_states": post_update_states,
"filtered_states": filtered_states,
"state_ranges": state_ranges,
"residuals": residuals,
"residual_sds": residual_sds,
"all_contributions": all_contributions,
}
for key in ["value", "contributions"]:
if key in debug_data:
res[key] = debug_data[key]
return res
| 7,223 |
def check_to_cache(local_object, timeout: float = None) -> Tuple[Optional[bool], Optional[str], Optional[str]]:
"""
Type-check current commit and save result to cache. Return status, log, and log filename, or None, None, None if a timeout is hit.
"""
try:
# As a hook we know we're in the project root when running.
mypy_output = subprocess.check_output(['make', 'mypy'], stderr=subprocess.STDOUT, timeout=timeout)
log = mypy_output.decode('utf-8')
# If we get here it passed
filename = write_cache(local_object, True, log)
return True, log, filename
except CalledProcessError as e:
# It did not work.
log = e.output.decode('utf-8')
# Save this in a cache
filename = write_cache(local_object, False, log)
return False, log, filename
except TimeoutExpired:
return None, None, None
| 7,224 |
def merge(a, b, path=None):
"""Deprecated.
merges b into a
Moved to siem.utils.merge_dicts.
"""
if path is None:
path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path + [str(key)])
elif a[key] == b[key]:
pass # same leaf value
elif str(a[key]) in str(b[key]):
# strで上書き。JSONだったのをstrに変換したデータ
a[key] = b[key]
else:
# conflict and override original value with new one
a[key] = b[key]
else:
a[key] = b[key]
return a
| 7,225 |
def cudnnActivationBackward(handle, mode, alpha, srcDesc, srcData, srcDiffDesc,
srcDiffData, destDesc, destData, beta,
destDiffDesc, destDiffData):
""""
Gradient of activation function.
This routine computes the gradient of a neuron activation function.
In-place operation is allowed for this routine; i.e., srcData and destData
pointers may be equal and srcDiffData and destDiffData pointers may be equal.
However, this requires the corresponding tensor descriptors to be identical
(particularly, the strides of the input and output must match for in-place operation
to be allowed).
Parameters
----------
handle : cudnnHandle
Handle to a previously created cuDNN context.
mode : cudnnActivationMode
Enumerant to specify the activation mode.
alpha: float
Scaling factor with which every element of the input tensor is multiplied.
srcDesc : cudnnTensorDescriptor
Handle to the previously initialized input tensor descriptor.
srcData : void_p
Data pointer to GPU memory associated with the tensor descriptor
srcDesc.
srcDiffDesc : cudnnTensorDescriptor
Handle to the previously initialized input differential tensor descriptor.
srcDiffData : void_p
Data pointer to GPU memory associated with the tensor descriptor
srcDiffData.
destDesc : cudnnTensorDescriptor
Handle to the previously initialized output tensor descriptor.
destData : void_p
Data pointer to GPU memory associated with the output tensor descriptor
destDesc.
beta: float
Scaling factor which is applied on every element of the output tensor prior
to adding the result of the activation gradient. Note that if beta is zero, the
output is not read and can contain any uninitialized data (including Nan numbers).
destDiffDesc : cudnnTensorDescriptor
Handle to the previously initialized output differential tensor descriptor.
destDiffData : void_p
Data pointer to GPU memory associated with the output tensor descriptor
destDiffDesc.
"""
dataType = cudnnGetTensor4dDescriptor(destDesc)[0]
if dataType == cudnnDataType['CUDNN_DATA_DOUBLE']:
alphaRef = ctypes.byref(ctypes.c_double(alpha))
betaRef = ctypes.byref(ctypes.c_double(beta))
else:
alphaRef = ctypes.byref(ctypes.c_float(alpha))
betaRef = ctypes.byref(ctypes.c_float(beta))
status = _libcudnn.cudnnActivationBackward(
handle, mode, alphaRef, srcDesc, srcData, srcDiffDesc, srcDiffData,
destDesc, destData, betaRef, destDiffDesc, destDiffData)
cudnnCheckStatus(status)
| 7,226 |
def post_attachment(fbid, media_url, file_type,
is_reusable=False, messaging_type="RESPONSE", tag=None):
""" Sends a media attachment to the specified user
:param str fbid: User id to send the audio.
:param str media_url: Url of a hosted media.
:param str file_type: 'image'/'audio'/'video'/'file'.
:param bool is_reusable: Defines the attachment to be resusable, \
the response will have an attachment_id that can be used to \
re-send the attachment without need to upload it again. (You can \
use the post_reusable_attachment method to upload using the id).
:param str messaging_type: Identifies the message type from: RESPONSE,\
UPDATE AND MESSAGE_TAG (Default: RESPONSE, if MESSAGE_TAG, tag param \
is required)
:param str tag: Tag classifying the message, must be one of the \
following `tags <https://developers.facebook.com/docs/messenger-\
platform/send-messages/message-tags#supported_tags>`_
:return: `Response object <http://docs.python-requests.org/en/\
master/api/#requests.Response>`_
:facebook docs: `/contenttypes <https://developers.facebook.\
com/docs/messenger-platform/send-api-reference/contenttypes>`_
"""
url = MESSAGES_URL.format(access_token=PAGE_ACCESS_TOKEN)
payload = dict()
payload['recipient'] = {'id': fbid}
payload['messaging_type'] = messaging_type
if bool(tag) or messaging_type == "MESSAGE_TAG":
payload['tag'] = tag
attachment_payload = dict()
attachment_payload['url'] = media_url
if is_reusable:
attachment_payload['is_reusable'] = is_reusable
attachment = {"type": file_type, "payload": attachment_payload}
payload['message'] = {"attachment": attachment}
data = json.dumps(payload)
status = requests.post(url, headers=HEADER, data=data)
return status
| 7,227 |
def random_categorical(logits, num_samples, seed):
"""Returns a sample from a categorical distribution. `logits` must be 2D."""
# TODO(siege): Switch to stateless RNG ops.
return tf.random.categorical(
logits=logits, num_samples=num_samples, seed=seed)
| 7,228 |
def create_or_update_dns_record(stack, record_name, record_type, record_value, hosted_zone_name, condition_field=""):
"""Create or Update Route53 Record Resource."""
return stack.stack.add_resource(RecordSetType(
'{0}'.format(record_name.replace('.', '').replace('*', 'wildcard')),
Condition=condition_field,
HostedZoneName='{0}.'.format(hosted_zone_name),
Type=record_type,
TTL="60",
Name='{0}.'.format(record_name),
ResourceRecords=record_value
))
| 7,229 |
def _append_from_array(h5dataset, array, cstop, truncate=False, axis=0):
"""Append to a dataset from an array."""
dstart = h5dataset.shape[0]
dstop = dstart + cstop
h5dataset.resize(dstop, axis=axis)
h5dataset[dstart:dstop] = array[0:cstop]
if not truncate:
h5dataset[dstart+cstop:] = 0.0
| 7,230 |
def med_filt(x, k=201):
"""Apply a length-k median filter to a 1D array x.
Boundaries are extended by repeating endpoints.
"""
if x.ndim > 1:
x = np.squeeze(x)
med = np.median(x)
assert k % 2 == 1, "Median filter length must be odd."
assert x.ndim == 1, "Input must be one-dimensional."
k2 = (k - 1) // 2
y = np.zeros((len(x), k), dtype=x.dtype)
y[:, k2] = x
for i in range(k2):
j = k2 - i
y[j:, i] = x[:-j]
y[:j, i] = x[0]
y[:-j, -(i + 1)] = x[j:]
y[-j:, -(i + 1)] = med
return np.median(y, axis=1)
| 7,231 |
def test_plot_grid(od_cup_anno_bboxes, od_cup_path):
""" Test that `plot_grid` works. """
# test callable args
def callable_args():
return od_cup_anno_bboxes, od_cup_path
plot_grid(display_bboxes, callable_args, rows=1)
# test iterable args
od_cup_paths = [od_cup_path, od_cup_path, od_cup_path]
od_cup_annos = [od_cup_anno_bboxes, od_cup_anno_bboxes, od_cup_anno_bboxes]
def iterator_args():
for path, bboxes in zip(od_cup_paths, od_cup_annos):
yield bboxes, path
plot_grid(display_bboxes, iterator_args(), rows=1)
| 7,232 |
def sync_or_create_user(openid_user):
"""
Checks the user, returned by the authentication-service
Requires a user-dict with at least: sub, email, updated_at
"""
def _validate_user(openid_user):
error = False
msg = ''
if not openid_user.get('sub'):
error = True
msg += ' sub'
if not openid_user.get('email'):
error = True
msg += ' email'
if not openid_user.get('updated_at'):
error = True
msg += ' updated_at'
if error:
return {'error': True, 'msg': 'Missing claims:' + msg}
else:
return {'msg': 'valid openid_user'}
def _insert_user(openid_user):
user = copy.deepcopy(openid_user)
user['max_units'] = 10
# user['active_units'] = []
user['roles'] = ['user']
user['user_id'] = openid_user.get('sub')
# Generate additional, normalized key for db on insert or replace
if openid_user.get('username'):
federated_name = openid_user.get('username')
elif openid_user.get('nickname'):
federated_name = openid_user.get('nickname')
elif openid_user.get('name'):
federated_name = openid_user.get('name')
else:
federated_name = openid_user.get('email').split('@')[0]
user['federated_name'] = federated_name
if _put_item('users', user):
# Tells client, that user is first-time user
# '_action'-key does not persist
user['_action'] = 'inserted'
return user
else:
return {'error': True, 'msg': 'Unable to create user'}
def _sync_user(openid_user, db_user):
# NOTE: First update openid_user with existing local values, as they
# will be overwritten on the put_item-request!
user = copy.deepcopy(openid_user)
user['federated_name'] = db_user.get('federated_name')
user['max_units'] = db_user.get('max_units', 10)
# user['active_units'] = db_user.get('active_units', [])
user['roles'] = db_user.get('roles', ['user'])
user['user_id'] = db_user.get('user_id')
if _put_item('users', user, action='update'):
user['_action'] = 'updated'
return user
else:
return {'error': True, 'msg': 'Unable to sync user'}
valid_input = _validate_user(openid_user)
if valid_input.get('error'):
return valid_input
db_user = get_user(openid_user.get('sub'))
# If no existing user
if db_user.get('error'):
if db_user.get('msg') == 'Item does not exist':
return _insert_user(openid_user)
else:
return db_user
elif db_user.get('updated_at') != openid_user.get('updated_at'):
return _sync_user(openid_user, db_user)
else:
db_user['_action'] = 'checked'
return db_user
| 7,233 |
def all_hmm(task):
"""Concatenate all HMM profiles into a database & press."""
base = noext(task.depends[-1])
# TODO - filter out *_all.hmm from `find` hits
sh("cat %s.hmm `find %s/ -name '*.hmm' | grep -v '_all.hmm'` > %s"
% (base, base, task.target))
sh("hmmpress -f %s" % task.target)
| 7,234 |
def test_catalogs(http_service: Any) -> None:
"""Should return status code 200 and many catalogs in a turtle body."""
url = f"{http_service}/catalogs"
resp = requests.get(url)
assert 200 == resp.status_code
assert 0 < len(resp.content)
assert "text/turtle; charset=utf-8" == resp.headers["Content-Type"]
g = Graph()
g.parse(data=resp.text, format="turtle")
assert 0 < len(g)
| 7,235 |
def add_scalar_typesi_coord(cube, value='sea_ice'):
"""Add scalar coordinate 'typesi' with value of `value`."""
logger.debug("Adding typesi coordinate (%s)", value)
typesi_coord = iris.coords.AuxCoord(value,
var_name='type',
standard_name='area_type',
long_name='Sea Ice area type',
units=Unit('no unit'))
try:
cube.coord('area_type')
except iris.exceptions.CoordinateNotFoundError:
cube.add_aux_coord(typesi_coord, ())
return cube
| 7,236 |
def related_tags(parser, token):
"""
Retrieves a list of instances of a given model which are tagged with
a given ``Tag`` and stores them in a context variable.
Usage::
{% related_tags [objects] as [varname] %}
The model is specified in ``[appname].[modelname]`` format.
The tag must be an instance of a ``Tag``, not the name of a tag.
Example::
{% tagged_objects comedy_tag in tv.Show as comedies %}
"""
bits = token.contents.split()
if len(bits) != 4:
raise TemplateSyntaxError(_('%s tag requires exactly 3 arguments') % bits[0])
if bits[2] != 'as':
raise TemplateSyntaxError(_("second argument to %s tag must be 'as'") % bits[0])
#pdb.set_trace()
return RelatedTagsNode(bits[1], bits[3])
| 7,237 |
def test_dates():
"""Test using dates."""
rm = RangeMap()
rm.set('b', datetime.date(1936, 12, 11))
rm.set('a', datetime.date(1952, 2, 6))
assert rm[datetime.date(1945, 1, 1)] == 'b'
assert rm[datetime.date(1965, 4, 6)] == 'a'
with pytest.raises(KeyError):
rm[datetime.date(1900, 1, 1)]
| 7,238 |
def ShowOnce(msg):
"""Display a message if that message has not been shown already.
Unlike logging.log_first_n, this will display multiple messages from the same
file/line if they are different. This helps for things like the same line
that shows 'missing %s': we'll see each value of %s instead of only the first.
Args:
msg: A string message to write to stderr.
"""
global _displayed_errors
if msg in _displayed_errors:
return
_displayed_errors.add(msg)
print(msg, file=sys.stderr)
| 7,239 |
def assess():
""" RESTful CRUD controller """
# Load Models
assess_tables()
impact_tables()
tablename = "%s_%s" % (module, resourcename)
table = db[tablename]
# Pre-processor
def prep(r):
if session.s3.mobile and r.method == "create" and r.interactive:
# redirect to mobile-specific form:
redirect(URL(f="assess_short_mobile"))
return True
response.s3.prep = prep
#table.incident_id.comment = DIV(_class="tooltip",
# _title="%s|%s" % (T("Incident"),
# T("Optional link to an Incident which this Assessment was triggered by.")))
tabs = [
(T("Edit Details"), None),
(T("Baselines"), "baseline"),
(T("Impacts"), "impact"),
(T("Summary"), "summary"),
#(T("Requested"), "ritem"),
]
rheader = lambda r: assess_rheader(r, tabs)
return s3_rest_controller(rheader=rheader)
| 7,240 |
def local_purity(H, y, nn=None, num_samples=10):
"""
:param H: embedding to evaluate
:param y: ground-truth classes
:param nn: number of neighbours to consider, if nn=None evaluate for nn=[1...size of max cluster]
:param num_samples: number of samples in the range (1, size of max cluster)
"""
if nn is None:
max_size_cluster = np.unique(y, return_counts=True)[1].max()
return np.fromiter((__local_purity(H, y, nn)
for nn in np.linspace(0, max_size_cluster, num_samples).astype(np.int32)), np.float32)
else:
return __local_purity(H, y, nn)
| 7,241 |
def test_get_sample_process_captures_output_by_default():
"""Test that get_sample_process will enable stdout and stderr capture by default."""
cmd = 'echo "hey there!"'
result: snafu.process.ProcessSample = snafu.process.get_process_sample(cmd, LOGGER, shell=True, retries=0)
assert result.successful.stdout == "hey there!\n"
no_capture_args = {
"capture_output": False,
"stdout": None,
"stderr": None,
}
for arg, val in no_capture_args.items():
print(arg, val)
result: snafu.process.ProcessSample = snafu.process.get_process_sample(
cmd, LOGGER, shell=True, retries=0, **{arg: val}
)
assert result.successful.stdout is None
| 7,242 |
def flatten_sxpr(sxpr: str, threshold: int = -1) -> str:
"""
Returns S-expression ``sxpr`` as a one-liner without unnecessary
whitespace.
The ``threshold`` value is a maximum number of
characters allowed in the flattened expression. If this number
is exceeded the the unflattened S-expression is returned. A
negative number means that the S-expression will always be
flattened. Zero or (any postive integer <= 3) essentially means
that the expression will not be flattened. Example::
>>> flatten_sxpr('(a\\n (b\\n c\\n )\\n)\\n')
'(a (b c))'
:param sxpr: and S-expression in string form
:param threshold: maximum allowed string-length of the flattened
S-exrpession. A value < 0 means that it may be arbitrarily long.
:return: Either flattened S-expression or, if the threshold has been
overstepped, the original S-expression without leading or
trailing whitespace.
"""
assert RX_IS_SXPR.match(sxpr)
if threshold == 0:
return sxpr
flat = re.sub(r'\s(?=\))', '', re.sub(r'(?<!")\s+', ' ', sxpr).replace('\n', '')).strip()
if len(flat) > threshold > 0:
return sxpr.strip()
return flat
| 7,243 |
def chunks(sequence: Iterable[T], chunk_size: int = 2) -> Iterable[List[T]]:
"""
[1,2,3,4,5], 2 --> [[1,2],[3,4],[5]]
"""
lsequence = list(sequence)
while lsequence:
size = min(len(lsequence), chunk_size)
yield lsequence[:size]
lsequence = lsequence[size:]
| 7,244 |
def glycan_to_graph(glycan, libr = None):
"""the monumental function for converting glycans into graphs\n
| Arguments:
| :-
| glycan (string): IUPAC-condensed glycan sequence (string)
| libr (list): sorted list of unique glycoletters observed in the glycans of our dataset\n
| Returns:
| :-
| (1) a list of labeled glycoletters from the glycan / node list
| (2) two lists to indicate which glycoletters are connected in the glycan graph / edge list
"""
if libr is None:
libr = lib
bracket_count = glycan.count('[')
parts = []
branchbranch = []
branchbranch2 = []
position_bb = []
b_counts = []
bb_count = 0
#checks for branches-within-branches and handles them
if bool(re.search('\[[^\]]+\[', glycan)):
double_pos = [(k.start(),k.end()) for k in re.finditer('\[[^\]]+\[', glycan)]
for spos, pos in double_pos:
bracket_count -= 1
glycan_part = glycan[spos+1:]
glycan_part = glycan_part[glycan_part.find('['):]
idx = [k.end() for k in re.finditer('\][^\(]+\(', glycan_part)][0]
idx2 = [k.start() for k in re.finditer('\][^\(]+\(', glycan_part)][0]
branchbranch.append(glycan_part[:idx-1].replace(']','').replace('[',''))
branchbranch2.append(glycan[pos-1:])
glycan_part = glycan[:pos-1]
b_counts.append(glycan_part.count('[')-bb_count)
glycan_part = glycan_part[glycan_part.rfind('[')+1:]
position_bb.append(glycan_part.count('(')*2)
bb_count += 1
for b in branchbranch2:
glycan = glycan.replace(b, ']'.join(b.split(']')[1:]))
main = re.sub("[\[].*?[\]]", "", glycan)
position = []
branch_points = [x.start() for x in re.finditer('\]', glycan)]
for i in branch_points:
glycan_part = glycan[:i+1]
glycan_part = re.sub("[\[].*?[\]]", "", glycan_part)
position.append(glycan_part.count('(')*2)
parts.append(main)
for k in range(1,bracket_count+1):
start = find_nth(glycan, '[', k) + 1
#checks whether glycan continues after branch
if bool(re.search("[\]][^\[]+[\(]", glycan[start:])):
#checks for double branches and removes second branch
if bool(re.search('\]\[', glycan[start:])):
glycan_part = re.sub("[\[].*?[\]]", "", glycan[start:])
end = re.search("[\]].*?[\(]", glycan_part).span()[1] - 1
parts.append(glycan_part[:end].replace(']',''))
else:
end = re.search("[\]].*?[\(]", glycan[start:]).span()[1] + start -1
parts.append(glycan[start:end].replace(']',''))
else:
if bool(re.search('\]\[', glycan[start:])):
glycan_part = re.sub("[\[].*?[\]]", "", glycan[start:])
end = len(glycan_part)
parts.append(glycan_part[:end].replace(']',''))
else:
end = len(glycan)
parts.append(glycan[start:end].replace(']',''))
try:
for bb in branchbranch:
parts.append(bb)
except:
pass
parts = min_process_glycans(parts)
parts_lengths = [len(j) for j in parts]
parts_tokenized = [string_to_labels(k, libr) for k in parts]
parts_tokenized = [parts_tokenized[0]] + [parts_tokenized[k][:-1] for k in range(1,len(parts_tokenized))]
parts_tokenized = [item for sublist in parts_tokenized for item in sublist]
range_list = list(range(len([item for sublist in parts for item in sublist])))
init = 0
parts_positions = []
for k in parts_lengths:
parts_positions.append(range_list[init:init+k])
init += k
for j in range(1,len(parts_positions)-len(branchbranch)):
parts_positions[j][-1] = position[j-1]
for j in range(1, len(parts_positions)):
try:
for z in range(j+1,len(parts_positions)):
parts_positions[z][:-1] = [o-1 for o in parts_positions[z][:-1]]
except:
pass
try:
for i,j in enumerate(range(len(parts_positions)-len(branchbranch), len(parts_positions))):
parts_positions[j][-1] = parts_positions[b_counts[i]][position_bb[i]]
except:
pass
pairs = []
for i in parts_positions:
pairs.append([(i[m],i[m+1]) for m in range(0,len(i)-1)])
pairs = list(zip(*[item for sublist in pairs for item in sublist]))
return parts_tokenized, pairs
| 7,245 |
def _check_argument_units(args, dimensionality):
"""Yield arguments with improper dimensionality."""
for arg, val in args.items():
# Get the needed dimensionality (for printing) as well as cached, parsed version
# for this argument.
try:
need, parsed = dimensionality[arg]
except KeyError:
# Argument did not have units specified in decorator
continue
# See if the value passed in is appropriate
try:
if val.dimensionality != parsed:
yield arg, val.units, need
# No dimensionality
except AttributeError:
# If this argument is dimensionless, don't worry
if parsed != '':
yield arg, 'none', need
| 7,246 |
def run(ex: "interactivity.Execution") -> "interactivity.Execution":
"""Exit the shell."""
ex.shell.shutdown = True
return ex.finalize(
status="EXIT",
message="Shutting down the shell.",
echo=True,
)
| 7,247 |
def get_features(df, row = False):
""" Transform the df into a df with basic features and dropna"""
df_feat = df
df_feat['spread'] = df_feat['high'] - df_feat['low']
df_feat['upper_shadow'] = upper_shadow(df_feat)
df_feat['lower_shadow'] = lower_shadow(df_feat)
df_feat['close-open'] = df_feat['close'] - df_feat['open']
df_feat['SMA_7'] = df_feat.iloc[:,1].rolling(window=7).mean()
df_feat['SMA_14'] = df_feat.iloc[:,1].rolling(window=14).mean()
df_feat['SMA_21'] = df_feat.iloc[:,1].rolling(window=21).mean()
# Create the STD_DEV feature for the past 7 days
df_feat['STD_DEV_7'] = df_feat.iloc[:,1].rolling(window=7).std()
# Features from ta-lib as example
df_feat.ta.donchian(lower_length=10, upper_length=15, append=True)
# Drop the NA rows created by the SMA indicators
df_feat.dropna(inplace = True)
return df_feat
| 7,248 |
def match_prob_for_sto_embed(sto_embed_word, sto_embed_vis):
"""
Compute match probability for two stochastic embeddings
:param sto_embed_word: (batch_size, num_words, hidden_dim * 2)
:param sto_embed_vis: (batch_size, num_words, hidden_dim * 2)
:return (batch_size, num_words)
"""
assert not bool(torch.isnan(sto_embed_word).any()) and not bool(torch.isnan(sto_embed_vis).any())
batch_size = sto_embed_word.shape[0]
num_words = sto_embed_word.shape[1]
mu_word, var_word = torch.split(sto_embed_word, DIM_EMBED, dim=-1)
mu_vis, var_vis = torch.split(sto_embed_vis, DIM_EMBED, dim=-1)
if cfg.metric == 'monte-carlo':
k = SAMPLING_K
z_word = batch_rsample(mu_word, var_word, k) # (batch_size, num_words, k, hidden_dim)
z_vis = batch_rsample(mu_vis, var_vis, k) # (batch_size, num_words, k, hidden_dim)
num_samples = k
z_word = z_word.unsqueeze(3).repeat([1, 1, 1, k, 1]) # (batch_size, num_words, k, k, hidden_dim)
z_vis = z_vis.repeat([1, 1, k, 1]).reshape(list(z_vis.shape[:2]) + [k, k, -1]) # (batch_size, num_words, k, k, hidden_dim)
if z_vis.shape[1] == 1:
z_vis = z_vis.repeat([1, num_words, 1, 1, 1]) # (batch_size, num_words, k, k, hidden_dim)
# Compute probabilities for all pair combinations
match_prob = - torch.sqrt(torch.sum((z_word - z_vis) ** 2, dim=-1))
match_prob = match_prob.sum(-1).sum(-1) / (num_samples ** 2)
if k > 1 and batch_size > 1 and num_words > 0:
assert bool(torch.all(z_word[0, 0, 0, 0] == z_word[0, 0, 0, 1]))
assert bool(torch.all(z_vis[0, 0, 0, 0] == z_vis[0, 0, 1, 0]))
if sto_embed_vis.shape[1] == 1 and num_words > 1:
assert bool(torch.all(z_vis[0, 0] == z_vis[0, 1]))
elif cfg.metric == 'w-distance':
match_prob = torch.sum((mu_word - mu_vis) ** 2 + (torch.sqrt(var_word) - torch.sqrt(var_vis)) ** 2, dim=-1)
else:
raise ValueError('Unexpected metric type')
assert match_prob.shape == (batch_size, num_words)
return match_prob
| 7,249 |
def POST(path):
"""
Define decorator @post('/path'):
"""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kw):
return func(*args, **kw)
wrapper.__method__ = 'POST'
wrapper.__route__ = path
return wrapper
return decorator
| 7,250 |
def BatchNorm(
inputs, axis=-1, momentum=0.9, eps=1e-5,
use_stats=-1, **kwargs):
"""Batch Normalization. `[Ioffe & Szegedy, 2015] <https://arxiv.org/abs/1502.03167>`_.
We enforce the number of inputs should be *5*, i.e.,
it is implemented into a fused version.
However, you can still fix the *gamma* and *beta*,
by disabling the their gradients directly.
**Type Constraints**: (*float16*, *float32*)
Parameters
----------
inputs : sequence of Tensor
The inputs, represent [x, mean, var, gamma, beta].
axis : int, optional
The channel axis.
momentum : float, optional, default=0.99
The momentum of moving average.
eps : float, optional, default=1e-5
The eps.
use_stats : int, optional, default=-1
Whether to use global stats.
Returns
-------
Tensor
The output tensor, calculated as:
|batchnorm_scale_function|
The moving average of mean/var, calculated as:
|default_moving_average_function|
"""
return Tensor.CreateOperator('BatchNorm', **ParseArgs(locals()))
| 7,251 |
async def test_create_doorbell(opp):
"""Test creation of a doorbell."""
doorbell_one = await _mock_doorbell_from_fixture(opp, "get_doorbell.json")
await _create_august_with_devices(opp, [doorbell_one])
binary_sensor_k98gidt45gul_name_motion = opp.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_OFF
binary_sensor_k98gidt45gul_name_online = opp.states.get(
"binary_sensor.k98gidt45gul_name_online"
)
assert binary_sensor_k98gidt45gul_name_online.state == STATE_ON
binary_sensor_k98gidt45gul_name_ding = opp.states.get(
"binary_sensor.k98gidt45gul_name_ding"
)
assert binary_sensor_k98gidt45gul_name_ding.state == STATE_OFF
binary_sensor_k98gidt45gul_name_motion = opp.states.get(
"binary_sensor.k98gidt45gul_name_motion"
)
assert binary_sensor_k98gidt45gul_name_motion.state == STATE_OFF
| 7,252 |
def problem_from_graph(graph):
""" Create a problem from the given interaction graph. For each interaction (i,j), 0 <= i <= j <= 1 is added. """
n = graph.vcount()
domain = Domain.make([], [f"x{i}" for i in range(n)], real_bounds=(0, 1))
X = domain.get_symbols()
support = smt.And(*((X[e.source] <= X[e.target]) for e in graph.es))
return Density(domain, support & domain.get_bounds(), smt.Real(1))
| 7,253 |
def rotate_points(x, y, x0, y0, phi):
"""
Rotate x and y around designated center (x0, y0).
Args:
x: x-values of point or array of points to be rotated
y: y-values of point or array of points to be rotated
x0: horizontal center of rotation
y0: vertical center of rotation
phi: angle to rotate (+ is ccw) in radians
Returns:
x, y: locations of rotated points
"""
xp = x - x0
yp = y - y0
s = np.sin(-phi)
c = np.cos(-phi)
xf = xp * c - yp * s
yf = xp * s + yp * c
xf += x0
yf += y0
return xf, yf
| 7,254 |
def xpme(
dates: List[date],
cashflows: List[float],
prices: List[float],
pme_prices: List[float],
) -> float:
"""Calculate PME for unevenly spaced / scheduled cashflows and return the PME IRR
only.
"""
return verbose_xpme(dates, cashflows, prices, pme_prices)[0]
| 7,255 |
def get_node(uuid):
"""Get node from cache by it's UUID.
:param uuid: node UUID.
:returns: structure NodeInfo.
"""
row = _db().execute('select * from nodes where uuid=?', (uuid,)).fetchone()
if row is None:
raise utils.Error('Could not find node %s in cache' % uuid, code=404)
return NodeInfo.from_row(row)
| 7,256 |
def bisect_jump_time(tween, value, b, c, d):
"""
**** Not working yet
return t for given value using bisect
does not work for whacky curves
"""
max_iter = 20
resolution = 0.01
iter = 1
lower = 0
upper = d
while iter < max_iter:
t = (upper - lower) / 2
if tween(t, b, c, d) - value < resolution:
return t
else:
upper = t
| 7,257 |
def __session_kill():
"""
unset session on the browser
Returns:
a 200 HTTP response with set-cookie to "expired" to unset the cookie on the browser
"""
res = make_response(jsonify(__structure(status="ok", msg=messages(__language(), 166))))
res.set_cookie("key", value="expired")
return res
| 7,258 |
def register_errorhandlers(app):
"""Register error handlers."""
def render_error(error):
"""Render error template."""
# If a HTTPException, pull the `code` attribute; default to 500
error_code = getattr(error, "code", 500)
return render_template(f"errors/{error_code}.html"), error_code
for errcode in [401, 404, 500]:
app.errorhandler(errcode)(render_error)
return None
| 7,259 |
def lock():
"""
Locks deploy
Parallel deploys are not allowed
"""
ensure('build_to')
echo_subtask("Creating `deploy.lock` file")
create_entity(
'/'.join([fetch('deploy_to'), 'deploy.lock'])
, entity_type='file',
protected=False
)
| 7,260 |
def test_learn_periodic_id():
"""Test ovk periodic estimator fit, predict. A=Id."""
regr_1 = ovk.OVKRidge('DPeriodic', lbda=0.01, period=2 * pi, theta=.99)
regr_1.fit(X, y)
assert regr_1.score(X_test, y_t) > 0.9
| 7,261 |
def pca_run(plink, sigmathreshold, projection_on_populations, numof_pc, numof_threads, draw_evec, draw_without_projection):
""" run eigenstrat program """
# ------------------------ #
# - run eigenstrat program - #
# ------------------------ #
plink_pca = plink + "_" + str(numof_pc) + "PC"
teststring = "%s -i %s.eigenstratgeno -a %s.snp -b %s.ind -k %s -o %s.pca -p %s.plot -e %s.eval -l %s.log -m 5 -t %s -s %s -w %s -f %s -g %s.snpweights" \
% (pca_main_program,
plink,
plink,
plink,
numof_pc,
plink_pca,
plink_pca,
plink_pca,
plink_pca,
numof_pc,
sigmathreshold,
projection_on_populations,
numof_threads,
plink_pca)
print >> sys.stderr, teststring
cmd = Command("%s -i %s.eigenstratgeno -a %s.snp -b %s.ind -k %s -o %s.pca -p %s.plot -e %s.eval -l %s.log -m 5 -t %s -s %s -w %s -f 1 -g %s.snpweights"
% (pca_main_program,
plink,
plink,
plink,
numof_pc,
plink_pca,
plink_pca,
plink_pca,
plink_pca,
numof_pc,
sigmathreshold,
projection_on_populations,
plink_pca))
cmd.run()
del cmd
# draw first two PCs
os.system("R --slave --args %s < %s" % (plink_pca, draw_evec))
# read which batches (HapMap) were used for projection
projection_batches = {}
try:
fh_proj = file(projection_on_populations, "r")
except IOError, e:
print e
sys.exit(1)
line = fh_proj.readline().rstrip('\n')
while line:
list = re.split("\s+", line)
if list[0] == "":
del list[0]
projection_batches[list[0]] = list[0]
line = fh_proj.readline().rstrip('\n')
fh_proj.close()
# re-write pca.evec file without projection samples (HapMap samples)
try:
fh_pcaevec = file(plink_pca + ".pca.evec", "r")
fh_pcaevec_new = file(plink_pca + ".withoutProjection.pca.evec", "w")
except IOError, e:
print e
sys.exit(1)
# skip header line
line = fh_pcaevec.readline().rstrip('\n')
line = fh_pcaevec.readline().rstrip('\n')
while line:
list = re.split("\s+", line)
if list[0] == "":
del list[0]
if list[-1] == "":
del list[-1]
if not list[-1] in projection_batches:
for i in xrange(len(list)):
if i == 0:
fh_pcaevec_new.writelines(list[i])
else:
fh_pcaevec_new.writelines("\t" + list[i])
fh_pcaevec_new.writelines("\n")
line = fh_pcaevec.readline().rstrip('\n')
fh_pcaevec.close()
fh_pcaevec_new.close()
# draw first two PCs without HapMap samples
os.system("R --slave --args %s %s < %s" % (plink_pca, plink_pca + ".withoutProjection", draw_without_projection))
| 7,262 |
def login(browser):
"""
Login to OKPy.
"""
token = refresh_token(no_browser=not browser)
print("Token = {}".format(token))
print("Token automatically saved")
| 7,263 |
def register(key):
"""Register callable object to global registry.
This is primarily used to wrap classes and functions into the bcdp pipeline.
It is also the primary means for which to customize bcdp for your own
usecases when overriding core functionality is required.
Parameters
----------
key : str
Key for obj in registry. Append periods ('.') to navigate the registry
tree. Example: 'data_source.rcmed'
Returns
-------
dec : function
Generic decorator which returns the wrapped class or function.
"""
def dec(obj):
registry[key] = obj
return obj
return dec
| 7,264 |
def _windows_long_path_name(short_path):
"""Use Windows' `GetLongPathNameW` via ctypes to get the canonical,
long path given a short filename.
"""
if not isinstance(short_path, six.text_type):
short_path = short_path.decode(_fsencoding())
import ctypes
buf = ctypes.create_unicode_buffer(260)
get_long_path_name_w = ctypes.windll.kernel32.GetLongPathNameW
return_value = get_long_path_name_w(short_path, buf, 260)
if return_value == 0 or return_value > 260:
# An error occurred
return short_path
else:
long_path = buf.value
# GetLongPathNameW does not change the case of the drive
# letter.
if len(long_path) > 1 and long_path[1] == ':':
long_path = long_path[0].upper() + long_path[1:]
return long_path
| 7,265 |
def _create_behavioral_cloning_agent(
time_step_spec: types.NestedTensorSpec, action_spec: types.NestedTensorSpec,
preprocessing_layers: types.NestedLayer,
policy_network: types.Network) -> tfa.agents.TFAgent:
"""Creates a behavioral_cloning_agent."""
network = policy_network(
time_step_spec.observation,
action_spec,
preprocessing_layers=preprocessing_layers,
name='QNetwork')
return behavioral_cloning_agent.BehavioralCloningAgent(
time_step_spec, action_spec, cloning_network=network, num_outer_dims=2)
| 7,266 |
def prep_fastq_inputs(in_files, data):
"""Prepare bgzipped fastq inputs
"""
if len(in_files) == 1 and _is_bam_input(in_files):
out = _bgzip_from_bam(in_files[0], data["dirs"], data)
elif len(in_files) == 1 and _is_cram_input(in_files):
out = _bgzip_from_cram(in_files[0], data["dirs"], data)
elif len(in_files) in [1, 2] and _ready_gzip_fastq(in_files, data):
out = _symlink_in_files(in_files, data)
else:
if len(in_files) > 2:
fpairs = fastq.combine_pairs(in_files)
pair_types = set([len(xs) for xs in fpairs])
assert len(pair_types) == 1
fpairs.sort(key=lambda x: os.path.basename(x[0]))
organized = [[xs[0] for xs in fpairs]]
if len(fpairs[0]) > 1:
organized.append([xs[1] for xs in fpairs])
in_files = organized
parallel = {"type": "local", "num_jobs": len(in_files),
"cores_per_job": max(1, data["config"]["algorithm"]["num_cores"] // len(in_files))}
inputs = [{"in_file": x, "read_num": i, "dirs": data["dirs"], "config": data["config"],
"is_cwl": "cwl_keys" in data,
"rgnames": data["rgnames"]}
for i, x in enumerate(in_files) if x]
out = run_multicore(_bgzip_from_fastq_parallel, [[d] for d in inputs], data["config"], parallel)
return out
| 7,267 |
def Parser_fake_quantize_range_abs_max(args):
"""
A placeholder for an empty function.
"""
pass
| 7,268 |
def sidequery():
"""Serves AJAX call for HTML content for the sidebar (*query* **record** page).
Used when the user is switching between **material** and **record** pages.
See also [M:RECORD.body][record.RECORD.body].
Client code: [{sidecontent.fetch}][sidecontentfetch].
"""
session.forget(response)
Query = QUERY()
Record = RECORDQUERY(Query)
return Record.body()
| 7,269 |
def test_non_positive_integer_min_exclusive004_1580_non_positive_integer_min_exclusive004_1580_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : (facet=minExclusive and value=-7 and
facet=maxInclusive and value=-1) and document value=-5
"""
assert_bindings(
schema="msData/datatypes/Facets/nonPositiveInteger/nonPositiveInteger_minExclusive004.xsd",
instance="msData/datatypes/Facets/nonPositiveInteger/nonPositiveInteger_minExclusive004.xml",
class_name="Test",
version="1.1",
mode=mode,
save_output=save_output,
output_format=output_format,
structure_style="filenames",
)
| 7,270 |
def learn_encoding_model_ln(sess, met, stimulus, response, ttf_in=None,
initialize_RF_using_ttf=True,
scale_ttf=True, lr=0.1,
lam_l1_rf=0):
"""Learn GLM encoding model using the metric.
Uses ttf to initialize the RF only if ttf_in is given and
initialize_RF_using_ttf=True.
If scale_ttf is True, it scales time course to match firing rate
in observed data.
"""
# get paramters
data_len = stimulus.shape[0]
n_cells = response.shape[2]
dimx = stimulus.shape[1]
dimy = stimulus.shape[2]
# generate responses using current parameters.
# stimulus - response placeholders
stim_tf = tf.placeholder(dtype=tf.float32, shape=[None, dimx, dimy])
resp_tf = tf.placeholder(dtype=tf.float32, shape=[None, n_cells])
# Compute variables.
tlen = 30
if ttf_in is None:
ttf = tf.Variable(0.1 + 0*np.random.randn(tlen).astype(np.float32),
name='ttf')
else:
ttf = tf.Variable(ttf_in.astype(np.float32), name='ttf')
# Time filter.
stim_inp = tf.expand_dims(tf.transpose(stim_tf, [1, 0, 2]), 3)
ttf_filt = tf.expand_dims(tf.expand_dims(tf.expand_dims(ttf, 1), 2), 3)
stim_time_filtered = tf.nn.conv2d(stim_inp, ttf_filt, strides=[1, 1, 1, 1],
padding='VALID')
stim_time_filt_reshape = tf.transpose(stim_time_filtered,
[1, 0, 2, 3])
# Initialize remaining variables
uninitialized_vars = []
for var in tf.all_variables():
try:
sess.run(var)
except tf.errors.FailedPreconditionError:
uninitialized_vars.append(var)
init_new_vars_op = tf.variables_initializer(uninitialized_vars)
sess.run(init_new_vars_op)
# compute STAs
if ttf_in is None or not initialize_RF_using_ttf :
stas_np = None
print('RF will be randomly initialized')
else:
stas = tf.reshape(tf.matmul(tf.transpose(tf.reshape(stim_time_filt_reshape
, [-1, dimx*dimy])),
resp_tf), [dimx, dimy, n_cells])
print('RF will be initialized to STAs computed using given ttf')
batch_sz = data_len - tlen
end_time = data_len
feed_dict = {stim_tf: stimulus[end_time-batch_sz-(tlen-1):
end_time, : , : ].astype(np.float32),
resp_tf: response[0, end_time-batch_sz:
end_time, : ].astype(np.float32)}
stas_np = sess.run(stas, feed_dict=feed_dict)
# Space filter.
if stas_np is None:
RF_all = tf.Variable(0.1 + 0*np.random.randn(dimx, dimy,
n_cells).astype(np.float32),
name='RFs')
else :
RF_all = tf.Variable(stas_np.astype(np.float32),
name='RFs')
stim_space_filtered = tf.reduce_sum(tf.reduce_sum(stim_time_filt_reshape * RF_all, 2),
1) # ? x n_cells
generator_signal = stim_space_filtered
firing_rate = tf.nn.relu(generator_signal)
# update parameters.
distances = met.get_expected_score(firing_rate, resp_tf)
# distances = tf.reduce_sum(tf.pow(firing_rate - resp_tf, 2), 1)
loss_encoding = (tf.reduce_sum(distances) +
lam_l1_rf*tf.reduce_sum(tf.abs(RF_all)))
train_step_RF = tf.train.AdamOptimizer(lr).minimize(loss_encoding,
var_list=[RF_all])
train_step_ttf = tf.train.AdamOptimizer(lr).minimize(loss_encoding,
var_list=[ttf])
# Initialize remaining variables
uninitialized_vars = []
for var in tf.all_variables():
try:
sess.run(var)
except tf.errors.FailedPreconditionError:
uninitialized_vars.append(var)
init_new_vars_op = tf.variables_initializer(uninitialized_vars)
sess.run(init_new_vars_op)
## Learning
# test data
batch_sz = 1000
end_time = np.random.randint(batch_sz, data_len)
feed_dict_test = {stim_tf: stimulus[end_time-batch_sz-(tlen-1): end_time,:,:].astype(np.float32),
resp_tf: response[0, end_time-batch_sz: end_time, :].astype(np.float32)}
# Scale RF and TTF
# Scale time course to match firing rate of all cells.
if scale_ttf:
scale_ttf = tf.reduce_mean(resp_tf) / tf.reduce_mean(firing_rate)
update_ttf = tf.assign(ttf, ttf*scale_ttf)
batch_sz = 1000
end_time = np.random.randint(batch_sz, data_len)
feed_dict = {stim_tf: stimulus[end_time-batch_sz-(tlen-1): end_time,:,:].astype(np.float32),
resp_tf: response[0, end_time-batch_sz: end_time, :].astype(np.float32)}
sess.run(update_ttf, feed_dict=feed_dict)
print('Time course scaled to match firing rate')
# TODO(bhaishahster): Scale RF to match firing rate of individual cells.
for outer_iter in range(10):
# Plot test loss
loss_encoding_np_test = sess.run(loss_encoding, feed_dict=feed_dict_test)
print(outer_iter, loss_encoding_np_test)
# Learn spatial RF
for iiter in range(1000):
end_time = np.random.randint(batch_sz+1000, data_len)
feed_dict = {stim_tf: stimulus[end_time-batch_sz-(tlen-1): end_time,:,:].astype(np.float32),
resp_tf: response[0, end_time-batch_sz: end_time, :].astype(np.float32)}
_, loss_encoding_np = sess.run([train_step_RF, loss_encoding],
feed_dict=feed_dict)
'''
if iiter % 100 == 0:
loss_encoding_np_test = sess.run(loss_encoding, feed_dict=feed_dict_test)
print(iiter, end_time, loss_encoding_np, loss_encoding_np_test)
'''
# Learn temporal part
for iiter in range(1000):
end_time = np.random.randint(batch_sz+1000, data_len)
feed_dict = {stim_tf: stimulus[end_time-batch_sz-(tlen-1): end_time,:,:].astype(np.float32),
resp_tf: response[0, end_time-batch_sz: end_time, :].astype(np.float32)}
_, loss_encoding_np = sess.run([train_step_ttf, loss_encoding],
feed_dict=feed_dict)
# Collect return parameters.
RF_np = sess.run(RF_all)
ttf_np = sess.run(ttf)
encoding_model = collections.namedtuple('encoding_model',
['stimulus', 'firing_rate'])
model = encoding_model(stim_tf, firing_rate)
return RF_np, ttf_np, model
'''
# do some response prediction
batch_sz = 1000
end_time = np.random.randint(batch_sz, data_len)
feed_dict_fr = {stim_tf: stimulus[end_time-batch_sz-(tlen-1): end_time,:,:].astype(np.float32),
resp_tf: response[0, end_time-batch_sz: end_time, :].astype(np.float32)}
fr_np = self.sess.run(firing_rate, feed_dict=feed_dict_fr)
spks_sample = np.sum(np.random.rand(batch_sz, n_cells) < fr_np)
spks_rec = np.sum(response[0, end_time-batch_sz: end_time, :].astype(np.float32))
print('True spks %d, sample spks %d' % (spks_rec, spks_sample))
plt.plot(fr_np[:, 0]);
plt.show()
# plot RF
RF_np = self.sess.run(RF_all)
plt.figure()
for icell in range(n_cells):
plt.subplot(np.ceil(np.sqrt(n_cells)), np.ceil(np.sqrt(n_cells)), icell+1)
plt.imshow(RF_np[:, :, icell], interpolation='nearest', cmap='gray')
plt.show()
# plot ttf
ttf_np = self.sess.run(ttf)
plt.plot(ttf_np)
plt.hold(True)
plt.plot(ttf_in)
plt.legend(['Fit', 'Initialized'])
plt.title('ttf')
plt.show()
'''
| 7,271 |
def _moveTo(x, y):
"""Send the mouse move event to Windows by calling SetCursorPos() win32
function.
Args:
button (str): The mouse button, either 'left', 'middle', or 'right'
x (int): The x position of the mouse event.
y (int): The y position of the mouse event.
Returns:
None
"""
extra = ctypes.c_ulong(0)
ii_ = INPUT_I()
ii_.mi = MOUSEINPUT(x, y, 0, (MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE), 0, ctypes.pointer(extra))
command = INPUT(ctypes.c_ulong(0), ii_)
ctypes.windll.user32.SendInput(1, ctypes.pointer(command), ctypes.sizeof(command))
# ctypes.windll.user32.SetCursorPos(x, y)
# This was a possible solution to issue #314 https://github.com/asweigart/pyautogui/issues/314
# but I'd like to hang on to SetCursorPos because mouse_event() has been superceded.
# _sendMouseEvent(MOUSEEVENTF_MOVE + MOUSEEVENTF_ABSOLUTE, x, y)
| 7,272 |
def event_speakers_call(transaction):
"""
GET /speakers-calls/1/event
:param transaction:
:return:
"""
with stash['app'].app_context():
speakers_call = SpeakersCallFactory()
db.session.add(speakers_call)
db.session.commit()
| 7,273 |
def random_answers_2020_ml():
"""
Generates random answers the machine learning challenge of
hackathons :ref:`l-hackathon-2020`.
"""
df = pandas.DataFrame({"index": numpy.arange(473333)})
df['label'] = numpy.random.randint(low=0, high=2, size=(df.shape[0], ))
df['score'] = numpy.random.random((df.shape[0], ))
return df
| 7,274 |
def _buildParser():
"""Returns a custom OptionParser for parsing command-line arguments.
"""
parser = _ErrorOptionParser(__doc__)
filter_group = optparse.OptionGroup(parser,
'File Options',
'Options used to select which files to process.')
filter_group.add_option(
'-f', '--files', dest='files_pattern',
default='(?!^.*\.pyc|.*\.ico|.*\.gif|.*\.png|.*\.jpg$)',
metavar='FILES_REGEX',
help=('Python regex pattern (*not* a glob!) defining files to process'
' in each directory [default: %default]'))
filter_group.add_option(
'-F', '--follow', dest='follow_symlinks', default=False,
action='store_true',
help=('follow file and subdirectory symlinks (possibly *DANGEROUS*)'
' [default: %default]'))
parser.add_option_group(filter_group)
dir_group = optparse.OptionGroup(parser,
'Directory Options',
'Options used to indicate which directories to traverse.')
dir_group.add_option(
'-s', '--start', dest='start_path', default=os.curdir, metavar='PATH',
help='directory in which to start processing files [default: %default]')
dir_group.add_option(
'-R', '--recursive', dest='recurse_dirs', default=False,
action='store_true',
help='recurse into subdirectories [default: %default]')
dir_group.add_option(
'-d', '--dirs', dest='dirs_pattern', default='^[^.].*$',
metavar='SUBDIRS_REGEX',
help=('Python regex pattern (*not* a glob!) defining subdirectories to'
' recurse into (if --recursive) [default: %default]'))
parser.add_option_group(dir_group)
output_group = optparse.OptionGroup(parser,
'Output Options',
'Options used to control program output.')
output_group.add_option(
'-a', '--abspath', dest='abs_path', default=False, action='store_true',
help=('output absolute paths instead of relative paths'
' [default: %default]'))
output_group.add_option(
'', '--nopaths', dest='hide_paths', default=False, action='store_true',
help=('suppress printing of file path names for successfully matched'
' files to stdout [default: %default]'))
output_group.add_option(
'', '--notext', dest='hide_text', default=False, action='store_true',
help=('suppress find/replace text output to stdout (but still print'
' paths if not --nopath, and still perform replacements if'
' specified) [default: %default]'))
output_group.add_option(
'-q', '--quiet', dest='quiet_output', default=False, action='store_true',
help=('suppress *all* printed output to stdout (but still perform'
' replacements if specified) [default: %default]'))
parser.add_option_group(output_group)
replace_group = optparse.OptionGroup(parser,
'Replace Options',
'Options applied when matches in files are replaced with substitutions.'
' (Only possible if REPLACE_FORMAT is supplied.)')
replace_group.add_option(
'-o', '--overwrite', dest='overwrite_files', default=False,
action='store_true',
help=('overwrite original files with formatted text substituted for'
' matches [default: %default]'))
replace_group.add_option(
'-b', '--backup', dest='backup_ext', default='', metavar='EXTENSION',
help=('if supplied, and file would be overwritten, backup original'
' file with the supplied extension [default is no backups of'
' overwritten files are kept]'))
replace_group.add_option(
'-n', '--new', dest='new_ext', default='', metavar='EXTENSION',
help=('if supplied, and file has matches and and is altered by'
' substitutions, create a new file with the supplied extension'
' [default is no new file is created]'))
parser.add_option_group(replace_group)
return parser
| 7,275 |
def _sizeof_fmt(num, suffix='B'):
"""Format a number as human readable, based on 1024 multipliers.
Suited to be used to reformat a size expressed in bytes.
By Fred Cirera, after https://stackoverflow.com/a/1094933/1870254
Args:
num (int): The number to be formatted.
suffix (str): the measure unit to append at the end of the formatted
number.
Returns:
str: The formatted number including multiplier and measure unit.
"""
for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
| 7,276 |
def train(
package: str,
config: str,
gpus: int,
gpus_per_node: int = None,
cpus_per_task: int = 2,
partition: str = None,
launcher: str = 'none',
port: int = None,
srun_args: Optional[str] = None,
yes: bool = True,
other_args: tuple = ()
) -> Tuple[bool, Union[str, Exception]]:
"""Train a model with given config.
Args:
package (str): The codebase name.
config (str): The config file path. If not exists, will search in the
config files of the codebase.
gpus (int): Number of gpus used for training.
gpus_per_node (int, optional): Number of gpus per node to use
(only applicable to launcher == "slurm"). Defaults to None.
cpus_per_task (int, optional): Number of cpus per task to use
(only applicable to launcher == "slurm"). Defaults to None.
partition (str, optional): The partition name
(only applicable to launcher == "slurm"). Defaults to None.
launcher (str, optional): The launcher used to launch jobs.
Defaults to 'none'.
port (int | None, optional): The port used for inter-process
communication (only applicable to slurm / pytorch launchers).
Default to None. If set to None, will randomly choose a port
between 20000 and 30000.
srun_args (str, optional): Other srun arguments that might be
used, all arguments should be in a string. Defaults to None.
yes (bool): Don’t ask for confirmation. Default: True.
other_args (tuple, optional): Other arguments, will be passed to the
codebase's training script. Defaults to ().
"""
full_name = module_full_name(package)
if full_name == '':
msg = f"Can't determine a unique package given abbreviation {package}"
raise ValueError(highlighted_error(msg))
package = full_name
# If launcher == "slurm", must have following args
if launcher == 'slurm':
msg = ('If launcher is slurm, '
'gpus-per-node and partition should not be None')
flag = (gpus_per_node is not None) and (partition is not None)
assert flag, msg
if port is None:
port = rd.randint(20000, 30000)
if launcher in ['slurm', 'pytorch']:
click.echo(f'Using port {port} for synchronization. ')
if not is_installed(package):
msg = (f'The codebase {package} is not installed, '
'do you want to install the latest release? ')
if yes or click.confirm(msg):
click.echo(f'Installing {package}')
cmd = ['mim', 'install', package]
ret = subprocess.check_call(cmd)
if ret != 0:
msg = f'{package} is not successfully installed'
raise RuntimeError(highlighted_error(msg))
else:
click.echo(f'{package} is successfully installed')
else:
msg = f'You can not train this model without {package} installed.'
return False, msg
pkg_root = get_installed_path(package)
if not osp.exists(config):
# configs is put in pkg/.mim in PR #68
config_root = osp.join(pkg_root, '.mim', 'configs')
if not osp.exists(config_root):
# If not pkg/.mim/config, try to search the whole pkg root.
config_root = pkg_root
# pkg/.mim/configs is a symbolic link to the real config folder,
# so we need to follow links.
files = recursively_find(
pkg_root, osp.basename(config), followlinks=True)
if len(files) == 0:
msg = (f"The path {config} doesn't exist and we can not find "
f'the config file in codebase {package}.')
raise ValueError(highlighted_error(msg))
elif len(files) > 1:
msg = (
f"The path {config} doesn't exist and we find multiple "
f'config files with same name in codebase {package}: {files}.')
raise ValueError(highlighted_error(msg))
# Use realpath instead of the symbolic path in pkg/.mim
config_path = osp.realpath(files[0])
click.echo(
f"The path {config} doesn't exist but we find the config file "
f'in codebase {package}, will use {config_path} instead.')
config = config_path
# tools will be put in package/.mim in PR #68
train_script = osp.join(pkg_root, '.mim', 'tools', 'train.py')
if not osp.exists(train_script):
train_script = osp.join(pkg_root, 'tools', 'train.py')
common_args = ['--launcher', launcher] + list(other_args)
if launcher == 'none':
if gpus:
cmd = ['python', train_script, config, '--gpus',
str(gpus)] + common_args
else:
cmd = ['python', train_script, config, '--device', 'cpu'
] + common_args
elif launcher == 'pytorch':
cmd = [
'python', '-m', 'torch.distributed.launch',
f'--nproc_per_node={gpus}', f'--master_port={port}', train_script,
config
] + common_args
elif launcher == 'slurm':
parsed_srun_args = srun_args.split() if srun_args else []
has_job_name = any([('--job-name' in x) or ('-J' in x)
for x in parsed_srun_args])
if not has_job_name:
job_name = osp.splitext(osp.basename(config))[0]
parsed_srun_args.append(f'--job-name={job_name}_train')
cmd = [
'srun', '-p', f'{partition}', f'--gres=gpu:{gpus_per_node}',
f'--ntasks={gpus}', f'--ntasks-per-node={gpus_per_node}',
f'--cpus-per-task={cpus_per_task}', '--kill-on-bad-exit=1'
] + parsed_srun_args + ['python', '-u', train_script, config
] + common_args
cmd_text = ' '.join(cmd)
click.echo(f'Training command is {cmd_text}. ')
ret = subprocess.check_call(
cmd, env=dict(os.environ, MASTER_PORT=str(port)))
if ret == 0:
return True, 'Training finished successfully. '
else:
return False, 'Training not finished successfully. '
| 7,277 |
def test_labels_painting(make_napari_viewer):
"""Test painting labels updates image."""
data = np.zeros((100, 100), dtype=np.int32)
viewer = make_napari_viewer(show=True)
viewer.add_labels(data)
layer = viewer.layers[0]
screenshot = viewer.screenshot(canvas_only=True, flash=False)
# Check that no painting has occurred
assert layer.data.max() == 0
assert screenshot[:, :, :2].max() == 0
# Enter paint mode
viewer.cursor.position = (0, 0)
layer.mode = 'paint'
layer.selected_label = 3
# Simulate click
Event = collections.namedtuple(
'Event', field_names=['type', 'is_dragging', 'position']
)
# Simulate click
event = ReadOnlyWrapper(
Event(
type='mouse_press',
is_dragging=False,
position=viewer.cursor.position,
)
)
mouse_press_callbacks(layer, event)
viewer.cursor.position = (100, 100)
# Simulate drag
event = ReadOnlyWrapper(
Event(
type='mouse_move',
is_dragging=True,
position=viewer.cursor.position,
)
)
mouse_move_callbacks(layer, event)
# Simulate release
event = ReadOnlyWrapper(
Event(
type='mouse_release',
is_dragging=False,
position=viewer.cursor.position,
)
)
mouse_release_callbacks(layer, event)
event = ReadOnlyWrapper(
Event(
type='mouse_press',
is_dragging=False,
position=viewer.cursor.position,
)
)
mouse_press_callbacks(layer, event)
screenshot = viewer.screenshot(canvas_only=True, flash=False)
# Check that painting has now occurred
assert layer.data.max() > 0
assert screenshot[:, :, :2].max() > 0
| 7,278 |
def CrawlWithSmbclient(config):
"""Crawls a list of SMB file shares, using smbclient.
Args:
config: Config object holding global configuration from commands flags
Returns:
report: Report object holding the results from the crawling the shares.
"""
shares = config.Shares()
if not shares:
print "No shares found!"
sys.exit(1)
if config.debug > 0:
print "Shares to crawl: \n - %s" % '\\\n - '.join([str(s) for s in shares])
report = Report()
for share in shares:
# builds SMB client command using either smbclient
opts = ["-N"]
if share.domain is not None:
opts.append("-W%s" % share.domain)
if share.username is not None:
if share.password is not None:
opts.append('-U"%s%%%%%s"' % (share.username, share.password))
else:
opts.append('-U"%s"' % share.username)
else:
opts.append("-Uguest")
client = "%s %s //%s/%s -c'%%s'" % (
config.client, " ".join(opts), share.hostname, share.share)
crawl_queue = [share.filename]
crawled = []
report.Add(Document(share))
while crawl_queue:
filename = crawl_queue.pop()
while filename in crawled:
filename = crawl_queue.pop()
crawled.append(filename)
file_url = share.Root() + filename[1:]
if config.debug > 1:
print "Trying %s" % share.Url(filename)
if filename[-1] == "/":
cmd = "ls \"%s*\"" % filename.replace("/", '\\')
else:
cmd = "get \"%s\" /dev/null" % filename.replace("/", '\\')
if config.debug > 3:
print "Running command: %s" % (client % cmd,)
status, output = commands.getstatusoutput(client % cmd)
if filename[-1] == "/":
# Get filenames out of directory listing
for line in output.split("\n"):
if line[:2] == " " and line[2:4] != "..":
parts = line.split()
timestamp = ":".join((parts[-1], str(
SHORT_MONTH_NAMES.index(parts[-4])+1), parts[-3], parts[-2]))
timestamp = datetime.datetime(*map(int, timestamp.split(":")))
size = int(parts[-6])
child = " ".join(parts[:-6])
if child[-1] == "D": child = child[:-2] + "/" # sript D attribute
regex = re.compile("^(A|H|S)(A|H|S)?(A|H|S)?$")
if regex.match(child[-1]): child = child[:-2] # strip attributes
if child[0] == ".":
doc = Document(share, filename, lastmod=timestamp)
doc.list_size = doc.real_size = 4096 # Just to avoid zero-sized
report.Add(doc)
continue
path = os.path.join(filename, child)
if config.maxdepth != -1 and (
path[:-1].count("/") - share.depth) > config.maxdepth:
continue
doc = Document(share, path, lastmod=timestamp)
crawl_queue.append(path)
if doc.IsFile:
doc.list_size = size
report.Add(doc)
if config.debug > 3:
print "Found '%s' last modified %s" % (doc.Url(), doc.lastmod)
elif line[:3] == "NT_":
status = line.split()[0]
if config.debug > 2:
print "%s for %s" % (status, filename)
report.Update(file_url, status=status)
else:
words = line.split()
for error in words:
if error[:3] == "NT_":
report.Update(file_url, status=error)
else:
# Get result of downloading the file
for line in output.split("\n"):
if line[:7] == "getting":
parts = line.split()
size = int(parts[parts.index("size") + 1])
if config.debug > 2:
print "%s has size %s" % (filename, size)
report.Update(file_url, real_size=size)
elif line[:3] == "NT_":
error = line.split()[0]
if config.debug > 2:
print "%s for %s" % (error, filename)
report.Update(file_url, status=error)
else:
words = line.split()
for error in words:
if error[:3] == "NT_":
report.Update(file_url, status=error)
return report
| 7,279 |
def new_image():
"""
Display an image, and ask the user to label it
"""
user_id = current_user.user_id
categories = current_app.config["CATEGORIES"]
label_form = LabelForm()
label_form.cat_radio.choices = [(cat,cat) for cat in categories]
if request.method=="POST":
if not "image_id" in session.keys():
print("No session ID - how did this happen?", file=sys.stderr)
else:
image_id = session["image_id"]
label = label_form.cat_radio.data
notes = label_form.notes.data
save_label(user_id, image_id, label, notes)
# get the next image
image_location, is_url, image_id = get_image(user_id)
if not image_location:
return render_template("no_images.html")
# store the image id in the session
session["image_id"] = image_id
# now reset the form to re-render the page
new_label_form = LabelForm(formdata=None)
new_label_form.cat_radio.choices = [(cat,cat) for cat in categories]
return render_template("new_image.html",
new_image=image_location,
img_id=image_id,
form=new_label_form)
| 7,280 |
def num_cluster_members(matrix, identity_threshold):
"""
Calculate number of sequences in alignment
within given identity_threshold of each other
Parameters
----------
matrix : np.array
N x L matrix containing N sequences of length L.
Matrix must be mapped to range(0, num_symbols) using
map_matrix function
identity_threshold : float
Sequences with at least this pairwise identity will be
grouped in the same cluster.
Returns
-------
np.array
Vector of length N containing number of cluster
members for each sequence (inverse of sequence
weight)
"""
N, L = matrix.shape
L = 1.0 * L
# minimal cluster size is 1 (self)
num_neighbors = np.ones((N))
# compare all pairs of sequences
for i in range(N - 1):
for j in range(i + 1, N):
pair_id = 0
for k in range(L):
if matrix[i, k] == matrix[j, k]:
pair_id += 1
if pair_id / L >= identity_threshold:
num_neighbors[i] += 1
num_neighbors[j] += 1
return num_neighbors
| 7,281 |
def get_score(command: str) -> float:
"""Get pylint score"""
output = check_output(command, shell=True).decode("utf-8")
start = output.find("Your code has been rated at ")
if start == -1:
raise ValueError(f'Could not find quality score in "{output.rstrip()}".')
start += len("Your code has been rated at ")
end = start + output[start:].find("/")
score = float(output[start:end])
return score
| 7,282 |
def tf_abstract_eval(f):
"""Returns a function that evaluates `f` given input shapes and dtypes.
It transforms function `f` to a function that performs the same computation as
`f` but only on shapes and dtypes (a.k.a. shape inference).
Args:
f: the function to be transformed.
Returns:
A function whose input arguments can be either the same as `f`'s or only
their shapes/dtypes represented by `ShapeDtype`, and whose return values are
`ShapeDtype`s with the same nested structure as `f`'s return values.
"""
f_shape = tf_np_extensions.eval_on_shapes(f)
def from_shape_type(x):
if isinstance(x, ShapeDtype):
return tf.TensorSpec(x.shape, x.dtype)
else:
return x
def to_shape_type(x): # pylint: disable=missing-docstring
# TODO(wangpeng): handle partial output shapes using `tf.shape`.
def to_numpy_shape(s):
if s.is_fully_defined():
return tuple(s.as_list())
else:
raise ValueError("The output shapes (%s) of the dry-run'ed function are"
' not fully defined.' % s)
def to_numpy_dtype(t):
return np.dtype(t.as_numpy_dtype)
if isinstance(x, tf.TensorSpec):
return ShapeDtype(to_numpy_shape(x.shape), to_numpy_dtype(x.dtype))
else:
return x
def f_return(*args):
args = tf.nest.map_structure(from_shape_type, args)
res = f_shape(*args)
return tf.nest.map_structure(to_shape_type, res)
return f_return
| 7,283 |
def __process_input(request_data: str) -> np.array:
"""
Converts input request data into numpy array
:param request_data in json format
:return: numpy array
"""
return np.asarray(json.loads(request_data)["input"])
| 7,284 |
def getDist_P2L(PointP,Pointa,Pointb):
"""计算点到直线的距离
PointP:定点坐标
Pointa:直线a点坐标
Pointb:直线b点坐标
"""
#求直线方程
A=0
B=0
C=0
A=Pointa[1]-Pointb[1]
B=Pointb[0]-Pointa[0]
C=Pointa[0]*Pointb[1]-Pointa[1]*Pointb[0]
#代入点到直线距离公式
distance=0
distance=(A*PointP[0]+B*PointP[1]+C)/math.sqrt(A*A+B*B)
return distance
| 7,285 |
def test_mean_covariance_metric(metric, mean, get_covmats):
"""Test mean_covariance for metric"""
n_matrices, n_channels = 3, 3
covmats = get_covmats(n_matrices, n_channels)
C = mean_covariance(covmats, metric=metric)
Ctrue = mean(covmats)
assert np.all(C == Ctrue)
| 7,286 |
def skipgram_batch(centers, contexts, num_tokens, dtype, index_dtype):
"""Create a batch for SG training objective."""
contexts = mx.nd.array(contexts[2], dtype=index_dtype)
indptr = mx.nd.arange(len(centers) + 1)
centers = mx.nd.array(centers, dtype=index_dtype)
centers_csr = mx.nd.sparse.csr_matrix(
(mx.nd.ones(centers.shape), centers, indptr), dtype=dtype,
shape=(len(centers), num_tokens))
return centers_csr, contexts, centers
| 7,287 |
def JD2RA(JD, longitude=21.42830, latitude=-30.72152, epoch='current'):
"""
Convert from Julian date to Equatorial Right Ascension at zenith
during a specified epoch.
Parameters:
-----------
JD : type=float, a float or an array of Julian Dates
longitude : type=float, longitude of observer in degrees east, default=HERA longitude
latitude : type=float, latitude of observer in degrees north, default=HERA latitutde
This only matters when using epoch="J2000"
epoch : type=str, epoch for RA calculation. options=['current', 'J2000'].
The 'current' epoch is the epoch at JD. Note that
LST is defined as the zenith RA in the current epoch. Note that
epoch='J2000' corresponds to the ICRS standard.
Output:
-------
RA : type=float, right ascension [degrees] at zenith JD times
in the specified epoch.
"""
# get JD type
if isinstance(JD, list) or isinstance(JD, np.ndarray):
_array = True
else:
_array = False
JD = [JD]
# setup RA list
RA = []
# iterate over jd
for jd in JD:
# use current epoch calculation
if epoch == 'current':
ra = JD2LST(jd, longitude=longitude) * 180 / np.pi
RA.append(ra)
# use J2000 epoch
elif epoch == 'J2000':
loc = crd.EarthLocation(lat=latitude * unt.deg, lon=longitude * unt.deg)
t = Time(jd, format='jd', scale='utc')
zen = crd.SkyCoord(frame='altaz', alt=90 * unt.deg, az=0 * unt.deg, obstime=t, location=loc)
RA.append(zen.icrs.ra.degree)
else:
raise ValueError("didn't recognize {} epoch".format(epoch))
RA = np.array(RA)
if _array:
return RA
else:
return RA[0]
| 7,288 |
def _average_gradients(tower_grads):
"""Calculate the average gradient for each shared variable across all towers.
Note that this function provides a synchronization point across all towers.
Args:
tower_grads: List of lists of (gradient, variable) tuples. The outer list is
over individual gradients. The inner list is over the gradient calculation
for each tower.
Returns:
List of pairs of (gradient, variable) where the gradient has been averaged
across all towers.
"""
average_grads = []
for grad_and_vars in zip(*tower_grads):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
grads = []
print(len(grad_and_vars))
for g, v in grad_and_vars:
if g is None:
print(v)
for grad_and_vars in zip(*tower_grads):
# Note that each grad_and_vars looks like the following:
# ((grad0_gpu0, var0_gpu0), ... , (grad0_gpuN, var0_gpuN))
grads = []
print(len(grad_and_vars))
for g, v in grad_and_vars:
if g is not None:
print(v)
for g, v in grad_and_vars:
# Add 0 dimension to the gradients to represent the tower.
print(v)
expanded_g = tf.expand_dims(g, 0)
# Append on a 'tower' dimension which we will average over below.
grads.append(expanded_g)
# Average over the 'tower' dimension.
grad = tf.concat(grads, 0)
grad = tf.reduce_mean(grad, 0)
capped_grad = tf.clip_by_value(grad, -200., 200.)
# Keep in mind that the Variables are redundant because they are shared
# across towers. So .. we will just return the first tower's pointer to
# the Variable.
v = grad_and_vars[0][1]
grad_and_var = (capped_grad, v)
average_grads.append(grad_and_var)
return average_grads
| 7,289 |
def player_statistics(players):
"""query & show historic stats for each player before the game starts"""
for player in players:
player.score = points_default
player.score_history = []
player_wins = int(db.get_wins(player.name))
player_total_games = int(db.get_total_games(player.name))
if player_total_games != 0:
player_win_ratio = player_wins / player_total_games
else:
player_win_ratio = 0
print(f"\nGesamt-Statistik von {RED}{player.name}{CLEAR}")
print(f"Siege: {GREEN}{player_wins}{CLEAR} ----- Niederlagen: {GREEN}{player_total_games-player_wins}{CLEAR} ----- Siegquote: {GREEN}{player_win_ratio:.2f}")
print(f"Punkteschnitt: {GREEN}{db.get_average_score(player.name, 10)}") #2nd parameter: gleitender durchschnitt über n spiele
print(f"Höchster Wurf: {GREEN}{db.get_top_hit(player.name, 1000)}") #average score for all games of player --> platzhalter für "all" finden
print(f"Höchster Checkout: {GREEN}{db.get_max_checkout(1000,player.name)}")
| 7,290 |
def _get_memory_banks_listed_in_dir(path):
"""Get all memory banks the kernel lists in a given directory.
Such a directory can be /sys/devices/system/node/ (contains all memory banks)
or /sys/devices/system/cpu/cpu*/ (contains all memory banks on the same NUMA node as that core)."""
# Such directories contain entries named "node<id>" for each memory bank
return [int(entry[4:]) for entry in os.listdir(path) if entry.startswith("node")]
| 7,291 |
def iter_datarows_shuffled(
parquet_files: List[Path],
columns: Union[dict, tuple] = DataRow._fields,
filters: List[Callable] = [],
random_state: Optional[np.random.RandomState] = None,
) -> RowGen:
"""Iterate over parquet data in multiple `parquet_files`, randomly chosing the next row.
Notes:
- Generating a training dataset from multiple domain folders
is better than preshuffling and storing all domains in a single
Parquet folder because it's easier to make each epoch trully random.
Args:
parquet_files: List of parquet files from which to obtain data.
Returns:
NamedTuple containing domain rows.
"""
if random_state is None:
random_state = np.random.RandomState()
# Note: right now we are not considering the effect of `filters`
# weights = np.array(
# [pq.ParquetFile(f).scan_contents(columns=["__index_level_0__"]) for f in parquet_files]
# )
weights_list = []
generator_list = []
for parquet_file in parquet_files:
weight = pq.ParquetFile(parquet_file).metadata.num_rows
generator = iter_datarows(parquet_file, columns, filters, random_state)
weights_list.append(weight)
generator_list.append(generator)
weights = np.array(weights_list)
weights = weights[:] / weights.sum()
generators = np.array(generator_list)
while True:
gen = random_state.choice(generators, p=weights)
yield next(gen)
| 7,292 |
def get_online_users(guest=False): # pragma: no cover
"""Returns all online users within a specified time range
:param guest: If True, it will return the online guests
"""
current = int(time.time()) // 60
minutes = range_method(flaskbb_config['ONLINE_LAST_MINUTES'])
if guest:
return redis_store.sunion(['online-guests/%d' % (current - x)
for x in minutes])
return redis_store.sunion(['online-users/%d' % (current - x)
for x in minutes])
| 7,293 |
def AddConfigFlags(parser):
"""Add flags for different types of configs."""
parser.add_argument(
'--config',
help='Filename of a top-level yaml config that specifies '
'resources to deploy.')
parser.add_argument(
'--template',
help='Filename of a top-level jinja or python config template.')
parser.add_argument(
'--composite-type',
help='Name of a composite type to deploy.')
| 7,294 |
def reverse_bearing(bearing: Union[int, float]):
"""
180 degrees from supplied bearing
:param bearing:
:return:
"""
assert isinstance(bearing, (float, int))
assert 0. <= bearing <= 360.
new_bearing = bearing + 180.
# Ensure strike is between zero and 360 (bearing)
return normalize_bearing(new_bearing)
| 7,295 |
def signUp_page(request):
"""load signUp page"""
return render(request, 'app/signUp_page.html')
| 7,296 |
def db(app, request):
"""
Session-wide test database.
"""
db_path = app.config["SQLALCHEMY_DATABASE_URI"]
db_path = db_path[len("sqlite:///"):]
print(db_path)
if os.path.exists(db_path):
os.unlink(db_path)
def teardown():
_db.drop_all()
os.unlink(db_path)
_db.app = app
apply_migrations()
request.addfinalizer(teardown)
return _db
| 7,297 |
def main():
""" Set virtual desktop
"""
# https://github.com/ValveSoftware/Proton/issues/872
util.protontricks('vd=1280x720')
| 7,298 |
def plot_each_model_prism(mod, title, modelnumber, grid_specification, fig):
""" Plots each individual model when called from plot_multiple_models_prism
"""
marker_dict = {'[]':'s', 'v': '^', 'O': 'o', 'I': '|', '+': 'X',
'L': '$L$', '^': '$V$', '*': '*', 'S': '$S$'}
axis = fig.add_subplot(grid_specification[modelnumber],
projection=Axes3D.name)
plt.title(title)
x_val, y_val, z_val = dimensions(mod)
# Set xticks, yticks and zticks based on no dims of x, y and z.
axis.set_xticks(list(range(x_val)))
axis.set_yticks(list(range(y_val)))
axis.set_zticks(list(range(z_val)))
axis.invert_zaxis()
for key, val in mod.items():
if val is not None:
if len(val) > 1 and val != '[]':
axis.scatter(key[0], key[1], key[2])
axis.annotate(val, (key[0], key[1], key[2]))
else:
axis.scatter(key[0], key[1], key[2],
marker=marker_dict[val], s=100)
| 7,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.