content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import logging
def get_tde_evolution(evolution_name=None, **kwargs):
"""Returns a TDE evolution as a function of redshift
:param evolution_name: Name of chosen evolution
:return: Normalised evolution, equal to 1 at z=0
"""
if evolution_name is None:
logging.info("No evolution specified. ... | 50de52005004bad57f466bc8d36fa62430ce5370 | 3,599,100 |
def choose_moore_domain(row, col, mooreDomain, n, rng) -> np.ndarray:
""" Choose n indexes w/o replacement in the moore domain centered around i, j. Does not consider grid edges.
:return: a list of indexes as lists. """
return rng.choice(mooreDomain[row][col], size=n, replace=False) | 1d50a363dd511913f4f29446eedc431f251f8bb5 | 3,599,101 |
def _remove_duplicates(items):
"""Return `items`, filtering any duplicate items.
Disussion: https://stackoverflow.com/a/7961390/4472195
NOTE: this requires Python 3.7+ in order to preserve order
Parameters
----------
items : list
[description]
Returns
-------
list
... | b44a16ed815e8cc09598fe2dc8e9871d45d0ae7e | 3,599,102 |
import json
def metadata_labels_add():
"""The ``/teams/metadata/labels/add`` endpoint requires authentication and expects the
argument ``description``. It adds a label to the metadata associated with teams.
Note that this endpoint requires a POST request.
It can be reached at
``/teams/metadata/l... | f8e37adff8fc2b7a139db6d3f548c84e624194ed | 3,599,103 |
def get_mods_composition(modifications):
"""Return the composition of a list of modifications.
Parameters
----------
modifications : list of str
List of modifications string (corresponding to Unimod titles).
Returns
-------
pyteomics.mass.Composition
The total composition c... | b8e1acbd661f04e33cb86e5fa44101001afbcc3e | 3,599,104 |
import urllib
import json
def get_results(query):
"""Fetches query search results from Jisho.org API.
Args:
query: A string representing the search query for Jisho.org.
Returns:
An array of JSON results from Jisho.org based on search query.
"""
request = urllib.request.urlopen(API_... | 9ed0969411a99fa307a4bba5e43f7d0157507624 | 3,599,105 |
def tailrc96(sps, x,y,z):
"""
Computes the components of the field of the model ring current and three tail modes with unit amplitudes
For the ring current, it means the disturbance of bz=-1nT at origin, and
for the tail modes it means maximal bx just above the sheet equal 1 nT.
"""
# common /... | 2fd1885cad28cb84ffa5d0e737f3855fa2939d31 | 3,599,106 |
def normalize_data(data, skipcols=None):
"""Normalizes the data so that all features are in the range [0,1]"""
rows = 0
for i in range(len(data)):
rows += data[i].shape[0]
rows2 = 0
data_all = np.empty((rows, data[0].shape[1]))
for i in range(len(data)):
data_all[rows2:rows2+data[i].shape[0], :] = ... | 63a4b9314228eaf7833bacbe701abb590b07daef | 3,599,107 |
import re
def seqs_dic_count_lc_nts(seqs_dic):
"""
Count number of lowercase nucleotides in sequences stored in sequence
dictionary.
>>> seqs_dic = {'seq1': "gtACGTac", 'seq2': 'cgtACacg'}
>>> seqs_dic_count_lc_nts(seqs_dic)
10
>>> seqs_dic = {'seq1': "ACGT", 'seq2': 'ACGTAC'}
>>> seq... | 4542885f22e255fa0f3d14a9d4ef523fdf19f2e8 | 3,599,108 |
def get_coa_urls():
"""
Get CoA URLs for given samples or projects.
"""
# Get certificate data and return the short links.
return NotImplementedError | 7401fd862d982d15d0ddbed93ae00792291526a0 | 3,599,109 |
def pointer_as_string(pointer, length=0):
"""Convert a WinAPI LPSTR to a Python string"""
return win32gui.PyGetString(pointer, length) | 573def09057a15d538e314066e8710deb461c8e1 | 3,599,110 |
def post_edit(request, username, post_id):
""" Страница редактирования поста. Использует форму для создания поста. """
info = profile_info(username, request.user)
post = info["author"].posts.get(pk=post_id)
if request.user != post.author:
context = {
"post": post,
}
c... | 36b46a3fdc4ccc37420e6193d5d3b0482813f2c8 | 3,599,111 |
from typing import Callable
import functools
from typing import Union
import logging
def log_name(func: Callable) -> Callable:
"""Decorator that logs the name of the function being executed"""
@functools.wraps(func)
def wrapper(*args: Union[int, str], **kwargs: Union[int, str]):
logging.debug(_log... | df6bf6fa7264ca7ef736c2352a684dd54308d764 | 3,599,112 |
def DOM_node_to_XML(tree, xml_declaration=True):
"""
Prints a DOM tree to its Unicode representation.
:param tree: the input DOM tree
:type tree: an ``xml.etree.ElementTree.Element`` object
:param xml_declaration: if ``True`` (default) prints a leading XML
declaration line
:type xml_dec... | 0ccead623440f4d70c787c503ff3d2c327d82066 | 3,599,113 |
def DifferentFromGolden(actual, golden, output_type, fail_msg):
"""Compares actual output against golden output.
If there are any differences, output an error message (to stdout) with
appropriate banners.
Args:
actual: actual output from the program under test, as a single
string.
golden: expec... | 42aa526f3cfc9428b9d24de253fde97ce7d8562f | 3,599,114 |
import os
def MultiTimeWind_res():
"""
Init WindResource resource handler
"""
path = os.path.join(TESTDATADIR, 'wtk/ri_100_wtk_*.h5')
return MultiTimeWindResource(path) | aad28314e853ae78910ae41873442988648ede14 | 3,599,115 |
def get_gdal_dataset(numpy_array, wkt, geotransform):
"""
Create a GDAL dataset from a numpy array
@param numpy_array: Data as a numpy array
@param wkt: String of well known text describing projection
@param geotransform: Affine global transformation coefficients
@return GDAL dataset
"""
... | e6d0fcf923af0849d24f4532ad5fd641d7c2117e | 3,599,116 |
import pathlib
def get_iniloc(path=None):
"""determine location & filenames for stored settings
if given, input should be an absolute path
"""
path = pathlib.Path(path) if path else pathlib.Path.cwd()
if path == pathlib.Path.home():
here = str(path)[1:]
else:
try:
h... | 5105269d745901227d9cadc06e51a0444ae1ae8e | 3,599,117 |
def up_a_directory(link_string):
"""
link: a string of a url in the form https://rivergillis.com/test/
returns: a string of a url in the form https://rivergillis.com/
"""
if not link_string:
return None
if link_string == get_root_url(link_string):
raise ValueError(link_string, " ... | efed90e2202557258c30d7b30ca96808650c3068 | 3,599,118 |
import json
def __bundle(sender_priv_key, recipient_pub_key, sender: str, message_d: dict,
message: str) -> dict:
"""
Pure implementation of bundling an encrypted payload.
"""
payload = json.dumps(message_d)
token, key = symmetric_encrypt(payload)
signature = sign_request(sender... | e0d3c2122e6f48649ef5e232ce8a2fa367776bd2 | 3,599,119 |
def gaussian_kernel(D,
sigma):
"""
Applies Gaussian kernel element-wise.
Computes exp(-d / (2 * (sigma ^ 2))) for each element d in D.
Parameters
----------
D: torch tensor
sigma: scalar
Gaussian kernel width.
Returns
----... | 22885ccb785893522e57861b82612989945cd5cf | 3,599,120 |
def low_pass(ys, cutoff, factor=0.1, framerate=44100, duration=1.0):
"""
Attenuate frequencies above the cutoff.
ys -- the wave (numpy array)
cutoff -- frequency (Hz)
factor -- what to multiply the magnitude by
framerate -- framerate of wave
"""
n = len(ys)
d = 1 / framerate # perio... | 6f8f6e57c64d23a0ff6fb38e7eb399e5caa15345 | 3,599,121 |
import os
def run_simply_p(met_df, p_struc, p_SU, p_LU, p_SC, p, dynamic_options, step_len=1.):
""" Simple hydrology, sediment and phosphorus model, with processes varying by land use, sub-catchment
and reach.
Version 0.1, alpha release. Comparison to previous version:
Correction to ... | 1e8398955434de8dd103e28174bf26a3f4b9518b | 3,599,122 |
def create_app(config):
"""
创建新的app对象
:param config: DICER2配置文件路径
:return: 新建的app对象
"""
app = Flask(__name__)
app.config.from_pyfile(config)
init_config(app)
init_api(app)
init_ext(app)
init_hook(app)
init_job()
return app | 63aa642c9399e0ba4df7ff25958540c8a2e7e8a1 | 3,599,123 |
import requests
def get_cac_token(auth_token, deployment_id, connector_name):
"""A function to create a connector token
Creates a connector token using the authentication token and deployment ID.
Args:
auth_token (str) : auth_token created using CAM Deployment Service Account
... | b8be0b29f7a38ccc2de9b6e1f8c889aa1ce18f99 | 3,599,124 |
def read_field_3d( filename, field_path, slicing=0., slicing_dir='y' ) :
"""
Extract a given field from an HDF5 file in the OpenPMD format,
when the geometry is 3d cartesian.
Parameters
----------
filename : string
The absolute path to the HDF5 file
field_path : string
... | ef72c23b58363ff46efa654e659caadc617e358c | 3,599,125 |
def accept_course(request, course_pk):
"""Sets the status of the course to Approved given the course id."""
Course.objects.filter(id=course_pk).update(status='approved')
messages.success(request, 'The course has been successfully approved.')
return redirect('staff:course_requests') | fd7264bd0d8150aac01994c8a961bc14bc8c032a | 3,599,126 |
def convert(s, locale, update=None):
"""
Main convert function.
:param s: must be `unicode` (Python 2) or `str` (Python 3).
:param locale: should be one of ``('zh-hans', 'zh-hant', 'zh-cn', 'zh-sg'
'zh-tw', 'zh-hk', 'zh-my', 'zh-mo')``.
:param update: a dict which upd... | eb3d3d339a6d36a62233c33986dc167db6c50045 | 3,599,127 |
def CurveFitter(key):
"""Curve Fitter factory method"""
fitters = _CurveFitter.__subclasses__()
for f in fitters:
if f.key == key:
break
else:
raise ValueError('{0}: unrecognized fitter'.format(key))
if f.requires_opt and not sciopt:
raise ValueError('{0}: require... | 8913a2e20eaecec196fd3c1862d57f6a9d84bdb7 | 3,599,128 |
import random
import string
def generate_admission_ids() -> list:
""" Generate a unique 10-digit ID for every admission record """
uids = []
for _ in range(num_of_rows):
x = ''.join(random.choice(string.digits) for _ in range(10))
uids.append(x)
return uids | b34c4d84c16fcac4bbd6370cade3623dc7ad8516 | 3,599,129 |
def test_session_commands():
"""
Test which commands inherit from SessionCommandMixin.
"""
def is_session_command(command):
return isinstance(command, SessionCommandMixin)
expected = ['download', 'install', 'list', 'search', 'uninstall', 'wheel']
check_commands(is_session_command, expec... | 23569817e1766a000dd0c875303598e0aae4522f | 3,599,130 |
def trigger_event(connection, id, fields=None, error_msg=None):
"""Trigger an event.
Args:
connection(object): MicroStrategy connection object returned by
`connection.Connection()`.
id(str): ID of the event
error_msg (string, optional): Custom Error Message for Error Handlin... | 418994565cd20cac681575286553d4fa92cf89c9 | 3,599,131 |
def combine_signatures_or_rename_preds(exprs, preferred_sigs=None):
"""
`signatures` is a list of dictionaries. Each dictionary has key-value
pairs where key is a predicate name, and value is a type object.
`exprs` are logical formula objects.
This function return a single signature dictionary wit... | cd3af1de9d4c05e2c4dd6a87037f287a49d8d6ce | 3,599,132 |
from typing import Optional
import os
def get_shank_channels(session_path: str, xml_filepath: Optional[str] = None):
"""Retrieve the channel ids belonging to the shanks in Neuroscope xml.
Same as first 'nshanks' elements of get_channel_groups(...).
Parameters
----------
session_path: str
xml... | cc2e5f9d1c8ff35ae6a689a40419672f2423c9d0 | 3,599,133 |
import codecs
def read_data(file_name):
"""
Helper function
"""
lst = []
with codecs.open(file_name, 'r', encoding='utf8') as f:
for line in f:
line = line.strip()
if line == '':
continue
(one, two, *rest) = line.split("\t")
l... | 76f64af52e1f1fe6b95e34a93ca1c729624fd7d9 | 3,599,134 |
from typing import Mapping
from typing import Any
from typing import Dict
import collections
def _flatten_nested_dict(struct: Mapping[str, Any]) -> Dict[str, Any]:
"""Flattens a given nested structure of tensors, sorting by flattened keys.
For example, if we have the nested dictionary {'d':3, 'a': {'b': 1, 'c':2... | 171688038586b276513b12aee23e215ce8583892 | 3,599,135 |
def parse_hue_api_response(response):
"""Take in the Hue API json response."""
data_dict = {} # The list of sensors, referenced by their hue_id.
# Loop over all keys (1,2 etc) to identify sensors and get data.
for key in response.keys():
sensor = response[key]
modelid = sensor['model... | f167eed97648167d299f3dd9ab53a67d95e9e345 | 3,599,136 |
from typing import Collection
def get_numpy_input_templates(
backend_input_templates: Collection[BackendVariable],
) -> Collection[np.array]:
"""Returns a collection of numpy representations of the input templates"""
numpy_input_templates = [to_numpy(x) for x in backend_input_templates]
return numpy_i... | 9cfb2c0ec1b3757e0dc7aada4b7cda4c1c24175a | 3,599,137 |
import argparse
def _parse_args():
"""Parse command-line arguments."""
parser = argparse.ArgumentParser()
#parser.add_argument("--gpus", type = int, default = 1)
#parser.add_argument("--precision", type = int, default = 16)
parser.add_argument("--progress_bar_refresh_rate", type = int, default = ... | e4f9735ad9e90b8b840f3786e6ac614da9cbe45c | 3,599,138 |
import tempfile
import time
from functools import reduce
import os
def evaluate_official_script(parser, vocab, num_buckets_test, test_batch_size, test_file, output_file,
debug=False):
"""Evaluate parser on a data set
Parameters
----------
parser : BiaffineParser
b... | ab2336c6ce01dbfb8b0f28dc2ebb19b37ca440eb | 3,599,139 |
from typing import List
from typing import Tuple
def fixture_diff_kwd_failure() -> List[Tuple[TestCase, str]]:
"""Generate a list of failures for the single tc diff kwd problem."""
suite = diff_one_tc_kwd.generate_test_suite(diff_wrong)
result = suite.run(TestCase().defaultTestResult())
return result... | 1e8c5a679e0eb78aab7226bf3fd4712742c98d18 | 3,599,140 |
from datetime import datetime
from re import A
def hrm_rheader(r, tabs=[],
profile = False):
""" Resource headers for component views """
if r.representation != "html":
# RHeaders only used in interactive views
return None
record = r.record
if record is None:
#... | 9d8d0e8599880ba07bd80c016b09063de2c04be1 | 3,599,141 |
def rmses(A, X, Y):
"""Returns the root-mean-squared error (RMSE) of the solution X."""
return npext.rms(Y - np.dot(A, X), axis=0) | b3016d22bc01070f73e25673df4ad4bd69276d9f | 3,599,142 |
import time
import pickle
import lzma
def controller(
hdf5path,
hdf5mode,
faultlist,
config_qemu,
num_workers,
queuedepth,
compressionlevel,
qemu_output,
goldenrun=True,
logger=hdf5collector,
qemu_pre=None,
qemu_post=None,
logger_postprocess=None,
):
"""
Thi... | 734326f338f309f38a0576770fd9a38872c17de9 | 3,599,143 |
import os
import requests
import zipfile
import shutil
import glob
def get_benchmark_dataset(data: str = 'Inspec',
cache_dir: str = None,
keep_only_valid_label: bool = False):
""" Get a dataset for keyword extraction (labels are not stemmed)
Parameter
... | 956abd30b4fab7bee00ebb18c390e6ac67749e2f | 3,599,144 |
import re
def shape_element(element, node_attr_fields=NODE_FIELDS, way_attr_fields=WAY_FIELDS,
problem_chars=PROBLEMCHARS, default_tag_type='regular'):
"""Clean and shape node or way XML element to Python dict"""
node_attribs = {}
way_attribs = {}
way_nodes = []
tags = []
co... | c4f5e6691a774ea58f71da42005f7ef901d34453 | 3,599,145 |
from typing import Any
import io
def read_file(filename: Text, encoding: Text = "utf-8-sig") -> Any:
"""Read text from a file."""
with io.open(filename, encoding=encoding) as f:
return f.read() | 00a08584e8afa43e4e7ba7018379819bd75356bb | 3,599,146 |
def toplevel_parent_of_window(window):
"""
Returns the first top-level parent of a wx.Window
"""
topwin = window
while not isinstance(topwin, wx.TopLevelWindow):
topwin = topwin.GetParent()
return topwin | 07d96cf6d55f6d6097ed375b4e125b09ff91bb13 | 3,599,147 |
def _budget_constraint(media: jnp.ndarray,
prices: jnp.ndarray,
budget: jnp.ndarray) -> jnp.float64:
"""Calculates optimization constraint to keep spend equal to the budget.
Args:
media: Array with the values of the media for this iteration.
prices: Prices of e... | ece0b9a7bbb741130301d81c2785835e15fc0117 | 3,599,148 |
def getSampleStyleSheet():
"""Returns a stylesheet object"""
stylesheet = StyleSheet1()
stylesheet.add(ParagraphStyle(name='Normal',
fontName='Times-Roman',
fontSize=10,
leading=12)
)
... | f8c801bb6a583bc51631134609e1d085f94edf1d | 3,599,149 |
from typing import Dict
def random_agent_max_spend(player_to_act: Player, actions: Dict[int, any]) -> int:
"""
A random agent that spends all of its money before ending the turn.
:param player_to_act: Not used in this function
:param actions: Available actions
:return: Action to play
"""
n... | 9c4eebd72544d32cfe2d4b738a16f5bec7f539a6 | 3,599,150 |
import torch
def generate_box(x_start: Tensor, y_start: Tensor, width: Tensor, height: Tensor) -> Tensor:
"""Generate 2D bounding boxes according to the provided start coords,
width and height.
Args:
x_start (Tensor):
Tensor containing the x coordinates of the bounding boxes to be
... | 6c42c6a6ff70ceb1fa67537da5f83dfed5ee41c8 | 3,599,151 |
import weakref
import types
def superreload(module, reload=reload, old_objects={}):
"""Enhanced version of the builtin reload function.
superreload remembers objects previously in the module, and
- upgrades the class dictionary of every old class in the module
- upgrades the code object of every old... | 69fed1362499445123a2e28de60d03302f7ed085 | 3,599,152 |
def _generate_strike_df(
vol_surface: ql.BlackVarianceSurface, strike_step: int
) -> pd.DataFrame:
"""Function to take the max/min strikes from a surface object and create new
datapoints at a given step/increment
Args:
vol_surface (ql.BlackVarianceSurface): Surface to extract data from
... | 4851ac20e8168336e5f79cbdcac13ecf3415f0f5 | 3,599,153 |
def evaluate_legacy(probs, y_true, verbose=False, normalize=True, bins=15):
"""
Evaluate model using various scoring measures: Error Rate, ECE, MCE, NLL, Brier Score
Params:
probs: a list containing probabilities for all the classes with a shape of (samples, classes)
y_true: a list cont... | 487431fb4c2f5342b046ee5d196568e211cccaa5 | 3,599,154 |
def basis_from_landmarks(landmark_points):
"""Computes an orthonormal basis from facial landmarks."""
# Estimate Z by fitting a plane
# This works better than trusting the chin to forehead vector, especially in
# full body captures.
face_axis_z = _normalize(fit_plane_normal(landmark_points))
face_axis_y = _... | 09864e918af037ef5d4257db65268c03f78fa653 | 3,599,155 |
def best_score(a_dictionary):
"""Returns a key with the biggest integer value.
Checks if a thing is a dicrionary with the is instance method"""
if not isinstance(a_dictionary, dict) or len(a_dictionary) == 0:
return None
ret = list(a_dictionary.keys())[0]
big = a_dictionary[ret]
for k, ... | e168c86e615539af525050ce400fa578cac603b9 | 3,599,156 |
def Substring(string: Expr, start: Expr, end: Expr) -> Expr:
"""Take a substring of a byte string.
Produces a new byte string consisting of the bytes starting at :code:`start` up to but not
including :code:`end`.
This expression is similar to :any:`Extract`, except this expression uses start and end i... | ca5624c7053f35ce4cefc033ca7ffd6717a3fd48 | 3,599,157 |
def login_to_qiita(driver, username, password):
"""Navigate to Qiita and login."""
driver.get("https://qiita.ucsd.edu/")
assert "Qiita" in driver.title
username_elem = driver.find_element_by_id("username")
username_elem.send_keys(username)
password_elem = driver.find_element_by_id("password")
... | bb6ea0f7661341b71c50b7d06ad404ec4909898d | 3,599,158 |
def _log_bessel_ive_fwd(v, z):
"""Compute output, aux (collaborates with _log_bessel_ive_bwd)."""
output = _log_bessel_ive_naive(v, z)
return output, (v, z) | a7e50974d390f684385fc8eed9173ff2a6aa6575 | 3,599,159 |
from datetime import datetime
def json_serial(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, datetime.datetime):
serial = obj.isoformat()
return serial
raise TypeError("Type not serializable") | 9f8899cbe89ee73aa3410a8e972065e70387fc3f | 3,599,160 |
def filter_grays(rgb, tolerance=15, output_type="bool"):
"""
Create a mask to filter out pixels where the red, green, and blue channel values are similar.
Args:
np_img: RGB image as a NumPy array.
tolerance: Tolerance value to determine how similar the values must be in order to be filtered out... | eee5c00ac60117fbdb275d09b30a5e9cda466ff8 | 3,599,161 |
def op_n(int_n):
"""
OP_N where N is a number, an OP_N represents that number.
"""
assert int_n == -1 or 1 <= int_n <= 16, "N in OP_N is in the set: {-1, [1-16]}"
op_1 = int(OP_1_TRUE.hex(), 16) # Fist number coded op is 1
hex_val = hex(op_1 + int_n - 1) # Do integer addition to find the right... | 94c69a9463d3af040e4fd9695487ee938649bbff | 3,599,162 |
import json
def data_sensor_paired_sensor_status_fixture():
"""Define data from a successful sensor_paired_sensor_status response."""
return json.loads(load_fixture("sensor_paired_sensor_status_data.json", "guardian")) | 9610a71c35ec8befb7d39740b33d7d56df8f9ec1 | 3,599,163 |
def get_A_dash_floor_other(house_insulation_type, floor_bath_insulation):
"""浴室の床の面積 (m2)
Args:
house_insulation_type(str): 床断熱住戸'または'基礎断熱住戸'
floor_bath_insulation(str): 床断熱住戸'または'基礎断熱住戸'または'浴室の床及び基礎が外気等に面していない'
Returns:
float: 浴室の床の面積 (m2)
"""
return get_table_3(16, house_insul... | 9509795bfd952121b17cfc937a5e3a41a5ecf4db | 3,599,164 |
def eratosthenes(n):
"""
This function is titled eratosthenes(n) because it uses the Eratosthenes Sieve to produce a list of prime
numbers. It takes in one positive integer arguement, the returns a list of all the primes less than the
given number.
Args:
n (int): User input
... | 7c0e0e89c1571dfc7a87883423a217ef36a984af | 3,599,165 |
import re
def guess_gender_by_surname(name):
"""Предполагает пол по имени"""
for key, value in list(SURNAME_POSTRULES.items()):
if re.match(key, name):
return (key, value)
return None | 497633392555d7e545c5fa17d6f77e3bd0e98550 | 3,599,166 |
def y_aver_bot(yw_mol, ypf_mol):
"""
Calculates the average mol concentration at bottom of column.
Parameters
----------
yw_mol : float
The mol concentration of waste, [kmol/kmol]
ypf_mol : float
The mol concentration of point of feed, [kmol/kmol]
Returns
-------
... | 21a438551cc7f6c3774999bafa30495dffd99201 | 3,599,167 |
def parameters_get(username=None, label=None, page=None, per_page=None): # noqa: E501
"""List all instances of Parameter
Gets a list of all instances of Parameter (more information in https://w3id.org/okn/o/sd#Parameter) # noqa: E501
:param username: Name of the user graph to query
:type username: st... | df95d1572ba7d1c78af8ab48047d1bc1f1556741 | 3,599,168 |
def get_D(anchors, samples):
""" Create squared distance matrix with
:param samples: n_positions x dim trajectory points.
:param anchors: n_anchors x dim anchor points.
:return D: matrix of squared distances (n_positions + n_anchors) x (n_positions + n_anchors)
"""
X = np.hstack([samples, an... | 559f0dcfc1d05c964ac3d997d99e7397f338c904 | 3,599,169 |
def _convert_to_numpy_obj(numpy_dtype, obj):
"""Explicitly convert obj based on numpy type except for string type."""
return numpy_dtype(obj) if numpy_dtype is not object else str(obj) | 54a7bd1576ec95456d47e2e3957370c0970cb376 | 3,599,170 |
def gen_s_quadratic(computed_data, param):
"""Generate the sensitivity matrix assuming the wavelength
dependent sensitivity as a quadratic polynomial. Elements are
the ratio of sensitivity at two wavenumber/wavelength points"""
mat = np.zeros((computed_data.shape[0], computed_data.shape[0]))
for i... | 3888503321e3d0a28ef27073f2101aa54f58badc | 3,599,171 |
def random():
"""
---------------------------------------------------------------------------
Returns a Random Number.
Returns
-------
str_sql
SQL expression.
"""
return str_sql("RANDOM()", "float") | 72e32dbde21496bc1c9b307c9a4d94c5727ccd6d | 3,599,172 |
def get_operators_and_operands_from_string(user_string):
"""Convert the input string to operators and operands.
Parameters
----------
user_string : str
the bodmas string
Returns
-------
[SingleStack]
Raises
------
ValueError : If an unsupported character is encountered... | 9d2026da1172cd0ef965273bfc934c17db426868 | 3,599,173 |
def pre_conv1x1_block(x,
in_channels,
out_channels,
strides=1,
return_preact=False,
training=False,
data_format="channels_last",
name="pre_conv1x1_block"):
"""
... | 9273bf7c279bdb3f5c3a6b3883294fcd5ee1244f | 3,599,174 |
def local_env():
"""
Environment settings for local.
Usage:
fab local <task>
"""
env.run = lrun
env.name = 'dev'
env.conf_path = 'dev'
env.project_root = LOCAL_PROJECT_PATH
env.hosts = ['localhost']
env.branch = 'develop'
env.venv_root = LOCAL_ENVIRONMENT_PATH
en... | f0c7d043daf2b581bb1f185b7a726811f20f50ba | 3,599,175 |
import re
def numbers_to_literals(s: str) -> str:
"""convert all numbers to litterals"""
if len(s) == 4:
return re.sub(r"\d+", lambda y: num2words.num2words(y.group(), to="year"), s) # noqa
return re.sub(r"\d+", lambda y: num2words.num2words(y.group()), s) | 5caa380f9a75e64eefd9691644fbcbfda6fc3fc4 | 3,599,176 |
from datetime import datetime
def project_reallocation(request):
"""
called from officeOfDeanRSPC/extention {name:project_reallocation} from office_module/urls.py
usage: To fill details in the database when faculty wants to reallocate fund of the project
model used: Project_Registration, Project_Reall... | ea5f6ed87e4456e06ca999ec8950447b79594dee | 3,599,177 |
def highest_degrees_in_community(graph_network, community):
"""
Returns the highest n top users from single community based on degree old_centrality
:param community: Community object holding the node objects
:return: a list of the n top user's node keys
"""
global graph
graph = graph_networ... | 9f0581e472e2d6e72e8324e268e2995dc89dc212 | 3,599,178 |
import json
def delete_volume_group(hostname, name):
"""
Delete volume group on machine.
CLI Example:
.. code-block:: bash
salt 'maas-node' maasng.delete_volume_group server_hostname vg0
salt-call maasng.delete_volume_group server_hostname vg0
"""
maas = _create_maas_client... | d5fbaf04741059245d86487df2675cc50ad03c02 | 3,599,179 |
import os
def main_config_validator(config: Config) -> Config:
"""主配置校验器
校验主配置是否合法,以及尽可能合法化配置
该方法会对每一个配置检查以下字段:
- oss_type: OSS 类型,只能是 'tencent-cos' 或 'aliyun-oss' 。
- oss_config: OSS 配置,必须是一个已经存在文件。
- local_dir: 本地文件路径,必须是一个已经存在的文件夹。
- direction: 同步方向,只能是 'local-to-remote' 或 'remote-to... | 0121fa68b35ac72c6dcb6477ac70cbb51e8ff044 | 3,599,180 |
import os
import json
def load_equalize_pairs():
"""
Loads equalize pairs from data file
:returns: List of equalize pairs
"""
eq_file = os.path.join(PKG_DIR, 'data', 'equalize_pairs.json')
with open(eq_file, 'r') as f:
eq_pairs = json.load(f)
return eq_pairs | dc1c678c8cb7eaab918fe4455c091ebb9e25e1eb | 3,599,181 |
async def async_unload_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(
config_entry, PLATFORMS
)
api_key = config_entry.data[CONF_API_KEY]
coordinator: TomorrowioDataUpdateCoordinator =... | 0f6958b8dd1c8fd44c61686a22ca0eb42381d24a | 3,599,182 |
def format_job_status(job):
"""Formats the job status field"""
return format_state(job['state']) | 5aae015f865a5c5382ea0e273b2b1f0a14b5fe46 | 3,599,183 |
import subprocess
def find_pe_header(fi, data, offset, output):
"""
Used by guess_multibyte_xor_keys()
"""
# Do not show command prompt window
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
# Execute find_pe_file.py for finding PE files
p... | b9ef32afb909eed64273679d1013f2840df68b7f | 3,599,184 |
def gen_from_template(template_file: str, data):
""" Quick shortcut to ezt with strings """
tmpl = ezt.Template(template_file)
fp = ezt.StringIO()
tmpl.generate(fp, data)
return fp.getvalue() | e90a45ba5ca39e9e99253506bc343eaae88ac2f9 | 3,599,185 |
from typing import Optional
from typing import Any
import time
import json
def success(message: Optional[str] = None, data: Any = None, status: int = 200, code: int = 20000) -> Response:
"""
函数体处理成功,请求流程正常结束
"""
if data is None:
data = dict()
res = {
'code': code,
'message'... | 21ed8a5748fdba20da28e92f9a0a2290166bdb75 | 3,599,186 |
import time
def dehydrate_time(value):
""" Dehydrator for `time` values.
:param value:
:type value: Time
:return:
"""
if isinstance(value, Time):
nanoseconds = int(value.ticks * 1000000000)
elif isinstance(value, time):
nanoseconds = (3600000000000 * value.hour + 600000000... | ba3528b7364a775ddcad7acebdb771f8aee666f4 | 3,599,187 |
def make_df_range(df, start, end):
"""
Given a dataframe, a starting date and an ending date (both datetime objects), return a data frame of the value counts for song ids
"""
songs = pd.DataFrame(columns=["ID","Timestamp"])
for i in range(len(df)):
timestamp = df.iloc[i,1]
parsed = p... | ea3dadc4f18e8cfdff6d7eac53760d3d420e99c0 | 3,599,188 |
def get_duration(self):
"""
Returns time taken for particles to exit the system following release
(duration of trajectory).
The duration (ns) is given as the time elapsed from the release of a
particle to it's exiting from the sytem and is returned for all
trajectories as an ndarray.
Param... | 3b9cbeac456c592d7ab66d522fce545539505344 | 3,599,189 |
import os
def get_solvers():
"""Get a list of the available datatracer solvers.
Returns:
list:
List of the names of the available datatracer solvers.
"""
return [
pretrained_solver[:-3]
for pretrained_solver in os.listdir(PRETRAINED_DIR)
if pretrained_solve... | f9e264ff27aad769dd3e1046e6f2f8aa2411d5d8 | 3,599,190 |
def softmax(x):
"""Compute softmax values for each sets of scores in x."""
e_x = np.exp(x - np.max(x))
return e_x / e_x.sum() | 2d47067fc6fb94a823e562eb192b926314bbf963 | 3,599,191 |
import struct
def make_primitive_serializer(format):
"""Create a serializer for a primitive type from a struct format string.
The given `format` is a format string as defined in the `struct` module
and is expected to include a single primitive type.
See: http://docs.python.org/library/struct.html
... | d7db31a67d3faf8d773f0317b9f8684b6f981426 | 3,599,192 |
import datasets
def evaluate(dataset: object, predictions: object, output_folder: object, ovthresh: object) -> object:
"""evaluate dataset using different methods based on dataset type.
Args:
dataset: Dataset object
predictions(list[BoxList]): each item in the list represents the
p... | d20048ffb80bd541e227d292478a19e1fd6c6dee | 3,599,193 |
from ralph.attachments.models import Attachment, AttachmentItem
import mimetypes
from typing import Iterable
def add_attachment_from_disk(objs, local_path_to_file, owner, description=''):
"""Create attachment from absolute file path.
Function create and returns attachment object with file from local path.
... | d7ff0be7716d90ca62528d5f9a734ae8b0eb38a1 | 3,599,194 |
def estimate_poses_given_rot(factors: gtsam.BetweenFactorPose3s,
rotations: gtsam.Values,
d: int = 3):
""" Estimate Poses from measurements, given rotations. From SfmProblem in shonan.
Arguments:
factors -- data structure with many BetweenFactor... | 1542b9e1f1d82384fa3e44e5f477cee489b259ab | 3,599,195 |
def _weights(x, dx=1, orig=0, ravel=True, labels=None):
"""
Compute linear interpolation weights for projection array `x`
and regularly spaced detector pixels separated by `dx` and
starting at `orig`.
"""
if ravel:
x = np.ravel(x)
floor_x = np.floor((x - orig) / dx).astype(np.int32)
... | 10c4250a7b185ce5730e1f24258810c2b099ede4 | 3,599,196 |
def hazel_library(package_name):
"""Returns the label of the haskell_library rule for the given package."""
return "@{}//:lib".format(hazel_workspace(package_name)) | 1c67b4b3ad5468c76394e9e0b68bc91ab6bfa61d | 3,599,197 |
import re
def regex_from_segments(segments, requires=None, escape_segment=True):
"""Converts a list of segment tuple pairs into a regular expression string.
Args:
segments (list): The segment tuple pairs to convert.
requires (dict): Key/value pairs to be used in each segment.
Returns:
... | 2753db6616bd7ac7d66c0fe84585f400a696d794 | 3,599,198 |
async def update_user(
id: str,
user: UserUpdate = Body(...),
current_user: User = Depends(services.get_current_user),
):
"""Endpoint for updating user."""
user = services.update_user(id=id, user=user)
if user:
return JSONResponse(status_code=200,
... | 8ab6500292b950ed760b1ba58a5f7ac0bceb1b5e | 3,599,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.