content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
from bs4 import BeautifulSoup
def get_document(url, payload):
"""
Load content from url and return a query enabled document. A dictionary
of get parameters can be set in payload.
"""
request = requests.get(url, params=payload)
return BeautifulSoup(request.text, 'xml') | 7029b3d3bc83749addf616098dc92dd05d82fa92 | 605,919 |
def file_len(filename):
"""
Returns the equivalent of wc - l
:param filename: file name
:return: number of lines in the file
"""
with open(filename) as f:
i = 0
for i, l in enumerate(f):
pass
return i + 1 | 3ccd5db150e3803a79cfc91bd5d285b26e5c50d1 | 605,927 |
def replace(orig, position, char):
"""
Replace a character in string by position
:param orig: origin string
:param position: position to be replaced
:param char: character to replace
:return:
"""
str_len = len(orig)
if position < 0 or position > str_len - 1:
return orig
... | 07cca07ed904d34cab1845b7636912c7be0fa2a1 | 605,928 |
def remove_duplicates(from_list):
"""
The function list() will convert an item to a list.
The function set() will convert an item to a set.
A set is similar to a list, but all values must be unique.
Converting a list to a set removes all duplicate values.
We then convert i... | 4248f61e170f3887d3df8d4243dc59d99b1b0bd6 | 605,931 |
def percent_used(used, total, decimal=2):
"""
Return percent used by giving total and used value.
:param used: Used value.
:type used: Integer
:param total: Total value.
:type total: Integer
:return: Float for percent used.
:rtype: Float
"""
pused = round((100. / total) * used, ... | 0c8b694d36af2dcaf903b307c34beb794bc391ff | 605,932 |
def entity_list(raw_entities_dict):
"""
Returns a list of tuples that preserves the qbbo_types and Id keys.
(The input is what you get when you run quickbooks.transactions()
or quickbooks.names())
Each item in list is a three-item tuple:
(qbbo_type,Id,raw_entity_dict)
"""
e_list =... | cc0fc4dd1e6f6bf7b426728c10cd5c2357bc2ef3 | 605,933 |
def molecular_weight_error(calculated: float, expected: float):
"""
Calculate the error between a calculated and expected molecular weight. This method may be used as a validation
tool for calculated isotope patterns.
:param calculated: calculated molecular weight (derived from an isotope pattern)
... | 39c01f3b013df72078797a81d13b7819f5ae515a | 605,934 |
import math
def dd2meters(inPt,scale=0.1):
"""Function to convert decimal degrees to meters based on the approximation
given by: https://en.wikipedia.org/wiki/Geographic_coordinate_system
Args:
inPt (list or array): A Y,X point provided in geographic coordinates
in that order.
... | 4d9fa7990fb445781afc507b03254224085d669c | 605,935 |
def dict2matrix(wDict,std=0,diag=0):
"""Transform the contiguity dictionary to a matrix
:param wDict: Contiguity dictionary
:type wDict: dictionary
:param std: 1 to get the standarized matrix
:type std: dictionary
**Example 1** ::
>>> import clusterpy
>>> lay = clusterpy.imp... | d6c2d334fba8c2dd503100916f2614ca14290f2f | 605,936 |
def degre(G, val):
"""Renvoie le degré d'un sommet, autrement dit son nombre de voisins"""
voisins = 0
for i in G[val]:
if i != val:
voisins += 1
return voisins | f58d11709eb7b464c42afa820a9276915bf3311e | 605,937 |
def strip_whitespace(string: str) -> str:
""" Strip leading and trailing whitespace from a string """
if string[-1] == " ":
string = "".join(string.rstrip())
if string[0] == " ":
string = "".join(string.lstrip())
return string | 9de016e162b45e3b444610008eab996cfdcfb198 | 605,938 |
from pathlib import Path
def _is_file_name_available(
path: str,
file_name: str,
file_extension: str):
"""
- Returns True if there is no file with the specified details, False
otherwise.
"""
path_str = path + '/' + file_name + file_extension
my_file = Path(path_str)
... | 91f7e1e5a8e812e082def4922e5f980e7369719d | 605,939 |
def _split_tensor_name(name):
"""Return tuple (op, port) with the op and int port for the tensor name."""
op_port = name.split(":", 2)
if len(op_port) == 1:
return op_port, 0
else:
return op_port[0], int(op_port[1]) | efe39f97abda4fbc801913d63fc8c9dd797ff90f | 605,940 |
from typing import List
from typing import Tuple
import json
def validate(result_range: List[Tuple[str, int]]) -> List[Tuple[int, int]]:
"""
Given a directory containing only JSON files produced by an allrepos crawl, this function
validates that there are no holes in the crawled data
Args:
result... | 1fefe485feed11bf4fb53bc75934e4145db80be6 | 605,941 |
def add_access_control_headers(response):
"""Adds the required access control headers"""
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Set-Cookie'
response.headers['Access-Control-Allow-Methods'] = 'POST,GET,PUT,DELETE'
respo... | c4108e3e34b349e9211b946e3501a5c5f9a4c79e | 605,946 |
import time
def format_time(to_format):
"""
Takes a string in the format 2200 and returns a string in the format
11:00 PM
"""
in_time = time.strptime(str(to_format), '%H%M')
return time.strftime('%I:%M %p', in_time) | acbd6031b88ef94728a0d50f59c3cc56348674ef | 605,949 |
from typing import OrderedDict
def get_mpl_markerstyles(inverse=None, include_none=True):
""" Obtain MPL's marker styles.
Parameters
----------
inverse : str, unicode or None, optional
If given, searches for an MPL marker style based on its description. A string containing
the found M... | 57ae763e42887b6e0af1e0640a41e0a3b3dce352 | 605,950 |
import json
def load_json(file_path):
"""
Load data from json file.
>>> result = load_json("./JsonAccessorDoctest.json")
>>> result
{'Fuji': {'Id': 30, 'server': ['JP', 'CN']}}
>>> len(result['Fuji']['server'])
2
"""
with open(file_path, 'r', encoding='utf8') as json_data:
... | fdb28da3129fbdf8c171ddd035483177fd176a6a | 605,952 |
from typing import Sequence
def map_on_tensor(fn, val):
"""Map a function on a Tensor or a list of Tensors"""
if isinstance(val, Sequence):
return [fn(v) for v in val]
return fn(val) | 0ad7ca2a52d5e33b71021b11d5151ffe424bc6c6 | 605,956 |
import re
def make_event_tags_re(tags):
"""Makes a regular expression object that matches event logs of |tags|."""
return re.compile(r'(?P<pid>[0-9]+) +[0-9]+ I (?P<tag>%s): (?P<time>\d+)' %
'|'.join(tags)) | 1c7cad2f456ea51bd63dc25f144d4fe24b444727 | 605,958 |
def _get_available_memory(mem_feat, constraints=None):
"""Get available memory
If constraints are given, parse constraint string into array of
constraints and compare them to active features. Currently only
handles comma-separated strings and not the more advanced
constructs described in the slurm ... | 9783084657979b46bd5a2a1c81abed09f5969fcd | 605,963 |
def k_day_percent_change(k, df):
"""
Computes the k-day adjusted close percent change.
Example: k=2, is the daily percent change
Arguments:
k -- number of days into past to use , k>1
df -- yahoo finance dataframe. Must be indexed by data, and have columne adj_close
"""
return (df.open ... | 0c7df27aa15948f8c7fb8cb2e5aef881dc1e4c86 | 605,965 |
def walkPath(nodes, path):
"""
This function can be used to walk a tree in the form returned by the
buildTreeUpDown function from the ndoes module, i.e. in dictionary form.
The path must be in the form of 'LRRL', where each letter indicates which
child-node is next (L: left, R: right). The function ... | 7e756b805a075795e98f45dda63299360d69f184 | 605,966 |
from typing import Callable
from typing import Any
import io
import base64
import zlib
def _decode_and_deserialize(
data: str, deserializer: Callable, decompress: bool = True
) -> Any:
"""Decode and deserialize input data.
Args:
data: Data to be deserialized.
deserializer: Function used t... | 6798eb49b312a216a667cc05dac940b376b32353 | 605,968 |
def __get_skip_select_quit(prompt):
"""Repeatedly prompts the user until they return a valid selection from skip/select/quit."""
while True:
response = input(prompt + " [enter to skip, 's' to select, 'q' to quit]")
if response == "":
return "skip"
if response == "s":
... | d88ce8e88d17aa1d531f5b850798137037c7fac6 | 605,969 |
def isPal(word):
"""
Test if a word or phrase is a palindrome (same backward or forward).
Assume it must have more than 2 letters, and that only letters and digits count.
"""
### keep only letters or numbers
w = ''.join([l for l in word.lower() if l.isalnum()])
### check if it is the same a... | 6f6a39aea1e972e2f1655556a5705ffc3768eac5 | 605,974 |
from typing import List
import warnings
def pascal_case_split(pascal_str: str) -> List[str]:
"""Parse a pascal case string (e.g. a ClassName) and return a list of strings."""
warnings.warn('trestle.utils.pascal_case_split function is deprecated', DeprecationWarning)
start_idx = [i for i, e in enumerate(pa... | b048fafdafb316494532979901747ef284639d60 | 605,983 |
def ExtractOperations(toolF):
""" Extract the operations from the function array of a bio.tools dictionary
"""
return [o["uri"] for o in toolF["operation"]] | b79614eb6b9b133f701cbe639f2bab5a3e137755 | 605,985 |
def terms_url() -> str:
"""Path to terms."""
return '/terms' | 9f216e43570b7877e2fd58aaa87acdd0998ceb0c | 605,987 |
def measure_scaler(measure, dom_start, dom_target):
""" Scales the measure value in the start domain [Type, min, max], in the target domain. """
return (measure - dom_start[1]) / (dom_start[2] - dom_start[1]) * (dom_target[2] - dom_target[1]) + dom_target[1] | 24b00ee2a35f7b4e7a5bb376873c5b58df135f2c | 605,988 |
import csv
def csv_to_list(csv_file, delimiter=','):
"""
Reads in a CSV file and returns the contents as list,
where every row is stored as a sublist, and each element
in the sublist represents 1 cell in the table.
"""
with open(csv_file, 'r') as csv_con:
reader = csv.reader(csv_... | 41d39241813e9cec6c9344c7f802efeea4cbdc7f | 605,990 |
def links(dataset_id):
"""Endpoints related to a dataset id"""
return {
"data_vars": f"/datasets/{dataset_id}",
"palette": f"/datasets/{dataset_id}/palette"
} | e012deb0fbe35447042fdf531cdb175ef7851229 | 605,992 |
from typing import Iterable
from typing import Any
from typing import List
def flatten(l: Iterable[Iterable[Any]]) -> List[Any]:
"""Flatten an N dimensional iterable object to a N-1 dimensional list by removing the outer iterable."""
return [item for sublist in l for item in sublist] | e41e07061e250aa70bba3d4ea3ae62abfb98c65b | 605,993 |
import re
def replace_all(str: str, substitutions: dict):
"""Replaces multiple substrings in a string.
Keyword arguments:
str -- the string to search and replace in
substitutions -- a dictionary that contains mappings of the original
substring to the replacement substring
"""
if not s... | 5d829e9d4bf23ae94c30c84f4747dd5974c74d70 | 605,997 |
def get_word_context(node, tree):
"""Return a list of word tokens within a node's neighborhood."""
context_bag = [node.token]
context_bag += [tree[idx].token for idx in node.dependent_indexes]
if node.head_idx is not None:
context_bag.append(tree[node.head_idx].token)
return context_bag | 962c7c7e7cdd30fffb8fbe43f9c8a5b695b804c7 | 605,998 |
def two_sum(arr, k):
"""
Return whether or two elements in an array sum to k
"""
seen = set()
for elt in arr:
if elt in seen:
return True
seen.add(k - elt)
return False | 74b64f24e6895b4f5cda05dbd5be89bf621b07fb | 605,999 |
def df_order_columns(df, columns_ordered=[]):
"""
Order some columns, and remain other as was
"""
columns = []
for c in columns_ordered:
if c in df.columns:
columns.append(c)
remains = [c for c in df.columns if c not in columns]
columns = columns + remains
assert len... | 3243ea3e3e679fd0dd23369853d846d397654391 | 606,000 |
def copy_series_from_dataframe(input_df, index_name, column_name):
"""
Take a multi-index DataFrame, and make a copy of the data
corresponding to a given index and column.
Parameters
----------
input_df : pandas.DataFrame
The DataFrame to extract the data from.
index_name : str
... | a591216258317dc134c0d270e33a7030819482c1 | 606,001 |
import re
def chinese_word_only(s: str):
"""
将字符串处理为仅保留中文字符
:param s:目标字符串
:return:一个2个元素的列表,第一个元素是仅中文字符串,第二个元素是其长度
"""
pattern = re.compile(r'[^\u4e00-\u9fa5]')
res = re.sub(pattern, '', s)
return [res, len(res)] | d84339712d62cf1668a3f196f81d3d03457d00c3 | 606,002 |
def convert_readable(size_to_convert):
"""
This function will convert size to human readable string
:param size_to_convert: size in bytes
:return: human-readable string with size
"""
i = 0
size_to_convert = int(size_to_convert)
units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB']
for i in ran... | c2717d9115e53433cdf3c6e278807a467232b686 | 606,005 |
import struct
def get_slicer_info(mod_file):
"""
Open an IMOD .mod file and retrieve the Slicer information
Args:
mod_file: The .mod file path
Returns: A list of Slicer point objects with keys {"angles", "coords"}
"""
results = []
with open(mod_file, "rb") as file:
token... | 522278eceab40d7741b22de63d01022266eaeeb4 | 606,006 |
def extractTextWithSimpleLayout(analyzed_data):
"""
Simple extraction of text from each page with basic layout support (1 group of text per page).
Sample output object:
[
[ # New Page
{ # New Text Group
"text": ["Extracted Text Line 1", "2nd line here"],
... | e9db12b47c20e92939c6c61716b11a779c9d2cc7 | 606,007 |
def compute_DC(net_dict, w_ext):
""" Computes DC input if no Poisson input is provided to the microcircuit.
Parameters
----------
net_dict
Parameters of the microcircuit.
w_ext
Weight of external connections.
Returns
-------
DC
DC input, which compensates lackin... | df9e577477440af5929bdf07b3da637915c0ee9c | 606,010 |
def getVal(x, y, M):
"""
Returns the value of the element (x,y) in M.
"""
if (x,y) in M:
return M[(x,y)]
elif (y,x) in M:
return M[(y,x)]
else:
return 0
pass | 3a260b1b8501b7501a456a8146ad5f1fb5f3b771 | 606,012 |
import pickle
def load_model(model_path):
"""
loads any trained model from model_path
args:
model_path (path-like): read from config.yaml
retuns:
model (sklearn.svm.SVC): trained classifier
"""
with open(model_path, "rb") as pickle_infile:
model = pickle.load(pickle_... | cb6f258aacfe2c174be854a58b126f1c3f088174 | 606,016 |
def integrate(da, over_dim, x=None, dx=None, method='trapz', cumulative=False, skipna=False):
"""
Returns trapezoidal/rectangular integration along specified dimension
| Author: Dougie Squire
| Date: 16/08/2018
Parameters
----------
da : xarray Dat... | 989f9ed7929e9c2d300bf8b646c59a8193185633 | 606,020 |
def landsat_c1_toa_cloud_mask(input_img, snow_flag=False, cirrus_flag=False,
cloud_confidence=2, shadow_confidence=3,
snow_confidence=3, cirrus_confidence=3):
"""Extract cloud mask from the Landsat Collection 1 TOA BQA band
Parameters
----------
... | cdbf1edd7980a616f52983e3085c0db826f45397 | 606,023 |
import time
def timestamp(method='iso8601'):
"""
make an iso8601 timestamp
Example:
>>> stamp = timestamp()
>>> print('stamp = {!r}'.format(stamp))
stamp = ...-...-...T...
"""
if method == 'iso8601':
# ISO 8601
# datetime.datetime.utcnow().isoformat()
... | 683312e00c30f29e1d04ecb5bd40910bf6cc672d | 606,025 |
def compare_lines(filename: str, basename: str, n: int) -> bool:
"""Compare a source file's lines with those of N separate files' lines
in ordered sequence. This is helpful for `split_file`, where we split a file into
chunks.
Args:
filename (str)
basename (str)
n (int)
Retu... | f5048ceafa711b7ddcde0fd048cf07abfb218674 | 606,028 |
def _composite_options(**kwargs):
"""Return a string representation of options that can be appended to a
composite metric query
"""
string = '{'
num_keys = len(kwargs.keys()) - 1
for index, key in enumerate(kwargs):
string += '{}'.format(key)
string += ': '
string += '"{}... | 1a276fc2bd02bed767bc67b0d878ad57bf72a0b0 | 606,030 |
import inspect
def is_classmethod(meth):
"""Detects if the given callable is a classmethod.
"""
if inspect.ismethoddescriptor(meth):
return isinstance(meth, classmethod)
if not inspect.ismethod(meth):
return False
if not inspect.isclass(meth.__self__):
return False
if n... | 14244212e52ce56e7e7e840d2b1d118d27ae3067 | 606,031 |
def extract_links(soup):
"""Extract outgoing links from a page."""
a_tags = soup.findAll('a', href=True)
links = [ link.get('href') for link in a_tags ]
return [ link for link in links if link and len(link) > 0 ] | 24867eb4098f487a5045e52c78e1de33eacecca1 | 606,033 |
def move(space: int, d: int) -> int:
"""For parm current space and die roll, return the new space the pawn will land on."""
return (space - 1 + d) % 10 + 1 | f5381b7de5fa96fb39d28a30656862d7b26d621a | 606,036 |
def vol_std(data):
""" Return standard deviation across voxels for 4D array `data`
Parameters
----------
data : 4D array
4D array from FMRI run with last axis indexing volumes. Call the shape
of this array (M, N, P, T) where T is the number of volumes.
Returns
-------
std_... | dc1779fbe28a78f3a345b6cbed2f95d4d87da9e4 | 606,038 |
def _subject_member_format(member_ref):
"""Format a member ref for consumption outside of this module."""
return {
'id': member_ref['id'],
'subject_id': member_ref['subject_id'],
'member': member_ref['member'],
'can_share': member_ref['can_share'],
'status': member_ref['s... | 24c6ad6123aebb3f0268c7eeed805ccd1a3e5aab | 606,039 |
def does_diff_include_ts_files(diff_files):
"""Returns true if diff includes TypeScript files.
Args:
diff_files: list(str). List of files changed.
Returns:
bool. Whether the diff contains changes in any TypeScript files.
"""
for file_path in diff_files:
if file_path.endswi... | b4bdde2c86687d27ccc0f59fdb4b5e76705e4ec7 | 606,042 |
def ranks(sample):
"""
Return the ranks of each element in an integer sample.
"""
indices = sorted(range(len(sample)), key=lambda i: sample[i])
return sorted(indices, key=lambda i: indices[i]) | 3961b17ea61624554d7cede104321fe5985039e4 | 606,043 |
def repeated_string(string: str, n: int, char: str = "a") -> int:
"""
>>> repeated_string("aba", 10)
7
>>> repeated_string("a", 1000000000000)
1000000000000
"""
string_size = len(string)
if string_size == 1:
return n if string == char else 0
whole, remainder = divmod(n, strin... | 02d9dd3925dec8690478b034071e8f624b973b8f | 606,044 |
from typing import List
def format_day_shifts(weekday: str, day_shifts: List[str]) -> str:
""" Convert given weekday shifts in a human-readable format.
E.g, 'tuesday': ['10 AM - 6 PM'] -> 'Tuesday: 10 AM - 6 PM' """
opening_hours = ", ".join(day_shifts) if day_shifts else "Closed"
return f"{weekday.c... | 3f662a52da262dd75362235b9551cf1bb3d3ac18 | 606,051 |
def merit3(EValw, Sw):
"""
Merit function calculation. Computes the merit function by selecting the
first scalar, ``Sw`` minus a weight. The weight is given by the average of
the second until last scalar. The first scalar is constructed in
`pypcaf.find_period` and `pypcaf.pca` functions. First the ... | a56379e9aa13fbdbf232b3a3ea4078bb83489001 | 606,052 |
def is_leaf(depth, node):
"""
is_terminal_fn for variable-depth trees.
Check if a node is a leaf node.
"""
return node.num_children() == 0 | f501e092886ffbbaffaae25b6199cfade030bfa8 | 606,055 |
import math
def is_square(n: int) -> bool:
"""Determines if the natural number n is a perfect square."""
return (int(math.sqrt(n)))**2 == n | d8f79746fa5733f10b2d7d8a438676b32aa160c6 | 606,057 |
def is_integer(obj):
"""
Return True if *obj* is an int, False otherwise.
"""
return isinstance(obj, int) | 34af733ffa96ff441379759fad14c80d6847a154 | 606,059 |
def fib2(n):
"""
returns list of Fibonacci series up to nth term
"""
result = [0, 1]
i = 2
while i < n:
result.append(result[i-1] + result[i-2])
i += 1
return result | dbef3bb7c270330c31860e350f0e15ed6d8d03e1 | 606,066 |
def cube_hessian_scaled(argument, lagrange, cube_scale= 1.):
"""
(Diagonal) Heissian of approximation to the
cube $[-\lambda,\lambda]^k$ with $\lambda$ being `lagrange`.
The function is
$$
z \mapsto \frac{2}{\lambda - z} - \frac{1}{\lambda - z + 1} +
\frac{1}{z - \lambda + 1}
$$
with... | e40404c18dc71dea43f308125d6f0f74cf8eca92 | 606,068 |
def octal_to_int(oct_str):
"""Convert an octal string to an int, respecting None"""
return int(oct_str, 8) if oct_str else None | b8eba750faba7858b7215443680664861c4708f1 | 606,070 |
import torch
def obtain_samples(flow, y, nsamples, device=None, batch_size=512):
"""Draw samples from the posterior.
Arguments:
flow {Flow} -- NSF model
y {array} -- strain data
nsamples {int} -- number of samples desired
Keyword Arguments:
device {torch.device} -- model de... | 06dfb1b75cc890bb939eebbf17beec2525198e6e | 606,071 |
from datetime import datetime
def unix_time(obj):
"""
Convert a date into an int from UNIX epoch time
Args:
obj (str): date
Returns:
str: UNIX epoch time
"""
t = datetime.strptime(obj, '%Y-%m-%dT%H:%M:%SZ').timestamp()
return str(round(t)) | 6815d849a6135068393a2b5af2f2bfb0163ba1ce | 606,072 |
def confusion_matrix(class_match_set, class_nonmatch_set, true_match_set,
all_comparisons):
"""Compute the confusion (error) matrix which has the following form:
+-----------------+-----------------------+----------------------+
| | Predicted Matches | Predicted Non... | 87bb0d3879d753816412c41cb0c33ed4776c5f3c | 606,073 |
import pytz
from datetime import datetime
def timestamp(time_format=None, local=False, time_zone=pytz.utc):
"""Return a formatted timestamp
Args:
time_format (str): A format suitable for ``strftime``
local (bool): If True, return timestamp in local timezone
time_zone: If local is Fals... | 9937832ed2e847e84006ec7c372fbcb48f23d848 | 606,075 |
def prep_file(file_name):
"""Take a file, extracts items line-by-line, and returns a list of them.
Args:
file_name (str): The file name to open
Returns:
items (list): A list of items extracted from the file
"""
items = []
with open(file_name) as files:
for newline in fi... | 267bab14557a85a60f600cc8908262f928df8b75 | 606,076 |
def match_replace_regex(regex, src_namespace, dest_namespace):
"""Return the new mapped namespace if the src_namespace matches the
regex."""
match = regex.match(src_namespace)
if match:
return dest_namespace.replace('*', match.group(1))
return None | 64496051177388b24c8e69896d654d5589916338 | 606,077 |
def subsample_fourier(x, k):
"""
Subsampling of a vector performed in the Fourier domain
Subsampling in the temporal domain amounts to periodization
in the Fourier domain, hence the formula.
Parameters
----------
x : tensor_like
input tensor with at least 3 dimensions, the last
... | 418a28bd9d96f70c338301fd0067811816513b52 | 606,081 |
import calendar
def get_leap_years(start_year=1980, end_year=2050):
"""
Gets the number of calendar days by year, either 365 or 366
Args:
start_year (Optional[int])
end_year (Optional[int])
Returns:
Dictionary, with keys --> values as yyyy --> n days
"""
leap_year_d... | 040e7d774d6ad52dbd3ff01dcc505add0649e0be | 606,086 |
def chrome_options(chrome_options):
""" Set options for the selenium chrome driver. """
chrome_options.add_argument('headless')
chrome_options.add_argument("--window-size=1280x800")
return chrome_options | 4280da2bbca9259a8771b47115c3150f0c9b81bd | 606,087 |
def get_header_files_size_data(sources_dir, header_files_by_size, rows_count):
"""
Builds table rows list containing data about header files sizes (largest/smallest).
:param sources_dir: configured sources directory
:param header_files_by_size: list of header files ordered by size (smallest to largest)... | 20a17490b453197784433d9efb8fea89deb9661e | 606,092 |
def PyFile_Name(space, w_p):
"""Return the name of the file specified by p as a string object."""
w_name = space.getattr(w_p, space.newtext("name"))
return w_name # borrowed ref, should be a W_StringObject from the file | 699f075691abd3e1f6f644d0a343090ca5c8fe15 | 606,093 |
def is_float3(items):
"""Verify that the sequence contains 3 floats.
Parameters
----------
items : sequence
The sequence of items.
Returns
-------
bool
"""
return len(items) == 3 and all(isinstance(item, float) for item in items) | 0ce6ad045941b626c75d84b649dc2cd4e5caec90 | 606,095 |
import torch
def random_joints2D_deviation(joints2D,
delta_j2d_dev_range=[-5, 5],
delta_j2d_hip_dev_range=[-15, 15]):
"""
Deviate 2D joint locations with uniform random noise.
:param joints2D: (bs, num joints, num joints)
:param delta_j2d_dev... | 17f96ce0637af952fcb369bba658788e88a2e901 | 606,101 |
import requests
def download(url, num_retries=2, user_agent='wswp', proxies=None):
""" Download a given URL and return the page content
args:
url (str): URL
kwargs:
user_agent (str): user agent (default: wswp)
proxies (dict): proxy dict w/ keys 'http' and 'https... | 953e2ecbf83f4829c2911448ef59c3204922c3f5 | 606,102 |
def reparameterize(mu, logvar):
"""
Draw a sample z ~ N(mu, std), such that it is differentiable
with respect to `mu` and `logvar`, by sampling e ~ N(0, I) and
performing a location-scale transform.
:param mu: torch.Tensor
:param logvar: torch.Tensor
:return:
"""
e = mu.new_empty(*mu... | 83f746bc6f51a5859173885622a31bbce2785e11 | 606,103 |
def load_txt(full_path_txt):
""" reads the AIF text file to find the AIF values and associated time-points.
Args
----
full_path_txt (string): file path to the AIF text file
Returns
-------
aif (list): arterial input function at each timepoint
time (list): co... | 59cb48476418c3ead167470cce6bdf77eda23946 | 606,110 |
def count_seqs(count_dict):
"""
Counts the total number of valid alignments
Parameters:
count_dict(dict): output from count_chrom_alignments()
Returns:
sum (int): Total number of valid alignments
"""
sum = 0
for id in count_dict:
sum += int(count_dict[id])
retur... | 2cf99b1ae0926b982e7ea6c96c834973b9483cae | 606,113 |
def node(issue, special=False):
"""Format a graph vertex as default or
triangle if special (i.e. blocking)."""
fmt = '"{}" '
if special:
fmt += "[ shape = triangle ]"
return fmt.format(issue) | 4a7f5cd2e3a8e288ec251d3f2cc1f3100f59ac56 | 606,114 |
def is_dev_only(dockerfile_path=str) -> bool:
"""
Check the build.conf for "devonly" flag.
Args:
dockerfile_path (str): the dockerfile's path
Returns:
"""
path = f"{dockerfile_path}/build.conf"
try:
with open(path) as f:
content = f.read()
if "devonl... | d51668751d9577cd64a52fb85267cf4d18d3ef63 | 606,117 |
def split_ver(v):
"""Covert the string '1.2.3' into the list [1,2,3]
"""
return [int(x) for x in v.split('.')] | df9b1d4cc6c63cbf82cc0a06374f6a9e73702308 | 606,119 |
def get_developer(repo_info):
"""Get trending developer name"""
try:
developer = ' '.join(repo_info.find('h2').find('a').text.split())
return developer
except AttributeError:
return | 2ce73e6676dd93ba2734bb354557caa516eb6ee8 | 606,121 |
def escape_quote_character_in_field(field_data: bytes, quotechar: bytes, escapechar: bytes) -> bytes:
"""
>>> escape_quote_character_in_field('test'.encode('ISO-8859-1'), quotechar=b'"', escapechar=b'"')
b'test'
>>> escape_quote_character_in_field('te"st'.encode('ISO-8859-1'), quotechar=b'"', escapechar... | cbb0f6fb92f96ac09d9ed439837abac7127c53d1 | 606,125 |
def replace_dict_keys(data, replacement):
"""
Recurisvely replaces the keys in data from a dictionary `replacement`.
"""
if isinstance(data, dict):
ret = {}
for k, v in data.items():
# Replace key
if k in replacement:
k = replacement[k]
... | 5529a9ecdcbda02bdc7e3acde7a38cb31b6d7f0e | 606,127 |
import requests
import json
def get(url):
"""
Submit http get to a URL and parse the JSON that's returned
:param url: The URL to submit get to
:return: The JSON response
"""
r = requests.get(url)
return json.loads(r.text) | 991c7fed0798142e4ed6925d955cc3a68f657174 | 606,128 |
def _has_parent_of_type(node, node_type, statement):
"""Check if the given node has a parent of the given type."""
parent = node.parent
while not isinstance(parent, node_type) and statement.parent_of(parent):
parent = parent.parent
return isinstance(parent, node_type) | 79e6feccb61acd961094eaf2adc20b58ce5cd613 | 606,130 |
def get_route_business_logic(fn):
"""
Returns the business logic function associated with an endpoint.
:param fn: The endpoint whose logic to return.
:return: A function pointer to the business logic for an endpoint, or None if no such logic exists.
"""
if not hasattr(fn, "route_business_logic")... | ac48fd4f540891c18a725363f8742f5ca29ce81d | 606,133 |
def from_latex_formula(text: str) -> str:
"""
Adapts a LaTeX formula to GIFT.
Parameters
----------
text: str
Naked (no $'s) LaTeX formula.
Returns
-------
res: str
GIFT-ready text.
"""
res = text
for to_be_escaped in ['\\', '{', '}', '=']:
res = res.replace(to_be_escaped, '\\' + to_be_escaped)
... | 7acf2288d3472635fc710e9221d79efacda56ea5 | 606,134 |
from pathlib import Path
def test_mbias_plot_config_file() -> str:
"""Return path to test M-bias plot config file
Note that this does not append the specification of the config dict
to be used (e.g. '*::default_config)
"""
return str(Path(__file__).parent / 'test_files' / 'test_mbias_plot_config.... | f865cbe1efa4893d6872395f3f69e041a70981a2 | 606,137 |
def killProcess(process):
"""
kill only if the process started and has not
finished yet (returncode is None if the process is alive)
"""
if (process is not None) and (process.returncode is None):
return process.kill() | a9f367d50c0f898688d04bb8fe1c438f158192dc | 606,141 |
def generate_output(advisory_id: str, details: dict) -> str:
"""
Generates the output for the given advisory_id and list of CPEs
:param advisory_id: Advisory ID from the OVAL XML file
:param details: Dictionary containing a list of CPEs and repositories for the advisory_id
:return: Output to displa... | 06f19ea4988d95cba7c1afb23ad228b8f838fbb0 | 606,142 |
def _get_bit(byte, ii):
"""Return the bit value at index `ii` of `byte`.
Bit index is 0 = MSB, 7 = LSB
"""
return (byte >> (7 - ii)) & 1 | 65de3c1f4e0fce19d05113b4cb13629b591c1f0d | 606,149 |
import copy
def select(a_list, query, *, exactly=0):
"""Scan a list of dictionaries and pick ones that match the query."""
documents = []
counter = 0
for item in a_list:
if not query(item):
continue
documents.append(copy.deepcopy(item))
if bool(exactly):
... | 9ca575ba0f2f098c6f006cb85370e846001daa8c | 606,150 |
def preprocess(lr, hr):
"""Preprocess lr and hr batch"""
lr = lr / 255.0
hr = (hr / 255.0) * 2.0 - 1.0
return lr, hr | 6ebbae474b8deddf09b994c502b820fabad68802 | 606,151 |
def parse_dssp(dssp_file):
"""parses a DSSP file and returns a dictionary of
keys=(resnum, chain) and values=(dssp code)"""
dssp_ss = dict()
with open(dssp_file, 'r') as infile:
for line in infile:
if line.startswith(' # RESIDUE'):
break
for line in infile:
... | a0c42d33460da2745ec0133df4890796b49d09f8 | 606,152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.