content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def concatenate_digits(a, b):
"""
Concatenate the digits of a and b
e.g. a=42, b=666 returns 42666
"""
return a * (10 ** num_digits(b)) + b | dd912bf0b567bcfcd4a6f15e908d037bed95bd5a | 3,625,577 |
def base64_decode_openflow(data):
"""Decode openflow message from base64 string to msg object"""
(msg, packet_length) = OFConnection.parse_of_packet(base64_decode(data))
return msg | 91337a570eb492e0a3ffe2b1a051994be43d3dc3 | 3,625,578 |
def impvol_table(data):
"""Implied volatility for structured data.
Parameters
----------
data : pandas DataFrame, record array, or dictionary of arrays
Mandatory labels: moneyness, maturity, premium, call
Returns
-------
array
Implied volatilities
Notes
-----
'... | 955b4e2cf6a924cc7bb1602c84bd68fdfca7b070 | 3,625,580 |
import json
def deserialize(payload: str) -> Model:
"""
:raises: ParsingError
"""
try:
raw_data = json.loads(payload)
except json.decoder.JSONDecodeError:
raise ParsingError
return Model.from_dict(raw_data) | 7d9a02522f4984094ed97e27be5d705653b19ea6 | 3,625,581 |
def toPSPmatrix(psp, N_neuron, index):
"""
推定したPSPの値からPSP matrix作る
indexをもとに、行列を作成する。
args:
psp: 推定結果のndarray
return:
psp_mat: PSP行列の2次元ndarray。行は結合先、列は結合元のニューロン番号を表す。
"""
# hintom diagramにする
psp_mat = np.zeros([N_neuron, N_neuron])
# 明示的にindexが与えられているのならば
assert... | 25d89a32d5c0162c380a6dcb6038eb828f843cda | 3,625,582 |
def repeat(a, n, axis, name='repeat'):
"""repeat a tensor along the axis.
For expamle:
a=[0, 1, 2, 3], n=2, axis=0
return [0, 0, 1, 1, 2, 2, 3, 3]
"""
with tf.name_scope(name):
ndim = len(a.shape)
if axis < 0:
axis += ndim
if axis < 0 or axis >= ndim:
... | ab90dcc2e92692407c73b7f3fc002807b840462d | 3,625,583 |
def get_syn_func_caller(func_name, domain_dim=None, fidel_dim=None,
noise_type='no_noise', noise_scale=None,
to_normalise_domain=True):
""" Returns a FunctionCaller object from the function name. """
func_name = func_name.lower()
funcs = ['hartmann', 'hartmann6', 'h... | c57f7d766292c0d28cfb16556217d6a12723378e | 3,625,584 |
from typing import Dict
def make_network_arc_consistent(csp: CSP, assignment: Dict[str, int]) -> bool:
"""Implementation of the AC-3 algorithm
Parameters
----------
csp : CSP
binary CSP constraint
assignment : [type]
current assignment of variables in CSP
Returns
-------
... | f7a78ad1acac7bf663019acc9570f97876234333 | 3,625,585 |
def cuda_if_gpu(T):
"""
Move tensor to GPU, if one is available.
:param T:
:return:
"""
return T.cuda() if use_cuda else T | 3faeec3afdcacd58991954649933510e3025b16f | 3,625,586 |
def convert_archive_posts(archive_posts):
"""Convert a list of SQL post rows to the format used for display within the post archive."""
converted_archive = [];
current_year = ""
current_month = ""
for post in archive_posts:
# If the posts created year is not the current year being parsed, ... | 1572d6105c4ed217f67021ebd7c9a3f1058a7617 | 3,625,587 |
def sigmoid(x):
"""
Compute the sigmoid of x
Arguments:
x -- A scalar or numpy array of any size
Return:
s -- sigmoid(x)
"""
s = 1 / (1 + np.exp(-x))
return s | ecba59afab22911bb2795cdc8059e63e49eebfc3 | 3,625,588 |
def stream_bytes(
data: ty.Union[bytes, gen_bytes_t], *, chunk_size: int = default_chunk_size
) -> ty.Tuple[gen_bytes_t, ty.Dict[str, str]]:
"""Gets a buffered generator for streaming binary data.
Returns a buffered generator which encodes binary data as
:mimetype:`multipart/form-data` with the corresponding head... | ab5ced446f8abd6ea59289785d2f56e5d3852b1a | 3,625,589 |
def VerifyType(owner, attr, value, template, callback):
"""Checks if an attribute has correct form.
@type owner: str
@param owner: name of the object containing the attribute
@type attr: str
@param attr: name of the attribute
@type value: dict
@param value: actual value of the attribute
@type template:... | 08fdd3e26104daad74b30fadb8535831e37c28ec | 3,625,590 |
def _get_search_text(keywords):
"""Get search text."""
search_text = ' '.join(['"{}"'.format(keyword) for keyword in keywords])
search_text = search_text.replace(':', ' ')
search_text = search_text.replace('=', ' ')
return search_text | cabb5d9ca5b5faf3d9287261aab0cd01df21a680 | 3,625,591 |
def _ExtractAddrs(header_value):
"""Given a message header value, return email address found there."""
friendly_addr_pairs = list(rfc822.AddressList(header_value))
return [addr for _friendly, addr in friendly_addr_pairs] | de717d17dd016b6e6f0d8c1b512225505e44f5a2 | 3,625,592 |
def readnext(x):
"""x is a list"""
if len(x) == 0:
return False
else:
return x.pop(0) | dd27ad3c8f750ef3e6df640fd710a0469b0839d0 | 3,625,593 |
import numpy
def ceil(x1, **kwargs):
"""
Compute the ceiling of the input, element-wise.
For full documentation refer to :obj:`numpy.ceil`.
Limitations
-----------
Parameter ``x1`` is supported as :obj:`dpnp.ndarray`.
Keyword arguments ``kwargs`` are currently unsupported.
... | 6b1260b79313f737f0c7eb1fe6bca433c9501557 | 3,625,594 |
def check_pq(pq):
"""Input validation for position and orientation quaternion.
Parameters
----------
pq : array-like, shape (7,)
Position and orientation quaternion: (x, y, z, qw, qx, qy, qz)
Returns
-------
pq : array, shape (7,)
Validated position and orientation quaterni... | 7b9d2be8c42fe514d2caa9a1fc97f753ed7c7df9 | 3,625,595 |
def elevate_nurbs_curve_degree(n, p, uk, cpw, t=1):
"""
Elevate the degree of a NURBS curve *t* times.
:param int n:
:param int p:
:param ndarray uk:
:param ndarray cpw:
:param int t:
:return: New number of control points - 1, new knot vector, and the new
control points of NURB... | 04c07ad0e10a0c3d954df9fbe9dcfdc565f1b6c5 | 3,625,596 |
async def async_setup(hass, config):
"""Platform setup, do nothing."""
return True | ece370c157b4c13098d80bd4b58b3ba17be86059 | 3,625,597 |
def coding_problem_19(house_costs):
"""
A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost
while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and
kth column represents the cost to ... | f9d8b33f449d7a2f87118be3e4d894988b781476 | 3,625,598 |
def create_account(data):
"""Creates a new account for a customer identified by customer_id"""
mandatory_params = ['customer_id', 'initial_deposit']
result = check_required_params(mandatory_params, data)
if result:
return result
customer = Customer.query.filter_by(id=data['customer_id']).fi... | 7a689ab614c4b0517e4e0f1da99e80d082d8816b | 3,625,599 |
import requests
def requests_get(url):
"""Make a get request using requests package.
Args:
url (str): url to do the request
Raises:
ConnectionError: If a RequestException occurred.
Returns:
response (str): the response from the get request
"""
try:
r = reque... | a438d211e6b5bf78af56783b5d22c85961a2d563 | 3,625,600 |
def get_mysensors_name(gateway, node_id, child_id):
"""Return a name for a node child."""
node_name = '{} {}'.format(
gateway.sensors[node_id].sketch_name, node_id)
node_name = next(
(node[CONF_NODE_NAME] for conf_id, node in gateway.nodes_config.items()
if node.get(CONF_NODE_NAME) ... | 67eca81ce4af653f603687048d2cc748400cd951 | 3,625,601 |
import math
def bloch_sunburst(vec, colormap):
"""Create a Bloch disc using a Plotly sunburst.
Parameters:
vec (ndarray): A vector of Bloch components.
colormap (Colormap): A matplotlib colormap.
Returns:
go.Figure: A Plotly figure instance,
Raises:
ValueError: Input... | fdfc47975ff11e8fcf871a9890da94ae4b87ad56 | 3,625,602 |
def link_models():
"""return settings or default"""
return getattr(project_settings, 'HTML_EDITOR_LINK_MODELS', ()) | abeb92515c4604fc9d301c7f70692c5b93b2ad73 | 3,625,603 |
def _join_dicts(*dicts):
"""
joins dictionaries together, while checking for key conflicts
"""
key_pool = set()
for _d in dicts:
new_keys = set(_d.keys())
a = key_pool.intersection(new_keys)
if key_pool.intersection(new_keys) != set():
assert False, "ERROR: dicts ... | 2dee7a6f6a89d310d6a58e35d14c57e8ddb5b804 | 3,625,604 |
def resolve(segments):
""" given the predicts of a segment from multiple files (as a pandas Series), return a new class (as a pandas Series) """
# strategy: weight each probability by the relative size of its area
# first calculate the relative size of each segment
segments['area'] = segments['area']/su... | b02708acb4a19ec59a3dc0f489e81b70fe53105c | 3,625,605 |
def getCandidates(fi, fo, sLang, dLang):
"""Check if a url could be a candidate or not."""
nCandidates = 0
for line in fi:
line = line.rstrip()
# tld url crawl<TAB>json_data
url = getURL(line)
url_components = normalize(url)
mapS = rulesOn(url, url_components, sLan... | 2b6c966f1ef38999de009d00fc26219c2c853417 | 3,625,606 |
def set_passphrase(module, **kwargs):
"""Adds or replace a LUKS passphrase in a give slot.
Return: <result> <error>"""
for req in ["device", "slot", "valid_passphrase", "new_passphrase"]:
if req not in kwargs:
return False, {"msg": "{0} is a required parameter".format(req)}
is_keyf... | 7eff574d565a7d3b93a3d607d8053b3bbe84dcc5 | 3,625,607 |
def run_train(config, data, inds):
"""
Sets splitter. Partitions train/val/test.
Loads model from config. Trains and evals.
Returns model and eval metrics.
"""
train_inds = inds["train_inds"]
val_inds = inds["val_inds"]
test_inds = inds["test_inds"]
model = keras_gcn(config)
los... | e0b96a3b64dc63ab94c7605198bfa8978d9f5d8b | 3,625,608 |
def cases_vs_deaths(df):
"""Checks that death count is no more than case count."""
return (df['deaths'] <= df['cases']).all() | 994ae93fb23090de50fc4069342487d0d8e621ed | 3,625,610 |
from typing import Optional
def retrieve_ledger_details_data(
token_address: str,
data_id: str,
issuer_address: Optional[str] = Header(None),
db: Session = Depends(db_session)):
"""Retrieve Ledger Details Data"""
# Validate Headers
validate_headers(issuer_address=(issuer_a... | 07eafff1e68124a5ce4836e4b1c413b161b442dd | 3,625,611 |
def sim1c_error(target_stats, cmr_stats):
"""
Sim 1c fits only the conditional SPCs and PFR, and uses mean squared error
instead of chi-squared error because standard errors are not available.
"""
y = []
y_hat = []
# Fit SPC and PFR
for stat in ('spc_fr1', 'spc_frl4', 'pfr'):
... | b52f592a9a31d16b622d25b1072b66a62007806f | 3,625,612 |
from datetime import datetime
def is_between(thing, start=None, end=None):
"""
given a thing with a date, returns true if the thing is between the start and end date
Parameters
----------
thing: dict
the thing that we want to know whether or not is after a date
start: datetime.date obje... | 6dc41a16a90d63f8f62a0c1a9a5ee57d2cacd562 | 3,625,613 |
import math
def CreateBoxOnStick(point1, point2, tipRatio=0.3):
"""
Creates an stick with a box as tip from point1 to point2.
Use tipRatio for setting the ratio for tip of the arrow.
"""
direction = map(lambda x, y: x - y, point2, point1)
length = math.sqrt(sum(map(lambda x: x ** 2, direction)))
unitDir = map... | c541d02f68e0d82811adab819943a1e7270743ff | 3,625,615 |
def _calcFiberLength(fiberData, fidx):
""" * INTERNAL FUNCTION *
Calculates the fiber length via arc length
INPUT:
fiberData - fiber tree containing tractography information
fidx - fiber index
OUTPUT:
L - fength of fiber
"""
no_of_pts = fiberData.pts_per_fiber
if n... | 7d0f97ca1b13333a710d5beac66593b4b963e5a7 | 3,625,617 |
def default_options(add_flags=True, flags=None):
"""Creates a DeepVariantOptions proto populated with reasonable defaults.
Args:
add_flags: bool. defaults to True. If True, we will push the value of
certain FLAGS into our options. If False, those option fields are left
uninitialized.
flags: obj... | 2370e1242c30dc1221876040222dde0a1fff027a | 3,625,619 |
def alert(title=None, message='', ok=None, cancel=None, other=None, icon_path=None):
"""Generate a simple alert window.
.. versionchanged:: 0.2.0
Providing a `cancel` string will set the button text rather than only using text "Cancel". `title` is no longer
a required parameter.
.. version... | fb81cffedca7e2a16a3412f743c5741254e95abf | 3,625,620 |
def _split_data(data, FEATURES, sort_keys=True, TEST_SIZE=TEST_SIZE, SEED=SEED, scale=False):
""" extracting features, split data """
data = featureFormat(data, FEATURES, sort_keys=sort_keys)
y, x = targetFeatureSplit(data)
if scale:
scaler = StandardScaler()
x = scaler.fit_transform(x)
... | 691f70c4b64f7a619bef64150e5bfedad5f35f53 | 3,625,622 |
def widget_url(widget, action='', prefix=None):
"""Returns the URL of the controller to perform `action` on `widget`.
If no `prefix` is passed the it will be tried to be fetched from
`tw.framework.request_local` where the :class:`WidgetBrowser` leaves it
on every request.
Example::
>>> fr... | 6bf49da76a4e483b47a587f2657b84b39ea74269 | 3,625,625 |
from typing import Dict
from typing import Any
from typing import Union
def build_transformer_block(
net_part: str,
block: Dict[str, Any],
pw_layer_type: str,
pw_activation_type: str,
) -> Union[EncoderLayer, TransformerDecoderLayer]:
"""Build function for transformer block.
Args:
net... | 8a6b8659f520b6c5caa9406e6611173ebca0383f | 3,625,626 |
def mondiode_value(fits_file, _, factor=5):
"""Compute the effective monitoring diode current by integrating
over the pd current time history in the AMP0_MEAS_TIMES extension
and dividing by the EXPTIME value.
"""
with fits.open(fits_file) as hdus:
x = hdus['AMP0.MEAS_TIMES'].data.field('AMP... | 4691418d8bf811662fb1c4552e52f9809d54fbd7 | 3,625,627 |
def get_loss_fn(loss_config, model):
"""Creates a loss function based on loss_config.
Args:
loss_config: (dict) loss config with following parameters:
- name: (str) name of the loss
- params: (dict) loss parameters if any
model: a model which its parameters might be used for defining
... | dbab26412353850ac0a8e404d2bcddb0cfad97c5 | 3,625,628 |
import re
def add_pronom_link_for_puids(text):
"""If text is a PUID, add a link to the PRONOM website"""
PUID_REGEX = r"fmt\/[0-9]+|x\-fmt\/[0-9]+" # regex to match fmt/# or x-fmt/#
if re.match(PUID_REGEX, text) is not None:
return '<a href="https://nationalarchives.gov.uk/PRONOM/{}" target="_bla... | 5fdc9c15895dfd75be54ad0258e66625462204a2 | 3,625,631 |
def delete_vit(request):
"""
Delete a vit with API
"""
user = KeyBackend().authenticate(request)
if request.method == "POST":
if request.user.is_authenticated:
try:
vit = Vit.objects.get(id=request.POST.get('vit_pk'))
if vit.user == request.user:
... | 0713a0d108745ff96fda083ae9e1413943e3a43a | 3,625,632 |
def convert(df_column):
"""
Converts a DataFrame column to list
"""
data_list = []
for element in df_column:
data_list.append(element)
return data_list | 6cd0f9b445573892612e01e0e3e25eb32d658be4 | 3,625,633 |
def get_model(embedding_matrix, name='baseline_model'):
"""
create model.
:return: model
"""
num_class = 4
inputs = tf.keras.layers.Input(shape=(config.MAX_SEQUENCE_LENGTH,))
embedding = tf.keras.layers.Embedding(embedding_matrix.shape[0], embedding_matrix.shape[1],
... | b388d7251a8bd1b5b87bc9c55fdabb795b0500e0 | 3,625,634 |
import requests
def _get_remote_svg_tile(hass, host, port, prefix, name, width_tiles, c1, c2):
"""Get remote SVG file."""
url_tile = URL_TILE_MASK.format(host, port, prefix, name, width_tiles)
ok, r_svg, status = False, None, -1
try:
r_svg = yield from hass.async_add_job(
partial(r... | af34d22684b71a49c7c71de59fbe8cff479b3220 | 3,625,635 |
def sub(a: PipeNumeric, b: PipeNumeric):
"""
Pipeline node which subtracts b from a.
Optimization is performed where possible.
The return type is int if both parameters were integer and so the result is static.
Otherwise a OneCycleNode is returned.
:param a: parameter a
:param b: parameter b... | 4d80ae6b2d62a865b567924f7acc1a6cc7dca490 | 3,625,636 |
from typing import Mapping
from typing import Any
import textwrap
def format_nested_dicts(value: Mapping[str, Mapping[str, Any]]) -> str:
"""
Format a mapping from string keys to sub-mappings.
"""
rows = []
if not value:
rows.append("(empty)")
else:
for outer_key, outer_value i... | 79d029a062f0e2545265ecdf5d8cdacb271c40c2 | 3,625,637 |
def MD5collect(signatures):
"""Deprecated. Use :func:`hash_collect` instead."""
_show_md5_warning("MD5collect")
return hash_collect(signatures) | 7124bbadfb3cea785463da15dadbc2fb4ac17c39 | 3,625,638 |
import profile
def adadelta(lr, tparams, grads, inp, cost, opt_ret=None, rho=0.99, eta=1e-7):
"""
Adadelta optimizer
:param lr:
:param tparams:
:param grads:
:param inp:
:param cost:
:param opt_ret:
:param rho: adadelta rho
:param eta: adadelta eta
:return f_grad_shared, f_... | be74e3d4f02c6a2249104a2312027f4d97dbf68d | 3,625,639 |
import random
def shuffle_string(s):
"""
Shuffle a string.
"""
if s is None:
return None
else:
return ''.join(random.sample(s, len(s))) | 25d109f11737b60cecf391fd955f2df4366de7e6 | 3,625,640 |
def dmp_zeros(n, u, K):
"""
Return a list of multivariate zeros.
Examples
========
>>> from sympy.polys.domains import ZZ
>>> from sympy.polys.densebasic import dmp_zeros
>>> dmp_zeros(3, 2, ZZ)
[[[[]]], [[[]]], [[[]]]]
>>> dmp_zeros(3, -1, ZZ)
[0, 0, 0]
"""
if not n:... | d6f33a2a40143c6ad4f379ab242e5960c3c79294 | 3,625,642 |
def to_ea(*args):
"""
to_ea(reg_cs, reg_ip) -> ea_t
Convert (seg,off) value to a linear address.
@param reg_cs (C++: sel_t)
@param reg_ip (C++: ea_t)
"""
return _ida_ida.to_ea(*args) | d7909944ff1852d0eb37416e67b54c8e673fbf7e | 3,625,643 |
from fileio.spec_load_write import async_rspec_scaled, rspecLoader
from fileio.utils import fns
from spectrum.utils import mutli_scale
from typing import Union
from typing import Iterable
from typing import Tuple
def get_chi_analysis_pipeline( primary_spectrum: Union[ Spectrum, str ], speclist: Iterable[ Union[ Spect... | ae504bdd9f3042cb2fac85cfdb2db1b2b95525fa | 3,625,644 |
from typing import List
from typing import Counter
def rank(words: List[str], exclude_stopwords: bool = False) -> Counter:
"""
Sort words by frequency
:param list words: a list of words
:param bool exclude_stopwords: exclude stopwords
:return: Counter
"""
if not words:
return None... | d80d2ea92e1aa19b0400041fd8a49576d8e91b9f | 3,625,645 |
def get_restaurant(request):
"""
通过openid获取餐厅信息
"""
openid = request.GET.get('openid', None)
try:
restaurant = Restaurant.objects.get(openid=openid)
except Restaurant.DoesNotExist:
return Response('restaurant not found', status=status.HTTP_404_NOT_FOUND)
serializer = Restaur... | ad00c7bc0cd273b4e93b5d22e12d798600542f4d | 3,625,646 |
def level_info():
"""Returns True if info logging is turned on."""
return get_verbosity() >= INFO | 895dd82b221c0cd4514c77005968d48e53dad78f | 3,625,647 |
def _get_low_and_high_version_from_range(version_range):
"""
Parse a version range into its low and high components.
:param version_range: the version range
:return: the low and high version components, an empty string is returned if there is no upper bound
"""
_method_name = '_get_low_and_high_... | 7d8e82b784a2bfc0c2d51997378a769fdb8d1a36 | 3,625,648 |
def get_rule_full_description(tool_name, rule_id, test_name, issue_dict):
"""
Constructs a full description for the rule
:param tool_name:
:param rule_id:
:param test_name:
:param issue_dict:
:return:
"""
issue_text = issue_dict.get("issue_text", "")
# Extract just the first lin... | 546dcb5ce2cbc22db652b3df2bf95f07118611cf | 3,625,649 |
def generate_config(context):
""" Entry point for the deployment resources. """
resources, outputs = create_dashboard_resource(context)
return {"resources": resources, "outputs": outputs} | ef89fabe24fc63079cec06a186dc46b31ef5fc07 | 3,625,650 |
import tqdm
def index_embedding_words(embedding_file):
"""Put all the words in embedding_file into a set."""
words = set()
with open(embedding_file) as f:
for line in tqdm(f, total=count_file_lines(embedding_file)):
w = Vocabulary.normalize(line.rstrip().split(' ')[0])
word... | 7a1378698bad45a8ba7ffff99f9e316aeb9d5b9c | 3,625,651 |
def dst():
"""Simple spatial graph nodes where all but one have been translated"""
dst = np.array([[0,0],
[1,0.1],
[0,1.1],
[1,1.1]])
return dst | 488d54abb891133a67d7ff0281a99dd6468c50ef | 3,625,652 |
import itertools
def check_length(seed, random, query_words, key_max):
"""
Google limits searches to 32 words, so we need to make sure we won't be generating anything longer
Need to consider
- number of words in seed
- number of words in random phrase
- number of words in the lists from the qu... | 14871b468454f324223673a0c57941ea9e63341a | 3,625,653 |
def warp_from_camera_motion(R0, t0, R1, t1, normal, distance, K1, K0_inv=None):
"""
R0, t0: source camera pose in object frame.
R1, t1: target camera pose in object frame.
normal, distance: normal and distance of object's principal plane (in object frame.)
K1: target camera's intrinsics
K0_... | 5897af5241318a943e97477dc9dfa87b240c0b8e | 3,625,654 |
def sind(x):
"""Trigonometric sine using :func:`np.sin <numpy.sin>`, element-wise with an input in degree.
Parameters
----------
x : array_like
Input array in degree.
Returns
-------
y : array_like
The corresponding tangent values. This is a scalar if x is a scalar.
""... | 010976eb7f25370c26ee0e4a4ff19828629ba68b | 3,625,656 |
import logging
def _stretch_intensity(image, smoothing_sigma=2.0):
"""Stretches the intensity range of the image to (0, 255)."""
output = image * 1
blurred = (gaussian(output, sigma=smoothing_sigma) * 255).astype('uint8')
i_max = blurred.max()
i_min = blurred.min()
logging.info('Stretching i... | ae129cb3fd2df883fb2b6f50a1016898dc137767 | 3,625,657 |
def is_string(val):
"""
Is the supplied value a string or unicode string?
See: https://stackoverflow.com/a/33699705/324122
"""
return isinstance(val, (str, u"".__class__)) | 99b082ec080f261a7485a4e8e608b7350997cf18 | 3,625,658 |
def inner_join(table_left, table_right, column):
"""
Inner join. If columns are repeated, the left table has preference.
:param table_left:
:param table_right:
:param column:
:return:
"""
if column not in table_left.keys:
raise ValueError('{} not in left table'.format(column))
... | c8ec19cc4da9bdb43091fe1867f040ac82f76104 | 3,625,659 |
from datetime import datetime
def time_string():
"""
Generate a string of numbers generated from now time (UTC).
"""
# UTC time up to microseconds
time_str = datetime.utcnow().strftime("%Y%m%d%H%M%S")
return time_str | c7258004db459563a1d229119b6148584cc72584 | 3,625,660 |
def colorvsn1(studydata, column, context):
"""Please convert numeric codes of 0 and 99 to the text strings they represent."""
return column.mask(column == 0, 'No').mask(column > 90, "Don't Know") | 3f05a3a78d1368e6116fa52366079c22dd183bc3 | 3,625,661 |
from typing import Any
from typing import Dict
from typing import Union
from typing import List
def flatten_omegaconf(cfg: Any) -> Dict[Any, Any]:
"""Recursively flatten a nested Dict into a simple one.
The difference between this function and `recurse` is that the dictionnary produced
by this one doesn'... | 2b5a6e4ec57b3949079aa836f74a15c0a45b608d | 3,625,662 |
def reports(request, report, casetype='Call'):
"""Handle report rendering"""
query = request.GET.get('q', '')
datetime_range = request.GET.get("datetime_range")
agent = request.GET.get("agent")
category = request.GET.get("category", "")
form = ReportFilterForm(request.GET)
dashboard_stats = ... | 9406a8421c8eb1047446e986d9ee297f41e7132c | 3,625,663 |
def score(hand):
"""
Compute the maximal score for a Yahtzee hand according to the
upper section of the Yahtzee score card.
hand: full yahtzee hand
Returns an integer score
"""
max_score = 0
sorted_hand_list = sorted(list(set(hand)))
for i_mem in sorted_hand_list:
temp_sco... | b1fae3c67793a96b040f8abae41514bef2c5b89c | 3,625,664 |
from typing import Dict
from typing import Union
def mismatched_units_matching_numbers_of_integer_digits(
digits: int, num_trials: int
) -> Dict[str, Union[str, float]]:
"""The hardest subtask. The input units and output units can all differ.
The number of digits supplied to both inputs is the same.
"""... | b85ad67ee2c01b12f1fbf39460d40cc56a638826 | 3,625,665 |
def context_get(stack, name):
"""
Find and return a name from a ContextStack instance.
"""
return stack.get(name) | a5a9a50c54e8f0f685e0cf21991e5c71aee0c3d6 | 3,625,666 |
def get_first_published_date(organization):
"""
Get first publisher date from an organization. Check if the date is invalid, get the date
:param organization:
:return:
"""
_invalid_dates = ('No data published', 'Date not found', 'Date is not valid')
# Check if publisher date already exists.... | 8b1b39352d7aa72c37599656abff4027dc716c56 | 3,625,667 |
from typing import Optional
def determine_redemption_annuity(
months_to_legal_maturity: int,
outstanding_balance: float,
interest_rate: float,
annuity: Optional[float] = None,
) -> float:
"""Calculate the redemption of an annuity mortgage.
On basis of the outstanding_balance at the start ... | 61dceb3d550bf58085a627fe6892ba372d05d433 | 3,625,669 |
def getversion(online=True):
"""Return a pywikibot version string.
@param online: (optional) Include information obtained online
"""
data = dict(getversiondict()) # copy dict to prevent changes in 'cache'
data['cmp_ver'] = 'n/a'
if online:
try:
hsh3 = getversion_onlinerepo... | 07c7b6e721b342bd7b5695e6be7a3cc9e49ad6c9 | 3,625,671 |
def euclidean_distance(X1, X2):
"""
Function to compute the euclidean distance between two vectors
:param X1: Vector 1
:param X2: Vector 2
:return: Scalar euclidean distance between X1 and X2
"""
return np.sqrt(np.sum(np.square(X1 - X2), axis=1)) | 738b1cf9811319a2f995fe2790d08eae6cedc138 | 3,625,672 |
import json
async def get_exchanges_for_market(symbol, collections_dir='./'):
"""
Returns the list of exchanges on which a market is traded
"""
try:
with open('{}collections.json'.format(collections_dir)) as f:
collections = json.load(f)
for market_name, exchanges in collec... | 30138efa8f77b3c5f36c90bdcf82c8e79d43bf44 | 3,625,673 |
def projectNodePosOnly(pt, upVec, p0, v1, v2):
"""
Project a point pt onto a triagnulated surface and the solution
that is the closest in the positive direction (as defined by
upVec).
pt: The initial point
upVec: The vector pointing in the search direction
p0: A numpy array of triangle orig... | 97099b485b4125a476105f654214044fd1f0a090 | 3,625,675 |
import time
import csv
import base64
def load_obj_tsv(fname, topk=None, hide_images=False):
"""Load object features from tsv file.
:param fname: The path to the tsv file.
:param topk: Only load features for top K images (lines) in the tsv file.
Will load all the features if topk is either -1 or N... | af21bae644dac06a8458899fa562082bd43b2641 | 3,625,676 |
from typing import Counter
from typing import Pattern
def extract_patterns(df):
"""
Extracts the unique patterns of contestation in an electoral system. Mimicks Linzer 2012's `findpatterns` R function.
Arguments
----------
df : data frame
dataframe containing vote values
... | 6c45dcfe9db2fe708b59656fdbce2233788692df | 3,625,678 |
import uuid
import json
def group_api(request):
"""
状态码说明:
200:成功
60001: 数据库操作异常
60002:etcd推送异常
60003: 不支持的请求
接口返回结果示例:{resultCode:200,data:response,info:u'成功'}
"""
"""
创建组接口
"""
if not request.user.has_perm('home_application.can_add_groups'):
return ... | 9a95a1a2c2dc5e75e150b91211f48d826e8dc696 | 3,625,679 |
def tree_names (tree):
"""Get the top-level names in a tree (including files and directories)."""
return [x[0] for x in list(tree.keys()) + tree[None] if x is not None] | 12a5522974671f3ab81f3a1ee8e8c4db77785bd3 | 3,625,680 |
def update_information_first(update=False):
"""
Decorator to wrap :class:`Information <ansys.mapdl.core.misc.Information>`
methods to force update the fields when accessed.
Parameters
----------
update : bool, optional
If ``True``, the class information is updated by calling ``/STATUS``... | a25c3c9aab10ce78bcc78819069fbd071ca5bbb2 | 3,625,681 |
def find_key(key: str, up: any):
"""根据key提取Value"""
if dict == type(up):
if key in up:
return up[key]
else:
for dict_key, dict_value in up.items():
if dict == type(dict_value) or list == type(dict_value):
result = find_key(key, dict_val... | d0a92bdb99d3c3fd3255aa1bbc68249114302a26 | 3,625,682 |
def main():
"""
适合存在可能影响最大最小值的异常点的大量数据
归一化处理异常值偏差较大的情况时容易出问题, 需要使用标准化
标准化将原始数据处理到均值为0, 标准差为1的范围
x_final = (x - avg) / sigma
也即是, (x - 该列平均值) / 标准差
标准差的计算为:
1. 计算平均值 avg
2. 计算方差, 即该列所有值 (x1 - avg)^2 + (x2 - avg)^2 + (x3 - avg)^2 + ... + (xn - avg)^2 / (n - 1)
3. 方差开方的结果即是标准差 sigma... | 06f5d2171c413d0d3a18375fa4d4074239263cd5 | 3,625,683 |
def get_class_names(file_meta, aspect_table):
"""
Creates and looks up names for classification, i.e. classifications that are not found in the database (custom)
will be generated and existing ones (non-custom) looked up in the classification_definitions table.
The name is generated as a combination of ... | 372613500cf6bda23b06fb983b6f52eeae02a4fd | 3,625,684 |
from typing import Any
def get_attrs(expr: relay.expr.Expr) -> Any:
"""Get the attributes from an expression."""
if isinstance(expr, Call):
return expr.attrs
if isinstance(expr, TupleGetItem):
return get_attrs(expr.tuple_value)
return {} | 377cf7f40943e35605543f145646f36a7334abc6 | 3,625,685 |
def clastic_decorator(subdecorator):
"""
If a decorator needs to accept *args and/or **kwargs,
this function makes that possible by precomputing the
argspec of the to-be-wrapped function and propagating
it to the decorated version, where it is available to
clastic for computing dependencies.
... | 33c55effa6a0053bb976de49281c54353ee77b4d | 3,625,686 |
def fixed_width_repr_of_int(value, width, pad_left=True):
"""
Format the given integer and ensure the result string is of the given
width. The string will be padded space on the left if the number is
small or replaced as a string of asterisks if the number is too big.
:param int value: An inte... | adb212746dd081112ec1de2c4ea8745d2601c055 | 3,625,688 |
def _getCompiledName(fldName, clsName):
"""Return mangled fldName if necessary, else no change."""
# If fldName starts with 2 underscores and does *not* end with 2 underscores...
if fldName[:2] == '__' and fldName[-2:] != '__':
return "_%s%s" % (clsName, fldName)
else:
return fldName | 91285b7c54e001d807850c66ac74521e55d05ca4 | 3,625,689 |
def backward_subd(U, y, pr):
"""Given a lower triangular matrix U and right-side vector y,
compute the solution vector x solving Ux = y."""
# x = zerod(len(y))
x = [De(0.0) for ix in y]
for i in range(len(x), 0, -1):
val_i = (y[i-1] - dot(U[i-1][i:], x[i:])) / U[i-1][i-1]
aa = '{}:.{... | 8308c2d406c5ceb56b1b5970ac0b993f75c24874 | 3,625,691 |
from typing import Dict
from typing import List
def get_recoverable_databases(credentials: Credentials, subscription_id: str, server: Dict) -> List[Dict]:
"""
Returns details of the Recoverable databases in a server.
"""
try:
client = get_client(credentials, subscription_id)
recoverabl... | 7b3ee0011089cce4d4e5c763d63798c38984cd1e | 3,625,692 |
async def async_get_service(hass, config, discovery_info=None):
"""Get the Tibber notification service."""
tibber_connection = hass.data[TIBBER_DOMAIN]
return TibberNotificationService(tibber_connection.send_notification) | c8f98df6b1a9a832b139c187d99aab4f03d1d9e5 | 3,625,693 |
def get_project(datasource):
"""Get the project info from given datasource
Args:
datasource: The odps url to extract project
"""
_, _, _, project = MaxComputeConnection.get_uri_parts(datasource)
return project | 2a4dc6412a0e942a1d690912efc09993eaeac147 | 3,625,694 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.