content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def load_data(connection_string: str):
"""
Load data from a source. Source could be:
- A JSON File
- A MongoDB
Load data from a file
---------------------
If you want to load data from a File, you must to provide this connection string:
>>> connection_string = "/path/to/my/file.json"... | abb806e62510077abf8a0b686a5882f637502275 | 3,658,837 |
def himmelblau(xy):
"""
Himmelblau's function, as a set of residuals (cost = sum(residuals**2))
The standard Himmelbau's function is with data as [11, 7], and four
minimum at (3.0, 2.0), ~(-2.8, 3.1), ~(-3.8, -3.3), ~(3.6, -1.8).
Himmelblau's function is a quadratic model in both x and y. Its data-... | 6951c77afd39596e7a799fe413bc2fc96a4818c2 | 3,658,838 |
from typing import Dict
def parse_instrument_data(smoothie_response: str) -> Dict[str, bytearray]:
"""
Parse instrument data.
Args:
smoothie_response: A string containing a mount prefix (L or R) followed by :
and a hex string.
Returns:
mapping of the mount prefix to the h... | 59f02a5d83b600f5fb4104f72f860925487f6422 | 3,658,839 |
def _volume_sum_check(props: PropsDict, sum_to=1, atol=1e-3) -> bool:
"""Check arrays all sum to no more than 1"""
check_broadcastable(**props)
sum_ar = np.zeros((1,))
for prop in props:
sum_ar = sum_ar + props[prop]
try:
assert sum_ar.max() <= sum_to + atol
except AssertionErr... | 631743276b833fd9ea58ae766614b851764ee771 | 3,658,841 |
def small_view(data, attribute):
"""
Extract a downsampled view from a dataset, for quick statistical summaries
"""
shp = data.shape
view = tuple([slice(None, None, np.intp(max(s / 50, 1))) for s in shp])
return data[attribute, view] | 62273269f87cbe6803ef0b5a8e47a681ca1f4d26 | 3,658,843 |
def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.
The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.
Returns:
A list of tuples, each of which contains (id, name, wins, matches... | c6554d1ff34dd08f756d1ad19665deacac4467de | 3,658,844 |
def get_all_feature_names(df: pd.DataFrame, target: str = None) -> list:
"""Get a list of all feature names in a dataframe.
Args:
df (pd.DataFrame): dataframe of features and target variable
target (str): name of target column in df
Returns:
all_feature_names (list): list of al... | b0b1964832c6f56200a3d7fbbccd1030e9c52a93 | 3,658,845 |
import random
def generate_enhancer_promoter_pair(ep_df):
"""
"""
std_ep_pair = ep_df[['chrom-Enh','chromStart','chromEnd','TSS']]
min_ep_gap = abs((std_ep_pair['chromEnd']-std_ep_pair['chromStart']).min())
max_ep_gap = abs((std_ep_pair['chromEnd']-std_ep_pair['chromStart']).max())
fake_samples = []
for enh... | b87906e6e2d5a23a729aa3f9b19fcd086db2e7c8 | 3,658,847 |
from typing import Union
from typing import Tuple
from typing import Dict
def constant_lrs(
draw, return_kwargs: bool = False
) -> Union[
st.SearchStrategy[lr_scheduler_pb2.ConstantLR],
st.SearchStrategy[Tuple[lr_scheduler_pb2.ConstantLR, Dict]],
]:
"""Returns a SearchStrategy for an ConstantLR plus m... | d7354717a052de2852ea61e55b1b2c3e3df19010 | 3,658,848 |
def get_read_only_storage_manager():
"""Get the current Flask app's read only storage manager, create if
necessary"""
return current_app.config.setdefault('read_only_storage_manager',
ReadOnlyStorageManager()) | cd5dac64a834ac98accb6824d5e971d763acc677 | 3,658,849 |
def __parse_sql(sql_rows):
"""
Parse sqlite3 databse output. Modify this function if you have a different
database setup. Helper function for sql_get().
Parameters:
sql_rows (str): output from SQL SELECT query.
Returns:
dict
"""
column_names... | 09c61da81af069709dd020b8643425c4c6964137 | 3,658,850 |
import scipy
import random
def _generate_to(qubo, seed, oct_upper_bound, bias=0.5):
"""
Given a QUBO, an upper bound on oct, and a bias of bipartite vertices,
generate an Erdos-Renyi graph such that oct_upper_bound number of vertices
form an OCT set and the remaining vertices are partitioned into part... | 653aedbd44bf87a9908c8abcf2c9480b836f4a03 | 3,658,851 |
def sqlCreate(fields=None, extraFields=None, addCoastGuardFields=True, dbType='postgres'):
"""Return the sqlhelp object to create the table.
@param fields: which fields to put in the create. Defaults to all.
@param extraFields: A sequence of tuples containing (name,sql type) for additional fields
@par... | 0a9bbbed4dd9c20e1126716bb64e2279d4ab29b6 | 3,658,852 |
def _section_cohort_management(course, access):
""" Provide data for the corresponding cohort management section """
course_key = course.id
ccx_enabled = hasattr(course_key, 'ccx')
section_data = {
'section_key': 'cohort_management',
'section_display_name': _('Cohorts'),
'access'... | 161f01b96952b8538d737c13718d455b69542b51 | 3,658,853 |
def rivers_by_station_number(stations, N):
"""Returns a list of N tuples on the form (river name, number of stations on the river). These tuples are sorted in decreasing order of station numbers.
If many stations have the same number of stations as the 'Nth' river, these are also included."""
riversLi... | 5f958116ae833d2ad4921662f753ca8f30a0af73 | 3,658,854 |
import json
def load_default_data() -> dict[str, str]:
"""Finds and opens a .json file with streamer data.
Reads from the file and assigns the data to streamer_list.
Args:
None
Returns:
A dict mapping keys (Twitch usernames) to their corresponding URLs.
Each row is repre... | bfeef64922fb4144228e031b9287c06525c4254d | 3,658,855 |
def get_value_key(generator, name):
"""
Return a key for the given generator and name pair.
If name None, no key is generated.
"""
if name is not None:
return f"{generator}+{name}"
return None | 0ad630299b00a23d029ea15543982125b792ad53 | 3,658,856 |
import math
def wav_to_log_spectrogram_clips(wav_file):
"""convert audio into logrithmic spectorgram, then chop it into 2d-segmentation of 100 frames"""
# convert audio into spectorgram
sound, sr = librosa.load(wav_file, sr=SR, mono=True)
stft = librosa.stft(sound, n_fft=N_FFT, hop_length=HOP_LEN, win... | 51ccf7d5687005f3eb01f382d37b6d7e09e45730 | 3,658,857 |
def get_title(mods):
"""
Function takes the objects MODS and extracts and returns the text of the title.
"""
title = mods.find("{{{0}}}titleInfo/{{{0}}}title".format(MODS_NS))
if title is not None:
return title.text | 652a9cc61c8d2538c80818759666022b19058074 | 3,658,858 |
def sample_ingredient(user, name='Cinnamon'):
"""
Create and return a sample ingredient
:param user: User(custom) object
:param name: name of the ingredient
:return: Ingredient object
"""
return Ingredient.objects.create(user=user, name=name) | 2828e1f42f6d755ac636d93d72b291cad3ba0061 | 3,658,860 |
def viterbi(O,S,Y, pi, A, B):
"""Generates a path which is a sequence of most likely states that generates the given observation Y.
Args:
O (numpy.ndarray): observation space. Size: 1 X N
S (numpy.ndarray): state space. Size: 1 X K
Y (list): observation sequence. ... | db533c584cf2a287cfcc6f4097566cdb493c42cc | 3,658,862 |
def int_to_bigint(value):
"""Convert integers larger than 64 bits to bytearray
Smaller integers are left alone
"""
if value.bit_length() > 63:
return value.to_bytes((value.bit_length() + 9) // 8, 'little', signed=True)
return value | 0f2d64887dc15d1902b8e10b0257a187ed75187f | 3,658,863 |
def xcorr(S, dtmax=10):
"""
Cross correlate each pair of columns in S at offsets up to dtmax
"""
# import pdb; pdb.set_trace()
(T,N) = S.shape
H = np.zeros((N,N,dtmax))
# Compute cross correlation at each time offset
for dt in np.arange(dtmax):
# print "Computing cross correlati... | 7b27b2ce5c574db253554e8d6c2ebf0ac7c354ca | 3,658,864 |
def register_hooks():
"""Exec all the rules files. Gather the hooks from them
and load them into the hook dict for later use.
"""
global HOOKS_LOADED
for name, path in load_rules().items():
globals = {}
with open(path) as f:
exec(compile(f.read(), path, 'exec'), globals)... | c4bfd57fa0a503f4a5be7004fe2145b42c28727a | 3,658,865 |
def proxy_rotator():
"""Return a cycle object of proxy dict"""
return Proxy.get_proxy_rotator() | 4b988214818599ba19cd45f43aeec03e9cc37e08 | 3,658,867 |
def pow(a, b):
""" Return an attribute that represents a ^ b. """
return multiplyDivide(a, b, MultiplyDivideOperation.POWER) | 17551ad9a872a854c177e43317f1d22242a10cd5 | 3,658,868 |
async def send_simple_embed_to_channel(bot: commands.Bot, channel_name: str, message: str, color: str = config["colors"]["default"]) -> discord.Message:
"""Send a simple embed message to the channel with the given name in the given guild, using the given message and an optional colour.
Args:
bot (comma... | 577594c5abdb946ac04decac3ef94ea0e8296535 | 3,658,869 |
def retry_on_server_errors_timeout_or_quota_issues_filter(exception):
"""Retry on server, timeout and 403 errors.
403 errors can be accessDenied, billingNotEnabled, and also quotaExceeded,
rateLimitExceeded."""
if HttpError is not None and isinstance(exception, HttpError):
if exception.status_code == 403:
... | 18be4224af641b35cfba50d0ec85a1d22908d1e4 | 3,658,870 |
def CSourceForElfSymbolTable(variable_prefix, names, str_offsets):
"""Generate C source definition for an ELF symbol table.
Args:
variable_prefix: variable name prefix
names: List of symbol names.
str_offsets: List of symbol name offsets in string table.
Returns:
String containing C source fragme... | 233c55815cf5b72092d3c60be42caffc95570c22 | 3,658,873 |
from typing import Optional
def get_endpoint_access(endpoint_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetEndpointAccessResult:
"""
Resource schema for a Redshift-managed VPC endpoint.
:param str endpoint_name: The name of the endpoint.
... | 6b38fbd0b27d1ce892fc37c37944979907796862 | 3,658,875 |
def predictor(
service: MLFlowDeploymentService,
data: np.ndarray,
) -> Output(predictions=np.ndarray):
"""Run a inference request against a prediction service"""
service.start(timeout=10) # should be a NOP if already started
prediction = service.predict(data)
prediction = prediction.argmax(ax... | c3b5f7241aeab0520db535134912431edf467137 | 3,658,876 |
def get_domain(ns, domain):
"""
Return LMIInstance of given LMI_SSSDDomain.
:type domain: string
:param domain: Name of the domain to find.
:rtype: LMIInstance of LMI_SSSDDomain
"""
keys = {'Name': domain}
try:
inst = ns.LMI_SSSDDomain.new_instance_name(keys).to_instance()
e... | beadbd0c172a07c2b55b5bf2b22a05abf562b95b | 3,658,877 |
def mmd_loss(embedding, auxiliary_labels, weights_pos, weights_neg, params):
""" Computes mmd loss, weighted or unweighted """
if weights_pos is None:
return mmd_loss_unweighted(embedding, auxiliary_labels, params)
return mmd_loss_weighted(embedding, auxiliary_labels,
weights_pos, weights_neg, params) | 6b592159587ec49fc6fd77ed286f338d11582a4b | 3,658,878 |
def perdidas (n_r,n_inv,n_x,**kwargs):
"""Calcula las perdidas por equipos"""
n_t=n_r*n_inv*n_x
for kwargs in kwargs:
n_t=n_t*kwargs
return n_t | 157825059ad192ba90991bff6206b289755ce0ba | 3,658,879 |
def _symlink_dep_cmd(lib, deps_dir, in_runfiles):
"""
Helper function to construct a command for symlinking a library into the
deps directory.
"""
lib_path = lib.short_path if in_runfiles else lib.path
return (
"ln -sf " + relative_path(deps_dir, lib_path) + " " +
deps_dir + "/" ... | 6672decdee61dfc7f5604c6ebe1c07ac99800a91 | 3,658,880 |
def boundingBoxEdgeLengths(domain):
"""
Returns the edge lengths of the bounding box of a domain
:param domain: a domain
:type domain: `escript.Domain`
:rtype: ``list`` of ``float``
"""
return [ v[1]-v[0] for v in boundingBox(domain) ] | a98fc867961bbf6a2ab518da6c933f1295d858db | 3,658,881 |
def get_user(isamAppliance, user):
"""
Get permitted features for user
NOTE: Getting an unexplained error for this function, URL maybe wrong
"""
return isamAppliance.invoke_get("Get permitted features for user",
"/authorization/features/users/{0}/v1".format(user)) | 0b2fd6c58e2623f8400daa942c83bd0757edd21f | 3,658,882 |
from typing import Sequence
from typing import List
from typing import Optional
def autoupdate(
config_file: str,
store: Store,
tags_only: bool,
freeze: bool,
repos: Sequence[str] = (),
add_unused_hooks: bool = False,
) -> int:
"""Auto-update the pre-commit config t... | f45aeae70d6e33b841791a09d9a1578834246e75 | 3,658,883 |
def plot_energy_resolution_cta_performance(cta_site, ax=None, **kwargs):
"""
Plot the cta performances (June 2018) for the true_energy resolution
Parameters
----------
cta_site: string
see `ctaplot.ana.cta_performance`
ax: `matplotlib.pyplot.axes`
kwargs: args for `matplotlib.pyplot... | 67f76bcaffb85339f45803d32daf3e2d783fb097 | 3,658,884 |
from typing import OrderedDict
def _n_nested_blocked_random_indices(sizes, n_iterations):
"""
Returns indices to randomly resample blocks of an array (with replacement) in
a nested manner many times. Here, "nested" resampling means to randomly resample
the first dimension, then for each randomly sampl... | 730ddba8f0753c29ebcf55c8449f365e6fc0b9ab | 3,658,885 |
def phase_type_from_parallel_erlang2(theta1, theta2, n1, n2):
"""Returns initial probabilities :math:`\\alpha` and generator matrix :math:`S`
for a phase-type representation of two parallel Erlang channels with parametrisation
:math:`(\\theta_1, n_1)` and :math:`(\\theta_2, n_2)` (rate and steps of Erlang
... | 667fc2abdb38e2e623a5f91f33ffb60f9b9e5ca8 | 3,658,886 |
def get_regions(max_time_value):
"""
Partition R into a finite collection of one-dimensional regions depending on the appearing max time value.
"""
regions = []
bound = 2 * max_time_value + 1
for i in range(0, bound + 1):
if i % 2 == 0:
temp = i // 2
r = Const... | 1cc825592e07dc0bef30f04896e57df189d28bb3 | 3,658,887 |
def label_edges(g: nx.DiGraph) -> nx.DiGraph:
"""Label all the edges automatically.
Args:
g: the original directed graph.
Raises:
Exception: when some edge already has attribute "label_".
Returns:
The original directed graph with all edges labelled.
"""
g_labelled = nx... | a74559cdce8d75a65913def6c545b86ed45b2ead | 3,658,888 |
from datetime import datetime
import calendar
def report_charts(request, report, casetype='Call'):
"""Return charts for the last 4 days based on the Call Summary Data"""
# The ussual filters.
query = request.GET.get('q', '')
interval = request.GET.get('interval', 'daily')
category = request.GET.ge... | 0e9721446e66ee901732a6b0792075ccee607eaa | 3,658,889 |
def _get_optimizer(learning_rate: float, gradient_clip_norm: float):
"""Gets model optimizer."""
kwargs = {'clipnorm': gradient_clip_norm} if gradient_clip_norm > 0 else {}
return tf.keras.optimizers.Adagrad(learning_rate, **kwargs) | 92b9b70c533828232872250eca724c2568638f2f | 3,658,890 |
def is_my_message(msg):
"""
Функция для проверки, какому боту отправлено сообщение.
Для того, чтобы не реагировать на команды для других ботов.
:param msg: Объект сообщения, для которого проводится проверка.
"""
text = msg.text.split()[0].split("@")
if len(text) > 1:
if text[1] != config.bot_name:
return Fa... | e99c8587ffbc1e582154785d657212f37358e926 | 3,658,891 |
from typing import Any
from typing import Dict
def execute_search_query(client: Client, query: Any, data_range: str) -> Dict[str, Any]:
"""Execute search job and waiting for the results
:type client: ``Client``
:param client: Http client
:type query: ``Any``
:param query: Search query
:type... | 68a58f9c4bc7c2b4a754cce8bd97022d327d5155 | 3,658,892 |
def static(directory: str) -> WSGIApp:
"""Return a WSGI app that serves static files under the given directory.
Powered by WhiteNoise.
"""
app = WhiteNoise(empty_wsgi_app())
if exists(directory):
app.add_files(directory)
return app | 9eae5f688b50d6c6c523e69ee0e79f667fb1d567 | 3,658,893 |
def check_filter(id):
"""
Helper function to determine if the current crime is in the dictionary
"""
if id not in important_crime:
return 30
else:
return important_crime[id] * 30 | 9ca74e57abd32db6176216f31deae193e0cac0d4 | 3,658,894 |
def rand_email(domain=None):
"""Generate a random zone name
:return: a random zone name e.g. example.org.
:rtype: string
"""
domain = domain or rand_zone_name()
return 'example@%s' % domain.rstrip('.') | 3653319c77b7e304ea03b7bb06888d115f45dc1e | 3,658,895 |
def wordcount_for_reddit(data, search_word):
"""Return the number of times a word has been used."""
count = 0
for result in data: # do something which each result from scrape
for key in result:
stringed_list = str(result[key])
text_list = stringed_list.split()
fo... | b0967aa896191a69cd1b969589b34522299ff415 | 3,658,896 |
def calc_precision(gnd_assignments, pred_assignments):
"""
gnd_clusters should be a torch tensor of longs, containing
the assignment to each cluster
assumes that cluster assignments are 0-based, and no 'holes'
"""
precision_sum = 0
assert len(gnd_assignments.size()) == 1
assert len(pred... | 536e25aa8e3b50e71beedaab3f2058c79d9957e3 | 3,658,898 |
def __get_app_package_path(package_type, app_or_model_class):
"""
:param package_type:
:return:
"""
models_path = []
found = False
if isinstance(app_or_model_class, str):
app_path_str = app_or_model_class
elif hasattr(app_or_model_class, '__module__'):
app_path_str = ap... | f08685ef47af65c3e74a76de1f64eb509ecc17b9 | 3,658,900 |
import base64
def dict_from_payload(base64_input: str, fport: int = None):
""" Decodes a base64-encoded binary payload into JSON.
Parameters
----------
base64_input : str
Base64-encoded binary payload
fport: int
FPort as provided in ... | 05fe484eef6c4376f0b6bafbde81c7cc4476b83e | 3,658,901 |
def handle(req):
"""POST"""
im = Image.open(BytesIO(req.files[list(req.files.keys())[0]].body))
w, h = im.size
im2 = ImageOps.mirror(im.crop((0, 0, w / 2, h)))
im.paste(im2, (int(w / 2), 0))
io = BytesIO()
im.save(io, format='PNG')
return req.Response(
body=io.getvalue(), mime_... | d62afe253e331b4d7f037bdc56fa927bceb8bc03 | 3,658,902 |
import glob
def read_sachs_all(folder_path):
"""Reads all the sachs data specified in the folder_path.
Args:
folder_path: str specifying the folder containing the sachs data
Returns:
An np.array containing all the sachs data
"""
sachs_data = list()
# Divides the Sachs dataset into environments... | 151f1eec79251019d1a1c2b828531f6c1f01d605 | 3,658,903 |
def user_permitted_tree(user):
"""Generate a dictionary of the representing a folder tree composed of
the elements the user is allowed to acccess.
"""
# Init
user_tree = {}
# Dynamically collect permission to avoid hardcoding
# Note: Any permission to an element is the same as read permiss... | fd9b7d60da7e085e948d4def0ababc3d0cb8233f | 3,658,904 |
def extract_failure(d):
"""
Returns the failure object the given deferred was errback'ed with.
If the deferred has result, not a failure a `ValueError` is raised.
If the deferred has no result yet a :class:`NotCalledError` is raised.
"""
if not has_result(d):
raise NotCalledError()
e... | 7bc160a8ebd1c5cdeab1a91a556576c750d342f8 | 3,658,905 |
def convert_where_clause(clause: dict) -> str:
"""
Convert a dictionary of clauses to a string for use in a query
Parameters
----------
clause : dict
Dictionary of clauses
Returns
-------
str
A string representation of the clauses
"""
out = "{"
for key in c... | 8b135c799df8d16c116e6a5282679ba43a054684 | 3,658,906 |
from unittest.mock import call
def all_metadata_async():
"""Retrieves all available metadata for an instance async"""
loop = trollius.get_event_loop()
res = loop.run_until_complete(call())
return res | 9759331fbd72271820896bd2849139dc13fc9d39 | 3,658,907 |
def median_std_from_ma(data: np.ma, axis=0):
"""On the assumption that there are bit-flips in the *data*,
attempt to find a value that might represent the standard
deviation of the 'real' data. The *data* object must be a
numpy masked array.
The value of *axis* determines which way the data are ha... | 587702c52bb2000ebfe920202270610e4ed49d8c | 3,658,908 |
def __check_value_range(x: int) -> bool:
"""
Checks if integer is in valid value range to
be a coordinate for Tic-Tac-Toe.
"""
if x < 1 or x > 3:
print(__standard_error_text +
"Coordinates have to be between 1 and 3.\n")
return False
return True | 45f21b3292097baea31846b8bcc51435ae15134c | 3,658,909 |
def find_option(opt):
"""
This function checks for option defined with optcode;
it could be implemented differently - by checking entries in world.cliopts
"""
# received msg from client must not be changed - make a copy of it
tmp = world.climsg[world.clntCounter].copy()
# 0 - ether, 1 - ipv... | 23904c16f9206f9030a40e17be5f6b01cb0439cf | 3,658,910 |
from typing import Set
def generic_add_model_components(
m,
d,
reserve_zone_param,
reserve_zone_set,
reserve_generator_set,
generator_reserve_provision_variable,
total_reserve_provision_expression,
):
"""
Generic treatment of reserves. This function creates model components
rel... | 2c7eef877e0ba7744ba624205fcf590071a95b84 | 3,658,911 |
def return_all_content(content):
"""Help function to return untruncated stripped content."""
return mark_safe(str(content).replace('><', '> <')) if content else None | e24a1ee812a3a011cf6e369ba96bc2989ad7603d | 3,658,912 |
def get_trailing_returns(uid):
""" Get trailing return chart """
connection = pymysql.connect(host=DB_SRV,
user=DB_USR,
password=DB_PWD,
db=DB_NAME,
charset='utf8mb4',
... | 96e8ea67b1b91c3dfc6994b5ff56d9384aca6da5 | 3,658,913 |
def bitsNotSet(bitmask, maskbits):
"""
Given a bitmask, returns True where any of maskbits are set
and False otherwise.
Parameters
----------
bitmask : ndarray
Input bitmask.
maskbits : ndarray
Bits to check if set in the bitmask
"""
goodLocs... | 746c054310ac06c58cc32e5635d270c64481a527 | 3,658,914 |
def plot(foo, x, y):
"""x, y are tuples of 3 values: xmin, xmax, xnum"""
np_foo = np.vectorize(foo)
x_space = np.linspace(*x)
y_space = np.linspace(*y)
xx, yy = np.meshgrid(x_space, y_space)
xx = xx.flatten()
yy = yy.flatten()
zz = np_foo(xx, yy)
num_x = x[-1]
num_y = y[-1]
p... | 67bfcc70a71140efa3d08960487a69943d2acdc8 | 3,658,915 |
import struct
def _StructPackEncoder(wire_type, format):
"""Return a constructor for an encoder for a fixed-width field.
Args:
wire_type: The field's wire type, for encoding tags.
format: The format string to pass to struct.pack().
"""
value_size = struct.calcsize(format)
def SpecificEncode... | 7c58d955a903bac423799c99183066268fb7711b | 3,658,916 |
def transition_temperature(wavelength):
"""
To get temperature of the transition in K
Wavelength in micros
T = h*f / kB
"""
w = u.Quantity(wavelength, u.um)
l = w.to(u.m)
c = _si.c.to(u.m / u.s)
h = _si.h.to(u.eV * u.s)
kb = _si.k_B.to(u.eV / u.K)
f = c/l
t = h*f/kb
r... | dbec1ee2c1ad01cd257791624105ff0c4de6e708 | 3,658,917 |
def truncate_string(string: str, max_length: int) -> str:
"""
Truncate a string to a specified maximum length.
:param string: String to truncate.
:param max_length: Maximum length of the output string.
:return: Possibly shortened string.
"""
if len(string) <= max_length:
return strin... | c7d159feadacae5a692b1f4d95da47a25dd67c16 | 3,658,918 |
import requests
import json
def geoinfo_from_ip(ip: str) -> dict: # pylint: disable=invalid-name
"""Looks up the geolocation of an IP address using ipinfo.io
Example ipinfo output:
{
"ip": "1.1.1.1",
"hostname": "one.one.one.one",
"anycast": true,
"city": "Miami",
"region":... | 956a9d12b6264dc283f64ee792144946e313627b | 3,658,919 |
def mpileup2acgt(pileup, quality, depth, reference, qlimit=53,
noend=False, nostart=False):
"""
This function was written by Francesco Favero,
from: sequenza-utils pileup2acgt
URL: https://bitbucket.org/sequenza_tools/sequenza-utils
original code were protected under GPLv3 license... | bf5a0c5e147ece6e9b3be5906ba81ed54593b257 | 3,658,920 |
def normalize_missing(xs):
"""Normalize missing values to avoid string 'None' inputs.
"""
if isinstance(xs, dict):
for k, v in xs.items():
xs[k] = normalize_missing(v)
elif isinstance(xs, (list, tuple)):
xs = [normalize_missing(x) for x in xs]
elif isinstance(xs, basestri... | 5d3fef8370e6a4e993eb06d96e5010c4b57907ba | 3,658,921 |
def ini_inventory(nhosts=10):
"""Return a .INI representation of inventory"""
output = list()
inv_list = generate_inventory(nhosts)
for group in inv_list.keys():
if group == '_meta':
continue
# output host groups
output.append('[%s]' % group)
for host in inv... | 46182c727e9dbb844281842574bbb54d2530d42b | 3,658,922 |
def get_crp_constrained_partition_counts(Z, Cd):
"""Compute effective counts at each table given dependence constraints.
Z is a dictionary mapping customer to table, and Cd is a list of lists
encoding the dependence constraints.
"""
# Compute the effective partition.
counts = defaultdict(int)
... | acda347ec904a7835c63afe5ec6efda5915df405 | 3,658,923 |
import re
from re import T
def create_doc():
"""Test basic layer creation and node creation."""
# Stupid tokenizer
tokenizer = re.compile(r"[a-zA-Z]+|[0-9]+|[^\s]")
doc = Document()
main_text = doc.add_text("main", "This code was written in Lund, Sweden.")
# 01... | 36171fd68712861370b6ea1a8ae49aa7ec0c139a | 3,658,924 |
def jissue_get_chunked(jira_in, project, issue_max_count, chunks=100):
""" This method is used to get the issue list with references,
in case the number of issues is more than 1000
"""
result = []
# step and rest simple calc
step = issue_max_count / chunks
rest = issue_max_count % chunks... | 1c32859b91f139f5b56ce00f38dba38b2297109e | 3,658,925 |
def negative_height_check(height):
"""Check the height return modified if negative."""
if height > 0x7FFFFFFF:
return height - 4294967296
return height | 4d319021f9e1839a17b861c92c7319ad199dfb42 | 3,658,926 |
def linked_gallery_view(request, obj_uuid):
"""
View For Permalinks
"""
gallery = get_object_or_404(Gallery, uuid=obj_uuid)
images = gallery.images.all().order_by(*gallery.display_sort_string)
paginator = Paginator(images, gallery.gallery_pagination_count)
page = request.GET.get('page')
... | c425c6678f2bfb3b76c039ef143d4e7cbc6ee922 | 3,658,928 |
def _gm_cluster_assign_id(gm_list, track_id, num_tracks, weight_threshold,
z_dim, max_id, max_iteration=1000):
"""The cluster algorithm that assign a new ID to the track
Args:
gm_list (:obj:`list`): List of ``GaussianComponent`` representing
current multi-target PH... | f079867333a9e66f7b48782b899f060c38694220 | 3,658,929 |
def get_bprop_scatter_nd(self):
"""Generate bprop for ScatterNd"""
op = P.GatherNd()
def bprop(indices, x, shape, out, dout):
return zeros_like(indices), op(dout, indices), zeros_like(shape)
return bprop | 3f2f5247b03ba49918e34534894c9c1761d02f07 | 3,658,930 |
import requests
def delete_policy_rule(policy_key, key, access_token):
"""
Deletes a policy rule with the given key.
Returns the response JSON.
See http://localhost:8080/docs#/Policy/delete_rule_api_v1_policy__policy_key__rule__rule_key__delete
"""
return requests.delete(
f"{FIDESOPS... | b53e52b2498707b82e3ceaf89be667886c75ca3c | 3,658,932 |
def knn_search_parallel(data, K, qin=None, qout=None, tree=None, t0=None, eps=None, leafsize=None, copy_data=False):
""" find the K nearest neighbours for data points in data,
using an O(n log n) kd-tree, exploiting all logical
processors on the computer. if eps <= 0, it returns the distance to the ... | cc0dfaee8d1990f1d336e6a5e71973e1b4702e25 | 3,658,933 |
from typing import Tuple
def compute_vectors_from_coordinates(
x: np.ndarray, y: np.ndarray, fps: int = 1
) -> Tuple[Vector, Vector, Vector, Vector, np.array]:
"""
Given the X and Y position at each frame -
Compute vectors:
i. velocity vector
ii. unit tangent
... | 073262b521f3da79945674cc60ea26fee4c87529 | 3,658,935 |
import requests
def get_now(pair):
"""
Return last info for crypto currency pair
:param pair: ex: btc-ltc
:return:
"""
info = {'marketName': pair, 'tickInterval': 'oneMin'}
return requests.get('https://bittrex.com/Api/v2.0/pub/market/GetLatestTick', params=info).json() | b5db7ba5c619f8369c052a37e010229db7f78186 | 3,658,936 |
def hsv(h: float, s: float, v: float) -> int:
"""Convert HSV to RGB.
:param h: Hue (0.0 to 1.0)
:param s: Saturation (0.0 to 1.0)
:param v: Value (0.0 to 1.0)
"""
return 0xFFFF | 638c1784f54ee51a3b7439f15dab45053a8c3099 | 3,658,938 |
def make_exponential_mask(img, locations, radius, alpha, INbreast=False):
"""Creating exponential proximity function mask.
Args:
img (np.array, 2-dim): the image, only it's size is important
locations (np.array, 2-dim): array should be (n_locs x 2) in size and
each row should corres... | 14be02cee27405c3a4abece7654b7bf902a43a47 | 3,658,939 |
from typing import Tuple
def delete(client, url: str, payload: dict) -> Tuple[dict, bool]:
"""Make DELETE requests to K8s (see `k8s_request`)."""
resp, code = request(client, 'DELETE', url, payload, headers=None)
err = (code not in (200, 202))
if err:
logit.error(f"{code} - DELETE - {url} - {r... | 8ed463e063b06a48b410112f163830778f887551 | 3,658,940 |
def f(x):
"""The objective is defined as the cost + a per-demographic penalty
for each demographic not reached."""
n = len(x)
assert n == n_venues
reached = np.zeros(n_demographics, dtype=int)
cost = 0.0
for xi, ri, ci in zip(x, r, c):
if xi:
reached = reached | ri #
... | d6724595086b0facccae84fd4f3460195bc84a1f | 3,658,941 |
def clamp(minVal, val, maxVal):
"""Clamp a `val` to be no lower than `minVal`, and no higher than `maxVal`."""
return max(minVal, min(maxVal, val)) | 004b9a393e69ca30f925da4cb18a8f93f12aa4ef | 3,658,942 |
def get_closest_spot(
lat: float, lng: float, area: config.Area
) -> t.Optional[config.Spot]:
"""Return closest spot if image taken within 100 m"""
if not area.spots:
return None
distances = [
(great_circle((spot.lat, spot.lng), (lat, lng)).meters, spot)
for spot in area.spots
... | 55424c3b5148209e62d51cc7c6e5759353f5cb0a | 3,658,943 |
def drawBezier(
page: Page,
p1: point_like,
p2: point_like,
p3: point_like,
p4: point_like,
color: OptSeq = None,
fill: OptSeq = None,
dashes: OptStr = None,
width: float = 1,
morph: OptStr = None,
closePath: bool = False,
lineCap: int = 0,
lineJoin: int = 0,
over... | 7bd3c0b8e3ca8717447213c6c2ac8bc94ea0f029 | 3,658,944 |
from functools import reduce
import operator
def product(numbers):
"""Return the product of the numbers.
>>> product([1,2,3,4])
24
"""
return reduce(operator.mul, numbers, 1) | 102ac352025ffff64a862c4c5ccbdbc89bdf807e | 3,658,945 |
def load_ref_system():
""" Returns l-phenylalanine as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
N 0.7060 -1.9967 -0.0757
C 1.1211 -0.6335 -0.4814
C 0.6291 0.4897 ... | 724e0d37ae5d811da156ad09d4b48d43f3e20d6a | 3,658,946 |
from typing import List
def range_with_bounds(start: int, stop: int, interval: int) -> List[int]:
"""Return list"""
result = [int(val) for val in range(start, stop, interval)]
if not isclose(result[-1], stop):
result.append(stop)
return result | 1667657d75f918d9a7527048ad4207a497a20316 | 3,658,948 |
import warnings
def iou_score(box1, box2):
"""Returns the Intersection-over-Union score, defined as the area of
the intersection divided by the intersection over the union of
the two bounding boxes. This measure is symmetric.
Args:
box1: The coordinates for box 1 as a list of points
b... | 746129ac390e045887ca44095af02370abb71d81 | 3,658,949 |
def _actually_on_chip(ra, dec, obs_md):
"""
Take a numpy array of RA in degrees, a numpy array of Decin degrees
and an ObservationMetaData and return a boolean array indicating
which of the objects are actually on a chip and which are not
"""
out_arr = np.array([False]*len(ra))
d_ang = 2.11
... | 809bfb59f63a62ab236fb2a3199e28b4f0ee93fd | 3,658,950 |
from typing import Tuple
def outlier_dataset(seed=None) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]:
"""Generates Outliers dataset, containing 10'000 inliers and 50 outliers
Args:
seed: random seed for generating points
Returns:
Tuple containing the inlier features, inlier l... | 1b19e66f151290047017bce76e581ae0e725626c | 3,658,951 |
def posts(request, payload={}, short_id=None):
"""
Posts endpoint of the example.com public api
Request with an id parameter:
/public_api/posts/1qkx8
POST JSON in the following format:
POST /public_api/posts/
{"ids":["1qkx8","ma6fz"]}
"""
Metrics.api_comment.record(re... | c8ec491638417fe972fe75c0cf9f26fe1cf877ae | 3,658,952 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.