content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_clean_films(input_list):
"""
Takes a list of movies' URLs from SWAPI and returns the actual movie names from the dictionary 'movie_reference'.
"""
movie_reference = {"1": "Ep 4: A New Hope",
"2": "Ep 5: The Empire Strikes Back",
... | 629eabdc8b3bf5d035d93633b89ad9d2fb0cb7b9 | 633,008 |
import re
def check_list_name(name):
"""checks that list_name begins with an alphanumeric character
Parameters
----------
name: string
name of the new listing.
Return
------
bool
True if listing name conforms to requirements
"""
return re.search(r'^\w+', name) ... | 4ce46453b6a0afa233569b171923a31e0ac3cacd | 633,009 |
def total_norm(tensors, norm_type=2):
""" Computes total norm of the tensors as if concatenated into 1 vector. """
if norm_type == float('inf'):
return max(t.abs().max() for t in tensors)
return sum(t.norm(norm_type) ** norm_type
for t in tensors) ** (1. / norm_type) | a5f7c4a8687a1f8e33dc507bd0428de34d278b27 | 633,010 |
def multiply_list(input_list):
"""
"""
result = 1
for number in input_list:
result = result * number
return(result) | 8b7948b73f656a6179ebc01243239f98f78a9f12 | 633,012 |
import re
def charges_clean_up(charges):
""" Returns cleaned charges. Charges are typically separated by newlines
and can often be in all caps, which we want to avoid."""
charges = charges.split("\n")
charges = [charge.capitalize() for charge in charges]
charges = "; ".join(charges)
# we want... | 7d3e65f12bc488f40af9d4421f3d0c58e01ce9cd | 633,013 |
def true_report(report):
"""Converts a boolean report into a string for output
Only used when the --boolean option is used. Converts the boolean
report into a string that is every key in the boolean report that has a
True value, joined by linebreaks (\\n)
Arguments:
report (list): the it... | a7314b51740135816a0f95afa0df999d720af4e3 | 633,014 |
import os
def get_filesize(file):
"""
Get file size. (GB)
"""
fs = os.path.getsize(file)
print(f"file size: {fs / 1024 ** 3:.3f} GB")
return fs / 1024 ** 3 | f520e98a93c6f843d86c38a1cf8bb14c21dd1c97 | 633,015 |
def make_ordinal(number):
"""
Coverts an integer to an ordinal string
:param number: integer to convert
:return: ordinal string
"""
number = int(number)
suffix = ['th', 'st', 'nd', 'rd', 'th'][min(number % 10, 4)]
if 11 <= (number % 100) <= 13:
suffix = 'th'
return str(numbe... | a022254ac0d7820f10688618314400eabe7dd758 | 633,016 |
def _get_displayed_page_numbers(current, final):
"""
This utility function determines a list of page numbers to display.
This gives us a nice contextually relevant set of page numbers.
For example:
current=14, final=16 -> [1, None, 13, 14, 15, 16]
This implementation gives one page to each side ... | 2c37f9a3de18b3aed22fe0e2cca84aeed4ce327b | 633,017 |
def OP_start(counter_state):
"""Our start state initializes counter_state.count = 0"""
counter_state.count = 0
operator = "counter"
return(operator, counter_state) | 0a261f9984ebfb3f732074212a278b8d96110790 | 633,018 |
def div_inplace(X, varX, Y, varY):
"""In-place division with error propagation"""
# Z = X/Y
# varZ = (varX + varY * (X/Y)**2) / Y**2 = (varX + varY * Z**2) / Y**2
X /= Y # X now has Z = X/Y
T = X**2 # create T with Z**2
T *= varY # T now has varY * Z**2
varX += T # varX now has varX ... | 197215925eefadd2390d4aaa1596d7177bff6358 | 633,019 |
def create_agents():
"""
Creates a new agents definition.
:return: dictionary with agents definitions.
"""
return {} | f8f63e0598779910fd7c31acd8be04f19a60ce85 | 633,020 |
def get_train_test_data(all_fc_data, train_subs, test_subs, behav_data, behav):
"""
Extracts requested FC and behavioral data for a list of train_subs and test_subs
"""
train_vcts = all_fc_data.loc[train_subs, :]
test_vcts = all_fc_data.loc[test_subs, :]
train_behav = behav_data.loc[train_subs... | 33a7288ae262bb7591f16b82f7a42cc628c671b5 | 633,021 |
import uuid
def _get_uuids(cnt):
"""
Return things like this 75659c39-eaea-47b7-ba26-92e9ff183e6c
"""
uuids = set()
while len(uuids) < cnt:
uuids.add(str(uuid.uuid4()))
return uuids | a1efa3020ddf125c401a7f55ba6014a1e4f257d5 | 633,022 |
def exp_smooth(new_n, new_s, new_m, old_n, old_s, old_m, a = 0.05):
"""
This function takes in new and old smoothed values for mean, sd and
sample size and returns an exponentially smoothed mean, sd and sample
size.
"""
smooth_n = a*new_n + (1-a)*old_n
smooth_s = a*new_s + (1-a)*old_s
sm... | 08c8c8c5aee12e530cd5152d8e5558fabcb68058 | 633,023 |
def hash1(key: str, tablesize: int) -> int:
"""
散列一个长度(最多)为8的字符串
C语言char型的范围是1~127,0是字符串结尾
求和的结果是8~1016=127*7
这样不是均匀分配(黑皮书说)
这是因为ASCII表中,可显示字符只占一部分
"""
hashval = 0
# 逐个读取字符的ASCII值
for k in key:
hashval += ord(k)
return hashval % tablesize | 725f188d39af57a636e1dc51915878c85ec776e3 | 633,024 |
def main(request, response):
"""
Check that headers sent to navigate here contain the device-memory client
hint, and report success/failure in a way compatible with
verify_navigation_state() in accept-ch-test.js
"""
if "device-memory" in request.headers and "sec-ch-ua" in request.headers and "s... | 519505ad2b265f82c8a6e28800c00c1dc87bae6d | 633,025 |
from bs4 import BeautifulSoup
import re
def get_summary(content):
"""Gets the summary of a license from tldrlegal.com"""
soup = BeautifulSoup(content, "html.parser")
summary = soup.find_all(attrs={
'class': re.compile(r".*\bsummary-content\b.*")})
if summary[0].p.string is None:
return summary[0].p... | c29e97369867a92eef2dbd5a75ecd7b33d571c71 | 633,026 |
import os
def hasextension(path, extension):
"""
Check to see if file has a certain extension.
e.g. isextension('hello.txt', '.txt') => True
:param path: The path / name of the file.
:return:
"""
_, file_extension = os.path.splitext(path)
return file_extension == extension | 70a808e38972fd7c0e1fb9ca264e705407b72a21 | 633,027 |
def _binary_op(op_func, comps):
""" Return a concatenation of operators `op_func` on each pair
of conditions in `conds`.
"""
if len(comps) == 1:
nuop = comps[0]
elif len(comps) == 2:
nuop = (op_func, comps[0], comps[1])
else:
frst = comps[0]
rest = comps[1:]
... | e8295dd43570ec515543cb1d09aefcb109de6d12 | 633,028 |
def istoken(docgraph, node_id, namespace=None):
"""returns true, iff the given node ID belongs to a token node.
Parameters
----------
node_id : str
the node to be checked
namespace : str or None
If a namespace is given, only look for tokens in the given namespace.
Otherwise,... | 79f4c553ae2918b4295dd443c2bc6e0866b040e7 | 633,029 |
def convert_meV_to_GHz(w):
"""
Convert an energy from unit meV to unit GHz.
Parameters
----------
w : float / array
The energy in the old unit.
Returns
-------
w_new_unit : float / array
The energy in the new unit.
"""
# 1 meV = 1.0/4.1357e-3 GHz
w_GHz = w /... | c75ad5d1112fb36ac8df7b36545d4ccebebfc7b8 | 633,030 |
import pickle
def open_pickle(path):
"""
Shortcut to open a pickle file
Parameters
----------
path : path to a xxxx.pickle file to open
Raises
-------
FileNotFoundError
PermissionError
Returns
-------
object : unserialised python object
Examples
-------
... | 3baebe51b68543988d4e3b787ce0220ffb85b953 | 633,031 |
def is_local_path(path: str) -> bool:
"""
Returns information about start time of an event. Nominally float seconds since the epoch,
but articulated here as being compatible with the format_elapsed function.
"""
if path.startswith("file://"):
return True
if "://" in path:
return ... | ec2c9eb92545918c614be75d0b42417b97def4b2 | 633,032 |
def exactly_one(iterable):
"""Obtain exactly one item from the iterable or raise an exception."""
i = iter(iterable)
try:
item = next(i)
except StopIteration:
raise ValueError("Too few items. Expected exactly one.")
try:
next(i)
except StopIteration:
return item
... | e51b3ac7cbd1d01718263618ff6f629a9830ec60 | 633,033 |
def writeGeneralExpr(val,Type):
"""
format an expression to put into the general section of the iges file; type can
be 'str', 'int' or 'dim'
"""
if Type == 'str':
if len(val) > 0:
return str(len(val))+'H'+val
else:
return ''
elif Type == 'int':
ret... | 33f311ff776fed98541323e17b2235987588c8ac | 633,034 |
def generate_final_vocabulary(reserved_tokens, char_tokens, curr_tokens):
"""Generates final vocab given reserved, single-character, and current tokens.
Args:
reserved_tokens: list of strings (tokens) that must be included in vocab
char_tokens: set of single-character strings
curr_tokens: stri... | 2996958639465aa756864ac88583c77ac313bf69 | 633,035 |
import tempfile
def write_to_text_file(content):
"""
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
Function to write content to a file
:param content:
:return:
"""
if content:
src_file = tempfile.mktemp()
src_fp = open(src_file, "w")
src_fp.write(cont... | b93f6abb0bcbad73628e8773f0e657bb54ac9468 | 633,036 |
def df_to_json(tokenList):
"""Take a list of tokens from df and return a python object."""
# If df's ouput format changes, we'll be in trouble, of course.
# the 0 token is the name of the filesystem
# the 1 token is the size of the filesystem in 1K blocks
# the 2 token is the amount used of the file... | 5073a01dcca9ab9f5e530fb4d8336d5615a5183f | 633,037 |
def _is_comparable_to(self, other):
"""
Check whether `other` is comparable to `self`.
"""
for func in self._requirements:
if not func(self, other):
return False
return True | 8a5bbd03cf166597d7b6ce856447c19af151b65b | 633,039 |
def _strip_markup_line(line, sigil):
"""Strip sigil and whitespace from a line of markup"""
return line.lstrip(sigil).rstrip() | 86daa55bbd2d3cddeed6a14930dab705af57705b | 633,040 |
def check_frame(buff):
"""
returns False if the buffer doesn't starts with a valid frame
returns the size of the frame in success
"""
if len(buff) < 2:
return False
min_size = 2
masked = False
payload_length = 0
if buff[1] & 128:
min_size += 4
masked = True
... | 594e3936706b512fe37a924046f79e6b160c88ca | 633,041 |
def is_prim_rou(modulus: int, degree: int, val: int) -> bool:
"""
Test whether input x is a primitive 2d^th root of unity in the integers modulo q. Does not require q and d to be
NTT-friendly pair.
:param modulus: Input modulus
:type modulus: int
:param degree: Input degree
:type degree: in... | b2d23ad6c580de460bf6e3d59e2c053ffd538892 | 633,042 |
def ordinal( value ):
"""
Converts zero or a *postive* integer (or their string
representations) to an ordinal value.
>>> for i in range(1,13):
... ordinal(i)
...
'1st'
'2nd'
'3rd'
'4th'
'5th'
'6th'
'7th'
'8th'
'9th'
'10th'
'11th'
'12th'
>>> for i in (100, '111', '112',1011):
... ordinal(i)
... | f87c29be42e048df117ee7e8641f6e8188ba9bd4 | 633,043 |
def get_bundle_id(issn_id, year, volume=None, number=None, supplement=None):
"""
Gera Id utilizado na ferramenta de migração
para cadastro do documentsbundle.
"""
items = (
("v", volume),
("n", number),
("s", supplement),
)
label = "-".join([f"{prefix}{value}"... | 85550ded36e8cdf3139c6e24b51dec6a455d6ad8 | 633,044 |
import os
from shutil import copyfile
def create_dummy_read_file(file_dir, dummy_rd_file="\\dummy.fsf", orig_rd_file="\\80cm_WhiteTarget_LT.fsf"):
"""
:param file_dir:
:param orig_rd_file:
:param dummy_rd_file:
:return:
"""
orig_file = file_dir + orig_rd_file
dummy_file = file_dir + d... | 97fa65eae619d0a79ddbc88f4f10324dd7525398 | 633,045 |
def bbox_sanity_check(img, bbox):
"""
This is to confirm that the bounding boxes are within image boundaries.
If this is not the case, modifications is applied.
This is to deal with inconsistencies in the annotation tools
"""
img_width, img_heigth = img.size
if bbox[0] < 0:
bbox[0] =... | 45642a6e5a8e607eeca1802648c52f0fb42020c2 | 633,046 |
def _clean_netloc(netloc):
"""Remove trailing '.' and ':' and tolower.
>>> _clean_netloc('eXample.coM:')
'example.com'
"""
try:
return netloc.rstrip('.:').lower()
except:
return netloc.rstrip('.:').decode('utf-8').lower().encode('utf-8') | d8b00244282a65a933460c6be4a7a9a728df8790 | 633,047 |
import os
def does_paste_exist(paste_id):
"""
This method is called when the Flask application wants to check if a
paste with a given Paste ID exists. The Paste ID is (typically) an
ASCII string and your method must return True if a paste with this ID
exists, or False if it doesn't.
:param pas... | 8b81de219558e9292993d9a99536dda767d61718 | 633,048 |
import os
import yaml
def get_ed_bgs_config():
"""
Get the application config.
:return: yaml config object
"""
__configfile_fd = os.open("ed-bgs_config.yaml", os.O_RDONLY)
__configfile = os.fdopen(__configfile_fd)
return yaml.load(__configfile, Loader=yaml.CLoader) | e0fbb1854c1f4543f4e1758775c077efaf31662b | 633,050 |
import io
import base64
def plot_as_base64(fig, charset='utf-8'):
"""
Convert supplied figure into string buffer and then return as base64-encoded string
(in the specified charset) for insertion into a page as a context attribute
"""
assert fig is not None
with io.BytesIO(bytearray(200*1024)) ... | a5c89c57be1b97e8b3ddd9ae01c984be4aa7fabd | 633,051 |
def dict_median(p):
"""
:param p: a dictionary of lists of votes for candidates
:return: a dictionary conaining only the median value for each candidate
"""
m = {}
for k, v in p.items():
l = sorted(v)
m[k] = l[int(len(l) / 2)]
return m | 867acbfc6f99505aeead60db2593fd9718dd85cb | 633,053 |
def correct_filters(distance, year, citations):
"""If a filter is too big or too small, set it to a default value."""
distance = int(distance)
distance = min(distance, 5)
distance = max(distance, 0)
year = int(year)
citations = int(citations)
citations = max(citations, 1)
return distance... | 755955e2198750dbfcac2e827171ace539a8dafa | 633,054 |
def load_kitti_odom_intrinsics(file_name, new_h, new_w):
"""Load kitti odometry data intrinscis
Args:
file_name (str): txt file path
Returns:
intrinsics (dict): each element contains [cx, cy, fx, fy]
"""
raw_img_h = 370.0
raw_img_w = 1226.0
intrinsics = {}
with open... | bd959fda5bf81bbfd414f77ce9f79bb27fd9c211 | 633,055 |
def build_titles_list(title, args):
"""Build a list of titles from the 'title' option and arguments.
Args:
title: NoneType or unicode Title given to options.title
args: list Leftover arguments on the command line, presumably extra titles.
Returns:
List of strings or [None].
"""
# If args is non... | 5428e56a3a42b5307b7593b21af9a050852aec2a | 633,056 |
def norm(s: str) -> str:
"""Normalize a string for dictionary lookup."""
return s.lower().replace(" ", "").replace("-", "").replace(".", "") | 9c04c2ebc3e3bb28fa4ba569ecffa5b407abf5a4 | 633,058 |
def make_pipeline(*steps):
"""Create a pipeline from estimators of any type.
Parameters
----------
steps : tuple of sktime estimators
in same order as used for pipeline construction
Returns
-------
pipe : sktime pipeline containing steps, in order
always a descendant of Bas... | b30c16bc28b01f96d2965385808d4d861b9ad4c2 | 633,059 |
def dig_pow(n, p):
"""
Some numbers have funny properties. For example:
89 --> 8¹ + 9² = 89 * 1
695 --> 6² + 9³ + 5⁴= 1390 = 695 * 2
46288 --> 4³ + 6⁴+ 2⁵ + 8⁶ + 8⁷ = 2360688 = 46288 * 51
Given a positive integer n written as abcd... (a, b, c, d... being digits) and a positive integer p
we w... | 75ce21dd0dac71a414cfe992dd83f96e38dc8dbb | 633,060 |
def primary_spherical(rho, phi):
"""Zernike primary Spherical."""
return 6 * rho**4 - 6 * rho**2 + 1 | 2c5c545dd644a45922850d5509785763b16535e2 | 633,061 |
import math
def _quadratic_interpolate(x1, y1, x2, y2, target_y):
"""
Computes the x value for which a quadratic function hitting x1,y1 and
x2,y2 would have a y value of target_y.
We use this because we expect the count near the centroids to be
proportional to the square of the radius, though the... | 08f1d0a0af2199889eb69780874ac6101336eab8 | 633,062 |
from typing import List
from typing import Dict
def one_hot_string_encoding(labels: List[List[str]],
mapping: Dict[str, int]) -> List[List[List[int]]]:
"""Converts string labels into one hot encodings."""
one_hot_labels = []
for dialog in labels:
one_hot_labels.append([])
fo... | 5c251475feb67bc02b61fdfb04e554c488d54033 | 633,063 |
def _get_boundary_date_string(date_sr, boundary, date_format='%Y-%m-%d'):
"""
Returns the first or last date of the series date_sr based on the
value passed in boundary.
date_sr: Series consisting of date
boundary: Allowed values are 'first' or 'last'
date_format: Format to be used for co... | 93ac0f29259e92411d9cd3f21a546394bf2924c6 | 633,064 |
def norm_random(random_number):
"""Turn a random number to a number between 0 and max_value """
precision = 20
res = 0.
for i in range(precision):
bit = random_number & (1 << i)
res += bit
res %= precision
res /= precision
return res | ea394f3bc7f7b60f4b1b5024a00facb7caa4ee38 | 633,065 |
def detach_nic(fco_api, server_uuid, nic_uuid):
"""
Detach NIC from server
:param fco_api: FCO API object
:param server_uuid: Server UUID
:param nic_uuid: NIC UUID
:return: Job-compatible object
"""
return fco_api.detachNic(serverUUID=server_uuid,
networkInt... | e48ee62e0f215db014e90b7d9178299330146778 | 633,068 |
import os
import re
def env_expand(path):
""" substitute occurences of $VAR or ${VAR} in path """
def envmatch(m):
return os.getenv(m.group(1) or m.group(2)) or ""
return re.sub(r'\$(?:{(\w+)}|(\w+))', envmatch, path) | 405a19f77f05a52647b74b767601091f043291fb | 633,069 |
def parseIfcfg(ifconfig):
"""
Parses the ifconfig in an array if info
:param iostat
:return: array of dict
"""
data = []
for nic,stat in ifconfig.items():
data.append({
nic: {
"bytes_sent": stat.bytes_sent,
"bytes_recv": stat.bytes_recv,
... | e53b02ff292ef276cfc60155a673b3c6948533f0 | 633,070 |
import torch
def get_rays_shapenet(hwf, poses):
"""
shapenet camera intrinsics are defined by H, W and focal.
this function can handle multiple camera poses at a time.
Args:
hwf (3,): H, W, focal
poses (N, 4, 4): pose for N number of images
Returns:
rays_o (N, H, W... | 2e3c25b819753e8e482da49bb33c4d4247a0284a | 633,071 |
from typing import List
import os
def _determine_local_import_names(start_dir: str) -> List[str]:
"""Determines all import names that should be considered "local".
This is used when running the linter to insure that import order is
properly checked.
"""
file_ext_pairs = [os.path.splitext(path) for... | d186c97dfae945c01701e07e7e814948d34fdebe | 633,073 |
import torch
def get_random_index(x: torch.Tensor) -> torch.Tensor:
"""Given a tensor it compute random indices between 0 and the number of the first dimension
:param x: Tensor used to get the number of rows
"""
batch_size = x.size()[0]
index = torch.randperm(batch_size)
return index | 088b5498f9fbf85802af19e72d23ca519f7e15d3 | 633,074 |
def repeat(num):
"""
repeat
:param num:
:return:
"""
def my_decorator(func):
"""
my decorator
:param func:
:return:
"""
def wrapper(*args, **kwargs):
"""
wrapper
:param args:
:param kwargs:
... | 0eacc740a42c8c54c847f6d9585ffb97d131f00a | 633,075 |
def instance_attributes(inst):
"""Given an instance, lists the name of all public non-callable members.
Attributes:
inst (obj): The instance of the object.
"""
return [n for n in dir(inst)
if not n.startswith('_')
and not callable(getattr(inst, n))] | 1daa5e34800276c314e9cc1dc8bcf2da2ba0a02f | 633,076 |
def calc_shield_power(block_count, active=False):
""" Calculate the power usage of Shield Rechargers
Given the number of Shield Rechargers, this function will calculate how
much power they draw in 'e/sec'. It will calculate both inactive
(shields full) and active (shields charging) power consumption b... | 60df874717b7d8e2e2dfc07b534f24025220e2b3 | 633,077 |
def type_to_class_string(type):
"""
Takes a ROS msg type and turns it into a Python module and class name.
E.g
>>> type_to_class_string("geometry_msgs/Pose")
geometry_msgs.msg._Pose.Pose
:Args:
| type (str): The ROS message type to return class string
:Returns:
| str: A py... | bcfbaa72c4709c735112977d413430acf3f90fdb | 633,078 |
def dfs(reactions, chemical, seen):
"""DFS to traverse all reaction requirements for chemical."""
seen.add(chemical)
if chemical == 'ORE':
return []
order = []
_, needed_chemicals = reactions[chemical]
for next_chemical, _ in needed_chemicals.items():
if next_chemical not in seen... | e9d5720d05fa5a1677d2e02758c26a13422a96ac | 633,079 |
def get_survey_local_time_dayofweek(dt):
"""Get day of week when survey was taken."""
try:
weekday = dt.weekday()
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
return weekdays[weekday]
except:
return None | 4ee97430f9ef3b87783985a574fbe74dab617f28 | 633,080 |
def sort_links(links):
"""Sorts endpoint links alphabetically by their href"""
return sorted(links, key=lambda link: link["href"]) | e20ac056cb341f1d8600b4c642812c7446d672a5 | 633,081 |
def convertBytes(nbytes):
"""Convert a size in bytes to a string."""
if nbytes >= 1e9:
return '{:.1f} GB'.format(nbytes / 1e9)
elif nbytes >= 1e6:
return '{:.1f} MB'.format(nbytes / 1e6)
elif nbytes >= 1e3:
return '{:.1f} KB'.format(nbytes / 1e3)
else:
return '{:.1f} ... | 34308e7bbdc4a6cb3753715ba9a0320d3979b27f | 633,082 |
import os
import subprocess
def _run_subprocess_ignore_stderr(command):
""" Return subprocess.check_output with the given command and ignores stderr."""
with open(os.devnull, "w") as devnull:
output = subprocess.check_output(command, stderr=devnull)
return output | 4f69f4297c143b63a4f969f00b62ee593f6117a5 | 633,083 |
from six import string_types
import logging
def log_level(level):
"""
Attempt to convert the given argument into a log level.
Log levels are represented as integers, where higher values are more
severe. If the given level is already an integer, it is simply returned.
If the given level is a s... | 53d0bc6057d50a8ad1ea2779114b33a586d91d33 | 633,084 |
def model_receptive_fields(model, input_dim):
"""Find receptive fields for units in different layers of the model.
Works only with the padding 'valid' (no padding) or padding 'same', when stride = 1"""
cum_rf = {}
last_rf = 1
for l in model.get_config():
l_type = l['class_name']
... | 470ebdb365e2dea8c976995ed30b00a5c781a749 | 633,085 |
def insert_instr(qobj, exp_index, item, pos):
"""Insert a QasmQobjInstruction into a QobjExperiment.
Args:
qobj (Qobj): a Qobj object
exp_index (int): The index of the experiment in the qobj.
instruction(QasmQobjInstruction): instruction to insert.
pos (int): the position to ins... | e26d4fe3b32ebdd890ce2b1bd99f86ce8686d063 | 633,086 |
def __points_to_dict(points):
"""transform list of [x, y] into a dict() where {x: y}"""
return {p[0]: p[1] for p in points} | 83c7445e1c4c2c034f609f19da0d9638b3d9dbf3 | 633,087 |
import argparse
def _parse_arguments():
"""
Parse the command line arguments.
:return: the parsed arguments
"""
parser = argparse.ArgumentParser()
parser.add_argument("-a", "--append",
help="Append to the file rather than overwrite it.",
action... | 3d86a1ab3ec67b74e660eecf09bfd99a50e8cdad | 633,088 |
from datetime import datetime
def utc_now():
"""
Get current datetime in UTC, without time zone info.
"""
return datetime.utcnow() | 7a88038af7319ed79b71bcc88c6820c923883ed6 | 633,089 |
import sys
def get_calls():
"""helper function to parameterize the rate limit decorator with platform specific API
rate limit value unless it recognizes that we are in a test environment, then rate
limit value is set to an artificially high value."""
if "pytest" in sys.modules:
# in testing, ... | 7eba4a8ecfa9bca2d9a0e04ea559d98b44ed1546 | 633,090 |
import time
from datetime import datetime
def getOffset():
"""Determines hours between local time and UTC as a timezone offset"""
ts = time.time()
utc_offset = (datetime.fromtimestamp(ts) -
datetime.utcfromtimestamp(ts)).total_seconds()
offset = str(round(utc_offset / 3600)) + ':00'
return ... | 85434ea8ff09fa6fa9d12143cc2bdf957aea6421 | 633,091 |
import hashlib
def CalculateSha256Checksum(filename):
"""Calculate the sha256 checksum for filename."""
sha = hashlib.sha256()
with open(filename, 'rb') as f:
data = f.read(65536)
while len(data) > 0:
sha.update(data)
data = f.read(65536)
return sha.hexdigest() | f3f353cb05c74e6b78285153a29a86eb56c87a58 | 633,092 |
def escapeBelString(belstring):
"""Escape double quotes in BEL string"""
return belstring.replace('"', '\\"') | ef2efa04cd356dd17d44f1a2f0b9f518d7c13170 | 633,093 |
def first_and_last(sequence):
"""Returns the first and last elements of a sequence"""
return sequence[0], sequence[-1] | 6aae9364559f3f9b892f9aa66c1e9e368997fb65 | 633,094 |
import logging
def create_logger(bot, chat_id):
""" Sends formatted logs to Telegram Bot."""
class LoggerTelegramBot(logging.Handler):
def emit(self, record):
log_entry = self.format(record)
bot.send_message(
chat_id=chat_id,
text=log_entry,
... | 79ab4bded2955fe8c170d0c8f7666a9df725b3d7 | 633,095 |
from collections import Counter
def gen_idx_byclass(labels):
"""
Neatly organize indices of labeled samples by their classes.
Parameters
----------
labels : list
Note that labels should be a simple Python list instead of a tensor.
Returns
-------
idx_byclass : dictionary {[cl... | c5969a62fc9f503df32fbbec8861cc34f9782a74 | 633,097 |
def derivar(coeficientes):
"""
coeficientes: Lista de los coeficientes del polinomio,
comenzando por el término independiente.
"""
d_coeficientes = []
# Deriva cada término y coloca el
# coeficiente en la lista d_coeficientes
for i in range(1, len(coeficientes)):
d_coefic... | 6ccdf840ddb7f331082684bd86de17531b9b921a | 633,098 |
def multiplica(x, y=2.0):
"""Multiplica dos números, por defecto el primero por 2."""
return x * y | 51d8243d80e90d97da284895f02b73884b67b341 | 633,099 |
def get_floor(directions):
"""
Get the floor for Santa.
Parameters
----------
directions : str
A string of parentheses representing directions. An opening parenthesis,
(, means he should go up one floor, and a closing parenthesis, ), means
he should go down one floor.
R... | f6ab8d6d2fb134a71a5a1a06db14073327a5eb58 | 633,100 |
def qvar2int(qvar):
"""Convert Py2 + Qt4 QVariant to an int"""
try:
return qvar.toInt()[0] # Py2 + Qt4
except AttributeError:
return qvar | 2a39ac5b34dffb62790eded64fdb31651a43a81c | 633,101 |
def get_randaug(aug: str) -> str:
"""Returns a string representing the RandAugment op to use during preprocessing."""
l, m = {
'light0': (2, 0),
'light1': (2, 10),
'medium1': (2, 15),
'medium2': (2, 15),
'strong1': (2, 20),
'strong2': (2, 20),
'extreme1': (4, 15),
'ex... | 5177e0a92b5ca5ba089647d1f12a916badffb0b8 | 633,102 |
import re
def separate_latex_anchors(markdown_content):
"""Fixes an LaTeX error caused by having one empty \anchor
Fixes an LaTeX error caused by having one \anchor followed inmediatly by
other (without content in the middle)"""
return re.sub(
r'\\anchor{(.*?)}\n\\anchor',
r'\\anchor... | 2976ef4112fb3b8f9fb0a91f7b5c5e6c4f742c2f | 633,103 |
from typing import List
def pad_zeros(data: List[int], num_elem: int) -> List[int]:
"""
pads array so output is num_elem is length
"""
if len(data) >= num_elem:
return data[:-num_elem]
data.extend([0] * (num_elem - len(data)))
return data | 2d988dc9dae8d54804bc85fc80582667e922690a | 633,104 |
def format_dict(data, key_lst):
"""转换返回dict中的可重复字段为list"""
if not (isinstance(data, dict) and isinstance(key_lst, list)):
return data
for key in key_lst:
# 将dict转为list,保持一致
if key in data and isinstance(data[key], dict):
lst = []
lst.append(data[key])
... | 618c1657ac104c09a17a31c050da397f8b4c5115 | 633,105 |
def get_app_type(PlatformType):
"""To Define the platform type for your app"""
switcher = {
PlatformType.ios: 'iOS',
PlatformType.android: 'Android'
}
app_type = switcher.get(PlatformType, 'Invalid environment option, or not yet implemented')
return app_type | 1c8885242f4258155322f301235320976778b0be | 633,106 |
import torch
def rotz_batch_pytorch(t):
"""
Rotation about z-axis
:param t:
:return:
"""
input_shape = t.shape
output = torch.zeros(tuple(list(input_shape) + [3, 3])).cuda()
c = torch.cos(t)
s = torch.sin(t)
# Transposed rotation matrix for x'A' = (Ax)'
# [[cos(t), -sin(t),... | c31d5e2718182d7a19c5bf1023514cd850455f86 | 633,107 |
import hashlib
def compare_hash(file_a: str, file_b: str) -> bool:
"""Compute and compare the hashes of two files"""
print("Comparing: ")
print(" File_A: "+file_a)
print(" File_B: "+file_b)
file_a_hash = hashlib.sha256(open(file_a, 'rb').read()).digest()
file_b_hash = hashlib.sha... | dad85b423ba59a823ccc656cf50e9c586deeb793 | 633,108 |
import re
def expand_sharded_pattern(file_pattern: str) -> str:
"""Expand shards in the given pattern for filenames like base@shards.
For example, '/path/to/basename@3' to expand to
'/path/to/basename-00000-of-00003'
'/path/to/basename-00001-of-00003'
'/path/to/basename-00002-of-00003'
Args:
f... | d2f1b2638d26889b059e225d9e64c395242184a0 | 633,111 |
import math
def _get_beta(steering_angle: float, wheel_base: float) -> float:
"""
Computes beta, the angle from rear axle to COG at instantaneous center of rotation
:param [rad] steering_angle: steering angle of the car
:param [m] wheel_base: distance between the axles
:return: [rad] Value of beta... | 16a8fbbe2b7f03e78dde168fafd914c7c4cc1d7f | 633,112 |
def get_stddev(d):
"""
Returns class variance and size variance across sites.
"""
classes = d.shape[0]
sites = d.shape[1]
s = d.sum()
d = d / s
cs = d.sum(axis=0)
cv = d.std(axis=0)
std1 = cv.sum() * classes
std2 = cs.var() * sites * sites / (sites - 1) if sites > 1 else 0
... | e72f1843265d5d9dfe84fe46a8d6b740abe22809 | 633,113 |
def three_to_one_gates_and_measurement_bob(q1, q2, q3):
"""
Performs the gates and measurements for Bob's side of the 3->1 protocol
:param q1: Bob's qubit from the first entangled pair
:param q2: Bob's qubit from the second entangled pair
:param q3: Bob's qubit from the third entangled pair
:ret... | ae318c4ef196aeb1392aea05e2de9d25f45aa672 | 633,115 |
def count_word(user, words):
"""Counts substrings of words in user profile and can get maximum +1 count for each community"""
counter = 0
# 1 - female, 2 - male
if 'sex' in user:
if user['sex'] == 1 and 'мужчин' in words:
return 0
elif user['sex'] == 2 and\
l... | 80c201fa983623fdeebdb4f77a518d4ae5f73208 | 633,116 |
import smtplib
def smtp_connection(c):
"""Create an SMTP connection from a Config object"""
if c.smtp_ssl:
klass = smtplib.SMTP_SSL
else:
klass = smtplib.SMTP
conn = klass(c.smtp_host, c.smtp_port, timeout=c.smtp_timeout)
if not c.smtp_ssl:
conn.ehlo()
conn.starttls... | db57f751cb25683222e6fd621ec02e7b05bc598e | 633,117 |
def len(object):
"""Return the number of items of a sequence or mapping.
:type object: collections.Sized
:rtype: int
"""
return 0 | 9d4d097e9ab05a0b774d48ea08dbfb892be56562 | 633,118 |
def config_loader_mock_no_creds(config_key):
"""Return mocked config values."""
if config_key == "energy_recorder.api_url":
return "http://pod-uri:8888"
elif config_key == "energy_recorder.api_user":
return ""
elif config_key == "energy_recorder.api_password":
return ""
else:... | cba5bdef266ea267f35c195b66defd0fa557a512 | 633,120 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.