content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def generate_noaa_interpolation_data(data_dir, pressure_levels, out_name='aloft',
start_year=1965, method='multiquadric', show_progress=True,
multi_thread=True, max_processes=None, chunk_size=1):
"""Function to generate interpolations for NOA... | 53fe8a07e51a3e58dec8908da67ebe3ec96719a5 | 74,593 |
import json
def load_prices(used_instance_types, region_name):
"""
Load current EC2 price-list from AWS.
"""
pricing = boto3.client("pricing")
price_map = {}
known_instance_types = []
product_list = []
for used_type in used_instance_types:
if used_type not in known_instance_typ... | 770003391152b9775f3af33d26ceb1c70573d809 | 74,594 |
def GDAL_GCP_GCPLine_set(*args):
"""GDAL_GCP_GCPLine_set(GCP gcp, double dfGCPLine)"""
return _gdal.GDAL_GCP_GCPLine_set(*args) | f824731f691ae3cbae53b34a6ae79cd69715e342 | 74,595 |
def rand(maximum=1.0):
"""Return a random number between 0 and maximum (default 1.0)
Parameters
----------
maximum: float, default=1.0
The maximum value for the randomly generated number.
"""
return Prefix("rand", maximum, agg=False, dtype=float) | 4c583e649fb2d9fb9ec09018079820a1be014c27 | 74,596 |
def load_cookies():
"""
To load in the saved cookies into the webdriver browser session.
Will return two boolean true or false values:
--> First value for pixiv Fanbox and second value for Fantia
"""
pixivCookieLoadedLocal = fantiaCookieLoadedLocal = False
fantiaCookieExist = appPath.joinp... | a3f683b5683d9323449b76ae3749211352e16e14 | 74,598 |
def post_inner_loop_update(temp_storage, this_np):
"""
This function updates the storage at the end of a step of the outer-loop, i.e., after all steps in the inner loop.
:param temp_storage: (dictionary) the dictionary with all the information and storage required by the inner loop
:param this_np: (Num... | f07b931ed999e18d73741020614d5faafb1664c3 | 74,600 |
import socket
def str_to_inet(ip: str) -> bytes:
"""
Converts a string representation of IP address to binary representation.
:param ip: IP like - "123.45.67.89"
:return: 32 bit representation of "123.45.67.89" like - '{-CY'
"""
try:
return socket.inet_pton(socket.AF_INET, ip)
exce... | 3ab520701ec0271499d3512425a939803ac0adc9 | 74,601 |
from functools import reduce
def _pack_bits_into_byte(iterable):
"""\
Packs eight bits into one byte.
If the length of the iterable is not a multiple of eight, ``0x0`` is used
to fill-up the missing values.
"""
return (reduce(lambda x, y: (x << 1) + y, e)
for e in zip_longest(*[it... | b747ab9c48af083631b2c0b4c1968d465bf523f1 | 74,602 |
import csv
def load_promoter_characterizations (filename, samples):
""" Load promoter characterization data from file
"""
pro_data_perf = {}
pro_data_full = {}
data_reader = csv.reader(open(filename, 'rU'), delimiter='\t')
# Ignore header
next(data_reader)
# Process each line
for row in data_reader:
cur_ch... | 2029c23d33768fb72bc0fb20e6a3dae7d0338887 | 74,603 |
def canonical(smi):
""" canonical smiles string
"""
pbmol = _pybel_molecule(smi, geom=False)
can_smi = pbmol.write('can').strip()
return can_smi | 3a00358a05b8ae8a332b43c1146ed76d0855913c | 74,604 |
from typing import Optional
from typing import List
from typing import Tuple
from pathlib import Path
def make_response(cli_args: Optional[List[str]] = None) -> Tuple[str, int]:
"""Makes a response to the given command line arguments."""
parser = ArgumentParser(
description="Executes Markdown code bl... | 546d3195f1cbffaa5d8de0310f1d633b87c4e910 | 74,605 |
def display_map(route_id):
"""Route, that renders a folium map with markers,
that correspond to the shops and mountain itself, respectively"""
mountain_coordinates = get_mount_coords(route_id, path_to_db)
shop_coordinates = get_shop_coords(
mountain_coordinates[0], client_id, client_secret)
... | 0e8e7e1324f9f9310242bee3ee9c705e2bffae83 | 74,607 |
def get_r77_id(cookie):
"""
get a Room 77 id from a cookie
"""
try:
r77_id, _ = cookie.split('%3B') # URI-encoded semicolon
except ValueError:
raise ValueError('Invalid cookie') # no semicolon
return int(r77_id) | 8513f1080eee73d342fcfee03df5f7927aca1197 | 74,608 |
def pred_sa(s_sa):
"""
return: [ pr_wc1_i, pr_wc2_i, ...]
"""
# get g_num
pr_sa = []
for s_sa1 in s_sa:
pr_sa.append(s_sa1.argmax().item())
return pr_sa | 5e961bad8d2b6c9d5f7a6e4eaf1c3e9238b79613 | 74,609 |
def task_accuracy_metrics(reward_list):
""" Accuracy as percentage of examples that received rewards """
accuracy = sum(reward_list)*100/float(len(reward_list))
print("Total Reward: %s, Accuracy: %s %%"%(sum(reward_list),accuracy))
return accuracy | 63a27a95ade76324ba3b2fd4b199275c17474082 | 74,610 |
def get_missing_ids(manifest_integrity: ManifestIntegrity, entity: dict) -> set():
"""
Check if a manifest's entity passes referential integrity.
:param entity: Manifest's entity.
"""
missing_ids = set()
references = manifest_integrity._extract_references(entity)
external_references = manif... | 14b95c562a11fbb410cd6c33eaf8dd014b9c3a54 | 74,611 |
def SumCoeffsOverSet(summing_set, A):
"""Returns the sum of coefficients corresponding to the summing set."""
return sum(A[i - 1] for i in summing_set) | 2fa61493d4abd07cf24670a56d4a56d08b5a602b | 74,612 |
def get_all_food_feed(id_food:int):
"""
Method to get all feed for food run
:return: food_models.FeedFood
"""
feeds = food_models.FeedFood.objects.filter(food__id=id_food)
return feeds | 07e6675a6e72a48231137b94b9223978692c3eba | 74,613 |
def convert_va(mpl_va):
"""Convert mpl vertical alignment word to equivalent HTML word.
Text alignment specifiers from mpl differ very slightly from those used
in HTML. See the VA_MAP for more details.
Positional arguments:
mpl_va -- vertical mpl text alignment spec.
"""
if mpl_va in VA_M... | 4c52d44cfc7de09d1b4a76404751ccbdcbee35c9 | 74,614 |
def camel_split(string):
# test: (str) -> str
"""
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees')))
('the', 'Birds', 'And', 'The', 'Bees')
>>> print('(%s)' % ', '.join("'%s'" % s for s in camel_split('theBirdsAndTheBees123')))
('the', 'Birds', 'And', 'The', 'Be... | f7d0d27e25a26b6e4135bb6d83dc35f5d1cd2374 | 74,615 |
def project_tags(project: Config) -> Tags:
"""Construct default tags for a project.
:param project: PipeFormer project
:return: Tags
"""
return Tags(pipeformer=project.name) | 5544b5457df069b051f2e462944db311702301cd | 74,616 |
import warnings
def recognize(models: dict, test_set: SinglesData):
""" Recognize test word sequences from word models set
:param models: dict of trained models
{'SOMEWORD': GaussianHMM model object, 'SOMEOTHERWORD': GaussianHMM model object, ...}
:param test_set: SinglesData object
:return: (lis... | 29d59123cf751dc02dcaa2e3cbff67cd8acd71ac | 74,619 |
def cct_7_3x1_32_c100(
img_size=32,
positional_embedding='learnable',
num_classes=100,
**kwargs):
"""cct_7_3x1_32_c100"""
return cct_7(
'cct_7_3x1_32_c100',
kernel_size=3,
n_conv_layers=1,
img_size=img_size,
positional_embedding=positional_... | 230ca2ca212ce69574db94512c3161e79f70df66 | 74,620 |
def get_task_status(task_id):
"""
Given a task ID, return a dictionary with status information.
"""
task = AsyncResult(task_id)
status = {
'successful': task.successful(),
'result': str(task.result), # result can be any picklable object
'status': task.status,
'ready'... | dc7e384f5efe804c00d6adeade6d1371f8366b0b | 74,621 |
import requests
import tqdm
def stock_gdfx_free_holding_teamwork_em() -> pd.DataFrame:
"""
东方财富网-数据中心-股东分析-股东协同-十大流通股东
https://data.eastmoney.com/gdfx/HoldingAnalyse.html
:return: 十大流通股东
:rtype: pandas.DataFrame
"""
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = ... | fdc1bce46e6b1e2a719c9a0e995c019d5a82bd8e | 74,622 |
from typing import Union
from typing import Iterable
from typing import Callable
from typing import Type
def enforce_subclasses_call(
methods: Union[str, Iterable[str]], attr: str = "_enforce_subclasses_call_cache"
) -> Callable[[Type], Type]:
"""Class decorator which enforces that if any subclasses define on... | c2e8c44d98dfb32ca96ae59ba2ce014b8799c7b9 | 74,623 |
def calculate_carbon_stage(
stage: FlightStage,
geod: pyproj.Geod,
non_co2_effects_scaling: float = 1.9,
) -> FlightStageCarbonSummary:
"""Calculate flight emissions for an array of distances in km
To account for the non-CO2 climate effects of aviation, the UK Government (in 2018)
recommends ap... | 53c3a1af434b88bd610f45690efb16bf345730f6 | 74,624 |
def init_benchmarks(n_values=None):
"""Initialize the strings we'll run the regexes against.
The strings used in the benchmark are prefixed and suffixed by
strings that are repeated n times.
The sequence n_values contains the values for n.
If n_values is None the values of n from the original benc... | 3333d705b16b1760129591d3ef873aad51e1a336 | 74,625 |
import re
import base64
def predict():
"""
Called when user presses the predict button.
Processes the canvas and handles the image.
Passes the loaded image into the neural network, and it makes
class prediction.
"""
# Local functions
def crop(x):
_len = len(x) - 1
for ... | c126ac6a025d8a9216d85f67ec8d231a2e76fa50 | 74,627 |
def split(pattern,
string,
max_split=0,
remove_empty_matches=False,
use_regex=False):
"""
Splits the given string by the specified pattern. The return character (\\n)
is not a natural split pattern (if you don't specify it yourself).
This function ignores escape s... | 5dab1389d06c1600b490b3f44a6cad566f52f706 | 74,628 |
def snake_to_camel(snake_case_string: str) -> str:
"""
Takes in a `snake_case` string and returns a `camelCase` string.
:params str snake_case_string: The snake_case string to be converted
into camelCase.
:returns: camelCase string
:rtype: str
"""
initial, *temp = snake_case_string.spli... | 4ef8fa72580739dbedfbac5bf9f95247f5ea69c3 | 74,629 |
def read(filename):
"""Read file content."""
with open(filename) as f:
return f.read() | 6bb989d523507a2902a6a068132ca99e78914ecb | 74,630 |
def gan(ddgan):
"""
Create DD-GAN
Args:
ddgan (Module): The ddgan module
Returns:
GAN: The GAN
"""
# Number of neighbour and self time values.
# Corresponds to n = n_b, n_a, n_self
added_dims = [1, 1, 3]
kwargs = {
"nsteps": np.sum(added_dims),
"ndi... | aa6866d8d0a81092938cafc121fd6da7b9347374 | 74,631 |
def flattenByRow(A):
""" Turn matrix into vector by row. Out of place operation
"""
B=A.copyrm
return B.block.bind(0,1,A.rowlength*A.collength) | 173155755c99ce5ade1989f8d16d1b6fd6ed4223 | 74,632 |
def reference_job(link, email) :
"""
Request the referencing of a website.
"""
print("referencing page %s with email %s"%(link,email))
# get final url after possible redictions
try :
link = url.crawl(link).url
except :
return 0
# create or update domain data
domain ... | 164307960aae5e3219f4a52b60c41801ab022997 | 74,633 |
from typing import Optional
def is_long_flag_reason(flag: str) -> Optional[str]:
"""
Checks if the given string is a valid long flag.
:param flag: The string to check.
:return: None if it is a valid long flag,
or the reason if not.
"""
# Long flags must start wit... | 00b9ee06f6ca8afe5c6de02f5550136d2f77b1d2 | 74,634 |
import hashlib
def _memorize(func):
"""Decorator to cache the given function's output.
"""
def _wrapper(self, *args, **kwargs):
"""Wrapper to cache the function's output.
"""
if self.use_cache:
cache = load_cache(self.cache_filename)
original_key = ':'.join([
self.__class__.__... | b04c3aa416e78a21f7e3e68fb80c2b625a6de06e | 74,635 |
def evaluate_with_new_model(round, training_info, model_x, test_images, test_label):
"""
It will evaluate the new model weight which is aggregrated from all client model.
:param what round is now
:param dictionary contains training detailed settings
:param the model for evaluation
:param origina... | 56aa794258b6fb4117abcf6d4dcb12fdb9e930de | 74,636 |
def _get_is_int(validator):
"""Create a integer type checker with numpy support for the given validator."""
# pylint: disable=unused-argument
def is_int(checker, instance):
return (validator.TYPE_CHECKER.is_type(instance, 'integer') or isinstance(instance, (np.int32, np.int64)))
return is_int | 45f0cb43dde920bc4d3dfd2a114dbf98d8216896 | 74,637 |
def formatsGenres(genres_list):
""" Formats Genres for Web app template. """
genres = ""
try:
for item in genres_list:
print(item.genre_type)
except:
genres = "Unknown"
else:
for genre in genres_list:
print(genre, genres_list[-1])
if l... | e9ba9a9388ba7b19c97f1f9959c3c828d1a15219 | 74,638 |
def avg_class_accuracy(y_pred, y_test):
"""the classification accuracy averaged over the classes"""
n_classes = len(set(y_test))
class_accs = []
for c in range(n_classes):
n_correct = np.sum(y_test[y_test == c] == y_pred[y_test == c])
n_class_samples = y_test[y_test == c].size
c... | 06b10ad5a74bffce6b744557a4ab60c7fa4fd302 | 74,639 |
import json
def read_json(path: PathType) -> dict:
"""
it returns the cloth data from a file
:param path: str
:return: Dict
"""
with open(path, "r") as f:
return json.loads(f.read()) | 17a56b05586312eb7a93661eb43ae199803f07df | 74,640 |
def sum_absolute(data):
"""
Calculate the sum of abolute values of the data.
Args:
data (list): values.
Returns the sum of absolute values of the data.
"""
return sum(absolute(data)) | 1f4972174f477e66146c7e89067ee9db47d8a26b | 74,643 |
def PolynomialInQ(u, v, x):
"""
If u is a polynomial in v(x), PolynomialInQ(u, v, x) returns True, else it returns False.
Examples
========
>>> from sympy.integrals.rubi.utility_function import PolynomialInQ
>>> from sympy.abc import x
>>> from sympy import log, S
>>> PolynomialInQ(S(... | b890a9e7788b56b62dd01d4b7e18c6ded33128c1 | 74,644 |
from typing import Optional
from typing import Union
from pathlib import Path
def single_image_nexus(
data_file: Optional[Union[Path, str]],
tristan_nexus: Optional[Union[Path, str]],
write_mode: str = "x",
) -> str:
"""
Create a NeXus file for a single-image or a stationary pump-probe dataset.
... | 643d288853ed2089fb462e30277871986eacbb06 | 74,645 |
def parse_int_list(text):
"""Parse a string into a list of integers
For example, the string "1,2,3,4" will be parsed to [1, 2, 3, 4].
Parameters
----------
text : str
String to parse
Returns
-------
List[int]
Parsed integer list
"""
result = [int(i) for i in te... | f83b21c9038e5ea8eb2c0d53ad94479cab9258f3 | 74,646 |
def unpack3Dforces(file, D=1, U=1):
"""
Unpacks ASCII files containing the following columns: non-dimensional time, time step, fx, fy, fz, vx, vy, vz.
fx, fy, fz are the pressure forces and vx, vy, vz the viscous forces (not returned with this function).
:param file: File to read from.
:param D: Cha... | 657b1f19d7b5979d1184d1a8c280085426209662 | 74,647 |
def index():
"""Default page that includes details for recent shows"""
database_connection.reconnect()
try:
if "recent_days_ahead" in config["settings"]:
days_ahead = int(config["settings"]["recent_days_ahead"])
else:
days_ahead = DEFAULT_RECENT_DAYS_AHEAD
except... | 4d350c424415e90e901ecb16a29b65d912918393 | 74,649 |
def onesided_2_twosided(data):
"""Convert a two-sided PSD to a one-sided PSD
In order to keep the power in the twosided PSD the same
as in the onesided version, the twosided values are 2 times
lower than the input data (except for the zero-lag and N-lag
values).
::
>>> twosided_2_ones... | 092e8ce15b1d0f9fe80acc708c9b73c899aa74f9 | 74,650 |
import logging
def _read_html(table):
"""Parse text into data frame."""
decimal_point = "@"
if decimal_point in table:
logging.info('%s in table: """%s"""', decimal_point, table)
beam.metrics.Metrics.counter(_NS, "Decimal point in table").inc()
return pd.read_html(
table,
flavor="html5lib"... | 92339fd7d5ad1bbaf8ff81c93fdaa3898a8c9db9 | 74,651 |
def recursive_parse_xml_to_dict(xml):
"""
Recursively parses XML contents to python dict.
We assume that `object` tags are the only ones that can appear
multiple times at the same level of a tree.
Args:
xml: xml tree obtained by parsing XML file contents using lxml.etree
Returns:
Python ... | a91885c1317fe3ee8fb50b4ad021ed05e900d79c | 74,652 |
def transformMinima2envelop(pageNd,dClusterWithTL):
"""
"""
lClustersPoly=[]
for row in dClusterWithTL:
# bb = ShapeLoader.contourObject(dClusterWithTL[row]).envelope
# if not bb.is_empty:
# cellNd = etree.Element('COL')
# pageNd.append(cellNd)
# cell... | b4d3cfee22c544fb40f8d07a3690444c54174600 | 74,653 |
from datetime import datetime
def paid_already(target_due_date):
"""return True if info in local copy of six_count.ods shows paid, else False"""
is_paid = False
curr_date = datetime.today().date()
# read data file
data = pyexcel_ods.get_data('/home/pi/data/six_count.ods')
# reverse rows and... | 63d72ee8cef39ed1877484605f1251edd48d397e | 74,654 |
def rfi_stations(fqs, lsts, stations=None, rfi=None):
"""
Generate an (NTIMES,NFREQS) waterfall containing RFI stations that
are localized in frequency.
Args:
lsts (array-like): shape=(NTIMES,), radians
local sidereal times of the waterfall to be generated.
fqs (array-like):... | 20001dde95275c2a2ff360e4df8c1de83b5bfa7f | 74,655 |
def retroactive_resolution(coefficients: np.matrix, vector: np.array) -> np.array:
"""
This function performs a retroactive linear system resolution
for triangular matrix
Examples:
2x1 + 2x2 - 1x3 = 5 2x1 + 2x2 = -1
0x1 - 2x2 - 1x3 = -7 0x1 - 2x2 = -1
0x1 + 0x2... | c007c746557d60c7ddcb16365eaba11432cf4f93 | 74,656 |
def AstToParsedExpr(a):
"""AstToParsedExpr(object a) object, str
AstToParsedExpr converts an Ast to an protobuf ParsedExpr value.
"""
return go.Ptr_expr_ParsedExpr(handle=_cel.cel_AstToParsedExpr(a.handle)) | e93a06af20bfd2d901f6847405c107ff7674b0ad | 74,657 |
import httpx
from typing import Optional
def create_github_client(
*, http_client: httpx.AsyncClient, oauth_token: Optional[str] = None
) -> GitHubAPI:
"""Create an HTTPx GitHub client.
Parameters
----------
http_client : httpx.AsyncClient
The httpx client.
oauth_token : str, optional... | 68f43d620788109402c349e8e4059614d5325dd2 | 74,658 |
def _apparent_position_in_true_coordinates(skycoord):
"""
Convert Skycoord in GCRS frame into one in which RA and Dec
are defined w.r.t to the true equinox and poles of the Earth
"""
jd1, jd2 = get_jd12(skycoord.obstime, 'tt')
_, _, _, _, _, _, _, rbpn = erfa.pn00a(jd1, jd2)
return SkyCoord(... | 919cc41a4500acdcea79a68e0b1769064c07c7f2 | 74,659 |
def to_python(value):
"""Converts Whispy Lispy types to Python types """
return value.values[0] | 1ffd36443e04b8aeb823e8eb932e4abf888975a2 | 74,660 |
def load_config(*paths, **kwargs):
"""
Loads config for given path and provider type.
:param paths: Tuple consisting of nested level path
:type paths: tuple
:keyword default_variables: Variables to be applied during template
evaluation
:type default_variables: dict
:keyword provider_typ... | ba394ed2a8c8b225de028fffb66fdb6797413ed0 | 74,661 |
def tobs():
#Docstring
"""Return a list Temperature Observations for the previous year."""
#Find dates
latest_date=session.query(Measurement.date).order_by(Measurement.date.desc()).first()
latest_date=latest_date[0]
year_ago=dt.datetime.strptime(latest_date,"%Y-%m-%d") - dt.timedelta(days=366)
... | 2fd0c837eb36293f0ff09f5166a9a2e8bbce3b6c | 74,663 |
def estimate_demand(regions, option, global_parameters,
country_parameters, timesteps, penetration_lut, smartphone_lut):
"""
Estimate demand metrics including:
- Total number of basic phone and smartphone users
- Total data demand (in Mbps per square kilometer)
- Total revenue (net p... | cc181ad68df5650bd744ab4acba700b9da975e19 | 74,664 |
def call_api(query, service):
""" calls api and returns result """
result = service.data().ga().get(**query).execute()
return result | 9816a2e4a0e38d25a376eb43325bf51982a921ce | 74,665 |
def d(**kwargs):
"""Helper of creating a config dict."""
return ml_collections.ConfigDict(initial_dictionary=kwargs) | 593854ef64229456e7b50cf4bcf2d4dacf2e7efa | 74,666 |
def load_json(filename):
"""
Load json data from a filename
"""
print 'Loading data from {0}.json...'.format(filename)
with open('{0}.json'.format(filename)) as f:
return json.load(f) | c22b345b5c8b3352146673a30cee7c705271b1d0 | 74,667 |
def generate_parser(start_symbol, productions, error_examples):
"""Generates a parser from grammar, and applies error_examples.
Arguments:
start_symbol: the start symbol of the grammar (a string)
productions: a list of parser_types.Production in the grammar
error_examples: A list of (source token... | 41e7bf037913302719c812f4c9c22dba4a0bb26c | 74,668 |
import tqdm
def multi_thread_tqdm(task, data, workers: int = 20) -> list:
"""
多线程任务进度条
@param task: 任务函数
@param data: 需要处理的数据,可迭代对象
@param workers: 线程数
@return: 任务函数返回结果的列表
"""
executor = ThreadPoolExecutor(max_workers=workers)
result = list(tqdm(executor.map(task, data), total=len... | 65fa431fefab1fe70c134e08cd3b990538ad3b4b | 74,670 |
import psutil
def current_memory_fraction():
"""Quick function to get a basic fraction of memory being used."""
mem_use = psutil.virtual_memory()
return mem_use.used / mem_use.total | cf4513ab6ba30d3251673d2c9173bf238856fbdd | 74,671 |
from datetime import datetime
def datetime_handler(obj):
"""
JSON serializer for objects not serializable by default json code
"""
if isinstance(obj, datetime.datetime):
return obj.isoformat()
raise TypeError("Unknown type") | 9712447929bcf189e308054a8597d9e2e884b9fa | 74,672 |
def get_precision(results_dic_dataset, interest, options,
fun=lambda x, y: y/x):
""" Get average precision of a function on the dataset. """
names, score = get_results(results_dic_dataset, options, function=fun)
inter = get_interest(names, interest)
return average_precision_score(inter... | 3488ae359c7ea39ae8e4380e411c0091bf8208e2 | 74,674 |
import contextlib
def compute_patch_embeddings(
samples,
model,
patches_field,
embeddings_field=None,
force_square=False,
alpha=None,
handle_missing="skip",
batch_size=None,
num_workers=None,
):
"""Computes embeddings for the image patches defined by ``patches_field``
of th... | be2b2ebeeef87e27687fd4ddd5ced0b6b6c263f2 | 74,675 |
def build_popularity_dict(game):
"""Return a Dict of how proportionally popular each player count is"""
popularity = {}
for x in game.player_suggestions:
if (
x.numeric_player_count >= game.min_players and
x.numeric_player_count <= game.max_players
):
... | 9718fca6f6ccb76f378e088c2aa2e16387f2383a | 74,676 |
def aggTs(year, unit, interval, mean=True, dir_name='H'):
"""
This function
1. resamples each profile over interval
2. gets interval mean (if True)
aggfunc must be a list and can be any standard statistical descriptor such as mean, std, describe, etc.
interval can be 'D' for calendar d... | f54592e1666e8b58ba7c750108060075983149df | 74,677 |
def remove_triple_junctions(G):
""" Remove triple junction from network
Parameters
----------
G : nx.graph
Graph
Returns
-------
G : nx.graph
Graph
"""
# Assertions
assert isinstance(G, nx.Graph), "G is not a NetworkX graph"
# Calculation
... | 1f6535b0e4cf9d4d21687ed97365a5783e40183c | 74,678 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_qradar_asset package"""
reload_params = {"package": u"fn_qradar_asset",
"incident_fields": [],
"action_fields": [],
"function_params": [u"incident_id"],
... | 983c1395a8355dbc973bce47145db4c095baafd9 | 74,679 |
def to_python(path):
"""Translates a `Path` object to a string of the form `MontyCarlo.module1`.
"""
res = path.name
while path != path.parent:
path = path.parent
res = path.name + "." + res
res = res[1:][11:]
return res + ".*" if res != "" else "*" | 24b7a669e0fc1e40113044f2da79e29d42f04c81 | 74,680 |
from typing import Tuple
def find_line(code: str, cursor_pos: int) -> Tuple[str, int, int]:
""" What is the full line, line_cursor and offset at the cursor position
in a multi-line string?
"""
if cursor_pos is None:
cursor_pos = len(code)
line, offset = line_at_cursor(code, cursor_pos)... | b0545d6ca5c51e2e1edc5f2199de12b0d54f6a01 | 74,681 |
from typing import Dict
def task_ttest_whole_brain_fishers() -> Dict:
"""
t-test the fisher transformed correlations.
"""
def create_task(images: PathLike, out_path: PathLike, name: str) -> dict:
"""
Allows this task to easily be generalizable.
Parameters
----------
... | 0a8079f6ff02732d52aff5906bd774caea6ee7d7 | 74,682 |
def cal_error(array, typeb = 0):
"""Calculate all errors of the input array.
Args:
array (numpy.array): The data measured directly for a single
physical datus. We use the mean value as the reliable
measurement for that and get type-A error meanwhile.
typeb (float): The t... | f0fc8832f730189e4f2a0597e1342f94ed2d8717 | 74,683 |
def plot_tokamak_source_3D(
tokamak_source,
ax=None,
quantity=None,
angles=[0, 0.5 * np.pi],
colorbar=None,
**kwargs,
):
"""Creates a 3D plot of the tokamak source.
See https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html#matplotlib.pyplot.plot
for more arguments.
... | f014da840fd72de4deacce542ef141e6d66740d6 | 74,684 |
def navigation(obj):
"""
Goes through json file and shows its structure
"""
if isinstance(obj,dict):
print()
print("This object is dictionary")
keys = list(obj.keys())
print()
print(keys)
print()
user_choice = input("Here are keys of this dictionar... | a2b3b556b38082ba06e6f3d1b3ce79d9f0c4de3e | 74,685 |
from opteryx.third_party.pyarrow_ops import align_tables
import pyarrow
import numpy
def _cross_join(left, right):
"""
A cross join is the cartesian product of two tables - this usually isn't very
useful, but it does allow you to the theta joins (non-equi joins)
"""
def _chunker(seq_1, seq_2, siz... | 0f666466b69e8ca66c4ed66aee9b1f661f6cfbff | 74,686 |
def parse_writing_conditions(writing_conditions):
""" Given writing condition file path, returns a dictionary which have writing condition
of each page image.
Returns
------
(dict): dictionary with key as page image name and value as writing condition.
"""
with open(writing_conditions) a... | 7e9306818e672a01f1dc7faa2f551a50293c8f96 | 74,687 |
from typing import List
def parse_dn_tree(dn: str, restrict_types: List[str] = None) -> List[RDN]:
"""A DN is a sequence of relative distinguished names (RDN) connected by commas, For examples:
we have a dn = "CN=Jeff Smith,OU=Sales,DC=Fabrikam,DC=COM", this method will parse the dn to:
>>> parse_dn_tree... | 98b1505ed86e709d7322c065c038ed04e493c7ff | 74,689 |
def device_mapper(os_type: str, proto: str = "netmiko"):
"""
map an os type to a netmiko device_type
:params os_type: type str
:params proto: type str, default "netmiko"
:returns: device_type string
"""
if proto == "netmiko":
device_types = {
"ios": "cisco_ios",
... | 81ad4c4dd86c7e6930cf0fb070681872783a5fb8 | 74,690 |
def strip_to_category(category):
"""Strip prefix and postfix from category link.
Parameters
----------
category : str
Returns
-------
stripped_category : str
String with stripped category
"""
if category.startswith('[[Kategori:'):
category = category[11:-2]
eli... | d4a274757aed9b3fbe2e9c5c187949a19b53e3ad | 74,691 |
def transformImage(img, u, v, box=None, method='bilinear'):
""" transformImage
@brief: Homography perspective transform from u to v
@[in] img: numpy image MxNx3
@[in] u: src 4 corners 3xn
@[in] v: dest 4 corners 3xn
@[in] method: interpolation method:nn/bilinear
@[out] o: transformed im... | 12675394cf4d6e1bdc89db78d9b392547f5bd475 | 74,692 |
import struct
def read_rom_address_list(rom, offset, count):
"""Reads a list of addresses in Wolf3D's weird storage method.
01 35 03 CC 00 -> 0xc0335
"""
rom.seek(offset)
offsets = []
for x in range(count):
zb = rom.read_ubyte()
assert 1 <= zb <= 3, 'zb is {}'.format(zb)
... | 4e9b0fff0d64a03901d4731c8165bb34fd98e8b5 | 74,694 |
def error(string):
""" An error message, bold and red """
return ''.join([BOLD, RED, string, RESET_ALL]) | a3a9e6ad49d7a93048d6230b0e35554866137124 | 74,696 |
def parse_block_control(state, outer_indent_level):
"""
precondition: `state.pos` is at a backslash in a block
postcondition: `state.pos` is either at the first character following the last
argument's closing brace, or at the start of the next non-empty line for
indented environments, or at ... | 97cd1d485a10dca0b9580a42e9227cec3792696b | 74,697 |
def overclock(name):
"""Handler for region 32."""
indices = {
'overvolt_protection': (31, 32), # Overvolt protection bit
'bits_0_to_30': (0, 31) # Unknown/Unused
}[name]
__overclock = get('overclock', 'binary')
return __overclock[indices[0]: indices[1]] | 1437a932b3364aade235e166f7231cb4bf284176 | 74,698 |
def get_reconstruction_metrics():
"""Gets a list with reconstruction metrics.
Returns:
list[Metric]: A list of metrics.
"""
return [PeakSignalToNoiseRatio(), StructuralSimilarityIndexMeasure()] | a80ffecc21920259778c5f95326bbcbd4968410d | 74,700 |
import json
import traceback
def request(request, agent_id):
"""
Returns an SAI description for a given a problem state according to the
current knoweldge base. Expects an HTTP POST with a json object stored as
a utf-8 btye string in the request body.
That object should have the following fields:... | 4f817526296ffe79cada0019789071db46f68204 | 74,702 |
def main():
""" Run the RunPostAnalyzer.py program """
parser = argparse.ArgumentParser(description="Script to run the PostAnalyzer on a folder for the difficulty categorizations: all, difficult, medium and rigid and output the results a results folder. The absolute path to the PostAnalysis.py program can be sp... | c41f1f0da7c1240461cc8050ece686c75af8c854 | 74,703 |
def clean_for_doc(nb):
"""
Cleans the notebook to be suitable for inclusion in the docs.
"""
new_cells = []
for cell in nb.worksheets[0].cells:
# Remove the pylab inline line cells.
if "input" in cell and \
cell["input"].strip().startswith("%pylab inline"):
... | 2cec552f8c2d2ae4437f7460db4f8bd4919c9f65 | 74,704 |
def download(ticker, filename=None, period='1y', interval='1d', start='', end=''):
"""
https://yahooquery.dpguthrie.com/
:param ticker: stock symbol
:param period: valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max
:param interval: valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3... | dcbf36bc360afe3e09f80a5fdf28d345a04eca9c | 74,705 |
import types
def filter_emoji_column(df, col="text"):
"""
df (DataFrame|list)
returns a dataframe with text not contain emoji's removed
"""
if isinstance(df, (list, filter, types.GeneratorType)):
return (filter_emoji_column(d) for d in df)
df = df.loc[df[col].apply(contains_emoji)]
... | cf188ad05fd826fe993795b7d135d8555b0e275f | 74,706 |
from ..viewers.trajectory_viewer import TrajectoryViewer
def draw3d(traj, **kwargs):
"""TrajectoryViewer: create a trajectory visualization
Args:
**kwargs (dict): kwargs for :class:`moldesign.widgets.trajectory.TrajectoryViewer`
"""
traj._viz = TrajectoryViewer(traj, **kwargs)
return traj... | 0a6ed3495d1057787dc8f0d2f2d78c65c4f49083 | 74,707 |
def create_inputs_model_and_nodes():
"""Create and return input data, a dispatch model and a node dict"""
dm = model_control.DispatchModel()
dm.update_model_configuration(
{"path_folder_input": "tests/csv_files/",
"fuel_cost_pathway": "middle",
"start_time": "2017-01-01 00:00:00",
... | b4c9e3ae6784ca82577f68af276f0c7627adfdbe | 74,708 |
def connectivity_graph(zma, dummy=False,
rqq_bond_max=3.5, rqh_bond_max=2.6, rhh_bond_max=1.9):
""" Convert a Z-Matrix to a molecular connectivitiy graph.
:param zma: Z-Matrix
:type zma: automol Z-Matrix data structure
:param rqq_bond_max: maximum distance between hea... | 8ddf50aa734601e6a321c7b0d9a5fa30d3f32bcb | 74,709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.