content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def dequote(s):
""" Remove outer quotes from string
If a string has single or double quotes around it, remove them.
todo: Make sure the pair of quotes match.
If a matching pair of quotes is not found, return the string unchanged.
"""
if s.startswith(("'", '"', '<')):
return s[1:-1... | ab56306fd9f21e2f43cd2325182e2cae202aae6f | 5,500 |
def display_ordinal_value(glyph: str):
"""Displays the integer value of the given glyph
Examples:
>>> display_ordinal_value('🐍')\n
128013
>>> display_ordinal_value('G')\n
71
>>> display_ordinal_value('g')\n
103
"""
return ord(glyph) | 7daa53180023bfec2968308d463ac615a83a4e55 | 5,501 |
def mixture_HPX( gases, Xs ):
"""
Given a mixture of gases and their mole fractions,
this method returns the enthalpy, pressure, and
composition string needed to initialize
the mixture gas in Cantera.
NOTE: The method of setting enthalpy
usually fails, b/c Cantera uses a Newton
itera... | a04a2bdcd1a58eaf26facf2f542d2c1aaba6e611 | 5,502 |
import json
def authorize(config):
"""Authorize in GSheets."""
json_credential = json.loads(config['credentials']['gspread']['credential'])
credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_credential, scope)
return gspread.authorize(credentials) | fd54e0df5a71d2896f925dbd9d4e7536659906f9 | 5,503 |
def _without_command(results):
"""A helper to tune up results so that they lack 'command'
which is guaranteed to differ between different cmd types
"""
out = []
for r in results:
r = r.copy()
r.pop('command')
out.append(r)
return out | 67927cf56884e0e3b22d0daf37e6c02eaef3849b | 5,504 |
def b(k, a):
"""
Optimal discretisation of TBSS to minimise error, p. 9.
"""
return ((k**(a+1)-(k-1)**(a+1))/(a+1))**(1/a) | d563a39710aec05334f38af704371db1dc7f94fc | 5,505 |
from typing import Tuple
from typing import Dict
def changepoint_loc_and_score(
time_series_data_window: pd.DataFrame,
kM_variance: float = 1.0,
kM_lengthscale: float = 1.0,
kM_likelihood_variance: float = 1.0,
k1_variance: float = None,
k1_lengthscale: float = None,
k2_variance: float = N... | ffa6c41ea9b7403130908e22fd82b396dc1a1af7 | 5,506 |
def get_network_interfaces(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP if specified.
"""
network_interfaces = []
networks = properties.get('networks', [])
if len(networks) == 0 and properties.get('network'... | 0f8db05c0c8b95f8bde7752a9e9766e479db098f | 5,507 |
def MATCH(*args) -> Function:
"""
Returns the relative position of an item in a range that matches a specified
value.
Learn more: https//support.google.com/docs/answer/3093378
"""
return Function("MATCH", args) | aa03f558e0948fac023622b6569bb6f504e92cba | 5,508 |
def set_dict_to_zero_with_list(dictionary, key_list):
""" Set dictionary keys from given list value to zero
Args:
dictionary (dict): dictionary to filter
key_list (list): keys to turn zero in filtered dictionary
Returns:
dictionary (dict): the filtered dictio... | 498c0c4a7444c0bbb33168c2f17bfcf2bd8e805e | 5,509 |
def terminal_condition_for_minitaur_extended_env(env):
"""Returns a bool indicating that the extended env is terminated.
This predicate checks whether 1) the legs are bent inward too much or
2) the body is tilted too much.
Args:
env: An instance of MinitaurGymEnv
"""
motor_angles = env.robot.motor_ang... | be80901777bc7d5c03b152e3c9af9a30c3526d1e | 5,510 |
from sys import path
def data_range(dt_start, dt_end):
"""read raw VP data between datetimes"""
filepath_fmt = path.join(DATA_DIR, DATA_FILE_FMT)
fnames = strftime_date_range(dt_start, dt_end, filepath_fmt)
pns = map(vprhimat2pn, fnames)
pns_out = []
for pn in pns:
if not pn.empty:
... | d71047a4c08dbfff4827c9baac026e981f975a38 | 5,511 |
import lt_shiso
import logparser
import lt_import
import lt_crf
import lt_shiso
import lt_misc
import os
def init_ltmanager(conf, db, table, reset_db):
"""Initializing ltmanager by loading argument parameters."""
lt_alg = conf.get("log_template", "lt_alg")
ltg_alg = conf.get("log_template", "ltgroup_alg")... | c11ab3426ac8abd3ea0128934a47ac14f69ea5ac | 5,512 |
def print_tree(tree, level=0, current=False):
"""Pretty-print a dictionary configuration `tree`"""
pre = ' ' * level
msg = ''
for k, v in tree.items():
if k == 'self':
msg += print_tree(v, level)
continue
# Detect subdevice
if isinstance(v, dict) and 'se... | f9697b506e9254b4982a037bdfbeb8a1d27f35bb | 5,513 |
def chaine_polynome(poly):
"""Renvoie la représentation dy polynôme _poly_ (version simple)"""
tab_str = [str(coef) + "*X^" + str(i) if i != 0 else str(coef) for i,coef in enumerate(poly)]
return " + ".join(tab_str[::-1]) | 79fd59afe84c1bd12e3417b9195514664d1bce20 | 5,514 |
def get_opr_from_dict(dict_of_opr_vals):
"""Takes in a dictionary where the keys are temperatures and values are optical rotation
values. The dictionary is for all the temperatures and optical rotation values extracted
for one molecule. This function determines which of the values in the dictionary to kee... | c0c688835ffb38fe4fb1a88fd91f8374d854d75a | 5,515 |
import re
def tokens(s):
"""Return a list of strings containing individual words from string s.
This function splits on whitespace transitions, and captures apostrophes
(for contractions).
>>> tokens("I'm fine, how are you?")
["I'm", 'fine', 'how', 'are', 'you']
"""
words = re.findall(r... | aee0b6fad2f9107c893496f1f3807e80c9d2e44b | 5,516 |
def get_variable_value(schema, definition_ast, input):
"""Given a variable definition, and any value of input, return a value which adheres to the variable definition, or throw an error."""
type = type_from_ast(schema, definition_ast.type)
if not type or not is_input_type(type):
raise GraphQLError(
... | 09c3fa10dcb25704c6323f78d244b27605a393ed | 5,517 |
def _convert_3d_crop_window_to_2d(crop_window):
"""Converts a 3D crop window to a 2D crop window.
Extracts just the spatial parameters of the crop window and assumes that those
apply uniformly across all channels.
Args:
crop_window: A 3D crop window, expressed as a Tensor in the format
[offset_heigh... | e5eb7d97c55c0ab18caf135728bb1daa6e5b2d8c | 5,518 |
def apply_along_axis(func1d, mat, axis):
"""Numba utility to apply reduction to a given axis."""
assert mat.ndim == 2
assert axis in [0, 1]
if axis == 0:
result = np.empty(mat.shape[1], mat.dtype)
for i in range(len(result)):
result[i, :] = func1d(mat[:, i])
else:
... | 87f1dcd3ed04e8626a59aaff1caabba6c52ce8d3 | 5,519 |
def get_all_article():
"""
获取所有 文章资讯
---
tags:
- 资讯文章 API
responses:
200:
description: 文章资讯更新成功
404:
description: 资源不存在
500:
description: 服务器异常
"""
articles = ArticleLibrary.get_all()
return jsonify(articles) | 7304e862351730ace03ad8e784665cf844d1c94f | 5,520 |
def cut_fedora_prefix(uri):
"""
Cut the Fedora URI prefix from a URI.
"""
return uri[len(FEDORA_URI_PREFIX):] | 617b00bc34f4ad69b82858496ecc19bc2a5e6fd2 | 5,521 |
def get_database_login_connection(user,password,host,database):
""" Return database connection object based on user and database details provided """
connection = psycopg2.connect(user = user,
password = password,
host = host,
... | 55b8cd2fb7e9e2acc00ce76c660f709920d59eb8 | 5,522 |
def getaddrinfo(host,port,family=0,socktype=socket.SOCK_STREAM,proto=0,allow_cname=True):
"""Resolve host and port into addrinfo struct.
Does the same thing as socket.getaddrinfo, but using `pyxmpp.resolver`. This
makes it possible to reuse data (A records from the additional section of
DNS reply) retu... | 1e65eb69a2d23dd93b0676be5e739545674aa021 | 5,523 |
import copy
import json
def get_layout_for_dashboard(available_pages_list):
"""
Makes the dictionary that determines the dashboard layout page.
Displays the graphic title to represent the graphic.
:param available_pages_list:
:return:
"""
available_pages_list_copy = copy.deepcopy(available... | a391a93a70c0fc755657a6b93ef90bd4811b6d4c | 5,524 |
def median(list_in):
"""
Calculates the median of the data
:param list_in: A list
:return: float
"""
list_in.sort()
half = int(len(list_in) / 2)
if len(list_in) % 2 != 0:
return float(list_in[half])
elif len(list_in) % 2 ==0:
value = (list_in[half - 1] + list_in[half... | 261487551098b80986cbfb8e4cd28279649ac456 | 5,525 |
def search_file(expr, path=None, abspath=False, follow_links=False):
"""
Given a search path, recursively descend to find files that match a
regular expression.
Can specify the following options:
path - The directory that is searched recursively
executable_extension - This string is used ... | f3d2501f535865455646168ecf81a4a12e66fcfa | 5,526 |
import logging
def delete_gwlbe(gwlbe_ids):
"""
Deletes VPC Endpoint (GWLB-E).
Accepts:
- gwlbe_ids (list of str): ['vpce-svc-xxxx', 'vpce-svc-yyyy']
Usage:
- delete_gwlbe(['vpce-xxxx', 'vpce-yyyy'])
"""
logging.info("Deleting VPC Endpoint Service:")
try:
response = ec2.d... | 854b9991dda8198de87895ddf7dbc65fbb6746e8 | 5,527 |
def subdivide_loop(surface:SurfaceData, number_of_iterations: int = 1) -> SurfaceData:
"""Make a mesh more detailed by subdividing in a loop.
If iterations are high, this can take very long.
Parameters
----------
surface:napari.types.SurfaceData
number_of_iterations:int
See Also
------... | 85fda9f2626f3fdd48c0a2eecbc4d3dffc49919a | 5,528 |
def register():
"""Register a new user.
Validates that the username is not already taken. Hashes the
password for security.
"""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
phone = request.form['full_phone']
cha... | 9e1b2c86a20710d56cf5cf737ab1a35d67970179 | 5,529 |
import os
def gen_key():
"""Function to generate a new access key which does not exist already"""
key = ''.join(choice(ascii_letters + digits) for _ in range(16))
folder = storage + key
# Repeat until key generated does not exist
while(os.path.exists(folder)):
key = ''.join(choice(ascii_l... | 42b4619c2d61d465ec2141625954d7410e411c05 | 5,530 |
import requests
import logging
def get_url(url, headers=None):
"""
get content from specified URL
"""
reply = requests.get(url, headers=headers)
if reply.status_code != 200:
logging.debug('[get_attribute] Failed to open {0}'.format(url))
return None
else:
return reply.... | faf182c2dc162f25abab5875e0c4253ca98df8a6 | 5,531 |
def Read_FImage(Object, Channel, iFlags=0):
"""
Read_FImage(Object, Channel, iFlags=0) -> bool
Read_FImage(Object, Channel) -> bool
"""
return _Channel.Read_FImage(Object, Channel, iFlags) | 06af43adbbfaf94e9f26b1ad41d6ba6f7ae5cfe7 | 5,532 |
import json
import yaml
def Export(message, stream=None, schema_path=None):
"""Writes a message as YAML to a stream.
Args:
message: Message to write.
stream: Output stream, None for writing to a string and returning it.
schema_path: JSON schema file path. If None then all message fields are
wri... | 53f74ff11dfe46eab0549ea466c5ea80c6876bd7 | 5,533 |
def user_locale_get(handle, user_name, name, caller="user_locale_get"):
"""
gets locale for the user
Args:
handle (UcsHandle)
user_name (string): username
name (string): locale name
Returns:
AaaUserLocale: managed object
Raises:
UcsOperationError: if AaaUse... | a748d8fd2e349c43dfabd07108943005be95729e | 5,534 |
from typing import Dict
from typing import List
from typing import Set
from typing import Any
from functools import reduce
def get_set_from_dict_from_dict(
instance: Dict[str, Dict[str, List]], field: str
) -> Set[Any]:
"""
Format of template field within payload
Function gets field from instance-dict... | 75ee6f4d46a4f57012e76b0f02fb20f629b6bf60 | 5,535 |
def initiate_os_session(unscoped: str, project: str) -> keystoneauth1.session.Session:
"""
Create a new openstack session with the unscoped token and project id.
Params:
unscoped: str
project: str
Returns:
A usable keystone session object for OS client connections
Return typ... | ab96af612721a5043c60e9a76c512301b0b1de6f | 5,536 |
def delete_topic_collection_items(request_ctx, collection_item_id, topic_id, **request_kwargs):
"""
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
... | 3c45e9f0b65e731480c8a81163be01b5cd5fbd83 | 5,537 |
from typing import List
def xml_section_extract_elsevier(section_root, element_list=None) -> List[ArticleElement]:
"""
Depth-first search of the text in the sections
"""
if element_list is None:
element_list = list()
for child in section_root:
if 'label' in child.tag or 'section-ti... | 919e1bb7f1ae96b857776f6c81c3e032cfbba4a9 | 5,538 |
def get_data_from_string(string, data_type, key=None):
"""
Getting data from string, type can be either int or float or str.
Key is basically starts with necessary string.
Key is need only when we parse strings from execution file
output (not from test.txt)
"""
data = []
if data_type i... | 10135d96bd0cdb37d38268a795f92d80be294adc | 5,539 |
import requests
def greenline(apikey, stop):
"""
Return processed green line data for a stop.
"""
# Only green line trips
filter_route = "Green-B,Green-C,Green-D,Green-E"
# Include vehicle and trip data
include = "vehicle,trip"
# API request
p = {"filter[route]": filter_route... | 254a7cb43cf0789b1437b6ee3ea2262b4d22b4ca | 5,540 |
def Get_Unread_Messages(service, userId):
"""Retrieves all unread messages with attachments, returns list of message ids.
Args:
service: Authorized Gmail API service instance.
userId: User's email address. The special value "me".
can be used to indicate the authenticate... | 2aa28ff1aa093754bd293a831be2dada0e629801 | 5,541 |
def rmse(y_true, y_pred):
"""
rmse
description:
computes RMSE
"""
return sqrt(mean_squared_error(y_true, y_pred)) | 377849b692190ae880221676eb898bbe84e466e5 | 5,542 |
from pathlib import Path
from typing import Type
def read_model_json(path: Path, model: Type[ModelT]) -> ModelT:
"""
Reading routine. Only keeps Model data
"""
return model.parse_file(path=path) | 0b0fb327efdc1acaff2adce3e5b738a1cabbf30a | 5,543 |
def details(request, id=None):
"""
Show details about alert
:param request:
:param id: alert ID
:return:
"""
alert = get_object_or_404(Alert, id=id)
context = {
"user": request.user,
"alert": alert,
}
return render(request, "alerts/details.html", context) | 9522a69fc69eb80da301541073bfc320e991fae8 | 5,544 |
def get_class_id_map():
"""Get mapping between class_id and class_name"""
sql = """
SELECT class_id
, class_name
FROM classes
"""
cur.execute(f"{sql};")
result = [dict(x) for x in cur.fetchall()]
class_map = {}
for r in result:
class_m... | d72df95f3f27cbfb04fe32b09d672ea1cff3cbc6 | 5,545 |
def epsilon_nfa_to_nfa(e_nfa: automata.nfa.EpsilonNFA)->automata.nfa.NFA: # todo: add tests
"""
Casts epsilon NFA to NFA.
:param EpsilonNFA e_nfa: original epsilon NFA
:return NFA: cast NFA that takes the same languages.
"""
assert type(e_nfa) is automata.nfa.EpsilonNFA
work = e_nfa.deepco... | 4ac75c1c7d4356e6ceb47b64273dea596988372b | 5,546 |
def potatoes(p0, w0, p1):
"""
- p1/100 = water1 / water1 + (1 - p0/100) * w0
=> water1 = w0 * p1/100 * (1 - p0/100) / (1 - p1/100)
- dry = w0 * (1 - p0/100)
- w1 = water1 + dry = w0 * (100 - p0) / (100 - p1)
Example:
98/100 = water1 / water1 + (1- 99/100) * 100
water1 = 49
w1 = 49... | f2955a58db3a48c64b6acc4980e663f33332aeea | 5,547 |
def calc_Cinv_CCGT(CC_size_W, CCGT_cost_data):
"""
Annualized investment costs for the Combined cycle
:type CC_size_W : float
:param CC_size_W: Electrical size of the CC
:rtype InvCa : float
:returns InvCa: annualized investment costs in CHF
..[C. Weber, 2008] C.Weber, Multi-objective design... | 92ea26dcfc66996dd564da9df73a117a57b308bd | 5,548 |
def get_middle_slice_tiles(data, slice_direction):
"""Create a strip of intensity-normalized, square middle slices.
"""
slicer = {"ax": 0, "cor": 1, "sag": 2}
all_data_slicer = [slice(None), slice(None), slice(None)]
num_slices = data.shape[slicer[slice_direction]]
slice_num = int(num_slices / ... | 7ab60139c38fd79a866ed14f065a3333c532162a | 5,549 |
import re
def glewIsSupported(var):
""" Return True if var is valid extension/core pair
Usage: glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite")
Note: GLEW API was not well documented and this function was
written in haste so the actual GLEW format for glewIsSupported
might be different.
TODO:
... | 114d4eb9f308f15f9169f24b418e4d78d4b792d8 | 5,550 |
def example_two():
"""Serve example two page."""
return render_template('public/examples/two.j2') | 759721686f0411d1ee5ad75f76ed5a0158067bae | 5,551 |
def omegaTurn(r_min, w_row, rows):
"""Determines a path (set of points) representing a omega turn.
The resulting path starts at 0,0 with a angle of 0 deg. (pose = 0,0,0). It
will turn left or right depending on if rows is positive (right turn) or
negative (left turn). Path should be translated and rota... | 39d3203d26199c585371e0208228c8b2839a8cd0 | 5,552 |
def sparse_ones(indices, dense_shape, dtype=tf.float32, name="sparse_ones"):
""" Creates a new `SparseTensor` with the given indices having value 1
Args:
indices (`Tensor`): a rank 2 tensor with the `(row,column)` indices for the resulting sparse tensor
dense_shape (`Tensor` or `TensorShape`): ... | 1dad9ce8d1f1ab1950f744fbfa084884732ea8de | 5,553 |
from typing import Any
def ask(*args: Any, **kwargs: Any) -> Any:
"""Ask a modular question in the statusbar (blocking).
Args:
message: The message to display to the user.
mode: A PromptMode.
default: The default value to display.
text: Additional text to show
option: ... | f5c65a4cdc83b5c22c4de97e41ed8a740f94ec3d | 5,554 |
import re
def get_sale(this_line, cattle, category):
"""Convert the input into a dictionary, with keys matching
the CSV column headers in the scrape_util module.
"""
cattle = cattle.replace("MARKET","")
cattle = cattle.replace(":","")
cattle = cattle.strip().title()
sale = {'cattle_cattle'... | f75e949558c9938a44f64ccce11bacce8d116e9f | 5,555 |
import os
import requests
def get_request(term, destination, days_input, price_limit, food_preference):
"""
Fetches restaurant information from the Yelp API for a given meal term, meal attribute, destination, number of days of vacation, price limit, and food preference.
Params:
term (str) the spe... | df9b5a2534278963dc5fa0719db3f915ce8fcb8d | 5,556 |
def eig_min(a, eps=1e-7, kmax=1e3, log=False):
"""
:param a: matrix to find min eigenvalue of
:param eps: desired precision
:param kmax: max number of iterations allowed
:param log: whether to log the iterations
"""
mu_1 = eig_max_abs(a, eps, kmax, log)
return mu_1 - eig_max_abs(mu_1 * np.eye(a.shape[0]) - a... | 0c990207fe2b3a77aba636918bf78d9a138b718d | 5,557 |
def relacao(lista):
"""Crie uma função que recebe uma lista de números reais e retorna uma outra lista de tamanho 3 em que
(i) o primeiro elemento é a quantidade de números maiores que zero,
(ii) o segundo elemento é a quantidade de números menores que zero e
(iii) o último elemento é a quantidade de... | 39e45d8221d5d5b7322ebec5aa3f761d9e2ef413 | 5,558 |
def _input_to_dictionary(input_):
"""Convert.
Args:
input_: GraphQL "data" dictionary structure from mutation
Returns:
result: Dict of inputs
"""
# 'column' is a dict of DB model 'non string' column names and their types
column = {
'idx_user': DATA_INT,
'enable... | 263eb2449e8d272ef6c7e147ca7286f70e5cdbf9 | 5,559 |
def validate(request):
"""Validate an authentication request."""
email_token = request.GET.get('a')
client_token = request.GET.get('b')
user = authenticate(email_token=email_token, counter_token=client_token)
if user:
login(request, user)
return redirect(request.GET.get('success', '/... | 5a6fbf9d67a048f973126248c3a5dfcf596e5370 | 5,560 |
def strip_chr(bt):
"""Strip 'chr' from chromosomes for BedTool object
Parameters
----------
bt : pybedtools.BedTool
BedTool to strip 'chr' from.
Returns
-------
out : pybedtools.BedTool
New BedTool with 'chr' stripped from chromosome names.
"""
try:
df = pd... | 1382a71799f6de081c3ff3092792012ebac25f01 | 5,561 |
def fit_slice(fitter, sliceid, lbda_range=[5000, 8000], nslices=5, **kwargs):
""" """
fitvalues = fitter.fit_slice(lbda_ranges=lbda_range, metaslices=nslices,
sliceid=sliceid, **kwargs)
return fitvalues | 2d2b4b91b0ba3b0dca908d56e8b5184e5ae36b9e | 5,562 |
import functools
def execute_sync(function, sync_type):
"""
Synchronize with the disassembler for safe database access.
Modified from https://github.com/vrtadmin/FIRST-plugin-ida
"""
@functools.wraps(function)
def wrapper(*args, **kwargs):
output = [None]
#
# this in... | 54034aa9853c1b04e7bfc2416a34019b87556518 | 5,563 |
def mk_living_arrangements(data_id, data): # measurement group 11
"""
transforms a f-living-arrangements.json form into the triples used by insertMeasurementGroup to
store each measurement that is in the form
:param data_id: unique id from the json form
:param da... | d4a327c3fc22facf3c4e21fe0b9fd3ce600beebc | 5,564 |
def ids_in(table):
"""Returns the ids in the given dataframe, either as a list of ints or a single int."""
entity, id_colname = get_entity_and_id_colname(table)
# Series.to_list() converts to a list of Python int rather than numpy.int64
# Conversion to the list type and the int type are both necessary f... | 5bb4a912c88bc7fc7e47cd14be5520c8cce32faf | 5,565 |
def transformer_ae_base_tpu():
"""Base config adjusted for TPU."""
hparams = transformer_ae_base()
transformer.update_hparams_for_tpu(hparams)
hparams.batch_size = 512
return hparams | a71bb88b10400c867e0ac8fd35c7c3e79a95a119 | 5,566 |
def attribute_volume(tree, altitudes, area=None):
"""
Volume of each node the given tree.
The volume :math:`V(n)` of a node :math:`n` is defined recursively as:
.. math::
V(n) = area(n) * | altitude(n) - altitude(parent(n)) | + \sum_{c \in children(n)} V(c)
:param tree: input tree
:p... | 91c884bcdcd4fde616870258f5d3f1582c420868 | 5,567 |
import os
def save_plot(
fig, filepath=None, format="png", interactive=False, return_filepath=False
):
"""Saves fig to filepath if specified, or to a default location if not.
Args:
fig (Figure): Figure to be saved.
filepath (str or Path, optional): Location to save file. Default is with f... | 1b631548d7ba475e1b176032b512d39c45435516 | 5,568 |
def populate_canary(canary_id, protocol, domain, dns, filename, rdir,
settings):
"""Create actual canary URI / URL."""
if protocol not in ['unc', 'http', 'https']:
raise ValidationError('Unknown protocol specified')
if dns:
domain = f"{canary_id}.{domain}"
else:
... | 48a4a75cd65cd4d555a14d6c06363e46e0ced3f5 | 5,569 |
import pkg_resources
def get_wastewater_location_data():
"""Read in data of wastewater facility location data.
:return: dataframe of wastewater location values
"""
data = pkg_resources.resource_filename('interflow', 'input_data/WW_Facility_Loc.csv')
# return dataframe
... | 23f0c425eccdf173e8c8563c8d80e5e7b6a9ead1 | 5,570 |
def generate_accounts(seeds):
"""Create private keys and addresses for all seeds.
"""
return {
seed: {
'privatekey': encode_hex(sha3(seed)),
'address': encode_hex(privatekey_to_address(sha3(seed))),
}
for seed in seeds
} | b10b9616b6d4826262c9296bfe389f001e098939 | 5,571 |
def get_annotation_df(
state: State,
piece: Piece,
root_type: PitchType,
tonic_type: PitchType,
) -> pd.DataFrame:
"""
Get a df containing the labels of the given state.
Parameters
----------
state : State
The state containing harmony annotations.
piece : Piece
T... | 19cf82dc77708099dc5c21695d30fd1c5d63ceb4 | 5,572 |
def prettify(elem):
"""Return a pretty-printed XML string for the Element."""
rough_string = ET.tostring(elem, "utf-8")
reparsed = minidom.parseString(rough_string)
return reparsed.toprettyxml(indent=" ") | 4469a4e5683dd3196ae188bd09517406ca8276bc | 5,573 |
def parse_new_multipart_upload(data):
"""
Parser for new multipart upload response.
:param data: Response data for new multipart upload.
:return: Returns a upload id.
"""
root = S3Element.fromstring('InitiateMultipartUploadResult', data)
return root.get_child_text('UploadId') | 02c83634a02ec94de698735b41424e9e53a2576f | 5,574 |
def mech_name_for_species(mech1_csv_str, mech2_csv_str, ich):
""" build dictionaries to get the name for a given InCHI string
"""
mech1_inchi_dct = mechparser.mechanism.species_inchi_name_dct(
mech1_csv_str)
mech2_inchi_dct = mechparser.mechanism.species_inchi_name_dct(
mech2_csv_str)
... | fe173853dd7b9460a016b370c60fbc6f4eeaac93 | 5,575 |
def get_api(api, cors_handler, marshal=None, resp_model=None,
parser=None, json_resp=True):
"""Returns default API decorator for GET request.
:param api: Flask rest_plus API
:param cors_handler: CORS handler
:param marshal: The API marshaller, e.g. api.marshal_list_with
:param resp_mode... | d4774ec394a7365418b60cc0ef7665e702c0da28 | 5,576 |
import math
def fetch_total_n_items(num_items, uniform_distribution=False):
"""Get num_items files from internet archive in our dirty categories list"""
logger.info(f"Fetching info for {num_items} internetarchive items...")
categories_weights = CATEGORIES_WEIGHTS
if uniform_distribution:
categ... | 6b661c4c83c6d7766cb0a57a7f20eaa03ce44ed9 | 5,577 |
def german_weekday_name(date):
"""Return the german weekday name for a given date."""
days = [u'Montag', u'Dienstag', u'Mittwoch', u'Donnerstag', u'Freitag', u'Samstag', u'Sonntag']
return days[date.weekday()] | 7d2919c61438ec913abe38cccd924bb69f866655 | 5,578 |
def load_data(database_filepath):
"""
Input:
database_filepath - path of the cleaned data file
Output:
X and Y for model training
Category names
"""
# load data from database
engine = create_engine('sqlite:///{}'.format(database_filepath))
df = pd.read_s... | 8647722a0b97a8130bfadfa6dec45fb71c9e6fe3 | 5,579 |
from scipy.special import lpmn, factorial
def real_spherical_harmonics(phi, theta, l, m):
"""Real spherical harmonics, also known as tesseral spherical harmonics
with condon shortley phase.
Only for scalar phi and theta!!!
"""
if m == 0:
y = np.sqrt(
(2 * l + 1) / (4... | 5c12cf5263676fccc2dee40c54670ea5150e2cfc | 5,580 |
from typing import Callable
def get_replace_function(replace_multiple: bool) -> Callable:
"""given bool:replace_multiple flag,
return replace function from modifier
"""
if replace_multiple:
return distend.modifier.replace_multiple
else:
return distend.modifier.replace_single | 6bb05bb4dd8b28f8581e576aa0f086b55eb7cae6 | 5,581 |
def accuracy(X,Y,w):
"""
First, evaluate the classifier on training data.
"""
n_correct = 0
for i in range(len(X)):
if predict(w, X[i]) == Y[i]:
n_correct += 1
return n_correct * 1.0 / len(X) | bdc68859ec7d1f011dc04f641565e44aaeffe908 | 5,582 |
from typing import List
def reduce_matrix(indices_to_remove: List[int], matrix: np.ndarray) -> np.ndarray:
"""
Removes indices from indices_to_remove from binary associated to indexing of matrix,
producing a new transition matrix.
To do so, it assigns all transition probabilities as the given state in... | dac7755b63593044a7df1658d3205572a935e64d | 5,583 |
def kdj(df, n=9):
"""
随机指标KDJ
N日RSV=(第N日收盘价-N日内最低价)/(N日内最高价-N日内最低价)×100%
当日K值=2/3前1日K值+1/3×当日RSV=SMA(RSV,M1)
当日D值=2/3前1日D值+1/3×当日K= SMA(K,M2)
当日J值=3 ×当日K值-2×当日D值
"""
_kdj = pd.DataFrame()
_kdj['date'] = df['date']
rsv = (df.close - df.low.rolling(n).min()) / (df.high.rolling(n).m... | 7aa88cd6ee972063a2bd45b1b5b83da0255b336c | 5,584 |
def identity_func(x):
"""The identify (a.k.a. transparent) function that returns it's input as is."""
return x | 06e0296c338d68663aa87d08b21f84919be3f85e | 5,585 |
def make_choice_validator(
choices, default_key=None, normalizer=None):
"""
Returns a callable that accepts the choices provided.
Choices should be provided as a list of 2-tuples, where the first
element is a string that should match user input (the key); the
second being the value associat... | 65ac672f16a1031a9051bc4f6769c6b1b88db727 | 5,586 |
import time
def find_best_polycomp_parameters(samples, num_of_coefficients_range,
samples_per_chunk_range, max_error,
algorithm, delta_coeffs=1, delta_samples=1,
period=None, callback=None, max_iterations=0):
""... | 47f076634c50cc18c760b7c60909a2d63a19fd3e | 5,587 |
def moving_average(data, window_size=100): #used this approach https://stackoverflow.com/questions/11352047/finding-moving-average-from-data-points-in-python
"""
Calculates a moving average for all the data
Args:
data: set of values
window_size: number of data points to consider in window
... | 8f04d659081a68c4287024e2b6567f257f7b9d92 | 5,588 |
import re
def _change_TRAVDV_to_TRAVdashDV(s:str):
"""
Reconciles mixcr name like TRAV29/DV5*01 to tcrdist2 name TRAV29DV5*01
Parameters
----------
s : str
Examples
--------
>>> _change_TRAVDV_to_TRAVdashDV('TRAV29DV5*01')
'TRAV29/DV5*01'
>>> _change_TRAVDV_to_TRAVdas... | b5df8b51c96ca9695aecc0fcae4589f35b692331 | 5,589 |
def gen_event_type_entry_str(event_type_name, event_type, event_config):
"""
return string like:
{"cpu-cycles", PERF_TYPE_HARDWARE, PERF_COUNT_HW_CPU_CYCLES},
"""
return '{"%s", %s, %s},\n' % (event_type_name, event_type, event_config) | ca89c19b45f182b8a7ae74ab76f3f42bddf46811 | 5,590 |
def encode_rotate_authentication_key_script(new_key: bytes) -> Script:
"""# Summary
Rotates the transaction sender's authentication key to the supplied new authentication key.
May
be sent by any account.
# Technical Description
Rotate the `account`'s `DiemAccount::DiemAccount` `authentication_... | 6235409d0232e29d42de22a7bec2285adfd0db38 | 5,591 |
def retrieval_visualizations(model, savefig=True):
"""
Plots incremental retrieval contexts and supports, as heatmaps, and prints recalled items.
**Required model attributes**:
- item_count: specifies number of items encoded into memory
- context: vector representing an internal contextual state
... | 96c4534a5e3057fb1bfd15068eec8cc61767c01d | 5,592 |
from pathlib import Path
def get_force_charge() -> str:
"""
Gets the command object for the force charge command
Returns:
The command object as a json string
"""
force_charge = Path('force_charge.json').read_text()
return force_charge | c67277c62664419c3b4a19ae57ea6de027c60416 | 5,593 |
def prune_motifs(ts, sorted_dic_list, r):
"""
:param ts: 1-dimensional time-series either resulting from the PCA method or the original 1-dimensional time-series
:type ts: 1d array
:param sorted_dic_list: list of motif dictionaries returned from the emd algorithm, ordered by relevance
:type sorted_... | 4fef0a51da25503548f6df59e09705c731a7fc6c | 5,594 |
def xor_columns(col, parity):
""" XOR a column with the parity values from the state """
result = []
for i in range(len(col)):
result.append(col[i] ^ parity[i])
return result | 2eff4dbf3edf2b97410e7bef17c043a30b1f3aa8 | 5,595 |
def initiate_default_resource_metadata(aws_resource):
"""
:type aws_resource: BaseAWSObject
"""
if not isinstance(aws_resource, BaseAWSObject):
raise TypeError
try:
metadata = aws_resource.Metadata
if not isinstance(metadata, dict):
raise TypeError("`troposphere.... | 4a510dd5a69f2499b407396f34818c79eead7c6a | 5,596 |
def token_vault_single(chain, team_multisig, token, freeze_ends_at, token_vault_balances) -> Contract:
"""Another token vault deployment with a single customer."""
total = 1000
args = [
team_multisig,
freeze_ends_at,
token.address,
total,
0 # Disable the tap
]
... | b42857cb7becacde9d5638f18f6dd7625eabb182 | 5,597 |
import json
import numpy
def pixel_pick():
"""Pick the value from a pixel.
Args:
body parameters:
catalog (str): catalog to query
asset_id (str): asset id to query
lng (float): longitude coordinate
lat (float): latitude coordinate
Returns:
... | c6cab95092da6b9a1f088a0bb565ee1973729112 | 5,598 |
import re
from typing import OrderedDict
def read_eep_track(fp, colnames=None):
""" read MIST eep tracks """
# read lines
f = open(fp, "r+")
s = f.readlines()
# get info
MIST_version = re.split(r"\s+", s[0].strip())[-1]
MESA_revision = re.split(r"\s*", s[1].strip())[-1]
Yinit, Zinit,... | 551c8e5ba05aec5f32d9184398427fb003db78ba | 5,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.