content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from typing import Union
from typing import Optional
import numpy
from datetime import datetime
def extract_sicd(
img_header: Union[ImageSegmentHeader, ImageSegmentHeader0],
transpose: True,
nitf_header: Optional[Union[NITFHeader, NITFHeader0]] = None) -> SICDType:
"""
Extract the best... | 536c95597ec426da168d3ca05317c9c8515dc73c | 3,659,300 |
import torch
from typing import Optional
def ppo_clip_policy_loss(
logps: torch.Tensor,
logps_old: torch.Tensor,
advs: torch.Tensor,
clipratio: Optional[float] = 0.2
) -> torch.Tensor:
"""
Loss function for a PPO-clip policy.
See paper for full loss function math: https://arxiv.org/abs... | 203c4072e1c04db9cceb9fa58f70b9af512ffb1c | 3,659,301 |
def reconstruct_modelseed_model(genome_id, model_id, template_reference=None):
""" Reconstruct a draft ModelSEED model for an organism.
Parameters
----------
genome_id : str
Genome ID or workspace reference to genome
model_id : str
ID of output model
template_reference : str, op... | 3547088922fe2df2f81622a8065368227a1948bc | 3,659,302 |
from timeseries import timeseries, loadDBstation
from datetime import datetime
def tide_pred_correc(modfile,lon,lat,time,dbfile,ID,z=None,conlist=None):
"""
Performs a tidal prediction at all points in [lon,lat] at times in vector [time]
Applies an amplitude and phase correction based on a time serie... | 883ac85787a700a785a0b0a08f521aaf6ad821d1 | 3,659,303 |
def generate_new_filename(this_key):
"""Generates filename for processed data from information in this_key."""
[_, _, source_id, experiment_id, _, _] = this_key.split('.')
this_fname = THIS_VARIABLE_ID+'_'+experiment_id+'_'+source_id
return this_fname | 2e9edb4730257e8fc4c68bbcbb32cce133041bb8 | 3,659,304 |
def get_connection(user, pwd):
""" Obtiene la conexion a Oracle """
try:
connection = cx_Oracle.connect(user + '/' + pwd + '@' +
config.FISCO_CONNECTION_STRING)
connection.autocommit = False
print('Connection Opened')
return connection
... | ba7ca784f0778fb06843e3c68af63e6348406735 | 3,659,305 |
from re import T
def _generate_select_expression_for_extended_string_unix_timestamp_ms_to_timestamp(source_column, name):
"""
More robust conversion from StringType to TimestampType. It is assumed that the
timezone is already set to UTC in spark / java to avoid implicit timezone conversions.
Is able t... | 22a1220c260406c82ede127b87fa23356d2f5192 | 3,659,306 |
import xmlrpclib
import getpass
def get_webf_session():
"""
Return an instance of a Webfaction server and a session for authentication
to make further API calls.
"""
server = xmlrpclib.ServerProxy("https://api.webfaction.com/")
print("Logging in to Webfaction as %s." % env.user)
if env.pas... | e6ebe8ad51cdf4a33fcfa70e5f1983ede6f66d31 | 3,659,307 |
from typing import Dict
from typing import List
def _unpack_school_column_aliases() -> Dict[str, List[str]]:
"""
Unpack the known aliases for lookup table of alias_column_name -> schema_column_name.
:return: lookup table.
:raises: ValueError if an alias has more than one mapping to a schema column
... | 3c6cff79c2ce50dff655bee7ac1626277b00e155 | 3,659,308 |
def suntimecorr(ra, dec, obst, coordtable, verbose=False):
"""
This function calculates the light-travel time correction from
observer to a standard location. It uses the 2D coordinates (RA
and DEC) of the object being observed and the 3D position of the
observer relative to the standard location. ... | c214a065e41ddc85713ab351e537ab08d521f090 | 3,659,309 |
from typing import Union
from typing import Tuple
from re import VERBOSE
import re
def normalize_address(address: str, asHex: bool=False) -> Union[Tuple[str, str], Tuple[str, bytes]]:
"""Takes an address as raw byte or id__ and provides both formats back"""
try:
# convert recipient to raw if provided ... | ce574f1b1c5231b97a444d3f3e767016cd879d6e | 3,659,310 |
def get_welcome_response():
""" Prompt the user for the prayer
"""
session_attributes = {}
card_title = "Welcome"
speech_output = "What would you like me to pray with you? I can pray the Rosary and the Divine Mercy Chaplet."
reprompt_text = "What would you like me to pray with you?"
sho... | 9bcf20bcc2afd96e1b3b93abb47ba654e2051884 | 3,659,311 |
from typing import Optional
import math
import time
import requests
import textwrap
def get_news(
limit: int = 60,
post_kind: str = "news",
filter_: Optional[str] = None,
region: str = "en",
) -> pd.DataFrame:
"""Get recent posts from CryptoPanic news aggregator platform. [Source: https://cryptopa... | 8535965e4058ce4bd76b2ef44a060e4083f2128e | 3,659,312 |
def login():
""" Display log in form and handle user login."""
email = request.args.get('emailLogin')
password = request.args.get('passwordLogin')
user = User.query.filter(User.email == email).first()
if user is None or not check_password_hash(user.password, password):
flash('Invalid ... | 9368ccc0e8d02baa58ce434e37e7ca7a2deb53e2 | 3,659,313 |
import _queue
def model_from_queue(model):
""" Returns the model dict if model is enqueued, else None."""
return _queue.get(model, None) | 46eea9b8a218181b000308b080a8c9dad7e866b2 | 3,659,314 |
import codecs
import os
import re
def get_email(package):
"""
Return package email as listed in `__email__` in `init.py`.
"""
init_py = codecs.open(os.path.abspath(os.path.join(package, '__init__.py')), encoding='utf-8').read()
return re.search("^__email__ = ['\"]([^'\"]+)['\"]", init_py, re.MULTI... | e07a2460f0229c16853ba09cf88e59b95659ee77 | 3,659,315 |
def get_class_name(obj, instance=True):
"""
Given a class or instance of a class, returns a string representing the
fully specified path of the class.
Parameters
----------
obj : object
An instance of any object
instance: bool
Indicates whether given object is an instance o... | 3a7ebd1fb2682ec5dff6d42cd2cccf918d67f9a0 | 3,659,316 |
from sys import path
def pipeline(opts):
"""Construct the pipeline"""
outdir = path.join(opts.outdir, opts.cancer)
pTCGADownload.input = [opts.snpmani]
pTCGADownload.args.nthread = opts.nthread
pTCGADownload.args.token = opts.token
pTCGADownload.config.export_dir = outdir
pTCGADownload.ca... | e0475e459d7eb403c2cc292682d956acb4dfb4f0 | 3,659,317 |
def mol_to_smiles(molecule, isomeric=True, explicit_hydrogen=True, mapped=True):
"""
Generate canonical SMILES with RDKit
Parameters
----------
molecule: RDKit Chem.rdchem.Mol instance
The molecule to generate SMILES for
isomeric: bool
If True, SMILES will have isomeric informat... | 1727dd4260fda0e9b741dab2b35c66562a8ee007 | 3,659,318 |
def _plot_events_nday(ax, grid, events, scale_factor=1.0):
"""
Plot a map of the total number of days spent in dry spell events.
Parameters
----------
ax : <matplotlib.axes.Axes> instance.
The axes to which the map will be drawn.
grid : <geo_grid.LandGrid> instance
Object descr... | dea821d98afe95790742636408b22b4c4fdc9688 | 3,659,319 |
def rank_transform(arr: np.ndarray, centered=True) -> np.ndarray:
"""
Transform a 1-dim ndarray with arbitrary scalar values to an array with equally spaced rank values.
This is a nonlinear transform.
:param arr: input array
:param centered: if the transform should by centered around zero
:retu... | d6d4cbf1e191c1fa61e58309d478547f88f0550f | 3,659,320 |
from datetime import datetime
def edit_post(id, alias):
"""Edit an existing post.
User has to be logged in and be either:
- Author of the post
- Editor (role)
- Administrator (role)
"""
post = Post.query.get_or_404(id)
if current_user != post.author and not (
current_user.has_... | 038b5f15125bd2263f8ea6a677f3de9a22edba04 | 3,659,321 |
from matplotlib import dates
def _date_list_to_num(ifg_date_list):
"""Convert list of dates, or list of date pairs, numpy array of floats
for 'days since 1970'
Handles both strings and datetimes
"""
arr = np.array(ifg_date_list)
if isinstance(arr.ravel()[0], str):
return dates.datestr... | 20171703003227307b971e68f48e03d478c5fcf5 | 3,659,322 |
import os
def get_font():
"""
Sets up a font capable of rendering the characters
"""
path = os.path.join(os.getcwd(), 'scripts', 'assets', 'fonts', 'NotoSansCJKjp-Regular.otf')
return font_manager.FontProperties(fname=path) | 7b1e532de6c8e68cb62bbde0e8dc67fb1ec5bdf9 | 3,659,323 |
def maxindices(l):
"""
Get indices for all occurences of maximal element in list
:param l:
:return:
"""
max_indices = []
max_value = l[0] #Assume un-exhaustible iterator
for i, v in enumerate(l):
if v > max_value:
max_value = v
max_indices = [i]
el... | b2f155fa97455c0327b2717591ebea2176773012 | 3,659,324 |
def get_grid_extents(data, edges=True):
"""
Get min and max lat and lon from an input GEOS-Chem xarray dataset or grid dict
Args:
data: xarray Dataset or dict
A GEOS-Chem dataset or a grid dict
edges (optional): bool
Whether grid extents should use cell edges instead... | c8cbef8b0dc3f6ce9c009955c2eff88fd5011ded | 3,659,325 |
def millisToNanos(millis):
"""
Converts milliseconds to nanoseconds.
:param millis: (long) - The long milliseconds value to convert.
:return: (long) QueryConstants.NULL_LONG if the input is equal to QueryConstants.NULL_LONG. Throws
DBTimeUtils.DBDateTimeOverflowException if the input is too la... | 4f659a6d994551c0ce72875009d688cb7c91571d | 3,659,326 |
def recursive_seed_part(
graph,
parts,
pop_target,
pop_col,
epsilon,
method=bipartition_tree,
node_repeats=1,
n=None,
ceil=None
):
"""
Returns a partition with ``num_dists`` districts balanced within ``epsilon`` of
``pop_target`` by recursively splitting graph using recur... | 8d2517e74d8726696d865ea4993a10602af74450 | 3,659,327 |
def codegen_reload_data():
"""Parameters to codegen used to generate the fn_carbon_black_cloud_devices package"""
reload_params = {"package": u"fn_carbon_black_cloud_devices",
"incident_fields": [],
"action_fields": [],
"function_params": [u"carbon_b... | 0f116dd5c9f7496af86dde2afbdd3442904dc40f | 3,659,328 |
def validate_investment_amount(investment_amount, intent_request):
"""
Validates the investment_amount provided by the user.
"""
# Validate the investment_amount should be equal to or greater than 5000.
if investment_amount is not None:
investment_amount = parse_int(
investment_... | 6f645d196e452377f4c16ae585ecc113ae5997b0 | 3,659,329 |
def new_id():
"""
Generates new bson ObjectId
"""
return str(ObjectId()) | aa02c802abf937720119f9843e55395d485b11c1 | 3,659,330 |
import lumapi
import pathlib
import json
def gc_sweep(
session=None,
draw_function=gc2d,
dirpath=CONFIG["workspace"],
overwrite=False,
run=True,
base_fsp_path=str(CONFIG["grating_coupler_2D_base"]),
**kwargs
):
""" grating coupler sweep
grating_coupler_2D_base optimizes Transmissi... | ae22a103adb2d440f25b14eac1d681d591237b67 | 3,659,331 |
def stem(word, stemmer=PORTER, **kwargs):
""" Returns the base form of the word when counting words in count().
With stemmer=PORTER, the Porter2 stemming algorithm is used.
With stemmer=LEMMA, either uses Word.lemma or inflect.singularize().
(with optional parameter language="en", pattern.en... | 71ac3a3ee30a226fcf13b2d4a3288003feeb7c3e | 3,659,332 |
def verify_bounce_message(msg):
"""
Verify an SES/SNS bounce notification message.
"""
verifier = BounceMessageVerifier(msg)
return verifier.is_verified() | c181e82d5748ed6a310650730bc1fc94cde8e33d | 3,659,333 |
def multiples(a, b):
"""This function checks if a number is a multiple of another."""
if type(a) != int or type(b) != int:
raise Exception('Values must be integers.')
elif a == 0:
raise Exception('0 is not valid.')
elif a == b:
raise Exception('Numbers should not be the same.')
... | 3f8bccd5429b5d307c0a018b7186bd75a76e996a | 3,659,334 |
import os
import datasets
def train_gilbo(gan, sess, outdir, checkpoint_path, dataset, options):
"""Build and train GILBO model.
Args:
gan: GAN object.
sess: tf.Session.
outdir: Output directory. A pickle file will be written there.
checkpoint_path: Path where gan"s checkpoints are written. Only ... | bc018f2fd875dd267a33f1ba42cabe8a2127b861 | 3,659,335 |
def unquote_keys(data):
"""Restores initial view of 'quoted' keys in dictionary data
:param data: is a dictionary
:return: data with restored keys if they were 'quoted'.
"""
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, dict):
un... | de3802fdf0b278fcb39870f49ec7435ae5a63f38 | 3,659,336 |
def retr_amplslen(peri, radistar, masscomp, massstar):
"""
Calculate the self-lensing amplitude.
Arguments
peri: orbital period [days]
radistar: radius of the star [Solar radius]
masscomp: mass of the companion [Solar mass]
massstar: mass of the star [Solar mass]
R... | 32c0618f0e5965357fbcadd090443d0baf0e65bd | 3,659,337 |
import os
import tarfile
def main_work(indir, outdir, aux=None, hv=None):
"""
:param indir:
:param outdir:
:param aux:
:param hv:
:return:
"""
if not os.path.exists(outdir):
os.makedirs(outdir)
if hv is None:
hv_ = all_hv
else:
hv_ = [hv]
if aux i... | fecdeec5b329d3a5b8ff809e947bd234ee6808e9 | 3,659,338 |
from datetime import datetime
def calculate_current_teach_week(semester_first_week_date='2021-3-08 08:00:00'):
"""
计算当前日期所属教学周,实现思路是:当前日期所属一年中的周 - 每学期的第一周
----
param: semester_first_week_date: 学期第一周的日期,例如 '2021-3-08 08:00:00'
return: 当前教学周
"""
# 获取指定日期属于当年的第几周, 返回字符串
semester_first_we... | 01a8df84b878e192dae1b1d0d38d78fb5c19f93e | 3,659,339 |
def get_first_model_each_manufacturer(cars=cars):
"""return a list of matching models (original ordering)"""
return [cars[key][0] for key in cars] | 639cd912a68149864f4d0ff6c1b2dc7bc911052f | 3,659,340 |
import re
def get_sandbox_table_name(dataset_id, rule_name):
"""
A helper function to create a table in the sandbox dataset
:param dataset_id: the dataset_id to which the rule is applied
:param rule_name: the name of the cleaning rule
:return: the concatenated table name
"""
return '{data... | ee07d40f885cb9d6d0d34cc0215620a2572b6b5f | 3,659,341 |
def index():
"""for i in range(0, 30):
data = QuizQuestions("math", None, "en_US", 7, "normal", "This is placeholder question number " + str(i), "c", "Answer A", "Answer B", "Answer C", "Answer D", True)
db.session.add(data)
db.session.commit()"""
return render_template("quiz_index.html") | 5be34099cead47e4d339edf14bdc39519e7242f5 | 3,659,342 |
from typing import Any
def _get_invoke_function_name() -> Any:
"""
Get invoke function Name.
Returns
-------
Function Name.
"""
props = get_properties()
functionName = f"orbit-{props['AWS_ORBIT_ENV']}-{props['AWS_ORBIT_TEAM_SPACE']}-container-runner"
return functionName | 387ed3d80e3fedcee4662ec9db62622bb8393aba | 3,659,343 |
def sigmaG(a, axis=None, overwrite_input=False, keepdims=False):
"""
Compute the rank-based estimate of the standard deviation
Parameters
----------
a : array_like
Array containing numbers whose mean is desired. If `a` is not an
array, a conversion is attempted.
axis : int, opti... | 7731a1ad94f85baf02125479fc96e89a59c8b594 | 3,659,344 |
def traverse_tagged_databases(
functional_unit, method, label="tag", default_tag="other", secondary_tags=[], fg_databases=None
):
"""Traverse a functional unit throughout its foreground database(s) or the
listed databses in fg_databses, and group impacts by tag label.
Contribution analysis work... | 02edd2f9b33760a730ea7906240b48418059430c | 3,659,345 |
def graft(
repo,
ctx,
base=None,
labels=None,
keepparent=False,
keepconflictparent=False,
wctx=None,
):
"""Do a graft-like merge.
This is a merge where the merge ancestor is chosen such that one
or more changesets are grafted onto the current changeset. In
addition to the me... | b715ead11ea83c61eff52a670396885cd6373739 | 3,659,346 |
def GetSiteFilters(filename):
""" Reader for a file of reportable sites.
The file contains 2 tokens: the site name and a normalization factor.
The method returns a hash table with the key being site and the value
the normalization factor to use.
"""
try:
#--- process the reportable sites ... | 5f5e02b4213a060ca2ea2485d9f4ce4a09e9995f | 3,659,347 |
import warnings
def MiniMobileNetV2(input_shape=None,
alpha=1.0,
expansion_factor=6,
depth_multiplier=1,
dropout=0.,
weight_decay=0.,
include_top=True,
weights=None,
... | 695d592f3b8e75f9d416702c3e2b74f8f608e211 | 3,659,348 |
import logging
def update_forward_cnt(**kwargs):
"""
更新被转发的次数,进行加1操作
:param kwargs: {'object_id': object_id}
:return:
"""
session = None
try:
session = get_session()
# 转发次数 +1
session.query(SecondHand).filter(SecondHand.OBJECT_ID == kwargs['object_id']).update(
... | f6525dfa61e6fb2a5c39e344a6528d5f581393cd | 3,659,349 |
import copy
def recursive_dict_merge(dict1, dict2):
"""
Merges dictionaries (of dictionaries).
Preference is given to the second dict, i.e. if a key occurs in both dicts, the value from `dict2` is used.
"""
result = copy.deepcopy(dict1)
for key in dict2:
if key in dict1 and isinstance(... | fbcb51ad47de0dd4d1c95cd59873918187736b63 | 3,659,350 |
import torch
def define_loss(name, device="cuda"):
"""
Defines the loss function associated to the name.
Supports losses in the LOSSES list, as well as the Lovasz, Softdice and Haussdorf losses.
Args:
name (str): Loss name.
device (str, optional): Device for torch. Defaults to "cuda".... | b3705a116af18dbe7d4a8cf8539c544e057a08d6 | 3,659,351 |
import os
def get_default_archive_path():
"""
Makeup default archive path.
Unify the archive path between local machine and cloud.
"""
if not XT_HWC_WORKSPACE:
return os.path.join(os.path.expanduser("~"), DEFAULT_ARCHIVE_DIR)
else:
return os.path.join(XT_HWC_WORKSPACE, DEFAULT... | 38ec50c5d841f470c37f1c5749a028e3ee4551a8 | 3,659,352 |
import os
def get_hosts_from_file(hostfile):
"""
Return the list of hosts from a given host file.
"""
hosts = []
if os.path.exists(hostfile):
for line in open(hostfile, "r").readlines():
hosts.append(line.split(' ', 1)[0])
return hosts | f49b7734caa679b328a9649c5fb6fd3009c20e18 | 3,659,353 |
import os
import errno
def process_exists(pid): # type: (int) -> bool
""" Checks if the processed with the given *pid* exists. Returns #True if
that is the case, #False otherwise. """
if pid == 0:
return False
try:
os.kill(pid, 0)
except OSError as exc:
if exc.errno == errno.ESRCH:
retur... | 80bc3de2270d69ca7b4b5e60e4e87d13253e2d11 | 3,659,354 |
import sys
import os
def get_application_name():
"""Attempts to find the application name using system arguments."""
if hasattr(sys, 'argv') and sys.argv[0]:
app_name = os.path.basename(sys.argv[0])
else:
app_name = None
return app_name | f37c0913b2e227e20a22e3d6bd8ba1fdf4b7f6f3 | 3,659,355 |
def get_atomate_wflows(wf_coll,
states,
seed_regex=None,
project_regex=None) -> pd.DataFrame:
"""Obtain workflow informaton for atomate jobs"""
return get_workflows(wf_coll, ['atomate-relax'],
states,
... | 131609b7360ed6f378235b2b0c34268bbce5b641 | 3,659,356 |
def the_H_function(sorted_citations_list, n=1):
"""from a list of integers [n1, n2 ..] representing publications citations,
return the max list-position which is >= integer
eg
>>> the_H_function([10, 8, 5, 4, 3]) => 4
>>> the_H_function([25, 8, 5, 3, 3]) => 3
>>> the_H_function([1000, 20]) => 2... | 24ad3d85963ef0a9d4531ba552371d7e829f1c2a | 3,659,357 |
from pydantic import BaseModel # noqa: E0611
import importlib
def build_trainer(model: BaseModel,
params: Parameters,
dataset: Dataset,
target_processor: TargetProcessor,
batch_processor: BatchProcessor) \
-> BaseTrainer:
"""
Bui... | b9a1ede91818e024b4a0932f13e37cda4b9b6d28 | 3,659,358 |
import random
from bs4 import BeautifulSoup
def get_random_quote(quotes_list):
"""Return a random quote to user."""
upper_limit = len(quotes_list)-1
select = random.randint(0, upper_limit)
selected_quote = quotes_list[select]
soup = BeautifulSoup(selected_quote, 'html.parser')
return soup.text | c50f99640da88319c2b643b0fe1c386206c0c00b | 3,659,359 |
from unittest.mock import patch
def record_states(hass):
"""Record some test states.
We inject a bunch of state updates from media player, zone and
thermostat.
"""
mp = "media_player.test"
mp2 = "media_player.test2"
mp3 = "media_player.test3"
therm = "thermostat.test"
therm2 = "th... | eb24d3ce56aa2ba4df9423107252bdd9142e0861 | 3,659,360 |
def ask_why(doc):
"""
Ask questions of the form “Why is ..x..?” where x is either a
combination of object and adjective or subject and adjective
or “Why ..prep.. the ..noun..”
"""
chunk = find_subj_chunk(doc)
if chunk != None and chunk["adjective"] != None:
subj = chunk["subject"]
... | 64ef365f5ebd64dff4384cc558ecfa7856661fdd | 3,659,361 |
def get_extension(fname):
"""
Get file extension.
"""
return '.' + fname.split(".")[-1] | 9fa6f63d848aa7781b55e9cc384c9a8cb9665c69 | 3,659,362 |
def large_xyz_to_luv_star(large_xyz, white_xyz):
"""
# 概要
XYZ から L*u*v* を計算する。
# 参考
https://en.wikipedia.org/wiki/CIELUV
"""
large_x, large_y, large_z = np.dsplit(large_xyz, 3)
white_xyz = np.array(white_xyz)
white_xyz = (white_xyz / white_xyz[1]).reshape((1, 1, 3))
x_n, y_n, z_n... | 689c13d99c7e8b279c6cd718aad33fce8baa5a67 | 3,659,363 |
def rotation(new_rotation=0):
"""Set the display rotation.
:param new_rotation: Specify the rotation in degrees: 0, 90, 180 or 270
"""
global _rotation
if new_rotation in [0, 90, 180, 270]:
_rotation = new_rotation
return True
else:
raise ValueError("Rotation: 0, 90, 1... | 4f12a90e104ef66e50520523d23b3fff421fa991 | 3,659,364 |
def parse_url (url:str) -> str:
"""
规范化 URL
-> hello/world
<- /hello/world
"""
if url == "": url = "/"
if not url.startswith ('/'): url = "/" + url # 添加开头斜杠
# if not url.endswith ("/"): url += "/" # 添加末尾斜杠
return url | dd2ace64bd5926f2b20a77c81a1e885e8a4d3d2b | 3,659,365 |
def bulk_edit(modeladmin, request, queryset):
""" Bulk edit selected items. """
form = None
if 'apply' in request.POST:
form = BulkEditForm(request.POST)
if form.is_valid():
property = form.cleaned_data['property']
cf_value = form.cleaned_data['cf_value']
... | 069eeb1a32d91bf7eeb055fa4014210f52e4792b | 3,659,366 |
def smooth_GF(C,S,avg_rad, start_deg):
"""from Wahr et al: Time-variable gravity recovery from space eq. 34.
This is Jekeli's [1981] smoothing method."""
C_smooth = C
S_smooth = S
Re = 6378.1363; # Radius of Earth in km
b = np.log(2) / (1 - np.cos(avg_rad / Re))
W=[]
W.append(1 / (2 * np.pi))
W.append(1 / (2 *... | 89c0edfe4af3ef476485517e06363acb09be4fda | 3,659,367 |
def get_vmstat():
"""
Get and format the content of /proc/vmstat
"""
buf = open("/proc/vmstat").read()
buf = [v.replace(' ', ":") for v in buf.split("\n")]
buf = ";".join(buf)
return buf | b2db72bbc3b143ff1ba37ee7e2dcc33295d4a4ea | 3,659,368 |
def upcomingIPOs(
symbol="",
exactDate="",
token="",
version="stable",
filter="",
format="json",
):
"""This will return all upcoming estimates, dividends, splits for a given symbol or the market. If market is passed for the symbol, IPOs will also be included.
https://iexcloud.io/docs/ap... | 0e456c36fb4cbb11eb863f22ae06fb01589fc21a | 3,659,369 |
from typing import Iterable
from typing import List
def sort_tokens(tokens: Iterable[Cwf]) -> List[Cwf]:
"""Sort tokens by natural order (sent, offset)"""
return sorted(tokens, key=lambda t: (t.get_sent(), int(t.get_offset()))) | 6b9ced6bdb72a1f53c7e721f5212894caa2c4756 | 3,659,370 |
def deep_seq_map(xss, fun, keys=None, fun_name=None, expand=False):
"""Applies fun to list of or dict of lists; adds the results in-place.
Usage: Transform a corpus iteratively by applying functions like
`tokenize`, `lower`, or vocabulary functions (word -> embedding id) to it.
from jtr.sisyphos.vocab... | 59406ae1ee87bfea82f4b22fb3d5fb96c29ccda6 | 3,659,371 |
def create_user(steamid, admin):
"""Create a user"""
steamid = string_to_steamid(steamid)
if not steamid.is_valid() or not steamid.type == EType.Individual:
echo('Invalid steam ID')
return 1
user = User(steamid64=steamid.as_64, admin=admin)
user.refresh_name()
if user.name is no... | 22f6a63d85d57e7df0ae5dad0e62e41ee7c6388a | 3,659,372 |
import json
def get_vocabularies():
"""
Return the currently used ontology
:return:
"""
vocabs = vocs.get_vocabularies()
vocabs = [(x, url_for('get_vocabulary', vid=x, _external=True)) for x in vocabs]
response = make_response(json.dumps(dict(vocabs)))
response.headers['Content-Type'] ... | 3b447b297209e8d6fa238ba8f0cf932f0e3eed84 | 3,659,373 |
def do3byte(*args):
"""do3byte(ea_t ea, asize_t length) -> bool"""
return _idaapi.do3byte(*args) | fa82f7dc5bfa5dcaea7db604ea4c7f1fc5883794 | 3,659,374 |
import logging
def compute_sap(ground_truth_data,
representation_function,
random_state,
num_train=gin.REQUIRED,
num_test=gin.REQUIRED,
batch_size=16,
continuous_factors=gin.REQUIRED):
"""Computes the SAP score.
Args:... | f9aad7f12597491cb57d5b7180debb76da3bc01f | 3,659,375 |
import re
def clean_cmd(cmd):
"""Removes multiple spaces and whitespace at beginning or end of command.
Args:
cmd (str): A string containing the command to clean.
Returns:
A cleaned command string.
"""
return re.sub(r'\s{2, }', ' ', cmd).strip(' \t\n\r') | d98f4fea9791cbb5936b306ee74335efc6515902 | 3,659,376 |
def multiply_scalar(mat, value):
""" Multiplies every element in the matrix by the given scalar value.
Args:
mat (Matrix): The input matrix.
value (int or float): The number that mat will be multipled by.
Returns:
Matrix: The resulting matrix from the multiplication of mat and value... | 3b2469213ddb93e06ce210ee082a403f5ed2cc4a | 3,659,377 |
def bin4D(data4D, bin_factor):
"""
Bin 4D data in spectral dimensions
Parameters
----------
data4D: ndarray of shape (4,4)
the first two dimensions are Fourier
space, while the next two dimensions
are real space
bin_factor: int
... | baa00278bb5e4c7fcef6f1a78019f227533de586 | 3,659,378 |
def lorentz(x, a, mu, ga):
""" Input: x - value and a=I, mu=x_0, ga - lorentz f. coeffitients (float)
Return: value of function with desired parameters in x (float)
Descr.: Calculate L-type function for given x and parameters"""
return (a * ga ** 2) / ((x - mu) ** 2 + ga ** 2) | 1af83bdca1ff14f25da86cb0f3dacbd36409f1e1 | 3,659,379 |
def main(arguments):
"""
if you call this then it will create and return the thunder obj for you
:param arguments: a thunder object or a dicitonary to initialise the thunder obj
:return:
"""
thunder = Thunder(deepcopy(arguments)) # load object
return thunder | d628d6b1fb3550b1d1056613680437b847ab7102 | 3,659,380 |
def make_train_func(
model,
loss_func,
optimizer,
dtype=None,
device=None,
call_model=None,
get_train_loss=None,
):
"""Create a train func for ``ignite``.
This function assumes that each batch is of the form ``(x, y)`` with no assumptions placed on ``x`` or ``y``.
Each batch wil... | 5ceb230e7c6fce891a23416883b12bd09c83ccd5 | 3,659,381 |
import time
def waitAndLocate(btn_img, params):
"""
Function to locate a button in the window
:param btn_img: path to the image of the button to look for
:return: coordinates + dimensions of the button
"""
start = time.time()
while True:
if time.time() - start > (3*60):
... | daf7c32d67f1d958c8dcd15e3721823863b44365 | 3,659,382 |
from typing import List
from typing import Tuple
import torch
def make_preds_batch(classifier: nn.Module,
batch_elements: List[SentenceEvidence],
device: str=None,
criterion: nn.Module=None,
tensorize_model_inputs: bool=True) -> Tuple... | 8656bcb3c9895c25cd3a62428d9426a34fc2d324 | 3,659,383 |
def quick_sort(array):
"""
Not Inplace, but Standard version
"""
if array == []:
return []
else:
pivot = array[-1]
smaller = quick_sort([x for x in array[0:-1] if x <= pivot])
larger = quick_sort([x for x in array[0:-1] if x > pivot])
return smaller + [pivot] ... | 40b969855394600a94ed264f5bffade95c72455e | 3,659,384 |
def calc_laplacian_matrix(D, W):
"""
给定图的度矩阵和相似度矩阵,计算拉普拉斯矩阵
:param W: 相似度矩阵
:param D: 图的度矩阵
:return: 拉普拉斯矩阵
"""
return D - W | 542efe382457a34587615d24935c040238098610 | 3,659,385 |
def _potrf_mhlo(platform, gpu_solver, dtype, a, lower):
"""Cholesky decomposition."""
a_type = ir.RankedTensorType(a.type)
dims = a_type.shape
m, n = dims[-2:]
assert m == n
batch_dims = tuple(dims[:-2])
num_bd = len(batch_dims)
batch = _prod(batch_dims)
lwork, opaque = gpu_solver.build_potrf_descrip... | 6f9a8aef2bec2d063ebaf7c739b11879a67fd342 | 3,659,386 |
def _bin2bcd(value):
"""Convert a binary value to binary coded decimal.
:param value: the binary value to convert to BCD. (required, no default)
"""
return value + 6 * (value // 10) | 508383fe8964da3a09699ee8e68f36cea4162746 | 3,659,387 |
import requests
from bs4 import BeautifulSoup
def osm_get_info(idx):
"""Получаем информацию об административной территории
"""
link = 'https://www.openstreetmap.org/api/0.6/relation/' + str(idx)
response = requests.get(link)
if response.status_code == 200:
soup = BeautifulSoup(response.tex... | 0d2ee403c6bcf3a5c5ee37d01b9b0925bfac6081 | 3,659,388 |
import sqlite3
def get_test_cases_coverage(session_id):
"""
coverage by test case
"""
tc_stats={}
tc_stats_list=[]
total_executed=0
sql='SELECT DISTINCT(test_id) FROM stats WHERE session_id=:sid AND test_id!="null"'
params={"sid":session_id}
conn=sqlite3.connect(CONNECTION_STRING)
... | acceee566f53b95316c9ccd2654b89f6a60c7a5a | 3,659,389 |
def can_minimize_file(file_path):
"""Check to see if we support minimization for this file."""
# If this is not a binary file, we should be able to minimize it in some way.
if not utils.is_binary_file(file_path):
return True
# Attempt to minimize IPC dumps.
if file_path.endswith(testcase_manager.IPCDUMP_... | 3d8f5e2ee4f834a353ce8973cd64da66712c8c1c | 3,659,390 |
def generate_new_xen_xml(VIRSH_TEMPLATE, vm_name,
disk_img,
mac_addr,
memory_size=1048576, # 1GB of memory
cpu_count=1):
"""
Given a name, disk, and mac, this will output the appropriate xml
confi... | 28eec535a5924a847bd887b903014aca4a97dd9b | 3,659,391 |
def literal_query(query):
"""Don't interprete any special query syntax
SQLite's FTS extensions support special query syntax for AND, OR and
prefix searches, as well as grouping and negation. There are not of much
use in the dictionary case, but they break some legitimate queries. So
let's treat all... | 65c5f3215a2d36fb15b54e5420ce52ac27d1b420 | 3,659,392 |
from typing import Dict
import os
def gene2symbol(key: str, value: str) -> Dict[str, str]:
"""Map between S. pombe gene IDs, symbols, synonyms and names.
# Arguments
key: str, one of {"ID", "Symbol", "Synonym", "Name"}
value: str, one of {"ID", "Symbol", "Synonym", "Name"}
# Returns
... | 2625a07a832ba7d4bf05d2743f1f0b56c2923e1f | 3,659,393 |
def graph_from_string(s):
"""
Turn a string like "1 2; 1->2" into a graph.
"""
vertex_string, edge_string = s.split(';')
vertices = vertex_string.split()
edge_pairs = []
for edge_sequence in edge_string.split():
sequence_nodes = edge_sequence.split('->')
for tail, head in z... | 772c876eb4c38fb4d595ee57fb5192622c92e837 | 3,659,394 |
def WideResnetBlocknt(channels, strides=(1,1), channel_mismatch=False, batchnorm='std', parameterization='ntk'):
"""A WideResnet block, with or without BatchNorm."""
Main = stax_nt.serial(_batch_norm_internal(batchnorm), stax_nt.Relu(), stax_nt.Conv(channels, (3,3), strides, padding='SAME', parameterization=para... | d1786bf36703669627807f9bf881630ff1592ef5 | 3,659,395 |
import torch
def inverse_pinhole_matrix(pinhole, eps=1e-6):
"""
Returns the inverted pinhole matrix from a pinhole model
"""
assert len(pinhole.shape) == 2 and pinhole.shape[1] == 12, pinhole.shape
# unpack pinhole values
fx, fy, cx, cy = torch.chunk(pinhole[..., :4], 4, dim=1) # Nx1
... | e2fd741598b858f9d8731e4dc2b0c79913941dbf | 3,659,396 |
from unittest.mock import patch
async def init_integration_empty_response(hass) -> MockConfigEntry:
"""Set up the Nightscout integration in Home Assistant."""
entry = MockConfigEntry(
domain=DOMAIN,
data={CONF_URL: "https://some.url:1234"},
)
with patch(
"homeassistant.componen... | 890230dabafbfa939433251fb1b4ba2a9b14a7bf | 3,659,397 |
def create_DCT_NETWORK_INFO(networkid: str) -> dict:
"""Computes dictionary DCT_NETWORK_INFO for XML file
:param networkid: network identifier
:type networkid: str
:return: dict
:rtype: [type]
"""
DCT_NETWORK_INFO.update({"id": networkid})
return DCT_NETWORK_INFO | 96eeb48e35bebfc4bc1923685f8bb627dfc5f473 | 3,659,398 |
def retrieve_question(request, uuid):
"""
"""
try:
question = Question.objects.get(pk=uuid)
except (Question.DoesNotExist, ValueError):
response_data = {
"error": {
"state": "not found",
"details": "Question object with ID {} could not be found... | ee6409c2b724977744d66d3fba7efa17fa75284c | 3,659,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.