content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_user_documents(user, documents=None):
"""
Return collections and documents for the user
"""
collections = get_user_collections(user)
if not documents:
documents = get_document_model().objects.all()
if not user.is_superuser:
documents = documents.filter(collection__in=coll... | 5,317,300 |
def VideoWriterCreate(
input_path: Optional[str] = None,
out_path: Optional[str] = None,
codec: str = "avc1",
fps: Optional[float] = None,
size: Tuple[int, int] = (None, None),
verbose: bool = False,
**kwargs,
) -> Tuple[bool, cv2.VideoWriter, str]:
"""Create a ``cv2.VideoWriter`` which ... | 5,317,301 |
async def hashtags(
db: DataBase = Depends(db_conn),
time_query: Dict = Depends(time_query),
party: str = Query(None, description="Abbreviated name of party", min_length=3),
):
"""Number of times a hashtag is used by supporters of a specific party.
A supporter of a party is someone who has retweete... | 5,317,302 |
def calculate_inverse_propensity_weighted_confidence_from_df_cache(
df_cached_predictions: pd.DataFrame,
rule_head: PyloAtom,
pylo_context: PyloContext,
propensity_score_controller,
verbose: bool = False,
o_propensity_score_per_prediction: Optional[pd.Series] = None
) -> ... | 5,317,303 |
def play():
""" Sample Game play in pygame window """
game = GAME(
env = ENV(
world = WORLD.get_world(
R=8, C=8,
SP=(0,0), EP=(5,5),
RNDSP=True, RNDEP=True,
EMPTY=-1... | 5,317,304 |
def _get_choices(ballot_type):
"""
Returns Q object that matches a ballot of the specified type that's
currently active, i.e. now() is between the vote_start and vote_end dates
"""
return Q(ballot__type=ballot_type) &\
Q(ballot__election__vote_start__lte=datetime.now()) &\
Q(ba... | 5,317,305 |
def route(user_model: Any, request: prediction_pb2.SeldonMessage) -> prediction_pb2.SeldonMessage:
"""
Parameters
----------
user_model
A Seldon user model
request
A SelodonMessage proto
Returns
-------
"""
if hasattr(user_model, "route_rest"):
logger.warning(... | 5,317,306 |
async def on_shutdown_notify(dp: Dispatcher) -> None:
"""
Newsletter to admins when the bot is stopped
"""
try:
await dp.bot.send_message(bot_config.bot_administrators.creator, 'Бот остановлен!')
except Exception as err:
logger_guru.warning(f'{repr(err)} : Сan not send a message to t... | 5,317,307 |
def find_percentile(array, percentile):
"""Find the value corresponding to the ``percentile``
percentile of ``array``.
Parameters
----------
array : numpy.ndarray
Array of values to be searched
percentile : float
Percentile to search for. For example, to find the 50th percentil... | 5,317,308 |
def p_property_list_path_1(p):
"""
property_list_path : empty
"""
p[0] = [] | 5,317,309 |
def sampleWST_boundedFromOneHalf(m,h,decimal_precision=10):
"""sampleWST_boundedFromOneHalf: Returns a Sample of a Reciprocal Relation Q with `m` alternatives, which is WST and whose entries Q[i,j] fulfill |Q[i,j]-0.5|>h.
m: Number of Alternatives
h: `float` in the interva... | 5,317,310 |
def all_contents( thing, check_subscenes=True ):
"""Iterate over this thing and all of its descendants."""
yield thing
if hasattr( thing, "contents" ):
for t in thing.contents:
if check_subscenes or not isinstance( t, maps.Scene ):
for tt in all_contents( t, check_subscen... | 5,317,311 |
def which(program):
"""Returns path of the executable, if it exists"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
if is_exe(program):
return program
else:
for path in os.environ["... | 5,317,312 |
async def test_no_user_settings():
"""the credential should default to Public Cloud and "organizations" tenant when it can't read VS Code settings"""
transport = async_validating_transport(
requests=[Request(base_url="https://{}/{}".format(AzureAuthorityHosts.AZURE_PUBLIC_CLOUD, "organizations"))],
... | 5,317,313 |
def EGM(par,sol,t,m,c,inv_v):
""" EGM with fully unrolled loops """
# loop over end-of-period assets
for i_a in prange(par.Na):
a = par.grid_a[t,i_a]
still_working_next_period = t+1 <= par.TR-1
Nshocks = par.Nshocks if still_working_next_period else 1
# loop over shocks
... | 5,317,314 |
def mstep(X: np.ndarray, responsibilities: np.ndarray) -> GaussianMixture:
"""
M-step: Updates the gaussian mixture by maximizing the log-likelihood
of the weighted dataset
:param X: (n, d) array holding the data
:param responsibilities: (n, K) array holding the responsibilities for all components ... | 5,317,315 |
def gene_mode(reference, reads, compress, tab, keep):
"""For when inputs are in-frame genes"""
check_input(reference, reads)
tab = check_tab(tab)
ids = []
names = []
seqs = []
og_seqs = {}
err = []
for record in SeqIO.parse(reference, 'fasta'):
ids.append(record.id)
n... | 5,317,316 |
def _acceptance_rule(fx: float, fn: float, temp: float) -> bool:
"""Metropolis acceptance rule"""
dfx = fn - fx
return (dfx < 0) or (
(dfx > 0) and (np.random.rand() <= np.exp(-(fn - fx) / temp))
) | 5,317,317 |
def write_PT_of_wells_from_t2output_in_time(input_dictionary):
"""It generates file containing the evolution of every block on every well
Extrae la evolucion de los bloques relacionados de todos los pozos en la direccion "../output/PT/evol"
Parameters
----------
input_dictionary : dictionary
Dictionary conta... | 5,317,318 |
def listGenericServerEndpoints():
"""Return list of names of generic server endpoints"""
return getObjectNameList( 'GenericServerEndpoint' ) | 5,317,319 |
def test_cls_maxqc4():
"""
Test cls-maxqc4 rule for OWL 2 RL.
If::
T(?x, owl:maxQualifiedCardinality, "1"^^xsd:nonNegativeInteger)
T(?x, owl:onProperty, ?p)
T(?x, owl:onClass, owl:Thing)
T(?u, rdf:type, ?x)
T(?u, ?p, ?y1)
T(?u, ?p, ?y2)
then::
... | 5,317,320 |
def test_domain_nameservers_command(mocker):
"""Test `dmcli domain nameservers`."""
mocker.patch(
"dmcli.utils.api.get",
return_value=[{"ResourceRecords": [{"Value": "ns-0000.awsdns-01.co.uk."}]}],
)
runner = CliRunner()
result = runner.invoke(domain, "nameservers", input="example.c... | 5,317,321 |
def exec_editor(*names):
"""Runs your configured editor on a supplied list of files. Uses exec,
there is no return!"""
ed = get_editor()
if ed.find("/") >= 0:
os.execv(ed, (ed,)+names)
else:
os.execvp(ed, (ed,)+names) | 5,317,322 |
def on_command(chat_buffer: str) -> None:
"""
OnTalkType callback.
"""
if chat_buffer.find("/autopot") == 0:
ap_window.open() | 5,317,323 |
def fnCalculate_MaxUnamRangeRate(prf,centre_frequency):
"""
Calculate the maximum unambiguous range rate in the case of unknown direction
Date: 19 June 2017
"""
return AstCnst.c*prf/(4.*centre_frequency); | 5,317,324 |
def convert_moz_time( moz_time_entry ):
""" Convert Mozilla timestamp-alike data entries to an ISO 8601-ish representation """
# [ https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSPR/Reference/PRTime ]
## result = datetime.fromtimestamp( moz_time_entry/1000000 ).strftime('%Y-%m-%d %H:%M:%S')
... | 5,317,325 |
def generate_model_from_yaml(serialized,
tablename,
primary_key,
deserialize_function = None,
cls = BaseModel,
serialization_config = None,
skip_n... | 5,317,326 |
def stft_power(data, sf, window=2, step=.2, band=(1, 30), interp=True,
norm=False):
"""Compute the pointwise power via STFT and interpolation.
Parameters
----------
data : array_like
Single-channel data.
sf : float
Sampling frequency of the data.
window : int
... | 5,317,327 |
def fromstring(s, shape=None):
"""Not supported for ObjectArray"""
raise TypeError("ObjectArray can't be constructed from a string") | 5,317,328 |
def preprocess_scans(project_dir, pc_dir_name):
"""
preprocess scans by loading scan.png in each scan directory,
then use preprocess_scan to create new images which are saved in a new directory pc_dir_name in pcs directory
"""
parent_scan_dirs = os.path.join(project_dir, 'scans')
scan_dirs = [os... | 5,317,329 |
def base_mono_29_30(n):
"""Finds the symmetry preserving HNFs for the base centered monoclinic
lattices with a determinant of n. Assuming for basis 29 A =
[[-0.666125, 1.16613 , 2.04852 ], [ 1. , 1. , 0. ], [ 1.61803 ,
-0.618034, 1. ]], for basis 30 A = [[ 1. , 1. , 0. ], [
1.61803 , -0.61803... | 5,317,330 |
def showInvLines(rh):
"""
Produce help output related to command synopsis
Input:
Request Handle
"""
if rh.subfunction != '':
rh.printLn("N", "Usage:")
rh.printLn("N", " python " + rh.cmdName + " GetHost " +
"diskpoolnames")
rh.printLn("N", " python " + rh.cmdName +... | 5,317,331 |
def test_grid_mapping_arrays(two_asm_core):
"""Check grid mapping array setup between dissimilar assemblies"""
# Two assemblies: Assembly 2 has finer mesh. That means gap mesh
# between assemblies 1 and 2 is defined by assembly 2; the other
# subchannels adjacent to assembly 1 are defined by assembly 1
... | 5,317,332 |
def create_parser():
"""
Create the CLI parser
:returns: a parser with subparsers: init, populate, update & query --------
"""
parser = argparse.ArgumentParser(description=__doc__, epilog=epi)
parser.add_argument('-v', '--verbose', action='store_true', default=False,
hel... | 5,317,333 |
def _write_conne(parameters):
"""Write CONNE block data."""
from ._common import connections
# Reorder connections
if parameters["connections_order"] is not None:
order = parameters["connections_order"]
else:
order = parameters["connections"].keys()
# Format
label_length = ... | 5,317,334 |
def objects_to_coordinate_arrays(posobjs,coords='auto',degrees=True):
"""
converts a sequence of position objects into an array of coordinates.
`coords` determines the order of the output coordinates - it can be a
comma-seperated list of coordinate names or if 'auto', it will be 'lat,long'
f... | 5,317,335 |
def vport_create(ctx, name, type, active, address_spoofing, vlan_id, **ids):
"""Add an vport to a given subnet or l2domain"""
id_type, id = check_id(**ids)
params = {'name': name,
'type': type,
'active': active,
'addressSpoofing': addr... | 5,317,336 |
def validate_username(username):
"""Validate the username.
See :data:`~.username_regex` to know which rules are applied.
:param username: A username.
:raises ValueError: If validation fails.
"""
if not username_regex.match(username):
raise ValueError(USERNAME_RULES) | 5,317,337 |
def primset_var(*prims):
"""Create a variable that matches a Primitive node."""
return var(lambda node: is_constant(node) and node.value in prims) | 5,317,338 |
def flatten_basis_data(basis):
"""
Takes in a dictionary of basis set info and flattens
all primitive data into vectors.
"""
nshells = len(basis)
coeffs = []
exps = []
atoms = []
ams = []
indices = []
dims = []
# Smush primitive data together into vectors
nbf = 0
... | 5,317,339 |
def create_file(textfile):
""" Creates text file containing
directory description
if the description doesn't exist
"""
try:
err_text = '"This directory doesn\'t have description.' +\
'Would you like to create one now?"'
subprocess.check_call([
... | 5,317,340 |
def test_contains():
"""Make sure 'contains' works."""
assert 'id' in resource
assert 'this_should_not_exist' not in resource | 5,317,341 |
def generate_spherical_1D_filter(size):
"""
Generate a discrete circle-shaped 1D filter of odd size
Return a list of length size
Le filtre en forme de demi-cercle a été choisi car il présente une forme de plateau
"""
assert size%2==1
x = np.linspace(-1,1,num = size+2)[1:-1]
... | 5,317,342 |
def send_email_with_rate_control(
user: User,
alert_type: str,
to_email: str,
subject,
plaintext,
html=None,
max_nb_alert=MAX_ALERT_24H,
nb_day=1,
) -> bool:
"""Same as send_email with rate control over alert_type.
Make sure no more than `max_nb_alert` emails are sent over the pe... | 5,317,343 |
def equatorial_to_ecliptic(ra, dec):
""" translate from equatorial ra & dec to ecliptic ones """
sc = SkyCoord(ra, dec, unit='deg', frame='icrs', obstime='J2000') \
.transform_to('barycentrictrueecliptic')
return sc.lat.value, sc.lon.value | 5,317,344 |
def get_decode_dir_name(ckpt_name):
"""Make a descriptive name for the decode dir, including the name of the checkpoint we use to decode. This is called in single_pass mode."""
if "train" in FLAGS.data_path: dataset = "train"
elif "val" in FLAGS.data_path: dataset = "val"
elif "test" in FLAGS.data_path: datase... | 5,317,345 |
def trade_day(dt, cal='US'):
"""
Latest trading day w.r.t given dt
Args:
dt: date of reference
cal: trading calendar
Returns:
pd.Timestamp: last trading day
Examples:
>>> trade_day('2018-12-25', cal='US').strftime('%Y-%m-%d')
'2018-12-24'
"""
from x... | 5,317,346 |
def read_cclist(self):
"""
Read cross-correlation data from file 'cclist.dat'.
Parameters:
-----------
self (saes_core), an instance of the saes_core class.
Returns:
---------
evid1
evid2
sta_cc
cc_val
evdict
"""
evid1,evid2 = None,None
data = np.genfromtxt(... | 5,317,347 |
def witchingHours(symbol="", **kwargs):
"""This is when option contracts and futures contracts expire on the exact same day.
https://iexcloud.io/docs/api/#witching-hours
Args:
symbol (str): symbol to use
"""
return _base(id="PREMIUM_WALLSTREETHORIZON_WITCHING_HOURS", symbol=symbol, **kwargs... | 5,317,348 |
def is_downloadable(major: int, minor: int, patch: int) -> bool:
"""Test whether is a downloadable nuke version.
Args:
major (int): Major version
minor (int): Minor version
patch (int): Patch version
Returns:
bool: Test result
"""
version = f'{major}.{minor}v{patch... | 5,317,349 |
def ExitFactoryMode(modem):
"""Exits factory mode of a modem.
Args:
modem_path: path to the modem.
"""
session.console.info('Exiting factory test mode(FTM)')
modem.SendCommand(DISABLE_FACTORY_TEST_MODE_COMMAND)
session.console.info('Exited factory test mode') | 5,317,350 |
def check_events(ai_settings, screen, stats, play_button, ship, aliens, bullets):
""" Respond to the different captured events in the game """
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.KEYDOWN:
check_keydown_event(... | 5,317,351 |
def test_single_condition_greater_than_datetime(df, right):
"""Test output for a single condition. ">". Datetimes"""
left_on, right_on = ["E", "Dates"]
expected = (
df.assign(t=1)
.merge(right.assign(t=1), on="t")
.query(f"{left_on} > {right_on}")
.reset_index(drop=True)
... | 5,317,352 |
def create_write_buffer(context, host):
"""Shorthand for creating a write-only buffer on the GPU."""
return ocl.Buffer(context, ocl.mem_flags.WRITE_ONLY, host.nbytes) | 5,317,353 |
def packet_read(serial_connection):
"""Read a packet from given serial connection.
"""
header = serial_connection.read(3)
if len(header) != 3:
print('error: failed to read packet header')
return None, None
command_type, payload_size = struct.unpack('>bH', header)
if payload_... | 5,317,354 |
def test_to_graph_should_return_dataset_as_graph() -> None:
"""It returns a dataset graph isomorphic to spec."""
catalog = Catalog()
catalog.identifier = "http://example.com/catalogs/1"
dataset1 = Dataset()
dataset1.identifier = "http://example.com/datasets/1"
dataset1.title = {"nb": "Datasett ... | 5,317,355 |
def is_nonnegative_length(G, l):
""" Checks whether a length function, defined on the arcs, satisfies the non-negative condition.
Args:
G: An instance of Graph class.
l: A dictionary that defines a length function on the edge set.
Returns:
A boolean, True if the length function sat... | 5,317,356 |
def prepare():
""" Configure environment for testing (like ansible playbook) """
tmt.steps.Prepare.enabled = True
return 'prepare' | 5,317,357 |
def layer(app_name, add_layer_str, remove_layer_str, clear):
"""Configure active layer settings.
\b
>> Example 1: Add VK_LAYER_foo:VK_LAYER_bar globally.
$ vk layer --add VK_LAYER_foo:VK_LAYER_bar
\b
>> Example 2: Add VK_LAYER_foo to <app_name>.
$ vk layer --app <app_name> --add VK_LAYER_f... | 5,317,358 |
def get_verified_absolute_path(path):
"""Verify and return absolute path of argument.
Args:
path : Relative/absolute path
Returns:
Absolute path
"""
installed_path = os.path.abspath(path)
if not os.path.exists(installed_path):
raise RuntimeError("No valid path for reque... | 5,317,359 |
def unflatten_tensor(input, feat_size, anchors):
"""
Un-flattens and un-permutes a tensor from size
[B x (W x H) x C] --> [B x C x W x H]
"""
bsize = input.shape[0]
if len(input.shape) >= 3: csize = input.shape[2]
else: csize = 1
input = input.view(bsize, feat_size[0] * anchors.shape[... | 5,317,360 |
def main() -> None:
"""Load data, create and start FashionMnistClient."""
parser = argparse.ArgumentParser(description="Flower")
parser.add_argument(
"--grpc_server_address",
type=str,
default=DEFAULT_GRPC_SERVER_ADDRESS,
help="gRPC server address (default: [::])",
)
... | 5,317,361 |
def pct_change(df_or_series, periods=1, fill_method='pad',
limit=None, freq=None, **kwargs):
"""
Percentage change between the current and a prior element.
Computes the percentage change from the immediately previous row by
default. This is useful in comparing the percentage of change in... | 5,317,362 |
def thing_two(arg1, arg2):
"""Do a second thing that also has errors."""
result=arg1*arg2
if result <> arg1:
print('derp') | 5,317,363 |
def get_percentage_from_total(total_serie, fraction_serie):
"""
Get which percentage is each element of a serie from the same element
(same date) on another serie.
"""
return compute_time_series(
[fraction_serie, total_serie], utils.get_percent) | 5,317,364 |
def get_isotope_data(isotope_string: str) -> dict:
"""Get the isotope's intrinsinc properties from a JSON data file."""
formatted_isotope_string = format_isotope_string(isotope_string)
isotope_dict = dict(ISOTOPE_DATA[formatted_isotope_string])
isotope_dict.update({"isotope": formatted_isotope_string})
... | 5,317,365 |
def resample_bins(xb, yb, min_bin=10, beta=0.5):
"""
Do a bootstrap resample within the len(xb) bins in the list yb.
Only resample if there are at least min_bin elements in a bin,
otherwise reject the entire bin with probability (1-beta).
"""
xb = np.asarray(xb)
bin_size = np.array(map(len,... | 5,317,366 |
def _run_optimizers(
product_batch: Dict[str, Any],
language: str,
country: str,
currency: str,
cached_optimizers: optimizer_cache.OptimizerCache,
) -> (Dict[str, Any], Dict[str, optimization_result.OptimizationResult]):
"""Transforms a JSON payload of product data using optimizers.
Args:
p... | 5,317,367 |
def get_colour_depth():
"""
Returns the maximum number of possible values per color channel,
that can be used with the availible number of
colours and colour pairs in the terminal.
"""
nr_colours = curses.COLORS
return int(math.pow(nr_colours, 1. / 3.)) | 5,317,368 |
def find_best_hand(*args):
"""Takes some cards and produces the best possible hand.
Parameters
----------
args : Multiple 'Card' type.
These cards form the sample of cards to use to attempt to make the
best hand possible.
Returns
-------
TODO
"""
assert len(... | 5,317,369 |
def google_translate(request):
"""Get translation from Google machine translation service."""
try:
text = request.GET["text"]
locale_code = request.GET["locale"]
if not locale_code:
raise ValueError("Locale code is empty")
except (MultiValueDictKeyError, ValueError) as ... | 5,317,370 |
def parseLemma(lines):
"""
:param lines:
:param normalize:
:return:
# ToDo: Fix issue with
Caeres2=Cāeres|miles|Cāerĭt,Cāerĭtēt||ĭtis, (-ētis), f.|2
Caerēs=Cāerēs|diues|Cāerĭt||ĭtis|2
"""
lemmas = {}
lemma_without_variations = re.compile(
r"^(?P<lemma>\w+\d?){1}(?:\=(?... | 5,317,371 |
def get_genre_regexp(ctx: Context, actor: Actor) -> Optional[str]:
"""
Extract the genre from user request if present
Use adapter to insert as a condition or a processing function
"""
last_request = ctx.last_request
for key in GENRE_DICT.keys():
if re.search(GENRE_DICT[key], last_request... | 5,317,372 |
def mapper(request_id, bucket, prefix):
"""Get instructions on how to process an input zarr store by chunk.
For a zarr store at s3://bucket/prefix, return a list of row boundaries
that correspond to chunks in the store. Assumes that the s3 path is
readable by an anonymous client.
"""
s3_path =... | 5,317,373 |
def byteify(data: Optional[Union[str, bytes]], encoding='utf-8', if_none=None) -> bytes:
"""
Convert a piece of data into bytes if it isn't already::
>>> byteify("hello world")
b"hello world"
By default, if ``data`` is ``None``, then a :class:`TypeError` will be raised by :func... | 5,317,374 |
def vote_details(request, id):
"""
Details for a vote.
Parameters:
id -- the id of the `Vote`.
"""
vote = Vote.objects.filter(uid=id)
if not vote:
return {}
data = {
'id': vote.id,
'author_id': vote.author.id,
'author': vote.author.name,
'post_id... | 5,317,375 |
def get_p_vals(location_median_results, author_gender_median_results, date_median_results):
"""
Takes results from **results_by_location(results, 'median')**, **results_by_author_gender**,
**results_by_date**.
ANOVA test for independence of:
- male vs female authors' median distance between female... | 5,317,376 |
def copyfiles(filelist, dest, copy=False):
"""Copy or symlink files in ``filelist`` to ``dest`` directory.
Parameters
----------
filelist : list
List of files to copy.
dest : path/files
full path to destination. If it is a list of length greater
than 1, then it assumes that ... | 5,317,377 |
def ancestors(repo, subset, x):
"""Changesets that are ancestors of changesets in set, including the
given changesets themselves.
If depth is specified, the result only includes changesets up to
the specified generation.
"""
# startdepth is for internal use only until we can decide the UI
a... | 5,317,378 |
def mock_down_payment_time_with_raise_closure(option = 1):
"""
@fn mock_down_payment_time_with_raise_closure
"""
def mock_down_payment_time_with_raise_input(input_prompt):
if "annual salary" in input_prompt.lower():
return down_payment_time_with_raise_test_values(
option).annual_salary
if... | 5,317,379 |
def hist_intersection(histA, histB):
""" Calcuates the intersection of two histograms.
If two normalised histograms are the same then the sum of the intersection
will be one.
Assumes histograms are normalised.
Parameters
----------
histA: 1D numpy array
normalised array where the ... | 5,317,380 |
def failure_format_traceback(fail):
"""
:param fail: must be an IFailedFuture
returns a string
"""
try:
f = six.StringIO()
traceback.print_exception(
fail._type,
fail.value,
fail._traceback,
file=f,
)
return f.getvalue()... | 5,317,381 |
def ConvT3D(parent, filters, kernel_size, strides=[1, 1, 1], padding="same",
use_bias=True, groups=1, dilation_rate=[1, 1, 1], name=""):
"""\
3D Transposed convolution layer (sometimes called deconvolution).
The need for transposed convolutions generally arises from the desire to
use a tran... | 5,317,382 |
def delete_sfns(bosslet_config):
"""Delete step functions."""
# DP TODO: delete activities
for name, _ in STEP_FUNCTIONS(bosslet_config):
sfn.delete(bosslet_config, name) | 5,317,383 |
def bytes_to_int(b: bytes) -> int:
"""
Convert bytes to a big-endian unsigned int.
:param b: The bytes to be converted.
:return: The int.
"""
return int.from_bytes(bytes=b, byteorder='big', signed=False) | 5,317,384 |
def parse_arguments() -> argparse.Namespace:
"""Parse arguments provided by the command-line
:return: list of decoded arguments
"""
parser = argparse.ArgumentParser(description=__doc__)
pa = parser.add_argument
pa('filename', type=str, help='input contents filename')
pa('-p', '--part', type... | 5,317,385 |
def train_step(sess, dataset, sequence_number, model, parameters):
"""
Train.
"""
# Perform one iteration
token_indices_sequence = dataset.token_indices['train'][sequence_number]
for i, token_index in enumerate(token_indices_sequence):
if token_index in dataset.infrequent_token_indices ... | 5,317,386 |
def cos_distance_numpy_vector(v1, v2):
"""get cos angle (similarity) between two vectors"""
d1 = numpy.sum(v1 * v1)
d1 = numpy.sqrt(d1) # magnitude of v1
d2 = numpy.sum(v2 * v2)
d2 = numpy.sqrt(d2) # magnitude of v2
n1 = v1 / d1
n2 = v2 / d2
return numpy.sum(n1 * n2) | 5,317,387 |
def send_smart_contract_thresholds(request, pk):
"""
Create a smartcontract file on disk and transmit it.
"""
try:
print("IN SEND_SAMART_COTNRA")
templ = Template.objects.get(id=pk)
print("IN... | 5,317,388 |
def list_all_submodules(package):
""" List all the modules in this package with their fully qualified names."""
root_modname = package.__name__
# if the module is not a package do nothing, we check this by the
# presence of the __path__ attribute which only packages have
if not hasattr(package, "_... | 5,317,389 |
def int_greater_than(x, inclusive: bool = False):
"""Creates property that must be an int greater than (or equal to)
some value
Parameters:
x: Value that the property must be greater than
inclusive (bool): If set to True, includes x as a possibility.
Returns:
property
"""... | 5,317,390 |
async def get_Sales_with_date_with_login(q: Query, start_date: Optional[str] = "", end_date: Optional[str] = ""):
"""
Get the sales of a particular day
"""
try:
tkit = Toolkit(shop_url=q.shop_url, api_secret=q.api_secret)
results = tkit.getSales(start_date, end_date)
return resu... | 5,317,391 |
def cell_to_se2_batch(cell_idx, mapmin, mapres):
"""
Coversion for Batch input : cell_idx = [batch_size, 2]
OUTPUT: [batch_size, 2]
"""
return (cell_idx[:,0] + 0.5) * mapres[0] + mapmin[0], (cell_idx[:,1] + 0.5) * mapres[1] + mapmin[1] | 5,317,392 |
def merge(elems, field = None, **kwargs):
"""
merge the fields for all elements in a list return it as a single
element.
Parameters
-----------
elems : list. a list of element object
kwargs: dict. other properties of the new element.
Examples
----------
>>> bpm = getElements('... | 5,317,393 |
def add_answerset(m_json, mid=None, **kwargs):
"""Add answerset."""
if mid is None:
mid = str(uuid4())
with session_scope() as session:
aset = Answerset(m_json, id=mid, **kwargs)
session.add(aset)
return mid | 5,317,394 |
def main() -> None:
"""inky_pi goodnight message main function
"""
weather_data: WeatherBase = OpenWeatherMap(LATITUDE, LONGITUDE, EXCLUDE_FLAGS,
WEATHER_API_TOKEN)
# Set the display object configured with specified Inky display model
display = InkyDra... | 5,317,395 |
async def serve(websocket, path):
"""
Serve Simulations via WebSocket
Server expects JSON in format:
{"simulation": 1/2, "I": <integer>, "c": <float>, "select": [<0/1>x14]}
"""
async for message in websocket:
parameters = json.loads(message)
log.info("Simulation Request: {}".for... | 5,317,396 |
def is_reserved(ips):
"""Indicates whether each address is reserved.
*** Addresses must be IPv4. IPv6 not yet supported. ***
"""
res = cudf.Series(rmm.device_array(len(ips), dtype="bool"))
ptr = res.data.mem.device_ctypes_pointer.value
reserved_ipv4_REGEX = r"^(2(4[0-9]|5[0-5]))\.([0-9]|[1-9][0-... | 5,317,397 |
def put_sqlite(config, graph_name, rdf_file, format, block_size, commit_threshold, cache_size):
"""Insert RDF triples from file RDF_FILE into the RDF graph GRAPH_NAME, described in the configuration file CONFIG."""
# load graph from config file
graph, backend = load_graph(config, graph_name, logger, backend... | 5,317,398 |
def add_col_from_dict(
infile,
col_data,
outfile,
dtypes,
write_header=True
):
"""
TODO: fill this in
Add column to gzipped CSV.
@param infile:
@param col_data:
@param outfile:
@param dtypes:
@param write_header:
@return:
"""
csvinput = CsverveInput(infi... | 5,317,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.