content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from io import StringIO
import pandas
from datetime import datetime
def isotherm_from_bel(path):
"""
Get the isotherm and sample data from a BEL Japan .dat file.
Parameters
----------
path : str
Path to the file to be read.
Returns
-------
dataDF
"""
with open(path) as ... | 7aa144942ef6e0cb3d2926817015692b8fe8b99b | 3,645,179 |
def model(x, a, b, c):
"""
Compute
.. math::
y = A + Be^{Cx}
Parameters
----------
x : array-like
The value of the model will be the same shape as the input.
a : float
The additive bias.
b : float
The multiplicative bias.
c : float
The expone... | 12a8272fb773226ad328daeb460cc2ca84d4c6e0 | 3,645,181 |
import inspect
def equal_matches(
matches_a: kapture.Matches,
matches_b: kapture.Matches) -> bool:
"""
Compare two instances of kapture.Matches.
:param matches_a: first set of matches
:param matches_b: second set of matches
:return: True if they are identical, False otherwise.
... | 57efdd63a56f4e94afc9a57e05f4e4f726ce7b44 | 3,645,183 |
def convert_to_example(img_data, target_data, img_shape, target_shape, dltile):
""" Converts image and target data into TFRecords example.
Parameters
----------
img_data: ndarray
Image data
target_data: ndarray
Target data
img_shape: tuple
Shape of the image data (h,... | d8dd2b78a85d2e34d657aa36bfe3515ef1dd5418 | 3,645,184 |
def linear(args, output_size, bias, bias_start=0.0, scope=None, var_on_cpu=True, wd=0.0):
"""Linear map: sum_i(args[i] * W[i]), where W[i] is a variable.
Args:
args: a 2D Tensor or a list of 2D, batch x n, Tensors.
output_size: int, second dimension of W[i].
bias: boolean, whether to add a bi... | 1072115bc42b3d2acb3d41cd0116a636f6bb7804 | 3,645,185 |
def _start_job(rule, settings, urls=None):
"""Start a new job for an InfernoRule
Note that the output of this function is a tuple of (InfernoJob, DiscoJob)
If this InfernoJob fails to start by some reasons, e.g. not enough blobs,
the DiscoJob would be None.
"""
job = InfernoJob(rule, settings, ... | 5eab30433004240d79f1ec4eeac868b40632cdde | 3,645,186 |
def mult(dic,data,r=1.0,i=1.0,c=1.0,inv=False,hdr=False,x1=1.0,xn='default'):
"""
Multiple by a Constant
Parameter c is used even when r and i are defined. NMRPipe ignores c when
r or i are defined.
Parameters:
* dic Dictionary of NMRPipe parameters.
* data array of spectral data.
... | 833ab3784dc9210aa6be0f968f9115982ea93753 | 3,645,187 |
import re
def navigation_target(m) -> re.Pattern:
"""A target to navigate to. Returns a regular expression."""
if hasattr(m, 'any_alphanumeric_key'):
return re.compile(re.escape(m.any_alphanumeric_key), re.IGNORECASE)
if hasattr(m, 'navigation_target_name'):
return re.compile(m.navigation_... | 62cc847f5454e76afb128fd752b7fa83fd2e167e | 3,645,189 |
def hammingDistance(strA, strB):
""" Determines the bitwise Hamming Distance between two strings. Used to
determine the fitness of a mutating string against the input.
Example:
bin(ord('a')) == '0b1100001'
bin(ord('9')) == '0b0111001'
bin... | d417ac22a1abd4c2df0f274d809096f354ac4150 | 3,645,190 |
import regex
def convert(s, syntax=None):
"""Convert a regex regular expression to re syntax.
The first argument is the regular expression, as a string object,
just like it would be passed to regex.compile(). (I.e., pass the
actual string object -- string quotes must already have been
removed an... | e61a9d555008c9b36b579f6eb1e32e1e9fa0e983 | 3,645,191 |
import select
def current_user(request):
"""Return the list of all the users with their ids.
"""
query = select([
User.id.label('PK_id'),
User.Login.label('fullname')
]).where(User.id == request.authenticated_userid)
print
return dict(DBSession.execute(query).fetchone()) | 6951a6c638886d773a9e92e161d9aa2b166b17b3 | 3,645,192 |
def get_test_examples_labels(dev_example_list, batch_size):
"""
:param dev_example_list: list of filenames containing dev examples
:param batch_size: int
:return: list of nlplingo dev examples, dev labels
"""
dev_chunk_generator = divide_chunks(dev_example_list, NUM_BIG_CHUNKS)
test_examples... | e46a3c1d9780c8b74fcef3311267ad87f5938a66 | 3,645,193 |
import uuid
import tokenize
from operator import getitem
from typing import Iterator
from typing import OrderedDict
def unpack_collections(*args, **kwargs):
"""Extract collections in preparation for compute/persist/etc...
Intended use is to find all collections in a set of (possibly nested)
python object... | d855a4cea5cb16a5863d670edb4bda6d15e2b371 | 3,645,194 |
def get_usernames(joomlasession):
"""Get list of usernames on the homepage."""
users = joomlasession.query(Jos_Users).all()
return [user.username for user in users] | b866cdd8fb47d12b7b79291f3335ded217fa8a1d | 3,645,195 |
def minor_block_encoder(block, include_transactions=False, extra_info=None):
"""Encode a block as JSON object.
:param block: a :class:`ethereum.block.Block`
:param include_transactions: if true transaction details are included, otherwise
only their hashes
:param extra_i... | 53b0eb26e7a8ef0c05f4149c71b09ff6505f85d0 | 3,645,196 |
def heaviside(x):
"""Implementation of the Heaviside step function (https://en.wikipedia.org/wiki/Heaviside_step_function)
Args:
x: Numpy-Array or single Scalar
Returns:
x with step values
"""
if x <= 0:
return 0
else:
return 1 | 5ef05263637501f82cea3befe897cd60ec39994d | 3,645,197 |
def FallbackReader(fname):
"""Guess the encoding of a file by brute force by trying one
encoding after the next until something succeeds.
@param fname: file path to read from
"""
txt = None
for enc in GetEncodings():
try:
handle = open(fname, 'rb')
reader = codec... | d9f4235df9f472c7584192e920980f5f2668202a | 3,645,198 |
def graph_3D(data, col="category", list_=[None], game=None, extents=None):
"""
3D t-sne graph data output
:param data: a pandas df generated from app_wrangling.call_boardgame_data()
:param col: string indicating which column (default 'category')
:param list_: list of elements in column (default [No... | 17ad05f2c7cc3413c145009fb72aed366ec9ab49 | 3,645,199 |
def get_selector(info, mode="advanced"):
"""
The selector that decides the scope of the dashboard. It MUST have the keywords
?work and ?author.
You can override everything here by adapting the query on WDQS:
https://w.wiki/3Cmd
Args:
info: either a dict containing complex information f... | c499a2b4e29a1afc91e6d40563a71ad5e71b7724 | 3,645,200 |
def get_table_names(self, connection, schema=None, **kw):
"""
Get table names
Args:
connection ():
schema ():
**kw:
Returns:
"""
return self._get_table_or_view_names(
["r", "e"], connection, schema, **kw
) | e66ae9eb284e10785c7172ab36c79b25a48dce47 | 3,645,201 |
def get_general(prefix, generator, pars, **kwargs):
""" A general getter function that either gets the asked-for data
from a file or generates it with the given generator function. """
pars = get_pars(pars, **kwargs)
id_pars, pars = get_id_pars_and_set_default_pars(pars)
try:
result = read_... | a27e25e0ec992f8faa13b167dafd38edd6eb6a1d | 3,645,202 |
def gen_case(test):
"""Generates an OK test case for a test
Args:
test (``Test``): OK test for this test case
Returns:
``dict``: the OK test case
"""
code_lines = str_to_doctest(test.input.split('\n'), [])
for i in range(len(code_lines) - 1):
if code_lines[i+1].sta... | 586a5436442172d43a022e33185bd84c302fdb9c | 3,645,203 |
def get_user_list_view(request):
"""
render user admin view
Arguments:
request {object} -- wsgi http request object
Returns:
html -- render html template
"""
if request.user.has_perm('auth.view_user'):
user_list = User.objects.all()
temp_name = 'admin/li... | f0ee280ac60a48f61f5da0d7d63b050e16ea6696 | 3,645,204 |
def to_odds(p):
"""
Converts a probability to odds
"""
with np.errstate(divide='ignore'):
return p / (1 - p) | b468b75ad736ca67e1fb39fd231bc185d851fbdf | 3,645,205 |
def step_euler(last, dt, drift, volatility, noise):
"""Approximate SDE in one time step with Euler scheme"""
return last + drift * dt + np.dot(volatility, noise) | e9f58425f696316679730397168c7965b3faadd5 | 3,645,206 |
def KK_RC66_fit(params, w, t_values):
"""
Kramers-Kronig Function: -RC-
Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com)
"""
Rs = params["Rs"]
R1 = params["R1"]
R2 = params["R2"]
R3 = params["R3"]
R4 = params["R4"]
R5 = params["R5"]
R6 = params["R6"]
... | eb64f86bc0a8a7ff0d88a1246a754563a955c61f | 3,645,207 |
from typing import List
def similar_in_manner(manner_1: UnmarkableManner) -> List[Manner]:
"""
If the value is a wildcard value, return
all possible manner of articualtion values, otherwise
return the single corresponding manner of articulation value.
"""
if isinstance(manner_1, MarkedManner):
return manner_1... | fea0c78c93a5f80e4f2bba6eac7f628106fba796 | 3,645,208 |
import re
def wikify(value):
"""Converts value to wikipedia "style" of URLS, removes non-word characters
and converts spaces to hyphens and leaves case of value.
"""
value = re.sub(r'[^\w\s-]', '', value).strip()
return re.sub(r'[-\s]+', '_', value) | dc4504ea6eb7905b5e18a1d1f473a4f337697b26 | 3,645,209 |
def build_model(name, num_classes, loss='softmax', pretrained=True,
use_gpu=True, dropout_prob=0.0, feature_dim=512, fpn=True, fpn_dim=256,
gap_as_conv=False, input_size=(256, 128), IN_first=False):
"""A function wrapper for building a model.
"""
avai_models = list(__model_fa... | 1278e5c30ebdb73e011b0630de3738936e87dc93 | 3,645,210 |
def policy_absent(name):
"""
Ensure that the named policy is not present
:param name: The name of the policy to be deleted
:returns: The result of the state execution
:rtype: dict
"""
current_policy = __salt__['mdl_vault.get_policy'](name)
ret = {'name': name,
'comment': '',
... | 6f1498f07a8e14f2e7668d7d5cc8d68128cb6004 | 3,645,211 |
def _tolist(arg):
"""
Assure that *arg* is a list, e.g. if string or None are given.
Parameters
----------
arg :
Argument to make list
Returns
-------
list
list(arg)
Examples
--------
>>> _tolist('string')
['string']
>>> _tolist([1,2,3])
[1, 2, ... | e4293991eeb6d15470511281680af44353232c37 | 3,645,212 |
def calc_Qhs_sys(bpr, tsd):
"""
it calculates final loads
"""
# GET SYSTEMS EFFICIENCIES
# GET SYSTEMS EFFICIENCIES
energy_source = bpr.supply['source_hs']
scale_technology = bpr.supply['scale_hs']
efficiency_average_year = bpr.supply['eff_hs']
if scale_technology == "BUILDING":
... | 6016e2061b441248606b5a3ea95930d38b678525 | 3,645,213 |
import socket
from time import time as now
def wait_net_service(server, port, timeout=None):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exce... | f8089ed335c783140ab4b334c44c534ee5c48121 | 3,645,214 |
import re
def latex_nucleus(nucleus):
"""Creates a isotope symbol string for processing by LaTeX.
Parameters
----------
nucleus : str
Of the form `'<mass><sym>'`, where `'<mass>'` is the nuceleus'
mass number and `'<sym>'` is its chemical symbol. I.e. for
lead-207, `nucleus` w... | e2a2c04a63284cdd8f06fdd556306149e7092703 | 3,645,215 |
def ConvertToFloat(line, colnam_list):
"""
Convert some columns (in colnam_list) to float, and round by 3 decimal.
:param line: a dictionary from DictReader.
:param colnam_list: float columns
:return: a new dictionary
"""
for name in colnam_list:
line[name] = round(float(line[name])... | e95fd6cfa9bb57060fdd835eea139fd9c67bc211 | 3,645,216 |
def rnn_step(x, prev_h, Wx, Wh, b):
"""
Run the forward pass for a single timestep of a vanilla RNN that uses a tanh
activation function.
The input data has dimension D, the hidden state has dimension H, and we use
a minibatch size of N.
Inputs:
- x: Input data for this timestep, of shape ... | 78fef10a4c23b7a33a60829e1ad02a2e0381b834 | 3,645,217 |
from typing import List
import json
def transform_application_assigned_users(json_app_data: str) -> List[str]:
"""
Transform application users data for graph consumption
:param json_app_data: raw json application data
:return: individual user id
"""
users: List[str] = []
app_data = json.l... | 625c8f662b364bb3fe63bb26b06eaca57ae8be79 | 3,645,218 |
def testapp(app):
"""Create Webtest app."""
return TestApp(app) | 68a46e993d75fc44de5a9063b409e89647a2738b | 3,645,219 |
def to_y_channel(img):
"""Change to Y channel of YCbCr.
Args:
img (ndarray): Images with range [0, 255].
Returns:
(ndarray): Images with range [0, 255] (float type) without round.
"""
img = img.astype(np.float32) / 255.
if img.ndim == 3 and img.shape[2] == 3:
img = bgr2... | 64873fabbe6cd12db8c9bc96e4e93f7181c7742d | 3,645,220 |
def get_user_signatures(user_id):
"""
Given a user ID, returns the user's signatures.
:param user_id: The user's ID.
:type user_id: string
:return: list of signature data for this user.
:rtype: [dict]
"""
user = get_user_instance()
try:
user.load(user_id)
except DoesNotE... | 8c099f84c9a9f383b56019f985f1be63e315503a | 3,645,221 |
import json
def post_vehicle_action():
""" Add vehicle
:return:
"""
output = JsonOutput()
try:
if not request.is_json:
raise TypeError('Payload is not json')
payload = request.json
usecases.SetVehicleUsecase(db=db, vehicle=payload).execute()
output.add(s... | a24b4e326fe12c7d2a7054ca4b89245924a96d60 | 3,645,222 |
def get_day_suffix(day):
"""
Returns the suffix of the day, such as in 1st, 2nd, ...
"""
if day in (1, 21, 31):
return 'st'
elif day in (2, 12, 22):
return 'nd'
elif day in (3, 23):
return 'rd'
else:
return 'th' | 7d9277303357de5405b3f6894cda24726d60ad47 | 3,645,223 |
def retain_images(image_dir,xml_file, annotation=''):
"""Deprecated"""
image_in_boxes_dict=return_image_in_boxes_dict(image_dir,xml_file, annotation)
return [img for img in image_in_boxes_dict if image_in_boxes_dict[img]] | 54efc8c8b3c31f8466a0044c2e679cbf5a5545ff | 3,645,224 |
from typing import List
from typing import Tuple
from typing import Dict
from pathlib import Path
from typing import cast
def compute_owa(
metrics: List[Tuple[float, float]],
datasets: Dict[K, DatasetSplit],
metadata: List[MetaData],
) -> float:
"""
Computes the OWA metric from the M4 competition,... | 2f4d19eecf85a9be720fb705eafe83c2ac1bced1 | 3,645,225 |
def parse(cell, config):
"""Extract connection info and result variable from SQL
Please don't add any more syntax requiring
special parsing.
Instead, add @arguments to SqlMagic.execute.
We're grandfathering the
connection string and `<<` operator in.
"""
result = {"connect... | 4711b5f873281db520ff4d91646412ca08f7cbb7 | 3,645,226 |
import requests
import json
def createResource(url, user, pWd, resourceName, resourceJson):
"""
create a new resource based on the provided JSON
returns rc=200 (valid) & other rc's from the put
resourceDef (json)
"""
# create a new resource
apiURL = url + "/access/1/catalog/resou... | 71257041a7bf098edd0668de6026539e554baff4 | 3,645,227 |
import string
def generate_invalid_sequence():
"""Generates an invalid sequence of length 10"""
return ''.join(np.random.choice(list(string.ascii_uppercase + string.digits), size=10)) | 33639bc0c97710c411b2bfd0033ed15200c8edff | 3,645,228 |
from input_surface import circle
def transform_bcs_profile(T, axis, Nc):
""" Translates the profile to body cs and then transforms it for rotation.
"""
profile = circle(Nc, radius = 1, flag = 0)
Pb_new = np.zeros((Nc, 3), dtype = float)
ind_p = np.arange(0, 3*Nc, step = 3, dtype = int)
p... | c3cacd480cba73c7a3ce1b6f5e90582fc93e2a4b | 3,645,229 |
def count_configuration(config, root=True, num_samples_per_dist=1):
"""Recursively count configuration."""
count = 1
if isinstance(config, dict):
for _, v in sorted(config.items()):
count *= count_configuration(
v, root=False, num_samples_per_dist=num_samples_per_dist)
elif callable(config):... | f7709bfd18744355f5739c4d0e4b52b952f6c8c7 | 3,645,230 |
def transition(state_table):
"""Decorator used to set up methods which cause transitions between states.
The decorator is applied to methods of the context (state machine) class.
Invoking the method may cause a transition to another state. To define
what the transitions are, the nextStates method of t... | 675a6afe6abd068027892be561c2d032d13be52a | 3,645,231 |
from typing import Union
def isfinite(x: Union[ivy.Array, ivy.NativeArray], f: ivy.Framework = None)\
-> Union[ivy.Array, ivy.NativeArray]:
"""
Tests each element x_i of the input array x to determine if finite (i.e., not NaN and not equal to positive
or negative infinity).
:param x: Input ar... | 7326343319dae8bb8681a9612caaaddfc947f8c1 | 3,645,232 |
from pathlib import Path
from typing import Optional
def form_overwrite_file(
PATH: Path, QUESTION: Optional[str] = None, DEFAULT_NO: bool = True
) -> bool:
"""Yes/no form to ask whether file should be overwritten if already existing."""
if QUESTION is None:
QUESTION = "Overwrite {PATH}?"
sav... | 51de7eb948af9e0b6cd354e8e72815e16955200c | 3,645,233 |
def dist(integer):
"""
Return the distance from center.
"""
if integer == 1:
return 0
c = which_layer(integer)
rows = layer_rows(c)
l = len(rows[0])
mid = (l / 2) - 1
for r in rows:
if integer in r:
list_pos = r.index(integer)
return c + abs(mid - list_pos) - 1 | 8fd27978058ac0d038836bd88dc2c7c590fec6b7 | 3,645,234 |
from datetime import datetime
def get_market_fundamental_by_ticker(date: str, market: str="KOSPI", prev=False) -> DataFrame:
"""특정 일자의 전종목 PER/PBR/배당수익률 조회
Args:
date (str ): 조회 일자 (YYMMDD)
market (str, optional): 조회 시장 (KOSPI/KOSDAQ/KONEX/ALL)
prev (bool, optional): 조회 일... | ac13ef09867b69f354b75f1e1bd98f46baf995fc | 3,645,235 |
def get_all(request):
""" Gets all tags in the db with counts of use """
tags = []
for tag in Tag.objects.all():
tag_data = {
'name': tag.name,
'count': tag.facebookimage_set.distinct().count()
}
if tag_data['count'] > 0:
tags.append(tag_... | bee0d6afd4ea8afeda0001d090cf0d9156249cce | 3,645,236 |
def quadratic_crop(x, bbox, alpha=1.0):
"""bbox is xmin, ymin, xmax, ymax"""
im_h, im_w = x.shape[:2]
bbox = np.array(bbox, dtype=np.float32)
bbox = np.clip(bbox, 0, max(im_h, im_w))
center = 0.5 * (bbox[0] + bbox[2]), 0.5 * (bbox[1] + bbox[3])
w = bbox[2] - bbox[0]
h = bbox[3] - bbox[1]
... | 53e9acf58cf743a89a4bfaafb9211abbbb9d57ec | 3,645,237 |
def cdlbreakaway(
client,
symbol,
timeframe="6m",
opencol="open",
highcol="high",
lowcol="low",
closecol="close",
):
"""This will return a dataframe of breakaway for the given symbol across
the given timeframe
Args:
client (pyEX.Client): Client
symbol (string): T... | c8bbc5adbbf742daabe39feaaa2dec01790297fe | 3,645,238 |
def depends_on(*args):
"""Caches a `Model` parameter based on its dependencies.
Example
-------
>>> @property
>>> @depends_on('x', 'y')
>>> def param(self):
>>> return self.x * self.y
Parameters
----------
args : list of str
List of parameters this parameter... | 09cdb0ad7601a953eafd01e3e19c0bdfb10dccb2 | 3,645,239 |
def l96(x, t, f):
""""This describes the derivative for the non-linear Lorenz 96 Model of arbitrary dimension n.
This will take the state vector x and return the equation for dxdt"""
# shift minus and plus indices
x_m_2 = np.concatenate([x[-2:], x[:-2]])
x_m_1 = np.concatenate([x[-1:], x[:-1]])
... | 0db03ed3a8923d18b50095852d17f9213e9f1f0f | 3,645,240 |
def translation(im0, im1, filter_pcorr=0, odds=1, constraints=None,
reports=None):
"""
Return translation vector to register images.
It tells how to translate the im1 to get im0.
Args:
im0 (2D numpy array): The first (template) image
im1 (2D numpy array): The second (sub... | 40e15b6154569d6bb13c7a38d595b603e9421d04 | 3,645,241 |
def CalculateConjointTriad(proteinsequence):
"""
Calculate the conjoint triad features from protein sequence.
Useage:
res = CalculateConjointTriad(protein)
Input: protein is a pure protein sequence.
Output is a dict form containing all 343 conjoint triad features.
"""
res = {}
pr... | 1ed73c1aa78c5360715eb71c9d56594d028cf6d3 | 3,645,242 |
def extract_url(url):
"""Creates a short version of the URL to work with. Also returns None if its not a valid adress.
Args:
url (str): The long version of the URL to shorten
Returns:
str: The short version of the URL
"""
if url.find("www.amazon.de") != -1:
index = ... | 85421799b601c89aa54fdce6e98c003ea80111eb | 3,645,244 |
import unicodedata
from typing import List
def match_name(own: str, other: str) -> bool:
"""
compares 2 medic names (respects missing middle names, or abbrev. name parts)
Args:
own: the first name
other: the last name
Returns: True if both names match
"""
# the simplest case,... | 6987deb8695f823cd5e1e0948bd2a21dc33759bd | 3,645,245 |
def price_setting():
""" Sets prices """
purchasing_price = float(input("enter purchasing price: "))
new_supplier = str(input("First time user(Y/N)?: ")).lower()
if new_supplier not in ['n', 'y']:
return True, {"errorMsg": f"{new_supplier} not a valid response"}, None
if new_supplier == 'y':... | 5d6b98b62ff7b6c8c3cc4278c3a4f2eb7c5f0f27 | 3,645,246 |
def d4_grid():
"""Test functionality of routing when D4 is specified.
The elevation field in this test looks like::
1 2 3 4 5 6 7
1 2 3 0 5 0 7
1 2 3 4 0 0 7
1 2 3 0 5 6 7
1 2 0 0 0 6 7
1 2 3 0 5 6 7
1 ... | ed285c91cc4cda270a469a0271d1b935f1043d32 | 3,645,247 |
import inspect
def pass_complex_ins(mqc):
"""
The number of PASS complex insertions.
Source: count_variants.py (bcftools view)
"""
k = inspect.currentframe().f_code.co_name
try:
d = next(iter(mqc["multiqc_npm_count_variants"].values()))
v = d["pass_complex_ins"]
v = i... | df7177b126829dca4a71252e797a2cb7d7d24ee3 | 3,645,248 |
def get_jwt():
"""
Get authorization token and validate its signature against the public key
from /.well-known/jwks endpoint
"""
expected_errors = {
KeyError: WRONG_PAYLOAD_STRUCTURE,
AssertionError: JWK_HOST_MISSING,
InvalidSignatureError: WRONG_KEY,
DecodeError: WR... | 92b757e3fa9774ac7e93fc0f89c446efefc47b33 | 3,645,249 |
def convert_categorical(df, col_old, conversion, col_new=None):
"""Convet categories"""
if col_new is None:
col_new = col_old
orig_values = df[col_old].values
good_rows = np.isin(orig_values, list(conversion))
df = df.iloc[good_rows]
orig_values = df[col_old].values
cat_values = np.z... | db07bb08f302edf615cab96b04b263f66fa9b8b1 | 3,645,251 |
def _get_pipeline_configs(force=False):
"""
Connects to Shotgun and retrieves information about all projects
and all pipeline configurations in Shotgun. Adds this to the disk cache.
If a cache already exists, this is used instead of talking to Shotgun.
To force a re-cache, set the force flag to Tru... | 3c504606e5a751e0015abbdcf74a3e2513d4d280 | 3,645,252 |
def info(parentwindow, message, buttons, *,
title=None, defaultbutton=None):
"""Display an information message."""
return _message('info', parentwindow, message, title, buttons,
defaultbutton) | 060e41cde2e83bdeab3fa3147caebabb3292923a | 3,645,254 |
def gru(xs, lengths, init_hidden, params):
"""RNN with GRU. Based on https://github.com/google/jax/pull/2298"""
def apply_fun_single(state, inputs):
i, x = inputs
inp_update = jnp.matmul(x, params["update_in"])
hidden_update = jnp.dot(state, params["update_weight"])
update_gate ... | 76c4ca1f90ba5cefc4227197d70c93c358d5f1d1 | 3,645,256 |
def get_strings_in_flattened_sequence(p):
"""
Traverses nested sequence and for each element, returns first string encountered
"""
if p is None:
return []
#
# string is returned as list of single string
#
if isinstance(p, path_str_type):
return [p]
#
# Get all... | 3de6829386d7877b745277cae88e3b3e6ac889a3 | 3,645,257 |
def kansuji2arabic(string, sep=False):
"""漢数字をアラビア数字に変換"""
def _transvalue(sj, re_obj=re_kunit, transdic=TRANSUNIT):
unit = 1
result = 0
for piece in reversed(re_obj.findall(sj)):
if piece in transdic:
if unit > 1:
result += unit
... | 4787618585baf660164d1c676ac7cae2750fe239 | 3,645,258 |
def get_image(member_status=None, most_recent=None, name=None, owner=None, properties=None, region=None, size_max=None, size_min=None, sort_direction=None, sort_key=None, tag=None, visibility=None):
"""
Use this data source to get the ID of an available OpenStack image.
"""
__args__ = dict()
__args... | 60fc60c558ac3c2e60fcdb73bf72a9d2bbc20855 | 3,645,259 |
def sort_course_dicts(courses):
""" Sorts course dictionaries
@courses: iterable object containing dictionaries representing courses.
Each course must have a course_number and abbreviation key
@return: returns a new list containing the given courses, in naturally sorted order.
"""
det... | f715cf1db4c77bd3412290bc870731e0d923871b | 3,645,260 |
import glob
import re
import numpy
def read_folder(filepath):
"""
Reads multiple image files from a folder and returns the resulting stack.
To find the images in the right order, a regex is used which will search
for files with the following pattern:
[prefix]_p[Nr][suffix]. The start number doesn'... | d50dc5ef09931b7950c91b5ea2f07eaa0d90cba1 | 3,645,261 |
from presqt.targets.zenodo.utilities.helpers.get_zenodo_children import zenodo_get_children
def zenodo_fetch_resource_helper(zenodo_project, resource_id, is_record=False, is_file=False):
"""
Takes a Zenodo deposition/record and builds a Zenodo PresQT resource.
Parameters
----------
zenodo_project... | 8427456ea648d1a5f4b5a0ee3baffc28649184aa | 3,645,262 |
import json
def add_role_menu(request):
"""菜单授权"""
menu_nums = request.POST.get("node_id_json")
role_id = request.POST.get("role_id")
role_obj = auth_db.Role.objects.get(id=role_id)
menu_nums = json.loads(menu_nums)
role_obj.menu.clear()
for i in menu_nums:
menu_obj = auth_db.M... | 31b8d2eb62ad105c4e44f6af7fa75cde2746d2f0 | 3,645,263 |
def oauth_url(auth_base, country, language):
"""Construct the URL for users to log in (in a browser) to start an
authenticated session.
"""
url = urljoin(auth_base, 'login/sign_in')
query = urlencode({
'country': country,
'language': language,
'svcCode': SVC_CODE,
'a... | d932d161ead93510e2a4b05c20f87982c726e158 | 3,645,265 |
def teammsg(self: Client, message: str) -> str:
"""Sends a team message."""
return self.run('teammsg', message) | 97a3a9c99af17fcf183d72158ec5dc9b5ad3689d | 3,645,266 |
def h_html_footnote(e, doc):
"""Handle footnotes with bigfoot"""
if not isinstance(e, pf.Note) or doc.format != "html":
return None
htmlref = rf'<sup id="fnref:{doc.footnotecounter}"><a href="#fn:{doc.footnotecounter}" rel="footnote">{doc.footnotecounter}</a></sup>'
htmlcontent_before = rf'<li c... | 462f4886cc7b4be46b3904abc3396096f36d7938 | 3,645,268 |
def segment(x,u1,u2):
""" given a figure x, create a new figure spanning the specified interval in the original figure
"""
if not (isgoodnum(u1) and isgoodnum(u2)) or close(u1,u2) or u1<0 or u2 < 0 or u1 > 1 or u2 > 1:
raise ValueError('bad parameter arguments passed to segment: '+str(u1)+', '+str(u... | 291ddfb011ece20840a4a56fdc7bc87f2187625f | 3,645,269 |
def box_from_anchor_and_target(anchors, regressed_targets):
"""
Get bounding box from anchor and target through transformation provided in the paper.
:param anchors: Nx4 anchor boxes
:param regressed_targets: Nx4 regression targets
:return:
"""
boxes_v = anchors[:, 2] * regressed_targets[:,... | c55a54535fbfa67502c1b65ec71c23d772dedd7e | 3,645,271 |
def block_device_mapping_update(context, bdm_id, values, legacy=True):
"""Update an entry of block device mapping."""
return IMPL.block_device_mapping_update(context, bdm_id, values, legacy) | 7959cc6c849cb599c719e21f8c8315a7bc7ddd09 | 3,645,272 |
def consumer(address,callback,message_type):
"""
Creates a consumer binding to the given address pull messages.
The callback is invoked for every reply received.
Args:
- address: the address to bind the PULL socket to.
- callback: the callback to invoke for every message. Mu... | a1c01bafa4f65ba0a0a212916556c36315fe2c88 | 3,645,273 |
def _parse_continuous_records(prepared_page, section_dict):
"""Handle parsing a continuous list of records."""
# import pdb; pdb.set_trace()
columns = 6
start = prepared_page.index('Date and time')
for i, column in enumerate(prepared_page[start:start + columns]):
column_index = start + i
... | 7ddcb52433828d37ce6e0cac5d51d8fcfb249296 | 3,645,274 |
def power_law_at_2500(x, amp, slope, z):
""" Power law model anchored at 2500 AA
This model is defined for a spectral dispersion axis in Angstroem.
:param x: Dispersion of the power law
:type x: np.ndarray
:param amp: Amplitude of the power law (at 2500 A)
:type amp: float
:param slope: Sl... | 508227f332f652d00c785074c20f9acefbce9258 | 3,645,275 |
def map2alm(
maps,
lmax=None,
mmax=None,
iter=3,
pol=True,
use_weights=False,
datapath=None,
gal_cut=0,
use_pixel_weights=False,
):
"""Computes the alm of a Healpix map. The input maps must all be
in ring ordering.
Parameters
----------
maps : array-like, shape (... | 9312a6c5ee40fe9a3ef3f6057ee5964d200f9732 | 3,645,276 |
def credits():
"""
Credits Page
"""
return render_template("credits.html") | 00fdc0be4c3abd3df21993b271977208252123df | 3,645,277 |
def register_view(request):
"""Register a new user."""
if request.method == "POST":
user_form = UserRegistrationForm(request.POST)
if user_form.is_valid():
# Create a new User object but don't save it yet.
new_user = user_form.save(commit=False)
# Set the chos... | 19fa639603c7ea67a76696e4b88aae376461988c | 3,645,278 |
def menu(request):
"""
A View to return the menu.html
where all menu images are returned
in a carousel.
"""
menus = MenuImages.objects.all()
context = {
'menus': menus
}
return render(request, 'menu/menu.html', context) | 9491d9e1d4084ed78d4aadfd867910e2d0511704 | 3,645,280 |
def wav_process(PATH, i):
"""
音频处理,在路径下读取指定序号的文件进行处理
Args:
PATH (str): 音频文件路径
i (int): 指定序号
Returns:
float: 计算得到的音源角度(单位:°)
"""
# 读取数据
wav, sr = read_wav(PATH, i + 1)
# 进行降噪
wav_rn = reduce_noise(wav)
# 计算角度
angle_list = estimate_angle(wav_rn, sr)
... | ee336928b4b5e221a72ba8b6509555666ff3b763 | 3,645,281 |
def extract_vuln_id(input_string):
"""
Function to extract a vulnerability ID from a message
"""
if 'fp' in input_string.lower():
wordlist = input_string.split()
vuln_id = wordlist[-1]
return vuln_id
else:
return None | 06673f2b401472185c8a3e6fc373d39c171791db | 3,645,282 |
def compare_images(img1, img2):
"""Expects strings of the locations of two images. Will return an integer representing their difference"""
with Image.open(img1) as img1, Image.open(img2) as img2:
# Calculate a difference image that is the difference between the two images.
diff = ImageChops.diff... | bc94987785a5731e71a1e25daae51179c415eda6 | 3,645,284 |
def bytes_to_nodes(buf):
""" Return a list of ReadNodes corresponding to the bytes in buf.
@param bytes buf: a bytes object
@rtype: list[ReadNode]
>>> bytes_to_nodes(bytes([0, 1, 0, 2]))
[ReadNode(0, 1, 0, 2)]
"""
lst = []
for i in range(0, len(buf), 4):
l_type = buf[i]
... | 1296b49f5d76605d4408eddf21b76f286dfc5f5b | 3,645,285 |
def list_unnecessary_loads(app_label=None):
"""
Scan the project directory tree for template files and process each and
every one of them.
:app_label: String; app label supplied by the user
:returns: None (outputs to the console)
"""
if app_label:
app = get_app(app_label)
else:... | d78aeb6132e4f79f4458454f6107f9003db37999 | 3,645,287 |
from typing import Any
def _element(
html_element: str,
html_class: str,
value: Any,
is_visible: bool,
**kwargs,
) -> dict:
"""
Template to return container with information for a <td></td> or <th></th> element.
"""
if "display_value" not in kwargs:
kwargs["display_value"] ... | 4ce4d2ff9f547470d4a875508c40d3ae2a927ba0 | 3,645,288 |
import torch
def lovasz_hinge_loss(pred, target, crop_masks, activation='relu', map2inf=False):
"""
Binary Lovasz hinge loss
pred: [P] Variable, logits at each prediction (between -\infty and +\infty)
target: [P] Tensor, binary ground truth labels (0 or 1)
"""
losses = []
for m, p, t i... | c1d7ce49feda1a2ba1116d03de3ba8a5b9ad65a9 | 3,645,290 |
def get_gene_summary(gene):
"""Gets gene summary from a model's gene."""
return {
gene.id: {
"name": gene.name,
"is_functional": gene.functional,
"reactions": [{rxn.id: rxn.name} for rxn in gene.reactions],
"annotation": gene.annotation,
"notes... | dd9cb3f8e9841a558898c67a16a02da1b39479d2 | 3,645,291 |
def prompt_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc')
"typ... | dc5f077d3710420b9d9b26032ee340c0671d009d | 3,645,292 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.