content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def stopping_player(bot, state):
""" A Player that just stands still. """
return bot.position | 72628e39d26760eedc9a0e85a8279ac530ab851d | 24,461 |
def check_continue(transformer: transformer_class.Transformer, check_md: dict, transformer_md: dict, full_md: dict) -> tuple:
"""Checks if conditions are right for continuing processing
Arguments:
transformer: instance of transformer class
Return:
Returns a tuple containining the return code... | 78348046acde489a129fc8a4426a9b11ee2e2238 | 24,462 |
def getFlatten(listToFlat):
"""
:param listToFlat: anything ,preferably list of strings
:return: flatten list (list of strings)
#sacred
"""
preSelect=mc.ls(sl=True,fl=True)
mc.select(cl=1)
mc.select(listToFlat)
flatten = mc.ls(sl=True, fl=True)
mc.select(preSelect)
return... | 91d1376d81140fd258c80bcc23cb220ce0f99926 | 24,463 |
def can_exit_room(state: State, slot: int) -> bool:
"""
Return True if amphipod can escape a room because all amphipods are in their place
Not exhaustive! If there are amphipods above it, it may still be stuck
"""
amphipod = state[slot]
assert amphipod != EMPTY_SLOT
room = slot // 4
bott... | 914881e90c2e9b357d49fb44d56b7f864b4973c0 | 24,464 |
def square_matrix(square):
"""
This function will calculate the value x
(i.e blurred pixel value) for each 3*3 blur image.
"""
tot_sum = 0
# Calculate sum of all teh pixels in a 3*3 matrix
for i in range(3):
for j in range(3):
tot_sum += square[i][j]
return tot_sum/... | 4f378736c19c33f104be462939b834ece403f713 | 24,465 |
def before_after_text(join_set, index, interval_list):
"""
Extracts any preceeding or following markup to be joined to an interval's text.
"""
before_text, after_text = '', ''
# Checking if we have some preceeding or following markup to join with.
if join_set:
if index > 0:
... | b2c63fe1e7ea5bb204e41b27bc79d2c81964369a | 24,466 |
import socket
import ssl
def create_server_ssl(addr, port, backlog):
"""
"""
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((addr, port))
server.listen(backlog)
context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
context.load_default_certs()
wrap = context.wrap_... | 3bcd3d8a157401f23c50e6c35fe9b8e45f4659d6 | 24,468 |
def other_ops(request):
"""
Other Operations View
"""
args = {
'pending': OtherOperation.objects.filter(status=0).count(),
'active': OtherOperation.objects.filter(status=1).count(),
'done': OtherOperation.objects.filter(status=2).count(),
'cancelled': OtherOperation.objec... | 727e620d0ba5798eb0bcdc31e31a831a9332e802 | 24,469 |
def distance_point_2_line(point, seg):
"""Finds the minimum distance and closest point between a point and a line
Args:
point ([float, float]): (x,y) point to test
seg ([[float, float], [float, float]]): two points defining the line
Returns:
A list of two items:
* Distance ... | 4627639f4b900b72a0b88104df44e498ef123cb4 | 24,470 |
def load_glove_from_file(glove_filepath):
"""
Load the GloVe embeddings
Args:
glove_filepath (str): path to the glove embeddings file
Returns:
word_to_index (dict), embeddings (numpy.ndarary)
"""
word_to_index = {}
embeddings = []
with open(glove_filepath, "r") as fp:
... | 30d8a0fb8e1b0728ae9943dd0f5c2387dbcdb778 | 24,471 |
def make_pd(space: gym.Space):
"""Create `ProbabilityDistribution` from gym.Space"""
if isinstance(space, gym.spaces.Discrete):
return CategoricalPd(space.n)
elif isinstance(space, gym.spaces.Box):
assert len(space.shape) == 1
return DiagGaussianPd(space.shape[0])
elif isinstance... | 0849e947061221ba08bf113f6576c531ca2df2cd | 24,472 |
import typing
import requests
def download_file_from_google_drive(
gdrive_file_id: typing.AnyStr,
destination: typing.AnyStr,
chunk_size: int = 32768
) -> typing.AnyStr:
"""
Downloads a file from google drive, bypassing the confirmation prompt.
Args:
gdrive_file_id: ID str... | 29cdcc509aa21a6f2ae14ed18f2c0523bbdbd5a4 | 24,473 |
import inspect
import functools
def attach(func, params):
"""
Given a function and a namespace of possible parameters,
bind any params matching the signature of the function
to that function.
"""
sig = inspect.signature(func)
params = Projection(sig.parameters.keys(), params)
return functools.partial(func, **... | 35116b9b3be12f1e19789e2b1c36b7c34b6138ea | 24,474 |
def question_route():
"""
題庫畫面
"""
# 取得使用者物件
useruid = current_user.get_id()
# 嘗試保持登入狀態
if not keep_active(useruid):
logout_user()
return question_page(useruid) | 1b752709aa8264fdc19aaa44f2233b2e0382e1b5 | 24,475 |
import base64
def generate_qrcode(url: str, should_cache: bool = True) -> str:
"""
Generate a QR code (as data URI) to a given URL.
:param url: the url the QR code should reference
:param should_cache: whether or not the QR code should be cached
:return: a data URI to a base64 encoded SVG image
... | ab89cf09d7d50217960f48f75ff17b1d46513f52 | 24,476 |
def hz2mel(f):
"""Convert an array of frequency in Hz into mel."""
return 1127.01048 * np.log(f/700 +1) | 84522419c972bf9b78c9931aef871f97a8a0d292 | 24,478 |
def figure(figsize=None, logo="iem", title=None, subtitle=None, **kwargs):
"""Return an opinionated matplotlib figure.
Parameters:
figsize (width, height): in inches for the figure, defaults to something
good for twitter.
dpi (int): dots per inch
logo (str): Currently, 'iem', 'dep' is... | fd89e550a891ccf6f639f8c981215aa25fa0ad06 | 24,479 |
def run_epoch(session, model, eval_op=None, verbose=False):
"""Runs the model on the given data."""
costs = 0.0
iters = 0
state = session.run(model.initial_state)
fetches = {
"cost": model.cost,
"final_state": model.final_state,
"accuracy":model.accuracy,
"y_new":mo... | a69ed33e930245118e0d4054a10d6c1fd61cc0da | 24,480 |
from typing import Any
def is_scoo(x: Any) -> bool:
"""check if an object is an `SCoo` (a SAX sparse S-matrix representation in COO-format)"""
return isinstance(x, (tuple, list)) and len(x) == 4 | 96d3937d9884198b75440e3de75949c713b8e16a | 24,481 |
def project_rename_folder(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /project-xxxx/renameFolder API method.
For more info, see: https://documentation.dnanexus.com/developer/api/data-containers/folders-and-deletion#api-method-class-xxxx-renamefolder
"""
return DXHTTPR... | 60bfe648eb9846bf06125fd65436e9c7cf5c2fd6 | 24,483 |
def is_seq(a):
"""Return `True` if `a` is a Z3 sequence expression.
>>> print (is_seq(Unit(IntVal(0))))
True
>>> print (is_seq(StringVal("abc")))
True
"""
return isinstance(a, SeqRef) | 1429fb3fd800a3688700a62dd0665df7536b56d9 | 24,485 |
from re import T
def identity(__obj: T, /) -> T:
"""Identity function"""
return __obj | 8c96839e48e1ec270bd57616abcc3234b6f0958f | 24,486 |
def lines_in_file(filename: str) -> int:
"""
Count the number of lines in a file
:param filename: A string containing the relative or absolute path to a file
:returns: The number of lines in the file
"""
with open(filename, "r") as f:
return len(f.readlines()) | d71b5c8de1b4eb9a45988e06c17a129f4a19f221 | 24,487 |
import click
def validate_input_parameters(live_parameters, original_parameters):
"""Return validated input parameters."""
parsed_input_parameters = dict(live_parameters)
for parameter in parsed_input_parameters.keys():
if parameter not in original_parameters:
click.echo(
... | 226b95d0d9b42e586e395107def239d4e61c057a | 24,489 |
def _upper_zero_group(match: ty.Match, /) -> str:
"""
Поднимает все символы в верхний
регистр у captured-группы `let`. Используется
для конвертации snake_case в camelCase.
Arguments:
match: Регекс-группа, полученная в результате `re.sub`
Returns:
Ту же букву из группы, но в верхн... | 311dbc41c17b1c6fde39b30d8126eb4c867d7a6f | 24,490 |
def _concatenate_shapes(shapes, axis):
"""Given array shapes, return the resulting shape and slices prefixes.
These help in nested concatenation.
Returns
-------
shape: tuple of int
This tuple satisfies:
```
shape, _ = _concatenate_shapes([arr.shape for shape in arrs], axis)... | 2ca93f3c656f1629fa3fdb7f5c8cb325abd40cf2 | 24,491 |
import re
def md_changes(seq, md_tag):
"""Recreates the reference sequence of a given alignment to the extent that the
MD tag can represent.
Note:
Used in conjunction with `cigar_changes` to recreate the
complete reference sequence
Args:
seq (str): aligned segment sequence
... | f8591d0084f6c10c9bbd1a39b3f9e13cfe952e68 | 24,492 |
def get_cs_token(accesskey="",secretkey="",identity_url="",tenant_id=""):
"""
Pass our accesskey and secretkey to keystone for tokenization.
"""
identity_request_json = json.dumps({
'auth' : {
'apiAccessKeyCredentials' : {
'accessKey' : accesskey,
'secretKey' : secretkey
},
"tenantId": tenant_i... | a14324651039687bb52e47f4068fcee74c34aa65 | 24,494 |
def get_auto_scaling_group(asg, asg_name: str):
"""Get boto3 Auto Scaling Group by name or raise exception"""
result = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name])
groups = result["AutoScalingGroups"]
if not groups:
raise Exception("Auto Scaling Group {} not found".format(a... | 07176e538cdb265ae86b16a5d36bf1b274f45c19 | 24,495 |
def guiraud_r(txt_len: int, vocab_size: int) -> np.float64:
"""
The TTR formula underwent simple corrections: RTTR (root type-token ratio), Guiraud, 1960.
"""
return vocab_size / np.sqrt(txt_len) | 9c054d6d741fabb64ec0659b280474385b5cfa79 | 24,496 |
def serialize_dagster_namedtuple(nt: tuple, **json_kwargs) -> str:
"""Serialize a whitelisted named tuple to a json encoded string"""
check.tuple_param(nt, "nt")
return _serialize_dagster_namedtuple(nt, whitelist_map=_WHITELIST_MAP, **json_kwargs) | fbe6606d0001d425593c0f4f880a6b314f69b94b | 24,497 |
def join_epiweek(year, week):
""" return an epiweek from the (year, week) pair """
return year * 100 + week | fdbc50f8a953ef7307e9558019b3c2b50bc65be4 | 24,498 |
def get_or_create_api_key(datastore: data_store.DataStore,
project_id: str) -> str:
"""Return API key of existing project or create a new project and API key.
If the project exists, return its API key, otherwise create a new project
with the provided project ID and return its API key.
... | 2cb5b04dcf44b0e39d171683a0bd184d582eaf34 | 24,499 |
def map_cosh(process):
"""
"""
return map_default(process, 'cosh', 'apply') | fe853e23f8008bc5e767ef5af8b4efc6a04de407 | 24,500 |
def cleanline(line):
"""去除讀入資料中的換行符與 ',' 結尾
"""
line = line.strip('\n')
line = line.strip(',')
return line | a4149663e2c3966c5d9be22f4aa009109e4a67ca | 24,502 |
from onnx.helper import make_node
import logging
def convert_contrib_box_nms(node, **kwargs):
"""Map MXNet's _contrib_box_nms operator to ONNX
"""
name, input_nodes, attrs = get_inputs(node, kwargs)
input_dtypes = get_input_dtypes(node, kwargs)
dtype = input_dtypes[0]
#dtype_t = onnx.mapping.... | 22bc975bc35ebe8e50f4749f981859460f695596 | 24,503 |
def fill76(text):
"""Any text. Wraps the text to fit in 76 columns."""
return fill(text, 76) | 953ed87d8cfbee7a10c752082783469e866e8540 | 24,504 |
def current_object(cursor_offset, line):
"""If in attribute completion, the object on which attribute should be
looked up."""
match = current_word(cursor_offset, line)
if match is None:
return None
start, end, word = match
matches = current_object_re.finditer(word)
s = ""
for m i... | cba608811a2081b382a2c522bb9d0651569739dd | 24,505 |
def _is_match(option, useful_options, find_perfect_match):
"""
returns True if 'option' is between the useful_options
"""
for useful_option in useful_options:
if len(option) == sum([1 for o in option if o in useful_option]):
if not find_perfect_match or len(set(useful_option)) == len... | bff60e1320744c16747926071afb3ee02022c55c | 24,507 |
def pass_aligned_filtering(left_read, right_read, counter):
"""
Test if the two reads pass the additional filters such as check for soft-clipped end next to the variant region,
or overlapping region between the two reads.
:param left_read: the left (or 5') most read
:param right_read: the right (or ... | 78849f12541510216407b7b40fb29a0befc920d7 | 24,508 |
def detect_slow_oscillation(data: Dataset, algo: str = 'AASM/Massimini2004', start_offset: float = None) -> pd.DataFrame:
"""
Detect slow waves (slow oscillations) locations in an edf file for each channel
:param edf_filepath: path of edf file to load. Will maybe work with other filetypes. untested.
:pa... | a241196b56b6fb426fc9949ee82fca40c0c854f2 | 24,510 |
def _map_channels_to_measurement_lists(snirf):
"""Returns a map of measurementList index to measurementList group name."""
prefix = "measurementList"
data_keys = snirf["nirs"]["data1"].keys()
mls = [k for k in data_keys if k.startswith(prefix)]
def _extract_channel_id(ml):
return int(ml[len... | d6d83c01baec5f345d58fff8a0d0107a40b8db37 | 24,511 |
def is_not_applicable_for_questionnaire(
value: QuestionGroup, responses: QuestionnaireResponses
) -> bool:
"""Returns true if the given group's questions are not answerable for the given responses.
That is, for all the questions in the given question group, only not
applicable answers have been provid... | a534ca5560193c81e18f4028bd032b4a8e5adf8a | 24,512 |
def _chebnodes(a,b,n):
"""Chebyshev nodes of rank n on interal [a,b]."""
if not a < b:
raise ValueError('Lower bound must be less than upper bound.')
return np.array([1/2*((a+b)+(b-a)*np.cos((2*k-1)*np.pi/(2*n))) for k in range(1,n+1)]) | 4378468aac0642f15b64dcdee75dcb970aab11f7 | 24,513 |
def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | c7b689b9e6042aa84689003e2de6ffff2229eb69 | 24,515 |
def spawn_actor(world: carla.World, blueprint: carla.ActorBlueprint, spawn_point: carla.Transform,
attach_to: carla.Actor = None, attachment_type=carla.AttachmentType.Rigid) -> carla.Actor:
"""Tries to spawn an actor in a CARLA simulator.
:param world: a carla.World instance.
:param ... | 83d29b21e76f52f1928009e22cee6a635ef4d025 | 24,516 |
def partition(lst, size):
"""Partition list @lst into eveni-sized lists of size @size."""
return [lst[i::size] for i in range(size)] | af7071a5aac36a51f449f153df145d9218808a4a | 24,517 |
def form_errors_json(form=None):
"""It prints form errors as JSON."""
if form:
return mark_safe(dict(form.errors.items())) # noqa: S703, S308
return {} | d9748d5ce4578855775af24d1a758030ad3fa432 | 24,518 |
def get_semantic_ocs_version_from_config():
"""
Returning OCS semantic version from config.
Returns:
semantic_version.base.Version: Object of semantic version for OCS.
"""
return get_semantic_version(config.ENV_DATA["ocs_version"], True) | 346aa6aacff9a758cf06b4a3dc4977e98e9ca501 | 24,519 |
from typing import List
def get_non_ntile_cols(frame: pd.DataFrame) -> List[str]:
"""
:param frame: data frame to get columns of
:return: all columns in the frame that dont contain 'Ntile'
"""
return [col for col in frame.columns if 'Ntile' not in col] | 93970b576381aa668ce75d77f03793380445d9e4 | 24,521 |
from typing import Any
from typing import Optional
from datetime import datetime
def deserialize_date(value: Any) -> Optional[datetime.datetime]:
"""A flexible converter for str -> datetime.datetime"""
if value is None:
return None
if isinstance(value, datetime.datetime):
return value
... | 15cdd07ad4bd5873d8ed01d3eb9ce3b4e780ca44 | 24,522 |
def intersect(x1, x2, y1, y2, a1, a2, b1, b2):
""" Return True if (x1,x2,y1,y2) rectangles intersect. """
return overlap(x1, x2, a1, a2) & overlap(y1, y2, b1, b2) | 1e9c530b1d5e085df073b8c32d874ef457e2246a | 24,523 |
from typing import List
def recording_to_chunks(fingerprints: np.ndarray,
samples_per_chunk: int) -> List[np.ndarray]:
"""Breaks fingerprints of a recording into fixed-length chunks."""
chunks = []
for pos in range(0, len(fingerprints), samples_per_chunk):
chunk = fingerpri... | eae1a3b882e545a8dc08f029ddb5113dcdf1bca4 | 24,525 |
def coset_enumeration_c(fp_grp, Y):
"""
>>> from sympy.combinatorics.free_group import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
>>> C = coset_enumeration_c(f, [x])
... | 0efeacfeeb2b20275378c58a3aacaed07ade57be | 24,526 |
def slr_pulse(
num=N, time_bw=TBW,
ptype=PULSE_TYPE, ftype=FILTER_TYPE,
d_1=PBR, d_2=SBR,
root_flip=ROOT_FLIP,
multi_band = MULTI_BAND,
n_bands = N_BANDS,
phs_type = PHS_TYPE,
band_sep = BAND_SEP
):
"""Use Shinnar-Le Roux algorithm to generate pulse"""
if root_flip is Fal... | 0986b6ea8adffd90c108308365ebf3172a6459d0 | 24,527 |
def policy_options(state, Q_omega, epsilon=0.1):
""" Epsilon-greedy policy used to select options """
if np.random.uniform() < epsilon:
return np.random.choice(range(Q_omega.shape[1]))
else:
return np.argmax(Q_omega[state]) | 66e36b81fdec06822ebb958611deca23bd64191b | 24,528 |
import tempfile
import time
def test_ps_s3_creation_triggers_on_master():
""" test object creation s3 notifications in using put/copy/post on master"""
if skip_push_tests:
return SkipTest("PubSub push tests don't run in teuthology")
hostname = get_ip()
proc = init_rabbitmq()
if proc is No... | bb0770cd80968d8878f0a3c379f5ce2da9863c8f | 24,529 |
import math
def weights_init(init_type='gaussian'):
"""
from https://github.com/naoto0804/pytorch-inpainting-with-partial-conv/blob/master/net.py
"""
def init_fun(m):
classname = m.__class__.__name__
if (classname.find('Conv') == 0 or classname.find(
'Linear') == 0) and... | d65dee3744daf59a2db832b5c4866bee2131b4d6 | 24,530 |
def title(default=None, level="header"):
"""
A decorator that add an optional title argument to component.
"""
def decorator(fn):
loc = get_argument_default(fn, "where", None) or st
@wraps(fn)
def wrapped(
*args,
title=default,
level=level,
... | c11a3ee7ccff5e6934fba857d438743464dd653e | 24,531 |
def _rect_to_css(rect):
"""
Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order
:param rect: a dlib 'rect' object
:return: a plain tuple representation of the rect in (top, right, bottom, left) order
"""
return rect.top(), rect.right(), rect.bottom(), rect.left... | e3439cc0eb30186b8fc905f518ff21883175b3e2 | 24,533 |
def client():
"""Client Fixture."""
client_obj = Client(base_url=BASE_URL)
return client_obj | bac2ccd038eb587b4dd67ce0cc63bef63af9c365 | 24,534 |
def encode_one_hot(s):
"""One-hot encode all characters of the given string.
"""
all = []
for c in s:
x = np.zeros((INPUT_VOCAB_SIZE))
index = char_indices[c]
x[index] = 1
all.append(x)
return all | e4bc2b02cea4dbf74346cbd672cb58246abe4edc | 24,535 |
from datetime import datetime
def date_to_datetime(date, time_choice='min'):
"""
Convert date to datetime.
:param date: date to convert
:param time_choice: max or min
:return: datetime
"""
choice = getattr(datetime.datetime, 'min' if time_choice == 'min' else 'max').time()
return time... | 9e429bf71288ffc3bd56b682f2e24fceb0ff49d4 | 24,536 |
def standardize_cell(atoms, cell_type):
""" Standardize the cell of the atomic structure.
Parameters:
atoms: `ase.Atoms`
Atomic structure.
cell_type: { 'standard', 'standard_no_symmetries', 'primitive', None}
Starting from the input cell, creates a standard cell according to same stan... | 4005cf7afd6f4992f3cc271608f0b8c84649d6b1 | 24,537 |
def get_biggan_stats():
""" precomputed biggan statistics """
center_of_mass = [137 / 255., 127 / 255.]
object_size = [213 / 255., 210 / 255.]
return center_of_mass, object_size | 6576e13b7a68369e90b2003171d946453bafd212 | 24,538 |
def get_input_var_value(soup, var_id):
"""Get the value from text input variables.
Use when you see this HTML format:
<input id="wired_config_var" ... value="value">
Args:
soup (soup): soup pagetext that will be searched.
var_id (string): The id of a var, used to find its value.
R... | 5a9dd65a285c62e0e5e79584858634cb7b0ece75 | 24,539 |
from typing import List
from typing import Any
import logging
def get_top(metric: str, limit: int) -> List[List[Any]]:
"""Get top stocks based on metric from sentimentinvestor [Source: sentimentinvestor]
Parameters
----------
metric : str
Metric to get top tickers for
limit : int
... | c203fcbe24ccf3d0c2253961d36ec7b556c8651c | 24,541 |
def test_add_single_entities(
reference_data: np.ndarray,
upper_bound: np.ndarray,
lower_bound: np.ndarray,
ishan: Entity,
) -> None:
"""Test the addition of SEPTs"""
tensor1 = SEPT(
child=reference_data, entity=ishan, max_vals=upper_bound, min_vals=lower_bound
)
tensor2 = SEPT(
... | 48531867a74d7267ae65d4350e82d26cae8bef44 | 24,542 |
def prob_get_expected_after_certain_turn(turns_later: int, turns_remain: int,
tiles_expect: int) -> float:
"""The probability of get expected tile after `turns_later` set of turns.
:param turns_later: Get the expected tile after `turns_after` set of turns
:param tur... | 6575c22302b73b58b2bd9aad5068ffe723fb5fe3 | 24,543 |
def get_gpcr_calpha_distances(pdb, xtc, gpcr_name, res_dbnum,
first_frame=0, last_frame=-1, step=1):
"""
Load distances between all selected atoms.
Parameters
----------
pdb : str
File name for the reference file (PDB or GRO format).
xtc : str
File ... | 3465246d610510f2976813fcc69c394e98452292 | 24,544 |
def main(yumrepomap=None,
**kwargs):
"""
Checks the distribution version and installs yum repo definition files
that are specific to that distribution.
:param yumrepomap: list of dicts, each dict contains two or three keys.
'url': the url to the yum repo definition file
... | 1caed81f53cd0dc2e1963aa1b53bc48c1ef71dd3 | 24,545 |
def zero_pad1d(inputs, padding=0):
"""Zero padding for 1d tensor
Args:
-----------------------------
inputs : tvm.te.tensor.Tensor
shape [batch, channel, length]
padding: (optional:0) int or tuple
-----------------------------
Returns:
-----------------------------
tvm.te.t... | 8135ffd8447d5fbc84988953a2bfca14b51d3f83 | 24,546 |
import torch
import math
def gelu(x):
"""gelu activation function copied from pytorch-pretrained-BERT."""
return x * 0.5 * (1.0 + torch.erf(x / math.sqrt(2.0))) | 35c0f45f904b2381acc95f5a2b4f28cec9fa924b | 24,547 |
import requests
def stock_fund_stock_holder(stock: str = "600004") -> pd.DataFrame:
"""
新浪财经-股本股东-基金持股
https://vip.stock.finance.sina.com.cn/corp/go.php/vCI_FundStockHolder/stockid/600004.phtml
:param stock: 股票代码
:type stock: str
:return: 新浪财经-股本股东-基金持股
:rtype: pandas.DataFrame
"""
... | acde3d06b9fabd9a22223401b6b9b947a1e248ff | 24,548 |
def set_to_available(request, slug, version):
"""
Updates the video status.
Sets the version already encoded to available.
"""
video = get_object_or_404(Video, slug=slug)
status, created = VideoStatus.objects.get_or_create(video_slug=slug)
if version == 'web':
status.web_availa... | ead832327d733b82b0d1bc38efd241baab039ed2 | 24,549 |
def generate_solve_c():
"""Generate C source string for the recursive solve() function."""
piece_letters = 'filnptuvwxyz'
stack = []
lines = []
add = lines.append
add('#define X_PIECE_NUM {}'.format(piece_letters.index('x')))
add("""
void solve(char* board, int pos, unsigned int used) {
... | dde70d4cdbeb8b691c1ffcb61ba524b2c1df9b2c | 24,551 |
def get_permission_info(room):
"""
Fetches permissions about the room, like ban info etc.
# Return Value
dict of session_id to current permissions,
a dict containing the name of the permission mapped to a boolean value.
"""
return jsonify({k: addExtraPermInfo(v) for k, v in room.permission... | aab7aa691e1e34e1bf20e3de744f8d4352a2421e | 24,552 |
def ravel(m):
"""ravel(m) returns a 1d array corresponding to all the elements of it's
argument.
"""
return reshape(m, (-1,)) | 728204f77737750783fef9818c102522f17c472e | 24,553 |
def parse_index_file(filename):
"""Parse index file."""
index = []
for line in open(filename):
# My additions
print ("Printing this unstripped text:", line)
index.append(int(line.strip()))
return index | a76c4e94c593a234fd858d369f0133a5170ec8bf | 24,554 |
import click
import socket
def init():
"""Top level command handler."""
@click.command()
@click.option('--port', type=int, help='Port to listen.', default=0)
@click.option('--tun-dev', type=str, required=True,
help='Device to use when establishing tunnels.')
@click.option('--tun... | ba660e7f6698457951e766ce402857a6a5e4bc86 | 24,555 |
def check_collision(bird_rect:object, pipes:list, collide_sound:object):
""" Checks for collision with the Pipe and the Base """
for pipe in pipes:
if bird_rect.colliderect(pipe):
collide_sound.play()
return False
if bird_rect.bottom >= gv.BASE_TOP:
return False
r... | 080c8a6142397e3c1b91b0e3a4dfbd3ed7f1acde | 24,556 |
def compute_ranking_scores(ranking_scores,
global_ranks_to_save,
rank_per_query):
""" Compute ranking scores (MRR and MAP) and a bunch of interesting ranks to save to file from a list of ranks.
Args:
ranking_scores: Ranking scores previously compute... | a25a664b67e35ff9b35327b364e84eaf9ae37aaa | 24,557 |
def AirAbsorptionRelaxationFrequencies(T,p,H,T0, p_r):
"""
Calculates the relaxation frequencies for air absorption conforming to
ISO 9613-1. Called by :any:`AirAbsorptionCoefficient`.
Parameters
----------
T : float
Temperature in K.
p : float
Pressure in Pa.
H : float
... | c8c047ed4d9a7fc62b2cdb6d19f0d3c8b1b4c570 | 24,558 |
def table_from_bool(ind1, ind2):
"""
Given two boolean arrays, return the 2x2 contingency table
ind1, ind2 : array-like
Arrays of the same length
"""
return [
sum(ind1 & ind2),
sum(ind1 & ~ind2),
sum(~ind1 & ind2),
sum(~ind1 & ~ind2),
... | 497ce6ad1810386fedb6ada9ba87f0a5baa6318a | 24,559 |
def preprocess_skills(month_kpi_skills: pd.DataFrame, quarter_kpi_skills: pd.DataFrame) -> pd.DataFrame:
"""
Функция принимает на вход два DataFrame:
- с данными по KPI сотрудников ВЭД за последний месяц
- с данными по KPI сотрудников ВЭД за последний квартал
Возвращает объединенный DataFrame по дву... | 6bcbc1b93c99acbef04bf0962678c35a3abd3faa | 24,560 |
def bias_col_spline(im, overscan, dymin=5, dymax=2, statistic=np.mean, **kwargs):
"""Compute the offset by fitting a spline to the mean of each row in the
serial overscan region.
Args:
im: A masked (lsst.afw.image.imageLib.MaskedImageF) or unmasked
(lsst.afw.image.imageLib.ImageF) afw i... | d157275dd8337b81c9f4c67efe1c033512f963d3 | 24,561 |
def read_config():
""" Returns the decoded config data in 'db_config.json'
Will return the decoded config file if 'db_config.json' exists and is a valid JSON format.
Otherwise, it will return a False.
"""
# Check if file exists
if not os.path.isfile('db_config.json'):
return False
#... | 36b0ccdbd653b654663c7a3c6cf47cb3f68bc399 | 24,562 |
import pandas
def get_sub_title_from_series(ser: pandas.Series, decimals: int = 3) -> str:
"""pandas.Seriesから、平均値、標準偏差、データ数が記載されたSubTitleを生成する。"""
mean = round(ser.mean(), decimals)
std = round(ser.std(), decimals)
sub_title = f"μ={mean}, α={std}, N={len(ser)}"
return sub_title | 45c227e7ddd203872f015e4a95532c8acb80d54f | 24,563 |
import numpy
def atand2(delta_y: ArrayLike, delta_x: ArrayLike) -> ArrayLike:
"""Return the arctan2 of an angle specified in degrees.
Returns
-------
float
An angle, in degrees.
"""
return numpy.degrees(numpy.arctan2(delta_y, delta_x)) | 14d825d9886a2a62e36748eb9660ee27e6ba6827 | 24,564 |
from typing import Union
def adjust_doy_calendar(
source: xr.DataArray, target: Union[xr.DataArray, xr.Dataset]
) -> xr.DataArray:
"""Interpolate from one set of dayofyear range to another calendar.
Interpolate an array defined over a `dayofyear` range (say 1 to 360) to another `dayofyear` range (say 1
... | d55da217c6b6e3b2947e992611da4e1fdacf7f5f | 24,565 |
def iou(box_a, box_b):
"""Calculates intersection area / union area for two bounding boxes."""
assert area(box_a) > 0
assert area(box_b) > 0
intersect = np.array(
[[max(box_a[0][0], box_b[0][0]),
max(box_a[0][1], box_b[0][1])],
[min(box_a[1][0], box_b[1][0]),
min(box_a[1][1], box_b[... | 9722673c7cc5b636d698453224cf3f06d1aa3678 | 24,566 |
def poll():
"""
The send buffer is flushed and any outstanding CA background activity is processed.
.. note:: same as pend_event(1e-12)
"""
status = libca.ca_pend_event(1e-12)
return ECA(status) | 96052229179a0188a3bb63a6e3ab35aa3d6cc5f7 | 24,567 |
def TopLevelWindow_GetDefaultSize(*args):
"""TopLevelWindow_GetDefaultSize() -> Size"""
return _windows_.TopLevelWindow_GetDefaultSize(*args) | e9a04052461bf64b7b3e4962a7df052e1f63de4b | 24,568 |
def human_size(numbytes):
"""converts a number of bytes into a readable string by humans"""
KB = 1024
MB = 1024*KB
GB = 1024*MB
TB = 1024*GB
if numbytes >= TB:
amount = numbytes / TB
unit = "TiB"
elif numbytes >= GB:
amount = numbytes / GB
unit = "GiB"
el... | 733fdff47350072b9cfcaf72a2de85f8a1d58cc6 | 24,569 |
from typing import Callable
from typing import Any
def node_definitions(
id_fetcher: Callable[[str, GraphQLResolveInfo], Any],
type_resolver: GraphQLTypeResolver = None,
) -> GraphQLNodeDefinitions:
"""
Given a function to map from an ID to an underlying object, and a function
to map from an under... | 4e041edacbd7e5d6c82dd7df8616a694aa00181a | 24,571 |
def get_image_from_request(request):
"""
This function is used to extract the image from a POST or GET request.
Usually it is a url of the image and, in case of the POST is possible
to send it as a multi-part data.
Returns a tuple with (ok:boolean, error:string, image:ndarray)
"""
if reques... | 0af18d65664e1c7dc264ac112b42e001ac293fd6 | 24,572 |
def con_external():
"""Define a connection fixture.
Returns
-------
ibis.omniscidb.OmniSciDBClient
"""
omnisci_client = ibis.omniscidb.connect(
user=EXT_OMNISCIDB_USER,
password=EXT_OMNISCIDB_PASSWORD,
host=EXT_OMNISCIDB_HOST,
port=EXT_OMNISCIDB_PORT,
data... | e5a57ebdf8640bd96a2e28678fe4d0b285fe8408 | 24,573 |
def parse_risk(data_byte_d):
"""Parse and arrange risk lists.
Parameters
----------
data_byte_d : object
Decoded StringIO object.
Returns
-------
neocc_lst : *pandas.Series* or *pandas.DataFrame*
Data frame with risk list data parsed.
"""
# Read data as csv
neoc... | cf8761e46df621ffcf69dba9e2c359c25da02234 | 24,574 |
def plot_step_w_variable_station_filters(df, df_stations=None, options=None):
"""
"""
p = PlotStepWithControls(df, df_stations, options)
return p.plot() | a1faa31c90f4c00103148aa50648f040849984b1 | 24,575 |
def pick_random_element(count):
"""
Parameters
----------
count: {string: int}
A dictionary of all transition
counts from some state
we're in to all other states
Returns
-------
The next character, randomly sampled
from the empirical probabilities
determined f... | 90388526b0a3a663f4f8d2ef6530484ddcf6fde2 | 24,576 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.