content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def yet_another_hash_table():
"""Make a hash table with multiple values and keys."""
h = HashTable()
h.set('koala', 'kool')
h.set('dog', 'chihuahua')
h.set('cat', 'fat')
h.set('moose', 'bullwinkle')
return h | 4e009e96e75016c9e9ea4964a56d62a4169814ec | 53,551 |
from typing import List
from typing import Pattern
def matplotgraph_predictions(user: discord.Member, predictions: List[Pattern], min_max_pattern: Pattern, average_prices: List[float], testing=False) -> BytesIO:
"""Graph the predictions"""
x_axis = day_segment_names[2:]
abs_min_points = [price.min for pr... | 7a21c7ab6fe6af9823d9ad3a0194f84ad0ef8cc0 | 53,552 |
import sqlite3
def open_corpus_volatile(treebank_id, tigerxml_corpus_path, veeroot=True):
"""Indexes a TIGER-XML corpus using a volatile in-memory index."""
db = sqlite3.connect(":memory:")
_index_treebank(tigerxml_corpus_path, db, veeroot)
return Corpus(treebank_id, db, EmptyDbProvider()) | b9b3a37fd52fa2830806d9a99c61c4a12acc6f48 | 53,553 |
def char_to_bool(letter):
"""Transform character (J/N) to Bool."""
if letter.upper() == 'J':
return True
elif letter.upper() == 'N':
return False
else:
raise ValueError('Ongeldige letter, alleen J of N toegestaan.') | ab12ffae09afdcf1e0ad9319238bef94b8f147ef | 53,554 |
def parse_exception(definition, name, message):
"""Parse an exception.
:param definition: Definition.
:param name: Name.
:param message: Message.
:returns:
the parsed exception or :class:`UnknownException` if the exception is
not known.
"""
if definition == 'entangle':
... | 9d9bddc42fb9de10c998907d930cf1b5c49da2d5 | 53,555 |
def _prf_divide(numerator, denominator):
"""Performs division and handles divide-by-zero.
On zero-division, sets the corresponding result elements to zero.
"""
result = numerator / denominator
mask = denominator == 0.0
return ma.array(result, mask=mask) | 0e562c659b2fda9835bd16b1e762bc0a86113c97 | 53,557 |
from typing import Optional
def authenticate_user(username: str, password: str) -> Optional[Admin]:
"""Authentucate user process.
Check if the username is in the admin database and the password is correct.
If both conditions are correct, it returns an Admin instance; otherwise it returns None"""
user... | f8e3e081239bd9e968200c4daa2cee69af2e5ffc | 53,558 |
def mock_clipboard(monkeypatch, request):
"""Fixture mocking clipboard IO.
This mocks pandas.io.clipboard.clipboard_get and
pandas.io.clipboard.clipboard_set.
This uses a local dict for storing data. The dictionary
key used is the test ID, available with ``request.node.name``.
This returns th... | 7acf72b45050d35cd57ddf9310304950610744c5 | 53,559 |
def fileNumber(filePath):
"""
Get the number of the file. foo.0080 would return 0080
"""
num = filePath.split('.')[-1]
return int(num) | 731918660f0c145c15ba99c2f5eb8be9745e8576 | 53,561 |
def dice(x, y):
"""Implementation of dice scores ofr 0/1 numy array"""
return 2 * np.sum(x * y) / (np.sum(x) + np.sum(y)) | 0a83c83377040123782576736a6d584f09f31186 | 53,562 |
def getAddressNode(network, address):
"""
Get the Layer3Address node of a host that has the igven address.
:param network: Hostnames the host could have -> Nmap scan
:type network: Layer3Network
:param address: Address to find
:type address: str
:returns: Layer3Address node or None
... | 3fc56c56c34df7d49f7d8fb872af19b29242534f | 53,563 |
def get_top_adj(full_results, num):
"""
Takes dictionary of results from run_adj_analysis and number of top results to return.
Returns the top num adjectives associated with male pronouns and female pronouns.
:param full_results: dictionary from result of run_adj_analysis
:param num: number of ... | 0eddb189f79bc9b18f2994f2a99aef1b07181691 | 53,564 |
import re
def create():
""" Create a new RSS feed over XHR
:return: Feed creation status response
:rtype: Response
"""
status = api.STATUS_FAIL
feed = "rss_{0}".format(re.sub('[^0-9a-zA-Z]+', '_', request.values['feed'].lower()))
if config.has_section(feed):
msg = "Duplicate feed... | 6e69211e8924d484d1b5cc4e88d09d1949f76e66 | 53,565 |
def get_host_token(profile=None):
""" Get the host and token for a profile from ~/.databrickscfg. """
cfg = provider.get_config() if profile is None else provider.get_config_for_profile(profile)
return (cfg.host,cfg.token) | 89e7fb425fb7965b560b70d51af46a68bf3cc233 | 53,566 |
import time
def loadAll(param=basic_param):
""" Charge toutes les colonnes selon les paramètres
Paramètres
----------
param : set
dictionnaire des paramètres
Retours
----------
df_global : pandas.dataframe
si Return == True renvoie le dataframe complet
"""
t1 = ti... | 4b9452c5b5cd4dfe322dd1b167c1181df01e09a5 | 53,567 |
def rfc_save_test(request, rfc_id, *args, **kwargs):
"""
"""
# Check user permissions
# Get the form data
form = RfcModuleForm(request.POST)
if not form.is_valid():
return HttpResponseBadRequest(form.errors)
# Get the rfc in question
update_rfc = request_for_change.objects.get(r... | 7372a992acde22d4e7366c21dc707b2fde98e18a | 53,568 |
def testPair(pair,coglist):
"""Determine the next cognate set to choose for a pair"""
curcog = cognateSet()
for cog in coglist:
curcog += cog
mycogs = [cognateSet()]
mycogs[0].noncognates += max((len(pair[0]),len(pair[1])))*2
newcogs = getListOfCognates(pair[0],pair[1],cognateSet())
... | c7a3a974823b82946dbaf2f45a63150090ba922b | 53,569 |
def _search_phrase_op(il, target_op):
""" Helper for finding parts of a phrase[+displacement] il """
op = il.operation
# Handle starting points
if op == LowLevelILOperation.LLIL_SET_REG:
return _search_phrase_op(il.src, target_op)
if op == LowLevelILOperation.LLIL_STORE:
return _search_phrase_op(il.... | f71a9ce5b949aea32077ec4b1b95dfcb19e7bcf5 | 53,570 |
def cube(path='./', pattern='', verbose=True):
""" Convenience wrapper around find.files to get *.cube files """
return files('cube', path=path, pattern=pattern, verbose=verbose) | 70ed21db1cb811ff6e8f118c12f7ff98989782ca | 53,571 |
def is_schema_compatible_in_topic(target_schema, topic):
"""Check whether given schema is a valid Avro schema and compatible
with existing schemas in the specified topic. Note that target_schema
is the avro json object.
"""
enabled_schemas = get_schemas_by_topic_name(topic.name)
for enabled_sche... | db30235c247ca41192ab80d3fd5e40a632286ead | 53,572 |
def JobStatus(jobid):
"""return status(es) of job
Parameter
---------
jobid
id of job
Returns
-------
list
state of each job in array
"""
status = []
for line in JobInfo(jobid, ['jobid', 'state'], noheader = True).split('\n'):
if (line.split() and '+' ... | fbeef89e588fdf7dda49d08cfc63992191a2ca7f | 53,573 |
def make_msg(comment, request):
""" Return a message from a comment & request. """
return build_msg('',
user_name = comment.user_name,
user_email = comment.user_email,
user_url = comment.user_email,
comment = comment.comment,
user_ip = request.META.get... | 4fed979fa478184e75c96fa3c78632797c210458 | 53,574 |
def DataFrameTableColumnComponent(
widget,
is_interactive,
column,
SpanOnBeginChange,
SpanOnEndChange,
TokenSpanOnBeginChange,
TokenSpanOnEndChange,
):
"""Constructs the widget component representing a single column of data within the table."""
column_items = []
# Begin with th... | 317b80a55a44eb42be0bf2456f50df5ca5fa6a08 | 53,575 |
def arg_wrap(fft_func, **extra_args):
"""Decorator to add kwargs based on fft suite.
Args:
fft_func: the fft function to arg wrap
extra_args: extra args to add to the PyFFTW call
Returns:
the wrapped function
"""
using_fftw = FFTMODULE.__name__.split('.')[0] == 'pyfftw'
def ... | 0dd9ed0da78aebc1ba1b82dcd3d2f4fd9bc736f2 | 53,577 |
import healpy
def get_healpix_dec_mask(dec_lim, nside):
"""
Compute a Healpix binnary mask given a limit declinaison
Parameters
----------
- dec_lim (deg): the limit declinaison for the mask
- nside : Healpix Nside argument
Outputs
--------
- mask (int array): the binnary mask cu... | 6bf968dc9d3ea106bb5bd74d70235dfd0c41be15 | 53,578 |
def singleton(fn):
"""
Lazily instantiate a function
"""
_instance = None
def wrapped():
nonlocal _instance
if _instance is None:
_instance = fn()
return _instance
return wrapped | c15a0b8a41a102cf4360af0bddbbdb289a794f87 | 53,579 |
def manhattan_distance(x, y):
""" Returns the Manhattan (City Block) distance between two lists
"""
return sum(abs(a - b) for a, b in zip(x, y)) | 4887024603a8fe3398ec80a17d1d70fbe15fdfab | 53,580 |
def score_from_local(directory):
"""Calculate score from a local results directory"""
results = gym.monitoring.monitor.load_results(directory)
# No scores yet saved
if results is None:
return None
episode_lengths = results['episode_lengths']
episode_rewards = results['episode_rewards']
... | 378de4e5c8b4c23c62f887630362c0552426503e | 53,581 |
def generate_dispatcher(method_handler, parent_class=None):
"""
Create a dispatcher class and return an instance of it from a dispatcher
definition.
The definition is a class with the following attributes:
_ EXPORTED_METHOD: dictionary where keys are method names and values
class attribute nam... | 9ea218791ec3d2e54b782cad9fce36b2d343962a | 53,583 |
def show_slave_hosts(server):
"""Function: show_slave_hosts
Description: Return the output of the 'show slave hosts' command.
Arguments:
(input) server -> Server instance.
(output) Results of command in dictionary format.
"""
return server.col_sql("show slave hosts") | 7adadfad7c84cb5b93b401ff3661a646fd315b48 | 53,584 |
from typing import Dict
def get_used_materials(materials_map: Dict[int, str], path_info: pd.DataFrame) -> str:
"""Collect text of used materials specifications.
Args:
materials_map: map material number -> spec.
path_info: dataframe containing column with used material numbers.
Returns:
... | 62af20460a72d66d215d03a8cc0e9bb0553f7bc4 | 53,585 |
def starting_coordinates():
"""
Starting coordinates on a pixel matrix.
"""
return (10, 10) | 68f8b493e36cba56808cfbcea6a4ee9368e0c720 | 53,586 |
def get_args():
"""Eat command line arguments, return argparse namespace for settings"""
parser = ArgumentParser()
parser.add_argument("filename", nargs="?",
help="trace file dump, stdin if not given")
parser.add_argument("-s", "--start", type=float, default=0,
help="start timest... | 13d602b5f56a29e4bd87e12ee26ecea5af4b29fb | 53,587 |
def delete_machine(index):
"""Add a new machine"""
Machine.delete(index)
return '', 200 | 5cf62890386c6bd2fd8300350c80570d96b86b6f | 53,588 |
def strip_html_tags(i_string):
"""
Quick solution to remove html tags being returned in episode description.
Will probably replace eventually.
"""
strippable = ('<p>', '</p>')
spaces = (' ',)
breaks = ('<br>',)
for s in strippable:
i_string = i_string.replace(s, '')
for... | 9454c7ee5e9006756426ca1fdecb97df8beb2cc4 | 53,589 |
def dos_element_spd_spin_polarized(
folder,
element_spd_dict,
output='dos_element_spd_sp.png',
fill=True,
alpha=0.3,
linewidth=1.5,
sigma=0.05,
energyaxis='x',
soc_axis='z',
color_list=None,
legend=True,
total=True,
figsize=(4, 3),
erange=[-6, 6],
fontsize=12,... | 8b1db8c829545a6f20a7c2dacb32e66220e851d6 | 53,590 |
def generate_index(csv_filepath):
"""
Generate an index 0...k for the k labels.
Parameters
----------
csv_filepath : str
Path to 'test.csv' or 'train.csv'
Returns
-------
tuple of dict and a list
dict : Maps a symbol_id as in test.csv and
train.csv to an integer in ... | 767d40f09405de3bddc85ba74c87c263a5adc612 | 53,592 |
import urllib
import json
def getPlayer(playerId,fullname):
"""
Retrieves player stats for the last game.
Career results can be added in the future
"""
url = "http://data.nba.net/prod/v1/2018/players/{}_gamelog.json".format(playerId)
with urllib.request.urlopen(url) as url2:
da... | ba91e44c4edd1f74a987fe98bc9d6c2667fe4aa1 | 53,593 |
def last_name_similarity_scorer(a: str, b: str):
"""Compares two first last strings, returns 1 if they match, 0 otherwise.
Uses Jaro-Winkler Distance Algorithm (JWDA) (en.wikipedia.org/wiki/Jaro–Winkler_distance).
JWDA "measurement scale is 0.0 to 1.0, where 0.0 is the least likely and 1.0 is a positiv... | 3851d22e2533133c0f76b863e9d184daee3a561a | 53,594 |
import random
def scoringInnings(team_1_array,
team_2_array,
innings,
bat_bowl_choice,
batting_score,
innings_data,
start_message,
max_overs,
max_wickets,
... | c285577203e86bb80db98ba21821eeeca8b67ea7 | 53,595 |
def fib_iter(n: int):
"""迭代解法,自低向上"""
dp = {}
dp[1] = dp[2] = 1
i = 3
while i <= n:
dp[i] = dp[i - 1] + dp[i - 2]
i += 1
return dp[n], dp | ec701c9f4b7c8a9c490e24bb90a309f1e0cdd7bf | 53,597 |
def convert_dashboard_tile_to_presentation_tile(element: dict) -> LookerPresentationTile:
"""Take the API response and convert into a LookerPresentationTile object"""
return LookerPresentationTile(
title=element['title'],
subtitle_text=element['subtitle_text'],
body=element['slide_params... | be08982305f5fdc7a2efee27344edc49238992ef | 53,598 |
def wrap_angle(array, wrap_count):
""" Wraps angle vector
Helper-function that wraps an angle vector containing angles in radian by
the number of elements specified by wrap count. The last wrap_count elements in
array are stacked to the beginning of the array and lowered by 2*pi and the
first... | a37d1a8e1e7ed42c3cc308df09c360e583d19fa6 | 53,599 |
import copy
import collections
def get_db_data(relation_data, unprefixed):
"""Organize database requests into a collections.OrderedDict
:param relation_data: shared-db relation data
:type relation_data: dict
:param unprefixed: Prefix to use for requests without a prefix. This should
... | 0e2a30624f35f49119ae9bd275153d5e9fdf7503 | 53,600 |
def KleinBottle():
"""
A minimal triangulation of the Klein bottle, as presented for example
in Davide Cervone's thesis [Cer1994]_.
EXAMPLES::
sage: simplicial_complexes.KleinBottle()
Minimal triangulation of the Klein bottle
"""
return UniqueSimplicialComplex([[2, 3, 7], [1, 2... | 37f00c16500b7cefe5f9c645d8a0d0aa986ab487 | 53,601 |
def speech_to_text(file_name, model_id):
"""Use Watson Speech to Text to convert audio file to text."""
# create Watson Speech to Text client
stt = SpeechToTextV1(iam_apikey=keys.speech_to_text_key)
# open the audio file
with open(file_name, 'rb') as audio_file:
# pass the file to Watson ... | d3e214e97c4d530a78ac9d2353ea38b3c70f5fdf | 53,602 |
def auth_connection(connection) -> openeo.Connection:
"""Connection fixture to a backend of given version with some image collections."""
connection.authenticate_basic(TEST_USER, TEST_PASSWORD)
return connection | 77638e524d014ddcdd75b6d3e40233b1175101f1 | 53,603 |
def convert(tree,fileName=None):
"""
Converts input files to be compatible with merge request #412, where we switch from custom
XML pathing to standard XPATH nomenclature.
@ In, tree, xml.etree.ElementTree.ElementTree object, the contents of a RAVEN input file
@ In, fileName, the name for the raven in... | 841f491370dc07d77f9af5428d78486136220ce9 | 53,604 |
def s3_lazy_put(filename, assume_immutable=False):
"""Put file to s3 only if out of sync."""
key = BUCKET.get_key(filename)
if key is None:
key = BUCKET.new_key(filename)
print 'uploading', filename
key.set_contents_from_filename(filename)
return key
elif assume_immutable... | b92c42194776d6f45e600716fb547109d5f87927 | 53,606 |
def moments(Xax, data, vheight=True, estimator=np.mean, negamp=None,
veryverbose=False, nsigcut=None, noise_estimate=None, **kwargs):
"""
Returns the gaussian parameters of a 1D distribution by calculating its
moments. Depending on the input parameters, will only output a subset of
the abo... | 63daf8eef8e2e24d97b8440ab81aa8aa21860002 | 53,607 |
def preprocess_adj(adj):
"""Preprocessing of adjacency matrix for simple GCN model"""
return normalize_adj(adj + sps.eye(adj.shape[0])).astype(np.float32) | fad916c7247ea1057450a78b17a2c8556719e35a | 53,608 |
from apysc._callable import callable_util
from apysc._event import handler_circular_calling_util as circ_util
from apysc._validation.variable_name_validation import \
def get_handler_name(
*, handler: _Handler, instance: Any) -> str:
"""
Get a handler name.
Parameters
----------
handler :... | 3b3051f2a79b4ecdcf7f5b5b362fdc6b3f2cf6ea | 53,609 |
def do_lookup(get_locations_func):
"""
Generic method which gets the locations in [(lat,lng),(lat,lng),...] format by calling get_locations_func
and returns an answer ready to go to the client.
:return:
"""
try:
locations = get_locations_func()
return {'results': [get_elevation(... | cd04851722836e37a5112428be26fa2f31ece1de | 53,610 |
def get_parameter_for_dev_mode(dev_mode_setting):
"""Return parameter for whether the test should be running on dev_mode.
Args:
dev_mode_setting: bool. Whether the test is running on dev_mode.
Returns:
str. A string for the testing mode command line parameter.
"""
return '--params.... | 502d8b070d441508c8c2e90700cdb807423d1e13 | 53,611 |
def get_username(prompt: str) -> str:
"""Prompt the user for a username"""
username = input(prompt)
return username | c6d6119ba9b2b1ec9408501afb04b513aa9b4965 | 53,613 |
def preprocess(x, y, nb_classes=10, clip_values=None):
"""Scales `x` to [0, 1] and converts `y` to class categorical confidences.
:param x: Data instances.
:type x: `np.ndarray`
:param y: Labels.
:type y: `np.ndarray`
:param nb_classes: Number of classes in dataset.
:type nb_classes: `int`
... | ed3abcec3cede4f97d1693f67653d3c57b7e5413 | 53,615 |
def mkatas(u_t, v_t, wap, t_t, ttt, g_w, p_l, lat, nlat, ntp, nlev):
"""Compute the stat.-trans. eddy APE conversions from u, v, wap and t.
Arguments:
- u_t: a 3D zonal velocity field;
- v_t: a 3D meridional velocity field;
- wap: a 3D vertical velocity field;
- t_t: a 3D temperature field;
... | 5656377647c143124c0c85d3b920393e2640cbed | 53,616 |
def fourier_model(cn, Nfreqs):
"""
Calculate a 1D (complex) Fourier series model from a set of complex coefficients.
Parameters
----------
coeffs : array_like
Array of complex Fourier coefficients, ordered from (-n, n), where n is
the highest harmonic mode in the model.
Nfreqs ... | 77c5dcad9535ab1e673bde66446081f23c329377 | 53,617 |
def remove_low_information_features(feature_matrix, features=None):
"""Select features that have at least 2 unique values and that are not all null
Args:
feature_matrix (:class:`pd.DataFrame`): DataFrame whose columns are feature names and rows are instances
features (list[:class:`f... | 0377b2b87d04ddaa89e332ed72c12a05b4a1c3e6 | 53,618 |
def latlt2cart(lat,lt,hemisphere):
"""
Latitude and local time to cartesian for a top-down dialplot
"""
r,theta = latlt2polar(lat,lt,hemisphere)
return r*cos(theta),r*sin(theta) | e295fd58fb57069229cb20a15d02b8a2d591d1d1 | 53,619 |
import hashlib
def md5_password(password, salt):
"""获取原始密码+salt的md5值
"""
trans_str = password + salt
md = hashlib.md5()
md.update(trans_str.encode('utf-8'))
return md.hexdigest() | cbb4306bfa1e11957a56d5ace5d810ac421f5d83 | 53,620 |
import math
def build_belief(belief_type: Belief, num_agents=NUM_AGENTS, **kwargs):
"""Evenly distributes the agents beliefs into subgroups.
"""
if belief_type is Belief.MILD:
middle = math.ceil(num_agents / 2)
return [0.2 + 0.2 * i / middle if i < middle else 0.6 + 0.2 * (i - middle)... | e83ca205cf528e3ed1400892077172dd195c9389 | 53,621 |
def create(workout_type, user_id):
"""Creates a workout object of the specified type."""
workout = None
if workout_type == Keys.WORKOUT_TYPE_EVENT:
workout = Event.Event(user_id)
elif workout_type == Keys.WORKOUT_TYPE_REST:
workout = Rest.Rest(user_id)
else:
workout = Workout... | 552457989abd845087411642895371aa272003d9 | 53,623 |
def clean_dfg_based_on_noise_thresh(dfg, activities, noise_threshold, parameters=None):
"""
Clean Directly-Follows graph based on noise threshold
Parameters
----------
dfg
Directly-Follows graph
activities
Activities in the DFG graph
noise_threshold
Noise threshold
... | 91e250dee69ae46fdbe410c64c533b13b07aa439 | 53,624 |
def post_form(lti):
# pylint: disable=unused-argument,
"""
Access route with 'initial' request.
:param lti: `lti` object
:return: string "hi"
"""
return "hi" | 1715ede499f78025730c936d9a167c5e6cc1caa6 | 53,625 |
def cached_accessor(func_or_att):
"""Decorated function checks in-memory cache and disc cache for att first"""
if callable(func_or_att): #allows decorator to be called without arguments
att = func_or_att.__name__
return cached_accessor(func_or_att.__name__)(func_or_att)
att = func_or_att
... | d63b216b76038081378be22678337c9ae4420ccc | 53,626 |
import collections
def api_root(request, format=None):
"""
GET:
Display all available urls.
Since some urls have specific permissions, you might not be able to access
them all.
"""
apis = PUBLIC_APIS(request, format)
if request.user.is_staff:
apis += PROTECTED_APIS(request, fo... | 16e8b671f57dbf7859216055ecba95960e29a176 | 53,630 |
from typing import Tuple
import requests
import time
def get_gas_from_etherscan(key: str,
verbose: bool = False) -> Tuple[int, int, int]:
"""
Fetch gas from Etherscan API
"""
r = requests.get('https://api.etherscan.io/api',
params={'module': 'gastracker'... | b61df980f33ff1471017a6531805c229712708d9 | 53,631 |
def bit(value, position, length=1):
"""
Return bit of number value at position
Position starts from 0 (LSB)
:param value:
:param position:
:param length:
:return:
"""
binary = bin(value)[2:]
size = len(binary) - 1
if position > size:
return 0
else:
return ... | f639eae3d3f260b5b0d29ddd6a3ad99c89267704 | 53,632 |
from operator import mod
def sidereal_lunar_longitude(tee):
"""Return sidereal lunar longitude at moment, tee."""
return mod(lunar_longitude(tee) - precession(tee) + SIDEREAL_START, 360) | 9e3406527da1ffbc3cb4223f30cf92a4a703b3e0 | 53,633 |
def create_view_event_from_tensor_basic_info(tensors_info):
"""
Create view event reply according to tensor names.
Args:
tensors_info (list[TensorBasicInfo]): The list of TensorBasicInfo. Each element has keys:
`full_name`, `node_type`, `iter`.
Returns:
EventReply, the even... | f288fe55942dd55d513e807419401d00f22ae7a5 | 53,634 |
def diff_template(page, label=None):
"""
Return a Template:Diff2 string for the given Page.
"""
if label is None:
label = page.title()
return f"{{{{Diff2|{page.latest_revision_id}|{label}}}}}" | 48cca6ad78ce2e0f2e1ce4902d56734fccf45030 | 53,635 |
def is_builtin(func):
"""Return true if the function is a DGL builtin function."""
return isinstance(func, fn.BuiltinFunction) | 2cdd395672f7e72a42be80c718f5b389d261befe | 53,636 |
import warnings
def compute_sun_angle(
position,
pose,
utc_datetime,
sensor_orientation,
):
""" compute the sun angle using pysolar functions"""
altitude = 0
azimuth = 0
with warnings.catch_warnings(): # Ignore pysolar leap seconds offset warning
warnings.simplefilter("ignore")... | 34df23edf3818b53fc3b501173a116d38ae8e108 | 53,637 |
def find_tuple_with_max_ncp(base, T, key, T_max_vals, T_min_vals):
"""
Scan through the whole table T, and find the i-th tuple that maximizes NCP(base, i).
Parameters
----------
:param base: list of int
Tuple to compare T's tuples against
:param key: T
the table
:param... | 0f48f01dc5a7ccf2f78c4f7e0f614a8ca6f765eb | 53,638 |
import re
def make_dataset_name(name):
"""Dataset name contains "letters, numbers, -, _" only, any other content will be replaced with "-"
"""
def may_replace(c):
if re.match("\w", c) is None:
if c == '-':
return c
else:
return "_"
e... | bf97474ffcb0c5e0354c724ca4defea1b04f8939 | 53,639 |
def averageOfNumbers():
""" averageOfNumbers
Outputs the average of a series of numbers entered by the user.
returns:
The average of the numbers input by the user.
"""
numbers = []
amount_of_numbers = input("How many numbers do you wish to input? ")
for x in range(1, int(amount... | 3403bf775f0675e0f54dc18f5146e37989fc0ce2 | 53,640 |
import csv
import tqdm
def process_covid_ctset_data(covid_ctset_meta_csv, covid_ctset_dir, output_dir):
"""Processes slices for all patients in the given COVID-CTSet CSV file"""
filenames = []
classes = []
with open(covid_ctset_meta_csv, 'r') as f:
reader = list(csv.DictReader(f, delimiter=','... | 4fd588f01667e0e91ae222f1b13684722d77c6ce | 53,641 |
import time
def pinsage_sample(graph,
nodes,
samples,
top_k=10,
proba=0.5,
norm_bais=1.0,
ignore_edges=set()):
"""Implement of graphsage sample.
Reference paper: .
Args:
graph: A pgl... | 7884479e95b91c5396745a805525aa0eee224445 | 53,643 |
import math
def calc_entropy(data, base=2):
"""
Calculate the entropy of data. Using documentation from
scipy.stats.entropy as the basis for this code
(https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html).
:param data: Measure the entropy of this object
:return: Calcu... | 72a9d111120415471c7d54e11c862ce8ebde4a55 | 53,645 |
import functools
def singledispatch_method(func):
"""Singledispatch on second argument, i.e. the one that isn't `self`."""
dispatcher = functools.singledispatch(func)
def wrapper(*args, **kw):
return dispatcher.dispatch(args[1].__class__)(*args, **kw)
wrapper.register = dispatcher.register
... | 5f1afbcba1d97420bc4b29ff983e19acd1159d3b | 53,646 |
import functools
def authenticate_user_registration(some_function):
""" Decorator for functions (pages) that require a user to provide identification. Returns
403 (forbidden) or 401 (depending on beiwe-api-version) if the identifying info (username,
password, device ID) are invalid.
In any function wr... | 293a8441e652e15b60529c2d6a8aa5fa0766ce57 | 53,648 |
def getValidPaths(author_collabs, year):
"""
selects the neighbours with valid paths
returns a list where each result is a tuple of author name, collaborations < year
"""
valid_neighbours = list()
for n in author_collabs:
valid_collabs = list()
for c in author_collabs[n]:
... | b9cc56b3bee490296afb9448c6082eb0206a74e7 | 53,649 |
def get_same_pinyin(char):
"""
取同音字
:param char:
:return:
"""
return same_pinyin.get(char, set()) | f53d9c61313dbd4b5263733a287065bfd8b78cb9 | 53,651 |
def get_chart_params(title, output, show_legend=False):
"""Parse output type and output options and return related chart
parameters. For example: returns filename if output_type is file
or server it output_type is server
Args:
title (str): the title of your plot.
output (str): selected ... | 6e120ba54ce690c3f75e3ee1def0ea804f06bfb5 | 53,652 |
def preprocess(img, net_input_height_size=368, stride=8,
pad_value=(0, 0, 0), img_mean=(128, 128, 128), img_scale=1/256):
"""
Args:
img:
Returns:
"""
height, width, _ = img.shape
scale = net_input_height_size / height
scaled_img = cv2.resize(img, (0, 0), fx=scale,... | d2c363b8101990a5069a359ac33ebf32a91fdbed | 53,653 |
def compute_DVARS(func_img, mean_img=None, mask=None, apply_mask=False):
"""Computes the DVARS for a given fMRI image."""
if mean_img is None:
mean_img = np.mean(func_img, axis=3)
if apply_mask:
if mask is None:
mask = mask_image(mean_img)
mean_img[np.logical_not(mask)]... | 7736cdfe6fd2ed243f262d0d2dbf3c661729bac4 | 53,654 |
def count_unplayed_cards(r, progress):
"""Returns the number of cards which are not yet played, including cards
which are unplayable because all those cards (or cards of a value below it)
are already discarded"""
n = 0
for suit in r.suits:
n += 5 - progress[suit]
return n | 445b1b3d07aff4c2010fc482cb7f5b55a8250bac | 53,655 |
def index(request):
"""View function for home page of site."""
# Render the HTML template index.html with the data in the context variable.
return render(
request,
'index.html',
context = {},
) | c76567019712cc77dbe41c34d179ed82959b952d | 53,656 |
def find_start_time(arr, reps=1):
"""! A function to find when simulations reaches a steady state with
respect to array, arr.
@param arr: Array to find steady state in
@param reps: repetitions of recursion
@return: st Start time, the index of time array when the simulation
first reaches a the s... | 11951c82ddbcd33130cfcd224e7511e8600bbe7e | 53,657 |
import torch
def calc_region(bbox, ratio, featmap_size=None):
"""Calculate a proportional bbox region.
The bbox center are fixed and the new h' and w' is h * ratio and w * ratio.
Args:
bbox (Tensor): Bboxes to calculate regions, shape (n, 4)
ratio (float): Ratio of the output region.
... | eaea91d60f34ab146cb48ff905eac8a0b5d21d7c | 53,659 |
def toFENhash(fen):
""" Removes the two last parts of the FEN notation
"""
return ' '.join(fen.split(" ")[:-2]) | bc2575ce35f8d2678753369d2b3a4d050388891f | 53,660 |
def remap_lads(lad_name):
"""Some LADs of MSOA census data do not match
the LAD geographies of the LAD population data
"""
if lad_name == 'E06000048':
lad_mapped = 'E06000057' #Northumberland
elif lad_name == 'E08000020':
lad_mapped = 'E08000037'
elif lad_name == 'E07000097':
... | 46e13886a4541fcd5a47870d845db717373084cc | 53,661 |
def generate_dummy_ip():
"""
makes a random ip address as a string
"""
return str(randint(0,255)) + "." + str(randint(0,255)) + "." + str(randint(0,255)) + "." + str(randint(0,255)) | fa893e110c4fbf0313a96d78b31dd27c29b9fc35 | 53,662 |
def get_paying_proxy_contract(w3: Web3, address=None):
"""
Get Paying Proxy Contract. This should be used just for contract creation/changing master_copy
If you want to call Safe methods you should use `get_safe_contract` with the Proxy address,
so you can access every method of the Safe
:param w3: ... | 1e3264d551e3b0604dc5f5c5f79c15412fc82fe8 | 53,665 |
def validate(detector, val_data, metric):
"""Test on validation dataset."""
metric.reset()
for img, label in val_data:
# scores, bboxes = detector.detect(img)
scores, bboxes = detector.ms_detect(img)
metric.update(bboxes, scores, label)
return metric.get() | 7b9f3a5405ea40eba37765d7fbc5b204203c96de | 53,667 |
def calculate_EcefPoints(lats, longs):
"""
Construct a numpy array of EcefPoints from 2 arrays containing
Latitudes and Longitudes.
Note: lats and longs must be of equal lengths.
Parameters
----------
lats: float array
An array of Latitudes in [degrees].
longs: float array
... | daa1497b0d14773386d519cd8b33bca2e2e122fd | 53,668 |
def compute_flow_map(u, v, gran=8):
"""
Plot optical flow map
"""
flow_map = np.zeros(u.shape)
for y in range(flow_map.shape[0]):
for x in range(flow_map.shape[1]):
if y % gran == 0 and x % gran == 0:
dx = 2 * int(u[y, x])
dy = 2 * int(v[y, x])
... | 3c74a87158e59980c0e807f24f4cbf3be80e8954 | 53,669 |
def brand_usage(number_of_brand_purchasers, total_purchasers):
"""Returns the percentage of brand usage for a period.
Args:
number_of_brand_purchasers (int): Total number of unique purchasers of a brand in a period.
total_purchasers (int): Total unique purchasers in a period.
Returns:
... | cc7478c4810876ea0a335e639a861dc9175028af | 53,670 |
def sim_walks(num_steps, num_trials, d_class):
"""Assumes num_steps an int >= 0, num_trials an int > 0,
d_class a subclass of Drunk
Simulates num_trials walks of num_steps steps each.
Returns a list of the final distances for each trial"""
Homer = d_class()
origin = Location(0, 0)
... | fffa42653f1b6e84eea10fac5cba6b6390129288 | 53,671 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.