content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def my_sentence_splitter(text,termination_points='.!~?'):
"""Concatenates a text character by character. Sentences end at a termination point
APR 19: Changed from dictionary to list of tuples. See my_old_sentence_splitter for changes.
Returns a list of namedtuples with the following fields:
... | fa30c5c670545bdd3afde7370b710f53827dff82 | 65,800 |
def as_float_x(x, exponent_bit_count, mantissa_bit_count):
"""
Modify mantissa and exponent number to convert float with given bit count.
"""
m, e = np.frexp(x)
m *= 2
e -= 1
max_exponent = 1 << (exponent_bit_count - 1)
min_exponent = -(max_exponent - 1) - mantissa_bit_count # Includes ... | e7fa0488008f970653b41ba4a01de5abd923861e | 65,801 |
def get_color_specifier(basecolor, number):
"""Build an OpenGL color array for the number of specified vertices."""
color = [float(x) for x in basecolor]
if len(color) == 3:
return ("c3d", color * int(number))
elif len(color) == 4:
return ("c4d", color * int(number)) | b7c14272aa393c66fdedc109b90f9c8fce6118b0 | 65,802 |
import os
import shutil
def create_temporary_copy(path, CONF):
"""Create a copy of a configuration YAML file"""
temp_path = os.path.join(DIR, 'temp_test.yaml')
shutil.copy2(path, temp_path)
with open(temp_path, 'r+') as conf_file:
conf = safe_load(conf_file)
conf["api"]["specs"][0]["pa... | f522f26f11ececc6b55f6fc5a594d7419941fa93 | 65,803 |
from typing import List
from typing import Tuple
def triangle(input_region: List[int]) -> Tuple[List[int], List[int]]:
"""Get coordinates of points inside a triangle
Args:
input_region (List[int]): Region in which to draw the triangle. [x1, y1, x2, y2]
Example:
>>> image = np.full((200,200,3... | aee3e9cfbb144bdedc981f849e35cc4eb1b88d74 | 65,804 |
def new_blog():
"""
Function that creates new blogs
"""
form = BlogForm()
if form.validate_on_submit():
category = form.category.data
blog = form.content.data
new_blog = Blog(content=blog, user=current_user)
new_blog.save_blog()
return redirect(url_for("mai... | 34b9b7b56d1817f919df419968ff29a9ed66d98d | 65,805 |
def generate_automorphism_dict(num_nodes, edges_range, directed=False, dtype=np.float64):
"""
Generate a dictionary with graphs belonging to the same isomorphism class.
:param num_nodes: int
:param edges_range: a generator with the integer number of edges to consider
:param directed: bool
:param... | 1380c04b0677c2a35b5ab2b52cf0f5041b5e46d7 | 65,806 |
def query_mesh(mesh_ids: list) -> dict:
"""Use biothings_client.py to query mesh ids and get back '_id' in mychem.info
:param: mesh_ids: list of mesh ids
"""
res = CHEM_CLIENT.querymany(mesh_ids, scopes='drugcentral.xrefs.mesh_supplemental_record_ui,ginas.xrefs.MESH,pharmgkb.xrefs.mesh', fields='_i... | ed04564f97d7784f14a21bf31757f6bd6e980929 | 65,807 |
def setscale(options):
"""
`setscale` sets the type of transformation to be used for subsequent GR output
primitives.
**Parameters:**
`options` :
Scale specification (see Table below)
+---------------+--------------------+
|OPTION_X_LOG |Logarithmic X-axis |
+--------------... | 8513044e9af320d8683c1b9fc40a91d272a1d40f | 65,808 |
def get_axis_box_sizes(efid, arg, axis):
"""
Returns the "box sizes", in "world" coordinate units,
for an axis of an argument to an external function
Arguments:
efid: the Ferret id of the external function
arg: the index (zero based) of the argument (can use ARG1, ARG2, ..., ARG9)
... | 6f3f59c908175f45d2c67ac655376cccbd22e631 | 65,809 |
def construct_graph(X, e, y, I, pid, norm_phi_min, delta, n_phi_sections, augmented):
"""Construct one graph (e.g. from one event)"""
""" Masks out the edges and hits falling within [phi_min, phi_min + delta_phi]"""
# Mask out phi segment edges and truths, leaving full hit list
seg_hits = (X[:,1] >... | 6a010a0679fa4dfaffae6d8279892e7165e97b23 | 65,810 |
from pathlib import Path
import hashlib
from datetime import datetime
import socket
import pprint
def single_run(parameters, elasticsearch_hostname, elasticsearch_port,
yaml_dir_prefix = "./output/pipelines/retriever"):
"""
Runs a grid search config
:param parameters: A dict with diverse config ... | f0abf802bc3f521cb121b58828ba6e63204dc98e | 65,811 |
from typing import Optional
from typing import Set
def sets(
elements: SearchStrategy[Ex],
*,
min_size: int = 0,
max_size: Optional[int] = None,
) -> SearchStrategy[Set[Ex]]:
"""This has the same behaviour as lists, but returns sets instead.
Note that Hypothesis cannot tell if values are draw... | 6e264597e0f6944fa38bfdbc280485769a9afb28 | 65,812 |
def Dm(n):
""" it creates forward difference matrix
n: number of rows/columns """
a = [1.,0.]
b = sp.zeros(n-2)
row1 = np.concatenate([a,b])
a = [1.,-1.]
col1 = np.concatenate([a,b])
D = sp.linalg.toeplitz(col1,row1)
return D | 4f5ee06ba3784ed3ed988089c44d093cc4b065de | 65,813 |
import os
def context_cache(func):
"""
A decorator to be used module functions which need to cache their
context.
To evaluate a __context__ and re-hydrate it if a given key
is empty or contains no items, pass a list of keys to evaulate.
"""
def context_cache_wrap(*args, **kwargs):
... | 56c55a78fe1eb6ad6f81305c0b50af92e16c9e3e | 65,814 |
def potts_crm(spin_counts, beta, tau):
"""
Computes the conditional rate matrix of a node based on the parent spins using Potts dynamics.
Parameters
----------
spin_counts : 1-D array, dtype: int
The nth element counts how many parents have spin n.
beta : float
Inverse Potts te... | 12648b2ec267403b9963dfcd45a2a8b7a3d044a3 | 65,815 |
import os
def list_files_in_folder(path, extension):
""" List all files in a directory using os.listdir """
files = []
for r, d, f in os.walk(path):
for file in f:
if extension in file:
files.append(os.path.join(r, file))
return files | 337277d7d03c8a48c61436e62155e6c1f59c639c | 65,816 |
import six
def finddir(o, match, case=False):
"""
return all attributes of *o* which match string in match. if case
is True require an exact case match.
"""
if case:
names = [(name, name) for name in dir(o)
if isinstance(name, six.string_types)]
else:
names = ... | d2eff57dfc0366a125c3079851985765ceada96d | 65,817 |
def C1(n):
""" integral related to first order finite Larmor radius effect
"""
c1 = poly2cheb([0,0,0,0,-1.5,0,2])
c2 = nthpoly(2*n)
kernel = chebmul(c1,c2)
cint = chebint(kernel)
return chebval(1,cint) | ff47f9b0ea7d4b6384ba17000209eaf9d777ffad | 65,818 |
def CreateAdvancedOptionsConfig(client, args, existing_advanced_options_config):
"""Returns a SecurityPolicyAdvancedOptionsConfig message."""
messages = client.messages
advanced_options_config = (
existing_advanced_options_config if existing_advanced_options_config
is not None else messages.SecurityP... | b242b32ba6733c41b1a53f269825c0f54bcf3f96 | 65,819 |
def update_track():
""" Send stream job to streamer with arguments contained in request.json
"""
global s
if s is not None:
disconnect()
s = StreamThread(args.key, args.rabbit_host, args.rabbit_port, **request.json)
s.start()
return Response(status=200) | 7b9161666c12a706ceec6991cf47d61b447be5d5 | 65,820 |
def _get_metadata_directory():
"""
Get the metadata directory from the user. The user
is asked to enter the directory, and if validated, is
returned to the caller. 'tuf.FormatError' is raised
if the directory is not properly formatted, and 'tuf.Error'
if it does not exist.
"""
metadata_dir... | 19c069bdb7ef590ce7060e9f6f2b074c0d90ac88 | 65,821 |
def concat(*args,**kwargs):
"""Concatenate multiple items together. Trap Occuring errors and log them without crashing.
"""
errorhandler = kwargs['errorhandler'] or raise_error
try:
return "".join(args)
except Exception as _E:
with open('error.wkzg.err','w') as f:
errorh... | 383d0d2870cd65d5d0feb4fada516f9fd52bb769 | 65,822 |
def insert(table, values, template='%({})s', col_conflict=None,
update_all=False, updates=None, where=None, returning=None):
""" Insert new values, with optional column conflict handling
Args:
table (str): database schema table to insert data into
values (dict): parameters to insert ... | 0e80c8ceb72b015681d63a0279f43dba2b61a05c | 65,823 |
def smooth(s,p0,p1):
"""
Do a boxcar average on a 1D dataset
:param v:
:return:
"""
result=s*0
count=0
for p in range(p0,p1):
result[-p0:-p1]+=s[-p0+p:len(s)-p1+p]
count+=1
result/=count
result[:-p0]=s[:-p0]
result[-p1:]=s[-p1:]
return result | 355252c5bd71447d043095de0d955d0f601dfd6d | 65,824 |
def simple_renderer(rn, meshes, yrot=0):
"""Create a renderer, optionally with texture."""
mesh = meshes[0]
if hasattr(rn, 'texture_image'):
if not hasattr(mesh, 'ft'):
mesh.ft = _copy(mesh.f)
vt = _copy(mesh.v[:, :2])
vt -= _np.min(vt, axis=0).reshape((1, -1))
... | 8525f841a147d9e5da039989a0efa8553c5f81bd | 65,825 |
def _unlParseNodePart(nodePart):
"""
Parse the Node part of a UNL
Arguments:
nodePart: The node part of a UNL
Returns:
unlList: List of node part parameters
in root to position order.
"""
if not nodePart:
if nodePart is None:
return None
... | 443c7f67b5deae47448bf93ff874acfb77cb83c3 | 65,826 |
def is_sbml_file(filename):
""" Determine whether a file is an SBML file
Args:
filename (:obj:`str`): path to file
Returns:
:obj:`bool`: whether the file is an SBML file
"""
try:
root = lxml.etree.parse(filename).getroot()
except Exception:
return False
ret... | f50ebdd21d23ed03d866734c2f7734ae1a4ea7bd | 65,827 |
def search():
""" Dataset Search Route
This route executes a dataset search
Args:
search is the search term in the GET Request
Retuns:
JSON containing the matching datasets
"""
return render_template('search.html', title='CONP | Search', user=current_user) | 9c3047ea2818e206f14267f54abe6af5f76bc531 | 65,828 |
def make_variant(chrom='chr1',
start=10,
alleles=None,
end=None,
filters=None,
qual=None,
gt=None,
gq=None,
sample_name=None,
gls=None,
is_phased=None... | 7e6e382fad8285523d88c49c3f31cdad6477fdc0 | 65,829 |
import random
def get_deck():
"""Returns a list of (rank, suit) tuples for all 52 cards."""
deck = []
for suit in (HEARTS, DIAMONDS, SPADES, CLUBS):
for rank in range(2, 11):
deck.append((str(rank), suit)) # Add the numbered cards
for rank in ('J', 'Q', 'K', 'A'):
... | 0ed1c1708ef972e4ed48c252badc9b81cca522f9 | 65,830 |
import os
def load_dataset(path_or_obj, index_col=[0, 1]):
"""load dataset from multiple file formats"""
if isinstance(path_or_obj, pd.DataFrame):
return path_or_obj
if not os.path.exists(path_or_obj):
raise ValueError(f"file {path_or_obj} doesn't exist")
_, extension = os.path.splitex... | 455898c96a557492a12ed290f5c6aa277459382a | 65,831 |
def most_provinces_list():
"""
:return: list of HOME_SEARCH_FILTER_LIST_LIMIT provinces with more artistprofiles
"""
artistprofiles_per_province = []
for province in ArtistProvince.objects.annotate():
num_profiles = ArtistProfile.objects.filter(provinces=province).count()
artistprofi... | 24a67e90e4fba94ecd22911edb620fed89daf0cc | 65,832 |
def dnsflow_eth(eth):
""" Check if dpkt.loopback.Loopback represents DNSFlow """
dnsflow = False
if eth.type != dpkt.ethernet.ETH_TYPE_IP:
return dnsflow
ip = eth.data
if ip.p == IP_PROTO_UDP and ip.data.dport == DNSFLOW_PORT:
dnsflow = True
return dnsflow | d5f09f59798c20ec11c86f6d84cada3dfbf6a721 | 65,833 |
import re
def is_valid_identifier(x: str) -> bool:
"""Check whether `x` is a valid identifier
Check whether `x` is a valid identifier for conditions, parameters,
observables... . Identifiers may contain upper and lower case letters,
digits and underscores, but must not start with a digit.
Argume... | e8776c8b988fc73925e8ce600de4de4230aad363 | 65,834 |
def require_drone(handler_method):
"""
A decorator to ensure the request is made as a drone.
Will also ensure superuser, which is implied with a drone request.
"""
def check_drone(self, *args, **kwargs):
if self.origin.get('type', '') != Origin.device:
raise APIPermissionExcepti... | c57c5a8b9156876d6a3dfb1760b1b839080022f8 | 65,835 |
def check_couch():
"""Confirm CouchDB is up and running, by hitting an arbitrary view."""
results = Application.view('app_manager/builds_by_date', limit=1).all()
assert isinstance(results, list), "Couch didn't return a list of builds"
return ServiceStatus(True, "Successfully queried an arbitrary couch v... | e9c8292ebd148d62db54dbaea9326764743ed48d | 65,836 |
import copy
def randomise_infection(nodes, nhigh=0, nlow=0, nrand=0, single_loc=True, node_choice=None):
"""Initialise randomised infection in nodes, infecting inf_prop of susceptibles or ninf.
If single_loc is True, then infecteds will be clumped in individual nodes, otherwise randomly
positioned over l... | dab6159fbdda907bd42ab21ad9a4eb4dfe5aa294 | 65,837 |
def extract_raster_by_shape_file(raster: str, shape_file: str, output_file=None):
""" 抽取 GeoTIFF 文件中的给定区域数据,返回数组
Parameters
----------
nodata: 指定 nodata 的值, 不在抽取范围内的值被标记为 nodata
output_file: 输出 .tif 文件路径, None 不输出
raster: .tif 文件的路径,要求坐标系为 WGS84 (EPSG:4326)
shape_file: .shp 文件的路径,要求坐标系为 WGS8... | 00d2285f344d472124ae1016060a0f5f17f452c8 | 65,838 |
import sys
def _cite_cmd(options):
"""
Return the post setup hook function for `openmdao cite`.
Parameters
----------
options : argparse Namespace
Command line options.
Returns
-------
function
The post-setup hook function.
"""
if options.outfile is None:
... | c7c1e61be107cde9d422b1c8df50a6997aab1243 | 65,839 |
def nextContest(intent, session):
""" Get the next contest details and prepares the speech to reply to the user.
"""
if 'WebsiteName' in intent['slots']:
website = intent['slots']['WebsiteName']
if 'value' in website:
website = website['value']
if website.lower() == "... | 3fbe3e846f55a6ec86a869fb0161ec4ba5e3de30 | 65,840 |
def seq(*args, **kwargs):
"""
seq(n1, n2, base=, by=, length=, ztol=)
Minimum number is 1 and maximum number of args is 2.
Any misspecification will result in an empty list.
Current version has no extensive error checking!
"""
# Undefined key?
unknownKeys = [key for key in... | 9536db09297be313c1177d6a2283fa421a1a4a3f | 65,841 |
def subtrace(trace, chains, reset_chains=True):
"""Get Multitrace with subset of chains from a super Multitrace"""
if type(chains) is int:
chains = [chains]
elif type(chains) is not list:
raise TypeError('chains is of type {}. Expected int or list of int')
straces = []
for chain in c... | 65fb2e6ef6ad637737e17f8145f9098738095206 | 65,842 |
def make_result_files(combinations):
"""
_result_*.csv を収集し result_files を作成する
yamlで指定された result_directory:
result_directory: <somepath>/{config}/{feature}/{net}/{fit}/{decision}
にある
anomaly_score_path()関数で定義されるファイル:
anormaly_score_{machine_type}_section_{section_name}_{target_dir}.... | 902b8e342c1fde5357dc0bb1eddec6f81be6a120 | 65,843 |
def convert_enum(enum_list, is_set_data_validation):
"""
导出enum入口函数
Args:
enum_list: [list]每一项是要导出的enum目录的完整路径
is_set_data_validation: [bool]是否为引用excel设置数据验证
Returns:
bool是否成功
"""
ec_converter.logger.info('开始对下列enum目录执行导表程序:\n%s', '\n'.join(enum_list))
if is_set_data... | 3146e3db299cca68800ebf027bf1ae3a2d72a0a3 | 65,844 |
def get_crimes_and_residents(crimes, residents):
"""This function takes the crimes and residents data frames and returns a dataframe with the crime / residents ratio"""
crime_and_residents = pd.merge(residents, crimes, on='MSOA', how='inner')
crime_and_residents['ratio'] = crime_and_residents.apply(lambda r... | 61469797338ea48a3009dd939de624d80f8d6cd5 | 65,845 |
from re import X
from re import I
def meyer_penny_program():
"""
Returns the program to simulate the Meyer-Penny Game
The full description is available in ../docs/source/exercises.rst
:return: pyQuil Program
"""
prog = pq.Program()
ro = prog.declare("ro", memory_size=2)
picard_registe... | 586e4c542f7b2a6f9844bdb6764e8a9671496e8e | 65,846 |
def qnorm(p) -> Float64Expression:
"""Inverts :meth:`.pnorm`.
Examples
--------
.. doctest::
>>> hl.eval_expr(hl.qnorm(0.90))
1.2815515655446008
Notes
-----
Returns left-quantile `x` for which p = Prob(:math:`Z` < x) with :math:`Z` a standard normal random variable.
`p... | f3c2becd1c333399a2f0146eef5aa735cecfd77f | 65,847 |
def _build_cam_images():
""" Create new thumbnail images based on large format index.
"""
try:
print '\n-- Generating thumbnails for cam_images cache...'
data = _compile_cam_images()
if not data or data is None:
data = []
return data
except Exception as err:
... | 082c2c2715de8a712c98e9c13598509b7e6a66ce | 65,848 |
import requests
import json
def query_es(query, es_index=None):
"""Query ES."""
uu = UrlUtils()
es_url = uu.rest_url
rest_url = es_url[:-1] if es_url.endswith('/') else es_url
url = "{}/_search?search_type=scan&scroll=60&size=100".format(rest_url)
if es_index:
url = "{}/{}/_search?sear... | cb85fb85c88be17cd92e5c815da998e331dd57d2 | 65,849 |
def create_obj(class_, *args, **kw):
"""Create an object of class and fire created event."""
obj = class_(*args)
zope.event.notify(zope.lifecycleevent.ObjectCreatedEvent(obj))
for attrib, value in kw.items():
setattr(obj, attrib, value)
return obj | 66db30195e1c38c44c29b54546775a0aa92f80ae | 65,850 |
def course_list(request):
"""
获取所有课程信息或新增一个课程
:param request:
:return:
"""
if request.method == "GET":
course = CourseSerializer(instance=Course.objects.all(), many=True)
return Response(data=course.data, status=status.HTTP_200_OK)
elif request.method == "POST":
cours... | 243bf684cf9bfa0a2c93c24120d24454906aac2d | 65,851 |
from codebay.l2tpserver import licensemanager
from codebay.l2tpserver import helpers
from codebay.l2tpserver.webui import uihelpers
from datetime import datetime
def _update_snmp():
"""Update SNMP data."""
now = datetime.datetime.utcnow()
st = helpers.get_status()
global_st = helpers.get_global_stat... | 9d8c1d1b6e3c38edd651a106b41496d3433c42a8 | 65,852 |
def postproc_y_hat(pred_flows, adapt_info=None):
"""Postprocess the results coming from the network during the test mode.
Here, y_hat, is the actual data, not the y_hat TF tensor. Override as necessary.
Args:
y_hat: predictions, see set_output_tnsrs() for details
adapt_info: adaptation infor... | d93109e0c6a902dafb79dc1a9d6dbe73f29dc970 | 65,853 |
import re
import sys
def prompt(prompt_text):
""" Prompt the user to choose one of the choices
Choices are identified in the prompt_text by square brackets around
a single letter option.
"""
choices = set(m.group(1) for m in re.finditer(r"\[(.)\]", prompt_text))
while True:
sys.stderr... | 1df7ea9797b72e07b31f9eef4d2095bb8b591c8d | 65,854 |
def calc_raid_partition_sectors(psize, start):
"""Calculates end sector and converts start and end sectors including
the unit of measure, compatible with parted.
:param psize: size of the raid partition
:param start: start sector of the raid partion in integer format
:return: start and end sector i... | a96e442d5915a108fbbf18838e2c4a311677eced | 65,855 |
def chunks(sentences, number_of_sentences):
"""
Split a list into N sized chunks.
"""
number_of_sentences = max(1, number_of_sentences)
return [sentences[i:i+number_of_sentences]
for i in range(0, len(sentences), number_of_sentences)] | a11c06c60e2230b611fd669a1342e17970e27ba5 | 65,856 |
def offset_7p(accel, tau):
"""Offset function corresponding to acceleration term, see BAS-045 Eq. 2
Note that accel is given in mas/year**2 whereas tau is in days. Therefore a conversion factor
has to be applied at the end.
Parameters
----------
accel : float
accel_ra or accel_dec in [... | bcf888ca670920194c40a7d9d3959c2804cadd9a | 65,857 |
def pad_data(X, Y, max_len, PAD_symbol=0):
"""
Pad data up till maximum length and create masks and lists of sentence lengths
:param X:
:param Y:
:param max_len:
:return:
"""
#print "to pad", X[0], Y[0]
feature_size = len(X[0][0])
#print "feature size", feature_size
seq_lens ... | f17a5b5ce4999327e8cfeab32a44136610819bda | 65,858 |
def cbServerGreeting(proto, username, password):
"""
Initial callback - invoked after the server sends us its greet message.
"""
# Hook up stdio
tp = TrivialPrompter()
stdio.StandardIO(tp)
proto.prompt = tp.prompt
proto.display = tp.display
return proto.login(username, password
... | 0fef295c90f53ae7a2e70b0a61a980ee6d1191bb | 65,859 |
import torch
def pos_def(ws, alpha=0.001, eps=1e-20):
"""Diagonal modification.
This method takes a complex Hermitian matrix represented by its upper
triangular part and adds the value of its trace multiplied by alpha
to the real part of its diagonal. The output will have the format:
(*,2,C+P)
... | f18cc9087d8ad0cef859b57d524b453ad11dd429 | 65,860 |
def split_morph_pos(morph):
"""
splits morph into the 'pos' and 'morph' strings for db search
"""
string2morph_id = get_morph_dict()
if isinstance(morph, str) and morph != None:
morph_list = morph.split(',')
if morph_list[0] in string2morph_id.keys():
pos = str(string2mor... | 82ce8d908fc3ca9ee1e6664b476e7ee4fd651f85 | 65,861 |
import http
import json
def get_movie_data(title):
"""Downloads movie data from imdbapi.com.
Returns a dictionary with the movie's data."""
# Create a connection object that will talk to the server.
server = "www.omdbapi.com"
connection = http.client.HTTPConnection(server)
# Quote the strin... | b9a9ace965dfb5af3f765970d18f9c71b5e6e081 | 65,862 |
def get_scores(args, folder, policy_file, env_name, algo, stats_path, hyperparams, n_evals):
"""
"""
env = create_test_env(
env_name,
n_envs=10,
stats_path=stats_path,
seed=args.seed,
log_dir=folder + "/../Logs",
should_render=not args.no_render,
hyper... | 9c03bd19566a2a26491cc2d4f027536c61b738c9 | 65,863 |
from scripts.engine.internal.data import store
from typing import Tuple
def get_tile(tile_pos: Tuple[int, int]) -> Tile:
"""
Get the tile at the specified location. Raises exception if out of bounds or doesnt exist.
"""
game_map = store.current_game_map # not using get_game_map for performance
a... | 68dd14e1fec1d2150dde8bab8b3e1f48dbd2bae3 | 65,864 |
from typing import Type
from typing import Callable
from typing import Any
from typing import List
def command(config: Type[BaseSettings], delimiter: str = ".", internal_delimiter: str = "__") -> Callable:
"""Decorator that transforms a given function into a click command, using as arguments a pydantic model.
... | b4f6238bd4f2518f1520f83fc86066b857fa86ba | 65,865 |
def test3():
"""test 3
Returns:
str: transportation plan
"""
a = [20, 11, 18, 27]
b = [11, 4, 10, 12, 8, 9, 10, 4]
c = [[-3, 6, 7, 12, 6, -3, 2, 16],
[4, 3, 7, 10, 0, 1, -3, 7],
[19, 3, 2, 7, 3, 7, 8, 15],
[1, 4, -7, -3, 9, 13, 17, 22]]
return matrix_tran... | 0bb86ffb8477453665eef346c0fa0c76f190758c | 65,866 |
import torch
def cfg_sample(model, steps, eta, method="ddim", batchsize=1):
"""Draws samples from a model given starting noise."""
_, side_y, side_x = model.shape
zero_embed = torch.zeros([1, model.clip_model.visual.output_dim], device=model.device)
target_embeds, weights = [zero_embed], []
def... | 750cb34e088cbe1daa4ff08b79e41ecc02853e0f | 65,867 |
def intro_binary_logic(
masks,
):
"""
Mask to dilated intro-channel binary or-logic.
Dilate mask -> compute or-logic
"""
def _mask_or_logic(
dilated_mask
):
c, h, w = dilated_mask.shape
or_logic = [
[
(
(dilated_mask[i]*... | 1ab7738a34814768d3ec14cd1ca2129f77624747 | 65,868 |
def add_user_db(user: User) -> bool:
"""
Adds a new user to the database.
:param user: User object to add to database
:return: True if added, else False if error.
"""
# If request didn't specify permissions, ensure that none are stored in the database.
if user.roles is None:
roles ... | a657abf98efcab5ee646be244107fa6f143afccb | 65,869 |
import os.path
import re
import h5py
import quaternion
import pprint
import warnings
def read_from_h5(file_name, **kwargs):
"""Read data from an H5 file in SXS format
Note that SXS format is essentially compatible with NRAR format. The existence of this function is not to be
taken as the author's endors... | a178be1ca054a2ed97cc2b3c7c2a1c08d5b0c694 | 65,870 |
import statistics
def ping_statistics(data):
"""
Render result statistics
:return: str result string
"""
TEMPLATE = """--- {hostname} ping statistics ---
{packet} packets transmitted, {packet_received} packets received, {packet_lost:.1f}% packet loss"""
RTT_TEMPLATE = """\nround-trip min/avg/m... | 1ba4977f6c70dd0719bb5b1d5301795b3ca0ad6a | 65,871 |
from typing import Optional
def inverse_from_cholesky_band(
lower_band: LowerTriangularBandedMatrixTensor, result_lower_bandwidth: Optional[int] = None
) -> LowerTriangularBandedMatrixTensor:
"""
Given a lower-banded matrix L that is assumed to be the Cholesky
decomposition of a (symmetric, Positive D... | 208f62bc747ee0fd2444ea62f456e0f3572afe5f | 65,872 |
import requests
def webhook_post(url, event_dict):
"""Posts an event to the supplied URL.
The request body is a JSON dictionary of:
* type: webhook message type (currently always 'event')
* event_dict: webhook data (the event payload)
Event payloads are in the same format as the /api/events/... | a8bdcce66cf272835e3b77b659c8b063eab51ebd | 65,873 |
import json
def process_settings(default_settings, user_settings_string=""):
"""Combine the default settings with any user settings.
Process the user settings and override the default if a corresponding user
setting exists. Print a warning if a there is a missing user setting.
Parameters
-------... | 8bfc0de7fd61f77cccdffe3101699b9a8ee0f264 | 65,874 |
def dot_s(inputa,inputb):
"""Dot product for space vectors"""
return inputa[:,0]*inputb[:,0] + inputa[:,1]*inputb[:,1] + inputa[:,2]*inputb[:,2] | 7991192fa07b953cd2e8e3d5439769eebf0e1608 | 65,875 |
import time
def utc2datetime(_utc, _format="%Y-%m-%d %H:%M:%S"):
"""
UTC转datetime
"""
return time.strftime(_format, time.localtime(int(_utc))) | 992304ee88c99bf81734b8bf473fe8359810a843 | 65,876 |
def pla(args, random_seeds, train_data, test_data):
"""
Perceptron Learning Algorithm
:param args:
:param train_data:
:param test_data:
"""
err = np.zeros((int(args['n_epochs']), 1))
train_loss = np.zeros_like(err)
test_loss = np.zeros_like(err)
for seed in random_seeds:
... | 14224d2e2eb0de0b71622792b08c31b7b49bd070 | 65,877 |
import pickle
def pickle_serialize(data):
"""
Serialize the data into bytes using pickle
Args:
data: a value
Returns:
Returns a bytes object serialized with pickle data.
"""
return pickle.dumps(data) | 9c8809ab7bbd0375e9d94d6baae95e26166e6c56 | 65,878 |
from typing import Iterable
import os
def create_line(array: Iterable, sep: str) -> str:
"""create row of results file"""
safe_array = [str(item) if item is not None else "" for item in array]
return f"{sep.join(safe_array)}{os.linesep}" | b855f1aed5960a3114c8c0f72d3446116e83d800 | 65,879 |
def _open_close_position_condition(df):
"""
找出开、平仓的K线
"""
hold_pos_cond = df[POSITION_COLUMN] != 0 # 持仓
open_pos_cond = df[POSITION_COLUMN] != df[POSITION_COLUMN].shift(1) # 当前周期和上个周期持仓发生变化为开仓
open_pos_cond = hold_pos_cond & open_pos_cond
close_pos_cond = df[POSITION_COLUMN] != df[POSITION... | 547ce81c439f8d2c0db793fc767cdd05bd6221de | 65,880 |
import json
from datetime import datetime
from typing import Counter
def update_personalchat(dropdown_users, start_date_str, end_date_str, interval1, interval2, datasets):
"""Update displayed data and chart at first and when filter apply."""
datasets = json.loads(datasets)
df = pd.read_json(datasets['data... | 42c5222bc9704ea753bc02f5ce0228f5a2257922 | 65,881 |
import os
def strip_id_from_video(path, s):
"""get the id of the video from a video's path"""
partial_split = path.split(os.sep)[-1].rsplit(".")[0]
delimiter = s['delimiter-between-multiple-videos']
if delimiter in partial_split:
partial_split = partial_split.split(delimiter)[0]
partial_... | e507898ccc6d974be428adf2842197d4f2c4c139 | 65,882 |
def edit_profile_processing(request: object, profile_change_form: object) -> object:
"""Change user data in profile."""
user = User.objects.get(email=request.user.email)
user.email = profile_change_form.cleaned_data.get('email')
if profile_change_form.cleaned_data.get('avatar') != 'images/profiles/anon... | 9c446353d007c4fd517c1758adbb41f36b669c9c | 65,883 |
def _find_serving_with_name(serving_name, servings):
"""
Finds a serving with a given name from a list of servings (O(N))
Args:
:serving_name: name of the serving to look for
:servings: the list of servings to look through
Returns:
serving with the given name
Raises:
... | ad881783a8a3605878c5a1ae28c37a60367e90f9 | 65,884 |
import os
import logging
def create_tf_model(model_path, flags):
"""Returns the appropriate Model implementation based on env vars."""
engine = os.environ.get("prediction_engine",
MODEL_SERVER_ENGINE_NAME)
if engine == MODEL_SERVER_ENGINE_NAME:
logging.debug("Starting model server ... | b640061759372e09e743d5910c1e80ce6c99d4ab | 65,885 |
def blurred_images_of_images_and_planes_from_1d_images_and_convolver(total_planes, image_plane_images_1d_of_planes,
image_plane_blurring_images_1d_of_planes, convolvers,
map_to_scale... | 1a9f898916a282e8ccfb356d22ff7fae21d04907 | 65,886 |
def parse_protein(seq):
"""Return a list of protein numbers that are human proteins.
Example
-------
"PROTEIN\nPR\t#8# Homo sapiens\n<10,11,273>\nPR\t#9# Rattus norvegicus <10,49,50,51,142,167,224,228>"
-> ["8"]
"""
seq = seq.split("\nPR\t") # PR is the identifier for proteins
... | b694b8711e86d5501f9d1623a063abd1c9a4da84 | 65,887 |
def significance(size_a, successes_a, size_b, successes_b):
"""
Calculates the significance for an A/B test.
:param size_a: Sample size of the experiment A
:param successes_a: Successes of the experiment A
:param size_b: Sample size fo the experiment B
:param successes_b: Successes of the e... | 67b0ed642a339c076457c3e0b659769ddac1210c | 65,888 |
def update_api_release(instance, notes=None):
"""Updates the details of the release of the API specified by its identifier."""
instance.notes = notes
return instance | 0aada7780ad9f9d492dbb4611a79cee8538be279 | 65,889 |
def edit_diff(start, goal, limit):
"""A diff function that computes the edit distance from START to GOAL.
>>> edit_diff("ash", "hash")
1
>>> edit_diff("roses", "arose") # roses -> aroses -> arose
2
>>> edit_diff("tesng", "testing") # tesng -> testng -> testing
2
>>> edit_diff("rlog... | 4016eca481c208fd39b028a4d267d5afb014bbe0 | 65,890 |
def time2milliseconds(the_time):
"""
Converts the time part of a datetime to milliseconds.
"""
result = 0
if the_time:
result += the_time.hour
result *= 60
result += the_time.minute
result *= 60
result += the_time.second
result *= 1000
return 0 | 5825fed1c9d64db5f145a73a158a5cb79d6065f7 | 65,891 |
def strip_cstring(data: bytes) -> str:
"""Strip strings to the first null, and convert to ascii.
The CmdSeq files appear to often have junk data in the unused
sections after the null byte, where C code doesn't touch.
"""
if b'\0' in data:
return data[:data.index(b'\0')].decode('ascii')
... | c315e84debe7eef239afd4c856d45f4d2a776af2 | 65,892 |
def model_format_args(model, pars):
"""Format the model and parameter args to save in output file.
Change to int, str and float.
model in [temp, logg, fe/h, alpha]
pars in order (R, band, vsini, sample).
Can now also optionally handle a 5th parameter RV.
"""
temp = int(model[0])
logg ... | 118a10c3670399c365c608d9ebfce7d48edb84fb | 65,893 |
def outlet_map(da_flw, ftype="infer"):
"""Returns a mask of basin outlets/pits from a flow direction raster.
Parameters
----------
da_flw: xr.DataArray
Flow direction data array
ftype : {'d8', 'ldd', 'nextxy', 'nextidx', 'infer'}, optional
name of flow direction type, infer from dat... | 0e64a214141ff6f82e3ee6295b2339d0ad92b29a | 65,894 |
from bs4 import BeautifulSoup
from typing import List
from datetime import datetime
def _get_novels_from_category_page(category_page: BeautifulSoup) -> List[ShortNovel]:
"""
Given a beautiful soup which correspond to a page of favorit return a list of novels
:param category_page:
:return:
"""
... | 0b63671c7a40cfcd452cef161e1b0af2ccf6618b | 65,895 |
import requests
import json
def install_geolocation_update(uri, token, zip_file):
"""
Makes a temp directory, copies zip, unzips archive and installs each of the
geolocation RPMs
Parameters
----------
uri : str Base URL to call api
token : str Valid access token for this API end... | 2e0f544d9d640e443ac2d834cad142ffb1f22b40 | 65,896 |
from typing import Optional
from typing import Union
import types
def set_bandit_policy_type(
info: Optional[Union[PolicyInfo, PerArmPolicyInfo]],
bandit_policy_type: types.Tensor) -> Union[PolicyInfo, PerArmPolicyInfo]:
"""Sets the InfoFields.BANDIT_POLICY_TYPE on info to bandit_policy_type.
If policy `... | 7c7cbc4795556512605da5ac0f4736b4d4aa4c00 | 65,897 |
def pos_record_generate(d: dict):
"""持仓记录生成器"""
pos_record = PosRecord(
code=d['code'],
exchange=d['exchange'],
account_id=d['account_id'],
first_buy_date=d['first_buy_date'],
last_sell_date=d['last_sell_date'],
max_vol=d['max_vol'],
buy_price_mean=d['buy_... | e38e87e4e43ba144cad4c1bc79c3149879a68cc4 | 65,898 |
def FlatArrow(line1, line2, c="r4", alpha=1, tipSize=1, tipWidth=1):
"""Build a 2D arrow in 3D space by joining two close lines.
|flatarrow| |flatarrow.py|_
"""
if isinstance(line1, Points): line1 = line1.points()
if isinstance(line2, Points): line2 = line2.points()
sm1, sm2 = np.array(line1[-... | 864524846214ce009b26f236d7fa70a438d65a56 | 65,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.