content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import random
def generate_sentence(data):
"""Generate new Markov chains sentence.
This data generates new sentence based on
Markov chains algorithm
**Note!** Current implementation is buggy and
will be changed in future
Args:
data (list): List of data to work with
Returns:
... | ea0c60012761f873c7bf505913c10beb55f9b1bd | 40,400 |
def update_repo_in_cache(repo_name: str, repo_dir: str, app_dir: str) -> None:
"""
Updates a single repo_details dict in the imported_repos cached list
:param repo_name: name of the repo to update
:param repo_dir: dir of the repo to update
:param app_dir: current application
:return: None
""... | 4863fcbab9429d32f90344dae65624296061757c | 40,401 |
from typing import OrderedDict
def read_event(io, metadata):
"""Reads the event that the stream points to.
:param io: the stream.
:param metadata: metadata of the PML file.
:return: Event object.
"""
process_idx, tid, event_class_val, operation_val, _, _, duration, date, result, stacktrace_de... | 14edb44a2e65f2108869997c9db050b4cbb0bd5b | 40,402 |
def Mean(xs):
"""Computes mean.
xs: sequence of values
returns: float mean
"""
return np.mean(xs) | 268f76d95b53057877ed58ce4ca48075e3f2b320 | 40,403 |
import struct
def tcp_shasum_calc(src: bytes, dst: bytes, proto: int, payload: bytes) -> bytes:
""" Calculate SHA256 sum of a TCP header
:param src: source IP address
:param dst: destination IP address
:param proto: TCP protocol
:param payload: TCP payload
:return: SHA256 sum
"""
_sum ... | 108703f417f5f15a4a24a0bf7ef08e503dd5244b | 40,404 |
def generate_exmat(T_mat, center, tracking):
"""
Generate the extrinsic matrix for the camera.
Develop the extrinsic matrix for the camera, which is used for transforming the object in the world coordinate
system into the homogeneous camera coordinate system. Note that the intermediate variable H_o2k (... | bc2cea794aa20d6161af228048a44440df15612c | 40,405 |
import requests
from bs4 import BeautifulSoup
def wiki(searchterm):
"""return the top wiki search result for the term"""
searchterm = quote(searchterm)
url = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={0}&format=json"
url = url.format(searchterm)
result = requests.get(... | 9f7611c7679a8ad7f4d97eb8c265e9ba193c0c67 | 40,406 |
def bce_loss(prediction, target):
"""
prediction and target should have the same size.
:param prediction:
:param target:
:return:
"""
return F.binary_cross_entropy_with_logits(prediction, target) | e06bd9e5eece5e276fa494461f68fd4e8ee0e9df | 40,407 |
def get_or_create_aa_group(conn: OSConnection, name: str) -> int:
"""create anti-affinity server group, if doesn't exists yet
parameters:
conn: OSConnection
name: str - group name
returns: str - group id
"""
try:
return conn.nova.server_groups.find(name=name).id
except ... | 699bf5f8d2bcce85893cc9682ccc4e8455b64269 | 40,408 |
def isMonthly(s):
"""
This function test if the data are monthly data from the time axis.
:param s: A cdms2 TransientVariable
:type s: cdms2.tvariable.TransientVariable
:returns: An integer flag indicating whether s has monthly data (1), or does not (0).
:rtype: int
"""
tim = s.getTime... | 6d666abd598e3d32464d0a0f668b14e32b365bd5 | 40,409 |
def pressure(v, t, n=6.022e23):
"""Compute the pressure in pascals of an ideal gas.
v -- volume of gas, in cubic meters
t -- absolute temperature in degrees kelvin
n -- particles of gas (default: one mole)
"""
return n * k_b * t / v | 454e1f88ed73adc6e23a4badd86563605ed35400 | 40,410 |
def instance_type_destroy(context, name):
""" Marks specific instance_type as deleted"""
session = get_session()
instance_type_ref = session.query(models.InstanceTypes).\
filter_by(name=name)
records = instance_type_ref.update(dict(deleted=True))
if records == 0... | 2764baf298602cd5c5fc7577a38df61309338410 | 40,411 |
from ipn import Paypal2IPN
def do_express_payment(token, payer_id, cart, settings):
"""Call DoExpressCheckoutPayment for each lineitem."""
params = {"METHOD": "DoExpressCheckoutPayment",
"TOKEN": token,
"PAYERID": payer_id,
"PAYMENTREQUEST_0_CURRENCYCODE": "USD", # TO... | e12308ae1b5d0512efb1a6b498b15f46f31ce447 | 40,412 |
def get_crs_from_raster(raster_address):
"""Function reads raster data and gets its coordinate reference system"""
with rio.open(raster_address) as f:
band_crs = f.crs
return band_crs | bf7fe1f4d4099a1e7360a41399eb55e583eea54d | 40,413 |
from typing import Mapping
import time
def _build_entrez_map(hgnc_manager: bio2bel_hgnc.Manager) -> Mapping[str, HumanGene]:
"""Build a mapping from entrez gene identifiers to their database models from :py:mod:`bio2bel_hgnc.models`."""
logger.info('getting entrez mapping')
t = time.time()
emap = {
... | ddd09199bd8a09a499c681854b49e6520d3bc59b | 40,414 |
from typing import Dict
from typing import Any
def build_conformer_block(
block: Dict[str, Any],
self_attn_class: str,
pw_layer_type: str,
pw_activation_type: str,
conv_mod_activation_type: str,
) -> ConformerEncoderLayer:
"""Build function for conformer block.
Args:
block: Confor... | a20ac1041883846e3792a535bcbb90402046c342 | 40,415 |
def _stringify_query_build_rows(qb_rows: [], order_by_desc: str = None) -> str:
"""
'Stringify' supplied rows by concatenating them, removing the final, dangling 'UNION ALL' keyword, and
optionally appending an 'ORDER BY' clause.
Intended for use with output rows of query builder algorithms.
:param ... | f76e4d4f8e63831b60756607436f15cb3efa3489 | 40,416 |
def tessellation(order, face_centers=False, face_areas=False):
"""
Constructs a tessellation from a subdivision of an icosahedron.
Parameters
----------
order : int
The order of the recursive tessellation.
compute_face_centers : bool, optional
compute_face_areas : bool, optiona... | 0f88707d650f72cf773c9de125f9b64dbd63a156 | 40,417 |
def InvokeWithModifiedEnv(extra_env, function, *args, **kwargs):
"""Runs the given function and arguments in a modified environment."""
try:
original_env = environ.copy()
environ.update(extra_env)
return function(*args, **kwargs)
finally:
environ.clear()
environ.update(original_env) | 30be66c6fda4cbf7d4a7b569f02f0ee7ab6cf59b | 40,418 |
def dihedral(bits, f, i):
"""Apply an element of the dihedral group to a bit board or bit pattern.
Args:
bits:
An integer whose bits represent a pattern on a Yavalath board, or a tuple of integers
f:
An integer indicating the number of flips about the horizontal axis to... | efbe38624aeb9cafc7d0392c9e73a0b87d2ec5e3 | 40,419 |
import os
import sys
def mute(func):
""" Decorator
Make stdout silent
"""
def _f(*args, **kwargs):
sys.stdout = open(os.devnull, 'w')
res = func(*args, **kwargs)
sys.stdout.close()
sys.stdout = sys.__stdout__
return res
return _f | 0f2260b309bffb8c0275bf2be8aed25022fddb13 | 40,420 |
from pathlib import Path
import os
import json
def automatic_alignment(id_series, id_ep, refsT, hypsT):
"""Aligns IMDB character's names with transcripts characters names.
Parameters
----------
id_series : `str`
Id of the series.
id_ep : `str`
Id of the episode.
refsT : `dict`... | bc16dd55e000d1b74fc1b47af4707d132ff567fc | 40,421 |
from typing import Dict
from typing import Type
def type_detect_frame(
df: pd.DataFrame, typeset: VisionsTypeset
) -> Dict[str, Type[VisionsBaseType]]:
"""Detect the type in the base graph
Args:
df: the DataFrame to detect types on
typeset: the Typeset that provides the type context
... | 3d602951c052cc8f4a55a32f1e9b1afdd1d7a7f8 | 40,422 |
def cleanup_data(df: pd.DataFrame) -> pd.DataFrame:
"""Clean up some empty/null values"""
df = df.replace(r"^\s+$", nan, regex=True)
df = df.replace("", nan, regex=True)
return df | 2fd5c676bbb76c86d078c12041b9901222a2603e | 40,423 |
def sigmoid(z):
"""The sigmoid function
"""
return 1. / (1. + np.exp(-z)) | c9929d74557b4e4bd50a1d7229c1b179e06fb0df | 40,424 |
def entrypoint(label):
"""
If a class if going to be registered with setuptools as an entrypoint it
must have the label it will be registered under associated with it via this
decorator.
This decorator sets the ENTRY_POINT_ORIG_LABEL and ENTRY_POINT_LABEL class
proprieties to the same value, la... | 68cb3f2d2a982fefd34f412888ae50fcea6a743f | 40,425 |
def check_semver():
"""Get output from pyang tool with option '--check-update-from' for all the modules between and filter.
I. If module compilation failed it will give you only link to get diff in between two yang modules.
II. If check-update-from has an output it will provide tree diff and output of the p... | b0dc49b13ca419fb74f1b3f31aa2acf4336d2516 | 40,426 |
import argparse
import os
import sys
import random
def main():
"""PointViz visualizer examples."""
parser = argparse.ArgumentParser(
description=main.__doc__,
formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument('pcap_path',
nargs='?',
... | a6026f786fd1d42ec9854f1aea4f326495a4475c | 40,427 |
def dictionary_and_embeddings_to_indices(word_frequencies, embeddings):
"""
Sort words by frequency (descending), adds offset (3 items), maps word indices to embeddings
and generate random embeddings for padding, start of sequence, and OOV
:param word_frequencies: dict (word: frequency)
:param embed... | 488a0b48ce2ac3454eb8935eb19aa91a757c2f96 | 40,428 |
def check_already_unfollowed(self, user_id):
""" controls if user was already unfollowed before """
if (
self.follows_db_c.execute(
"SELECT EXISTS(SELECT 1 FROM usernames WHERE username_id='"
+ user_id
+ "' AND unfollow_count > 0 LIMIT 1)"
).fetchone()[0]
... | 92e27dcd18546ae9c79cd284660c0ccb66542352 | 40,429 |
def base_seir_model_OLD(param, dict):
"""
# S=susceptable, E=exposed, I=infected, R=Removed (with icfrac with a delay of idelayD)
# Added: Recovered, Hospitalized, Dead
:param param:
:param dict:
:return:
"""
n, r0, sigma, gamma, alpha, delay_hos, delay_rec, delay_hosrec, delay_hosd, ho... | bb7f06372ca009800ed315a7c39745519cfdd827 | 40,430 |
import warnings
def get_view_edge(state: SDFGState, view: nd.AccessNode) -> gr.MultiConnectorEdge[mm.Memlet]:
"""
Given a view access node, returns the
incoming/outgoing edge which points to the viewed access node.
See the ruleset in the documentation of ``dace.data.View``.
:param state: The stat... | 7016413bd09458dd34850a58cbea6c08055d2b59 | 40,431 |
def service(service, private_base_url):
"""Add upstream policy"""
proxy = service.proxy.list()
proxy.policies.insert(0, rawobj.PolicyConfig("upstream", {
"rules": [{"url": private_base_url("echo_api"), "regex": "/httpbin"}]}))
return service | e92b64d2017154f87893d8f15bc3e685a64b3219 | 40,432 |
from tqdm import tqdm_notebook
def reduce_mem_usage(df, columns=None, verbose=True, debug=False):
""" Reduce memory usage of provided DataFrame using best dtype for each column """
if columns == None:
columns = df.columns
elif len(columns) == 0:
return df
if verbose:
print("... | c376021de629d27568a6eb9bb02993ef1847ef6e | 40,433 |
def metadata():
"""
Provides the metadata for the Real plug-in.
This gives human-readable information on the plug-in, dependency resolution
information, and tells the plug-in system what this plug-in can do.
:return: Dictionary of metadata.
"""
return {
"name": "Real",
"description": "Defines real numbers t... | f7cd9cb16a1122471c25e085a7e222f86ecfc269 | 40,434 |
def hide_empty(value, prefix=', '):
"""Return a string with optional prefix if value is non-empty"""
value = str(value)
return prefix + value if value else '' | d2943dbce763bd054dc26839b2d24232867b3312 | 40,435 |
def merge_layers_on_edges(mask):
"""
First merges layers left halves to right halves, then top to bottom.
"""
lr_center = mask.shape[1] // 2
left_half_idx = np.argwhere(mask[:, lr_center - 1, :].sum(axis=0) > 0).flatten()
right_half_idx = np.argwhere(mask[:, lr_center, :].sum(axis=0) > 0).flatte... | 3fa92ed3889d7867fe32a5814db0b318322630f5 | 40,436 |
import struct
def kvlds_length_and_bytes(data):
""" Make some bytes storing the length and data in the kvlds format. """
# Sanity check
if not isinstance(data, bytes):
raise NotBinaryData()
if len(data) > 255:
raise KivalooTooMuchData()
# Return form expected by kivaloo
return... | bd658f772280bdc9183706e521619f5135117b39 | 40,437 |
import tokenize
import torch
import random
def answer(sentence):
"""
This is the main function of all the project, it recibes a sentence:
p:sentence
And using other functions in our project, implements the bag of words
algorithm to answer it.
"""
# check if the user wants to exit the chat
if sentence == 'S... | 7069566fa8c2cdef61be7ccc0bfd2b75e8cf6b14 | 40,438 |
from typing import List
def asset_key(assets: List[str]) -> str:
"""Convert multiple version specs into a URL-friendly key."""
return make_name(
'-'.join(assets)
.replace('==', '-eq-')
.replace('>=', '-gte-')
.replace('<=', '-lte-')
.replace('>', '-gt-')
.replac... | 56b8d0be7be262d400cdeced6c358a464039c9d0 | 40,439 |
def request_clone_or_create(request, rid, title, submit_url, TRequestCreateCloneForm, TRequestCreateCloneConfirmation,
form_prefill, default_step_values = {'nEventsPerJob':'1000','priority':'880'}):
"""
Fill form for creating request. Create request->slice->steps for POST
View cr... | 0ab6d5e29889f05f72e5dfc65da99c40630d3171 | 40,440 |
def LF_DG_BICLUSTER_OVEREXPRESSION(c):
"""
This label function uses the bicluster data located in the
A global network of biomedical relationships
"""
sen_pos = c.get_parent().position
pubmed_id = int(c.get_parent().document.name)
if (pubmed_id, sen_pos) in overexpression_base:
retur... | 0dc7a960185ced1ff47e2b386a717f58f69d988e | 40,441 |
import logging
import os
import csv
def check_table_and_warn_if_dmg_freq_is_low(folder):
"""Returns true if the damage frequencies are too low to allow
Bayesian estimation of DNA damages, i.e < 1% at first position.
"""
logger = logging.getLogger(__name__)
filename = "misincorporation.txt"
mis... | d776bf11d311ae1fac9f259e8f7a78f9caf8d1b8 | 40,442 |
def preauction_filters(participants, task, indivisible_tasks=False):
"""Apply some preauction filters to the participants list in order to remove any invalid candidates.
Args:
participants (list): A list of participating nodes and their info.
indivisible_tasks (bool): Only allow nodes that offe... | 7eadb0f8e95942ae0b3033cbca90ea44fba4d199 | 40,443 |
def mk_fitfunc(fname, pnames, globname, extraargs=[]):
"""
Dynamically make a fit function for the given param names, to be passed to Minuit.
Return a string definition of the function, to be exec'd, and the list of
generated internal arg names corresponding to pnames.
"""
fargs = ["A%03i" % i ... | 01832d811b37b9367666cf4e10ad7b471b047e3b | 40,444 |
import argparse
def parse_args():
"""Parse input arguments."""
parser = argparse.ArgumentParser(description='Faster R-CNN demo')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [0]',
default=0, type=int)
parser.add_argument('--cpu', dest='cpu_mode',
... | 203d915ecc759da5b44fc579174a562de479174f | 40,445 |
import requests
import logging
def setTOURL(url:str) -> bool:
"""
Sets the :data:`TO_USE_SSL`, :data:`TO_PORT` and :data:`TO_HOST` global variables and verifies,
them.
:param url: A full URL (including schema - and port when necessary) specifying the location of
a running Traffic Ops server
:returns: whether ... | e3b827560acf28de9ee30c6bfa4c10464544db7f | 40,446 |
import transformers
from typing import List
from typing import Tuple
import tqdm
import torch
def test_two_span(
test_data: data.DataLoader,
model: transformers.PreTrainedModel,
loss_func: nn.modules.loss._Loss,
ids: List[int],
dev=None
) -> Tuple[float, float, float]:
... | 803edd73b56aeab80501a5d88cb431ca1d4b9cee | 40,447 |
def set_env_solver_nodes(lattice, perveance, max_sep=0.01, min_sep=1e-6):
"""Place a set of envelope solver nodes into the lattice.
The method will place the set into the lattice as child nodes of
the first level accelerator nodes. The nodes will be inserted at
the beginning of a particular part of... | 3962354550a273264defefa98fe59565f4445a3e | 40,448 |
import compileall
import sys
def compile_file(dir):
"""
Compile a py file
"""
try:
compileall.compile_dir(dir=dir, ddir=dir, force=0,
quiet=report_problem)
except Exception:
return sys.exc_info()[1]
return None | 7dac0ba12bb8a3045e76f2229b70d5ef77dbac28 | 40,449 |
def render_question_type_049(workspace, module, node, question, answer):
"""
Dependency:
- QID: 77 | I will offer the the following incentives to get customers to try my products or services
- QID: 78 | I will use the following physical marketing materials as ways to communicate my product or service to... | ca79ed8424a02ccd6763a329ad26a5e1049f3c8b | 40,450 |
def default_on_failure(request, message, **kwargs):
""" default failure action on signin """
return render('openid_failure.html', {
'message': message
}) | 92d08ad3f2f0ffa7aea55ac9c16357d58dfba141 | 40,451 |
def insert_vendor(vendor_name):
""" insert a new vendor into the vendors table """
sql = """INSERT INTO vendors(vendor_name)
VALUES(%s) RETURNING vendor_id;"""
conn = None
vendor_id = None
try:
# read database configuration
params = config()
# connect to the Post... | edba0738a24280f9adc99832b7a4919028c97db9 | 40,452 |
def isSymmetric(root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
leftPart=[root.left]
rightPart=[root.right]
while leftPart and rightPart:
leftNode=leftPart.pop()
rightNode=rightPart.pop()
if leftNode and rightNode:
if ... | 7026794a5e94df15439da1e776b485927fcf6078 | 40,453 |
import os
import errno
def test_decoder_cache_shrink_threadsafe(monkeypatch, tmp_path):
"""Tests that shrink handles files deleted by other processes."""
cache_dir = str(tmp_path)
solver_mock = SolverMock()
with DecoderCache(cache_dir=cache_dir) as cache:
cache.wrap_solver(solver_mock)(**get_... | ab66ae2da228aec62391813a71dfeece601ca2e3 | 40,454 |
import json
def convert_request_to(target):
"""
convert different kinds of request to needed input.
there are 4 needed inputs:
- GraphNode
- GraphRelation
- RawString
- ExtractorInput
"""
def _convert_request_to(func):
@wraps(func)
def wrapper(self, request, contex... | bf77b97e1d0c94c998d200d79e7b3203780cfbc4 | 40,455 |
from datetime import datetime
def json_serial(obj):
""" JSON serializer for datetime objects """
if isinstance(obj, (datetime, date)):
return obj.isoformat()
raise TypeError ("Type %s not serializable" % type(obj)) | a1fca440b22fd656e2d69e96cfcb4bfb2e708ed9 | 40,456 |
def thick_plane_points(plane: Plane, thickness, plane_point=None):
"""
Convert plane point to two thick plane points.
Given a Plane and a thickness, return two points along the normal that
are `thickness` apart. Optionally specify a specific point in the plane.
"""
if plane_point is None:
... | b2f2f3930306e67c7138813819b9c3407ef1bdbf | 40,457 |
from datetime import datetime
def get_timestamp_string(
date_array
):
"""
Convenience function returning the datetime timestamp based on the given input
Args:
date_array: array
Array of integers corresponding to [year, month, day, hour, minute, second].
Any integer... | cc97e261a9b34e7b37cfaa22a8e4996084f9a9d0 | 40,458 |
def Tracker(switch=1,targetName="Landmark", targetParam=0.1):
"""Turn tracker on or off. Or get status = 2"""
##Target Parameters Comment
##RedBall diameter of ball (meter) Used to compute the distance between robot and ball.
##Face width of face (meter) Used to compute the distance betwee... | 978728cc8619fd811f1ee4dd6858bf7185470a55 | 40,459 |
def from_file(file, gpu=None):
"""Preprocess pitch from file"""
return from_audio(cargan.load.audio(file), cargan.SAMPLE_RATE, gpu) | d49f253a061c3c81aaadb98cacab0f6476280b44 | 40,460 |
def mod(t1, t2):
"""
Element-wise division remainder of values of operand t1 by values of operand t2 (i.e. t1 % t2), not commutative.
Takes the two operands (scalar or tensor) whose elements are to be divided (operand 1 by operand 2) as arguments.
Currently t1 and t2 are just passed to remainder.
... | 2fbb505fa031f3ee0cbed6341a4d0ddeb3e5122e | 40,461 |
import time
from datetime import datetime
def check_date(birth_date):
"""If false it has a validation message with it"""
if birth_date != None:
birth_date = birth_date.strip()
if birth_date == '':
return (False, "Please Enter Your Birth Date")
try:
time.strptim... | 06c7a10413d1509201ae672cca5985769d12871e | 40,462 |
from pathlib import Path
def gdb_run_silent_cmd(cmd: CommandType, before: CommandType = (), after: CommandType = (),
target: Path = DEFAULT_TARGET,
strip_ansi: bool = STRIP_ANSI_DEFAULT) -> str:
"""Disable the output and run entirely the `target` binary."""
before... | 463ab8384f06a30f7946eb41efc8de937f1844ca | 40,463 |
def get_instance_data(instance_id):
"""Fetch instance details and return type and subnet."""
try:
result = ec2_client.describe_instances(InstanceIds=[instance_id])
vpc_subnet_id = result['Reservations'][0]['Instances'][0]['SubnetId']
instance_type = result['Reservations'][0]['Instances'... | 1160ab51f95a8bdf2110ffa9e960754bde29c53b | 40,464 |
from sys import version
def can_finetune(
last_fingerprint: Fingerprint,
new_fingerprint: Fingerprint,
core: bool = False,
nlu: bool = False,
) -> bool:
"""Checks if components of a model can be finetuned with incremental training.
Args:
last_fingerprint: The fingerprint of the old mo... | 2e28d386079d616aedb99e5ed7a3d619daa032f9 | 40,465 |
import heapq
def min_window(k):
"""
Algorithm to find minimum window length between k lists. Uses
a heap.
"""
heap = []
p=[0 for i in range(len(k))]
min_r = 99999999
ma=0
for i in range(len(k)):
if k[i][0]>ma:
ma=k[i][0]
heapq.heappush(heap,(k[i... | 4ad706eac321a43924a32e2883c3ffae24a7f989 | 40,466 |
from pyshacl.extras.js.target import JSTargetType
from typing import Sequence
from typing import Union
from typing import List
from typing import Type
def gather_target_types(shacl_graph: 'ShapesGraph') -> Sequence[Union['SHACLTargetType', 'SPARQLTargetType']]:
"""
:param shacl_graph:
:type shacl_graph: ... | 907a56deb6d2843ad34fe3facb05631e930b8ef7 | 40,467 |
import math
def r_vonmises(n,mu,kappa):
"""
This function is used for generating random numbers for a von Mises circular distribution
Parameters:
n: int, Number of observations
mu: float/int, location parameter
kappa: float/int, scale parameter. Large valu... | bed5f08ee507c6cb6009e38bfba2dd664594c001 | 40,468 |
def video_flip_transform(buildState):
"""
APPLIES: VIDEO
Applies frame rate adjustments first and the flips the masks.
Resize is supported (last), but not recommended as part of the operation.
:param buildState:
:return: updated composite mask
@type buildState: BuildState
@rtype: Composi... | 2c79557feffe46b8225825fefb2df77d8c494a78 | 40,469 |
import sys
def alpha_023(enddate, index='all'):
"""
Inputs:
enddate: 必选参数,计算哪一天的因子
index: 默认参数,股票指数,默认为所有股票'all'
Outputs:
eries:index为成分股代码,values为对应因子值或0.00,当不满足条件时为0.00
公式:
(((sum(high, 20) / 20) < high) ? (-1\* delta(high, 2)) : 0)
"""
enddate = to_date_st... | ab7f65627f7c8371e51df4ddbb5e3b535f3379ab | 40,470 |
def upstart_restart(name):
"""Tries a `restart` command to the given service, if not successful
will stop it and start it. If the service is not started, will start it."""
with fabric.api.settings(warn_only=True):
status = sudo("service %s status|cat" % name)
if status.failed:
return sudo("service %s start" % n... | 1fc7f88db8d5787ec2079b1b1e2e676f726d7fb1 | 40,471 |
import sys
import logging
def default_main(parser):
""" Default entry point implementation """
args = safe_parse_args(parser, sys.argv[1:])
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
if hasattr(args, 'func'):
args.func(args)
return args | 81ab7308ea45005b75d0105f9128b3c77c845e9c | 40,472 |
import re
def reorder(text):
"""reorder strings that are in format [title, The] to [The title]"""
m = re.match("([\w ]+), The$", text)
return "The " + m.group(1) if m else text | 6040efec7e579f50e1ef2429569dd621e7acc401 | 40,473 |
def TNorm(aFuzzyNumber, bFuzzyNumber, normType='logic'):
"""
T-Norm conjunctive operators.
normType is an operator's name:
'logic' - result of fuzzy logic AND (min operator),
'algebraic' - result of algebraic multiplication operation,
'boundary' - result of boundary multiplication op... | 369db3c5c2a573c4d585388f8067a8c5fc5a0b20 | 40,474 |
def register_by_user_type(self, request, current_serializer):
"""Complementary function for manage register by serializer"""
serializer = current_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
data = UserSerializer(user).data
return Response(data... | 718b405e86798dbc761f8b337a234d34880296d6 | 40,475 |
def table_standardise_units_inplace(table):
"""Standardise units for all columns in a table in place.
"""
for column in table.columns.values():
if column.unit:
column.unit = standardise_unit(column.unit)
return table | e49741684741bd0e451b5ca435d28a184223708c | 40,476 |
def get_virtual_nodes(glycan, libr = None, reducing_end = ['Glc', 'GlcNAc']):
"""find unobserved biosynthetic precursors of a glycan\n
| Arguments:
| :-
| glycan (string): glycan in IUPAC-condensed format
| libr (list): library of monosaccharides; if you have one use it, otherwise a comprehensive lib will be ... | ebc1a8380663757122f0b676fdf9d87068880f3a | 40,477 |
def parallel_read(file_patterns,
parse_fn,
shuffle_filenames=True,
num_train_samples_per_task=4,
num_val_samples_per_task=4,
shuffle_buffer_size=50,
filter_fn=None,
interleave_cycle_length=None,... | f1ed1b1e1089701da1627149993407a331bde10a | 40,478 |
def rblock(inputs, filters, kernel_size, padding='valid', activation=None, scale=0.1):
"""Create a scaled Residual block connecting the down-path and the up-path of the u-net architecture
Activations are scaled by a constant to prevent the network from dying. Usually is set between 0.1 and 0.3. See:
https:... | aecc29b0f92e04e4e87876d560be7529d442b377 | 40,479 |
import re
def removeLanguageLinks(text: str, site=None, marker: str = '') -> str:
"""Return text with all inter-language links removed.
If a link to an unknown language is encountered, a warning
is printed.
:param text: The text that needs to be modified.
:param site: The site that the text is c... | 90128230dcd7e4b6299afda62c7e19b67189c575 | 40,480 |
def q_factorial(n, q=None):
"""
Return the `q`-analogue of the factorial `n!`.
If `q` is unspecified, then it defaults to using the generator `q` for
a univariate polynomial ring over the integers.
EXAMPLES::
sage: from sage.combinat.q_analogues import q_factorial
sage: q_factoria... | 9c8e5c97aa963a574df53d3262abddd5083042d9 | 40,481 |
from typing import List
import requests
def http_upload_files(
path: str, token: str, data: dict, files_info: List, domain: str = config.HF_AUTONLP_BACKEND_API, **kwargs
) -> requests.Response:
"""Uploads files to AutoNLP"""
try:
response = requests.post(
url=domain + path,
... | 2a35482c03582eca814a6087430b17e08b126199 | 40,482 |
from typing import Dict
from typing import Any
from typing import Tuple
def get_most_purchased_item(user_data: Dict[str, Dict[str, Any]]) -> Tuple[str, Dict[str, int]]:
"""
Returns the name of the most purchased item.
"""
return get_most_N_item(user_data, 3) | f2b7f78e81128f9c448752df9067596af412d005 | 40,483 |
def mean(x, axis=None, keepdims=False):
"""Mean of a tensor, alongside the specified axis.
# Arguments
x: A tensor or variable.
axis: An integer or list of integers in [-rank(x), rank(x)),
the axes to compute the mean. If `None` (default), computes
the mean over all dime... | d1a813ef9316bc3777355872a76e24a34d34318e | 40,484 |
def as_dict_with_keys(obj, keys):
"""
Convert SQLAlchemy model to list of dictionary with provided keys.
"""
return [dict((a, b) for (a, b) in zip(keys, item)) for item in obj] | 1fcab95f9f94696c1af652b0b181e6e3e69f7f53 | 40,485 |
def get_required_fields():
""" Get required fields for the deployment from UI.
Fields required for update only:
eventId, rd, deploymentNumber, versionNumber,
[lastModifiedTimestamp, deployCruiseInfo, recoverCruiseInfo, ingestInfo]
At a minimum, deploymentNumber, versionNumber and (instr... | fe2439b7e5adcd7b9d98f828c3315253e0786bc8 | 40,486 |
def requirements(path=getcwd(), freeze_file=FREEZE_FILE, venv=None):
"""manage requirements (dependencies) in `requirements.txt`
and `upgrade_requirements.txt`"""
log(INFO, ICONS["setup"] + "setup environment requirements")
code = False
if freeze_file and not exists(join(path, freeze_file)):
... | 8eb403fcd22cf5d8602a1f893816682c6f58cd18 | 40,487 |
def filter_df_by_threshold(df: pd.DataFrame,
threshold: int,
y_col: str='family'):
"""
Filter rare classes from dataset in a pd.DataFrame
Input:
df (pd.DataFrame):
Must contain at least 1 column with name given by `y_col`
threshold (int):
Exclude any rows from df that contain a `y_col` ... | 5fdd5d3b0acb011db5dd5d512e7c3695bbe996e6 | 40,488 |
def canned_elasticsearch(task_vars=None, exec_oc=None):
"""Create an Elasticsearch check object with stubbed exec_oc method"""
check = Elasticsearch(None, task_vars or {})
if exec_oc:
check.exec_oc = exec_oc
return check | c238261469a9e29ed88735a977850fed0545fa98 | 40,489 |
import torch
def get_cupy_tensor_dtype(tensor):
"""Return the corresponded Cupy dtype given a tensor."""
if isinstance(tensor, cupy.ndarray):
return tensor.dtype.type
if torch_available():
if isinstance(tensor, torch.Tensor):
return TORCH_NUMPY_DTYPE_MAP[tensor.dtype]
raise... | 8c074863db6557ff45df7d70c36549df43336c41 | 40,490 |
def addfunctions(abunch):
"""add functions to epbunch"""
key = abunch.obj[0].upper()
# -----------------
# TODO : alternate strategy to avoid listing the objkeys in snames
# check if epbunch has field "Zone_Name" or "Building_Surface_Name"
# and is in group u'Thermal Zones and Surfaces'
# ... | 69bb2bf0ec75b2900c3b70f0f9918686876833eb | 40,491 |
def maximo_libreria(a: float, b: float) -> float:
"""Re-escribir utilizando el built-in max.
Referencia: https://docs.python.org/3/library/functions.html#max
"""
return max(a, b) | 41f4c37c2dcb0a64c11c1517f93c119722002e3d | 40,492 |
def calculate_sensitivity(nex, nbg, alpha):
"""
Sensitivity calculation using nex/sqrt(nbg)
Parameters
---------
nex: `float` number of excess events in the signal region
nbg: `float` number of events in the background region
alpha: `float` inverse of the number of off positions
Re... | f8fe7c01f2b208a508c2f5b753962d4461530865 | 40,493 |
def highlight_min(s: pd.Series) -> pd.Series:
"""Takes a row from pandas series and colors a cell if value in a
cell is min value in an entire row"""
is_min = s == s.min()
return ["background-color: steelblue" if v else "" for v in is_min] | 06f4d093b18457b0e2523c7f098b56faf3fd6c1e | 40,494 |
def sort(li):
"""
Performs a mini radix sort on the top ten documents by first sorting
on document ids, then sorting on document ranking. As sorted() is stable,
this ensures that any documents with identical rankings will be sorted on
their document ids in increasing order
"""
... | eb71387372e3542db685ef97b45e5c5464657fc9 | 40,495 |
def MULS(product, multiplicand, multiplier):
"""
args:
sum: the register where the addition result is stored.
augend: the left operand of the addition.
addend: the right operand of the addition.
function:
Performs basic addition.
"""
return TacInstruction(instruction... | a318d43d696a9491842164150bed7160f8c71c09 | 40,496 |
def __generic_install(item, force_mode, new_only, check_function,
install_function, install_args):
"""Generic check and caller"""
try:
# First check if we know about this item
if check_function(item.name):
log.d(TAG, "Item exists, need to check")
... | 820689251f3596336223d4b547007951019102b3 | 40,497 |
def chord_and_tangent(F, P):
"""
Use the chord and tangent method to get another point on a cubic.
INPUT:
- ``F`` -- a homogeneous cubic in three variables with rational
coefficients, as a polynomial ring element, defining a smooth
plane cubic curve.
- ``P`` -- a 3-tuple `(x,y,z)` def... | 1a5d70da8fe966cab25462314996149c4c464aa7 | 40,498 |
def optimize(X, Y, a_prev, parameters, learning_rate = 0.01):
"""
Execute one step of the optimization to train the model.
Arguments:
X -- list of integers, where each integer is a number that maps to a character in the vocabulary.
Y -- list of integers, exactly the same as X but shifted one in... | d8d4a9fc7cff397b51b663f400cbe58131102cbd | 40,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.