content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def innerscripts_to_array(p):
"""Extracts inner scripts from page"""
res = []
all = p.xpath('//script')
for tag in all:
if 'src' in tag.attrib:
continue
else:
item = {'text' : tag.text_content()}
if 'type' in tag.attrib: item['type'] = tag.attrib['type... | 66780626b854ecefdf629b1b7ba8d7327dcd206e | 681,022 |
def validate_int(arg):
"""Guard against value errors when attempting to
convert a null to int"""
if len(arg) < 1:
return 0
return int(arg) | ab7cc52f4f8330840b6406cafd01b3a594e0e451 | 681,023 |
def genome_size(peaks_file, haploid=True):
"""
Finds the genome size of an organsim, based on the peaks file created by kmercountexact.sh
:param peaks_file: Path to peaks file created by kmercountexact.
:param haploid: Set to True if organism of interest is haploid, False if not. Default True.
:retu... | 4dac59dc012e5d101479e3055ae668fe1e4484c5 | 681,024 |
def get_prefix(matchers, other):
""" Get prefix based on matchers for a given object. """
name = None
priority = None
for matcher in matchers:
matcher_prefix = matcher.prefix(other)
matcher_priority = matcher.priority()
if name is None or matcher_priority > priority:
... | 8cd4a9952becb57542f00ecf62d358d0cadde573 | 681,025 |
def append_remote_csv_to_table(tbl, csv, **kwargs):
"""
Load Remote data into existing Hive table
"""
path = csv.path
if path[0] != '/':
path = '/home/%s/%s' % (csv.auth['username'], csv.path)
if tbl.bind.dialect.name == 'hive':
statement =('LOAD DATA LOCAL INPATH "%(path)s" INT... | 91131b5e33d8501dece4bed663bd9f3eaa178543 | 681,026 |
import numpy
import itertools
def shuffle(inputs, outputs, indices=None, strict=False):
"""
shuffle with low memory usage
:param inputs:
:param outputs:
:param indices:
:param strict:
:return:
"""
if isinstance(inputs, (str)):
inputs = [inputs]
if isinstance(output... | 4f634747927183dc5be4fe553a158a60bd3c3ac7 | 681,027 |
import time
def issued_and_expiration_times(seconds_to_expire):
"""
Return the times in unix time that a token is being issued and will be
expired (the issuing time being now, and the expiration being
``seconds_to_expire`` seconds after that). Used for constructing JWTs
Args:
seconds_to_ex... | 0f2fc78f94cf605e784083cc805cf67858ee8b5c | 681,029 |
import pytz
from datetime import datetime
def datetime_from(text):
"""Convert a string representation of a date into a UTC datetime. We
assume the incoming date is in Eastern and represents the last second of
that day. We must account for a misleading timestamp; only the date
provided is relevant"""
... | 74228b12e998575dc607e1d2d7b954dd656e53c4 | 681,030 |
def get_queryarg_data(data, valtype, style='form', explode=False):
"""
Deserialize data based on style in openapi
"""
if style == 'form' and not explode:
if valtype == 'object':
newdata = data.split(',')
values = dict(zip(newdata[::2], newdata[1::2]))
return v... | 916ddf4e375d58088c756751232afacbdca68c69 | 681,031 |
def get_json(request_obj, remove_token=True):
"""
This function is responsible for getting the json data that was sent with
with a request or return an empty dict if no data is sent
Args:
~~~~~
request_obj: request object that data should be attached to
Returns:
~~~~~~~~
di... | e3dc01488df4fbe2b54f2f9a88df1e5beb443992 | 681,032 |
def parse_op_and_node(line):
"""Parse a line containing an op node followed by a node name.
For example, if the line is
" [Variable] hidden/weights",
this function will return ("Variable", "hidden/weights")
Args:
line: The line to be parsed, as a str.
Returns:
Name of the parsed op type.
N... | 3ea15d42192286bd8b81b0f0f5fdf0c2be7f8c93 | 681,033 |
from typing import List
def lines_to_list(lines: str) -> List[str]:
"""Split a string into a list of non-empty lines."""
return [line for line in lines.strip().splitlines() if line] | 970615170ac035f945982f188190f3920550e251 | 681,034 |
def _invert(ax,x,y):
"""
Translate pixel position to data coordinates.
"""
try:
xdata,ydata = ax.transAxes.inverted().transform((x,y))
except:
# Support older matplot
xdata,ydata = ax.transAxes.inverse_xy_tup((x,y))
return xdata,ydata | ee27170a977ab5c3d2798b49a67412e1e8fd21d7 | 681,035 |
def r(line):
"""
Selects rho from a given line.
"""
r, _ = line
return r | 555f4fecc67f895ddf69f568b856ab7a8bdad3dd | 681,037 |
from pathlib import Path
def locate_jar():
"""Locate the scripts jar file relative to this script.
Throws a FileNotFoundError with a message if the jar file couldn't be
identified.
"""
# get the directory name of the currently running script,
# resolving any symlinks
script_dir = Path(__f... | 2c3156c802644dc1dbf61e8a89a0f07f4624f50a | 681,038 |
def get_value_counts_categorical(df, column, alt_filter, ascending=False):
"""
Count the number of rows in `df` where `alt_filter == True` for each unique
value in `df.loc[alt_filter, column]`.
Parameters
----------
df : pandas DataFrame
The dataframe containing the column that we wish ... | 837ac319a4937739f731cb6e4ae7072879a651e0 | 681,039 |
import os
from pathlib import Path
def default_csv_path() -> str:
"""
return the full path to the local csv file included in the package
"""
return str(os.path.join(Path(__file__).parent, "corrections.csv")) | d73ef9fe6679916af1284bf7c4100043a39132d3 | 681,040 |
def textindent(t, indent=0):
"""Indent text."""
return "\n".join(" " * indent + p for p in t.split("\n")) | 08ca6d4e61f8ef0b173bff7814c26bc14fd2c0e9 | 681,041 |
def allocate_function_registers(function):
"""
In the future, use some liveness analysis and add more parameters.
"""
return function.assign_regs() | 5d186ba55b89a43d48c144363ad2030f43a2de37 | 681,042 |
def parse_js_date(date):
"""
Translate the easy-to-use JavaScript format strings to Python's cumbersome
strftime format. Also, this is some ugly code -- and it's completely
order-dependent.
"""
# AM/PM
if 'A' in date:
date = date.replace('A', '%p')
elif 'a' in date:
date ... | 781d247ca56ee46b7c43a29438ea18b987a9a21e | 681,043 |
def iter(object, sentinel=None):
"""Get an iterator from an object. In the first form, the argument must
supply its own iterator, or be a sequence. In the second form, the callable
is called until it returns the sentinel.
:type object: collections.Iterable[T] | (() -> object)
:type sentinel: object... | 8f7def61269fa4a6a926bf4978c3cf9c1b45564b | 681,044 |
def canonicalShape(shape):
"""Calculates a *canonical* shape, how the given ``shape`` should
be presented. The shape is forced to be at least three dimensions,
with any other trailing dimensions of length 1 ignored.
"""
shape = list(shape)
# Squeeze out empty dimensions, as
# 3D image can ... | 0f11a7298253fe9655846a663f5761cd17ae2880 | 681,045 |
def is_aho(n: int) -> bool:
"""3の倍数と3のつく数字はあほになる。"""
return n % 3 == 0 | d6ac77772ab4ef607dc0781bd63facd9586cb02f | 681,046 |
import torch
def pretty2tensor_response(y_pandas, device=None):
"""
maps between the pretty format for the response "y_pandas" and the tensor format used behind the scenes. Accepts
only continuous response variables
if "device"=None, then the device of the current system will be assigned
:param y... | 39b11b5b7f825984327a7b008d6da93c358f05a7 | 681,047 |
def cluster_words(list_words):
"""
cluster similar words based on structure, eg, ['mahathir mohamad', 'mahathir'] = ['mahathir mohamad']
Parameters
----------
list_words : list of str
Returns
-------
string: list of clustered words
"""
if not isinstance(list_words, list):
... | b844b93f5934959abb9a72c8d8dfe0e617e656a6 | 681,048 |
def _to_long_sha_digest(digest, repo):
"""Returns the full 40-char SHA digest of a commit."""
return repo.git.rev_parse(digest) if len(digest) < 40 else digest | d1a7bc87e32917b2ef24db8b201e7f2509d705a8 | 681,049 |
def backtrack(c, x, y, i, j):
"""Backtrack the LCS length matrix to get the actual LCS"""
if i == -1 or j == -1:
return ""
elif x[i] == y[j]:
return backtrack(c, x, y, i-1, j-1) + x[i]
elif c[i][j-1] >= c[i-1][j]:
return backtrack(c, x, y, i, j-1)
elif c[i][j-1] < c[i-1][j]:
... | d3b060cd22db0983551f4100e4764c50f7777508 | 681,050 |
import torch
def tversky_index(yhat, ytrue, alpha=0.3, beta=0.7, epsilon=1e-6):
"""
Computes Tversky index
Args:
yhat (Tensor): predicted masks
ytrue (Tensor): targets masks
alpha (Float): weight for False positive
beta (Float): weight for False negative
... | c6c13e26555467469829ee2f9b4096ff0705ee99 | 681,052 |
def _is_plugable_7port_hub(node):
"""Check if a node is a Plugable 7-Port Hub
(Model USB2-HUB7BC)
The topology of this device is a 4-port hub,
with another 4-port hub connected on port 4.
"""
if '1a40:0101' not in node.desc:
return False
if not node.HasPort(4):
return False
return '1a40:0101' in... | a2725a708fb9bc6d7611d0b278545c503152d7e2 | 681,053 |
from typing import Dict
from typing import Any
def decision_list_best_params_surroundings(best_params: Dict[str, Any]) -> Dict[str, Any]:
"""Get best parameters surroundings for random forest."""
min_samples_split = best_params["min_samples_split"]
max_depth = best_params["max_depth"]
n_estimator... | da075d719dda78baab89ab2798820abb84c0ea70 | 681,055 |
def load_file(filename):
"""
Loads and returns the contents of filename.
:param filename: A string containing the filepath of the file to be loaded/
:type filename: str
:return: Contents of the loaded file.
:rtype: str
"""
with open(filename, "r") as fh:
return fh.read() | 3685ffa5faa775805ff5d4fa13750b9874cef752 | 681,057 |
def morphology_used_in_fitting(optimized_params_dict, emodel):
"""Returns the morphology name from finals.json used in model fitting.
Args:
optimized_params_dict (dict): contains the optimized parameters,
as well as the original morphology path
emodel (str): name of the emodel
... | 1f935675543a178d65021cfad8f5b4aa5b0d9951 | 681,058 |
import click
import sys
def parse_arn_from_input_profile(account_roles, profile):
"""Given a list of account/role details, return the ARNs for the given profile
Args:
account_roles: List of dictionaries containing account/role details
profile: A user-provided profile to retreive the ARN from ... | b634a4879f1f2fbbc59c9f46bfd7894834ad12f7 | 681,061 |
def ifnone(value, ifnone='~'):
""" Pass a string other than "None" back if the value is None.
Used in datestamp handling.
"""
if value is None:
return ifnone
return value | 5d8814123cbb37860ca5554f1a1d726c930b78ae | 681,062 |
def rivers_with_station(stations):
"""
Args:
stations: list of MonitoringStation objects
Returns:
A set of names (string) of rivers that have an associated monitoring station.
"""
rivers = set()
for s in stations:
rivers.add(s.river)
return rivers | e866eedcffb25cff8a6a682401db1484f1009d7c | 681,064 |
import torch
def genLinearModule(D_in, out=1):
"""Two separate linear functions of the input covariates."""
model = torch.nn.Sequential(torch.nn.Linear(D_in, out),)
return model.double() | 9ce2d4a8ee382867a46a391927cba2f8cb5b893d | 681,065 |
def f16(value):
""" Multiply with maximum value of a number 16bit (0xFFFF)
:param value: Input value
:return: value * 0xFFFF
"""
return int(round(65536 * value)) | 0556c481163c7e676b0160765ad0a7a0ca1306f2 | 681,066 |
def sval(val):
"""
Returns a string value for the given object. When the object is an instanceof bytes,
utf-8 decoding is used.
Parameters
----------
val : object
The object to convert
Returns
-------
string
The input value converted (if needed) to a string
"""... | 423c4934edde09939d83f988dcedb6d19146fb8d | 681,067 |
def send_all(sock, data):
"""
发送数据
:param sock: 发送数据的目标地址连接对象
:param data: 发送的数据
"""
bytes_sent = 0
while True:
r = sock.send(data[bytes_sent:])
if r < 0:
return r
bytes_sent += r
if bytes_sent == len(data):
return bytes_sent | 60bd4b04b13b79c55545f5fe58d3a1e47525922d | 681,068 |
def read_rules(file_location):
"""Read file with lugages rules
"""
return open(file_location, 'r').read().split('\n') | 5c6b01d273158621d0c7c9b190722195e6b0028f | 681,069 |
def _superclasses(obj, cls):
"""return remaining classes in object's MRO after cls"""
mro = type(obj).__mro__
return mro[mro.index(cls)+1:] | afa47a46fff3d7b525988baae57579e240a40c06 | 681,071 |
def _align_sentence_spans_for_long_sentences(original_sentence_spans, trimmed_sentence_spans):
"""Align new token spans after enforcing limits to the original locations in raw text.
This is needed to keep track of each token's location in original document. After enforcing
sentence limits, some sentences g... | 144b71600846aee5293bc1ce10837fbe35d79c7a | 681,072 |
def _strip_mongodb_id(x):
"""
Rename the ``_id`` key from a dict as ``id``, if the latter doesn't already
exist. If that's the case, remove the key.
Update the object in-place.
"""
if "_id" in x:
if "id" not in x:
x["id"] = x.pop("_id")
else:
del x["_id"]
... | c2f9824b55234c638ce3b88fcef01c1a26937e9f | 681,073 |
def phony(params: dict) -> str:
"""
Build phony rules according to 42 rules
"""
phony = "all re clean fclean norm bonus"
if params["library_libft"]:
phony += " libft"
if params["library_mlx"] and params["compile_mlx"]:
phony += " minilibx"
return phony | 0db9f695caa3801467f7d6d3efecc070e0bda6ec | 681,074 |
def get_eec(self):
"""Get the Electrical Equivalent Circuit
Parameters
----------
self : LUT
a LUT object
Returns
----------
eec : EEC
Electrical Equivalent Circuit
"""
if self.simu is None:
return None
if self.simu.elec is None:
return None
... | 7939b0613342ff3d701e072ca2f0bc5fd58eb931 | 681,075 |
def next_power_of_2(v):
"""
Returns the next power of 2, or the argument if it's already a power of 2.
"""
v -= 1
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
return v + 1 | 231925c06c493f1113616fea4cb6c0269c2f7f01 | 681,076 |
def init_parser(parser):
"""Initialize parser arguments."""
parser.add_argument(
'bulk_data_path', type=str,
help=("""Path to mixture data file; .csv, .txt, .xlsx or .xls format
with sample names as columns and genes as rows.""")
)
parser.add_argument(
'celltype_data_pat... | 0fb86fef4bdcb6cf6001f74855107e8f3713837d | 681,077 |
def voter_sms_phone_number_save_doc_template_values(url_root):
"""
Show documentation about voterSMSPhoneNumberSave
"""
required_query_parameter_list = [
{
'name': 'api_key',
'value': 'string (from post, cookie, or get (in that order))', # boolean, integer... | c5717bee9cf3eea97284a3686ab9dfa7444236ca | 681,078 |
import numpy
def _validate_adj_param(value, name):
"""
Validate the aperture adjustment vector parameters.
Parameters
----------
value : None|numpy.ndarray|list|tuple
name : str
Returns
-------
numpy.ndarray
"""
if value is None:
value = numpy.array([0, 0, 0], dt... | 164f1752226c74e7fdb558c13599482aeaa6d0a5 | 681,079 |
def find_index_in_intent_list(intents,contexts):
"""
"""
possible_indexes = set()
for index,intent in enumerate(intents):
for context in contexts:
if set(intent)==set(context):
possible_indexes.add(index)
return list(possible_indexes) | e8982c80d7526ab2cdb109b97e46d909e3c056ba | 681,080 |
def redirect_with_trailing_slash(environ, start_response):
"""Response if the trilling slash is missing
after the cgi script file name.
"""
status = "301 Moved Permanently"
url = "".join([
environ["wsgi.url_scheme"],
"://",
environ["SERVER_NAME"],
("SERVER_PORT" in ... | fc6b3cee7a670f3e208cff1f2c05840691db152a | 681,081 |
def badinstrmapper(bad):
"""
Get routine to delete bad instructions
:param bad: bad instruction string
"""
def mapper(line):
return line.replace(bad, '')
return mapper | 574ba1b69672dc892056b35ff5f7c8ea5c4632c5 | 681,082 |
import requests
import json
def edit_link(token, link, title):
"""
Edits an already existing Bitly links title.
Args:
token (str): Bitly access token.
link (str): Shortened URL to be edited by Bitly.
title (str): Updated Bitly link title.
Returns:
Bitly status informa... | 3fbdc07f0e2d7b54787295250654ffffbf97054b | 681,083 |
def check_lat(lat):
"""
Checks whether the input latitude is within range and correct type
Parameters
----------
lat : float or int
latitude (-90 to 90) in degrees
Returns
-------
None. Raises an exception in case
"""
if isinstance(lat, (int, float)):
if abs(lat... | a4b87645b0f1a19c79da387352b49ba12277a39d | 681,084 |
def merge_p(bi,p,bigrams):
"""
Calculates the merge probability by combining the probs of the bigram of words and the prob of merge.
Arguments
bi : bigram
p : p(MG->mg) from grammar (should be 1)
Returns
combined probability of merge op and bigram
"""
(w1,w2)=bi
return bi... | 58831a487e0bb441fa3f19e0deead0a1f7632df8 | 681,085 |
def combine(a, b):
""" sandwiches b in two copies of a and wrap by double quotes"""
c = '"' + a + b + a + '"'
return c | 984361527233b31799516a5a696f630aa88a1daf | 681,086 |
import os
def splitpath(path):
"""Like os.path.split, only does all the splits at once."""
l=[]
while path:
head,tail=os.path.split(path)
l.insert(0, tail)
path=head
return l | 307b15b218e05f31b5e01771c5742003563d9669 | 681,087 |
def _find_get(root, path, value, defa=False):
"""
Error catching of things required to be set in xml. Gives useful
errormessage instead of stuff like "AttributeError: 'NoneType' object
has no attribute 'get'"
Parameters
----------
root : Element
Element in xml-tree to find parameter... | c51e4d99ba536d6100e21acf99e008d4da102574 | 681,088 |
import os
import logging
def activate_pre_commit() -> bool:
"""
Activate Pre Commit
Parameter
Return
Example
>>> activate_pre_commit()
True
"""
try:
os.system('. .venv/bin/activate && pre-commit install')
logging.info(f'Pre Commit: start successfully')
... | 09b1df512acc7d313bd3982a7a1020fd85dccc46 | 681,089 |
from typing import List
def find_string_anagrams(str1: str, pattern: str) -> List[int]:
"""
This problem follows the Sliding Window pattern and is very similar to Permutation in a String. In this problem, we
need to find every occurrence of any permutation of the pattern in the string. We will use a list ... | 281dba1d21d779ab4060a8889ffb0ab81f061d30 | 681,090 |
def create_suffix(suffix, index):
"""Create suffix using an index
Args:
suffix (string): Base suffix
index (int/string): Index
Returns:
string: Suffic
"""
i = "%02d" % (int(index) + 1,)
return suffix + "-" + i | bfb133372a7797fc7dfd011ce26dbdd0956d996d | 681,091 |
def is_substring(text: str, elements: set) -> bool:
"""
Check if a string is a substring of any string in a set
Args:
text (str): text to be tested
elements (set(str)): set of string to be tested against for substring condition
Return:
(bool): whether or not if text is a substr... | de576a5ef9cdfed82233f071520bc6e3c76674fb | 681,092 |
import copy
def find_transitions(letters, pathways, counts, proportion):
"""Produce transition matrix between activities.
Including activity to exit in final column.
"""
pathways = copy.deepcopy(pathways).dropna()
TM = [[0 for i in range(len(letters)+1)] for j in range(len(letters))]
for ... | a50e8f91ad6a8613187829f3819e2b3cc0d90c43 | 681,093 |
def find_subsequence(subseq, seq):
"""If subsequence exists in sequence, return True. otherwise return False.
can be modified to return the appropriate index (useful to test WHERE a
chain is converged)
"""
i, n, m = -1, len(seq), len(subseq)
try:
while True:
i = seq.index(sub... | 69fb5f47f5dec64b1b641d66cd11b2a4e330c77d | 681,094 |
def _format_error(error: list) -> dict:
"""
Convert the error type list to a dict.
Args:
error (list): a two element list with the error type and description
Returns:
dict: explicit names for the list elements
"""
return {'error_type': error[0], 'description': error[1]} | 842dd6b456ac25e90c79f720ea59794188001234 | 681,095 |
def token_identity(it, token_payload=None):
""" Echo back what it gets. """
return (it, token_payload) | 6fe367d1e908a8812c8372e5909b54c8bb7b17f5 | 681,096 |
def print_statement(statement):
"""
Takes the statement and writes it to file
returns the file name that it wrote to
"""
seq = statement.split("\n")
# file name is the second in the sequence
file_name = f"FOLDER {seq[1].replace('READER_FOLDER_LABEL_', '')}".translate(str.maketrans(' ', '_')... | ecc20b62990ee301713567ff923215941e93100a | 681,097 |
def zonekey(zoneDev):
""" Return internal key for supplied Indigo zone device. """
#assert zoneDev.deviceTypeId == 'zone'
return (int(zoneDev.pluginProps['partitionNumber']),
int(zoneDev.pluginProps['zoneNumber'])) | 9e601d9819226b78f02a18e7f19a1d7238918144 | 681,098 |
def form_columns(board: list) -> list:
"""
Returns columns of the board.
>>> form_columns([])
['', '', '', '', '', '', '', '', '']
"""
lst = []
general = []
for i in range(9):
for line in board:
lst.append(line[i])
general.append("".join(lst))
lst.clea... | 2752962bc27dbdb53b250fa7c3be3823d57f9e17 | 681,099 |
from pathlib import Path
import os
def fullpath(path):
""" Expand '~' and resolve the given path. Path can be a string or a Path obj. """
return Path(os.path.expandvars(str(path))).expanduser().resolve(strict=False) | e05e99cfa3e31458651dc09e1afd2a6358ace824 | 681,101 |
def dp_dt(en_grad):
"""
Args:
f (torch.Tensor): an energy gradient tensor of dimension N_J x N_at x 3.
It is evaluated at the center positions of each of the
N_j basis vectors.
"""
f = -en_grad
return f | 810c1dd272edc9fac5838ab1fa84c470fe0c784b | 681,102 |
def ler():
"""
-> Fazer leitura de qualquer valor
return: l
"""
l = input("\033[0;32mDigite Aqui: \033[m")
return l | 8ba4ca3e6ac886f3c6b68a3c0e8798d4a6b27c01 | 681,103 |
def first(s):
"""Return the first element from an ordered collection
or an arbitrary element from an unordered collection.
Raise StopIteration if the collection is empty.
"""
return next(iter(s)) | 85535e7ccd25812154190c2bfb9dcfd7c48cfeff | 681,104 |
def auth_headers(token):
"""Return a list of Authorization headers corresponding to token."""
return [('Authorization', 'Bearer %s' % token)] | b42cc008ba2aa13d722214beef074f02a537c045 | 681,105 |
def check_class_dict(param_type):
"""Check the class dict"""
dict_type = str(param_type).replace("<", "")
dict_type = dict_type.replace(">", "")
dict_type = dict_type.split(" ")[-1]
check_dect = dict_type != "dict" and not isinstance(param_type, dict)
if not hasattr(param_type, '__annotations__'... | d113f31cf9f45e1b91e923774c7e3b3dd1042393 | 681,106 |
def is_relevant_syst_for_shape_corr(flavor_btv, syst):
"""Returns true if a flavor/syst combination is relevant"""
if flavor_btv == 0:
return syst in [ "central",
"up_jes", "down_jes",
"up_lf", "down_lf",
"up_hfstats1", "down_hfs... | 3b7740f4385fa1e25035dd9fba2c87581bc7dcc0 | 681,107 |
import json
def burn_in_info(skeleton, info):
"""Burn model info into the HTML skeleton.
The result will render the hard-coded model info and
have no external network dependencies for code or data.
"""
# Note that Python's json serializer does not escape slashes in strings.
# Since we're inl... | 86cc51a18601ce9b0656e915c6b10d07bc1fead2 | 681,108 |
import requests
def make_request(url):
"""
Make request to an URL
:param url: any url
:return: success and response if successful, otherwise error
"""
try:
return 'success', requests.get(url)
except requests.exceptions.ConnectionError:
return 'connection error', None | 5612c3728519fa732937d3863a643e1d68eb1e4d | 681,109 |
def parse_generic_header(filename):
"""
Given a binary file with phrases and line breaks, enters the
first word of a phrase as dictionary key and the following
string (without linebreaks) as value. Returns the dictionary.
Parameters
----------
filename : str or Path
Full filename.
... | 12dcfaa6382d46448c42d0a6425bbd2f4f377afc | 681,110 |
import pickle
def load_model(path):
"""Funcao que carrega o modelo
Args:
path (string): endereço para o modelo
Returns:
model: model instance
"""
with open(path, "rb") as f:
model = pickle.load(f)
return model | 2ec9f806bc803471bf7407ff0cdc3d9e38e86918 | 681,111 |
def empty_on_text_factory():
"""
Function used to un-register on_text method of window property of MenuWindow object.
:return: functor with empty on_text method
"""
def functor(_text):
pass
return functor | 09ba5696a8e0dde6dd1a25e58a034d539ba5b96e | 681,112 |
def insert_ascii(reaction_id):
"""
Replace normal signs with the ascii number to match ids with the spreadsheet
"""
return reaction_id.replace("-","__45__").replace("(","__40__").replace(")","__41__").replace(".", "__46__").replace("+", "__43__") | 393bd0f93ecaf020c56f4d3394c8d9bfd9e5d848 | 681,113 |
def quotes_inner(quoted: str) -> str:
"""
For a string containing a quoted part returns the inner part
"""
left_quote = quoted.find('"')
right_quote = quoted.rfind('"')
if right_quote < 0:
right_quote = len(quoted)
return quoted[left_quote + 1:right_quote] | 737718431d353e3ac9bd21fd625a61557b423d68 | 681,114 |
def getAvailableBands():
"""give the bands composition for each name.
0 being the landsat 7,
1 landsat 5,
2, landsat 8
3: sentinel 2"""
bands = {
"Red, Green, Blue": {
"landsat_7": ["B3", "B2", "B1"],
"landsat_5": ["B3", "B2", "B1"],
"landsat_8": ["B4... | b2fb8a2a068a18fb4687d8e2c57f3ee6c12b2df0 | 681,116 |
import glob
import os
import fnmatch
import logging
def GetNetworkInterfaceByPath(interface_path, allow_multiple=False):
"""Gets the name of the network interface.
The name of network interface created by USB dongle is unstable. This function
gets the current interface name of a certain USB port.
For exampl... | caf229d79952a627606e9eda101a022fd92079b5 | 681,117 |
def guess_lon_lat_columns(colnames):
"""
Given column names in a table, return the columns to use for lon/lat, or
None/None if no high confidence possibilities.
"""
# Do all the checks in lowercase
colnames_lower = [colname.lower() for colname in colnames]
for lon, lat in [('ra', 'dec'), (... | f8f1385bc1a694241d98077c8ad499015e36021b | 681,118 |
def _fipsFunction(func, *args, **kwargs):
"""Make hash function support FIPS mode."""
try:
return func(*args, **kwargs)
except ValueError:
return func(*args, usedforsecurity=False, **kwargs) | 2dfb942611b64bf543e75708029455124b7ef261 | 681,119 |
from typing import OrderedDict
def get_sector_subsector(x,column_pairs):
"""This function filters out the most likely sector and subsector codes assigned to a building
In an OSM dataset, based on a mapping of building attributes to macroeconomic sectors
Based on our mapping a building might be e... | 3b87a965e6bd94cd0d4b4206b65fbb5a283b8e3e | 681,120 |
def get_pkt_data(il, offset, use_index=False, size=4):
"""
Returns llil expression to get data from packet at offset
:param il: llil function to generate expression with
:param offset: packet offset to retrieve
:param use_index: add the index register to offset if true
:param size: number of byt... | a7f466cb0666ee6d02368bae9f55c335d47f9100 | 681,122 |
def copy_to_len_sliced(s, l):
"""Returns the maximim length string made of copies of `s` with the length
exactly `l`; if the length of `s` doesn't match, it ends with the beginning
slice of `s`.
Parameters
----------
s : string
String to be copied and sliced.
l : int
Th... | 165b2ab2358f5742139f947e3f370637c8a9ffe4 | 681,123 |
import sys
def _version_check_pkg_resources(pkg_resources):
"""Check that pkg_resources supports the APIs we need."""
# Check that pkg_resources is new enough.
#
# Determining the version of an arbitrarily old version of
# pkg_resources is tough, since it doesn't have a version literal,
# and ... | e88f1256109a90f05c093e96b589699fcb632793 | 681,124 |
import math
def t_test(image1, image2):
"""Performs a Student's t-test for the provided images."""
num = image1.rms[0] - image2.rms[0]
denom = math.sqrt(((image1.stddev[0]**2)/image1.count[0]) + ((image2.stddev[0]**2)/image2.count[0]))
if denom == 0:
return 0
t = num / denom
if t < 0:
... | 6b276fd0fd45e5a263e326e94fde850ca6e441a8 | 681,125 |
def user_help():
"""
Returns HELP TEXT RESPONSE
"""
get_help = """*Welcome to Geeksters.*\n\nThese are the conversations which can be used to talk to the chatbot. It tries to generate Human-alike responses and makes the bot more fun and engaging.
Manage and complete your tasks on time by typing so... | 2adfb1e1fc151f7634f16da15c607355f533bbca | 681,126 |
def normalize(grid):
""" normalize grid to (0,1) """
field = grid.T.values
min_h, max_h = field.min(), field.max()
return (field - min_h) / (max_h - min_h) | 0bd5bb6cac14a283aaa8ca6dabc914b920fcfa3a | 681,127 |
import json
import requests
def post(header, address, request_parameter_type, data,cookies):
"""
post 请求
:param header: 请求头
:param address: host地址
:param request_parameter_type: 接口请求参数格式 (form-data, raw, Restful)
:param data: 请求参数
:return:
"""
try:
if request_parameter_ty... | 9214157d673ae4ece974e8deb90ecb64d39c51ea | 681,128 |
from typing import Callable
def _func_to_funcname(func: Callable) -> str:
"""Returns module.function or module.class.function"""
if not callable(func):
raise TypeError
# noinspection PyUnresolvedReferences
return f'{func.__module__}.{func.__name__}' | bd2d9ea661398c8f1e117772bba234d6c45d8995 | 681,129 |
def fastaParserSpectraClusterPy(header):
"""Custom parser for fasta headers adapted from
https://github.com/spectra-cluster/spectra-cluster-py
:param header: str, protein entry header from a fasta file
:returns: dict, parsed header
"""
isUniprot = lambda h: h[0:3] in ['sp|', 'tr|', 'up|']
... | b5695bc412523a586f77c15587916d4b885ef5ef | 681,130 |
def column_check(df, column):
"""Check if `column` is in `df`."""
return column in df.columns | b584753a3b3789e90436bcc368af21f99a8a7348 | 681,131 |
def repr_listed_values(values):
"""
Represent values for messages.
Examples
--------
>>> repr_listed_values(['green', 'blue', 'yellow'])
'green, blue and yellow'
"""
*values, last = values
if values:
return ", ".join(values) + ' and ' + last
else:
retur... | 15bbadebfdde620b68f8cb9e32806ee5bdab37b6 | 681,133 |
def intersect_datasets(dataset1, dataset2, intersect_on='exam_codes'):
"""Returns the intersection of two dataset Bunches.
The output is a dataset (Bunch).
The intersection is on patient id and visit code or date
"""
if intersect_on not in ['exam_codes', 'exam_dates']:
raise ValueErr... | 32a9dc781420c69bb9a0ed42b00f9b2e24878e36 | 681,134 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.