content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import socket
def create_input_socket(port):
"""Connect to the given socket as a read-only client"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setblocking(True)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 640 * 100)
sock.bind(('127.0.0.1', port))
sock.listen(1)
... | 872baa07e5d3bb2b82312306c28690a5800456d5 | 636,744 |
import codecs
import csv
import logging
import traceback
def read_csv(from_path):
"""
Reads the data from a test result csv file.
Returns the data as a list containing lists.
"""
data = []
try:
with codecs.open(from_path, 'r', 'utf-8') as inp:
reader = csv.reader(inp, di... | 6051ead3c74d487a8ca0268d9adbb6d5f3652651 | 636,745 |
def center_crop_image(image, new_width, new_height):
"""
:param image: type: ndarray
:param new_width:
:param new_height:
:return:
"""
was_transposed = False
if image.shape[0] <= 4:
# need to transpose it..
image = image.transpose(1, 2, 0) # (chan, height, width) -> (heig... | 82972ed6e9612d5faac814a0f951bc1cefe1a741 | 636,746 |
def fill_buckets(buckets, all_jobs):
"""Split jobs in buckets according their memory consumption."""
if 0 in buckets.keys(): # do not split it
buckets[0] = list(all_jobs.keys())
return buckets
# buckets were set
memlims = sorted(buckets.keys())
prev_lim = 0
for memlim in memlims... | 3bcebb8a57777fa6af8a1347255493e7c18592b3 | 636,747 |
def _add_solr_language_info(res, obj):
"""
:param res: Solr document, i.e. a dict to which new keys will be added.
:param obj: object which is searched for language information.
:return: mutated dict res
"""
if getattr(obj, 'language', None):
res['language_t'] = obj.language.name
... | e434932074afc8df7d8c6b9e6702e431eed69c32 | 636,748 |
from typing import Union
from typing import List
def sieve_of_eratosthenes(n: int = 2) -> Union[List[int], None]:
"""
Returns a list of prime numbers up to and including n.
For n<2 returns None.
>>> sieve_of_eratosthenes()
[2]
>>> sieve_of_eratosthenes(5)
[2, 3, 5]
>>> sieve_of_eratos... | b0425e13aa71c666593a846caff29d85d19aea42 | 636,749 |
import logging
import os
def _setup_logger(flag=0, name=None, fname=None, fmt=None, fmode='w'):
"""Setup logger
flag:
1 - use only console
2 - use only file
3 - use console and file
"""
if fmt is None:
fmt = "\x1b[1;36m%(levelname)s\x1b[0m %(message)s"
_logger = logging.getLogger(name)
if... | dd3afbefe2d54c0c9d76cb7c4f5f0dcf709d3876 | 636,750 |
def winner(player):
"""
Check if the player won (has no pieces left in his hand)
:param player: Player whose turn it is
:return: True, if Player won, otherwise False
"""
if len(player.hand) == 0:
return True
return False | 0c71441e43ee828aa7820e9f860ac9b97268b407 | 636,751 |
import os
import re
def getprocessedimg(op_dir, pattern = r'(.+?).'):
"""
NOT USING
getprocessedimg check the output folder and create a list of processed data
pattern: the pattern re search
"""
processed_img = []
for (directory, dir_names, file_names) in os.walk(op_dir):
for file_name in file_names:
# pr... | ff89782763e1fe35e414106f8024bfe60710f3c7 | 636,752 |
import numpy
def create_uniform_random_initializer(min_value, max_value):
"""Creates uniform-random initializer.
:param min_value: Minimum value in distribution (used to fill initialized
model-input matrix).
:param max_value: Max value in distribution.
:return: init_function: Function (see be... | fc2e7e9c3e32514d7406d1b371b381e1c710c051 | 636,753 |
def algorithm_u(ns, m):
"""
implementation of Knuth's Algorithm U for finding all set partitions with a given number of blocks
from https://codereview.stackexchange.com/questions/1526/finding-all-k-subset-partitions
example: algorithm_u([1,2,3,4,5,6,7,8],2)
"""
def visit(n, a):
ps = [[]... | 9cb7340f21b5f98d77f5c2e82c548adee28d736e | 636,755 |
def secret_max(secret):
"""
Return a lambda that returns either the argument from the lambda or the argument passed in to secret_max, whichever one's product is bigger.
:param secret: secret list of two numbers (list)
:return: lambda that takes a list of two numbers
"""
return lambda num: m... | 30c87a9ae61afc701cd74ae723193fa3dc8db4bc | 636,757 |
def random_sampling_cat(urm, datareader, cat, n_samples):
"""
Set n_samples equal to zero for the selected category. Samples will be equally spaced.
:param urm: the user rating matrix
:param datareader: a Datareader object
:param cat: the selected category
:param n_samples: number of tracks to s... | 5772599220d320185cc78d54c50dfd126cf19f39 | 636,758 |
import torch
def get_patch(images, action_sequence, patch_size):
"""Get small patch of the original image"""
batch_size = images.size(0)
image_size = images.size(2)
patch_coordinate = torch.floor(action_sequence * (image_size - patch_size)).int()
patches = []
for i in range(batch_size):
... | 5b1fe1de57b82c87e652b7b6e2ecf60dbe5b8ee3 | 636,759 |
import os
def get_env(variable):
"""**get_env(variable)** -> return the value of the environnement variable
* variable: (string) name of the variable to ask
<code>
Example:
get_env('LANG')
Returns:
'en_US.UTF-8'
</code>
"""
return os.environ.get(variable, '') | cbe95b88054747862991d1a56986f3ebe2b65064 | 636,760 |
def joint_stracks(t_list_a, t_list_b):
"""
join two track lists
:param t_list_a:
:param t_list_b:
:return:
"""
exists = {}
res = []
for t in t_list_a:
exists[t.track_id] = 1
res.append(t)
for t in t_list_b:
tid = t.track_id
if not exists.get(tid, 0... | 04e59fa715ecc2021166645fef1fda7c06c7776f | 636,761 |
def zero_matrix(mat):
""" 1.8 Zero Matrix: Write an algorithm such that if an element in an MxN
matrix is 0, its entire row and column are set to 0.
"""
n = len(mat)
m = len(mat[0])
rows = set([])
columns = set([])
for i in range(n):
for j in range(m):
if mat[i][j] ==... | ab38fa8110860d6b595293e7fe3d180a1131a109 | 636,762 |
import re
def _set_time_ref(vars, timevar, reftime, cycle=None):
"""
internal method: Set time reference
"""
if isinstance(timevar, str):
timevar = [timevar]
for tvar in timevar:
for nvar in vars:
if nvar["name"] == tvar:
if "units" in nvar["attr"]:
... | 78c30336593f4504b22a19914a25ddb74e1200fa | 636,763 |
def getStorageAccountByName(self, storageAccountName):
"""Gets the StorageAccount object"""
# Get all the storage accounts in the subscription
allStorageAccounts = self.storage_client.storage_accounts.list()
# Kind: BlobStorage ==> WASB (Example : 'https://rechappastorage.blob.core.windows.net/', dfs:... | 8337238c820202bda6f4aca64a4df0221cbeab85 | 636,764 |
def is_prime(num):
"""
This function checks whether the input natural number larger than 1 is a prime number.
:param num:
:return: boolean
"""
i = 2
while i ** 2 <= num:
if num % i == 0:
return False
i += 1
return True | dacfb5919dfc52c38f5b364651c9e9d81bec9628 | 636,765 |
import time
def dt_to_ts(dt):
"""
datetime转换为时间戳
:param dt: datetime
:return:
"""
return int(time.mktime(dt.timetuple())) | 770f61ed5641bf741e6a3a5dae199b59bd150163 | 636,766 |
import torch
def np2tensor(array, device=None):
"""Convert form np.ndarray to torch.Tensor.
Args:
array (np.ndarray): A tensor of any sizes
Returns:
tensor (torch.Tensor):
"""
tensor = torch.from_numpy(array).to(device)
return tensor | a4f7a0f7e05d49699010877f1d6385eda3354bca | 636,767 |
def element_finder(compound_list):
"""
Args:
compound_list (list) - list of the compounds in the reaction with correct spacing and capitalization
Returns (list):
list of elements in the reaction
Example:
>>>element_finder(["H2O", "C6H12O6", "CH3CH2(CHO)CH3"])
... | ec2e425063b05c833e44cdb80ae381f80cdaeac4 | 636,768 |
from typing import Union
from pathlib import Path
def has_dicm_prefix(filename: Union[str, Path]) -> bool:
"""DICOM files have a 128 byte preamble followed by bytes 'DICM'."""
with open(filename, "rb") as f:
f.seek(128)
return f.read(4) == b"DICM" | cddbc4862d9f72695b46b8094e4c24696d6ad5f4 | 636,769 |
import subprocess
def is_installed(app):
"""
Wrapper for "rpm -q <app>" command
Return value: True if application is found,
False in other cases.
Output of rpm command is not supressed.
"""
return True if subprocess.call(["rpm", "-q", app]) == 0 else False | 48d22d6901fdbd0023497cb7470aeaaf5ac70c1c | 636,770 |
def get_sequencing_cell_id(dataset_uuid:str, barcode:str)->str:
"""Takes a dataset uuid and a barcode of a cell within that dataset to produce a unique cell ID"""
return "-".join([dataset_uuid, barcode]) | e0b8b33d192d2398ecedcef206da48c05160c3dd | 636,771 |
def splitlines(string_with_lines):
"""Return a ``list`` from a string with lines."""
return string_with_lines.splitlines() | daea6a35fd652eaab1cda5a022d8d0a85047bf03 | 636,772 |
def auth(request_obj, endpoint, method):
"""Override this function in your application.
If this function returns False, 401 forbidden is raised and the documentation is not visible.
:param request_obj:
:param endpoint:
:param method:
"""
return True | 4a38f65e3a29a41839275bb9b2677f00652f198b | 636,773 |
def _gap_difference(seq_gaps: dict, union_gaps: dict) -> tuple:
"""
Parameters
----------
seq_gaps
{gap pos: length, } of a sequence used to generate the gap union
union_gaps
{gap pos: maximum length, ...} derived from the same seq aligned
to different sequences
Returns... | c52db6cf9557af7425b36ac0a590e8ee69ccf993 | 636,775 |
import logging
import sys
def _get_number(length):
"""Read a number in the lengths specification"""
try:
value = int(length)
except ValueError:
logging.critical("Lengths list is invalid")
sys.exit(1)
if value < 1:
logging.critical("Length value must be strictly positiv... | 6e8ab531a0fa8171ec7d36e133cd9a55cbd1246f | 636,776 |
def bits2frac(bits, length):
"""For a given enumeratable bits, compute the binary fraction."""
return sum(bits[i] * 2**(-i-1) for i in range(length)) | 7df61a89092e98164384b78dc11ad09d12d399ef | 636,778 |
import random
def one_chance_in (n):
"""
Returns True with a 1/n chance.
"""
return (random.randint(1,n) == 1) | 61f9838139606b33e7f923c03f589571feec8bdc | 636,779 |
def lorenz(t, x, sigma=10, beta=2.66667, rho=28):
"""
parameters:
:sigma : 10
:beta : 2.7
:rho : 28
"""
return [
sigma * (x[1] - x[0]),
x[0] * (rho - x[2]) - x[1],
x[0] * x[1] - beta * x[2],
] | 4d7acd5e98f8d61551095270ba8402372dc41df6 | 636,780 |
import numpy
def mp3_singles(D1, D2, F, I):
"""Return the singles contribution to the 3rd order energy."""
dA = (-1.0)*numpy.einsum(
'ai,ij,ja,ia,ja->',
F.vo, F.oo, F.ov, D1, D1)
dB = numpy.einsum(
'ai,ba,ib,ia,ib->',
F.vo, F.vv, F.ov, D1, D1)
dC = numpy.einsum(
... | cd9830e2ef5d98770d003741d50ec81dbac98d9f | 636,782 |
def create_data_model():
"""Create the data for the example."""
data = {}
weights = [48, 30, 42, 36, 36, 48, 42, 42, 36, 24, 30, 30, 42, 36, 36]
values = [10, 30, 25, 50, 35, 30, 15, 40, 30, 35, 45, 10, 20, 30, 25]
data['num_items'] = len(weights)
data['all_items'] = range(data['num_items'])
... | c01b2cb0195e97a0ee67c60980d14c38a0f81163 | 636,783 |
def divide_LeftRight(img):
"""
Divide bi-camera image into left image and right image
bi-camera image shape:(720,2560,3); left and right image shape:(720,1280,3)
:param img: CV2 mat image
:return: ;left_img, right_img
"""
divide_index = img.shape[1] // 2
right_img = img[:, 0:divide_index... | 2ffbbdb8ea166f4221e4a0722146faa6a432c8b1 | 636,784 |
def match(long_sequence, short_sequence):
"""
Finding perfect match based on the length of the short sequence,
If there is no perfect match, the condition for judging perfect match would be
subtracted by 1 in order as new condition for judging the most similarity.
Above steps would be repeated until... | 64789ad11f21502cf874b869e514494c313625be | 636,785 |
def extract_scores(transcript):
"""Extract scores of different types from a grading job's output, starting
from the bottom of the output
:param transcript: the grading output
:type transcript: str
:return: a list of (key, score) pairs
"""
score_lines = []
found_score = False
for l... | 7232e63b19ae7d302e31259258632b0dac645964 | 636,786 |
import optparse
def parse_args():
"""获取参数"""
parser = optparse.OptionParser()
parser.add_option('-o', '--out', action='store', type='string', dest='out', default='', help='输出文件名')
parser.add_option('-f', '--fps', action='store', type='int', dest='fps', default='10', help='帧率')
parser.add_opt... | 1386a5d9da03029cdf16584aa6831a811b87803e | 636,787 |
def fixstyle(obj):
"""Try to convert styles into a dictionary"""
if obj:
if isinstance(obj, list):
lengths = [len(x) for x in obj]
if min(lengths) == max(lengths) == 2:
obj = dict(obj)
elif isinstance(obj, dict) and 'styles' in obj:
obj['styles... | 63f9d2c32c4fa1e1054d349f29fb843c5a42f0d7 | 636,788 |
def _make_fasta(
num_proteins, peptides, peptides_per_protein, random_state, prefix=""
):
"""Create a FASTA string from a set of peptides
Parameters
----------
num_proteins : int
The number of proteins to generate.
peptides : list of str
A list of peptide sequences.
peptides... | bf2439afce4cda8b603e04fc4186a6660bba2edb | 636,789 |
def populate_coordinates_dictionary(dictified_values, coordinates_dictionary={}):
"""
The dictionnary coordinates_dictionary' will be populated (or updated) with
values from the 'dictified_values' dictionnary
Parameters
----------
dictified_values : dict
A dictionary of Sentinel-1 value... | abf8fadd4b7a0981552cd655c62c891c1661323f | 636,791 |
def extract_signal(s):
"""
Returns the portion of s between the (first) pair of parentheses,
or the whole of s if there are no parentheses.
"""
loc0 = s.find("(")
if loc0 >= 0:
loc1 = s.find(")")
if loc1 >= 0:
return s[loc0 + 1 : s.find(")")]
return s | 38d695e8e42f385a14b1a392aaf5d3dfd9d6f55b | 636,792 |
def nice_time(sec_in):
""" Pretty formatting for time stamps """
seconds = int(sec_in) % 60
minutes = int((sec_in / 60)) % 60
hours = int(sec_in / 3600)
return "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds) | 47df5b5b1b10f8d0f831e4707df30872dae712c1 | 636,794 |
def is_tag(elm):
"""
True if the passed object is a HTML/XML tag
* **elm**:
* **return**:
>>> from bs4 import BeautifulSoup as bs
>>> doc = bs("<span></span><p>bubu</p>", "html.parser")
>>> span = doc.span
>>> is_tag(doc.span)
True
>>> is_tag(doc.p)
True
>>> is_tag(list... | 5cdbbea685a9b1030dbeb5d83aa32df3d20b121b | 636,795 |
def get_value(specs, name):
""" Unpack metric specification
Parameters
----------
specs: dict
a dict with keys value and name
name: str
the spec name
Return
------
value: float or None
value of the spec if exists, None otherwise
"""
value = None
for ... | 06a83cdb70f891235f773eda28ec0fc59bc86e79 | 636,796 |
def get_schema_defs():
"""
ledgere eklenmemis (schema tanimlari) schemalari listele
"""
with open('json_schemas/indy_schemas.json', 'r') as f:
schemas = f.read()
return schemas | 5c80ed2831f906fdaeee0a179a3ba01984ceee78 | 636,798 |
import os
def download_pdb(pdb, data_dir, assembly=1):
"""Function to download pdb -- either biological assembly or if that
is not available/specified -- download default pdb structure
Uses biological assembly as default, otherwise gets default pdb.
Args:
pdb (str): pdb ID.
data_... | cef7ac8f86f043214adf13a9e4d603a9914607b2 | 636,799 |
def get_default_arrow(scale=1):
"""Get the default arrow
"""
return {
'cylinder_radius': scale*0.05,
'cylinder_height': scale*0.75,
'cone_radius': scale*0.125,
'cone_height': scale*0.25
} | 10276185aad3710315a477a07e38c05049371984 | 636,800 |
import torch
def batch_rot2aa(Rs):
"""
Rs is B x 3 x 3
void cMathUtil::RotMatToAxisAngle(const tMatrix& mat, tVector& out_axis,
double& out_theta)
{
double c = 0.5 * (mat(0, 0) + mat(1, 1) + mat(2, 2) - 1);
c = cMathUtil::Clamp(c, -1.0, 1.0);
... | a0d3a7213a65e6b1821c3c56907c1a705c981ca8 | 636,801 |
def query_templater(
table_name,
columns=None,
conds=None,
db_name="darpa_data"
):
""" Generates an appropriate SQL query for db_name
Params:
table_name : str
Some darpa_data table
columns : [str] or None
A list of column names to fetch... | b8f7bd3423407fe4be47a0f136375cafb0f97582 | 636,802 |
import string
def sanitize_channel_name(name: str) -> str:
"""Filter out characters that aren't allowed by Discord for guild channels.
Args:
name: Channel name.
Returns:
Sanitized channel name.
"""
whitelist = string.ascii_lowercase + string.digits + "-_"
name = name.lower().... | 2f0b246cbecfcf8a39ea6810da836c9d469bc0f1 | 636,804 |
import argparse
def parser(options=None):
""" Parser for igmguesses
Parameters
----------
options
Returns
-------
"""
parser = argparse.ArgumentParser(description='Parser for IGMGuesses')
parser.add_argument("in_file", type=str, help="Spectral file")
parser.add_argument("-o... | 16eeeb37bc0527b05dade678ec20c2fc6b1b686b | 636,805 |
def links_to_labels(links):
"""
:param links: Dict of [doc_id, set of connected doc ids]
:return labels: Dict of [doc_id, label]
"""
labels = dict()
label = 1
for (pivot, linkage) in links.iteritems():
if pivot not in labels:
labels[pivot] = label
for id in li... | 06fdcf60f57b0d16b76079075609f65b208f71b1 | 636,806 |
def get_tag_posts(Tag, tag_name):
""" 获取指定标签的博文 """
query_tag = Tag.query.filter_by(name=tag_name).first()
if query_tag:
return query_tag.posts
else:
return None | 474ea116e0195c98fc01b6cff249945094642243 | 636,807 |
def apply_changes(config_changes, config):
"""
Found config changes and apply
"""
for artifact_name, changes in config_changes.items():
if 'changes' in changes.keys():
for key, value in changes['changes'].items():
config["artifacts"][artifact_name][key] = value
... | fb2846c56dc788797864e58eb51dbee32ea49180 | 636,808 |
def sliceBinStr(binStr):
"""
32位二进制平均切成 4 片
"""
aSection = binStr[0:8]
bSection = binStr[8:16]
cSection = binStr[16:24]
dSection = binStr[24:]
# print('aSection=%s, bSection=%s, cSection=%s, dSection=%s' % (aSection, bSection, cSection, dSection))
return aSection, bSection, cSection,... | 7c12d49aea9d9227a059a9d02ad26ef903ed5935 | 636,809 |
import textwrap
import tempfile
def _prepare_test() -> str:
"""Helper function for the :func:`read_input` doctest."""
_, file = tempfile.mkstemp(text=True)
with open(file, "w") as f:
f.write(textwrap.dedent(""" &FORCE_EVAL
&DFT
BASIS_SET_FILE_NAME /... | 90d721d6ca52657ce6668dae8463a97bb0ffd4b0 | 636,810 |
def qcollide(Aleft, Aright, Bleft, Bright):
"""
optimised for speed.
"""
# quickest rejections first;
if Aright < Bleft:
return False
if Aleft > Bright:
return False
if Aleft <= Bright and Aright >= Bright:
return True # Bright point is within A, collision
if A... | 32f8e5fd9a89013b2849854aefa0ca523b3ed091 | 636,812 |
import numpy
def fermi_dirac(x):
"""
Return fermi-dirac distribution weight.
"""
if x < -200:
f = 1.
elif x > 200:
f = 0.
else:
f = 1./(numpy.exp(x) + 1)
return f | adde278e58125433e27a8560339d43693749c7b4 | 636,813 |
def _is_job_queued(api_job_response):
"""Checks whether a job has been queued or not."""
is_queued, position = False, 0
if 'infoQueue' in api_job_response:
if 'status' in api_job_response['infoQueue']:
queue_status = api_job_response['infoQueue']['status']
is_queued = queue_s... | dcc0357ba3fd1f4ae3a7629d6f0036fa5036511e | 636,814 |
from operator import mul
def multiplyLists(lst1, lst2):
"""Return the elementwise product of lst1 and lst2."""
assert len(lst1) == len(lst2), "The lists have to be the same length."
return list(map(mul, lst1, lst2)) | fe26b0d143a1beec53c7ed771e383e7edff6154a | 636,815 |
def serialize_uint256(n: int) -> bytes:
"""
Serialize an unsigned integer ``n`` as 32 bytes (256 bits) in big-endian
order.
Corresponds directly to the "ser_256(p)" function in BIP32
(https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#conventions).
:param n: The integer to be seria... | e8987a9a59843bc5cac22d11c3222abe5ccd7f6b | 636,817 |
def y_overlaps(cluster1, cluster2):
"""
author: Jon Liberal
Test if there is y-axis overlap for 2 clusters
param cluster1 First cluster's coordinates
param cluster2 Second cluster's coordinates
return Boolean: True if overlap else False
"""
return not (cluster2[0] > cluster1[1] or cluste... | debc6e38c90813970dd08d061aea01059d2c7a1c | 636,818 |
def add_mask_to_image(img, mask, x, y):
"""Paste a mask at specific position on image"""
if y + mask.shape[0] > img.shape[0]:
max_height = img.shape[0] - y
mask = mask[: max_height, :]
if x + mask.shape[1] > img.shape[1]:
max_width = img.shape[1] - x
mask = mask[: , :max_wid... | 093b0410c0a0dfc46c4f4b717b34932b9672c05d | 636,819 |
import argparse
def setup_argparser() -> argparse.ArgumentParser: # pragma: no cover
"""
Setup argument parser
Returns:
Any: Initialized argument parser
"""
parser = argparse.ArgumentParser(
description="Get the Certification Project related data"
)
parser.add_argument(
... | bebbdb829564843017495e5837ec082642412eac | 636,821 |
def get_virtual_chain_version():
"""
Get the version string for this virtual chain.
"""
return "v1.0" | f4300a2bcb3bd6f6a9d8ea1360716f59fbffd868 | 636,822 |
def run_tomtom(query_file, target_file):
"""Run tomtom from MEME suite to get matches to file
"""
return None | ededd78ee8c6491c9dbdf8e1d09f02e7b790744a | 636,823 |
import re
import subprocess
def ldd(file):
"""
Return a list of library names linked with the file.
"""
regex = re.compile('\t(?P<m>[a-zA-Z0-9/_\-]+)[.]so.*')
out = subprocess.getoutput("ldd "+file)
out = out.split('\n')
out = [ regex.match(o) for o in out ]
out = [ o.group(1) for o in... | e69d5125a66b14eb285df0416cbb1406ff91ab34 | 636,824 |
import os
def ls(resource, files=True, directories=False):
"""Return a list of files and optionally directories located at resource."""
file_list = []
for (_dirpath, _dirnames, _filenames) in os.walk(resource):
if files:
file_list.extend(_filenames)
if directories:
... | 8a74d077ae8a0147ee803e672574f07a617a3251 | 636,825 |
def dSquaredLoss(a, y):
"""
:param a: vector of activations output from the network
:param y: the corresponding correct label
:return: the vector of partial derivatives of the squared loss with respect to the output activations
"""
# assuming that we measure the L(a, y) by sum(1/2*square(y_i - a... | 9793bd5bd9e9f5190b0868466a8716a5ce82c653 | 636,826 |
import numpy
def rsvw_function(top, up):
"""Function defined to summary some calculations. For more information,
please consult http://bdigital.unal.edu.co/65682/1/1053830848.2018.pdf,
pag. 26.
"""
r = numpy.exp(top.alpha) * (
up.g * (numpy.cos(top.gamma)) - up.h * (numpy.sin(top.gamma))
... | 664e5499b01f0b8ea055f80f356d7fe5f6b01dfc | 636,827 |
def get_cmd_arg(arg, cmd_tree):
"""
Return the indicated command argument from command parse tree. If arg is
a str it is a keyword. If arg is an int it is a positional index. If
the argument is not found, return None.
Args:
arg: Command argument to look up
cmd_tree: Parsed command t... | b90c24bbc387ddc0158a3d5d000126d844be2be8 | 636,828 |
def get_notes_by_song(song, notes_map):
"""
Iterate over all labels for a given song.
Same note have different midi codes in different octaves.
For example the note C has the following codes: 12, 24, 36, 48, 60, 72,
84, 96, 108, 120
For this representation, we transform all these code only t... | 311666e0f72fad8c8c10c7128a633c7ae18653d2 | 636,829 |
def means_factor_prod(sum_sq_factor, mean_factor):
"""
Calculates <X^TX>
"""
mean_prod = mean_factor.T @ mean_factor
n = mean_prod.shape[0]
mean_prod.flat[::n + 1] = sum_sq_factor # .flat[] allows for inplace assignment
return mean_prod | e0d3a32a7bce62b6ab1ba5e7b219a9704a9e56a6 | 636,830 |
def sweep_activation_toggle(
sourced_val,
meas_triggered,
swp_on,
swp_stop,
swp_step,
mode_val
):
"""decide whether to turn on or off the sweep
when single mode is selected, it is off by default
when sweep mode is selected, it enables the sweep if is wasn't on
otherwise it stops ... | 88139b1e14243c62e2b79dba7b643d2c5287caf3 | 636,831 |
import torch
def get_bert_embeddings(tokens_tensor, segments_tensors, model):
"""Get embeddings from an embedding model
Args:
tokens_tensor (obj): Torch tensor size [n_tokens]
with token ids for each token in text
segments_tensors (obj): Torch tensor size [n_tokens]
... | 6b9ddd69f6f61d5667bc321ae3628485a9a2fa47 | 636,832 |
import re
def format_taxonomy(T, hierarchy, acc, no_prefix=False):
"""
Formatting taxonomy to conform to a set hierarchy
Arguments:
T : iterable, taxonomy
hierarchy : taxonomic hierarchy
acc : accession
Return:
[taxonomy_level1, taxonomy_level2, ...]
"""
regex = re.com... | a018fc9da96cb22fc944e9f030451970d509e4e8 | 636,833 |
def parse_dependencies_windows(data):
""" Parses the given output from dumpbin /dependents to determine the list
of dll's this executable file depends on. """
lines = data.splitlines()
li = 0
while li < len(lines):
line = lines[li]
li += 1
if line.find(' has the following de... | 4e3f6ed46171d2861d68e1bf06302652cb5b5103 | 636,834 |
def get_preferred_locale(request):
"""Return the locale the current user prefers, if any.
Used to decide in which language to show the Translate page.
"""
user = request.user
if user.is_authenticated and user.profile.custom_homepage:
return user.profile.custom_homepage
return None | 6ac27e6e88aafe67a7fe8d3a5f08a93dbf1aba40 | 636,835 |
def get_window_pos(location, video_size, offset=100):
""" calculate the window position given a location string and the size
of the total video """
width, height = video_size[0]//2, video_size[1]//2
if location == 'upper left':
return 0, 0
elif location == 'lower left':
return 0,... | 31ea9332352e4f1928a545f57ccf24056f9992a6 | 636,836 |
def _gs_one_element(h, basis, integration, max_iter=3):
"""Orthonormalize a function against an orthonormal basis."""
norm = integration.norm(h)
e = h / norm
for _ in range(max_iter):
for b in basis:
e -= b * integration.dot(b, e)
new_norm = integration.norm(e)
if ne... | 2d5c9cf6552153d7c9848c09c306677ebe30e610 | 636,837 |
def get_datetime_str(dt):
"""
>>> dt = datetime.datetime.now()
>>> def get_datetime_str(dt):
... return dt.strftime("%Y-%m-%d %H:%M:%S")
>>> get_datetime_str(dt)
'2021-04-11 17:19:10'
"""
return dt.strftime("%Y-%m-%d %H:%M:%S") | 5c657ab1d43879cb16c80b4c89061864f6827d18 | 636,838 |
import gc
import time
def measure(func, inner_iterations=1, repeats=5):
"""
Runs func ``repeats`` times and returns the fastest speed
(inner loop iterations per second). Use ``inner_iterations`` to specify
the number of inner loop iterations.
Use this function for long-running functions.
"""
... | 65bbf304eb8d2e3db5fbc3e56cb118503339ccb9 | 636,839 |
def calculateBoxInertia(mass, size):
"""Returns upper diagonal of inertia tensor of a box as tuple.
Args:
mass(float): The box' mass.
size(iterable): The box' size.
Returns:
: tuple(6)
"""
i = mass / 12
ixx = i * (size[1] ** 2 + size[2] ** 2)
ixy = 0
ixz = 0
iyy ... | e8634f8079a002a0c96876dcb12ec3d29ed1b58e | 636,840 |
import numpy
def geographical_area_from_bounds(lon1,lat1,lon2,lat2):
"""
Computes area of spatial cell identified by origin coordinate and top right cooridnate.
The functions computes area only for square/rectangle bounding box by based on spherical earth assumption.
Args:
lon1,lat1 : Origin c... | e755fc2762a1b362235ec1fff7ba7436e1a6d556 | 636,841 |
import random
def dad_joke_generator(request):
"""Gives back a random dad joke from an array
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.poco... | 1cd2d45ea74410191515a243c80dc31b30e23a11 | 636,842 |
def get_suspecious_items(_items):
"""Items with libraryCatalog==Zotero
These items are suspecious, cause they were imported from
pdf files and maybe Zotero did not import the metadata properly.
:param _items: Zotero library items
:type _items: list containing dicts
:returns: list containing di... | d067dc2756630b814552b461927c31530cb67e4f | 636,843 |
import logging
def resolve_collection_methods(methods):
"""
Convert methods (string) to list of validated methods to resolve
"""
valid_methods = ['group', 'localadmin', 'session', 'trusts', 'default', 'all', 'loggedon',
'objectprops', 'experimental', 'acl', 'dcom', 'rdp', 'psremot... | 3acfc05775401483641c08b520b7e1626273f9ff | 636,844 |
import argparse
def argument_parser():
""" Define the arguments and return the parser object"""
parser = argparse.ArgumentParser(
description="Sort and index with LAStools a folder with point cloud elements (LAS/LAZ files or subfolders containing LAS/LAZ files). The sorted/index data is copied in the outp... | c9741dc0514ba545c2eb7d6da808cd3587eb907d | 636,845 |
def validate_change_dict_for_blog_post(change_dict):
"""Validates change_dict required for updating values of blog post.
Args:
change_dict: dict. Data that needs to be validated.
Returns:
dict. Returns the change_dict after validation.
"""
if 'title' in change_dict:
blog_do... | 926e145cefaced48e662ee31b219c9176a98bd6c | 636,846 |
def covxy(x, y):
""" Covariance => average of pair products. """
N = x.shape[0]
psum = 0
for i in range(N):
psum = psum + x[i] * y[i]
return psum / N | bf315cabb6d2af97a508d981dd3af24c74ebd21f | 636,848 |
def overlaps(low1: int, high1: int, low2: int, high2: int) -> bool:
"""
Returns true if the two regions
[low1, high1] and [low2, high2]
overlap.
"""
return high1 >= low2 and high2 >= low1 | c44a5dd3ebfb3ce8cebb531d0da2778d650e5a29 | 636,849 |
def uniq(seq):
"""return uniq elements of a list, preserving order
:param seq: an iterable to be analyzed
"""
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] | 111efd8305b618bad380052883bf5ccbecb4d1ba | 636,850 |
def MatchCheck(offered_organ, potential_recipient, Sim):
"""
This function peforms an initial check on the offered organ and potential patient to see if patient
can accept it or not based on biological characteristics
Input:
@offered_organ: organ being offered
@potential_recipient: recip... | 3bf95f04d6aea7343eb09b7320599bf6e0161c18 | 636,851 |
from typing import Any
def import_class(name: str) -> Any:
"""Import from a module specified by a string"""
components = name.split(".")
mod = __import__(components[0])
for comp in components[1:]:
mod = getattr(mod, comp)
return mod | a69ecbf83d7df82537a7c261da3a412acc69234c | 636,852 |
def average_even_is_average_odd(hand):
"""
:param hand: list - cards in hand.
:return: bool - are even and odd averages equal?
"""
even = 0
odd = 0
even_count = 0
odd_count = 0
for index, element in enumerate(hand):
if index % 2 == 0:
even += element
... | dbf93a5363c264de78ca9f76b81cd6f0f30ab462 | 636,854 |
def getDesiredData(dataManager, desiredComponents, startDateTime, endDateTime, removeSetpoints=False, removeRequests=False, removeBooleans=False):
"""Get the data from the desired components at the specified dates. After retrieval, clean and reshape the dataframes
to disregard unuseful data such as setpoints and requ... | 4a03ea1e8d405e4a749ae4031e9a8cc74be22f82 | 636,855 |
def check_parameter_file(filename):
"""
Function does a rudimentary check whether the cols, splits and divs columns
in the parameter files are formatted properly.
Just provides a preliminary check. Will only catch basic mistakes
Parameters
----------
filename : str
Path to paramete... | cc5ba1d921ce62f68e8aabe96ec6bfccefd8df79 | 636,856 |
def ComputeGammaRatio(lognH):
"""
ratio = Gamma/Gamma_UVB
eqn 14. from Rahmati 2013.
"""
# value taken from table 2 Rahmati+ 2013
nH_ssh = 5.1*1.0e-4
nH = 10**lognH
ratio = 0.98*(1+(nH/nH_ssh)**1.64)**-2.28 + 0.02*(1+nH/nH_ssh)**-0.84
return ratio | aa868f6d6f8b2ea3073870acf6dd3d19c1214995 | 636,857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.