content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def __persistent_cache_manager(mode='r'):
"""
pds - persistent data structure
modes:
r - recover, s - save
"""
if not __PERSISTENT_CACHE:
return
global __BUZZER_CACHE
if mode == 's':
# SAVE CACHE
with open('buzzer.pds', 'w') as f:
f.write(','.join(... | 5,349,400 |
def default_summary_collector():
"""
Get the :class:`SummaryCollector` object at the top of context stack.
Returns:
SummaryCollector: The summary collector.
"""
return _summary_collect_stack.top() | 5,349,401 |
def norm(*args, **kwargs):
""" See https://www.tensorflow.org/versions/master/api_docs/python/tf/norm .
"""
return tensorflow.norm(*args, **kwargs) | 5,349,402 |
def read_fasta(input_fasta):
"""Return a list of seqeunces from a given FASTA file."""
try:
seq = []
records = []
is_fasta = False
with open_fasta(input_fasta) as fasta_fh:
for line in fasta_fh:
line = line.rstrip()
if line.startswith('... | 5,349,403 |
def get_steering_policies(compartment_id: Optional[str] = None,
display_name: Optional[str] = None,
display_name_contains: Optional[str] = None,
filters: Optional[Sequence[pulumi.InputType['GetSteeringPoliciesFilterArgs']]] = None,
... | 5,349,404 |
def res_input_matrix_random_sparse(idim = 1, odim = 1, density=0.1, dist = 'normal'):
"""reservoirs.res_input_matrix_random_sparse
Create a sparse reservoir input matrix. Wrapper for
create_matrix_sparse_random.
Arguments:
idim: input dimension
odim: hidden dimension
density: density
d... | 5,349,405 |
def _MakeApiMap(root_package, api_config):
"""Converts a map of api_config into ApiDef.
Args:
root_package: str, root path of where generate api will reside.
api_config: {api_name->api_version->{discovery,default,version,...}},
description of each api.
Returns:
{api_name->api_version-... | 5,349,406 |
def make_election_frame(votes, shares=None, party_names=None, margin_idx=None):
"""
Constructs an election frame from at most two arrays.
If provided,
"""
if votes.ndim == 1:
votes = votes.reshape(-1,1)
if votes.shape[-1] == 1 and shares is not None:
votes, shares = votes, shares... | 5,349,407 |
def test_cli_min(runner):
"""Test cli."""
result = runner.invoke(cli, ['-l', 'min', 'data/setup.py'])
assert result.exit_code == 0
if sys.version_info[:2] == (2, 7):
assert result.output == \
'CairoSVG==1.0.20\n' \
'click==5.0.0\n' \
'functools32==3.2.3-2\n' \... | 5,349,408 |
def payload_from_api_post_event(event):
"""Maps an API event to the expected payload"""
# event = {
# 'timeserie1': [(1, 100), (2, 100)],
# 'timeserie2': [(3, 100), (4, 100)],
# }
body = json.loads(event['body'])
return body | 5,349,409 |
def delete(*filenames):
"""Permanently delete files.
Delete on non-finalized/non-existent files is a no-op.
Args:
filenames: finalized file names as strings. filename should has format
"/gs/bucket/filename" or "/blobstore/blobkey".
Raises:
InvalidFileNameError: Raised when any filename is not o... | 5,349,410 |
def format_link_header(link_header_data):
"""Return a string ready to be used in a Link: header."""
links = ['<{0}>; rel="{1}"'.format(data['link'], data['rel'])
for data in link_header_data]
return ', '.join(links) | 5,349,411 |
def parse_collection_members(object_: dict) -> dict:
"""Parse the members of a collection to make it easier
to insert in database.
:param object_: The body of the request having object members
:type object_: dict
:return: Object with parsed members
:rtype: dict
"""
members = list()
... | 5,349,412 |
def PoissonWasserstein_S2(tau, rho, function1, function2, numerical=False):
""" Computes the Poisson bracket of two linear functionals on the space P^{OO}(S^2), of measures with a smooth
positive density function on the 2-sphere S^2, at a measure in P^{OO}(S^2).
The Poisson bracket on P^{... | 5,349,413 |
def poly_in_gdf():
""" Fixture for a bounding box polygon. """
return make_poly_in_gdf() | 5,349,414 |
def apply_inclusion_exclusion_criteria(
df: pd.DataFrame, col: str, criteria: List[List[str], List[str]]
) -> pd.Series:
"""Filter out files based on `criteria`, a nested list of row values to include or exclude, respectively
:param df: dataframe to filter
:type df: pd.DataFrame
:param col: column ... | 5,349,415 |
def prune_string(string):
"""Prune a string.
- Replace multiple consecutive spaces with a single space.
- Remove spaces after open brackets.
- Remove spaces before close brackets.
"""
return re.sub(
r" +(?=[\)\]\}])",
"",
re.sub(r"(?<=[\(\[\{]) +", "", re.sub(r" +", " "... | 5,349,416 |
def detect_face(MaybeImage):
"""
Take an image and return positional information for the largest face in it.
Args:
MaybeImage: An image grabbed from the local camera.
Returns:
Maybe tuple((bool, [int]) or (bool, str)): True and list of positional
coordinates of the largest face found. False ... | 5,349,417 |
def test_wrong_relations():
"""docstring for test_wrong_relations"""
# GIVEN a individual with correct family info
sample_info = {
"sample_id": "1",
"sex": "male",
"phenotype": "affected",
"mother": "3",
"father": "2",
}
mother_info = {
"sample_id": "3... | 5,349,418 |
def compute_TVL1(prev, curr, bound=15):
"""Compute the TV-L1 optical flow."""
TVL1 = cv2.DualTVL1OpticalFlow_create()
flow = TVL1.calc(prev, curr, None)
assert flow.dtype == np.float32
flow = (flow + bound) * (255.0 / (2 * bound))
flow = np.round(flow).astype(int)
flow[flow >= 255] = 255
... | 5,349,419 |
def draw_3d(xyz=None, species=None, project_directory=None, save_only=False):
"""
Draws the molecule in a "3D-balls" style.
Saves an image if a species and ``project_directory`` are provided.
Args:
xyz (str, dict, optional): The coordinates to display.
species (ARCSpecies, optional): xy... | 5,349,420 |
def _un_partial_ize(func):
"""
Alter functions working on 1st arg being a callable, to descend it if it's a partial.
"""
@wraps(func)
def wrapper(fn, *args, **kw):
if isinstance(fn, (partial, partialmethod)):
fn = fn.func
return func(fn, *args, **kw)
return wrapper | 5,349,421 |
def search_full_text(text, ipstreet_api_key):
"""sends input text to /full_text semantic search endpoint. returns json results"""
endpoint = 'https://api.ipstreet.com/v2/full_text'
headers = {'x-api-key': ipstreet_api_key}
payload = json.dumps({'raw_text': str(text),
'q': {
... | 5,349,422 |
def main(filename, plotDir='Plots/'):
"""
"""
# Which pixels and sidebands?
pixelOffsets = Pointing.GetPixelOffsets('COMAP_FEEDS.dat')
# READ IN THE DATA
d = h5py.File(filename)
tod = d['spectrometer/tod']
mjd = d['spectrometer/MJD'][:]
if len(d['pointing/az'].shape) > 1:
... | 5,349,423 |
def load_args_from_config(args, cfg):
"""Override the values of arguments from a config file
Args:
args: ArgumentParser object
cfg: a dictionary with arguments to be overridden
"""
for key in cfg:
if key in args:
type_of_key = type(args.__getattribute__(key))
... | 5,349,424 |
def add_rows(df, row_list=[], column_list=[], append=False):
"""
add a list of rows by index number for a wide form dataframe
"""
df = df.filter(items=row_list, axis=0)
df = pd.DataFrame(df.sum()).T
return df | 5,349,425 |
def coerce_data_type_value(context, presentation, data_type, entry_schema, constraints, value, # pylint: disable=unused-argument
aspect):
"""
Handles the ``_coerce_data()`` hook for complex data types.
There are two kinds of handling:
1. If we have a primitive type as our gr... | 5,349,426 |
def Inst2Vec(
bytecode: str, vocab: vocabulary.VocabularyZipFile, embedding
) -> np.ndarray:
"""Transform an LLVM bytecode to an array of embeddings.
Args:
bytecode: The input bytecode.
vocab: The vocabulary.
embedding: The embedding.
Returns:
An array of embeddings.
"""
embed = lambda x: ... | 5,349,427 |
def extract_from_code(code, gettext_functions):
"""Extract strings from Python bytecode.
>>> from genshi.template.eval import Expression
>>> expr = Expression('_("Hello")')
>>> list(extract_from_code(expr, GETTEXT_FUNCTIONS))
[('_', u'Hello')]
>>> expr = Expression('ngettext("You have ... | 5,349,428 |
def sample_raw_locations(stacking_program, address_suffix=""):
"""
Samples the (raw) horizontal location of blocks in the stacking program.
p(raw_locations | stacking_program)
Args
stacking_program [num_blocks]
Returns [num_blocks]
"""
device = stacking_program[0].device
dist =... | 5,349,429 |
def get_raw_data(params, data_type=1):
"""Method to filter which report user wants."""
# class="table table-bordered"
data = None
raw_data = []
td_zeros = '<td>0</td>' * 12
tblanks = ['M', 'F'] * 6
blanks = ['0'] * 13
csvh = ['0 - 5 yrs', '', '6 - 10 yrs', '', '11 - 15 yrs', '',
... | 5,349,430 |
def get_existing_cert(server, req_id, username, password, encoding='b64'):
"""
Gets a certificate that has already been created.
Args:
server: The FQDN to a server running the Certification Authority
Web Enrollment role (must be listening on https)
req_id: The request... | 5,349,431 |
def test_show_config():
"""
Arrange/Act: Run the `show_config` command.
Assert: The output includes the correct headding `COLUMN_NAMES`".
"""
runner: CliRunner = CliRunner()
result: Result = runner.invoke(cli.cli, ["show-config"])
assert result.exit_code == 0
assert "COLUMN_NAMES" in res... | 5,349,432 |
def processCall(*aPositionalArgs, **dKeywordArgs):
"""
Wrapper around subprocess.call to deal with its absense in older
python versions.
Returns process exit code (see subprocess.poll).
"""
assert dKeywordArgs.get('stdout') == None;
assert dKeywordArgs.get('stderr') == None;
_processFixP... | 5,349,433 |
def test_get_section_keys_invalid_section():
"""
gets all available keys in given section which is unavailable
of specified config store. it should raise an error.
"""
with pytest.raises(ConfigurationStoreSectionNotFoundError):
config_services.get_section_keys('application', 'missing_sectio... | 5,349,434 |
def as_sparse_variable(x, name=None):
"""
Wrapper around SparseVariable constructor.
@param x: A sparse matrix. as_sparse_variable reads dtype and format
properties out of this sparse matrix.
@return: SparseVariable version of sp.
@todo Verify that sp is sufficiently sparse, and raise a warning... | 5,349,435 |
def _get_go2parents(go2parents, goid, goterm):
"""Add the parent GO IDs for one GO term and their parents."""
if goid in go2parents:
return go2parents[goid]
parent_goids = set()
for parent_goterm in goterm.parents:
parent_goid = parent_goterm.id
parent_goids.add(parent_goid)
... | 5,349,436 |
def _axhspan() -> None:
"""水平方向に背景色を変更する
"""
x, y = _create_data()
pos_begin = (max(y) - min(y)) * 0.3 + min(y)
pos_end = (max(y) - min(y)) * 0.7 + min(y)
_ = plt.figure()
plt.plot(x, y)
plt.axhspan(pos_begin, pos_end, color="green", alpha=0.3)
plt.savefig("data/axhspan.png")
_... | 5,349,437 |
def test_span_confidence_score_extension_added(he_vocab):
"""
Check that confidence_score extension is available
"""
new_head = NERHead(nlp=None, name="test")
mock_doc = Doc(he_vocab, words=["שלום", "כיתה", "אלף"])
assert Span.has_extension("confidence_score") | 5,349,438 |
def compute_conditional_statistics(x_test, x, kernel, ind):
"""
This version uses cho_factor and cho_solve - much more efficient when using JAX
Predicts marginal states at new time points. (new time points should be sorted)
Calculates the conditional density:
p(xₙ|u₋, u₊) = 𝓝(Pₙ @ [u₋, u₊... | 5,349,439 |
def int_to_bytes(value: int) -> bytes:
"""
Encode an integer to an array of bytes.
:param value: any integer
:return: integer value representation as bytes
"""
return value.to_bytes(length=BYTES_LENGTH, byteorder=BYTES_ORDER) | 5,349,440 |
def check_invalid_args_sequential(config):
"""Sanity check for some command-line arguments specific to training on
the copy task.
Args:
config (argparse.Namespace): Parsed command-line arguments.
"""
if config.first_task_input_len <= 0:
raise ValueError('"first_task_input_len" must ... | 5,349,441 |
def generate_1d_trajectory_distribution(
n_demos, n_steps, initial_offset_range=3.0, final_offset_range=0.1,
noise_per_step_range=20.0, random_state=np.random.RandomState(0)):
"""Generates toy data for testing and demonstration.
Parameters
----------
n_demos : int
Number of demo... | 5,349,442 |
def encrypt(binary_plaintext, binary_key):
"""Generate binary ciphertext from binary plaintext with AES."""
padded_plaintext = pad_plaintext(binary_plaintext, 128)
subkeys = key_schedule(binary_key)
final_blocks = []
for block in block_split(padded_plaintext, 128):
block_matrix = binary_to_m... | 5,349,443 |
def emit_event(project_slug, action_slug, payload, sender_name, sender_secret,
event_uuid=None):
"""Emit Event.
:param project_slug: the slug of the project
:param action_slug: the slug of the action
:param payload: the payload that emit with action
:param sender_name: name that iden... | 5,349,444 |
def add_item(cart_id: str, item: CartItem):
"""
Endpoint. Add item to cart.
:param str cart_id: cart id
:param CartItem item: pair of name and price
:return: dict with cart, item and price
:rtype: dict
"""
logger.info(f'Request@/add_item/{cart_id}')
return cart.add_item(cart_id=cart... | 5,349,445 |
def _inst2earth(advo, reverse=False, rotate_vars=None, force=False):
"""
Rotate data in an ADV object to the earth from the instrument
frame (or vice-versa).
Parameters
----------
advo : The adv object containing the data.
reverse : bool (default: False)
If True, this function p... | 5,349,446 |
def maja_get_subdirectories(search_directory):
"""
Search in search directory all the subdirs
TODO: use logging
:param search_directory:
:type search_directory:
"""
return [os.path.join(search_directory, name) for name in os.listdir(search_directory)
if os.path.isdir(os.path.... | 5,349,447 |
def get_artist_songs_genius(artist_id=None):
"""
Wrapper for the /artists/:id/songs Genius API endpoint
Returns songs for a given artist ID or 1 if an error occurred.
"""
if artist_id is None:
logger.debug("get_artist_song_genius was not passed correct params.")
logger.debug... | 5,349,448 |
def _setup_api_changes():
"""
Setups *Colour* API changes.
"""
global API_CHANGES
for renamed in API_CHANGES['Renamed']:
name, access = renamed
API_CHANGES[name.split('.')[-1]] = Renamed(name, access) # noqa
API_CHANGES.pop('Renamed') | 5,349,449 |
def example_broadcast_data(nm3_modem, message):
"""Example: $B - Broadcast Data."""
print('Example: Broadcast Data')
sent_bytes_count = nm3_modem.send_broadcast_message(message)
if sent_bytes_count == -1:
print(' Error')
else:
# Pause for the modem to finish the transmission... | 5,349,450 |
def kepler(k, r, v, tofs, numiter=350, **kwargs):
"""Propagates Keplerian orbit.
Parameters
----------
k : ~astropy.units.Quantity
Standard gravitational parameter of the attractor.
r : ~astropy.units.Quantity
Position vector.
v : ~astropy.units.Quantity
Velocity vector.... | 5,349,451 |
def get_latency_of_one_partition(
partition: Partition, node_to_latency_mapping: Dict[Node, NodeLatency]
) -> PartitionLatency:
"""Given a partiton and its nodes' latency, return a PartitionLatency for this partition"""
def get_top_nodes(partition: Partition) -> List[Node]:
"""Given a partition, re... | 5,349,452 |
def test_multiple_sweeps(multi_sweep_type, ccp4, dials_data, run_in_tmpdir):
"""
Run xia2 with various different multiple-sweep options.
Run xia2 using procrunner and look for errors or timeouts. Run it with a reduced
number of reflections per degree required for profile modelling and turn off the
... | 5,349,453 |
def nearest_dy(lon,lat,t,gs,dy,tr = [0,0],box = [0,0],time_vec = False,space_array = False):
"""
give this a dy object and a gs object,
the nearest point to the supplied lon lat will be returned
tr is a time range option [time points previous, after]
if tr > 0 time_vec=True will return a rs/H/WAVES/... | 5,349,454 |
def get_return_type() -> None:
"""Prompt the user for the return datatype of the function.
:return return_type: {str}
"""
return_type = None # function or method
while return_type is None or return_type == "":
return_type = prompt(
"return type? [bool|dict|float|int|list|str|... | 5,349,455 |
def solve_capcha(capcha_str):
"""Function which calculates the solution to part 1
Arguments
---------
capcha_str : str, a string of numbers
Returns
-------
total : int, the sum of adjacent matches
"""
capcha = [int(cc) for cc in list(capcha_str)]
total = 0
for ii in... | 5,349,456 |
def compose(fs: Union[ModuleList, Sequence[Callable]]) -> F:
"""
Compose functions as a pipeline function.
Args:
fs (``Sequence[Callable]`` | :class:`~torch.nn.ModuleList`): The functions input for composition.
Returns:
:class:`~fn.func.F`: The composed output function.
Examples::... | 5,349,457 |
def nanargmin(a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring
NaNs. For all-NaN slices ``ValueError`` is raised. Warning: the results
cannot be trusted if a slice contains only NaNs and Infs.
Parameters
----------
a : array_like
Input data.... | 5,349,458 |
def check_right_flank(seq_right, list_rep, verbose=False):
"""
Check if start of right flank sequence contains last repetitive sequence.
:param seq_right: str - right flank sequence
:param list_rep: list(Repetition) - list of Repetitions(seq, num)
:param verbose: bool - be verbose
:return: seq_r... | 5,349,459 |
def is_path_creatable(pathname):
"""
if any previous level of parent folder exists, returns true
"""
if not is_path_valid(pathname):
return False
pathname = os.path.normpath(pathname)
pathname = os.path.dirname(os.path.abspath(pathname))
# recursively to find the previous level of p... | 5,349,460 |
def forward_application_conj_reject():
"""forward application conjunction constraint -- parse should fail
>>> test(r"Fred|NNP|(NP\NP)/(NP\NP) and|CC|conj cars|NNS|NP")
>>>
""" | 5,349,461 |
def readout_gg(_X, X, O):
"""
Graph Gathering implementation. (The none shown in the equation)
_X: final node embeddings.
X: initial node features.
O: desired output dimension.
"""
val1 = dense(tf.concat([_X, X], axis=2), O, use_bias=True)
val1 = tf.nn.sigmoid(val1)
val2 = dense(_X, ... | 5,349,462 |
def plot_taylor_axes(axes, cax, option):
"""
Plot axes for Taylor diagram.
Plots the x & y axes for a Taylor diagram using the information
provided in the AXES dictionary returned by the
GET_TAYLOR_DIAGRAM_AXES function.
INPUTS:
axes : data structure containing axes information for targe... | 5,349,463 |
def list_timezones():
"""Return a list of all time zones known to the system."""
l=[]
for i in xrange(parentsize):
l.append(_winreg.EnumKey(tzparent, i))
return l | 5,349,464 |
def keyword_decorator(deco):
"""Wrap a decorator to optionally takes keyword arguments."""
@functools.wraps(deco)
def new_deco(fn=None, **kwargs):
if fn is None:
@functools.wraps(deco)
def newer_deco(fn):
return deco(fn, **kwargs)
return newer_deco... | 5,349,465 |
def get_permutations(expr, debug=False):
"""
Returns the permutations of a MatAdd expression for lengths 2 to len(expr).
For example, for A + B + C + D, we return:
[A+B, A+C, A+D, B+C, B+D, C+D, A+B+C, A+B+D, A+C+D, B+C+D, A+B+C+D]
"""
from symgp.superexpress... | 5,349,466 |
def test_wrong_add_param(conn, ipaddr):
""" Test passing wrong parameter for add method. """
with pytest.raises(ClosedConnection):
cli = LDAPClient("ldap://%s" % ipaddr)
LDAPConnection(cli).add(bonsai.LDAPEntry("cn=dummy"))
with pytest.raises(TypeError):
conn.add("wrong") | 5,349,467 |
def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True):
"""Return spherical linear interpolation between two quaternions.
>>> q0 = random_quaternion()
>>> q1 = random_quaternion()
>>> q = quaternion_slerp(q0, q1, 0.0)
>>> numpy.allclose(q, q0)
True
>>> q = quaternion_slerp(... | 5,349,468 |
def doctest2md(lines):
"""
Convert the given doctest to a syntax highlighted markdown segment.
"""
is_only_code = True
lines = unindent(lines)
for line in lines:
if not line.startswith('>>> ') and not line.startswith('... ') and line not in ['>>>', '...']:
is_only_code = Fals... | 5,349,469 |
def generate(epsilon=0.0, model=None, phase="dev", args=None):
"""Run one training session with a particular set of hyperparameters."""
args, device = parse_args()
criterion = nn.CrossEntropyLoss()
dataloaders, idx_to_class = get_cifar_loader()
# dataloaders, idx_to_class = get_loader(args)
... | 5,349,470 |
def get_return_value(total, cash_given):
"""show how much money you owe to customer after they give you a bill."""
return Decimal(Decimal(total) - Decimal(cash_given)).quantize(Decimal('.01')) | 5,349,471 |
def initlog(logfile=None, level=None, log_stdout=True):
"""
Initialize the log, default log level is NOTSET, it will write the log
message into logfile, and also print onto the screen.
If set log_stdout to False, will not print the log message onto the screen.
"""
log_levels = {'debug': logging.... | 5,349,472 |
def show_predictions(scores, target='y', threshold=0.5, path_out=False, verbose=True, figsize=(7, 200)):
"""This function will plot which have been correctly classified. The input is
single dict containing labels as keys and information on each model as values
in the order [auc_score, ids_test, y_true, y... | 5,349,473 |
def listen_remove(card, interval, card_id):
""" Listens for a card to be placed on the reader """
# Screen.wrapper(datascreen)
while 1:
screensaverstate = 1
if not card.select():
# data = json.dumps({"card_info":
# [{"card_id": card_id}, {"timedate": get_time()}, {"action": "Removed"}]})
# print(data)
... | 5,349,474 |
def det(a, **kwargs):
"""
Compute the determinant of arrays, with broadcasting.
Parameters
----------
a : (NDIMS, M, M) array
Input array. Its inner dimensions must be those of a square 2-D array.
Returns
-------
det : (NDIMS) array
Determinants of `a`
See Also
... | 5,349,475 |
def SegStart(ea):
"""
Get start address of a segment
@param ea: any address in the segment
@return: start of segment
BADADDR - the specified address doesn't belong to any segment
"""
seg = idaapi.getseg(ea)
if not seg:
return BADADDR
else:
re... | 5,349,476 |
def plot_lollipops(index, points, line, ax, ecolor='g', capsize=0, fmt='none'):
"""Make a floaters-and-sinkers plot.
`points` : The data points as a dataframe.
"""
delta = points - line
ax.errorbar(index, points, [delta, zeros(len(index))],
ecolor='g', capsize=0, fmt=fmt, linewidth=... | 5,349,477 |
def test_get_pipeline_yaml_simple():
"""Pipeline yaml loads with simple yaml."""
file = io.StringIO('1: 2\n2: 3')
pipeline = pypyr_yaml.get_pipeline_yaml(file)
assert pipeline == {1: 2, 2: 3} | 5,349,478 |
def update_school_term(request):
"""
修改周期的开始时间和结束时间
:param request:
:return:
"""
operation_object = None
try:
if request.method == 'POST':
object_form = SchoolTermUpdateForm(request.POST)
if object_form.is_valid():
update_id = object_form.clean... | 5,349,479 |
def set_simple_fault_geometry_3D(w, src):
"""
Builds a 3D polygon from a node instance
"""
assert "simpleFaultSource" in src.tag
geometry_node = src.nodes[get_taglist(src).index("simpleFaultGeometry")]
fault_attrs = parse_simple_fault_geometry(geometry_node)
build_polygon_from_fault_attrs(w,... | 5,349,480 |
def main():
"""Run when called from the command line"""
parser = ArgumentParser(
prog="brp",
description="rename batches of files at one time",
)
parser.add_argument(
"-V",
"--version",
action="version",
version=f"%(prog)s {__version__}",
)
parser.... | 5,349,481 |
def test_vectorized():
"""See that heatindex and windchill can do lists"""
temp = datatypes.temperature([0, 10], "F")
sknt = datatypes.speed([30, 40], "MPH")
val = meteorology.windchill(temp, sknt).value("F")
assert abs(val[0] - -24.50) < 0.01 | 5,349,482 |
def chown(
path: Pathable, owner: str, flags: t.Optional[str] = None, sudo: bool = False
) -> ChangeList:
"""Change a path's owner."""
path = _to_path(path)
needs_sudo_w = need_sudo_to_write(path)
needs_sudo_r = need_sudo_to_read(path)
if needs_sudo_r and not sudo:
raise NeedsSudoExcept... | 5,349,483 |
def metric_dist(endclasses, metrics='all', cols=2, comp_groups={}, bins=10, metric_bins={}, legend_loc=-1,
xlabels={}, ylabel='count', title='', indiv_kwargs={}, figsize='default',
v_padding=0.4, h_padding=0.05, title_padding=0.1, **kwargs):
"""
Plots the histogram of given met... | 5,349,484 |
def get_colors(df, colormap=None, vmin=None, vmax=None, axis=1):
"""
Function to automatically gets a colormap for all the values passed in,
Have the option to normalise the colormap.
:params:
values list(): list of int() or str() that have all the values that need a color to be map
to. ... | 5,349,485 |
def proxy_channels(subreddits):
"""
Helper function to proxy submissions and posts.
Args:
subreddits (list of praw.models.Subreddit):
A list of subreddits
Returns:
list of ChannelProxy: list of proxied channels
"""
channels = {
channel.name: channel
... | 5,349,486 |
def anno2map(anno):
"""
anno: {
'file' ==> file index
'instances': [
{ 'class_name':
'class_idx':
'silhouette':
'part': [(name, mask), ...]
},
...
]
}
"""
height, width = ... | 5,349,487 |
def string_to_bool(val: str):
"""Convert a homie string bool to a python bool"""
return val == STATE_ON | 5,349,488 |
def profile(request):
"""
Update a User profile using built in Django Users Model if the user is logged in
otherwise redirect them to registration version
"""
if request.user.is_authenticated():
obj = get_object_or_404(TolaUser, user=request.user)
form = RegistrationForm(request.POST... | 5,349,489 |
def run_kmeans(chunksets, cluster_options={}):
"""
Produces files {{prefix}}.clusters, and {{prefix}}.cluster.stats
:chunksets : list of named tuple with attributes 'directory' and 'prefix'
:returns name of the centroid for each cluster
"""
kmeans_options_dict={ "--nclusters" : 10, ... | 5,349,490 |
def conj(Q):
"""Returns the conjugate of a dual quaternion.
"""
res = cs.SX.zeros(8)
res[0] = -Q[0]
res[1] = -Q[1]
res[2] = -Q[2]
res[3] = Q[3]
res[4] = -Q[4]
res[5] = -Q[5]
res[6] = -Q[6]
res[7] = Q[7]
return res | 5,349,491 |
def benchmark_summary(benchmark_snapshot_df):
"""Creates summary table for a benchmark snapshot with columns:
|fuzzer|time||count|mean|std|min|25%|median|75%|max|
"""
groups = benchmark_snapshot_df.groupby(['fuzzer', 'time'])
summary = groups['edges_covered'].describe()
summary.rename(columns={'... | 5,349,492 |
def is_pio_job_running(*target_jobs: str) -> bool:
"""
pass in jobs to check if they are running
ex:
> result = is_pio_job_running("od_reading")
> result = is_pio_job_running("od_reading", "stirring")
"""
with local_intermittent_storage("pio_jobs_running") as cache:
for job in targ... | 5,349,493 |
def benchmark(skip, params=(3,2,0)):
"""Time computation of the image at various different resolutions"""
for res in range(100,1010,skip):
minComputeDuration = 100000000
minCopyDuration = 100000000
for itr in range(5):
(output, (computeDur, copyDur)) = renderOrbitals(params,... | 5,349,494 |
def encode(text, encoding='utf-8'):
"""
Returns a unicode representation of the string
"""
if isinstance(text, basestring):
if not isinstance(text, unicode):
text = unicode(text, encoding, 'ignore')
return text | 5,349,495 |
def calculate_sparsity(df: pd.DataFrame) -> tuple:
"""Calculate the data sparsity based on ratings and reviews.
Args:
df ([pd.DataFrame]): DataFrame with counts of `overall` and `reviewText`
measured against total `reviewerID` * `asin`.
Returns:
[tuple]: Tuple of data sparsity ... | 5,349,496 |
def send_multi_domain_data_request(req_session):
""" Group Market Data request by Domain type """
# Note: that I dont need to group by domain, I could just
# iterate through the file and request each one individually
# but I felt this was neater!
grouped = defaultdict(list)
# Create lists groupe... | 5,349,497 |
def char_fun_est(
train_data,
paras=[3, 20], n_trees = 200, uv = 0, J = 1, include_reward = 0, fixed_state_comp = None):
"""
For each cross-fitting-task, use QRF to do prediction
paras == "CV_once": use CV_once to fit
get_CV_paras == True: just to get paras by using CV
Returns
... | 5,349,498 |
def create_tables_for_import(volume_id, namespace):
"""Create the import or permanent obs_ tables and all the mult tables they
reference. This does NOT create the target-specific obs_surface_geometry
tables because we don't yet know what target names we have."""
volume_id_prefix = volume_id[:volu... | 5,349,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.