content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _position_is_empty_in_board(position, board):
"""
Checks if given position is empty ("-") in the board.
:param position: Two-elements tuple representing a
position in the board. Example: (0, 1)
:param board: Game board.
Returns True if given position is empty, False otherw... | dda9166588cdeaf81f5c17c57bedc81b856a0ce5 | 601,821 |
def code_replace(temp_line):
""" Replace some special cases in code segment or inline code
Note that in HTML if we keep use < or >, then if we meet js code
then the browser will consider it as js code for the html page.
Therefore, we need to replace < and >.
Moreover, if we have space/tab in the... | 3c081a5477e286167ce3619c308e71477ecf81f2 | 601,822 |
def _labelled(obj):
"""
Returns labelled element of the object (extractor or labelled region)
"""
if hasattr(obj, "annotation"):
return obj.annotation
return obj | 379c84a41a9f5a44e2afe94adfe5579f783361f3 | 601,823 |
def is_anonymous(request):
"""
Returns True if request.user is not authenticated else returns False
"""
return not request.user.is_authenticated | 42add0b288342ced0e44e126946da16751871af3 | 601,824 |
def humanize_join(sequence, separator=',', spacing=' ',
conjunction='or', oxford_comma=True):
"""
Join a list together using the English syntax of inserting a
conjunction before the last item.
Keyword Arguments:
sequence -- The sequence to join together. Convert iterables to sequences
... | 29d6812d6bb4e914f6e5fc0797235ae0a06d62e9 | 601,825 |
def compute_loss_packet_count(overall_packets, lost_packets):
"""
Compute loss percentage based on the number of lost packets and the number of overal packets.
"""
if overall_packets != 0:
loss = (lost_packets / overall_packets)*100
else:
return 100
return loss if loss >=0 else... | c668ce6c7ee6807e2e10ff4eefa66aa866b3427a | 601,833 |
from typing import Iterable
from typing import Any
from typing import List
def init(it: Iterable[Any]) -> List[Any]:
"""
Get all but end of iterable object
Args:
it: Iterable object
Examples:
>>> fpsm.init([1, 2, 3])
[1, 2]
>>> fpsm,init(range(5))
[0, 1, 2, 3]... | f8fe0a1de2f23e4bcd8f02e81d7449f36c2452bd | 601,852 |
def search_for_attr_value(obj_list, attr, value):
"""
Finds the first (not necesarilly the only) object in a list, where its
attribute 'attr' is equal to 'value', returns None if none is found.
"""
return next((obj for obj in obj_list if getattr(obj,attr, None) == value), None) | 2e92b69d253158747194cbd9d9415df9078ffc4c | 601,853 |
def check_user(user, soup_object):
"""
To check if user exists in the table in the soup object
:param user: (string) name of user
:param soup_object: (object) soup object that contains table
:return: True if user is found in table, False if not found in table
"""
if user in soup_object.fin... | f15a1bd6506f30d32e6a37b245086bd30751ec7c | 601,862 |
import torch
def get_ang(a, b, c):
"""calculate planar angles for all consecutive triples (a[i],b[i],c[i])
from Cartesian coordinates of three sets of atoms a,b,c
Parameters
----------
a,b,c : pytorch tensors of shape [batch,nres,3]
store Cartesian coordinates of three sets of atoms
... | 6b442444a1dcddc242df7991a2260fc3d98709d8 | 601,863 |
def coding_problem_47(prices):
"""
Given a array of numbers representing the stock prices of a company in chronological order, write a function that
calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you
can sell it. For example, given [9, 11, ... | c2a844dd2e0404000a405f415a1ed585c687cce6 | 601,866 |
import struct
def py_int2signed_word(val, be=False):
"""
Converts Python int value to word of bytes.
"""
sig = '>h' if be else '<h'
return struct.pack(sig, val) | 5ebf82c3e151c31098604619d0e549214d27f486 | 601,871 |
import requests
def extra_metadata_helper(json_content, headers):
"""
Build extra metadata dict to help with other integrations.
Parameters
----------
json_content: dict
Information about the GitLab repo
headers: dict
GitLab Authorization header
Returns
-------
... | cf1e7d82b127cebf752a603b24e9d42b07f18713 | 601,876 |
def float_dist(id1, id2):
"""
Compute distance between two identities for NumPyDB.
Assumption: id1 and id2 are real numbers (but always sent
as strings).
This function is typically used when time values are
used as identifiers.
"""
return abs(float(id1) - float(id2)) | c40c7956291afcb8ffe151496c289dad6828b9b1 | 601,877 |
def get_neighbors(position, grid_dimension):
""" Given a position (row index, col index) and the length of a side of the grid, return
a list of tuples representing the grid coordinates for the horizonal and vertical neighbors
"""
neighbors = []
if position[0] > 0:
neighbors.append((position[... | f372f3a809c1d24525fea210c82d10cec7bdbdeb | 601,878 |
import re
def parse_fasta_to_dict(fasta):
"""Parse a fasta file into a dictionary of name -> sequence"""
if not fasta.startswith('>'):
raise ValueError("Input did not start with '>', not a valid Fasta file")
result = {}
for block in fasta.split(">"):
block = block.strip()
if b... | a71df2f304ba4d232434cecde58e7b622786d815 | 601,880 |
def all_key_seqs(template):
"""Returns a list of all valid key paths from a template."""
result = []
for k, v in template.iteritems():
if isinstance(v, dict):
for suffix in all_key_seqs(v):
result.append([k] + suffix)
else:
result.append([k])
return result | a17322dfe8b3b2378cee60ff08193f1b5a95b351 | 601,881 |
from typing import Optional
import inspect
def calling_function(skip=2) -> Optional[str]:
"""
Returns the name of the function which called your function/method.
Example::
>>> def x(skip=2): return calling_function(skip=2)
>>>
>>> def y(skip=2): return x(skip)
... | 92c5ab0d87781d869fff101c196e56748590762d | 601,882 |
def filterTheDict(dictObj, callback): # DGTEMP - Not useful anymore
""" Function copied from https://thispointer.com/python-filter-a-dictionary-by-conditions-on-keys-or-values/
Iterate over all the key value pairs in dictionary and call the given
callback function() on each pair. Items for which callback()... | 3c35ee2dcf998c8dbecb47b759eecdbbc90e832a | 601,884 |
def load(filename):
""" Read a Java properties file into a Dictionary """
props = {}
file = open(filename, 'r')
for line in file.readlines():
line = line.strip()
if (len(line) == 0 or line[0] == "#"): continue
pair = line.split('=')
if len(pair) < 2: continue # hack until I support \ line conti... | a6ea02d5a361186a12320a54dd6f17a3e20e9ae4 | 601,886 |
def plot_contour(ax, *args, **kwargs):
"""Contour lines with fill color and sharp edges."""
ax.contour(*args, **kwargs)
return ax.contourf(*args, **kwargs) | e71bf71700d2856d25a91775d45aff992e2967d7 | 601,891 |
import json
def simple_scenario_analysis_input() -> dict:
"""
Fixture for getting the scenario analysis input used for tests from a file.
- Complexity: simple
"""
with open('tests/assets/simple/jaamsim_scenario_analysis_input.json') as scenario_file:
scenario_analysis_input = json... | f8143f8c717df32bb69f4cd94b3751ae9e68ab19 | 601,893 |
def get_event_distirb(data_ob, object_ids=None):
"""
returns a dictionary showing the distribution of objects among various types.
Parameters
----------
data_ob: Data.Data
Data object with the light curve data
object_ids: list of ids among which distribution is to be searched for. if le... | 7d102048ced6677ce43014d701008697315c8170 | 601,894 |
def bubble_sort(arr):
"""
Passes over a list comparing two elements and repeats with a smaller,
sliced off end of the list each iteration until sorted.
"""
for i in range(len(arr)):
for j in range(len(arr) - i - 1):
# swap if left element is greater than right element
... | ec4351cbf497623c60e283a3de0f9f29f3b20320 | 601,895 |
def wrap_angle(x):
"""Wraps an angle between 0 and 360 degrees
Args:
x: the angle to wrap
Returns:
a new angle on the interval [0, 360]
"""
if x < 0:
x = 360 - x
elif x > 360:
x = x - 360
return x | 011c21fb4354ce9462196da6a0c971d9c5f83dc7 | 601,899 |
def sdf_supported_property_non_string(property_name):
"""
Check to verify that this property is support natively in SDF
(without modification)
:param property_name name to check
:return: boolean true/false
"""
supportedProperties = ["minimum",
"maximum", "uniqueIte... | ccc8108dbcc1eb5cb665050b1a5874fcc2ec7b3a | 601,900 |
def str2fiware(string: str):
"""
Fiware does not support all characters.
Converting provided string according to Fiware specifications. The mapping
for character replacement can be provided as dict. If no mapping is
provided the default library mapping will be used. For list of forbidden
charact... | 35af6ff4bcd6a9e7382f5732eeed45d6f959213b | 601,903 |
def get_topological_order(G):
"""
Use BFS to find the order of variables in a network.
Parameters
----------
G : Network (see network.py)
The Bayesian network for which to calculate the order.
Returns
-------
list of int
Features as node ID's (see network.py)
Topo... | bef146a8d2794b8694f562a1f1bac4375eae04a0 | 601,904 |
def GeneralizedLorentz1D(x, x_0=1., fwhm=1., value=1., power_coeff=1.):
"""
Generalized Lorentzian function,
implemented using astropy.modeling.models custom model
Parameters
----------
x: numpy.ndarray
non-zero frequencies
x_0 : float
peak central frequency
fwhm : flo... | 45d6e4711af4fad63d13710ebeb43b225b881f88 | 601,907 |
def parameters_to_tensor_groups(parameter_groups, attribute):
""" Function to reduce a parameter group from an optimizer to tensor_group with
the same structure and just the requested parameter
:param parameter_groups: The parameter group to extract from
:param attribute: The attribute from the paramete... | e3718b6990aa113ae28426581bdf96eb4b958d27 | 601,910 |
def decode_mac_address(encoded_mac_address):
""" Returns a readable MAC Address. """
return ":".join(["{:02x}".format(ch) for ch in encoded_mac_address]) | 941b4dcf96026f17c898d717950ba71e8a9c05c0 | 601,911 |
def safe_issubclass(cls, classinfo) -> bool:
"""Check if the input type is a subclass of the given class.
Args:
cls (type): input type.
classinfo (type): parent class.
Returns:
bool: True if the input type is a subclass of the given class
"""
try:
r = issubclass(cls... | 43cbad292cc00edd4b323d19d75f520b3bef47d4 | 601,914 |
def normalize_price(price: str) -> float:
"""Normalizes USD price with thousand separator into float value"""
return float(price.strip().replace(',', '')) | 56d14d05ab7ef4490f4ec96b65f300558bc0cd4a | 601,919 |
def num2rgb(color):
"""Convert a color value into r,b,g colors in the range 0−1.
The input is an integer that is clamped to the range 0−0xFFFFFF.
This is then separated in red, green and blue components.
Arguments:
color: integer color value.
Returns:
(r, g, b) tuple where each co... | ebcd2d7467f45fefd9514c8786f92e6bbc0333d4 | 601,922 |
def get_extension(file):
"""
Return the Extension of a filename
"""
return file.split('.')[-1] | dfbc1159210c1be5440d9270d70b251112fd56c0 | 601,923 |
from typing import Optional
from typing import Union
def _get_module_config(module: Optional[Union[str, dict]]) -> list:
"""
Get an WCS module configuration format.
Parameters
----------
module : Optional[str, dict]
The module information from which to construct the module configuration.
... | 18f541e7d3a4a7c87b2216a4fdb3559158dfc705 | 601,927 |
import inspect
import importlib
def calling_module(n=1):
"""Get the module calling, if available.
As a fallback, this will import a module using the calling frame's
globals value of `__name__`.
Args:
n (int): The number of levels up the stack from this function call.
The default ... | 3d6450a9f99e5115f80e5de462a270e2f4d01e5f | 601,929 |
def nt_pos_shift(nt_pos, AAshift):
"""
Modify nucleotide positions in our alignment to actual positions in the real wild-type sequence.
nt_pos : base number of wild type sequence start at 1, not python 0
AAshift : the residue corresponding to the wild type base starting at 1
"""
if (nt_pos < 1):
raise Excep... | ab1b031007777092a291b4232bb5b3b495271096 | 601,933 |
def list_objects(s3_resource, bucket, prefix, suffix=None):
"""
Get list of keys in an S3 bucket, filtering by prefix and suffix. Function
developed by Kaixi Zhang as part of AWS_S3 class and adapted slightly here.
This function retrieves all matching objects, and is not subject to the 1000
item lim... | 08185bfa888a4633911d163812d1bc4cb4127694 | 601,936 |
import string
import random
def random_text(length, alph=string.ascii_letters + string.digits):
""" Random text generator. NOT crypto safe.
Generates random text with specified length and alphabet.
"""
return ''.join(random.choice(alph) for _ in range(length)) | 469e60c3910d34656876e172f7249f99692a40e7 | 601,938 |
import re
def sanitize(in_str: str) -> str:
"""
Remove whitespace from string and fix some characters
:param in_str: input string
:return: processed string
"""
whitespace_rem = re.sub(r"\n+", "\n", in_str.replace("\r", "").strip())
quote_san = re.sub(u"\u2018|\u2019", "'", whitespace_rem)... | d0a1b623ed2e022012bbbd1495d24e6635ae517b | 601,943 |
from datetime import datetime
def days_from_date(job_date):
"""Returns the time in days between today's date and the date of the job posting"""
current_date = datetime.today()
time_difference = current_date - job_date
number_of_days = time_difference.days
return number_of_days | 15e761f97894a4f96f2530946c08eabf951a1fe5 | 601,944 |
def _normalize_url(url):
"""Remove fragment from an URL"""
return url.split('#', 1)[0] | eba3741204f89ed44ea041453bcfafa886d4ae2f | 601,947 |
def zone_aux_type_english(raw_table, base_index):
""" Convert zone aux type to English """
value = raw_table[base_index]
if value == 0:
return "NA"
if value == 1:
return "NA"
if value == 2:
return "NA"
if value == 3:
return "DHW loop"
if value == 4:
r... | a7227dcdc6221f1cf8c89f9ce16b4393a47f65d7 | 601,948 |
def get_file_extension(path):
"""returns the file extension of path"""
if "." not in path:
return ""
else:
return path.split(".")[-1].lower() | 0e4f4fa9ed2f44260a734c46e819a6db88f8ac54 | 601,950 |
def schomate(T):
"""
Shchomate equation to calculate specific heat of water vapor for a given temperature T.
:param T: Temperature [K]
:return: Heat Capacity [J/mol*K]
"""
t = T / 1000
if 500 <= T < 1700:
a, b, c, d, e = [30.092, 6.832514, 6.793425, -2.53448, 0.082139]
elif T == 1700:
return 2.7175
elif 17... | f93951cd3582f1d4010a44fb1255bf4140a958b3 | 601,954 |
def _isInt(argstr):
""" Returns True if and only if the given string represents an integer. """
try:
int(argstr, 0) # hex values must have the "0x" prefix for this to work
return True
except (ValueError, TypeError):
return False | 6ec4bfd37b59b28317433fedcd68967193f47b3c | 601,956 |
def indentedCode(codes, count):
"""Indent code, used for generating test codes."""
return "\n".join(" " * count + line if line else "" for line in codes) | ee9142368c5c1d73d51db7190fc1c009a96275ea | 601,958 |
def listify(initial):
"""
Takes a string separated by commas, and breaks each component
separated by commas into its own element in a list. Then, it
returns the list as float elements. Also gets rid of alternating zero pattern.
Return: listified version of initial
Prec... | 9d383b4eb503f002de7d576a2e47ea01a08fdf05 | 601,969 |
import re
def sentencecase(sentence):
"""returns a sentence in sentencecase but with text in braces preserved
Parameters
----------
sentence: str
The sentence
Returns
-------
The sentence in sentence-case (but preserving any text wrapped in braces)
Notes
-----
tbd o... | eaf3c7cd763f43b6e2281b962b5023d84fb39ce0 | 601,973 |
import logging
def prepare_logger(level):
"""Configure logging for the module."""
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
datefmt='%Y/%m/%d %H:%M:%S',
fmt='%(asctime)s %(levelname)-5s %(message)s'))
bot_logger = logging.getLogger(__package__)
praw... | ce63a1819530d3d1b0e0e6dd6248df762e421832 | 601,975 |
import torch
def unit_to_midi(unit, midi_min, midi_max = 90.0, clip = False):
"""Map the unit interval [0, 1] to MIDI notes."""
unit = torch.clamp(unit, 0.0, 1.0) if clip else unit
return midi_min + (midi_max - midi_min) * unit | 1525f95e18206041b73cf5a4cf00745fb3a7e241 | 601,976 |
import click
def option(*args, **kwargs):
"""
`hml.option` is a cheap wrapper of `click.option` just so that all
the decorators can be prefixed with the same name
"""
def _register(func):
return click.option(*args, **kwargs)(func)
return _register | 48b9e4e2cd306bb4ee00d69fc951509fd2127952 | 601,977 |
def get_color(idx):
"""Gets a defined hex color from the list below, in order to associate
a user within the timesheet calender for better readability.
"""
colors = [
'#FFCF7F', '#7FFF7F',
'#BFBFBF', '#FF9F7F',
'#7FE9FF', '#7F88FF',
'#E57FFF', '#FF7F94',
'#FF7FD0'... | 9478bbb01382267e5c5e6a7281c6c6f6fca7bbb7 | 601,979 |
def group_and_count_by_status(all_data):
"""
Group by programme code and registration status and then
count how many of each combination there are
"""
grouped = all_data.groupby(['Prog Code', 'Dec/', 'App Cat']).size()
grouped = grouped.sort_index()
return grouped | 45ae525a66ea696a2e0605df7ac3c9a8e7eb7311 | 601,981 |
def on_palm(sim):
""" Determines if the cube is on the palm of the hand."""
sim.forward()
cube_middle_idx = sim.model.site_name2id("cube:center")
cube_middle_pos = sim.data.site_xpos[cube_middle_idx]
is_on_palm = cube_middle_pos[2] > 0.04
return is_on_palm | 7ae4b6996cd22ac733be2e7f650ebfa63081e3e5 | 601,982 |
def parse_title(lines):
"""Parse optional book title."""
TITLE_PREFIX = '# '
book_title = None
if lines[0].startswith(TITLE_PREFIX):
book_title = lines.pop(0)[len(TITLE_PREFIX):].strip()
return book_title | 9f25f7fb5be621d068ddc73bda2432daf5c63a84 | 601,984 |
def set_name_callsign(icao: str, reg=None, craft_type=None, flight=None, known_craft={}):
"""
Sets the Name and Callsign of the CoT Event.
Populates the fields with ICAO, Reg, Craft Type and Flight data, if available.
"""
name: str = known_craft.get("CALLSIGN")
if name:
callsign = name
... | 961a2761e6e71859dfc259ea74e7185ebb29ade2 | 601,987 |
import operator
def which_button(btn_dict):
"""
Assesses which button was pressed given the time
each button was pressed at. It finds the latest
pressed button and returns the key for it.
Parameters
----------
btn_dict : dict
an input dict in the form of {'button name': float(n_cl... | 7149ff373b6db372b498829deb7b89cee9b7a58f | 601,989 |
import pprint
def get_storage_locations_to_compare(possible_storage_locations):
"""This function will ask the user for the storage locations to compare and output them in a tuple."""
storage_location1 = None
storage_location2 = None
print("The possible storage locations are: ")
pprint.pprint(pos... | 15602ef2688f07365efadfcd2ae7782859f4b785 | 601,990 |
import re
def _find_embedded_brackets(string, in_char, out_char):
"""
Finds the substring surrounded by the in_char and out_char
intended use is to identify embedded bracketed sequences
For example, if you have the input
string = "[#1$(*-C(-[#7,#8,F,#16,Cl,Br])-[#7,#8,F,#16,Cl,Br]):1]"
sub_st... | d98c9e78dd309ca9bab435e5f5946e422034d9af | 601,992 |
def pose_mse(gt, output):
"""
The simple version of MSE between two poses, where invalid/failed pose is considered to be all (0, 0)
"""
total_mse = 0
cnt = 0
for idx, joint in enumerate(gt):
if output is not None:
output_joint = output[idx]
else:
outpu... | ad55e989a4a5ea17d2e7fa7de6a8813092466a03 | 601,993 |
from typing import Union
from typing import Tuple
from pathlib import Path
import json
def get_profile_by_cik(cik:Union[str,int]) -> Union[None,Tuple[int,str,str]]:
"""
gets the company profile using the CIK number
Args:
cik (Union[str,int]): the SEC issued Central Index Key (CIK)
Returns:
... | 80524225facf92963667f48a9614b3ecaf1db1f3 | 601,996 |
def get_stations_from_filelist(filename):
"""Build a listing of stations from a simple file listing the stations.
The file should simply have one station per line.
"""
stations = []
for line in open(filename):
stations.append(line.strip())
return stations | 26ed41783c2b1be234c7faadee0dc1654e26d91d | 602,001 |
def escape_arg(argument):
"""Escapes an argument to a command line utility."""
argument = argument.replace('\\', "\\\\").replace("'", "\'").replace('"', '\\"').replace("!", "\\!").replace("`", "\\`")
return "\"%s\"" % argument | ae3bfd1124313ce45ea6a950f5dadf2eb3e8ed15 | 602,006 |
def _is_python_file(filename: str) -> bool:
"""Check if file is a Python file."""
return filename.endswith(".py") | 6e4e366514b04a57116b91f4edf357e86950e8d7 | 602,008 |
def distance1(word):
"""All edits that are one edit away from `word`."""
letters = "abcdefghijklmnopqrstuvwxyz"
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
repl... | 1d3a111b6469b5e12e89414258427e76c0f7b416 | 602,010 |
def get_spines(ax):
"""
return the spines in the order of Cascading-style sheets for the ax
- Top
- Right
- Bottom
- Left
"""
spines = ax.spines.items()
rtn_spines = [0, 1, 2, 3]
for direction, spine in spines:
if direction == "top":
rtn_spines[0] = spin... | be1f6124b8c81de70c9d1d6b1a5a66656f754089 | 602,012 |
def dict_get(dict, key, default=None):
"""
Returns the value of key in the given dict, or the default value if
the key is not found.
"""
if dict is None:
return default
return dict.get(key, default) | f85c0355e560cacd8642f213cf9904319735fd73 | 602,015 |
from datetime import datetime
def months_since_date(start_date) -> int:
"""
Computes the number of months since a given date.
My definition of "number of months" relates to the number of times
you'd flip the calendar page to go to another month, e.g. the
number of months between Jan 31 and Feb 1 i... | 11dc51138c4e5f8007fc373c7420e05429fc098d | 602,019 |
from typing import Tuple
def get_seat_id(seat: Tuple[int, int]) -> int:
"""calculate seat_id from (row, col)"""
return seat[0] * 8 + seat[1] | f485578e875538e5cf2593bfd5b3d52fcbdfe3a9 | 602,021 |
import secrets
def randomClosureChoice(bucket:list):
"""
Return a randomly-chosen element from a list and remove intA.
Be careful to set bucket = GivenList.copy() to not loose original variable !
"""
choice = secrets.choice(bucket)
bucket.remove(choice)
return choice | 4e361f0b576548e4efe1f922ec20fe3ab24bcc10 | 602,024 |
def loss_inversely_correlated_box_class_count_scaled(X, y):
"""
Return
-1 * (concept_direction * prediction / box_class_count)
where
prediction = X[0]
box_class_count = X[1]
concept_direction = y
"""
eps = 1e-08
prediction, box_class_count, *_ = X
concept_dir... | 3b3fc005fcc770da280664010f3e9c61f87a50a2 | 602,026 |
def to_list(x:str):
""" Convert string to list of strings """
x_list=str(x).split(',')
x_list_cleaned=[" ".join(item.split()) for item in x_list]
return x_list_cleaned | 977c720876c397791956c42d81111c445398db71 | 602,027 |
from typing import List
def conjunction_rotations_generator(length: int) -> List[bool]:
"""
Generate rotations list for 'conjunction' block (no rotations).
:param length: Length of rotation list to generate.
:return: 'Conjunction' rotations list.
"""
return [False for _ in range(length)] | d9ddbf80977f1091a1a2a3ace1d94fe8fa21d630 | 602,028 |
def measXY(q, angle):
"""Measure qubit `q` in the basis spanned by `|0> ± e^{i*angle} |1>`.
This is equivalent to doing a Z-rotation of `angle`, then a Hadamard,
and measuring in the Z-basis.
Note: we use the convention that we rotate by +`angle` (not -`angle`).
"""
q.rot_Z(angle=angle)
q.H(... | 076c835c26a7d5b8d270cfef01b36119989ebcc3 | 602,031 |
def join_paths(*args):
"""Join paths without duplicating separators.
This is roughly equivalent to Python's `os.path.join`.
Args:
*args (:obj:`list` of :obj:`str`): Path components to be joined.
Returns:
:obj:`str`: The concatenation of the input path components.
"""
result = ""
... | b48f8805c59e6a7038121a85f828ff3f8e792e29 | 602,035 |
def code_block(language: str, code: str, **options: str) -> str:
"""Format code as a code block.
Parameters:
language: The code block language.
code: The source code to format.
**options: Additional options passed from the source, to add back to the generated code block.
Returns:
... | 183aea0609908e0d9ceb8619f1181f7ad8cb87b8 | 602,037 |
def weighted_rating(x, m, C):
"""
This function is to calculate weighted ratings
"""
v = x['vote_count']
R = x['vote_average']
return (v/(v+m) * R) + (m/(m+v) * C) | fcab0eeed3f97c1ca411b23422ab3fd87974c45d | 602,042 |
def checkpassword_dict(user_password_dict):
"""Returns a checkpassword function which checks credentials
against a dictionary of the form: {username : password}.
If you want a simple dictionary-based authentication scheme, use
checkpassword_dict(my_credentials_dict) as the value for the
checkpasswo... | 0045fb9e1366bdb054b6b51bf3ce754ccd151a18 | 602,043 |
def floor2(i):
"""Find greatest even integer less than or equal to given integer.
Arguments:
i (int): starting integer
Returns:
(int): greatest even integer
"""
return i - (i%2) | 14cfb340da1205f560c9cf1a18b954eb4d4b283b | 602,045 |
def get_sha_for_tag(repo, tag):
"""
Returns a commit PyGithub object for the specified repository and tag.
"""
branches = repo.get_branches()
matched_branches = [match for match in branches if match.name == tag]
if matched_branches:
return matched_branches[0].commit.sha
tags = repo.... | 016aa4a0bcb44deb1c72ae3a186280a9aadda762 | 602,046 |
def get_auth_key(req):
"""Returns the auth key from request headers"""
return req.headers.get("X-Auth-Key") | 74a101dd71c0a1483889c295c8d933491676dd32 | 602,048 |
def indent(txt, n=4, s=" "):
"""Text indenter.
Args:
txt (:obj:`str`):
The text to indent.
n (:obj:`str`, optional):
Number of s to indent txt. Defaults to: 4.
s (:obj:`str`, optional):
Char to use for indent. Defaults to: " ".
Returns:
(... | d22d09e155b2ba64c8fe56c7bbb88e778ccdadf2 | 602,049 |
def collatz_odd(number):
"""Return 3n+1 for a given number."""
return (number * 3) + 1 | 21056336161eeaa5f553674f5c789042c4a86665 | 602,052 |
from typing import Union
from pathlib import Path
def get_latest_save(directory: Union[str, Path]) -> Path:
"""Gets the path to the latest model checkpoint, assuming it was saved with
the format 'model-XXXX.pt'
Parameters
----------
directory: Path or str
The path to a directory containin... | 92ace5b0c521855186f1317e3ce6298a940c88cc | 602,054 |
def _relative_degree(z, p):
"""
Return relative degree of transfer function from zeros and poles
"""
degree = len(p) - len(z)
if degree < 0:
raise ValueError("Improper transfer function. "
"Must have at least as many poles as zeros.")
else:
return degree | 18a84d5be41ac3fe1126c7ed45de4ebc2adc56e2 | 602,055 |
def retrieve_cors_header(response, key):
"""
Method to retrieve a CORS header value from a HTTP response.
:param response: A HTTPResponse object.
:param key: A key representing the desired header value to retrieve.
:return: The header value or None if the header do not exists.
"""
headers =... | 87e0851335a89a7a9501109770c1f32e1d0ca28d | 602,057 |
import re
def rm_quot_marks(text: str) -> str:
"""Remove quotation marks from `text`."""
# \u0022\u0027\u00ab\u00bb\u2018\u2019\u201a\u201b\u201c\u201d\u201e\u201f\u2039\u203a\u276e\u276f\u275b\u275c\u275d\u275e\u275f\u2760\u2e42\u301d\u301e\u301f
return re.sub(r'["\'«»‘’‚‛“”„‟‹›❮❯❛❜❝❞❟❠]','',text) | 8736ed795d86259b3cf0448cbf4c70d45486b172 | 602,058 |
def calculate_perimeter(length, width):
"""
Calculates the perimeter of a rectangle with dimensions length and width.
"""
return 2 * length + 2 * width | ba2853d7ec65d47f21be4459eeca43814049fc22 | 602,059 |
def html_starttag_and_attrs(tag, attrs, startendtag=False):
"""Utility functon to reconstruct starttag and attrs
Params:
- tag (str): HTML element tag
- attrs (list): HTML element attributes formatted as a list of tuples
- startendtag (bool, False): Flag to handle startend tags
Example:
... | 4c7b1c1fec1f101620e7663e991bfcfcf05fda25 | 602,061 |
import json
import requests
def indexd_submit(
hostname, access_token, file_name, size, urls, hashes, authz=None, did=None
):
"""
:params hostname: url of the commons
"params access_token: token for submitting files to indexd"
:params file_name: path to file
:params size: size of the file
... | a7a1f82b1615a3c214943a6b701bacb22f2ef812 | 602,063 |
def workflow_image_location(instance, filename):
"""Return the location of a stored media file for a Workflow."""
workflow_id = instance.id
image_type = instance.type
file_extension = filename.rpartition(".")[2]
return f"workflow_system/workflows/{workflow_id}/{image_type}.{file_extension}" | 88ecd24e3b81a2c719696002d819c4115d1a586c | 602,065 |
from typing import List
from typing import Tuple
def stan_warmup_schedule(
num_steps: int,
initial_buffer_size: int = 75,
final_buffer_size: int = 50,
first_window_size: int = 25,
) -> List[Tuple[int, bool]]:
"""Return the schedule for Stan's warmup.
The schedule below is intended to be as cl... | e2c860181bf5102dd12b56ab410996c9c6bc702a | 602,067 |
import signal
def CMDdevserver(parser, args):
"""Runs the app locally via dev_appserver.py."""
parser.allow_positional_args = True
parser.disable_interspersed_args()
parser.add_option(
'-o', '--open', action='store_true',
help='Listen to all interfaces (less secure)')
app, options, args = parser... | 514de999ca52d6ef43581f328444686b7b53435e | 602,068 |
def get_tile_position(node, target):
""" Return (row,col) of a tile """
return divmod(node.matrix.index(target), node.width) | bbf1c451fdf1908dea83b9f4b0405727f22f0cce | 602,072 |
def unparse_color(r, g, b, a, type):
"""
Take the r, g, b, a color values and give back
a type css color string. This is the inverse function of parse_color
"""
if type == '#rgb':
# Don't lose precision on rgb shortcut
if r % 17 == 0 and g % 17 == 0 and b % 17 == 0:
retur... | c5e612ec617074798a0684de28ca1440e5c2c784 | 602,073 |
import json
def load_dictionary_from_file(file_path):
"""Load a dictionary from a JSON file.
Parameters
----------
file_path : string
The JSON file path to load the dictionary from.
Returns
-------
dictionary : dict
The dictionary loaded from a JSON file.
"""
wit... | f273b13e43f0df1b3cab4c0f8097bec401b83c23 | 602,074 |
import re
def _clean(entity_frag):
"""
Clean the given trunk (text contains entity and pattern)
by removal of the leading and tailing puncutions and stopwords
"""
stopwords = '(of|in|to|and|or|the|a)'
head_regex = r'^\s*{}\b'.format(stopwords)
tail_regex = r'\b{}\s*$'.format(stopwords)
... | 3f93ba567828b4538cc91ae99186953373202aa5 | 602,076 |
def get_account(item):
""" return account from an item. Can be a string or a dict """
try:
account = item['account'] # try value from dict
except TypeError:
account = item
return account | 665a8f262f320f802cfbb2941b133cbae7c23692 | 602,078 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.