content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _subsample( X, ind):
""" like X[ind,:] but works in case X has size (n,) """
if X.ndim == 1:
y = X[ind]
elif X.ndim == 2:
y = X[ind,:]
else:
raise ValueError("Expected 1D or 2D array")
return y | 6d9a3632fbe88acdf664fe919e93b14ac2933a86 | 633,635 |
def _make_task_name(cls, addons=None):
"""Makes a pretty name for a task class."""
base_name = ".".join([cls.__module__, cls.__name__])
extra = ''
if addons:
extra = ';%s' % (", ".join([str(a) for a in addons]))
return base_name + extra | 07cd75c4782cdfcc268720c5a411a9eb161a4a0c | 633,636 |
def _test2(num1, num2):
"""Sample function for TestCase.
Returns the supplied values.
Args:
num1: number 1
num2: number 2
Returns:
float: sum of number 1 and 2
"""
return float(num1) + float(num2) | 9d43da9a9864d367a54248386e78fe15f0977a37 | 633,637 |
import six
def collect_namespaces(root_spec):
"""Constructs a set of namespaces in a given ElementSpec.
Args:
root_spec: An `ElementSpec` for the root element in the schema.
Returns:
A set of strings specifying the names of all the namespaces that are present
in the spec.
"""
findable_namespac... | 5eba961e8aaa7f4a84279fd082b55fab66f7ce37 | 633,638 |
def school2nation(id_num):
"""
Takes school id, returns nation id of the school.
"""
if id_num < 97100000:
return id_num // 100000 * 10000
if id_num < 97200000:
return 7240000
if id_num < 97400000:
return 8400000
return 320100 | 74e7eb74b2adf1cd2c8855a1bcc35eddf38586e3 | 633,639 |
def pybb_posted_by(post, user):
"""
Check if the post is writed by the user.
"""
return post.user == user | 5bd87efee55d00af13b10be2247956408c42cb18 | 633,646 |
import torch
def shearx_grid(output_size, ulim=(-1, 1), vlim=(-5, 5), out=None, device=None):
"""Horizontal shear coordinate system.
Args:
output_size: (int, int), number of sampled values for the v-coordinate and u-coordinate respectively
ulim: (float, float), Cartesian y-coordinate limi... | 76682d670995b45140207029458855201d3207ed | 633,647 |
import pickle
def get_ibc_data(use_neutral=False,
use_subsampling=False,
return_subsampling_depths=False,
labels=(0, 1, 2)):
"""
Samples the annotated IBC data. This dataset can be described
more here. http://www.cs.umd.edu/~miyyer/ibc/.
This dataset... | 4571b6d42b2dca1c52fb5089e29047c17c64363f | 633,651 |
def tokens2options(tokens):
"""Split the list of tokens into the options it specifies, even if
there is a single option.
Arguments:
`tokens` -- the list of tokens to split, as provided by the tokenizer.
Returns:
A list of options, suitable for parsing.
"""
options = []
option = []
... | ac3ba1d2c21a3d2e7b14ec55091dce2f6397b866 | 633,653 |
def threshold_RMSE(upper_bound, lower_bound, q=3):
"""Compute threshold for RMSE metric.
Args:
upper_bound (int): Upper bound of regression outputs
lower_bound (int): lower bound of regression outputs
q (int): Quantification parameter
Returns:
threshold (float): The minimal... | 210036056c59d4a52fa9401a78529ee7c8d3b503 | 633,658 |
def capitalize_correct(phrase):
"""
Capitalizes words in a string, avoiding possessives being capitalized
"""
phrase = phrase.strip()
return " ".join(w.capitalize() for w in phrase.split()) | 3771dbd16bb21a03cf009d8301821545e0a03f95 | 633,662 |
def parseSecondsIntoReadableTime(seconds):
"""Generate a string based on seconds having the format "m:s:cs"."""
minutes = seconds / 60
absoluteMinutes = int(minutes)
seconds = (minutes - absoluteMinutes) * 60
absoluteSeconds = int(seconds)
m = str(absoluteMinutes)
if absoluteMinutes <= 9:
... | 88773b328018b8b6b05139dc8e8e57f9e387c97c | 633,664 |
from typing import Dict
from typing import Any
from warnings import warn
def has_license_and_update(data: Dict[str, Any]) -> bool:
"""Check if license header exists anywhere in notebook and format.
Args:
data: object representing a parsed JSON notebook.
Returns:
Boolean: True if notebook contains the ... | 67f3f6d7b9f31961f138824482926dcf529f5409 | 633,670 |
from pkg_resources import get_distribution, DistributionNotFound
def distribution_version(name):
"""try to get the version of the named distribution,
returs None on failure"""
try:
dist = get_distribution(name)
except DistributionNotFound:
pass
else:
return dist.version | 08f437a02ea356abe821e635a5319f6bd324c204 | 633,673 |
def to_css_length(x):
"""
Return the standard length string of css.
It's compatible with number values in old versions.
:param x:
:return:
"""
if isinstance(x, (int, float)):
return '{}px'.format(x)
else:
return x | bb4dde6bb8288f3b7c11e89f56b1413f881abb86 | 633,674 |
def nD0_active(N, vzero, dr, L):
"""
Returns product of particle density n = N/L^2 and active diffusion constant
D_0 = vzero^2/2*dr.
Parameters
----------
N : int or float
Number of particles.
vzero : float
Self-propelling velocity.
dr : float
Rotation diffusion ... | 14ea2f249a68fd4dbdde94d72b94fc3d38009a68 | 633,675 |
def _val_to_bool(val):
"""Convert a text representation to a bool."""
if val == 'true':
return True
else:
return False | 7a5e2428b5025fad318622ff040c7b97282c8af3 | 633,679 |
import torch
def getTheLargestComponent(affinity_mat: torch.Tensor, seg_index: int, device: torch.device):
"""
Find the largest affinity_mat connected components for each given node.
This is for checking whether the affinity_mat is fully connected.
Args:
affinity_mat: (torch.tensor)
... | f782f32d17795e3ff94b158b86380faacd3c69a5 | 633,682 |
def rgb_from_int(val):
"""Return an RGB tuple converted from an int in the range [0, 0xffffff]."""
return tuple([
((val >> 16) & 0xff) / 0xff,
((val >> 8) & 0xff) / 0xff,
(val & 0xff) / 0xff]) | 8fa2447d8ee3df1b084331204fb8b79a5885847a | 633,688 |
import requests
def exchange_token(refresh_token, token_endpoint, client_id):
"""Exchange token for access token."""
response = requests.post(
token_endpoint,
data={
'grant_type': 'refresh_token',
'client_id': client_id,
'refresh_token': refresh_token,
... | bd8573ce96961f67dee5fb7af62bcceca93f9ae8 | 633,690 |
from bs4 import BeautifulSoup
import requests
def get_soup(url: str) -> BeautifulSoup:
"""
Generic BeautifulSoup page scraping starter code
:param url: String, the url of the page to scrape
:return: BeautifulSoup object
"""
try:
page: requests.Response = requests.get(url)
soup:... | bd0d5d14c8e6d1b12b6061f14babc317105849aa | 633,693 |
import re
def detect_file_content(content: str, f: str="/etc/passwd") -> bool:
""" Detect specific file content in content
:param str content: file content that should be analyzed
:param str f: file that the content should be compared with
:return bool: True if the content was recognized, False other... | c4043b2c2bd6b43f3e1b6e8bfda201950d9120ac | 633,695 |
def should_be_zipped(input_file, input_files):
"""
Determine whether a given input file should be included in the zip.
Compiler includes and target files should only be included if there is
no compiler info file present.
"""
return (input_file in ['metadata.json', 'compiler_info.json']
... | 8f6667928357807e0dba683ac1f655911a0703fc | 633,696 |
def get_idx_via_binary_search(nums: list[int], target: int) -> int:
"""Returns the index of target if it exists, otherwise -1
Complexity:
n = len(nums)
Time: O(logn)
Space: O(1)
Args:
nums: array of integers sorted in ascending order
target: element for which to sea... | 4aa52f2a22d13be23d2fdb69b2e6495d43369254 | 633,697 |
import torch
def gaussian_sample(mu, sigma):
""" Sample a gaussian variable using the reparametrization trick.
Arguments:
mu (torch.Tensor): Mean.
sigma (torch.Tensor): Standard deviation. Same size as mu.
Returns:
z (torch.Tensor): Samples. Same size as mean.
"""
... | 5017285f806723f0ec7aa1c3f713fa5d3785216b | 633,698 |
def compare_digest(a, b):
"""
** From Django source **
Run a constant time comparison against two strings
Returns true if a and b are equal.
a and b must both be the same length, or False is
returned immediately
"""
if len(a) != len(b):
return False
result = 0
for ch_a, ... | 9f96e33e9ee37208a152ed3a4d79c22909b79b58 | 633,700 |
from typing import Dict
import time
import requests
def stock_js_weibo_nlp_time() -> Dict:
"""
https://datacenter.jin10.com/market
:return: 特定时间表示的字典
:rtype: dict
"""
url = "https://datacenter-api.jin10.com/weibo/config"
payload = {"_": int(time.time() * 1000)}
headers = {
"aut... | 69292b924e058122822bb6caec970d2fc39da508 | 633,701 |
def square_this(x):
"""Return the square of a number."""
return x**2 | 2e93801ba9d53b11acb3600f012fffa7d2ee0801 | 633,704 |
async def assert_reply_matches(self, contents: str, regex):
""" Send a message and wait for a response. If the response does not match a regex, fail the test.
Requires a properly formatted Python regex ready to be used in the ``re`` functions.
:param str contents: The content of the trigger message. (A co... | f898b0904a7d6909453eb204fdd1abfeb42437c2 | 633,707 |
def list_apim_api(client, resource_group_name, service_name):
"""List all APIs of an API Management instance. """
return client.api.list_by_service(resource_group_name, service_name) | d6242d20fa146784f646280fae390653325659ca | 633,711 |
def remote_bazel_options(crosstool_top):
"""Returns bazel options for the "remote" execution strategy."""
k8 = [
"--cpu=k8",
"--host_cpu=k8",
"--crosstool_top=" + crosstool_top,
"--define=EXECUTOR=remote",
]
return k8 + [
"--spawn_strategy=remote",
"--genrule_strategy=remote"... | 60a1a851b2b51dcd58602d416d4a20b0f690fa6e | 633,713 |
def get_mode_H_array(mode_H, mode_MR, mode_OR):
"""暖房の運転モードを取得する
Args:
mode_H(str): 暖房方式
mode_MR(str): 主たる居室の運転方法 (連続運転|間歇運転)
mode_OR(str): その他の居室の運転方法 (連続運転|間歇運転)
Returns:
tuple: 暖房の運転モード
"""
# 運転モード(暖房)
if mode_H == '住戸全体を連続的に暖房する方式':
# 全館連続
return tu... | 77bc356e7212a250c5e15fff63ecb34052548088 | 633,715 |
def is_short_info(obj):
"""Return whether the object is a short representation of a dataset"""
fields = ['bodySize', 'bodyRows', 'bodyFormat', 'numErrors', 'metaTitle',
'commitTime']
return bool(set(obj) & set(fields)) | 62a4f59d29b5999a6bd5e10eed5513f5925f1d01 | 633,716 |
def compute_average_bits(encodings, frequency):
"""
Compute the average storage bits of the current layer after Huffman Coding.
:param 'encodings': Encoding map mapping each weight parameter to its Huffman coding.
:param 'frequency': Frequency map mapping each weight parameter to the total number of its... | 8bf4296f742dab76145c8fbc6d37249b054aff18 | 633,717 |
def split_list(ls, sep):
"""
Split list similarly to split string, according to some separator
"""
ret = []
cur = []
for x in ls:
if (x != sep):
cur.append(x)
elif cur:
ret.append(cur)
cur = []
if cur:
ret.append(cur)
return ret | fc978be22ff39ad416bd1e6a0ec0974758852c47 | 633,719 |
def get_function_indent(line: str) -> int:
"""
Get function indents from begging of the file.
"""
first_function_entrance = line.index('def')
indents = line[:first_function_entrance]
indents_space_count = len(indents)
return indents_space_count | 1e42e082f0c171255c6cac4d426191a83d12a719 | 633,721 |
def subject_member_update(client, memb_id, values):
"""Update an SubjectMember object"""
return client.subject_member_update(memb_id=memb_id, values=values) | 425fa1d21186d5c18e9478cb6a6ec200c56f7f12 | 633,722 |
from pathlib import Path
def existing_git_submodule(path: Path) -> bool:
"""Check if a git submodule exists
:param Path path: Submodule path
:return: True, if .git file exists inside path
"""
return Path(path / '.git').is_file() | a0fb29aad65373f49d5306daa3ac13475f328a72 | 633,725 |
def round_odd(x):
"""Round X to nearest odd integer."""
return int(x + 1 - x % 2) | 25dcf95626a280b61d4a1b1c9270fe9d358a0688 | 633,731 |
def consensus_decision(consensus):
""" Given a consensus dict, return list of candidates to delete/archive.
"""
delete = []
archive = []
for k, v in consensus.items():
tags = v['tags']
if 'delete' in tags or 'rfi' in tags:
delete.append(k)
elif 'archive' in tags ... | 789526ef84e6522651a2e13f676688320445fc95 | 633,735 |
def _input_wrap(prompt, default=None):
"""
Run input() with formatted prompt, and return
The while loop can be used to ensure correct output
"""
understood = False
while not understood:
result = input(prompt.format(default=default)).lower().strip()
if result in {"y", "yes"}:
... | 112e1bf613e1fc79d570107e881edbb8f721076c | 633,738 |
import hashlib
def hash_file(file_path):
"""
Return the hash of a file.
"""
md5 = hashlib.md5()
with open(file_path, 'rb') as file:
md5.update(file.read())
return md5.hexdigest() | f15f591f5e5ca1ae3d807b3b47fddccf3cfdceaa | 633,739 |
def getmAxId(root):
"""Returns the highest id number from the xml """
a=0
for face in root.iter('Face'):
id = int(face.attrib.get('id'))
if(id>a):
a=id
return(a) | cd6c20933d460a442b2eb48525a5dae895ba6544 | 633,740 |
def cer(e):
"""
Canonicalize the representation of an undirected edge.
Works by returning a sorted tuple.
"""
return tuple(sorted(e)) | 799a7765c2b77d50828c5b3a365713305a84531e | 633,751 |
def delete_migration(connection, basename):
"""
Delete a migration in `migrations_applied` table
"""
# Prepare query
sql = "DELETE FROM migrations_applied WHERE name = %s"
# Run
with connection.cursor() as cursor:
cursor.execute(sql, (basename,))
connection.commit()
... | de81e8443343c90aae4690e7c1b2bed9e8dd3239 | 633,752 |
def build_slack_message(integration, title, title_link, fallback_text, fields,
pre_text, body, color, thumb_url, image_url):
"""Build message using Slack webhook format.
This will build the payload data for HTTP requests to services such as
Slack, Mattermost and Discord.
Args:
... | 108c9d556cc70aafaf7c4f2c53a2356c753c1a6a | 633,756 |
def iface_definition(iface, ssid, psk):
"""Returns the corresponding iface definition as a string,
formatted for inclusion in /etc/network/interfaces.d/"""
return \
"""iface {} inet dhcp
wpa-ssid "{}"
wpa-psk {}
""".format(iface, ssid, psk) | 4f4e2899250e7002edcdb65af6674cfe3815ab57 | 633,758 |
def get_walk_data(walk, data):
"""Retrieve data specific to a given walk.
Args:
walk (str): walk identifier.
data (dict): holds all data matrices/lists, including unique
walk identifiers in 'subject_walk_IDs'.
Returns:
walk_data (dict): all data matrices/lists for a sin... | b18578bead7c92fa248903f74f3732cf2c10641d | 633,759 |
def degrees(graph):
"""Returns a list of node degrees in a ProgramGraph.
Args:
graph: A ProgramGraph.
Returns:
An (unsorted) list of node degrees (in-degree plus out-degree).
"""
return [len(graph.neighbors(node)) for node in graph.all_nodes()] | c267577c476ddce3112870532753eb6a4cbcfdd5 | 633,760 |
import math
def haversine(origin, destination):
"""
Returns the distance between two points using the haversine formula
http://www.platoscave.net/blog/2009/oct/5/calculate-distance-latitude-longitude-python/
>>> int(haversine((-1.31017, 51.7459), (-1.199226, 51.749327)))
7647
"""
... | 1bd61ffb086eaf8898cf545e65d851b338c38626 | 633,763 |
import requests
import time
def request_url_json(url: str) -> dict:
"""Get JSON object version of reponse to GET request to given URL.
Args:
url: URL to make the GET request.
Returns:
JSON decoded response from the GET call.
Empty dict is returned in case the call fails.
"""
print(url)
try... | 98c0ed775c58a99984c09d2c545a8b03f6492f0c | 633,769 |
def kmer_count(k, rc=False):
"""
Counts the number of possible k-mers
Args:
k (int): kmer size
rc (bool): Use canonical k-mers
Returns:
int: number of possible kmers
"""
if not rc:
return 4**k
n_palindromes = 0
if k % 2 == 0:
n_palindromes = 4**(... | 26545d0dabdf562b16dcbc323a79e7fc50f7e303 | 633,770 |
def long_repeat(line):
"""
length the longest substring that consists of the same char
"""
line_length = len(line)
if line_length <= 1:
return line_length
count_list = [0]
current_count = 1
current_ch = ''
for i in range(0,line_length):
ch = line[i]
if ch... | 4f7a2dfc5ec6ed08eaa9fc114e4484324b8bdfaa | 633,772 |
def get_initial_cholcovs_index_tuples(n_mixtures, factors):
"""Index tuples for initial_cov.
Args:
n_mixtures (int): Number of elements in the mixture distribution of the factors.
factors (list): The latent factors of the model
Returns:
ind_tups (list)
"""
ind_tups = []
... | 4f05cbe919fa47360eaf41064f79c9c5a5f7d940 | 633,773 |
def parametrizeTimeoutMixin(protocol, reactor):
"""
Parametrizes the L{TimeoutMixin} so that it works with whatever reactor is
being used by the test.
@param protocol: A L{_GenericHTTPChannel} or something implementing a
similar interface.
@type protocol: L{_GenericHTTPChannel}
@param ... | c544304edaab99ab69de0d23c261a1fa69239ae4 | 633,775 |
import hashlib
def checksum_file(path):
"""Compute the sha256 checksum of a path"""
hasher = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hasher.update(chunk)
return hasher.hexdigest() | 913114ed0a21edc2bfd64312d5f503dfb2310746 | 633,776 |
from typing import Optional
import torch
import itertools
def unit_box(n: int, scale: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Create a (scaled) version of a unit box
Args:
n: number of dimensions
scale: scaling of each dimension
Returns:
torch.Tensor: scaled unit ... | 13ee8e3498e3f613e7f8286c80d5098af24b1dcc | 633,777 |
def get_p2p_ssqr_diff_over_var(model):
"""
Get sum of squared differences of consecutive values as a fraction of the
variance of the data.
"""
return model['ssqr_diff_over_var'] | 193b81827c6dd5a3f2ff3c1456a8acf29707f49e | 633,780 |
def SetPageSize(unused_ref, args, request):
"""Set page size to request.pageSize.
Args:
unused_ref: unused.
args: The argparse namespace.
request: The request to modify.
Returns:
The updated request.
"""
if hasattr(args, 'page-size') and args.IsSpecified('page_size'):
request.pageSize = ... | 3482ce9d17407bc21c629520f96207b75c2b15e4 | 633,781 |
def reverse_y_mapper(height, mapper):
"""
Returns a coordinate mapper function for grids with reversed Y coordinates.
:param height: width of strip
:param mapper: grid mapper to wrap
:return: mapper(x, y)
"""
max_y = height - 1
def y_mapper(x, y):
return mapper(x, max_y - y)
... | 9a33ef9a7b9fb831198fc567ee64965f68835a70 | 633,783 |
def ip_version(vnum):
"""String version of ip version"""
return 'ipv4' if vnum == 4 else 'ipv6' | 81f7df80861e2f7cb675b4e56bf50f03c1eeb515 | 633,785 |
def create_padding_mask(seq):
"""
Mask all the pad tokens in the batch of sequence. It ensures that the model does not treat padding
as the input.
The mask indicates where pad value 0 is present: it outputs a 1 at those locations, and a 0 otherwise.
The input shape is [batch, seq_len], the output sh... | e133a2f93ea0ea9a4e053b384831971bff85bd1a | 633,790 |
def ns_between(l, r, ns):
"""Checks if all ns are between l and r (inclusive)."""
return all(l <= n <= r for n in ns) | dfa30d7ddf3abe0832387df1205591c09fc88e99 | 633,791 |
def dom2dict(element):
"""Converts DOM elements to dictionaries of attributes."""
keys = list(element.attributes.keys())
values = [val.value for val in list(element.attributes.values())]
return dict(list(zip(keys, values))) | ecf828218236961d03d7abff71beec15384622ed | 633,799 |
def split(text):
"""
Convenience function to parse a string into a list using two or more spaces
as the delimiter.
Parameters
----------
text : string
Contains text to be parsed
Returns
-------
textout : list
list of strings containing the parsed input text
"""
... | abc45882e8b333a608e65d8e171fc155b9b3e749 | 633,800 |
def format_time(t, format_spec='dhms'):
"""
Return a formatted time string describing the duration of
the input in seconds in terms of days,hours,minutes and seconds.
"""
if format_spec == '':
sb, mb, hb, db = True, True, True, True
else:
sb = 's' in format_spec
mb = 'm' in format_spec
hb = 'h' in format... | 405e9e914cca2b620704f82c08826d50af7f30ce | 633,802 |
def scale_for_curses(rgb_value: int) -> int:
"""Scale a single RGB value for curses.
:param rgb_value: One RGB value
:returns: The value scaled for curses
"""
curses_ceiling = 1000
rgb_ceiling = 255
return int(rgb_value * curses_ceiling / rgb_ceiling) | 9b1b36466c8f63b249c92bfc91deb39bbcbba651 | 633,803 |
import requests
def minify(file_content:str) -> str:
"""Access Toptal's CSS Minifier API.
Parameters
----------
file_content : str
CSS file content in str format.
Returns
-------
str
Minifier CSS in str format.
"""
payload = {'input': file_content}
url =... | 1a81b822f56262cd18e9405a40c5ee3cdc529726 | 633,804 |
def simple_wsgi(_, start_response):
"""A simple wsgi app that always returns an empty response."""
start_response("200 OK", [("Content-Type", "text/html")])
return [b""] | b0d576bfa684f6d7edb8d54afae680d1b93b91c6 | 633,806 |
def count_consecutives(tosses):
"""
Counts the number of consecutive heads or tails.
"""
consecutive_tosses = 1
max_consecutive_tosses = 1
for i in range(0, len(tosses) - 1):
if tosses[i] == tosses[i + 1]:
consecutive_tosses += 1
max_consecutive_tosses = max(max_c... | cc985dce259302f60c124668f539a5d1cd0a2c4e | 633,809 |
def get_target_for_label(label):
"""Convert a label to `0` or `1`.
Args:
label(string) - Either "POSITIVE" or "NEGATIVE".
Returns:
`0` or `1`.
"""
if(label == 'POSITIVE'):
return 1
else:
return 0 | 88b9a7ec3efec5cfa8c26d4651aabe28b1e63adf | 633,810 |
def custom_format(template, **kwargs):
"""
Custom format of strings for only those that we provide
:param template: str - string to format
:param kwargs: dict - dictionary of strings to replace
:return: str - formatted string
"""
for k, v in kwargs.items():
template = template.replac... | 9664bbd5799286f6950b3515e6d4144c0569dcdd | 633,815 |
def invert(dct):
""" Transposes the keys and values in a dictionary
:param dct: dictionary to transpose
:tupe dct: dict
:rtype: dict
"""
return {val: key for key, val in dct.items()} | 29a788c05982c72ee9bb77018ae9fabb402042bb | 633,821 |
def comp_stacked_rating_hist_allbrands(review_item):
"""
Compute rating distributions for all brands
:param review_item: a merged data frame containing item and review info
:return: brands: an ascending list containing names of all brands
scores: an ascending list containing all possible ra... | 55392ce55e137efe8af1746f757fef33430f362f | 633,823 |
def is_number(term):
"""check if term is a number. Returns bool"""
if isinstance(term, int) or term.isdigit():
return True | 9bf36372e98759d9b1b471de32d0b608fa9143b1 | 633,825 |
def compact(inDict, keep_if=lambda k, v: v is not None):
"""
Takes a dictionary and returns a copy with elements matching a given lambda removed. The
default behavior will remove any values that are `None`.
Args:
inDict (dict): The dictionary to operate on.
keep_if (lambda(k,v), option... | 68633968b0e1f3e4e22a1f4d4793b3174a00392d | 633,827 |
def simple_filter(**kwargs):
"""Return a simple filter that requires all keyword arguments to be equal
to their specified value."""
criteria = []
for key, value in kwargs.items():
criteria.append({'type': 'SIMPLE', 'propertyName': key,
'operator': 'Equals', 'operand': va... | aae4cbd9263345ea6a561ea40ba4f412323c589b | 633,830 |
def fixture_repo_id() -> int:
"""Return a repository ID."""
return 102909380 | abc7cd8e79ba499ce6412ce7c4f8a9216696a573 | 633,834 |
import inspect
def disable_for_loaddata(signal_handler):
"""The signals to update denormalized data should not be called
during loaddata management command (can raise an IntegrityError)"""
def wrapper(*args, **kwargs):
for fr in inspect.stack():
if inspect.getmodulename(fr[1]) == 'load... | ed91b7e354b6ba27ff4cf3da4a26ea94bb0920d4 | 633,835 |
def remove_short_segments(
lbl_tb, segment_inds_list, timebin_dur, min_segment_dur, unlabeled_label=0
):
"""remove segments from vector of labeled timebins
that are shorter than specified duration
Parameters
----------
lbl_tb : numpy.ndarray
vector of labeled spectrogram time bins, i.e.... | c9bf2d57e6a404d268fac4dcae5fef76e6ca3a97 | 633,836 |
def simple_decorator(pattern=None):
"""Build a simple decorator function from the given pattern.
The decorator will prefix each line with the given pattern. If the given
pattern contains a '{}' placeholder, it will be used as a separator
between the prefix and suffix. In other words, this:
simpl... | e294c491a5443a47cd1b36db0bc7a23beda5ae03 | 633,841 |
def parse_tf_ids(target_tfs_filename):
"""
If user has provided a file with Ensembl transcript ids, parse these to a list.
"""
with open(target_tfs_filename, 'r') as target_tfs_file:
target_tfs_list = target_tfs_file.read().splitlines()
target_tfs_list = [x.upper() for x in target_tfs_l... | 0f29175e300c651588bddcf3c98e76c5c39abcea | 633,842 |
def strfdelta(tdelta, fmt):
"""Utility function. Formats a `timedelta` into human readable string."""
d = {"days": tdelta.days}
d["hours"], rem = divmod(tdelta.seconds, 3600)
d["minutes"], d["seconds"] = divmod(rem, 60)
return fmt.format(**d) | 0057311e65dc8517a46ff4bbaff53b4e99417187 | 633,847 |
from typing import Any
import functools
import inspect
def is_coroutine_function(obj: Any) -> bool:
"""
Correctly determines if an object is a coroutine function,
including those wrapped in functools.partial objects.
"""
while isinstance(obj, functools.partial):
obj = obj.func
return i... | 9bd275de3f27c6b7e6653eb052e9dd45f3832688 | 633,851 |
def is_kernel_module_loaded(module_name):
"""
Checks whether the kernel module with the specified name is loaded.
Args:
module_name (str) : Name of the module to check.
Returns:
True, if the module is loaded; otherwise False.
"""
with open("/proc/modules") as file:
lin... | 3b5018e05c494d7791eb994a2433c2062ee91589 | 633,852 |
def GenerateAnnulusRZPhiToNode(nRCoords, nZCoords, phiPoints):
"""
Generate the map from r, z phi IDs to node IDs for a structured 3D linear
tet annulus mesh
"""
rzphiToNode = []
index = 0
for i in range(nRCoords):
rzphiToNode.append([])
for j in range(nZCoords):
rzphiToNode[i].append([]... | 0a017582fe5cc3c6fd72fc44e90aa69f08e7be09 | 633,853 |
def clip_command(command):
"""Is this a clip command?
:param command: string
"""
# It is possible to have `\clip` or `SELECT * FROM \clip`. So we check
# for both conditions.
return command.strip().endswith('\\clip') or command.strip().startswith('\\clip') | 3b2b167ea36f8e095dcda22708a18cd5cf809e64 | 633,858 |
def sum_digits(n):
"""Calculate the sum of digits.
Parameters:
n (int): Number.
Returns:
int: Sum of digitis of n.
Examples:
>>> sum_digits(42)
6
"""
s = 0
while n:
s += n % 10
n //= 10
return s | b017b1ad886c65536bd47316f92cc14b9ab0885c | 633,861 |
def Pad(ids, pad_id, length):
"""Pad or trim list to len length.
Args:
ids: list of ints to pad
pad_id: what to pad with
length: length to pad or trim to
Returns:
ids trimmed or padded with pad_id
"""
assert pad_id is not None
assert length is not None
if len(ids) < length:
a = [pad... | 3533e3d38c6f5ed4dae25b565ce2805a9b55c2ef | 633,869 |
import csv
def read_symbols(symbol_file='symbols.csv'):
"""
Read symbols.
Parameters
----------
symbol_file : str
Path to a CSV (with ',' as delimiter) which contains one symbol label
in the second colum
Returns
-------
list
Of symbol labels
"""
with o... | 65cc8c41f860c779ab8d8a1f94266fbc9930ea5a | 633,874 |
def extract_inventions_dreamcoder(dc_json):
"""
extract the learned inventions from a dreamcoder json file and sort by length
"""
return sorted([prod["expression"] for prod in dc_json["DSL"]["productions"] if prod["expression"].startswith("#")], key=len) | b32831439a5f7729004604a2765a9f20bf443871 | 633,875 |
def load_cluster_labels(clusterpath, one_indexed=True):
"""
one_indexed: if true, assume cluster index starts at 1 (e.g. as in 2018_scMCA data)
"""
cluster_labels = {}
if one_indexed:
dec = 1
else:
dec = 0
# expected format of csv file is "cluster number, name"
with open(... | fed3adb9dc9c5653aaf05548a8c7e6d5739f6e82 | 633,878 |
from typing import List
from typing import Dict
from typing import Any
def exact_str_match_fn(targets: List[str], responses: List[str]) -> Dict[str, Any]:
"""Exact match between targets and responses."""
# aitor: might want to use these metrics after removing irrelevant words.
# they do something like thi... | e36a81358cdbd3eee383b827cfac79bbdb29c99d | 633,880 |
def parse_coverage_list(coverage_list):
"""
Given a coverage_list (structured as a list of coverage statements (which
are strings) that define the poset, parses them into a dictionary.
Parameters
----------
coverage_list : `list`
list of coverage statements defining a poset, e.g.:
... | 9715bd6fed1c3d032ef5ef5524429c35a7370307 | 633,882 |
def author_name(author):
"""
Rewrite author name in a specific form:
Take the last word that is present in 'author'. Set that as last name.
If a different word is present, take the first letter. If not, set a default of X.
e.g. the name 'Albert de Vries' gets turned into 'A. Vries';
... | de7831b5f5e9dd4225275e3dc07d6608697aa9ee | 633,887 |
def update_pos(pos1,pos2):
"""
Get the coordinate of the bounding box containing two parts
:param pos1: Coordinate of the first part.
:param pos2: Coordinate of the second part.
:return: Coordinate of the bounding box containing the two parts
"""
x1 = min(pos1[0],pos2[0])
y1 = min(pos1[1... | db671fb75640436852e96e86b3af96985e52e605 | 633,889 |
def FOG(conf, value):
"""Get FOG Color code from config"""
if value == 1:
return conf.get_color("colors", "color_fog1")
else:
return conf.get_color("colors", "color_fog2") | bc50f383f2fe42e47ed95b00fc8d579529513322 | 633,891 |
def is_id(argument: str) -> bool:
"""
Determines whether the given argument is a valid id (i.e. an integer).
:param argument: the string argument to evaluate
:return: true if the argument can be evaluated as an interger, false otherwise
"""
try:
int(argument)
except ValueError:
... | 280ca87168366e9c4fae6c4e7297cdabc9ee497e | 633,892 |
def author_clean(author):
""" Clean an author and return the formatted string """
replace = [".", ";", " ", ",", "_", "-"]
author_split = author.strip().split(",")
clean_author = ""
if len(author_split) >= 2:
last_name = author_split[0]
first_name = author_split[1]
for rep in... | 85f43ab0d8d2c6f40508a3770aad0d24c75daaa1 | 633,893 |
def fill_array(x,x_val):
"""
fill_array(x,x_val)
If x_val[i] != None then x[i] == x_val[i].
"""
constraints = []
for i in range(len(x)):
if x_val[i] != None:
constraints += [x[i] == x_val[i]]
return constraints | 68c5260a95a4cf23daf556b225cc270152b21088 | 633,894 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.