content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def find_kwic(item, regexes, shell_nouns):
"""This function takes the location of a vertically annotated text of COCA/COHA
and transforms it to the form [['word', 'lemma', 'POS'], ['word2', 'lemma2', 'POS2'], ...]
As a second argument the regex objects to be used in the search are passed
(they are built... | 65a76b7be4037f2e142b20378ac7a8c68dc7f4c2 | 35,727 |
def is_numeric(value: str):
"""Return True if given value is a number"""
return value.isdigit() | fe61469ab388534a17d079590591378f87078cd3 | 35,728 |
def mixed(operations, paths, _fs=None):
"""Decorates a function that supports multiple types of action.
:param operations: The list of operations (e.g. ["readlink"]).
:param paths: The paths to match (e.g. ["/<file>", "/<file>.txt"]).
:param _fs: An optional _DiazedFileSystem instance (mostly for testi... | 7a7144cb49d64cca74f0e366af3d4a9574a86f8b | 35,729 |
def bladeTELoss(w, t, Temp, alpha, beta, rho, C, K, Y):
"""Thermoelastic calculations for blades
Invoked for upper joint only (there is no lower blade)
w = angular frequency
t = blade thickness
Temp = temperature
alpha = coeff of thermal expansion
beta = temp dependence of Young's modulus
... | d655542a0e09bff311c6f0cbbf57e2c8de954149 | 35,730 |
def pretty_snp_association(association):
"""
Prints association stats in roughly the same format as STOPGAP for a cluster of SNPs
Args: GeneSNP_Association
Returntype: String
"""
snp = association.snp
gene_name = association.gene.name
gene_id = association.gene.id
score = association.score
results = [sn... | f302c451463cce38a2abcab60d322ec876da4efb | 35,731 |
import torch
def nb_Genes(w, device="cpu"):
"""
========================================================================== \n
Return the number of selected genes from the matrix w \n
#----- INPUT \n
w ... | ba9d7f150e177799c1fdf4c521859b6879b09997 | 35,732 |
def S_IMODE(mode):
"""Return the portion of the file's mode that can be set by
os.chmod().
"""
return mode & 0o7777 | b77df185704a5df812dc1fe2431f80d847c9bc15 | 35,733 |
def storage_initial_constraint_rule(backend_model, node, tech):
"""
If storage is cyclic, allow an initial storage to still be set. This is
applied to the storage of the final timestep/datestep of the series as that,
in cyclic storage, is the 'storage_previous_step' for the first
timestep/datestep.
... | b538cd05f834b18471b348d73e6c5a4ca3c5acab | 35,735 |
def get_hform_298k_thermp(output_string):
"""
Obtains deltaHf from thermp output
"""
# Line pattern containing the DeltaHf value at 298 K
dhf298_pattern = ('h298 final' +
app.one_or_more(app.SPACE) +
app.capturing(app.FLOAT))
dhf298 = float(apf.last_c... | 1ac0a111501a0dff5987c662302b6cabf09e6477 | 35,736 |
def filter_peaks_width(peakdic, width_range):
"""
Filter a dictionary of peaks by peak range width.
- peakdic: Dictionary of peaks per sequence (chromosome)
- with_range: Tuple with the minimum and maximum peak
peak width to keep. Other peaks will be discarded
"""
minim, maxim = width_r... | ede51a85999daf589c233fb53e4834ebb3cf3b0a | 35,737 |
def scrape_course(data):
"""Initializes the course if it doesn't exist and returns a list of
("instructor", data) pairs."""
print " " + data['url']
instructors = []
coursesoup = BeautifulSoup(requests.get(data['url']).text)
ratingstab = coursesoup.find(id="tab-ratings")
floatdivs = ratingsta... | 0e3fc6e05774ec89fb67dcaab1acf3d38853ae0b | 35,738 |
def send_tp(mcr, x, y, z, a, b, player):
"""
Send the telepor command using mcr. 'x', 'y' 'z'
are cartesian coordinates, 'a' and 'b' are angles.
"""
tp_parameters = [str(i) for i in ["/tp", player, x, y, z, a, b]]
mc_command = ' '.join(tp_parameters)
resp = mcr.command(mc_command)
return... | 43c5d94d209c6a4f9d988c6c2711fc3927bd37c3 | 35,739 |
def ori_smooth(directions,frames_per_second=None,return_missing=False):
"""smooth orientations using an RTS smoother
This treats orientations as XYZ positions
"""
dt = 1.0/frames_per_second
A = np.array([[1, 0, 0, dt, 0, 0],
[0, 1, 0, 0, dt, 0],
[0, 0, 1, 0, 0, ... | 85871a95409d059617d41931155c14c6b9532d93 | 35,741 |
from typing import Sequence
import array
def compile_array(data: Sequence[float], format="xyseb") -> array.array:
"""Gather point components from input data.
Format codes:
- ``x`` = x-coordinate
- ``y`` = y-coordinate
- ``s`` = start width
- ``e`` = end width
- ``b`` ... | 6de809fdcd32a1b39a2cc3e8639cb8047fc476fa | 35,742 |
def nms(bboxes, iou_threshold, sigma = 0.3, method = 'nms'):
""" function to implement non-maximal suppression / softmax non-maximal supression of bboxes """
""" takes bboxes with the shape of (num_of_box, 6), where 6 => (xmin, ymin, xmax, ymax, score, class) """
# remove duplicates in classes
... | 5e2b390f2c920d6d0f6909bb058cc50b316a36b3 | 35,743 |
def hls_to_hex(h, l, s):
"""Converts a (hue, lightness, saturation) tuple to a "#rrbbgg" string.
Args:
h, l, s: the HLS values
Returns:
a hex string
"""
return rgb_to_hex(*hls_to_rgb(h, l, s)) | 562e4f802b1cc19734574186cbf107f3a288e044 | 35,744 |
def seconds_to_hhmmssms(seconds):
"""Parses the number of seconds after midnight and returns the corresponding HH:MM:SS.f-string.
Args:
seconds (float): number of seconds after midnight.
Returns:
str: the corresponding HH:MM:SS.f-string.
"""
int_seconds = int(seconds)
ms = roun... | ce68c6238de4229aed99d3e4a72596d72f97af7c | 35,746 |
import torch
def sample_with_probs(model, x, steps, temperature=1.0, sample=False, top_k=None, first_sentence=False):
"""
A modified version of sample from mingpt.util that also returns probability of each sentence
and allow end with first sentence complete
"""
block_size = model.get_block_size()
... | 643e8e0f05c126180fa0998212d8070394df8764 | 35,747 |
def expression(processor, composer, searcher):
# type: (Parser, Compiler, scanner.Scanner) -> Tuple[Parser, Compiler]
"""Compiles expression."""
return parse_precedence(processor, composer, searcher, Precedence.PREC_ASSIGNMENT) | 84b2e3f832a6dcbb89199f1e5c3b69f2044fb36c | 35,748 |
import time
def get_games_results(game_name: str, web: str = "all"):
"""
Get games results from spiders
:param game_name:
:param web:
:return: list of games, obtained from spiders.
"""
games = []
not_formatted_games = []
time.sleep(get_random_delay())
if web == "eneba":
... | a78b520aa9426a4ba733a060f4a34432b35d8bce | 35,749 |
def plot_pr_curve(y_true, y_pred, title=None):
"""
Convenience function for plotting precision recall curve
@param: y_true - ground truth
@type: array like
@param: y_pred_train - predictions
@type: array like
"""
precision, recall, _ = precision_recall_curve(y_true, y_pred)
avg_prec... | ad8575afc92d1e03b2ab9a8f27395ebfec0f606f | 35,750 |
def matrix_from_interactions(interactions, mapping, default=0.0):
"""Generate numpy matrices from interaction dictionary
:param interactions: dictionary read from WORDOM avgpsn
:param mapping: residuemap, preserves residue names
:param default: default interaction
:return: tuple of interaction stre... | c120ed1d56aed8c3b25a2c06d579af5d76705377 | 35,751 |
def to_flags(value):
"""Return a (flags, ednsflags) tuple which encodes the rcode.
*value*, an ``int``, the rcode.
Raises ``ValueError`` if rcode is < 0 or > 4095.
Returns an ``(int, int)`` tuple.
"""
if value < 0 or value > 4095:
raise ValueError('rcode must be >= 0 and <= 4095')
... | 12477f6db3f1124d08884815ded5f2313ab1af98 | 35,752 |
def map_mix_query_attr_to_ch(mixing_query):
"""Map the mixing query attributes (tip_angle and phase) to the channel index.
If the attribute is defined for the channel use the defined value else set it to 0.
Args:
spectral_dimension: A list SpectralDimension objects.
index: The index of the ... | 9192b9abbc2710b8ebdf172ad34c3dfadf8048ef | 35,753 |
def masked( arr, v, mask ):
""" Performs the 1D convolution on arr, omitting pixels under the mask """
arr = arr.astype(float)
smoothed = conv( arr*mask, v )
norm = conv( mask.astype(np.float), v )
return smoothed/norm | ac12e1703b931800bcaea1d496dceb98e1c9303b | 35,754 |
from datetime import datetime
def api_get_videos_duration(list_videos, api_service):
"""Get the duration of 50 videos at once.
:param list_videos: A list of video IDs, maximum size 50.
:param api_service: API Google Token generated with Google.py call.
:return: a dictionary associating video id and d... | a88dd81b510ba99038401e90eb524194860a2c83 | 35,757 |
def build_pieces(headers, batch_size, start, end, max_piece_size=100000, metadata_columns=None):
"""
Build pieces function takes as input a list of headers and
returns a list of pieces split in size maximum max_piece_size.
Input: (filename, count, count_before)
Output: (filename:str, piece_start:int... | 92f3ac97d1a9ec16c0aea491ac773707463d05e3 | 35,758 |
from typing import Dict
def collect_values(wdlfile: str, separate_required: bool,
category_key: str, fallback_category: str,
description_key: str, fallback_description: str,
fallback_description_to_object: bool,
strict: bool) -> Dict:
"""... | 356fcdde70ca644c2bf9fd8d78ed0fba539c3aaf | 35,759 |
def _GetConfigMapsChanges(args):
"""Return config map env var and volume changes for given args."""
volume_kwargs = {}
env_kwargs = {}
updates = _StripKeys(
getattr(args, 'update_config_maps', None) or args.set_config_maps or {})
volume_kwargs['updates'] = {
k: v for k, v in updates.items() if _I... | c82e3d8d85cf224c4af7ebb397136aa253e36a17 | 35,760 |
import torch
def dice_loss(pred, target):
"""Cacluate dice loss
Parameters
----------
pred:
predictions from the model
target:
ground truth label
"""
smooth = 1.0
pred = torch.sigmoid(pred)
p_flat = pred.view(-1)
t_flat = target.view(-1)
i... | 5bdede57fd34340b823324f962b20e5481333adf | 35,762 |
import tqdm
import requests
def stock_em_dxsyl(market: str = "上海主板") -> pd.DataFrame:
"""
东方财富网-数据中心-新股数据-打新收益率
http://data.eastmoney.com/xg/xg/dxsyl.html
:param market: choice of {"上海主板", "创业板", "深圳主板"}
:type market: str
:return: 指定市场的打新收益率数据
:rtype: pandas.DataFrame
"""
market_ma... | 42eaac231a9c5a2ab7e5d209ac8f2093de0869a8 | 35,763 |
def get_warningness() -> int:
"""Gets the warning level of the entire program"""
return _warningness | 57bb29e6697698707132435ccf0f27aba9bab0d2 | 35,764 |
import scipy
def distanceMetrics(vol1, vol2, voxelsize_mm):
"""
avgd[mm] - Average symmetric surface distance
rmsd[mm] - RMS symmetric surface distance
maxd[mm] - Maximum symmetric surface distance
"""
# crop data to reduce computation time
pads1 = getDataPadding(vol1)
pads2 = getDataP... | 684db2e73cf861fcf657ccd6a979ee42187f5b47 | 35,765 |
def point_in_quadrilateral_2d(
point: np.ndarray, quadrilateral: np.ndarray
) -> bool:
"""Determines whether a point is inside a 2D quadrilateral.
Parameters
----------
point : np.ndarray
(2,) array containing coordinates of a point.
quadrilateral : np.ndarray
(4, 2) array conta... | cde2c018d792f8ee406a8fe4ca3eaf336ccdd0b1 | 35,766 |
def pSEDIa( sedtype ):
""" returns the likelihood of observing
host galaxy with the given rest-frame
B-K color, assuming the SN is a Ia.
The SED type is from the GOODZ SED template
set (Dahlen et al 2010).
1=E, 2=Sbc, 3=Scd, 4=Irr, 5,6=Starburst
plus 4 interpolations between each.
... | 493966a39f5a8d01390f4652643e861c7570963d | 35,767 |
import re
def markov(bot, msg):
"""Return the best quote ever."""
if final_model:
# This tries to generate a sentence that doesn't "overlap", or
# share too much similarity with seeded text.
# Read more here: https://github.com/jsvine/markovify#basic-usage
sentence = final_mode... | 24ea657257880ec0755360eb64d9bbcd9dfaf62f | 35,768 |
def two_body_mc_stress_stress_jit(
bond_array_1,
c1,
etypes1,
bond_array_2,
c2,
etypes2,
d1,
d2,
d3,
d4,
sig,
ls,
r_cut,
cutoff_func,
):
"""2-body multi-element kernel between two partial stress components
accelerated with Numba.
Args:
bon... | f5f702398f7bb3e8b498b60653bcc2a520e81f95 | 35,769 |
def new_world_news(cat):
"""[categories]\n\n
lore \n
general\n
updates\n
"""
return nww.news(cat) | 696fc748cc8927ba75059fda9dd787afe6250471 | 35,771 |
import time
def aggregation_svg(es, query: Query):
""" Execute aggregation query and render as an SVG. """
is_internal = "/logs" in request.headers.get('Referer', '')
width = query.args.pop('width', '100%' if is_internal else '1800')
width_scale = None
if width != '100%':
width_scale = ti... | 3ef3e01232fcaeccdb810df80bc824494569b439 | 35,772 |
def transposem(inp):
"""Transpose multiple matrices."""
perm = list(range(len(inp.shape)))
perm[-2], perm[-1] = perm[-1], perm[-2]
return tf.transpose(inp, perm) | 1851aef9afa0717953bf409ac9ecdb993f0dd674 | 35,773 |
from typing import Any
def list_api_tokens(
component_manager: ComponentManager = Depends(get_component_manager),
token: str = Depends(get_api_token),
) -> Any:
"""Returns list of created API tokens associated with the authenticated user."""
authorized_access = component_manager.verify_access(token)
... | 7b52a3fff5594cdf3be5eaf0a344c23ea0e320c4 | 35,775 |
def get_val_via_socket(key):
"""Retrieve value of key from redis over Unix socket file."""
set_redis_socket_pool()
global SOCKET_POOL
# retrieve value
r = StrictRedis(connection_pool=SOCKET_POOL)
res = r.get(key)
return res.decode() if hasattr(res, "decode") else res | 3783d121ec16365edc81c8a538015598a100dd55 | 35,776 |
def euclidean_distance(goal_pose):
"""Euclidean distance between current pose and the goal."""
return sqrt(pow((goal_pose.pose.position.x - pose.pose.pose.position.x), 2) +
pow((goal_pose.pose.position.y - pose.pose.pose.position.y), 2)) | bdcf6f005eb548f2fb8a2d3f530cf276f75725a2 | 35,777 |
def get_rel_join_parts(database, from_table, rel) -> QueryParts:
"""
:param Database database: The database being reviewed.
:param Table from_table:
:param Relationship rel: The relationship to get the parts from.
:return: New join parts for a join based on a relationship.
"""
to_table = dat... | 75346106c368f760eef36a7c0eb504d04eafe298 | 35,778 |
from lightgbm import LGBMRegressor
from entmoot.learning.tree_model import EntingRegressor, MisicRegressor
def cook_estimator(base_estimator, std_estimator=None, space=None, random_state=None,
base_estimator_params=None):
"""Cook a default estimator.
For the special base_estimator called "DUMMY" the... | 53fea2782062124d1814cc298a55a45195b145af | 35,779 |
from pandas import Series
from typing import Optional
def _convert_and_box_cache(
arg: DatetimeScalarOrArrayConvertible,
cache_array: "Series",
name: Optional[str] = None,
) -> "Index":
"""
Convert array of dates with a cache and wrap the result in an Index.
Parameters
----------
arg ... | 60d2f5752b51aa16f2d5d2a67192158dc27f57d1 | 35,780 |
def generate_file_path(package_path, file_name):
"""
Dynamically generate full path to file, including filename and extension.
:param package_path: (array) ordered list of packages in path to test file
:param file_name: (string) name of the file w/ test, including the extension
:return: (string) fu... | a6d2ac12cdc726c4727e23301971e921cab9455b | 35,781 |
from typing import Tuple
def pdread_2col(filename: str, noheader: bool = False) -> Tuple[ndarray, ndarray]:
"""Read in a 2 column file with pandas.
Parameters
----------
filename: str
Name of file to read.
noheader: bool
Flag indicating if there is no column names given in file.
... | b1cd7282bf7122abf412351069d7f949be7928cc | 35,782 |
async def infer_type_map_array(engine, fn, ary):
"""Infer the return type of map_array."""
fn_t = await fn['type']
ary_t = await ary['type']
if not isinstance(ary_t, Array):
raise MyiaTypeError('Expected array')
xref = engine.vref({'type': ary_t.elements})
return Array(await fn_t(xref)) | c3bed37c4adfb0e1a1acfe86242bae9349edffa7 | 35,783 |
def _fullname(attr):
"""Fully qualified name of an attribute."""
fullname = ""
if hasattr(attr, "__module__"):
fullname += attr.__module__
if hasattr(attr, "__name__"):
if fullname:
fullname += "."
fullname += attr.__name__
if not fullname:
fullname = str(... | 672120f7b16175b9fed091fbdd93456ba5d89004 | 35,784 |
def example_positionfixes():
"""Positionfixes for tests."""
p1 = Point(8.5067847, 47.4)
p2 = Point(8.5067847, 47.5)
p3 = Point(8.5067847, 47.6)
t1 = pd.Timestamp("1971-01-01 00:00:00", tz="utc")
t2 = pd.Timestamp("1971-01-01 05:00:00", tz="utc")
t3 = pd.Timestamp("1971-01-02 07:00:00", tz="... | 496283dc4d73588e7c9891577bc8915a8ec58863 | 35,785 |
def do_histtestbasic() -> bool:
"""Run this unit test with hard coded, default parameters."""
file = "sample.txt"
par = [5, 0, 15]
test = HistTestBasic(txtfile=file, params=par)
return test.test(False) | b8f033ba62d073a44b9208f8233892774cc7b502 | 35,787 |
def static(**kwargs):
"""
Return a predefined ``dict`` when the given regex matches.
"""
return lambda values: kwargs | ac12595cc1b70dd5f9cccd8ae043f650f0ef59c5 | 35,789 |
def get_user_profile(email): # GET
"""Get user profile
Fetches from the user collection by using the user's email as key.
Args:
User's email (str)
Returns:
User profile object (dict)
"""
# NOTE: This method previously called LCS with director credentials in order to retrieve ... | 10fe0b3ff37d54d51d456392cb1984d92e10c10a | 35,791 |
import hashlib
def sha1(string):
"""Compute the sha1 hexdigest of the string."""
return hashlib.sha1(string.encode('utf-8')).hexdigest() | b663fc501e24a2331f69847024756b97dabc0cd4 | 35,792 |
import cgi
import re
def generate_rss():
""" Generate the RSS feed pages on a daily basis """
def parse():
try:
form = cgi.FieldStorage()
form_play = form.getfirst('play', '')
form_date = form.getfirst('start', '')
# alphanumeric only for play
... | 9b92b9cc6095ccbce0bfab204476c205c7e47569 | 35,793 |
from datetime import datetime
def current_weather():
"""
Get all stations
render template to client
"""
global last_updated_weather_time, last_updated_weather_data, first_run_weather
if (((last_updated_weather_time - datetime.datetime.now())).total_seconds() < -900 or first_run_weather):
... | 25dfb78759903c1f089d397b548a79d36304cf74 | 35,794 |
import re
def parse_timedelta(time_str):
"""
Parse a time string e.g. (2h13m) into a timedelta object. Stolen on the web
"""
regex = re.compile(r'^((?P<days>[\.\d]+?)d)?((?P<hours>[\.\d]+?)h)?((?P<minutes>[\.\d]+?)m)?((?P<seconds>[\.\d]+?)s)?$')
time_str=replace(time_str,{
'sec':'s',
... | 0b18f77197f8122cb92ccd7b7552baab800173f7 | 35,795 |
def gmtime(space, w_seconds=None):
"""gmtime([seconds]) -> (tm_year, tm_mon, tm_day, tm_hour, tm_min,
tm_sec, tm_wday, tm_yday, tm_isdst)
Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
GMT). When 'seconds' is not passed in, convert the current time instead... | f4095b64c60c67454f7ef24e295438f3eff68a77 | 35,796 |
from typing import Callable
def nested_defaultdict(default_factory: Callable, depth: int = 1) -> defaultdict:
"""Creates a nested default dictionary of arbitrary depth with a specified callable as leaf."""
if not depth:
return default_factory()
result = partial(defaultdict, default_factory)
fo... | 58b162431d70f559dc58a256e78d201644cddde3 | 35,797 |
def main(client_id, client_secret):
"""Console script for boxcast_python_sdk."""
client = BoxCastClient(client_id, client_secret)
account = client.get_account()
print(account)
return 0 | ec6562052d7bf6cb8594356df16cbcf0d98314b2 | 35,798 |
import pytz
from datetime import datetime
def now(timezone):
"""Get the current time in the given timezone
Args:
timezone: The desired timezone as a string. eg 'US/Eastern'
"""
utc = pytz.timezone('UTC').localize(datetime.utcnow())
return utc.astimezone(pytz.timezone(timezone)) | ebd89601ebcb945f01c3e68fbe0f5350e4fc2d0a | 35,799 |
def ReadBlackList(path):
"""Read a blacklist of forbidden directories and files.
Ignore lines starting with a # so we can comment the datafile.
Args:
path: file to load the blacklist from.
Returns:
dictionary of path:True mappings
"""
blacklist_file = open(path, 'r')
catalog = []
for entry in ... | 694b9bd8c09385677d49e8563ac8f08b923cadb0 | 35,800 |
def height_water_critical(FlowRate, Width):
"""Return the critical local water height.
:param FlowRate: flow rate of water
:type FlowRate: u.m**3/u.s
:param Width: width of channel (????????)
:type Width: u.m
:return: critical water height
:rtype: u.m
"""
ut.check_range([FlowRate.m... | 39602709854f04e007533fe133a47edf722e6a5a | 35,801 |
def author_number_of_files_owned(results):
""" Number of files owned by author.
:param results: results from author_file_owned()
:return: {author: number of files owned}
:rtype: dict
"""
authors = defaultdict(int)
for item in results:
authors[item.name] += 1
return authors | 7a4b07f58bc0f4898408a16353c7b5a7f2108904 | 35,803 |
def updateBounds(bounds, (x, y), min=min, max=max):
"""Return the bounding recangle of rectangle bounds and point (x, y)."""
xMin, yMin, xMax, yMax = bounds
return min(xMin, x), min(yMin, y), max(xMax, x), max(yMax, y) | 5e77fd6b422a252a5c8fc1b22a642ce05e5caf82 | 35,804 |
def prepare_metadata(devkit_archive):
"""Extract dataset metadata required for HDF5 file setup.
Parameters
----------
devkit_archive : str or file-like object
The filename or file-handle for the gzipped TAR archive
containing the ILSVRC2012 development kit.
Returns
-------
... | 3d0e7cd536983c6f505bf5d62d5a8be4e50ab167 | 35,806 |
import io
def optimize_results(sample_names,
control_samples,
FPs_per_genome,
plot_roc=False,
plot_tuning_curve=False,
filtered_results_file=None,
output_dir=None,
mutatio... | add62fbf94e7f984d883957801b59dca022287a6 | 35,807 |
from datetime import datetime
def get_detections(
args,
config: DictConfig,
module: ModuleType,
model: nn.Module,
geoscreens_data: LightningDataModule,
video_id: str,
):
"""
Returns:
Dict: keys = frame index, value = a dict of detections that looks something like::
... | 3c28598b6b9bd465434932ee8809e73cecedf698 | 35,808 |
def gen_format_string(a: np.array):
"""
Generates a matrix format in the shape of a.
>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(gen_format_string(a))
┌ ┐
|{:>2}{:>2}{:>2} |
|{:>2}{:>2}{:>2} |
|{:>2}{:>2}{:>2} |
└ ┘
The template can be rendered with the help of... | c975ab9c99b75f14757f8fecc5c1215180af3f98 | 35,810 |
def create_quantum_model():
"""Create a QNN model circuit and readout operation to go along with it."""
data_qubits = cirq.GridQubit.rect(4, 4) # a 4x4 grid.
readout = cirq.GridQubit(-1, -1) # a single qubit at [-1,-1]
circuit = cirq.Circuit()
# Prepare the readout qubit.
circuit.append(cirq.... | c7dcc577f3ef7a5ced1dd4b9bf08be4e5065d315 | 35,812 |
def get_completeness_coef(iocs_per_feed: int, total_iocs: int) -> float:
"""
This function wrapper is intended for
calculate feed completeness factor
Parameters:
iocs_per_feed: int — Number of IoCs in the CTI feed
total_iocs: int — Number of IoCs across all CTI feeds
... | 9f677549f90b8e8d6eb2d328eb91068ea32920bf | 35,813 |
def valid_model(model):
"""Check if the model is valid."""
if model is None:
raise ValueError("The SaraBotTagger model can not be None")
path_to_model = f'{absolute_path}/bot_model/{model}'
model = load(path_to_model)
return True | 8e00d0907e31f1370bd52532ae06df6f7458737a | 35,814 |
def getApi(token_path):
""" Логинится в вк и возвращает готовую к работе сессию """
with open(token_path) as f:
token = f.read().strip()
session = vk_api.VkApi(token=token, api_version="5.52")
return session.get_api() | 143b11a9e2612bc10bf41b716d21adcf14bdc60d | 35,815 |
import re
def projects():
"""
General purpose provider of paths to test projects with the conventional layout
"""
base_path = PROJECT_ROOT / "tests" / "fixtures"
projects = {
re.match(r"^([_\w]+)_project", path.name).groups()[0]: path.resolve()
for path in base_path.glob("*_project... | 250473fbb89f65d8163e7d2f6085cc7217ea2860 | 35,816 |
def qair2rh(qair: xr.DataArray, temp: xr.DataArray, pres: xr.DataArray) -> xr.DataArray:
"""
Get the relative humdity from the specific humidity.
Args:
qair (xr.DataArray): The specific humidity (dimensionless).
temp (xr.DataArray): The temperature (kelvin).
pres (xr.DataArray): The... | 3e230a3c79d8106486f3eb3b67a1459705bbfb89 | 35,817 |
import re
def read_trees(input_dir, features, signals, backgrounds, selection=None,
negative_weight_treatment="passthrough",
equalise_signal=True, branch_w="EvtWeight",
col_w="MVAWeight", col_target="Signal"):
"""
Read in Ttrees.
Files in the input directory s... | 88e27750eb84173f0505533da4c0e3e44d80a9cf | 35,818 |
def package_form(request):
"""
Upload a new package
"""
return render(request, 'packages/package_form.html', {
'form': PackageForm(),
}) | f57c92fcdbf67a4d410af6ca20f44e3d0bdb72a5 | 35,819 |
from typing import List
def destory(list_id):
"""Delete list."""
list = db_session.query(List).filter(List.id == list_id).first()
if(list.user_id != login_session['user_id']):
flash("This list does not belong to your account")
return redirect(url_for('list.index'))
db_session.delete(li... | 54899380c4a80d076815b9fe3f835fc44fb5d911 | 35,820 |
def categorize_os():
"""
Categorize operating system by its parent distribution.
Args:
None
Raises:
None
Returns:
None
"""
os_name = get_system_name()
if os_name in ["ubuntu", "kali", "backtrack", "debian"]:
return "debian"
# elif some other OS, add... | 84df15c78e3e9c40294e6ad77afbac857df3e29e | 35,823 |
def has_names_directive(block: FencedBlock) -> bool:
"""Does the code block have a share-names or clear-names directive."""
assert block.role == Role.CODE, "must be a Python code block."
return block.has_directive(Marker.SHARE_NAMES) or block.has_directive(
Marker.CLEAR_NAMES
) | cd70019e724c4f0370fa1c3c9db8d52c22c80e3f | 35,824 |
import math
def make_reber_classification(n_samples, invalid_size=0.5,
return_indeces=False):
"""
Generate random dataset for Reber grammar classification.
Invalid words contains the same letters as at Reber grammar, but
they are build whithout grammar rules.
Paramet... | c38627651ed2fb3f18bbebbefe3e06801c1accf5 | 35,825 |
def batchify(X, size):
"""
```
Splits X into separate batch sizes specified by size.
Args:
X(list): elements
size(int): batch size
Returns:
list of evenly sized batches with the last batch having the remaining elements
```
"""
return [X[x : x + size] for x in rang... | d3e4ad015eb3b8bb4cdbaa6bf87a2bc1989c4614 | 35,826 |
def _single_entity_stmt(
start_day: dt,
end_day: dt,
event_types: tuple[str, ...],
entity_id: str,
entity_id_like: str,
) -> StatementLambdaElement:
"""Generate a logbook query for a single entity."""
stmt = lambda_stmt(
lambda: _select_events_without_states(start_day, end_day, event... | 0cbc33f1715b65cfbd803ab9674c6264d73a096e | 35,827 |
def listtoslides(data):
"""Checks if format is correct + adds img and durration elements"""
slides = []
for slide in data:
slide = slide[:2]
slide[0] = slide[0][:25]
slide[1] = slide[1][:180]
slide.append("imgpath")
slide.append(0)
slides.append(slide)
ret... | b4b7180fc5755eff6a32ff8b448f1dfd65ad6f75 | 35,828 |
def clean_data(sample):
"""
整体清洗函数,为了方便多线程使用
Args:
sample: 一个元组,包含正文内容和标题内容
Returns:
"""
(content, title) = sample
sample = dict()
# 清洗数据
sample["title"] = clean_weibo_title(title.strip())
sample["content"] = clean_weibo_content(content.strip())
return sample | 268f98dfc8e8aaeb7f6a10887278964b6deb56db | 35,829 |
def read_cat_as_dataframe(fichero_cat, tipo_registro, columns=None):
"""
Devuelve un pandas.DataFrame con los registros del el tipo deseado
- fichero_cat: fichero .cat, puede estar comprimido.
- tipo_registro: Tipo de registro, p.ej.: '11', '15'
- columns: Lista con los nombres de l... | 47a25aa147bcf00ff3aa45abc4c5ef524a11761a | 35,830 |
def init_cppn_from_img(image: np.array, color: bool = True, sim_threshold: float = 0.6, max_optim_iter: int = 10000,
init_stop_bound: int = 100) -> CPPN:
"""
Initializes a CPPN using the given image by optimizing the SSIM score between the CPPNs output and the image.
This is done by t... | bb97754776dfceb05d144e7f125d5eda2008a5bd | 35,831 |
def unwind_create_nodes_query(data, labels=None, keys=None):
""" Generate a parameterised ``UNWIND...CREATE`` query for bulk
loading nodes into Neo4j.
:param data:
:param labels:
:param keys:
:return: (query, parameters) tuple
"""
return cypher_join("UNWIND $data AS r",
... | 3c0c444ecd1497399c27607bf0deb3026f017a03 | 35,832 |
def _scalePoints(points, scale=1, convertToInteger=True):
"""
Scale points and optionally convert them to integers.
"""
if convertToInteger:
points = [
(int(round(x * scale)), int(round(y * scale)))
for (x, y) in points
]
else:
points = [(x * scale, y ... | 3ce3fedfbf7c428386af1571cc1a770bd9f66018 | 35,833 |
def get_customer_tax_rate(request, product):
"""Returns the specfic customer tax for the current customer and product.
"""
cache_key = 'cached_customer_tax_rate_%s' % product.pk
if request and hasattr(request, cache_key):
return getattr(request, cache_key)
customer_tax = get_first_valid(requ... | 64491092626f0bb12c9a8a0522fc81acfe55846c | 35,834 |
def iscoroutinepartial(coro):
"""
Function returns True if function it's a partial instance of coroutine. See additional information here_.
:param coro: Function
:return: bool
.. _here: https://goo.gl/C0S4sQ
"""
while True:
parent = coro
coro = getattr(parent, 'func', No... | dace8744f79475518a0c52f488c17d9b685fae07 | 35,835 |
def AppendFchunk(funcea, ea1, ea2):
"""
Append a function chunk to the function
@param funcea: any address in the function
@param ea1: start of function tail
@param ea2: end of function tail
@return: 0 if failed, 1 if success
@note: If a chunk exists at the specified addresses, it must hav... | 709c1790d6dd1e472ab97efdab84eeef9a87ab8f | 35,837 |
def testing_audio():
"""Load data for the tests."""
return sf.read(TEST_WAVEFILE_PATH, always_2d=True, dtype='float32') | c61f3429bcb1ed7745ae07282b65e0b0b0a6cfb8 | 35,838 |
def linr(xdata, ydata):
"""Return the linear regression coefficients a and b for (x,y) data.
Returns the y-intercept and slope of the straight line of the least-
squared regression line, that is, the line which minimises the sum of
the squares of the errors between the actual and calculated y values.
... | 0761004020d5a4b723e39f9988a4e379a64506cd | 35,839 |
def album_sticker_get(client, album, sticker):
"""Gets a sticker associated with an album."""
# I am pretty sure that MPD only implements stickers for songs, so
# the sticker gets attached to the first song in the album.
tracks = client.find("album", album)
if len(tracks) == 0:
return
... | 4fd02292c1d7be672de9ccc926f5880c7b831503 | 35,840 |
def print_confusion_matrix(confusion_matrix, class_names, filename, normalize = True, figsize = (5,5), fontsize=16):
"""Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap.
Arguments
---------
confusion_matrix: numpy.ndarray
The numpy.ndarray object retu... | bfb7cfd33a35d5e1b1a08255c2e777c26d45c566 | 35,841 |
from re import T
def group():
""" RESTful CRUD controller """
tablename = "pr_group"
table = s3db[tablename]
response.s3.filter = (table.system == False) # do not show system groups
s3mgr.configure("pr_group_membership",
list_fields=["id",
"p... | 110e7c17dc8a4a3f129845f278e1a4d9760da8c3 | 35,843 |
import torch
def colorization_inference(model, img):
"""Inference image with the model.
Args:
model (nn.Module): The loaded model.
img (str): File path of input image.
Returns:
np.ndarray: The predicted colorization result.
"""
# cfg = model.cfg
device = next(model.p... | 8d47cfb2c5242e23ebd4e57952badb3d41bec450 | 35,844 |
def load_templates_from_dir(directory: str) -> Environment:
"""Produce an Environment targeted at a directory."""
return Environment(loader=FileSystemLoader(directory)) | 8d2e8062164d4fa02be41c059253524e5da86b92 | 35,846 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.