content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import List
from typing import Dict
import ast
def trigger_data_load(
regions: List[str],
cluster_config_path: str,
default_config_path: str,
env_config_path: str,
input_vars: Dict[str, str],
) -> dict:
"""
:param regions: AWS regions in which the EMR job ne... | 9f51c3284de2acb65105615ec40b2611603d7a24 | 3,634,008 |
def _test_afqt(df):
""" NLSY provides percentile information for AFQT scores, reconstructed here
as a check based on NLSY instructions.
"""
# Breaking the logic of the code a bit, copies of the object are drawn from here.
df_internal = df.copy(deep=True)
# Adjust for missing values here, even ... | 97937957fc8d8782dde655fbf5f063264fe2e575 | 3,634,009 |
import csv
def _load_roiscsv(fp):
"""
Loads the specified ROIs CSV file.
:param fp: the file object for the ROIs CSV data to load
:type fp: file
:return: the list of predictions
:rtype: list
"""
result = []
reader = csv.DictReader(fp)
for i, row in enumerate(reader):
... | 13c697e224aba1562d15b39dac18c932a2b2fa0e | 3,634,010 |
def argmin(array):
""" Return the index to the maximum element of an array """
return min(zip(array, xrange(len(array))))[1] | 17e30a433d20eeef8d5a3cc48361245ba9ad9328 | 3,634,011 |
def braid_group_rep_loss(input_dim=1):
"""
Purpose
-------
loss for the braid group. When the loss is minimal, the braid group relations are satisfied for the generator R_op.
Parameters
----------
input_dim, the dimension of the R_op generator for the braid group.
... | 1d76f8a950ba997bc5a692cb56daa413d853491e | 3,634,012 |
def strains():
"""
Endpoint that returns a list of all available strains.
Returns
-------
strains : JSON
Returns a JSON array of all available strains.
"""
try:
strains = df2.to_json(orient="records")
except Exception as e:
raise e
return strains | 793a8cc692247c6a9b930f69a2956620b23f5809 | 3,634,013 |
def _number_of_digits(number: int) -> int:
""" Returns the number of digits in the given number """
return int(log10(number)) + 1 | c3270c53516793345ce2b96dbc205ccbbca3adf2 | 3,634,014 |
def get_document(doc_slug: str) -> QuerySet:
""" Возвращает документ по слагу. """
return models.Document.objects.filter(
slug=doc_slug
).select_related('category', 'publisher') | 4c169b3ba1b4486a4c5c4c851dfa4e2efdb6ca07 | 3,634,016 |
def currentsellings():
"""shows a list of the ites that the user is currently selling"""
items = Item.query.filter(
(Item.user_id == session["user_id"]) & (Item.sold == 0)).all()
return render_template("currentsellings.html", items=items) | 6aa8dd754fda4b566f15909a556e9ca1678f7a7e | 3,634,017 |
def catches(raisable: Raisable, catchable: Catchable):
"""
Tests if raisable value would be catchable by catchable value.
"""
if isinstance(catchable, type):
catchable = [catchable]
if isinstance(raisable, type):
return any(issubclass(raisable, exc) for exc in catchable)
else:
... | 14ddb2465e618ba090e0885edf1141bd9657ac2b | 3,634,018 |
def bootstrap_test(
stat_val,
bootstrap_estimates,
nobs,
stat_val_control,
bootstrap_estimates_control,
nobs_control
) -> BootstrapTestResult:
"""
:param stat_val: sample value of statistic in treatment group
:param bootstrap_estimates: bootstrap estimates (10... | 488f6c8cbd5f27f97840e511a0d8b04f5c3647dd | 3,634,019 |
import urllib
import tempfile
def query_ned_by_refcode(refcode='2011ApJS..193...18W',
root_url='http://nedwww.ipac.caltech.edu/cgi-bin/nph-objsearch'):
"""
Query NED for basic data on objects cited in a particular reference.
keywords:
refcode - 19-digit reference code for journal article.
... | 31846479c7098708ff67862852b1d1f9812e4dbb | 3,634,020 |
def calc_distance_between_point_and_line(line_points, p3):
"""[Calcs the perpendicular distance between a point and a line]
Arguments:
line_points {[list]} -- [list of two 2-by-1 np arrays with the two points that define the line]
p3 {[np array]} -- [point to calculate the distance from]
... | 3993d40afc5be216c5e9e8b1dee1061c11d8dfb4 | 3,634,021 |
def set_hash_status(qhash, **kwargs):
"""
Set the enabled status of a hash
Variables:
qhash => Hash to change the status
Arguments:
None
Data Block:
"true"
Result example:
{"success": True}
"""
user = kwargs['user']
data = request.json
if len(qhash) not... | e6f5fe661b01ad1b9b591ab9c23f61b62bce81f9 | 3,634,022 |
def ubatch_to_csv(batch):
"""
Utility function to convert a batch of APIUser data to CSV.
"""
permkey = 'permissions_dict'
fields = [k for k in batch[0].keys() if k != permkey]
fields.extend(batch[0][permkey].keys())
return '{}\n{}'.format(','.join(fields), '\n'.join([
','.join([str(... | 9950cb8e1f79f2cc37580142a125717e7e534de1 | 3,634,024 |
import requests
def get_user_repositories(username: str, show_forked: bool) -> list[Repository]:
"""
Retrieve the github repositories for a specific user.
Args:
username: The github username
show_forked: Whether to keep or discard forked repos
Returns: The github repositories for the... | 97dc310b1efbfde1121dcc79fa6464a33ed943f5 | 3,634,025 |
import torch
def evaluate_sample(
ds,
sample_id,
t=None,
visualise=True,
gt_masked=None,
model=None,
mask_targ=None,
save=False,
pose=None,
):
"""
Evaluate one sample of a dataset (ds). Calculate PSNR and mAP,
and visualise different model components for this sample. Ad... | 0f87f7cd35fd6263c646de29241b4c807828055f | 3,634,026 |
from googleapiclient import discovery
from googleapiclient import errors
from typing import NamedTuple
def retrieve_best_run(
project_id: str, job_id: str
) -> NamedTuple('Outputs', [('metric_value', float), ('alpha', float),
('max_iter', int)]):
"""Retrieves the parameters of the be... | 8fdc98557703cbedf8620c1c62ca62a223f15dee | 3,634,027 |
def FindDeck(transact, msg_list):
"""
Returns None if not a deck message.
:param transact:
:param msg_list:
:return:
"""
for msg in msg_list:
if 'connectResp' in msg:
try:
deck = msg['connectResp']['deckMessage']['deckCards']
Log('Found Dec... | 98e5ce5921f43c8ec260db052fcd7058d3c9f322 | 3,634,028 |
from typing import Optional
def mean(x: VariableLike,
dim: Optional[str] = None,
*,
out: Optional[VariableLike] = None) -> VariableLike:
"""Element-wise mean over the specified dimension.
If the input has variances, the variances stored in the output are based on
the "standard ... | 471d6f36b1ed30ce5dc57ec3a018f4adc0325094 | 3,634,029 |
def HarmonicOscillator(inverse_mass_matrix, k=1.0, m=1.0):
"""Potential and Kinetic energy of an harmonic oscillator."""
def potential_energy(x: TensorVariable) -> TensorVariable:
return at.sum(0.5 * k * at.square(x))
def kinetic_energy(p: TensorVariable) -> TensorVariable:
v = inverse_mas... | bf035050405f8d7d074ff1931e25d990cfba91f0 | 3,634,030 |
def guid_to_num(guid):
"""
Convert a DHT guid to an integer.
Args:
guid: The guid to convert, as a string or unicode, in
hexadecimal.
Returns:
An integer corresponding to the DHT guid given.
"""
return int(guid.rstrip('L'), base=16) | 7da3e7a60b6ae3410baab62083714f47a3afc790 | 3,634,031 |
def script_code(script_name):
"""Returns the four-letter ISO 15924 code of a script from its long name."""
load_data()
folded_script_name = _folded_script_name(script_name)
try:
return _HARD_CODED_FOLDED_SCRIPT_NAME_TO_CODE[folded_script_name]
except:
return _folded_script_name_to_co... | 6e04beff3dbaf22b0f348edc7fd2af201d16f024 | 3,634,032 |
from typing import Dict
def get_dashboard() -> Dict:
"""Get dashboard for user
:return: Returns dictionary with surveys and reports
:rtype: Dict
"""
user = get_user()
user_surveys = get_user_surveys(user)
result = []
for survey in user_surveys:
author = get_user(survey.Author... | 28d99043ffc1cd57b40916bc1a5839e8c38ee161 | 3,634,033 |
def acos(close):
"""Vector Trigonometric ACos
:param close:
:return:
:real:
"""
return ACOS(close) | 66c3be980464bb816435ee2ef65ab3ef2a4c3cfc | 3,634,034 |
import itertools
def gather_slice_list_items(slices, key):
"""For a list of slices, get the flattened list of all of a certain key."""
return list(itertools.chain(*[s[key] for s in slices if key in s])) | 068b511aefa124f9881f0d8cdc4d115b15922066 | 3,634,035 |
def mock_rasterio_open_cogs(band):
"""Mock rasterio Open for Sentinel2 dataset."""
assert band.startswith("s3://sentinel-cogs")
band = band.replace("s3://sentinel-cogs", SENTINEL_COG_BUCKET)
return rasterio.open(band) | 53e69cf3bd01dd9697d502aece59c00e16032fed | 3,634,036 |
def advance_time(df, delay, column=None, keep_all_timestep=False):
"""
This function rolls the given columns of the given dataframe by a number of hours defined by the delay.
It also erases the last n-rows (n=delay) of each sequences.
:param df:
:param delay:
:param column:
:param keep_all_t... | f361e4b63ef68ea0cdb923bf8337787a6094fe83 | 3,634,037 |
from re import T
def course():
""" Courses Controller """
mode = session.s3.hrm.mode
def prep(r):
if mode is not None:
auth.permission.fail()
if r.component_name == "training":
s3.crud_strings["hrm_training"].label_create = T("Add Trainee")
return True
... | a3197b21baee42982b780dfe76d80fe08e043324 | 3,634,038 |
def reset_password(request):
"""view to reset the password"""
if request.method == "POST":
valid, errors = validate(*['code', 'password'], **get_request_data(request))
if not valid:
return Response({"error": errors}, status=status.HTTP_422_UNPROCESSABLE_ENTITY)
data = get_req... | cf75ee3b2fa5249b01abc690e4adebfd6d1ac16c | 3,634,040 |
def str_to_datetime(date: str) -> dt:
"""Convert str to datetime"""
if date is None:
return None
return dt.strptime(date, '%Y-%m-%d') | 5db25c97fd6e79d7c8ed26a95c4809a5c432c705 | 3,634,041 |
def test_applies_method_filters(app):
"""Method filters are applied for generated and rendered templates"""
with app.test_request_context():
genshi = app.extensions['genshi']
@genshi.filter('html')
def prepend_title(template):
return template | Transformer('head/title').prep... | e7fecc970507fa2745cb87a6ebf0c341fb0f1c76 | 3,634,042 |
def contributions(datafile):
""" text data file => list of string """
contribs = []
with open(datafile, 'r') as data:
for line in data.readlines():
line = line.strip()
line_data = line.split(" ")
info_string = " ".join(line_data[:-1])
contrib = {}
con... | 37c5743df822be2cefdbe0bad60db35491ea599d | 3,634,043 |
from datetime import datetime
import dateutil
def utcnow():
"""
Get the current UTC time which has the time zone info.
"""
return datetime.datetime.now(dateutil.tz.tzutc()) | 9efe15bac944732ee5260ba0834b796370cae0d3 | 3,634,044 |
from corehq.apps.users.models import CouchUser
def get_xform_location(xform):
"""
Returns the sql location associated with the user who submitted an xform
"""
user_id = getattr(xform.metadata, 'userID', None)
if not user_id:
return None
user = CouchUser.get_by_user_id(user_id)
if ... | e681325e161946bc12f32db721094ce9b68192f6 | 3,634,045 |
import cloudpickle
import inspect
def wrap_non_picklable_objects(obj, keep_wrapper=True):
"""Wrapper for non-picklable object to use cloudpickle to serialize them.
Note that this wrapper tends to slow down the serialization process as it
is done with cloudpickle which is typically slower compared to pick... | fdddcfbcff2137dd98b037171563e999ef53d138 | 3,634,046 |
def values(names):
"""
Method decorator that allows inject return values into method parameters.
It tries to find desired value going deep. For convinience injects list with only one value as value.
:param names: dict of "value-name": "method-parameter-name"
"""
def wrapper(func):
@wraps... | 324bbe30c9c0ae508c479cd760d3debd84cfa3d6 | 3,634,047 |
def post():
""" Get. """
return render_template('public/post.html') | dc33760c5e45f777efa1ddde5f6dae19676e2809 | 3,634,048 |
from typing import List
def ensemble(models: List [training.Model],
model_input: Tensor) -> training.Model:
""" ensemble part
"""
outputs = [model.outputs[0] for model in models]
y = Average()(outputs)
model = Model(model_input, y, name='ensemble')
return model | 41ec18fafaa19e67b40371fe553e8bc6ebdb10b3 | 3,634,049 |
def save_layout(request, layout_id):
""" Save layout properties """
if request.method != 'POST':
return res.get_only_post_allowed({})
layout_entry = BluesteelLayoutEntry.objects.filter(id=layout_id).first()
if layout_entry is None:
return res.get_response(404, 'Bluesteel layout not foun... | 735979a70ecb128589317a4eb26d7c077705a406 | 3,634,050 |
def _to_deck(group: ParseResults) -> Deck:
"""Parse a deck into a python list."""
result: Deck
if "size" in group:
N = int(group["size"])
if group["type"] == "C":
result = ["".join(group.value)]
elif group["type"] == "I":
result = [int("".join(k)) for k in gro... | dcf67e00ae293b88386d2b58bed66b59e7588b41 | 3,634,051 |
def build_gabriel_graph_from_delaunay(X, tri, delaunay_adjacency_matrix):
"""Remove edges from delaunay triangulation and returns the adjaceny matrix of a Gabriel graph
:param delaunay_adjacency_matrix: scipy sparse matrix (csr format)
"""
# Convert adjacency matrix to coo format for direct access to ea... | 6da3883cbc03357c737e358903d875535b8ee4fc | 3,634,052 |
import random
def randomize_demand(demand):
"""Return a randomized demand when given a static demand"""
return random.uniform(0, 2.25) * demand | 01eed8f0008e71af117920782a2a42b566055a89 | 3,634,054 |
def _collect_input_shape(input_tensors):
"""Collects the output shape(s) of a list of Keras tensors.
# Arguments
input_tensors: list of input tensors (or single input tensor).
# Returns
List of shape tuples (or single tuple), one tuple per input.
"""
input_tensors = to_list(input_t... | 4c3dfc82f999c6def2a3c78c2f323de8a4e2c67c | 3,634,055 |
from datetime import datetime
import math
def iaga2df(iaga2002_fname, D_to_radians=True):
"""
Parser the magnetometer data record stored in the IAGA-2002 format
file *iaga2002_fname*. If *D_to_radians*, declination data (D) are
converted from degrees to radians. Return the tuple with the
:class:`D... | 394d24392a00aed1be4e5975794bb67fecf03f14 | 3,634,056 |
def geom_bar(mapping=aes(), *, fill=None, color=None, position="stack", size=None):
"""Create a bar chart that counts occurrences of the various values of the ``x`` aesthetic.
Supported aesthetics: ``x``, ``color``, ``fill``
Returns
-------
:class:`FigureAttribute`
The geom to be applied.
... | 5d617797742ad4ea1e2b13424bc80054f97be436 | 3,634,057 |
def MobileNetV3_Large_Base(num_classes,
in_channels):
"""构建基础(大型)MobileNetV3
"""
return MobileNetV3_Large(num_classes=num_classes,
in_channels=in_channels,
alpha=1.0) | 979b48ee5488e0fe3a566983539a4cd9b683b862 | 3,634,059 |
def compute_trajectory_points(path, sgrid,
ugrid, xgrid,
dt=1e-2, smooth=True,
smooth_eps=1e-4):
"""Compute trajectory with uniform sampling time.
Note
----
Additionally, if `smooth` is True, the return trajectory... | 924a68984a08d4db821e94e2fdf32879bd03f356 | 3,634,060 |
from typing import Tuple
def _reorder_cols(
df, key_columns: Tuple[str], master_grouping_key: str
) -> pd.DataFrame:
"""
Helper function for creating a user-friendly schema structure for the output prediction
dataframe that mirrors what would be expected (grouping columns preceding data).
:param ... | 05d51a1d8d3869dfb6bd83d5d81e6c9b56638c73 | 3,634,062 |
from typing import Dict
from typing import Any
import requests
def create_rule(rule: Dict[str, Any]) -> Dict[str, Any]:
"""Create a rule, returning the result from SmartThings."""
url = _url("/rules")
params = {"locationId": CONTEXT.get().location_id}
response = requests.post(url=url, headers=_headers... | f68010520874d07b5c469d91d9e7ca804460535e | 3,634,064 |
from config import bot_config as _BOT_CONFIG
def _get_bot_config():
"""Returns the bot_config.py module. Imports it only once.
This file is called implicitly by _call_hook() and _call_hook_safe().
"""
global _BOT_CONFIG
if not _BOT_CONFIG:
return _BOT_CONFIG | 0b725caa079b37ac2274b4350c4473e5016efac2 | 3,634,065 |
def img_post_process(img_tensor):
"""Image postprocess
Convert torch.tensor() images into list of cv2 images.
1. Convert torch.tensor() to np.array(), and transpose [C, H, W] to [H, W, C].
2. Scale [0., 1.] into [0, 255].
3. Convert data format float to np.uint8.
4. Convert color channels from R... | c43ded6097d726ce62e8ad1c8ae5025ce4d21cb8 | 3,634,066 |
def apply_grid(dataset, masker=None, scale=5, threshold=None):
""" Imposes a 3D grid on the brain volume and averages across all voxels
that fall within each cell.
Args:
dataset: Data to apply grid to. Either a Dataset instance, or a numpy
array with voxels in rows and features in column... | 22727b208f9f57037e2d35dc78acc7bdbd49212a | 3,634,067 |
from pathlib import Path
from typing import Optional
from typing import Set
def cookiecutter_template(
output_dir: Path,
repo: Repo,
cruft_state: CruftState,
project_dir: Path = Path("."),
cookiecutter_input: bool = False,
checkout: Optional[str] = None,
deleted_paths: Optional[Set[Path]] ... | 0351039fc7022de1908fca2e2bc54676cd01bc56 | 3,634,068 |
def get_item():
"""Returns a dict representing an item."""
return {
'name': 'Nikon D3100 14.2 MP',
'category': 'Cameras',
'subcategory': 'Nikon Cameras',
'extended_info': {}
} | 692c3d83ee1cc04026e71b7ad7357ebd9930f47f | 3,634,069 |
import math
def humanify_ms(ms: int) -> str:
""" Converts an amount of millis to a more readable string.
Args:
ms (int): the amount of millis to convert
Returns:
The human string that represents the given amount of millis
"""
if ms > TimeUnits.MS_IN_MIN:
return "{:d}m {:d... | 6130ea6a6de05c12b04ae14be3ff2f180c113391 | 3,634,070 |
import torch
def abs_(input):
"""
In-place version of :func:`treetensor.torch.abs`.
Examples::
>>> import torch
>>> import treetensor.torch as ttorch
>>> t = ttorch.tensor([12, 0, -3])
>>> ttorch.abs_(t)
>>> t
tensor([12, 0, 3])
>>> t = ttorch.t... | 65b32c91cf00a72b94b950d0e65cca71390b8c24 | 3,634,071 |
import pathlib
def get_filepath(filepath, overwrite):
"""
Get the filepath to download to and ensure dir exists.
Returns
-------
`pathlib.Path`, `bool`
"""
filepath = pathlib.Path(filepath)
if filepath.exists():
if not overwrite:
return str(filepath), True
... | bceb462f98f328d20226d6e516d78b027614cd01 | 3,634,073 |
import textwrap
def dedent(text):
"""Remove any common leading whitespace from every line in a given text."""
return textwrap.dedent(text) | 514f9f41feac1c19ff92d6c9258bf54d7d3d7bd8 | 3,634,076 |
from typing import Dict
from typing import List
def get_agents(agents: Dict, nr_players: int, action_num: int, state_shape: List):
"""
Initalize agents to play the game.
:param nr_players: Number of players, amount of agents generated
:param agents: Dictionary of agent_name: number of agents pairs
... | dfaee6e93e14a33659817da626f8dd990c46d528 | 3,634,077 |
def enumerate_square(i, n):
"""
Given i in the range(n^2-n) compute a bijective mapping
range(n^2-n) -> range(n)*range(n-1)
"""
row = int(i // (n-1))
col = int(i % (n-1))
if col >= row:
col += 1
return row, col | 93d3465c88a7bc9952161524fded4d7250131a65 | 3,634,078 |
def universal_transformer_with_lstm_as_transition_function(
layer_inputs, step, hparams, ffn_unit, attention_unit,
pad_remover=None):
"""Universal Transformer which uses a lstm as transition function.
It's kind of like having a lstm, filliped vertically next to the Universal
Transformer that co... | 41051acefd16acff70f25d6402c43bf92176217d | 3,634,079 |
def extract_names(bigrams):
"""
Tag each of the bigram tuples with the appropriate Part of Speech.
"""
named_bigrams = []
NUM_BIGRAMS = len(bigrams)
stemmer = LancasterStemmer()
for index, bigram in enumerate(bigrams):
if bigram[0].upper() in FIRST_NAMES:
person = " ".joi... | 0eaf7e29940750af52b4d096ea47bc3524897817 | 3,634,080 |
def GetActiveProjectAndAccount():
"""Get the active project name and account for the active credentials.
For use with wrapping legacy tools that take projects and credentials on
the command line.
Returns:
(str, str), A tuple whose first element is the project, and whose second
element is the account.
... | cde41445f0f0811a8e580ff617f08573fac91d9a | 3,634,081 |
import falcon
def csrf_protection(func):
"""
Protect resource from common CSRF attacks by checking user agent and referrer
"""
def wrapped(self, req, resp, *args, **kwargs):
# Assume curl and python-requests are used intentionally
if req.user_agent.startswith("curl/") or req.user_agent... | 411a89f02eee3d236ae1f1dc124dfac3a22800d8 | 3,634,082 |
from pathlib import Path
async def get_system(
system_id: UUID = Path(
..., description="ID of system to get", example=models.SYSTEM_ID
),
storage: StorageInterface = Depends(StorageInterface),
) -> models.StoredPVSystem:
"""Get a single PV System"""
with storage.start_transaction() as st:... | 99d600f5f67c6aacd93866f2f874d5aec8fe2089 | 3,634,083 |
import re
def get_playback_time(playback_duration):
""" Get the playback time(in seconds) from the string:
Eg: PT0H1M59.89S
"""
# Get all the numbers in the string
numbers = re.split('[PTHMS]', playback_duration)
# remove all the empty strings
numbers = [value for value in numbers if v... | 6a68c68ce465610b57626a725ac9c8889b527fdb | 3,634,084 |
def rate_limit(state, task_name, rate_limit, **kwargs):
"""Tell worker(s) to modify the rate limit for a task by type.
See Also:
:attr:`celery.task.base.Task.rate_limit`.
Arguments:
task_name (str): Type of task to set rate limit for.
rate_limit (int, str): New rate limit.
"""
... | abdd903fe492e64dec799e02d9a4359814067a1e | 3,634,085 |
import torch
def listdict2dictlist(listdict: list, to_array=False) -> dict:
"""
@type listdict: list
@param listdict: list of dicts with the same keys
@return: dictlist: dict of lists of the same lengths
@rtype: dict
"""
d = {k: [d[k] for d in listdict] for k in listdict[0].keys()}
if ... | 77c464d1a2e272bf43b39489ea41294603464334 | 3,634,086 |
def hitLine(lineA, lineB, point, lineWidth):
"""Checks whether the point is in line or out.
lineA tuple: a point of the line.
lineB tuple: another point of the line.
point tuple: point we want to check.
lineWidth float: width of the line.
returns: True if in and False if out.
"""
if li... | b20430c8ef161d19431c5e4cc19951cc09ffa352 | 3,634,087 |
def parse_args() -> Namespace:
"""
Parse arguments.
Parse optional arguments passed to the application during runtime and
return the results.
Returns
-------
Namespace
Returns a ``Namespace`` containing all of the arguments passed by the
user including defaults.
"""
... | 8326c37ccd1a5878dd54fb84aa25ea78a87451c8 | 3,634,088 |
def PatchWord(ea, value):
"""
Change value of a program word (2 bytes)
@param ea: linear address
@param value: new value of the word
@return: 1 if successful, 0 if not
"""
return idaapi.patch_word(ea, value) | e2e03d198764b706f643c5a41aefa7a6a67fc387 | 3,634,089 |
def _binary_array_to_hex(arr):
"""
internal function to make a hex string out of a binary array
"""
h = 0
s = []
for i, v in enumerate(arr.flatten()):
if v:
h += 2**(i % 8)
if (i % 8) == 7:
s.append(hex(h)[2:].rjust(2, '0'))
h = 0
return "... | b705e4dc1dfc48f92f7c97dd7ba9d4dd4c4d0a98 | 3,634,090 |
def float_nsf(num, precision=17):
"""n-Significant Figures"""
return ('{0:.%ie}' % (precision - 1)).format(float(num)) | c2390b69364455adc6220e1e4aad81d7081bd5e4 | 3,634,091 |
import logging
def logit_layer_for_bitext(
nb_classes, # V
inputs, # [B, M, dim]
outputs, # [B, N]
dim,
nb_softmax_samples, # S
is_training,
approximation='botev-batch',
support=None, # [S]
importance=None, # [S]
name='logit'
):
... | 1efd3cffe3194c7bca9b571ddd01369adeef9207 | 3,634,092 |
def angle_close(angle1, angle2):
""" Determines whether an angle1 is close to angle2. """
return abs(angle_difference(angle1, angle2)) < np.pi/8 | 7a480a94de8440ff50307e9c7a218424fe45675a | 3,634,095 |
def server_url():
# type: () -> Optional[str]
"""Get the configured server URL
"""
url = toolkit.config.get(SERVER_URL_CONF_KEY)
if not url:
raise ValueError("Configuration option '{}' is not set".format(
SERVER_URL_CONF_KEY))
if url[-1] == '/':
url = url[0:-1]
re... | e4958022e1beb415af4f23e93d678dd9982e1637 | 3,634,096 |
def clean_data():
"""
Method for cleaning the data and removing unnecessary features
Args:
None
Returns:
df (pandas dataframe): Return pandas dataframe
"""
df = pd.read_csv("dashboard/asset/data/kl_billboard.csv")
# Drop different types of roads such as motorway, trunk etc... | b3fa3cd8b590b5f7ec4168006a0470c0398a2f8a | 3,634,097 |
from stingray.lightcurve import Lightcurve
from stingray.events import EventList
from stingray.crossspectrum import Crossspectrum
from hendrics.io import get_file_type
from stingray.io import _retrieve_pickle_object
import logging
def load_dataset_from_intermediate_file(fname):
"""Save Stingray object to intermed... | e1603554494082bd4cc155a81d283225e4305e73 | 3,634,098 |
import functools
def _FlowMethod(func):
"""Decorator that checks the if port_id exists on board."""
@functools.wraps(func)
def wrapper(instance, port_id, *args, **kwargs):
if port_id not in instance.flows:
raise FlowManagerError('Not a exist port_id %d' % port_id)
return func(instance, port_id, *a... | d977b07b329c2943aa2dca465cab80227e8c67f3 | 3,634,099 |
import numpy
def _xml_column_name_orig_to_new(column_name_orig):
"""Converts name of XML column from original (segmotion) to new format.
:param column_name_orig: Column name in original format.
:return: column_name: Column name in new format.
"""
orig_column_flags = [c == column_name_orig for c ... | 4f5302381d6a94d74d311355e1aad8c79e1e0cbe | 3,634,101 |
def ndwi(raster):
"""
Normalized Difference Water Index (NDWI)
NDWI := factor * (Green - NIR1) / (Green + NIR1)
:param raster: xarray or numpy array object in the form (c, h, w)
:return: new band with SI calculated
"""
nir1, green = _get_band_locations(
raster.attrs['band_names'], ['... | 64e8d553b8ace8c3fc3ea2a7fed98c43fcadf22a | 3,634,104 |
def get_settings():
"""Utility function to retrieve settings.py values with defaults"""
return {
"DJANGO_WYSIWYG_MEDIA_URL": getattr(settings, "DJANGO_WYSIWYG_MEDIA_URL", urljoin(settings.STATIC_URL, "ckeditor/")),
"DJANGO_WYSIWYG_FLAVOR": getattr(settings, "DJANGO_WYSIWYG_FLAVOR", "yui"),
... | 1028431d5facd406020892cb5019b26de55f7193 | 3,634,105 |
def einsum_via_matmul(input_tensor, w, num_inner_dims):
"""Implements einsum via matmul and reshape ops.
Args:
input_tensor: float Tensor of shape [<batch_dims>, <inner_dims>].
w: float Tensor of shape [<inner_dims>, <outer_dims>].
num_inner_dims: int. number of dimensions to use for inner pr... | acc672a84661e11444a452393587d0dfc164b636 | 3,634,106 |
def cost(guess, tdoa, array):
""" Calculate the sum of the squares of the loss function of hyperbolic
least squares problem
guess : 1D or 2D row ndarray with one or more guesses coordinates
tdoa : column 2D ndarray with the TDOA from some reference sensor
receptorsPosit... | 27b08a1a6966d5f18974244f4db53db5c6c14fee | 3,634,107 |
def from_literal(tup):
"""Convert from simple literal form to the more uniform typestruct."""
def expand(vals):
return [from_literal(x) for x in vals]
def union(vals):
if not isinstance(vals, tuple):
vals = (vals,)
v = expand(vals)
return frozenset(v)
if not isinstance(tup, tuple):
... | a06d35e27512bfeae030494ca6cad7ebac5c7d2c | 3,634,108 |
def distill_resnet_32_to_15_cifar20x5():
"""Set of hyperparameters."""
hparams = distill_base()
hparams.teacher_model = "resnet"
hparams.teacher_hparams = "resnet_cifar_32"
hparams.student_model = "resnet"
hparams.student_hparams = "resnet_cifar_15"
hparams.optimizer_momentum_nesterov = True
# (base_lr... | 503b49f0e61191eb87516b8c83ca88fbc0313be2 | 3,634,109 |
from datetime import datetime
def timestamp() -> datetime.datetime:
"""
Returns a datetime object representing the current UTC time. The last 3 digits of the microsecond frame are set
to zero.
:return: a UTC timestamp
"""
# Get tz-aware datetime object.
dt = arrow.utcnow().naive
# S... | e1fb7fbe39bef103704af0a7bfece4038506bbdc | 3,634,110 |
def next_fake_batch():
"""
Return random seeds for the generator.
"""
batch = np.random.uniform(
-1.0,
1.0,
size=[FLAGS.batch_size, FLAGS.seed_size])
return batch.astype(np.float32) | 80c4b32fd145430dad06b16fd90273fd9aa944f1 | 3,634,111 |
def print_result(error, real_word):
"""" print_result"""
if error == 5:
print("You lost!")
print("Real word is:", real_word)
else:
print("You won!")
return 0 | 598814ac64ac767c102080a0a82541d3b888843c | 3,634,112 |
def read_cpu_info():
"""Return the CPU model number & number of CPUs."""
try:
with open('/proc/cpuinfo') as f:
models = [line[line.index(':')+2:] for line in f if line.startswith('model name')]
return models[0].strip(), len(models)
except:
log.exception('Failed to read CP... | 68ce0de7a36d01fc18f3be7f182b37735ec5683a | 3,634,113 |
import yaml
def _yaml_parse(s):
"""Uses yaml module to parse s to a Python value.
First tries to parse as an unnamed flag function with at least two
args and, if successful, returns s unmodified. This prevents yaml
from attempting to parse strings like '1:1' which it considers to
be timestamps.
... | 52a788b63ade60bed879b5d0a14e21177902af2e | 3,634,114 |
def mongo_convert(sch):
"""Converts a schema dictionary into a mongo-usable form."""
out = {}
for k in sch.keys():
if k == 'type':
out["bsonType"] = sch[k]
elif isinstance(sch[k], list):
out["minimum"] = sch[k][0]
out["maximum"] = sch[k][1]
elif is... | 0208ceda058042a9f44249a1b724c4b7883afec1 | 3,634,115 |
def files_identical(a, b):
"""Return a tuple (file a == file b, index of first difference)"""
a_bytes = open(a, "rb").read()
b_bytes = open(b, "rb").read()
return bytes_identical(a_bytes, b_bytes) | a8e392f5b2682459525c329d1bd8ab64104628b6 | 3,634,116 |
import math
def discounted_cumulative_gain(rank_list):
"""Calculate the discounted cumulative gain based on the input rank list and return a list."""
discounted_cg = []
discounted_cg.append(rank_list[0])
for i in range(1, len(rank_list)):
d = rank_list[i]/math.log2(i+1)
dcg = d + disco... | eaa5ad6185e2abb239097be5399dffd82d143fd3 | 3,634,117 |
def adapter(js_constructor, base=Adapter):
"""
Allows a class to implement its adapting logic with a `js_args()` method on the class itself.
This just helps reduce the amount of code you have to write.
For example:
@adapter('wagtail.mywidget')
class MyWidget():
...
... | e808a4a8dd50fa61157f45a014ec390cc8ee1370 | 3,634,118 |
import warnings
import inspect
def data(input, name_func=None, doc_func=None, skip_on_empty=False, **legacy):
""" A "brute force" method of parameterizing test cases. Creates new
test cases and injects them into the namespace that the wrapped
function is being defined in. Useful for parameterizing... | 2d38bb642a1e5a020f7c07de8348c5621c8cbccb | 3,634,120 |
def get_form_field_names(form_class):
"""Return the list of field names of a WTForm.
:param form_class: A `Form` subclass
"""
unbound_fields = form_class._unbound_fields
if unbound_fields:
return [f[0] for f in unbound_fields]
field_names = []
# the following logic has been taken fr... | 27c91a1e3c1b71f69d44747955d59cee525aa50e | 3,634,121 |
def gen_empty_structure_data_array(number_of_atoms):
"""
Generate an array data structure to contain structure data.
Parameters
----------
number_of_atoms : int
The number of atoms in the structure.
Determines the size of the axis 0 of the structure array.
Returns
-------
... | 3602483721bd5573cfa9bb605db52511999349ac | 3,634,122 |
from datetime import datetime
def actives_alerts_table(strategy, style='', offset=None, limit=None, col_ofs=None,
group=None, ordering=None, datetime_format='%y-%m-%d %H:%M:%S'):
"""
Returns a table of any active alerts.
"""
COLUMNS = ('Symbol', '#', 'Label', 'TF', 'Created', ... | 729c9e7f30c1c73c4f41cb8ced18820b79639db7 | 3,634,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.