content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def toBytes(text, encoding=DEFAULT_ENCODING):
"""
Converts the inputted text to base string bytes array.
:param text | <variant>
:return <str> || <bytes> (python3)
"""
if not text:
return text
if not isinstance(text, bytes_type):
text = text.encode(encodin... | 1220ba953b2a0bf4d701c058f9626a340aefef51 | 65,756 |
def knapsack_iterative(items, bag_capacity):
"""
Uses dp to find optimal solution to the one-zero (either take or leave)
knapsack problem
:param items: assumed given as a tuple of (space_it_takes_up, value)
:param bag_capacity: given as an integer of the capacity of the bag
:return: maximised va... | 65872a23762d314dac2c357ba0941142237eaedb | 65,757 |
import scipy
def my_rq(M):
"""RQ decomposition, ensures diagonal of R is positive"""
R,K = scipy.linalg.rq(M)
n = R.shape[0]
for i in range(n):
if R[i,i]<0:
# I checked this with Mathematica. Works if R is upper-triangular.
R[:,i] = -R[:,i]
K[i,:] = -K[i,:]
... | 31a23cbb2c673d00d753ab92de4e369167b3930a | 65,758 |
def change_time_units(times, value, operation='divide'):
"""Change the units of timestamps.
Parameters
----------
times : 1d array
Vector of timestamps to update.
value : float
Value to divide / multiply by.
operation : {'divide', 'multiply'}
Operation to apply.
"""
... | f698d78a68d5056cf3864c47b29ed0e347b5aa4c | 65,759 |
from ..database import UserVote
def vote_exists(user, uri):
""" Check if a vote from this user for this track already exists. """
vote = db.session.query(UserVote).filter(UserVote.uid == user.id, UserVote.uri == uri).first()
return vote | 160c2b18a2dc7f880c800e2e436db9884bd97e9e | 65,760 |
from typing import Optional
from typing import Dict
from typing import Any
import time
import requests
def get_request_time(url: str, params: Optional[Dict[str, Any]] = None) -> Optional[float]:
"""timeit GET request"""
try:
start = time.monotonic()
requests.get(url, params=params)
ret... | ae99e5f706aed51c17634f92125cb2f0fe66be76 | 65,761 |
def zero_(x):
"""
**Notes**:
**This API is ONLY available in Dygraph mode**
This function fill the Tensor with zero inplace.
Args:
x (Tensor): ``x`` is the Tensor we want to filled with zero inplace
Returns:
x (Tensor): Tensor x filled with zero inplace
Examples:
... | 11eec580f6206086c6e0a8397187a33996849fed | 65,762 |
def build(options, is_training=False):
"""Builds a Model based on the options.
Args:
options: a model_pb2.Model instance.
is_training: True if this model is being built for training.
Returns:
a Model instance.
Raises:
ValueError: if options is invalid.
"""
if not isins... | 7cd3c00ad4fb661e2e1e9fb87e47666c8fd6a8e5 | 65,763 |
import re
def get_cluster_info(host, port):
"""
return dict with info about nodes in cluster and current version
{
'nodes': [
'IP:port',
'IP:port',
],
'version': '1.4.4'
}
"""
client = Telnet(host, int(port))
client.write(b'version\n')
re... | 0d4d79738c31ed770164652764577ad31690c101 | 65,764 |
def get_alpha(A,VMR,rhoe,ze):
"""
Calculate Absorption optical depth profile
A - absorption coefficient [m2/molecule]
VMR - trace gas mixing ratio [vol/vol, dimensionless]
rhoe - air number density [molecules/m3]
ze - profile altitude [m]
"""
# convert vmr to molecules/m3
nxe = VMR... | 88328687e96b535e202c5a1b5421ed09ae25adc4 | 65,765 |
import random
import string
def generate_callback_token():
"""
Generate a token and store it in the callback token file
:return: the token
"""
token = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(64))
with open(callback_token_file, "w") as fp:
fp.write(... | 7ea24be7c724fbf9eb783da89a5677b2caa455d2 | 65,766 |
def check_AIC_base10_checksum(AIC):
"""Check if a string checksum char in the base10 representation is correct.
Parameters
----------
AIC : str
The string containing the code to check
Returns
-------
bool
True if the checksum is correct.
"""
return AIC[-1] == calc_A... | 7a5b8f37bf2737b1a78050489d9212e0715b3ef0 | 65,769 |
import json
def getUrnJson(data):
"""Returns URN to entity in JSON data"""
decodedJson = json.loads(data)
return decodedJson["urn:lri:property_type:id"] | af1761acb9322f295af3500cc4ecc519da16d7b1 | 65,770 |
import math
def _uiconm(x, window_size):
"""
Underwater image contrast measure
https://github.com/tkrahn108/UIQM/blob/master/src/uiconm.cpp
https://ieeexplore.ieee.org/abstract/document/5609219
"""
plip_lambda = 1026.0
plip_gamma = 1026.0
plip_beta = 1.0
plip_mu = 1026... | 84ffa2d9291cbb926a1d123a6ff93fe2974d14ca | 65,771 |
from re import T
def _are_equal_or_one_is_empty(l1: tuple[T, ...], l2: tuple[T, ...]) -> bool:
"""Determine whether the two tuples are equal or one is the empty tuple."""
return (
l1 == l2 or (len(l1) == 0 and len(l2) > 0) or (len(l1) > 0 and len(l2) == 0)
) | 1c6e5319f42a9006558c16469997f26011939100 | 65,772 |
def type_to_str(_type : type | tuple, sep : str =" or "):
"""
Converts type or tuple of types to string
e. g. <class 'bin_types.functions.Function'> -> function
For tuples will separate types with argument sep, standard sep is " or "
"""
if isinstance(_type, tuple):
types = []
... | 04589e24aef9db1d302b8d4d439d7d5e1ba70e49 | 65,773 |
def scale(X):
"""データ行列Xを属性ごとに標準化したデータを返す"""
# 属性の数(=列の数)
col = X.shape[1]
# 属性ごとに平均値と標準偏差を計算
mu = np.mean(X, axis=0)
sigma = np.std(X, axis=0)
# 属性ごとデータを標準化
for i in range(col):
X[:,i] = (X[:,i] - mu[i]) / sigma[i]
return X | 61e2d935a08262d7c669719eb3055cd6704d1405 | 65,774 |
def make_storage(storage_type: str) -> Storage:
"""Storage factory."""
return STORAGE_MAP[storage_type]() | c652973660735fbca28bfc5921e54f499ae5e29f | 65,775 |
import json
def load_evaluate_metrics(workspace: str):
"""Load and return metrics."""
filepath = workspace_path(workspace, "metrics/evaluate_metrics.json")
with open(filepath, "r") as f:
data = json.load(f)
data["loss"] = float(data["loss"])
data["accuracy"] = float(data["accuracy"])
... | 33e98e8bbfcf9dd4a0707ed1c820250bffa00d9e | 65,776 |
def get_total_pages(items):
"""
returns the total number of pages for a list of serialized items
"""
items_per_page = 12
if len(items) % items_per_page == 0:
return int(len(items) / items_per_page)
pages = int(len(items) / items_per_page + 1)
return pages | 8e2b0a33f6c462e3f38d24643968bd5ed265d1a9 | 65,777 |
import time
def file_upload_to(instance, filename):
"""
文件上传相对路径
:param instance: 实例
:param filename: 文件名
:return: 上传的文件路径
"""
# 传过来的实力,需要有个user_id的值,用户ID
print(instance.user_id)
name = 'file/{}/{}_{}'.format(time.strftime('%Y/%m'), instance.user_id, filename)
return name | a24fc844c6d469cd66af4a5ade3e526781fc53c7 | 65,778 |
def dot(v, u):
"""v and u are vectors. v and u -> list"""
vx, vy = v[0], v[1]
ux, uy = u[0], u[1]
dotproduct = vx*ux + vy*uy
return dotproduct | b9a8794ff98787b7ae8e8c1420a375360abb34fa | 65,779 |
def parse_update(expression):
""" parsing something like "update some_table set (x,y,z) where a = 30;" """
pattern = 'update\s+(.*?)set(.*?)\s*(where\s(.*?)\s*)?;'
m = match(expression,pattern)
tables = m.group(1)
columns = map(str.strip,split_if_not_none(m.group(2), ","))
clauses = split_if_not... | 53e5e65410ab8c350c325528b0e01cc5d23a4a3d | 65,780 |
from typing import OrderedDict
def map_ascii_to_range_ordered(range_length):
"""
performs the same calculation as above, with difference of ordering the output as it came in
>>> map_ascii_to_range_ordered(5)
>>> OrderedDict([('a', 0), ('b', 1), ('c', 2), ('d', 3), ('e', 4)])
:param range_length: l... | 07934277e7a920dad4bb0a3512e7efa2219ef85a | 65,781 |
def inv_entry_to_path(data):
"""
Determine the path from the intersphinx inventory entry
Discard the anchors between head and tail to make it
compatible with situations where extra meta information is encoded.
"""
path_tuple = data[2].split("#")
if len(path_tuple) > 1:
path_str = "#... | 2c36c3a5755d7f82da534d417cc8350c96e0360a | 65,782 |
def construct_feature_columns(input_features_num=None, input_features_cat=None,
feature_type=['numerical','cat_with_identy','cat_with_hash_bucket',
'cat_with_vocab_file','cat_with_vocab_list']):
"""Construct the TensorFlow Feature Columns.
Args:
input_features_num: The na... | c60c66d4632cdd01af0777ac1dbbcd5525a030c8 | 65,783 |
import bisect
def where(start,end,arr):
"""Find where the start location and end location indexes in an array"""
astart = bisect.bisect_left(arr, start)
aend = bisect.bisect_right(arr[start:], end) + start
return astart, aend | c942a3d8f681a81e8bb473724e25f5dd980aa338 | 65,784 |
import requests
def twitter_data(access_token, screen_name):
"""
This function gets information about user from Twitter.
"""
base_url = "https://api.twitter.com/"
search_headers = {
'Authorization': 'Bearer {}'.format(access_token)
}
search_params = {
'screen_name': screen... | f72a06f9939544d45db2b0e09a0bba02a1f00294 | 65,785 |
def get_config():
"""Get the default hyperparameter configuration."""
config = ml_collections.ConfigDict()
config.batch_size = 128
config.test_batch_size = 1000
config.epochs = 20
config.seed = 1
config.train_mc_iters = 2500
#config.train_mc_iters = 2500
config.s_init = 0.27
config.eta = 1.
con... | 727ea85ca308a7b8905c9a66659e47ac631764e7 | 65,786 |
from typing import get_args
import json
def setup_model_and_optimizer(model, optimizer, train_dataset_provider, lr_scheduler_builder):
"""Setup model and optimizer."""
args = get_args()
if optimizer is None:
optimizer = get_optimizer(model)
lr_scheduler = get_learning_rate_scheduler(optimizer,... | 48ac38ce06c47ed02a8d829ebff848d015af5afc | 65,787 |
def win_segmentation(x,n_win,overlap):
"""
Segment time series x into windows of n_win points with an overlap of overlap
Parameters
----------
x: ndarray of shape (samples,)
Time series
n_win: integer
Number of data points per window
overlap: float
Percentage o... | d97e3d6ef5a3db958141eeaeae95f5b4dff54217 | 65,789 |
def decode_powerset_labels(y):
"""Decode the label and return a binary array. Assumes the labels are encoded
the in the FastTest format: __label__x"""
def decode_label(label):
split_label = label.replace('__label__', '').split('_')
return list(map(_int_or_str, split_label))
return np.arr... | df4753d596fbbf5ffee8931bfbe2365fc8955f70 | 65,791 |
from typing import Optional
from typing import Dict
def get_book_titles(
book: Book, version: Version = DEFAULT_VERSION
) -> Optional[BookTitles]:
"""
Given a book of the Bible and optionally a version return the book title.
:param book:
:param version:
:return: the book title
"""
try... | 1cba886d5ba9c8950239ef6af51a65681c6708d7 | 65,792 |
def mime(mime_id, cursor=None):
"""
Query for mime information from the repository.
"""
cursor = check_cursor(cursor)
cursor.execute('''
SELECT *
FROM mimes
WHERE id = %s
''', (mime_id,))
return cursor | b8d1443badaa8465f3d2df103c9f9a42fc3ad5ea | 65,793 |
import time
def recognize_image(img, config):
"""Receives a numpy image and a config parameter. Returns a string recognized text"""
img = np.array(img)
img = pre_img.get_grayscale(img)
blurred1 = cv2.medianBlur(img, 3)
blurred2 = cv2.medianBlur(img, 51)
divided = np.ma.divide(blurred1, blurred... | 0eb1795245f17ba462dbbd6820917a9529e904a2 | 65,794 |
def Imu_I0c1c2c3c4(mu, c):
"""
I(mu, c) where c = (I0, c1, c2, c3, c4)
"""
return c[0]*(1-c[1]*(1-mu**0.5)-c[2]*(1-mu)-c[3]*(1-mu**1.5)-c[4]*(1-mu**2.)) | 6553deaff09f4a3e00364b271095b5e80472b3a1 | 65,795 |
def linear_chain_crf(input, label, param_attr=None, length=None):
"""
:api_attr: Static Graph
Linear Chain CRF.
${comment}
Args:
input(${emission_type}): ${emission_comment}
label(${label_type}): ${label_comment}
Length(${length_type}): ${length_comment}
param_attr... | 70fd28b436cdf5ade1762a254b76a9303efdb7e9 | 65,796 |
def centroid_linkage(active_sites,min_clusters,printMe=False):
"""
Centroid Linkage clustering
This implementation builds until it hits min_clusters. Dendrograms not supported.
Inputs: List of ActiveSite instances and number of clusters
Outputs: List of labels and cluster centers
"""
... | 45e738dab93e504a673b37666cb73152db7c7730 | 65,797 |
def add_due_reservations(create_user, add_due_flights):
"""Fixture to add reservations"""
user = create_user(USER)
reservations = [{
"flight": add_due_flights[0],
"seat_number": "E001",
"type": "ECO",
"made_by": user,
}, {
"flight": add_due_flights[1],
"s... | 92f08e064a945f4222755c8cc01ab9afe6e0555b | 65,798 |
def isinstance_qutip_qobj(obj):
"""Check if the object is a qutip Qobj.
Args:
obj (any): Any object for testing.
Returns:
Bool: True if obj is qutip Qobj
"""
if (
type(obj).__name__ == "Qobj"
and hasattr(obj, "_data")
and type(obj._data).__name__ == "fast_cs... | 3c140e012d0df97852e84c50a37e6464e107fe2e | 65,799 |
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 |
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 |
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 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 |
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 |
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 |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.