content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def recovery_invalid_token(
) -> str:
"""Return a valid auth token"""
return 'wrong' | 38ff965ffa7b579965e479ca1d676a4b40978772 | 703,882 |
def get_parameter_name(argument):
"""Return the name of the parameter without the leading prefix."""
if argument[0] not in {'$', '%'}:
raise AssertionError(u'Unexpectedly received an unprefixed parameter name, unable to '
u'determine whether it is a runtime or tagged paramet... | 54b51cd5e3239fbfaaccaad123975df0e84374fc | 703,883 |
import hashlib
def cmpHash(file1, file2):
"""Compare the hash of two files."""
hash1 = hashlib.md5()
with open(file1, 'rb') as f:
hash1.update(f.read())
hash1 = hash1.hexdigest()
hash2 = hashlib.md5()
with open(file2, 'rb') as f:
hash2.update(f.read())
hash2 = hash2... | 891b71188de42fb9c30a6559cd22b39685b6fc13 | 703,884 |
def bfmt(num, size=8):
""" Returns the printable string version of a binary number <num> that's length <size> """
if num > 2**size:
return format((num >> size) & (2**size - 1), 'b').zfill(size)
try:
return format(num, 'b').zfill(size)
except ValueError:
return num | 8aadc9671643b48c7c05032473b05fd872475bb0 | 703,887 |
def check_barcode_is_off(alignment, tags, log=None):
"""
See if the barcode was recognised with soft clipping.
if so, it returns True and can be counted in the optional log
:param alignment: the read
:param tags: alignment tags as dict
:return:
"""
if 'RG' in tags:
if tags['bm']... | 7adcbb8eae797750b3e543c52db41341d82f0937 | 703,888 |
def already_visited(string):
"""
Helper method used to identify if a subroutine call or definition has
already been visited by the script in another instance
:param string: The call or definition of a subroutine/function
:return: a boolean indicating if it has been visited already or not
"""
... | 7a9d84b6e04cdf7edb27bb7cf49cf1021130ab07 | 703,889 |
import pathlib
def get_stem_name(file_name: pathlib.Path | str | None) -> str:
"""Get the stem name from a file name.
Args:
file_name (pathlib.Path | str | None): File name or file path.
Returns:
str: Stem name.
"""
if file_name is None:
return ""
if isinstance(file_... | 01bab045f2c54aedf848922550ae241c9ddf8bce | 703,890 |
def getSingleIndexedParamValue(request, param_name, values=()):
"""Returns a value indexed by a query parameter in the HTTP request.
Args:
request: the Django HTTP request object
param_name: name of the query parameter in the HTTP request
values: list (or tuple) of ordered values; one of which is
... | c8a1a552d1ad9435e21243bf05226b373257d163 | 703,891 |
def _call(calls):
"""Make final call"""
final_call = ''
if calls['is_hiv'] == 'No':
final_call = 'NonHIV'
return final_call
if calls['deletion'] == 'Yes':
final_call = 'Large Deletion'
if calls['inversion'] == 'Yes':
final_call += ' with Internal Inversion'
... | c5e293255911cfdb16a73a026a13b7a394ae71cc | 703,892 |
import math
def get_sierpinski_carpet_set(width, height):
"""
获得谢尔宾斯基地毯点集
:param width:
:param height:
:return: 谢尔宾斯基地毯点集
"""
def get_sierpinski_carpet_points(left, top, right, bottom):
"""
递归获取谢尔宾斯基地毯的点
:param left:
:param top:
:param right:
... | b66bbe0dd25b47d81089b35d21a255b3b56c1f1e | 703,894 |
def destroy_asteroids(angles):
"""Destroy asteroids, start with laser pointing up and rotate clockwise."""
destroy_list = []
sorted_angles = sorted(angles)
while sorted_angles:
for angle in sorted_angles:
if not angles[angle]:
sorted_angles.remove(angle)
e... | 166fbd4e87152748b1d6527315fb87a91b617b7a | 703,895 |
import json
def add_filename(json_):
"""
Args:
string: json path
Returns:
dict: annotion label
"""
with open(json_) as f:
imgs_anns = json.load(f)
img_extension = json_.split('/')[-1].split('.')[0]+'.jpg'
imgs_anns['filename'] = img_extension
return img... | 3710a1d6f177b36c6786797f9af5c58cd527f354 | 703,896 |
from typing import OrderedDict
def sort_ordered_games_list(ordered_games_lists):
""" Reverses as sorts ordered games lists alphabetically """
new_order = OrderedDict()
for group, games in reversed(ordered_games_lists.items()):
new_order[group] = OrderedDict(
sorted(games.items(), key... | bc1b40884ad450d8a2b447c2628bfe77cd2797fa | 703,897 |
import time
import os
import subprocess
def get_map_mrr(qids, predictions, labels, device=0, keep_results=False):
"""
Get the map and mrr using the trec_eval utility.
qids, predictions, labels should have the same length.
device is not a required parameter, it is only used to prevent potential naming ... | 0ddc68fd12afebd2954e0c71e1bc58ffd0f6a1bf | 703,898 |
from typing import Union
from typing import Dict
from typing import Optional
def get_config_float(
current: Union[int, float], config: Dict[str, str], name: str
) -> Optional[float]:
"""
Convenience function to get config values as float.
:param current: current config value to use when one is not pr... | d2bb436c4b2b4aef35a8f46927bc9145ecfed04c | 703,900 |
def getRatingDistributionOfAMovie(ratingRDD, movieID):
""" Get the rating distribution of a specific movie
Args:
ratingRDD: a RDD containing tuples of (UserID, MovieID, Rating)
movieID: the ID of a specific movie
Returns:
[(rating score, number of this rating score)]
"""
retu... | 708c67e51d318b887deea1ec3ec4dc4a272e794e | 703,901 |
def lower_allbutfirst_letter(mystring):
"""Lowercase all letters except the first one
"""
return mystring[0].upper() + mystring[1:].lower() | 860d1449865790e15ccc840ee85ea366b2de5a64 | 703,902 |
import random
def strtest(aString):
"""this function takes the string and returns the string in a random order"""
newstring = random.sample(aString, len(aString))
newstring = "".join(newstring)
return(newstring) | 28bb6ed6b9f3a10ea19fbebb8ef60091123b0fd5 | 703,903 |
def mongo_uses_error_check(store):
"""
Does mongo use the error check as a separate message?
"""
if hasattr(store, 'modulestores'):
return any(mongo_uses_error_check(substore) for substore in store.modulestores)
return False | 52d4a5135531ff18b0e19ac7aa91a453a2e736f1 | 703,904 |
def bedLine(chrom, chromStart, chromEnd, name, score=None, strand=None,
thickStart=None, thickEnd=None, itemRgb=None, blockCount=None,
blockSizes=None, blockStarts=None):
""" Give the fields, create a bed line string
"""
s = ('%s %d %d %s'
% (chrom, chromStart, chromEnd, name))
i... | dd294d5d31ea3a2f7beb8a11a7ec705eb10cf1a4 | 703,906 |
def fatorial(num):
"""
Calcula a fatorial
:param num:
:return:
"""
fat = 1
if num == 0:
return fat
for i in range(1,num+1,1):
fat *= i # fat = fat * i
return fat | 181ea2bde3acef3f6ff4311054fb209edfad6160 | 703,907 |
def GePacketOut(egress_port, mcast, padding):
""" Generate packet_out packet with bytearray format """
out1 = "{0:09b}".format(egress_port)
out2 = "{0:016b}".format(mcast)
out3 = "{0:07b}".format(padding)
out = out1+out2+out3
a = bytearray([int(out[0:8],2),int(out[8:16],2),int(out[16:24],2),int... | c56abb84ec067cf8abb8e69d82c1342c4f20e0e9 | 703,908 |
def cmp_public_numbers(pn1, pn2):
"""
Compare 2 sets of public numbers. These is a way to compare
2 public RSA keys. If the sets are the same then the keys are the same.
:param pn1: The set of values belonging to the 1st key
:param pn2: The set of values belonging to the 2nd key
:return: True i... | a91a7204412d07808dbd6d5040f6df8baa576417 | 703,909 |
def ranges(int_list):
"""
Given a sorted list of integers function will return
an array of strings that represent the ranges
"""
begin = 0
end = 0
ranges = []
for i in int_list:
# At the start of iteration set the value of
# `begin` and `end` to equal the first element
... | cc6aab9442a6f6986acccb1fa46cd61ff1e4ba07 | 703,910 |
def format_data(x_data=None,y_data=None):
"""
=============================================================================
Function converts a list of separate x and y coordinates to a format suitable
for plotting in ReportLab
Arguments:
x_data - a list of x coordinates (or any object that can be indexe... | 34ac418f38194644f9372f20d47535424c7bfb52 | 703,911 |
import json
import os
import sys
def write_plugins_index(file_name, plugins):
"""
Writes the list of (name, version, description) of the plugins given
into the index file in JSON format.
Returns True if the file was actually updated, or False if it was already
up-to-date.
"""
# separators ... | 52d110bb0e90c661f95b144fa95d6143d7e719a7 | 703,912 |
def get_console_scripts(entry_points):
"""pygradle's 'entrypoints' are misnamed: they really mean 'consolescripts'"""
if not entry_points:
return None
if isinstance(entry_points, dict):
return entry_points.get("console_scripts")
if isinstance(entry_points, list):
result = []
... | 4ca1f6bb50959570c1c6d28312aabb939fe9daf8 | 703,913 |
def flatten(array: list):
"""Converts a list of lists into a single list of x elements"""
return [x for row in array for x in row] | 178f8ddb6e4b4887e8c1eb79f32fe51c0cf5fd89 | 703,914 |
def keyevent2tuple(event):
"""Convert QKeyEvent instance into a tuple"""
return (event.type(), event.key(), event.modifiers(), event.text(),
event.isAutoRepeat(), event.count()) | a456ce7790232ecf8ea4f6f68109a2023f4f257b | 703,915 |
import math
def get_inv_unit(block_index,diff):
"""
given a block index and a 0-indexed layer in that block, returns a unit index.
"""
bottleneck_block_mapping = {1:0,
2:3,
3:7,
4:13}
return bottleneck... | ed6936a81dd8f32f76a27efcf89b8e76d384b008 | 703,916 |
def liste_erreur(estimation, sol):
"""
Renvoie une liste d'erreurs pour une estimation et un pas donnés.
Paramètres
----------
estimation : estimation calculée pour la résolution de l'équation différentielle
sol : solution exacte
"""
(x,y) = estimation ... | 61a800f1316a153d50e39ce80239ddd4b841f74e | 703,917 |
import math
def find_roots_quadratic(a: float, b: float, c: float) -> set:
"""Return a set containing the solutions to the equation ax^2 + bx + c = 0.
Each solution is a float.
You may ASSUME that:
- a != 0
- (b * b) - (4 * a * c) >= 0
>>> find_roots_quadratic(1, -15, 56) == {8.0, 7.0}
... | 664f3ec213200ac2ed3a1cc4f8001da4331938bc | 703,918 |
def trick_for_mountaincar(state, done, reward, state_):
"""
-1 for each time step, until the goal position of 0.5 is reached.
As with MountainCarContinuous v0, there is no penalty for climbing the left hill,
which upon reached acts as a wall.
state[0] means position: -1.2 ~ 0.6
state[1] veloc... | 7ef703f6df9c1d10a250c18cb85def2702a3378d | 703,919 |
def edge_failure_sampling(failure_scenarios,edge_column):
"""Criteria for selecting failure samples
Parameters
---------
failure_scenarios - Pandas DataFrame of failure scenarios
edge_column - String name of column to select failed edge ID's
Returns
-------
edge_failure_samples - List ... | 91c251241dcde7d457b69b2033a1751b3ae963fd | 703,920 |
import time
import random
def my_solver(filename: str) -> str:
"""Dummy solver function.
It does nothing apart from waiting on average 2.5sec
:type filename: object
:Return: the same filename a the input
"""
print("Running my solver")
time.sleep(random.random() * 2)
return filename | 8aac2ebe64e8c3d1596441942e4c9a348c977f8f | 703,921 |
import re
def count_arg_nums(method_signature):
"""
Based on the method signature(jni format) to count the arguments number.
:param method_signature: method signature(jni format)
:return: arguments number
"""
arg_signature = re.findall(re.compile(r'\((.*?)\)'), method_signature)[0]
pattern... | 6703653e26ced05baf1a639d93d6435ea8b6ff8e | 703,922 |
def form_columns(form):
"""
:param form: Taken from requests.form
:return: columns: list of slugified column names
labels: dict mapping string labels of special column types
(observed_date, latitude, longitude, location)
to names of columns
"""
labels = {}
... | a3a2fdaa17310c04bb28675f88976cd7283f65a9 | 703,923 |
def bin2int(buf):
"""the reverse of int2bin, convert a binary buffer to an integer"""
x = 0
for b in bytearray(buf):
x <<= 8
x |= b
return x | 0c0edd88d7d4157f60641bc05f810184ef56f133 | 703,924 |
import base64
import six
def UrlSafeB64Decode(message):
"""wrapper of base64.urlsafe_b64decode.
Helper method to avoid calling six multiple times for preparing b64 strings.
Args:
message: string or binary to decode
Returns:
decoded data in string format.
"""
data = base64.urlsafe_b64decode(six.e... | f675c56f0bbd35661adfbea85135a9434fd7b107 | 703,925 |
def imei_parse_nibble(nibble):
"""Parse one nibble of an IMEI and return its ASCII representation."""
if nibble < 10:
return chr(nibble + ord('0'))
if nibble == 0xa:
return '*'
if nibble == 0xb:
return '#'
if nibble == 0xc:
return 'C'
if nibble == 0xd:
ret... | 837445a7679bc5355978d7d4e69c5c9fa166cb3f | 703,926 |
def check_command_succeeded(reply):
"""
Return true if command succeeded, print reason and return false if command
rejected
param reply: BinaryReply
return: boolean
"""
if reply.command_number == 255: # 255 is the binary error response code.
print ("Danger! Command reject... | a320b5000f59790e314108398339b9a66dbf6520 | 703,927 |
def format_interval(seconds):
""" Format an integer number of seconds to a human readable string."""
units = [
(('week', 'weeks'), 604800),
(('day', 'days'), 86400),
(('hour', 'hours'), 3600),
(('minute', 'minutes'), 60),
#(('second', 'seconds'), 1)
]
result = []
... | 8deae4627807f4c5e0cc1844499ebb39f658f2d0 | 703,928 |
def split_on_comma(tokens):
"""Split a list of tokens on commas, ie ``,`` DELIM tokens.
Only "top-level" comma tokens are splitting points, not commas inside a
function or other :class:`ContainerToken`.
:param tokens:
An iterable of :class:`~.token_data.Token` or
:class:`~.token_data.C... | 8b89dc6857a7b3e9bcc02f3a291e0ff0cd8d5f20 | 703,929 |
def find(db, user):
"""
find the notelist
:param db:
:param user:
:return:
"""
document = db.notelist.find_one({"_id": user})
return document | 04c6ad64e9b8ff2f5cd5462cebb9d37127b6d176 | 703,930 |
import numpy
def preprocess_image(x, mode='caffe'):
""" Preprocess an image by subtracting the ImageNet mean.
Args
x: numpy.array of shape (None, None, 3) or (3, None, None).
mode: One of "caffe" or "tf".
- caffe: will zero-center each color channel with
respect to ... | a5fe2fe24e9dcef65a7f704a17ab14d4ddb72f97 | 703,931 |
def calculate_metric(threshold, args):
"""
给定阈值得到预测类别后,计算precision和recall,其中precision是avg_sample(hit_cnt/pred_cnt), recall是avg_sample(hit_cnt/label_cnt),在当前场景下label_cnt恒等于1
"""
# 格式:label:pred_cls,pred_score;pred_cls,pred_score;
# 78089261739417600:78089261739417600,0.995399;
# 获取label_list... | 97bb7a81e9731a3f0c48000f98669d03f1d48ca4 | 703,932 |
import os
import csv
import random
def load_data():
"""Load data from the Quora dataset."""
# Partition off part of the train data for evaluation
with open(os.path.join('data', 'quora', 'train.csv'), 'r') as train_file:
train_data = [row for row in csv.reader(train_file, delimiter=',', quotechar='... | 98d1b5241785cdb2f229fa076f64128aa4aaee29 | 703,933 |
from datetime import datetime
def current_time() -> datetime:
"""Return timezone-aware current time as datetime."""
return datetime.now().astimezone() | 2b7237f4c5a0d88ab7643dfdd3b1f8c524683884 | 703,934 |
def make_label(label_text):
"""
returns a label object
conforming to api specs
given a name
"""
return {
'messageListVisibility': 'show',
'name': label_text,
'labelListVisibility': 'labelShow'
} | 8c388d138136af4f01ec02db1565d66049b38cf1 | 703,935 |
import torch
def _empty_memory(memory_dim):
"""Get a empty memory, assuming the memory is a row vector
"""
return torch.zeros(1, memory_dim) | b7454e52bbc3c20061d53716c2e805603eb041ff | 703,937 |
def mult(A, B):
"""
Function to multiply two values A and B, use as "mult(A, B)"
"""
return A * B | 586c9077303dd8a36ae6007ff74756f77ec8fb3b | 703,939 |
def get_link_href(result_object, link_relation):
"""
Given a result_object (returned by a previous API call), return
the link href for a link relation.
'result_object' a JSON object returned by a previous API call. May not
be None.
'link_relation' the link relation for which href is required.
... | 400cd38d1b29ea71bf974d8aa16c1b3adf104428 | 703,940 |
import sys
def _are_we_frozen():
"""Returns whether we are frozen via py2exe.
This will affect how we find out where we are located."""
return hasattr(sys, "frozen") | a9e55631ce9f8d60351e41d257c225f859e39a05 | 703,941 |
import re
def rx_filter(objs: list, attr: str, prompt: str) -> list:
"""
Filter a list of dicts based on user-entered regex match to one of their values.
"""
while True:
search_term = input(prompt+" ")
# Prefer exact match first -- otherwise can never select an item that's a substri... | f0c6dd5609020054da7895e577483c911d9aaea3 | 703,942 |
def _get_usb_hub_map(device_info_list):
"""Creates a map of usb hub addresses to device_infos by port.
Args:
device_info_list (list): list of known usb_connections dicts.
Returns:
dict: map of usb hub addresses to device_infos by port
"""
map_usb_hub_ports = {}
for device_info in device_info_li... | eaadc4713a41fdf38cea4fce35806d1d8772df27 | 703,943 |
import os
import subprocess
def get_current_commit(srcdir):
"""Return information about git commit checked out in the given directory.
:param srcdir: source code directory
:type srcdir: str
:return: commit information composed of brief SHA1 and subject
:rtype: str
"""
os.chdir(srcdir)
... | 3b3601303135bfdfe66cb069ef7d4ed1f413af8b | 703,944 |
import re
def parse_pgsql_logs(data):
"""
Parse the pgsql benchmark data from ripsaw and return
the data in list format
Args:
data (str): log data from pgsql bench run
Returns:
list_data (list): data digestable by scripts with below format
e.g.:
[
... | 5bd5cd43432b17be6bd52004b151b32a0f574980 | 703,945 |
def jd2gdate(myjd):
"""Julian date to Gregorian calendar date and time of day.
The input and output are for the proleptic Gregorian calendar.
Parameters
----------
myjd:
julian date (float).
Returns
-------
y, m, d, f : int, int, int, float
Four element tuple containing... | f43a299fd8627804893eb5b6266d6a016c191d72 | 703,946 |
def get_policy_targets(context, presentation):
"""
Returns our target node templates and groups if we have them.
"""
node_templates = []
groups = []
our_targets = presentation.targets
if our_targets:
all_node_templates = \
context.presentation.get('service_template', 't... | f483b9749c25b7d56c0e0a02a6787d936782e470 | 703,948 |
def merge_df(df1, df2):
""" Genera un dataframe seleccionant les columnes que ens
interessen dels dos dataframes, eliminant valors NA, i actualitza
les notes de '538 Grade' simplificant-les.
Keyword arguments:
df1 -- dataframe que conté les dades de les entrevistes.
df2 -- dataframe que conté l... | 955569ebbbbcf141eedd64ca3ee9b9b89f7922be | 703,949 |
import torch
def isPD(B):
"""Check whether a matrix is positive definite.
Args:
B ([torch.Tensor]): [Input matrix.]
Returns:
[bool]: [Returns True if matrix is positive definite, otherwise False.]
"""
try:
_ = torch.cholesky(B)
return True
except RuntimeError:... | c51dc4f6f48ac7417f49ef41b81f3b04816b9279 | 703,950 |
def convert_TriMap_to_SelectedLEDs( best_led_config ):
""" Returns a lookup dict of the selected LEDs.
"""
d = {}
for tri_num in best_led_config:
for led_num in best_led_config[tri_num]:
d[led_num] = True
return d | 521a1be0d11cb8198944e437d20d4ac0349c8856 | 703,951 |
def _run_symbolic_method(op_name, symbolic_fn, args):
"""
This trampoline function gets invoked for every symbolic method
call from C++.
"""
try:
return symbolic_fn(*args)
except TypeError as e:
# Handle the specific case where we didn't successfully dispatch
# to symboli... | c95f8d18e4b3a0ed7a06ccc6bdf178a820537d08 | 703,952 |
def get_table_id(table):
"""
Returns id column of the cdm table
:param table: cdm table name
:return: id column name for the table
"""
return table + '_id' | 33fd8f445f15fb7e7c22535a31249abf6f0c819b | 703,954 |
from typing import Sequence
from typing import Hashable
def all_items_present(sequence: Sequence[Hashable], values: Sequence[Hashable]) -> bool:
"""
Check whether all provided `values` are present at any index
in the provided `sequence`.
Arguments:
sequence: An iterable of Hashable values to ... | f43a881159ccf147d3bc22cfeb261620fff67d7a | 703,955 |
def reorder(rules):
""" Set in ascending order a list of rules, based on their score.
"""
return(sorted(rules, key = lambda x : x.score)) | cf4ff3b8d8aacd5e868ee468b37071fed2c1d67e | 703,956 |
import re
def extract_floats(string):
"""Extract all real numbers from the string into a list (used to parse the CMI gateway's cgi output)."""
return [float(t) for t in re.findall(r'[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?', string)] | 0dc26261d45bd0974e925df5ed660a6e31adf30c | 703,957 |
def binary(n, digits):
"""Returns a tuple of (digits) integers representing the
integer (n) in binary. For example, binary(3,3) returns (0, 1, 1)"""
t = []
for i in range(digits):
n, r = divmod(n, 2)
t.append(r)
return tuple(reversed(t)) | bc52a985b86954b1d23bb80a14c56b3e3dfb7c59 | 703,958 |
import sympy
def GetShapeFunctionDefinitionLine3D3N(x,xg):
""" This computes the shape functions on 3D line
Keyword arguments:
x -- Definition of line
xg -- Gauss point
"""
N = sympy.zeros(3)
N[1] = -(((x[1,2]-x[2,2])*(x[2,0]+x[2,1]-xg[0]-xg[1])-(x[1,0]+x[1,1]-x[2,0]-x[2,1])*(x[2,2]-xg[2]... | aaa2f5b7afac4afc60d2b79ef3f22fba3553aabb | 703,959 |
import os
def picasso() -> dict:
"""Handler for service discovery
:returns: picasso service descriptor
:rtype: dict
"""
return {"app": "demo-man", "svc": "picasso", "version": os.environ["VERSION"]} | d8e8fe0ca6287536143149edd47c2e42f932a515 | 703,960 |
def _sorted_photon_data_tables(h5file):
"""Return a sorted list of keys "photon_dataN", sorted by N.
If there is only one "photon_data" (with no N) it returns the list
['photon_data'].
"""
prefix = 'photon_data'
ph_datas = [n for n in h5file.root._f_iter_nodes()
if n._v_name.sta... | a8df6edb5cfa9b328d7648e0c9ab9f883812ee5a | 703,962 |
def prepare_wld(bbox, mwidth, mheight):
"""Create georeferencing world file"""
pixel_x_size = (bbox.maxx - bbox.minx) / mwidth
pixel_y_size = (bbox.maxy - bbox.miny) / mheight
left_pixel_center_x = bbox.minx + pixel_x_size * 0.5
top_pixel_center_y = bbox.maxy - pixel_y_size * 0.5
return ''.join(... | 668c348d74780a79a39ebc53f3f119ea37855e8e | 703,963 |
def graphql_refresh_token_mutation(client, variables):
"""
Refreshes an auth token
:param client:
:param variables: contains a token key that is the token to update
:return:
"""
return client.execute('''
mutation refreshTokenMutation($token: String!) {
refreshToken(token: $to... | c217217b289a188de8709dbe875853329d2c3fbc | 703,964 |
def check_duplicate_stats(stats1, stats2, threshold=0.01):
"""
Check two lists of paired statistics for duplicates.
Returns a list of the pairs that agree within to <1%.
INPUTS:
STATS1 : List of first statistical metric, e.g. Standard Deviations
STATS2 : List of second statistical metric, e.g.... | eb75d9d02a92cdb337dcbc100b282773543ac894 | 703,965 |
import re
def _parse_uci_regression_dataset(name_str):
"""Parse name and seed for uci regression data.
E.g. yacht_2 is the yacht dataset with seed 2.
"""
pattern_string = "(?P<name>[a-z]+)_(?P<seed>[0-9]+)"
pattern = re.compile(pattern_string)
matched = pattern.match(name_str)
if matched:
name = ma... | dd2158e1a5ceeba25a088b07ff8064e8016ae551 | 703,966 |
import re
def get_params(proto):
""" get the list of parameters from a function prototype
example: proto = "int main (int argc, char ** argv)"
returns: ['int argc', 'char ** argv']
"""
paramregex = re.compile('.*\((.*)\);')
a = paramregex.findall(proto)[0].split(', ')
#a = [i.replace('cons... | 37841b2503f53353fcbb881993e8b486c199ea58 | 703,967 |
import inspect
def list_module_public_functions(mod, excepted=()):
""" Build the list of all public functions of a module.
Args:
mod: Module to parse
excepted: List of function names to not include. Default is none.
Returns:
List of public functions declared in this module
"... | d27dc869cf12701bcb7d2406d60a51a8539a9e1b | 703,968 |
def translate_marker_and_linestyle_to_Plotly_mode(marker, linestyle):
"""<marker> and <linestyle> are each one and only one of the valid
options for each object."""
if marker is None and linestyle != 'none':
mode = 'lines'
elif marker is not None and linestyle != 'none':
mode = 'lines+markers'
elif marker is n... | 53de94176afe47f5a9b69e7ad676853b4b19a8db | 703,969 |
def strRT(R, T):
"""Returns a string for a rotation/translation pair in a readable form.
"""
x = "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[0,0], R[0,1], R[0,2], T[0])
x += "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[1,0], R[1,1], R[1,2], T[1])
x += "[%6.3f %6.3f %6.3f %6.3f]\n" % (
R[2,0]... | 2d7ec1bf2ebd5a03472b7b6155ed43fdcc71f76a | 703,971 |
def extract_classes(document):
""" document = "545,32 8:1 18:2"
extract_classes(document) => returns "545,32"
"""
return document.split()[0] | b7e8fed3a60e3e1d51a067bef91367f960e34e6b | 703,972 |
def general_value(value):
"""Checks if value is generally valid
Returns:
200 if ok,
700 if ',' in value,
701 if '\n' in value"""
if ',' in value:
return 700
elif '\n' in value:
return 701
else:
return 200 | 5cf8388294cae31ca70ce528b38ca78cdfd85c2c | 703,973 |
def _cast_to(matrix, dtype):
""" Make a copy of the array as double precision floats or return the reference if it already is"""
return matrix.astype(dtype) if matrix.dtype != dtype else matrix | 9625311c0918ca71c679b1ac43abe67f2a4b0f2d | 703,974 |
def reverse_str(string):
"""
Base case: length of string
Modification: str slice
"""
if len(string) == 1:
return string
return reverse_str(string[1:]) + string[0] | eb0d27816e8fe54f1136f4a507478f40a3354d72 | 703,975 |
def find_key_value_in_list(listing, key, value):
"""
look for key with value in list and return dict
:param listing:
:param key:
:param value:
:return: dict_found
"""
# for l in listing:
# if key in l.keys():
# if l[key] == value:
# print("l[key = ", v... | 642d8e43cbfbeef9bc014c85085c7027380156e2 | 703,976 |
def remove_duplicates(df, by=["full_text"]):
"""
Remove duplicates from raw data file by specific columns and save results in file with name given.
"""
boolean_mask = df.duplicated(subset=by, keep="first")
df = df[~boolean_mask]
return df | dfe99259a90280b346290dd2c880ab51e443e036 | 703,978 |
def tex_parenthesis(obj):
"""Return obj with parenthesis if there is a plus or minus sign."""
result = str(obj)
return f"({result})" if "+" in result or "-" in result else result | 356a3886d27d431e90de2a76e6590481ad85f05e | 703,979 |
def swap_target_nonterminals(target):
"""
Swap non-terminal tokens.
:param target: List of target tokens
:return: List of target tokens
"""
return ['X_1' if token == 'X_0' else 'X_0' if token == 'X_1' else token for token in target] | 56e91df1a513ee5dad1071337463e039ded57a86 | 703,980 |
import os
import stat
def is_executable_file(path):
"""Checks that path is an executable regular file (or a symlink to a file).
This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``, but
on some platforms :func:`os.access` gives us the wrong answer, so this
checks permission bits dire... | b9ec4bfa15d0a121ff4958b146d8e1646e6b15ed | 703,981 |
def padZeros(numberString, numZeros, insertSide):
"""Return a string padded with zeros on the left or right side."""
if insertSide == 'left':
return '0' * numZeros + numberString
elif insertSide == 'right':
return numberString + '0' * numZeros | d0c2d08a392e4792b13a64d076c8fb6aff1572cb | 703,982 |
def readdirs(DIR):
"""Implementation of perl readdir in list context"""
result = (DIR[0])[DIR[1]:]
DIR[1] = len(DIR[0])
return result | 98d9b588704ea2820b14ba2c5542ea0a619a02ce | 703,983 |
def behav_data_inverted(df):
"""
Flips the dimensions that need inverting
Faster than using is_inverted_dim
"""
# Apparently groupby with categorical dtype is broken
# See https://github.com/pandas-dev/pandas/issues/22512#issuecomment-422422573
df["class_"] = df["class_"].astype(str)
inv... | 69ad0d4cea1a12b2dd8dc256c77b13f1002ae6b8 | 703,984 |
def _resample_event_obs(obs, fx, obs_data):
"""
Resample the event observation.
Parameters
----------
obs : datamodel.Observation
The Observation being resampled.
fx : datamodel.EventForecast
The corresponding Forecast.
obs_data : pd.Series
Timeseries data of the eve... | 1c66ae124aaa2e732c7d0ec3e733ae2b5caaa6cb | 703,985 |
def _arg_raw(dvi, delta):
"""Return *delta* without reading anything more from the dvi file"""
return delta | 041cfaaf23c6e229b60d5278e8cf27352e078a65 | 703,986 |
def to_bytes(binary_string: str) -> bytes:
"""Change a string, like "00000011" to a bytestring
:param str binary_string: The string
:returns: The bytestring
:rtype: bytes
"""
if len(binary_string) % 8 != 0:
binary_string += "0" * (
8 - len(binary_string) % 8
) # fill... | 83dda243e27d7f7988d520c0455e43d1937d5447 | 703,987 |
def _read_tmpfd(fil):
"""Read from a temporary file object
Call this method only when nothing more will be written to the temporary
file - i.e., all the writing has already been done.
"""
fil.seek(0)
return fil.read() | 08648325e7e0e9bcd543d3238cb4630ac284f6ed | 703,988 |
def evens(input):
"""
Returns a list with only the even elements of data
Example: evens([0, 1, 2, 3, 4]) returns [0,2,4]
Parameter input: The data to process
Precondition: input an iterable, each element an int
"""
result = []
for x in input:
if x % 2 == 0:
result.a... | 8a219f8815d95a18bea148eaae117f3356a77d4b | 703,989 |
def _check_insert_data(obj, datatype, name):
""" Checks validity of an object """
if obj is None:
return False
if not isinstance(obj, datatype):
raise TypeError("{} must be {}; got {}".format(
name, datatype.__name__, type(obj).__name__))
return True | 057d0124db3f304e7efd4093510c663f5383af63 | 703,990 |
import os
def dir_exists(foldername):
""" Return True if folder exists, else False
"""
return os.path.isdir(foldername) | edf3bc0dcdb16e816f48134ede420b758aa53d16 | 703,991 |
def piece_not(piece: str) -> str:
"""
helper function to return the other game piece that is not the current game piece
Preconditions:
- piece in {'x', 'o'}
>>> piece_not('x')
'o'
>>> piece_not('o')
'x'
"""
return 'x' if piece == 'o' else 'o' | 18bb3b45accf98d4f914e3f50372c4c083c1db4d | 703,992 |
def argsum(*args):
"""sum of all arguments"""
return sum(args) | 2445ef4f3fc321b3eae1997a8c44c628cd72d70a | 703,993 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.