content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import sys
def fg_args():
"""Get/format the script arguments.
Args:
N/A
Returns:
script args (str)
"""
return "".join(f"{i}: {j}\n" for i, j in enumerate(sys.argv[1:], 1)) | 0c08e903380c96ff84bf4d70cf4fc27483d64a12 | 45,584 |
import re
def GetMakeFileVars(makefile_path):
"""Extracts variable definitions from the given make file.
Args:
makefile_path: Path to the make file.
Returns:
A dictionary mapping variable names to their assigned value.
"""
result = {}
pattern = re.compile(r'^\s*([^:#=\s]+)\s*:=\s*(.*?[^\\])$', r... | 7869801b18a4e4aa1cdc3e5d30219ed449e897ac | 45,587 |
import random
def ranf(x1, x2):
"""
return random float between x1 and x2
:param float x1:
:param float x2:
:return float:
"""
return random.uniform(x1, x2) | 6b17e1e5ff3293a8ad4b5027caf9db954bbfb6da | 45,589 |
import re
def _search(value):
"""
Maps to `re.search` (match anywhere in `v`).
"""
return lambda v: re.search(value, v) | 9d03811520c32d1aa7ab8fde8b913d8ad59456af | 45,590 |
def deletepickup_lines(pickup_linesId): # noqa: E501
"""Delete a pickup_lines
Deletes an existing `pickup_lines`. # noqa: E501
:param pickup_linesId: A unique identifier for a `pickup_lines`.
:type pickup_linesId: str
:rtype: None
"""
return 'do some magic!' | 2dff6f98ec03e04f3131c5531e602a4d3f7250e3 | 45,592 |
def _parse_ids(ids, info_dict):
"""Parse different formats of ``ids`` into the right dictionary format,
potentially using the information in ``info_dict`` to complete it.
"""
if ids is None:
# Infer all id information from info_dict
return {outer_key: inner_dict.keys() for outer_key, inn... | f3771a753d30a81e9f0dcd0120708f862bfd8466 | 45,593 |
def read_predictions(pred_file):
"""
Read a predictions file with format:
SEQUENCE1 pred1 err1
SEQUENCE2 pred2 err2
... ...
return a dictionary mapping sequence to prediction
"""
out_dict = {}
with open(pred_file) as lines:
for l in lines:
if l.... | 5081027deff7c05d4abe23d757a5156d92f355ff | 45,594 |
import requests
def acessar_links(urls):
"""
função responsavel por acessar os links do site da Brasil Escola.
"""
return [requests.get(site) for site in urls] | 1976187ec3f67476bc40b796c06824532393588b | 45,595 |
def backends_mapping(custom_backend, httpbin_original, httpbin_new):
"""
Creates custom backends with paths "/orig", "/new,
using deployed httpbin_original and httpbin_new as
the upstream APIs
"""
return {
"/orig": custom_backend("backend-orig", httpbin_original),
"/new": custom_... | 16ccc00a449081eb0418ac5a1d193f04caa1407a | 45,596 |
def half_odd_array(r):
"""Return r that ends in .5"""
int_width = int(2*r)
# force odd width
if int_width%2==0:
int_width+=1
new_r = int_width/2.0
assert new_r-0.5==int(new_r)
return new_r | e807b4ef37fbb9105b77fe0f31bdb398cbe39106 | 45,597 |
def import_file(path):
"""Import and parse the triggers file"""
if path.lower().endswith('.txt'):
# open file and readlines
with open(path, 'r') as trigger_file:
content = trigger_file.readlines()
# remove new lines
parsed_text = [x.strip() for x in content]... | 11d36ad2b9ceb30eb713173fb8bfa50cb46cc0f4 | 45,598 |
import importlib
def create_ajaxable_view_from_model_inherit_parent_class(model_class, parent_class_list, operation="Create"):
"""
:param model_class: the django model class
:param operation: "Create" or "Update"
:param ajax_mixin: user may pass a sub class of AjaxableResponseMixin to put more info in... | 00c007b28dd41ae887ec0741cddb632d7d62bcf5 | 45,599 |
import torch
def isRotationMatrix(R):
"""R*R^{-1}=I"""
return torch.norm(torch.eye(3, dtype=R.dtype)-R.mm(R.t())) < 1e-6 | 62f526afa339bf23b49aa67dae18c9f03658b71e | 45,600 |
def id_field_creation(invoice_id, batch_number, sequence_number):
"""
Returns a field for matching between Fiserv and Smartfolio
It is defined as a concatenation of the Credit Card number and the invoice ID
:return: str
"""
## Old ID included sequence number but this was changing over time... | 2a26299ffd4a0fcf40f6401e38a467e61cb6eebd | 45,602 |
def configure_simulation(independent_variable_value, input_params, empirical_profile, original_team_size,
configuration_function, simulation_configuration):
"""
Adjusts the simulation configuration to the current independent variable value.
:param independent_variable_value:
:re... | 75cb70c042f766d098bdf73ac6a30743a2d93fed | 45,603 |
import inspect
def bold_title(text: str) -> str:
"""
Create bold title in exam header
:return: latex code
"""
return inspect.cleandoc(rf"""
\begin{{center}}
\textbf {{ {{\Large {text} }} }}
\end{{center}}
""") | 73f29514761c55e97a0edd5d54dc01f2c76108c4 | 45,604 |
def calculate_damage(attacker, defender):
"""Calculate and return effective power of attacker against defender.
args:
attacker: [side, units, hit_points, weaknesses, immunities,
damage, damage_type, initiative]
defender: [side, units, hit_points, weaknesses, ... | 093e3a95ce4db864f4c4e9526e2b16378d407b7e | 45,605 |
import sys
def is_hooked():
"""
Returns
-------
:class:`bool`
Whether prettify, or another module, is hooked into :attr:`sys.excepthook`.
"""
return sys.excepthook is not sys.__excepthook__ | ec1445e18f0a5a7b3532f619863e3fbf19ea7990 | 45,606 |
import re
def Tagcleaner(text):
"""
Remove "<>" tags from text
and return cleaned text
"""
# import re
cleanr = re.compile('<.*?>')
text_clean = re.sub(cleanr, '', text)
return text_clean | fa563b8ca252fd3bf65351ac67ed6549f996a833 | 45,607 |
import sqlite3
import pandas
def get_cdr_data_table_df(db_path):
"""
Get a dataframe with typical info from the cdr_data table in the PyIgClassify db.
:param db_con: sqlite3.con
:rtype: pandas.DataFrame
"""
query="SELECT "\
"cdr_data.PDB," \
"cdr_data.gene," \
... | ecb8efef7cf4c724ec7784c3ff98670385c12293 | 45,608 |
def afmSetup(x_input, y_input, n_trees=5, n_depth=5, n_feature_vector=1):
"""
afmSetup creates the necessary arrays and variables for the rest
of the afmMiner module
"""
###Setup user defined variables
x9x9 = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
x7x7 = [-3, -2, -1, 0, 1, 2, 3]
x5x5 = [-2, -1... | d375a7568e2dbc70d635821d6204ee7c47bb7933 | 45,610 |
def get_category_info_from_anno(anno_file, with_background=True):
"""
Get class id to category id map and category id
to category name map from annotation file.
Args:
anno_file (str): annotation file path
with_background (bool, default True):
whether load background as class... | 1fa8a5c8c3af52b8a2a65e8494e20a27d2c79101 | 45,611 |
def parse_line(line):
"""
line is in the format distance,zipcode,city,state,gender,race,income,price
"""
line = line.strip().split(",")[1:]
# zipcode = str(line[0])
# city = str(line[1])
state = str(line[2])
gender = str(line[3])
race = str(line[4])
income = str(line[5])
pric... | e8354ae51bc8fdc856dc6cf38fe9b8abb51fa2c9 | 45,612 |
def get_magmom_string(structure):
"""
Based on a POSCAR, returns the string required for the MAGMOM
setting in the INCAR. Initializes transition metals with 6.0
bohr magneton and all others with 0.5.
Args:
structure (Structure): Pymatgen Structure object
Returns:
string with IN... | e9ae02d20c34cfade463374b83fedfee86838155 | 45,613 |
import codecs
def char_frequency(file_path):
"""count very char in the input file.
Args:
file_path: input file
return:
a dictionary of char and count
"""
char_count_dict = dict()
with codecs.open(file_path, encoding='utf-8-sig') as input_file:
for line in input_file.readlin... | 2cdb4c66e0822aaeea287e4efce1ef08328d1998 | 45,614 |
def region_cursor_start(region):
"""swap region range so that the end region would be at the beginning
so cursor starts from the beginning when highlighted"""
if region.b > region.a:
region.a, region.b = region.b, region.a
return region | 2aa9622e8a783179d0945e815ac3ef89da2d4c2d | 45,615 |
import torch
def kronecker(A, B):
"""
Return the kronecker product between two matrices [1].
Args:
A (torch.Tensor): 1st matrix.
B (torch.Tensor): 2nd matrix.
Returns:
torch.Tensor: kronecker product between two matrices
References:
[1] Kronecker product (Wikiped... | d6c987cc0c3a40e1396086fd725a067e01fa3f68 | 45,617 |
import os
def create_locator_method(lm, schema):
"""
Returns a function that works as an InputLocator method - it reads the
:param str lm: the name of the locator method
:param dict schema: the configuration of this locator method as defined in schemas.yml
:return: the locator method (note, only k... | 368cb2904c23c7274b23f6b3299a88b3ae067419 | 45,618 |
def longest_row_number(array):
"""Find the length of the longest row in the array
:param list in_array: a list of arrays
"""
if len(array) > 0:
# map runs len() against each member of the array
return max(map(len, array))
else:
return 0 | 515a357bdb5d180fa48fb3accd0f47fe6f22d8d3 | 45,621 |
def _positive_int(integer_string):
"""
将一个字符串转成正整数
"""
ret = int(integer_string)
if ret <= 0:
raise ValueError()
return ret | 5e7541fcc9dc8a5b68a3b714ff28a6f8586c56c2 | 45,623 |
def change_mass_res(dm_oldres, x_oldres, dm_newres):
"""for mass grid with cell masses dm_oldres, and abundances
x_oldres, find abundances at new resolution grid with cell masses
dm_newres
"""
x_newres = dm_newres * 0.0
l_new = 0
l_old = 0
Nnew = len(dm_newres)
Nold = le... | d07e2b4aded7d9186837d1742421e5483ce3151e | 45,624 |
def _check_func_names(selected, feature_funcs_names):
""" Checks if the names of selected feature functions match the available
feature functions.
Parameters
----------
selected : list of str
Names of the selected feature functions.
feature_funcs_names : dict-keys or list
Names... | b8f036dad2b777142de3c98cd3928d6d22fa52cb | 45,625 |
def list_to_str(a_list,
delimiter = "\t",
newline = True):
"""
=================================================================================================
list_to_str(a_list, delimiter, newline)
Given a list, the delimiter (default '\t'), and whether to add a ... | 827275cc7a0207578158be7d5d5aefd18028992d | 45,626 |
def is_enclosed(expression):
"""
Check if the the expression is enclosed in brackets
>>> is_enclosed('(foo)(bar)')
False
>>> is_enclosed('((foo)(bar))')
True
>>> is_enclosed('[[foo]{bar}]')
True
"""
brackets = ["()", "[]", "{}"]
if expression[0] + expression[-1] not in brackets:
return False
... | dfc63a83011342d1713e91abcc9cea6ddafae6fa | 45,627 |
def getScalarsType(colouringOptions):
"""
Return scalars type based on colouring options
"""
# scalar type
if colouringOptions.colourBy == "Species" or colouringOptions.colourBy == "Solid colour":
scalarType = 0
elif colouringOptions.colourBy == "Height":
scalarType = 1... | 35c2dfaab09f5a4ddee0321605d05575ccca95f0 | 45,628 |
def _build_msg_fqn(msg_obj):
"""Build FQN in form of package name."""
if "." in msg_obj.fqn:
values = msg_obj.fqn.split(".")
pkg = ".".join(values[:-1]).lower()
fqn = pkg + "." + msg_obj.name
return fqn
else:
return msg_obj.name | cd1e39a3201d3a770a6da5d79fd5022da1e6375d | 45,629 |
import sys
def getProjectId():
"""Retrieves the project id from the script arguments.
Returns:
str -- the project name
Exits when project id is not set
"""
try:
project_id = sys.argv[1]
except:
exit('Missing Project ID. Usage: python3 monitoring_integration_test.py $PRO... | 0260d832990d7f93f7b7fb153debaba5c5fc8a80 | 45,631 |
def remove_keys(dct, keys=[]):
"""Remove keys from a dict."""
return {key: val for key, val in dct.items() if key not in keys} | 7ccab472f303350c5a2a6b07d62dffc74affdf0b | 45,632 |
def text_objects(text, font, color):
""" convert the supplied text to a text surface """
textSurface = font.render(text, True, color)
return textSurface, textSurface.get_rect() | 8b9cf9d8c092c3f1b9f9608ed3c1a5b9023aa82b | 45,633 |
def add_percentile(df, fig):
"""Adds percebtile lines to an existing graphic based on the dataframe
Parameters
----------
df (Dataframe): Dataframe with the data to generate the percentiles
fig (Figure): original figure
Returns
-------
fig: figure with the trendline include... | dddf08632b22697528cc20befae275a5dab7ba2f | 45,634 |
from typing import Callable
import importlib
def get_resource_handler(function_name: str) -> Callable:
"""Return our handler from ResourceHandler class"""
module_name, klass_name, func_name = function_name.rsplit('.', 2)
module = importlib.import_module(module_name)
klass = getattr(module, klass_nam... | e9c7a5afb755f9f671a449355faa3ca75447981c | 45,635 |
def diff_3(arrA, arrB):
"""
Using XOR
"""
return list(set(arrA) ^ set(arrB)) | 2bb977191c070a748891ac6b52036f9efbaf0c58 | 45,636 |
from datetime import datetime
def default_date():
"""Return a string representing the current date
>>> default_date()
'20210729'
:return: A date in a string
:rtype: str
"""
return datetime.now().strftime("%Y%m%d") | 46494a8877a6baf5f944975123efdb26a6305839 | 45,637 |
import os
def extract_extension(path):
"""
Reads a file path and returns the extension or None if the path
contains no extension.
:Parameters:
path : str
A filesystem path
"""
filename = os.path.basename(path)
parts = filename.split(".")
if len(parts) == 1:
... | b58e9a00e9d4c29bf507a85da3a12a1479723ea4 | 45,638 |
def conf_keywords():
"""Conf the wrap line key words. """
wrap_keywords = ['left hash join', 'hash join', 'left join', 'inner join', 'outer join', 'right join', 'where',
'group by', 'order by', 'select', 'from', 'having', 'join', 'on', 'using', 'with']
func_keywords = ['sum', 'min', 'm... | 65f7032987fc6610eb55ded1dc6d29043badcae0 | 45,639 |
import itertools
def proportion_with_neighbours(block_list):
"""
Calculate the percentage of positive windows that have positive neighbours
:param list block_list: list of positive windows.
:returns: Percentage positive windows with positive neighbours.
"""
no_with_neighbours = 0
for key... | de314f13a234a90dcb4698666943a2a6619e9318 | 45,640 |
def _filter_methods(methods: set) -> set:
"""Filter out HEAD and OPTIONS methods.
Not instrumenting HEAD and OPTIONS methods by default.
"""
return set(filter(
lambda x: x not in {'HEAD', 'OPTIONS'},
methods,
)) | f7fbf4d5bf9a0f74d4377a9dcff364c857fba940 | 45,642 |
from re import match
from re import split
def _list_of_countries(value):
"""
Parses a comma or semicolon delimited list of ISO 3166-1 alpha-2 codes,
discarding those which don't match our expected format. We also allow a
special pseudo-country code "iso".
Returns a list of lower-case, stripped co... | e5bb98b1f4b60aa2ccf6105eaec03b6e686a9c47 | 45,643 |
def _is_ipv4_like(s):
"""Find if a string superficially looks like an IPv4 address.
AWS documentation plays it fast and loose with this; in other
regions, it seems like even non-valid IPv4 addresses (in
particular, ones that possess decimal numbers out of range for
IPv4) are rejected.
"""
p... | e252ceed3270fdec37b6285492af49ff4b661a20 | 45,644 |
def getDate(timestamp):
"""
Extracts the date from a timestamp.
:param timestamp: The timestamp from which the date should be obtained. \t
:type timestamp: string \n
:returns: The date info of the timestamp. \t
:rtype: string \n
"""
return timestamp.split('T')[0] | 8b612541dc17d76e0b17d9c774597a740f969b98 | 45,645 |
def _gr_ymax_ ( graph ) :
""" Get maximal x for the points
>>> graph = ...
>>> ymax = graph.ymax ()
"""
return graph.bb() [ 3 ] | ae97976f11395cf75026cfdca7c82ad0f9a239bb | 45,646 |
import os
def _get_ca_bundle():
"""Tries to find the platform ca bundle for the system (on linux systems)"""
ca_bundles = [
# list taken from https://golang.org/src/crypto/x509/root_linux.go
"/etc/ssl/certs/ca-certificates.crt", # Debian/Ubuntu/Gentoo etc.
"/etc/pki/tls/... | 0ae6b89ca420ded37c673e768eec1fc82ef5c082 | 45,647 |
def get_xy(df, y, mask, vars):
"""Returns specified X and y with reset indices."""
X = df.loc[mask, vars].reset_index(drop=True)
y = df.loc[mask, y].reset_index(drop=True)
return X, y | 7ca6021453b628f017570e279968397110109f97 | 45,649 |
def fib(n, start=(0, 1)):
"""iterative fibonacci function"""
a, b = start
while n > 0:
a, b = b, a + b
n -= 1
return n | 7f08b8965c1de682e77a60313601d78616ef62fd | 45,650 |
def kelvin_to_celsius( arg1 ):
""" Function to convert kelvin to celsius.
Takes a single flaot as an argument and returns a float itself. """
celsius = (arg1 - 273.15)
return "{:.2f}".format(celsius) | 212e2ce8af4607b23ced3cc12b62adea443ad670 | 45,651 |
import os
def extractJobId(datacat_path):
"""Extract the eTraveler job ID from the filename path."""
return int(os.path.basename(os.path.split(datacat_path)[0])) | 332dd26dccffb0a9c26c712a1a129c3e5f95cf7b | 45,655 |
def num(r):
"""
Convert from Z3 to python float values.
"""
return float(r.numerator_as_long()) / float(r.denominator_as_long()) | dbb41e4d490bb6495fa1e3440472b72614a47075 | 45,658 |
import binascii
import os
def generate_random_id(length):
"""Generates a random ID.
Args:
length: Length of a generated random ID. Must be an even number.
Returns:
Generated random ID string.
"""
assert length % 2 == 0
return binascii.hexlify(os.urandom(length / 2)) | 4ede66b57bca9723e075804829ff220076abcd63 | 45,659 |
def sum_two_smallest_numbers(numbers):
"""This will find the sum of the two lowest ints in a string."""
x = sorted(numbers)[:2]
return x[0] + x[1] | f033465bbf4404acc5aecb9a451846dc2c5c862c | 45,660 |
def expand_skipgrams_word_list(wlist, qsize, output, sep='~'):
"""Expands a list of words into a list of skipgrams. It uses `sep` to join words
:param wlist: List of words computed by :py:func:`microtc.textmodel.get_word_list`.
:type wlist: list
:param qsize: (qsize, skip) qsize is the q-gram size and ... | 8a4402b47d0a644f0a3f99df92e6071c1597ea6d | 45,661 |
def create_system_dict(df):
"""
Reads a pandas dataFrame and creates a dictionary where the keys are the site ids and the values are a the list of
systems for each site.
:param df: pandas dataFrame with site and system information a `site` and a `system` column.
:return: dictionary with systems asso... | 843336cd4dfdb4dbc7580ae2c815724f0270bf10 | 45,663 |
def get_port_mtu(duthost, interface):
"""
Get MTU of port from interface name
Args:
duthost: DUT host object
interface: Full interface name
Returns: MTU
"""
out = ''
if '.' in interface:
out = duthost.show_and_parse("show subinterface status {}".format(interface))
... | f0b3cb81a16cb37b2e407d17876cd3e88b19b427 | 45,664 |
def add_request_to_kwargs(method):
"""
This is decorator for adding request to passed arguments.
For example::
class MainApiClass(object):
@add_request_to_kwargs
def func2(self, user, request):
return Msg(u'func2')
"""
def extra_kwargs_func(request, ... | 758c80cb1571f6e9af46df41b86fb1aea405731b | 45,665 |
def binding_energy(proton_seq, affinities):
"""Calculate binding energy from proton affinities
Parameters
----------
proton_seq : ndarray
protonation state of residues
affinities : ndarray
proton affinities for residues
Returns
-------
binding energy : float
Bin... | 23201ae7bca072f3b1d971e7e15ad4fd485eda79 | 45,666 |
def extract_file_names(arg, val, args, acc):
"""
action used to convert string from --files parameter into a list of file name
"""
acc[arg] = val.split(',')
return args, acc | df5056e903e68d539fd09ed9fdf7a9c817e6e080 | 45,668 |
def clean(s):
""" Remove white spaces from <s>. """
return s.strip(' \t\n\r\f\v') | 65e16099090d4af8ab289ddd8e12321305fc70d0 | 45,669 |
from typing import Callable
def extract_name(callable: Callable) -> str:
""" Given a callable that could be either a class or a function, retrieve
its name at runtime for subsequent use
Args:
callable (Callable): Callable whose name is to be extracted
Return:
Name of callable (str... | 7b4a04856abd2601b26cf0623ac961bc86c9790c | 45,670 |
def subs(a, b):
"""Function that subtracts lists element by element.
Parameters
----------
a
b
"""
for i, val in enumerate(a):
val = val - b[i]
a[i] = val
return a | c1ad3dfa547ea8157f74b8a09ff698b9e48fcde7 | 45,671 |
def get_contributors(raw):
"""
Extract contributors.
Only contributors tagged as belonging
to any of the valid roles will be extracted.
@param raw: json object of a Libris edition
@type raw: dictionary
"""
valid_roles = ["author", "editor",
"translator", "illustrator... | 18e8b3737643e825b7e94a75603883086f5a37d1 | 45,672 |
def get_perf_dict(ndisk, medium, iotype):
"""Basic IOPS budgetting"""
unit = 200
if medium == 'hdd':
unit = 200
elif medium == 'ssd':
unit = 70000
elif medium == 'nvme':
unit = 700000
r = {
'jbod': unit,
'raid0': ndisk * unit,
'raid1': ndisk * un... | cf7d2d474242811debf33b404aa8ffcd97d383fe | 45,673 |
def _setup_motifs_files(args):
"""convenience fn, make sure setup is same across
multiplicity/orientation/spacing workflows
"""
motifs_files = {}
motifs_files["early"] = "{}/{}/ggr.scanmotifs.h5".format(
args.inputs["inference"][args.cluster]["scanmotifs_dir"],
args.inputs["inferenc... | a0d3acd6451e97d42e5239b7685525e04ed3eb0c | 45,674 |
import sys
import subprocess
def _LoadInstrumentedImageInNewProc(opts):
"""Loads opts.instrumented_image in a sub-process using --load-image.
Args:
opts: the parsed and validated arguments.
Returns:
True on success, False otherwise.
"""
cmd = [sys.executable, __file__, '--build-dir', opts.build_di... | b516004adda467d42f7c43ad96ab0e28cab22eea | 45,675 |
def dividers_num(num):
"""
выводит список всех делителей числа
:param num:
:return:
"""
result = []
for i in range(1, num//2 + 1):
if num % i == 0:
result.append(i)
return result + [num] | 3de297f43fdf863c78db9c458eab9c7b56425122 | 45,676 |
import os
def _repo_path(cfg, key=None):
"""Return path to root directory of repository or subdirectory
:return: path
"""
repo = cfg['repository']
if 'path' in repo:
path = repo['path']
else:
path = os.getcwd()
subdir = '' if key is None else repo[key]
return os.path.n... | 172356588817fcc00936e7585ec7cdffbb47191c | 45,678 |
import os
import gzip
import zipfile
import codecs
def read(fil):
"""Returns a file handler and detects gzipped files."""
if os.path.splitext(fil)[-1] == '.gz':
return gzip.open(fil, 'rb')
elif os.path.splitext(fil)[-1] == '.zip':
zf = zipfile.ZipFile(fil, 'r')
return zf.open(zf.in... | e0da80871a357af2e909ee966c6c5cce778f1c53 | 45,679 |
def add_main_cat(df):
""" Takes a df and adds a column with the main category
input:
df (pd.DataFrame): dataframe to add column to, must contain "cat_id"
returns:
df (pd.DataFrame): dataframe with extracted main cat
"""
df["main_cat"] = df["cat_id"].astype(str).str.s... | 213e3c068adfba336c9610c208f46057ecf8b7ee | 45,680 |
from typing import Sequence
def is_palindrome(sequence: Sequence) -> bool:
""" Returns whether a sequence is a palindrome """
return sequence[0:len(sequence) // 2] == sequence[-1:(len(sequence) - 1) // 2:-1] | cf60fa4198d29514f255ed5597187d9ece928626 | 45,681 |
import os
def unique_id():
"""Generates a random 12-byte hexidecimal string"""
return os.urandom(12).hex() | c05333a6286421d6f6c586c02e96a08a29c45115 | 45,682 |
def pytest_report_header(config):
"""Print a message in case the plugin is activated."""
if config.option.dependencies:
return 'Only tests affected by the changed files are being run.' | f1169bcc8747e4f64d4d607e7eef6199928f186b | 45,684 |
def lower_first_char(string):
"""De-capitalize the first letter of a string.
Args:
string (str): The input string.
Returns:
str: The de-capitalized string.
.. note::
This function is not the exact opposite of the capitalize function of the
standard library. For example... | 053b23379ed504268c94194ff54e62b7bb112bfe | 45,685 |
def db_entry_get(db_entry_list, url):
""" Find an existing entry in the database based on url """
matches = [ entry for entry in db_entry_list if entry['url'] == url ]
if len(matches) > 1:
raise Exception('Internal Error: found multiple matching entries for url "{}"'.format(url))
return matches[... | 29ada876907b732d87cf0c32e4d80b155673552c | 45,688 |
def transform_coord(coord, matrix):
"""
Transforms the given coordinate by the given matrix
:param coord: The coordinate to transform (tuple (x, y))
:param matrix: The matrix to transform by (3x3 numpy array)
:return: The transformed coordinate (tuple (x, y), components casted to ints)
"""
h... | 39b75a25fd47c47a8ad9ed27c5c52a901fdd6874 | 45,690 |
import pathlib
import os
def find_features_path(src_path):
"""Find path to the features directory in feature testing layout.
:param src_path: Path to feature or python file
:type src_path: str
:return: Relative pathlib.Path object to features directory
"""
path = pathlib.Path(os.path.expandu... | 6b6c9602bf36ea9180e862169a755fb4b562e656 | 45,691 |
def naiveVarDrop(X, searchCols, tol=0.0001, standardize=False, asList=False,
print_=False):
"""
Drop columns based on which columns have variance below the threshold.
Parameters
----------
X : pandas dataframe
Feature (or design) matrix.
searchCols : list or list-like (... | 9bee1417a6cfff3b398c612463c6f56a163db1ba | 45,692 |
def METADATA_TYPE_PROCESSED():
"""Type for matadata for processed data"""
return "processed" | 28bd78de0d3c03168cf742467f20ecc123cac50e | 45,694 |
def selectCommands(commands, indexList, lineNumbers=False):
"""Prints commands indexed by the list passed."""
commandList = []
for index in indexList:
record = commands[index]['cmd']
if lineNumbers:
record = (index, record)
commandList.append(record)
return comma... | 650632d0e168df8cbf5bc64aa79fd4b8fb746b44 | 45,695 |
def should_go_right(event: dict):
"""Returns true if the current text event implies a "right" button press to proceed."""
if event["text"].startswith("Review"):
return True
elif event["text"].startswith("Amount"):
return True
elif event["text"].startswith("Address"):
return True... | c5c47f5e4f02b6e875e869201d6a266a819d3ba6 | 45,697 |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
"""Return True if the values a and b are close to each other and False otherwise. (Clone from Python 3.5)
Args:
a: A float.
b: A float.
rel_tol: The relative tolerance – it is the maximum allowed difference between a and b, relative to the ... | 270be278b3865f5faebdf1bb436daa7bec90fb9c | 45,699 |
def get_user_identity(event):
"""Gets event identity from event."""
return event['detail'].get('userIdentity', {}) | d90b47ad530ce05fd2e667c2e5499519ea00122a | 45,700 |
import yaml
def read_yaml(infile, log=None) -> dict:
"""
Read YAML file and return a python dictionary
Args:
infile: path to the json file; can be hdfs path
Returns:
python dictionary
"""
if infile.startswith("hdfs"):
raise NotImplementedError
else:
return... | 9c0c2ce90841119d158a72966061db3a7fa9a36a | 45,701 |
def distance_point(p1, p2):
"""
Returns the Euclidian distance between two points.
Retourne la distance euclidienne entre deux points.
@param p1 point 1
@param p2 point 2
@return distance
"""
d = 0
for a, b in zip(p1, p2):
d += (a - b) ** 2
... | 56cbebd2856e870e807fe6a4bd92b914f806d64e | 45,704 |
import os
def _GetTermSizeEnvironment():
"""Returns the terminal x and y dimensions from the environment."""
return (int(os.environ['COLUMNS']), int(os.environ['LINES'])) | bcd53ac354cadddd5de6a16b1d73a1bb361b086f | 45,705 |
import torch
import math
def scalar_field_modes(n, m, dtype=torch.float64, device='cpu'):
"""
sqrt(1 / Energy per mode) and the modes
"""
x = torch.linspace(0, 1, n, dtype=dtype, device=device)
k = torch.arange(1, m + 1, dtype=dtype, device=device)
i, j = torch.meshgrid(k, k)
r = (i.pow(2)... | 02d2794f2a519d645c779e7effc6dae8bdb14ac0 | 45,706 |
def get_cloudines(input_json):
"""Return the cloudiness using a phrase description."""
clouds_val = int(input_json['clouds']['all'])
cloudines = ''
if 11 <= clouds_val < 25:
cloudines = 'Few clouds'
elif 25 <= clouds_val < 50:
cloudines = 'Scattered clouds'
elif 50 <= clouds_val ... | 2dc9a828e6b767504e2632d102e65c352695d7a7 | 45,707 |
def get_extension(t_path):
""" Get extension of the file
:param t_path: path or name of the file
:return: string with extension of the file or empty string if we failed
to get it
"""
path_parts = str.split(t_path, '.')
extension = path_parts[-1:][0]
extension = extension.lower()
re... | 70fa800714c1fbd71f3071ed4832a1cd96f1949f | 45,708 |
import subprocess
def test_lint(recipe):
"""Determine whether recipe file lints.
Args:
recipe: Recipe object.
Returns:
Tuple of Bool: Failure or success, and a string describing the
test and result.
"""
result = False
description = "Recipe file passes plutil -lint test... | 54862a4c5123350ba8385811c0ab997b091134f7 | 45,709 |
def ordered(request):
"""Boolean 'ordered' parameter for Categorical."""
return request.param | deebafb0fc8e254790c0647fce60897c54d4c21f | 45,710 |
def _simple_scalar_str(s):
"""String representation of a simple scalar."""
if isinstance(s, complex):
return "J".join(map(_simple_scalar_str, [s.real, s.imag]))
# Non-complex numeric type:
elif s < 0:
return f"¯{-s}"
elif int(s) == s:
return str(int(s))
else:
ret... | 8e12f27180e8aea173f3d884bec50106b1bde993 | 45,711 |
import os
import errno
def OpenOrCreate (file_name, tag=None, preserve_contents=False):
"""Return a file object used to write binary data into the given file.
Use the C{tag} keyword to preserve the contents of existing files
that are not supposed to be overwritten.
To get a writable file but leaving... | 22e69f5440ec21559f516847ec3457952900c78a | 45,714 |
import os
def load_images():
"""return paths of images of pwd"""
image_files = list(f for f in os.listdir() if f.endswith('.png') or f.endswith('.jpg') or f.endswith('.bmp'))
if image_files:
print('load images {}'.format(image_files))
return image_files
else:
return None | d8dfb9fd9e8bd1aea5ef2ee3e9f2d7a5831fd60c | 45,715 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.