content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def complete_session(session: namedtuple, speeches: list) -> dict:
"""
This will result in loss of data bc content will be reduced to speeches.
HTML_classes, speaker_flow, speaker_role etc. will not be given any longer
since it's assumed that speakers are either members of parliament or
ministers.
... | 185e1518e48252fcdc222aeddf8f2ba30884c93e | 3,656,861 |
import fileinput
import re
def replace_text_in_file(file_path, replace_this, for_that, case_insensitive=False, is_regex=False, keep_copy=False,
number_of_subs=0):
""" replace a string or regex (if is_regex is set) from a file given in file_path, with another string.
This is a rep... | 12c978759fd5a31bacb396d3068ab762b442dd27 | 3,656,862 |
def load_annotations(ann_file):
"""Load the annotation according to ann_file into video_infos."""
video_infos = []
anno_database = mmcv.load(ann_file)
for video_name in anno_database:
video_info = anno_database[video_name]
video_info['video_name'] = video_name
video_infos.append(... | ac337917f313e5c695a5388c481e12787d7d78a0 | 3,656,863 |
from typing import List
from typing import Dict
def seq_hist(seq_lens: List[int]) -> Dict[int, int]:
"""Returns a dict of sequence_length/count key/val pairs.
For each entry in the list of sequence lengths, tabulates
the frequency of appearance in the list and returns the
data as a dict. Useful for histogra... | 5778b7566d1b64e8db0e2dce6bbf53e06cdb196d | 3,656,865 |
from typing import List
def clifford_canonical_F(
pauli_layer: List[int], gamma: np.ndarray, delta: np.ndarray
) -> Circuit:
"""
Returns a Hadamard free Clifford circuit using the canonical form of elements of the Borel group
introduced in https://arxiv.org/abs/2003.09412. The canonical form has the s... | 9818866b3196ccf9608f7ea8a17145bfa9ddb2d2 | 3,656,867 |
def calculate_second_moment_nondegenerate(
mu1: float, mu2: float, sigma1: float, sigma2: float, a: float, alpha: float
) -> float:
"""The second (raw) moment of a random variable :math:`\\min(Y_1, Y_2)`.
Args:
mu1: mean of the first Gaussian random variable :math:`Y_1`
mu2: mean of the sec... | 74869b0b461777ae9cce658829c2c90ff9a4adff | 3,656,868 |
from re import X
def q_make( x, y, z, angle):
"""q_make: make a quaternion given an axis and an angle (in radians)
notes:
- rotation is counter-clockwise when rotation axis vector is
pointing at you
- if angle or vector are 0, the identity quaternion is returned.
double x, y, z : ... | bd95a3d6f89599297a089d75882aa319e474a1b7 | 3,656,869 |
def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover
"""
create an engine connected to a mssql database using pymssql.
"""
return create_engine(
_create_mssql_pymssql(username, password, host, port, database),
**kwargs
) | a4d644839879ae374ba091f1b9e79fd210c03e3e | 3,656,870 |
def get_right_list_elements(result):
"""Some of the results are empty - therefore, the try-except.
Others are lists with more than one element and only specific
elements are relevant.
Args:
result (dict of lists): result of the xpath elements.
Returns:
dict of strs
"""
for... | b81e80363f82dfe43878b3d8cb319f7129ebfc50 | 3,656,871 |
def gen_pixloc(frame_shape, xgap=0, ygap=0, ysize=1., gen=True):
"""
Generate an array of physical pixel coordinates
Parameters
----------
frame : ndarray
uniformly illuminated and normalized flat field frame
xgap : int (optional)
ygap : int (optional)
ysize : float (optional)
... | e09bb42cc0b003f6cedf5eed79ee65293aab13e2 | 3,656,872 |
def select(df: pd.DataFrame, time_key,
from_time='00-00-00 00', to_time='99-01-01 00'):
"""
:param df:
:param time_key:
:param from_time:
:param to_time:
:return:
:rtype: pandas.DataFrame
"""
select_index = (df[time_key] >= from_time) & (df[time_key] < to_time)
return ... | e925c2543bfabf9091fae18d9dc47c01364e1df8 | 3,656,873 |
def load_apogee_distances(dr=None, unit='distance', cuts=True, extinction=True, keepdims=False):
"""
Load apogee distances (absolute magnitude from stellar model)
:param dr: Apogee DR
:type dr: int
:param unit: which unit you want to get back
- "absmag" for absolute magnitude
... | 763d646c284cb056295ae57d7a7c9ced87964406 | 3,656,874 |
import json
import logging
def userstudy(config, data_train):
"""
Update the model based on feedback from user study.
- [config]: hyperparameters for model fine-tuning
- [data_train]: data pool to sample from
"""
def preprocess_data(doc, queries):
"""
Create a new field in [doc... | d3240142b55b202833364a9583b9c7c7e237bea2 | 3,656,875 |
import re
def clique_create(request):
"""
Creates a new grouping in the database (this integration must be stored in the db to be useful)
Arguments: /group-create "groupname" "@user1 @user2"
"""
requesting_user_id = request.POST.get('user_id')
args = re.findall(DOUBLE_QUOTE_ARG_REGEX, request.... | b990079ad0685b8c524dec65166da40f0e664ef7 | 3,656,876 |
import warnings
def cg_atoms(atoms, units, sites, scale, scaleValue, siteMap, keepSingleAtoms,
package):
"""
Get positions for atoms in the coarse-grained structure and the final
bond description. Returns a dictionary of the lattice, fractional
coordinates, and bonds. Also provides the... | 5cd2a6b8b0ce886b92912eb3dd8b14f0ea14f602 | 3,656,877 |
def compute_msa_weights(msa, threshold=.8):
"""
msa (Bio.Align.MultipleSeqAlignment): alignment for which sequence frequency based weights are to be computed
threshold (float): sequence identity threshold for reweighting
NOTE that columns where both sequences have a gap will not be taken into account w... | 13663501f57eef204533795c2271276a99b4a403 | 3,656,879 |
def search_storefront(client, phrase):
"""Execute storefront search on client matching phrase."""
resp = client.get(reverse("search:search"), {"q": phrase})
return [prod for prod, _ in resp.context["results"].object_list] | 0509c39cd9adb0b4c6d0849c8b068dcb3455b807 | 3,656,880 |
def is_repo_in_config(config, repo, rev, hook_id):
"""Get if a repository is defined in a pre-commit configuration.
Parameters
----------
config : dict
Pre-commit configuration dictionary.
repo : str
Repository to search.
rev : str
Repository tag revision.
hook_id : Ho... | 855315c50f4bfe53a4f9b7a5d392bb539e364617 | 3,656,881 |
def mat33_to_quat(mat):
"""
Convert matrix to quaternion.
:param mat: 3x3 matrix
:return: list, quaternion [x, y, z, w]
"""
wxyz = transforms3d.quaternions.mat2quat(mat)
return [wxyz[1], wxyz[2], wxyz[3], wxyz[0]] | 1dcedf919674895a1ed647314c328525e4068dfe | 3,656,882 |
def reshape(x, new_shape):
"""
Reshapes a tensor without changing its data.
Args:
x (Tensor): A tensor to be reshaped.
new_shape (Union[int, list(int), tuple(int)]): The new shape should be
compatible with the original shape. If the tuple has only one element,
the re... | 583ffc9e40c328586ec9d21b7a73cbc610eb5c29 | 3,656,883 |
def update_depth(depth_grid, elapsed_ts, depth_factor):
"""Just in time Update Depth for lake to pond
Parameters
----------
depth_grid: np.array like (float)
grid of current lake depths
elapsed_ts: float
number timesteps since start year
depth_factor: float
Returns
----... | e3fe2498421697ce584b385544a7501f54c02b85 | 3,656,884 |
def get_submissions(config, event_name, state='new'):
"""
Retrieve a list of submissions and their associated files
depending on their current status
Parameters
----------
config : dict
configuration
event_name : str
name of the RAMP event
state : str, optional
s... | e724c44b00db489f27c42acf7b21ba06a4ce0def | 3,656,885 |
def split_dataframe(df, size=10*1024*1024):
"""Splits huge dataframes(CSVs) into smaller segments of given size in bytes"""
# size of each row
row_size = df.memory_usage().sum() / len(df)
# maximum number of rows in each segment
row_limit = int(size // row_size)
# number of segments
seg... | 46f34d388e6f596bfcf803b4569eb3015344bafb | 3,656,886 |
from pathlib import Path
from typing import Optional
def convert_table_codes(input_filename: Path, output_filename: Path = None, column: str = 'countryCode',
namespace: Optional[str] = None, fuzzy:int = 0) -> Path:
"""
Adds a 'regionCode' column to the given table containing iso-3 country codes.
Parameters
----... | 1bba37fda512cf13e99a08a0ab7ebfdf10a4e330 | 3,656,887 |
def allow_view(user):
"""Is the current user allowed to view the user account?
Yes, if current user is admin, staff or self.
"""
if not flask.g.current_user: return False
if flask.g.am_admin: return True
if flask.g.am_staff: return True
if flask.g.current_user['username'] == user['username']... | 334e56796235e5bfab6f2220443c80fc5ff68a51 | 3,656,888 |
from datetime import datetime
import time
def httptimestamp(inhttpdate):
"""
Return timestamp from RFC1123 (HTTP/1.1).
"""
dat = datetime.datetime(*eut.parsedate(inhttpdate)[:5])
return int(time.mktime(dat.timetuple())) | acfcdbea1a9d331b7623478841c6cd1d45fd45bf | 3,656,889 |
from datetime import datetime
def calculate_duration(start_date, end_date=None):
""" Calculate how many years and months have passed between start and end dates """
# If end date not defined, use current date
if not end_date:
end_date = datetime.date.today()
years = end_date.year - start_date.... | d41c52d4d0274ce3b829b33f07c9730a34ab4cbd | 3,656,890 |
import typing
def actives(apikey: str) -> typing.List[typing.Dict]:
"""
Query FMP /actives/ API
:param apikey: Your API key.
:return: A list of dictionaries.
"""
path = f"actives"
query_vars = {"apikey": apikey}
return __return_json_v3(path=path, query_vars=query_vars) | de4eecc6f3006158407efd51d67b6a5ac40d2cfd | 3,656,892 |
def print_unicodeinfo(val: str, key: str) -> str:
"""
Prints the occurrence, unicode character or guideline rules and additional information
:param args: arguments instance
:param val: count of the occurrences of key
:param key: key (glyph or guideline rules)
:return:
"""
return f"{val:-... | 194bb1d03613e9708f8deea8c233d02dacd3e3b6 | 3,656,893 |
def qx_to_npx(df):
""" Return df with qx converted to npx.
"""
df = 1 - df
out = df.cumprod().shift()
for i in df.index:
out.loc[i, i] = 1
return out | 683a26f57dfb7ae1762df84f74186f0b88cb4688 | 3,656,894 |
def homepage(selenium, config):
"""Get homepage with selenium."""
selenium.get(config.BASE_URL)
selenium.set_window_size(config.WINDOW_WIDTH, config.WINDOW_HEIGHT)
custom_click_cookie_rollbar(selenium, config.MAX_WAIT_TIME)
return selenium | 39217a38ac09d41093070ed06803e36485f04e2b | 3,656,895 |
import torch
def _if_scalar_type_as(g, self, tensor):
"""
Convert self into the same type of tensor, as necessary.
We only support implicit casting for scalars, so we never
actually need to insert an ONNX cast operator here; just
fix up the scalar.
"""
if isinstance(self, torch._C.Value):... | 8e53bf67c8bbc78f142ffcb8027c0876eed951fe | 3,656,896 |
def read_images_text(path):
"""
see: src/base/reconstruction.cc
void Reconstruction::ReadImagesText(const std::string& path)
void Reconstruction::WriteImagesText(const std::string& path)
"""
images = {}
with open(path, "r") as fid:
while True:
line = fid.readline(... | 2aed7477e43bdcb73ad9eb866960b814278bbf0c | 3,656,897 |
def emailIsValid(email):
"""Return true if email is valid otherwise false"""
return EMAIL_RE.match(email) is not None | d9e28b68e31f1ab95c63aa80cd4a2a461cbac852 | 3,656,898 |
def calculate_line_number(text):
"""Calculate line numbers in the text"""
return len([line for line in text.split("\n") if line.strip() != ""]) | f35533945203ec2f47a89e7072ddd9b172f5554b | 3,656,899 |
def links_at_node(shape):
"""Get link ids for each node.
Parameters
----------
shape : tuple of int
Shape of grid of nodes.
Returns
-------
(N, 4) ndarray of int
Array of link ids.
Examples
--------
>>> from landlab.grid.structured_quad.links import links_at_no... | 0f354530d5c6b415c886df25e1b15ba2477de8c9 | 3,656,900 |
def manage_addFancyContent(self, id, REQUEST=None):
"""Add the fancy fancy content."""
id = self._setObject(id, FancyContent(id))
return '' | 47efd8df7d0ccc12894729d142a09a8a53562ff5 | 3,656,901 |
def convert_sentences(sentences, tokenizer):
"""
Truncate each sentence to 512 bpes in order to fit on BERT and convert it to bpes.
:param tokenizer: The BERT tokenizer we used in order convert each sentence to ids.
:param sentences: The tokenized sentences of the summary we are processing.
:return:... | 48cde2cba0af288bff9f49cb2ffc66dd22cfd952 | 3,656,902 |
from typing import Union
from typing import Tuple
def imscale(image: Imagelike, scale: Union[float, Tuple[float, float]],
**kwargs) -> np.ndarray:
"""Scale the given image. The result will be a new image
scaled by the specified scale.
"""
global _resizer
if _resizer is None:
_... | 1c0949b445620febe1482ea4d32ae2dd4ac44e04 | 3,656,903 |
def _packages_info() -> dict:
"""Return a dict with installed packages version"""
return Dependencies.installed_packages() | a4095968c7553aad017e97ab88322c616586961f | 3,656,905 |
def _first(root: TreeNode) -> TreeNode:
"""Return a first in "inorder" traversal order
of the `root` subtree
Args:
root (TreeNode): root of subtree
Returns:
TreeNode: first node in subtree
"""
if root.left is None:
return root
return _first(root.left) | 6464b7b920b32d3e3fd309eb1a7de26bd21a5710 | 3,656,907 |
def get_library_version() -> str:
"""
Returns the version of minecraft-launcher-lib
"""
return __version__ | aaa0703835cb00370bf30e96f2988f4c2e16bb51 | 3,656,908 |
def load_image(image):
"""reshape and convert image to fit the model"""
img = cv2.imread(image) # Load images
img = cv2.resize(img, (257, 257), interpolation=cv2.INTER_LINEAR) # resize
img = (np.float32(img) - 127.5) / 127.5 # change image to float and normalize
img = img.reshape((1, 257, 25... | 642f1da152b7e852e46c57d4c2608e469ba7bddb | 3,656,910 |
def hist_trigger_time_diff(df_dev):
"""
plots
"""
df = devices_trigger_time_diff(df_dev.copy())
fig = go.Figure()
trace = go.Histogram(x=np.log(df['row_duration'].dt.total_seconds()/60),
nbinsx=200,
)
fig.add_trace(trace)
return fig | 43ae70a2ff9a6b7f9927d91c88c2d540f7b8ca24 | 3,656,911 |
def verify_spec(spec_utid, proxy_utid):
"""
For a specific unit test id (utid) compares the spec with the proxy
"""
results=''
for key in spec_utid:
results += '%s: spec=%s, proxy=%s (%s) *** ' % (key,spec_utid[key],proxy_utid[key],(spec_utid.get(key)==proxy_utid.get(key)))
return results | b9854e23f0d88ed4f9abcc0c16236a2d543b9eb0 | 3,656,912 |
def lammps_created_gsd(job):
"""Check if the mdtraj has converted the production to a gsd trajectory for the job."""
return job.isfile("trajectory-npt.gsd") | a66c899a20e9602098150f46067d5505572232c2 | 3,656,913 |
from datetime import datetime
def neo4j_data_age(data, max_data_age=None):
"""
Checks the noclook_last_seen property against datetime.datetime.now() and
if the difference is greater than max_data_age (hours)
(django_settings.NEO4J_MAX_DATA_AGE will be used if max_data_age is not specified)
and the... | 77f703f972b7b67ec5de48c9f8a0aceef3cd0646 | 3,656,914 |
import optparse
def ProfileOptions(parser):
"""Build option group for profiling chrome.
Args:
parser: OptionParser object for parsing the command-line.
Returns:
Option group that contains profiling chrome options.
"""
profile_options = optparse.OptionGroup(parser, 'Profile Chrome Options')
brows... | 57b41cf7a629b566aec995be2d6181357000fc1c | 3,656,915 |
def _clean_unicode(value):
"""Return the value as a unicode."""
if isinstance(value, str):
return value.decode('utf-8')
else:
return unicode(value) | be04bf30cecd7f25d0c39c05f6d5e6d995438c0b | 3,656,916 |
def deslugify_province(prov):
"""
Province slug to name, i.e. dashes to spaces and title case.
KZN is a special case.
"""
if prov == 'kwazulu-natal':
return 'KwaZulu-Natal'
return prov.replace('-', ' ').title() | 8e88ea7325c3b911495780b4437bc02784fbad82 | 3,656,917 |
import re
def parse_vectors(vectors):
""" Basic cleanup of vector or vectors
Strip out V from V#s. Similar to parse tables, this by no means guarantees
a valid entry, just helps with some standard input formats
Parameters
----------
vectors : list of str or str
A string or list of st... | d2161e45bae51db21d7668ea6008ddb9ada16c4e | 3,656,920 |
def sort_slopes(sds):
"""Sort slopes from bottom to top then right to left"""
sds = np.array(sds)
scores = sds[:, 0, 1] + sds[:, 1, 1] * 1e6
inds = np.argsort(scores)
return sds[inds] | 3bb62bf3be98176ae096bfe5f55b203173c3a425 | 3,656,921 |
def serialize_skycoord(o):
"""
Serializes an :obj:`astropy.coordinates.SkyCoord`, for JSONification.
Args:
o (:obj:`astropy.coordinates.SkyCoord`): :obj:`SkyCoord` to be serialized.
Returns:
A dictionary that can be passed to :obj:`json.dumps`.
"""
representation = o.representa... | 52830d9243cac36573c358f1579987eb43435892 | 3,656,923 |
def redis_sentinel(create_sentinel, sentinel, loop):
"""Returns Redis Sentinel client instance."""
redis_sentinel = loop.run_until_complete(
create_sentinel([sentinel.tcp_address], timeout=2, loop=loop))
assert loop.run_until_complete(redis_sentinel.ping()) == b'PONG'
return redis_sentinel | 3b779c9ef73e3bc5949afadbace34a9dcca1273a | 3,656,924 |
from typing import Tuple
from typing import Dict
def compute_features(
seq_path: str,
map_features_utils_instance: MapFeaturesUtils,
social_features_utils_instance: SocialFeaturesUtils,
) -> Tuple[np.ndarray, Dict[str, np.ndarray]]:
"""Compute social and map features for the sequence.
... | bd8414b81bc3b1856773767d4f8db8897436ddf3 | 3,656,925 |
def summarizeTitlesByLength(titlesAlignments, limit=None):
"""
Sort match titles by sequence length.
@param titlesAlignments: A L{dark.titles.TitlesAlignments} instance.
@param limit: An C{int} limit on the number of results to show.
@return: An C{IPython.display.HTML} instance with match titles so... | 31f9a358032018b51910148dfaa82d4deb08191f | 3,656,926 |
def _diff_tail(msg):
"""`msg` is an arbitrary length difference "path", which could
be coming from any part of the mapping hierarchy and ending in any kind of
selector tree. The last item is always the change message: add, replace,
delete <blah>. The next to last should always be a selector key of s... | 224a4ca5f73b1f147c27599b62f0540480e40a0d | 3,656,927 |
def select_standard_name(session, cluster, importance_table_name):
"""
Use cluster members for a WHERE ... IN (...) query
Use SQLAlchemy to handle the escaping
"""
stmt = session.query('name from %s' % importance_table_name) \
.filter(column('name').in_(list(cluster))) \
.order_by('"... | 173113f8abf6b675fefe7279cfa1e28579747085 | 3,656,928 |
def calculate_depth(experiment):
""" Calculate the minor, major, total depth
Args:
experiment (remixt.Experiment): experiment object
Returns:
pandas.DataFrame: read depth table with columns, 'major', 'minor', 'total', 'length'
"""
data = remixt.analysis.experiment.create_segment_... | d4db665eff37f6590a2362af8896db25b8ae758b | 3,656,929 |
import random
def checkerboard(key, nsq, size, dtype=np.float32):
"""Create a checkerboard background image with random colors.
NOTE: only supports a single value for nsq (number squares).
Args:
key: JAX PRNGkey.
nsq (int): number of squares per side of the checkerboard.
size (int): size of one si... | 4f6428450a05fcb92ba05e22e336d887860fb143 | 3,656,930 |
import torch
def choice(x, a):
"""Generate a random sample from an array of given size."""
if torch.is_tensor(x):
return x[torch.randint(len(x), (a,))]
return x | af21321bcd12fe5f1a5eb59b8f0db14096899b5d | 3,656,931 |
def correct_gene_names(df):
""" Fix datetime entries in Gene names
"""
update_symbols = []
for i, gs in enumerate(df.Gene_Symbol):
if (not (isinstance(gs, str))) or (':' in gs):
update_symbols.append(mapping.get_name_from_uniprot(df.Uniprot_Id.iloc[i]))
else:
upda... | 5ca1aa1da60f238f9c377640b9f1a350658ea9d0 | 3,656,932 |
def process_repl_args(args):
""" Process PANDA replay-related arguments.
"""
assert False, 'Not implemented yet.'
cmd = []
cmd.extend(['-display', 'none'])
return cmd
# p_test "${panda_rr}-rr-snp" f "trace memory snapshot"
# p_test "${panda_rr}-rr-nondet.log" f "trace nondet log"
# -... | 660495454f3b04f76d9aa0447262cb3a8c06b543 | 3,656,933 |
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in range(1, min(k, n - k) + 1): # changed from xrange
ntok *= n
ktok *= t
n -= 1
return ntok // ... | 22c8639b3e110673164faa1ea84d669d5f8816d4 | 3,656,934 |
import pickle
def _get_ReaLiSe_dataset(which="15"):
"""
For its
"""
print("Loading ReaLiSe Dataset !")
print("Hint: The Data You loading now is the preprocessed sighan from ReaLise, ")
ddp_exec("os.system('date')")
path = "../SE_tmp_back/milestone/ReaLiSe/data/"
train_dataset = pickl... | 418f443fa3e2094b5288bcaf3490780632b2922c | 3,656,935 |
def generate_check_phrase() -> bytes:
""" Generate check-phrase for connecting of auxiliary socket.
:return: some array of ATOM_LENGTH bytes.
"""
return get_random_bytes(ATOM_LENGTH) | 9bcd270bd1f9c3a7943d4910c065cc9fdee02141 | 3,656,936 |
import pickle
def load_pickle(filename: str):
"""
Load a file from disk.
Parameters
----------
filename: str
Name of the file that is loaded.
Returns
-------
"""
return pickle.load(open(filename, 'rb')) | cae6710ba18664f244c55525c14a6bda0bea314d | 3,656,937 |
def crop_to_reference(dataset: xr.Dataset, ref_dataset: xr.Dataset) -> xr.Dataset:
""" Crops horizontal coordinates to match reference dataset """
if "longitude" not in dataset.coords.keys():
raise ValueError("Longitude is not a coordinate of dataset.")
if "longitude" not in ref_dataset.coords... | c915ec99dca5cd33531c049447e23e380590b1af | 3,656,940 |
def parse_line(description, inline_comments=_INLINE_COMMENT_PREFIXES):
"""
Parse a line and correctly add the description(s) to a collection
"""
# manually strip out the comments
# py2 cannot ignore comments on a continuation line
# https://stackoverflow.com/q/9110428/1177288
#
# PY3 ca... | 6fc58aef5b103ce429ed82378bce81a4550abb0f | 3,656,941 |
def target_frame():
"""Input frame."""
return 'IAU_ENCELADUS' | 8c57ab924a7b4471ac2f549493ebc176e853c652 | 3,656,942 |
def cards(cs):
"""Parse cards"""
cs = cs.split(' ')
result = np.zeros([len(valueL), len(colorL)], int)
for c in cs:
result[np.where(valueL == c[0])[0][0], np.where(colorL == c[1])[0][0]] = 1
return result | 9db7aa3ae9b42fb7b3fcd67371bca02b455fd8e4 | 3,656,943 |
def _get_max_diag_idx(m, n_A, n_B, diags, start, percentage):
"""
Determine the diag index for when the desired percentage of distances is computed
Parameters
----------
m : int
Window size
n_A : int
The length of the time series or sequence for which to compute the matrix
... | b6f86ee110ae4fa16638f86f2dcf324e7ebfb674 | 3,656,944 |
def get_argument_values(arg_defs, arg_asts, variables):
"""Prepares an object map of argument values given a list of argument
definitions and list of argument AST nodes."""
if arg_asts:
arg_ast_map = {arg.name.value: arg for arg in arg_asts}
else:
arg_ast_map = {}
result = {}
f... | 0bad38e7155d04ac297e2112b8f9b70e5fcc18a0 | 3,656,945 |
def get_identifier(positioner_id, command_id, uid=0, response_code=0):
"""Returns a 29 bits identifier with the correct format.
The CAN identifier format for the positioners uses an extended frame with
29-bit encoding so that the 11 higher bits correspond to the positioner
ID, the 8 middle bits are the... | 57a1ce7004186e8c1c88c06665311e71010705c4 | 3,656,946 |
def standardized(array):
"""Normalize the values in an array.
Arguments:
array (np.ndarray): Array of values to normalize.
Returns:
array with zero mean and unit standard deviation.
"""
return (array - array.mean()) / max(1e-4, array.std()) | 1764dfd1e4e173d2ca081edeb8b7165a79d63b7d | 3,656,947 |
import json
def newaddress(fn,passphrase,addr_type=0):
"""
getnetaddress
"""
wallet = Wallet(fn).fromFile(passphrase)
# Address Types
# addr_type == 0, deposit
# addr_type == 1, change
# addr_type == 2, staking
# addr_type == 3, Dealer
# Address types aren't programmatically important, but help to organize
... | 8afca8b83ea8464d3aeb02f5d2e406d2f5bebc53 | 3,656,948 |
import logging
def index(args):
"""Handles the index step of the program."""
if not args.index: # build index
logging.info(" Building index...")
index_list = generate_index(args.input_dir)
if not index_list: # list is empty
logging.error(" Empty index. Exiting...")
... | 5e8e37d387612eb81984c7bff48e747780475f78 | 3,656,949 |
def _output_object_or_file_map_configurator(prerequisites, args):
"""Adds the output file map or single object file to the command line."""
return _output_or_file_map(
output_file_map = prerequisites.output_file_map,
outputs = prerequisites.object_files,
args = args,
) | 7d362be5d6478764810ae3a9013ce1cb807efde3 | 3,656,951 |
def get_file_name():
"""This function asl the user for file and returns it"""
f_name = input('Input your file name: ')
return f_name | 5d3e524ebe423410f721afb070bfba9d804ed19f | 3,656,952 |
import itertools
def minimum_distance(geo1, geo2):
""" get the minimum distance between atoms in geo1 and those in geo2
"""
xyzs1 = coordinates(geo1)
xyzs2 = coordinates(geo2)
return min(cart.vec.distance(xyz1, xyz2)
for xyz1, xyz2 in itertools.product(xyzs1, xyzs2)) | ce6493d7e12bd3f48db209a01fe85eb4305835d0 | 3,656,954 |
def prepare():
"""
Get the list of filtered tweets by target entity where each item contains the tweet
with its original attributes when downloaded from Twitter
:return:
"""
path = '../../Data.json'
List = loadData(path) # load data
tweets = [List[i]['text'] for i in range(len(List))] ... | 0707993267bd6e76d432b08e947582f8a151f591 | 3,656,955 |
import requests
def deletecall(bam_url,api_call,call_parameters,delete_entity,header):
"""API request to delete and return values"""
call_url = "http://"+bam_url+"/Services/REST/v1/"+api_call+"?"
print("You are requesting to delete:")
print(delete_entity)
answer = input("Do you want to proceed (y ... | f6cffd225b9dd8d4d387b472d5ef522e2a48d738 | 3,656,957 |
def haDecFromAzAlt (azAlt, lat):
"""Converts alt/az position to ha/dec position.
Inputs:
- azAlt (az, alt) (deg)
- lat latitude (degrees);
>0 is north of the equator, <0 is south
Returns a tuple containing:
- haDec (HA, Dec) (deg), a tuple;
HA is i... | 9387d6771dd3fd4754a874141679902954adbecf | 3,656,958 |
def get_description(expression, options=None):
"""Generates a human readable string for the Cron Expression
Args:
expression: The cron expression string
options: Options to control the output description
Returns:
The cron expression description
"""
descripter = ExpressionDes... | b52bb4bda67074e5b9270f33f68892e371234dc4 | 3,656,959 |
def midpoint(close, length=None, offset=None, **kwargs):
"""Indicator: Midpoint"""
# Validate arguments
close = verify_series(close)
length = int(length) if length and length > 0 else 1
min_periods = int(kwargs['min_periods']) if 'min_periods' in kwargs and kwargs['min_periods'] is not None else len... | 3b14546715bec61dfd73a70d4a83042366c1ef08 | 3,656,961 |
from ..distributions.baseclass import Dist
import numpy
def quad_fejer(order, domain=(0, 1), growth=False, segments=1):
"""
Generate the quadrature abscissas and weights in Fejer quadrature.
Args:
order (int, numpy.ndarray):
Quadrature order.
domain (chaospy.distributions.base... | ec2472e134a2adab5cfa42703fdaafde844aee79 | 3,656,962 |
from pathlib import Path
def probe(app: FastFlixApp, file: Path) -> Box:
""" Run FFprobe on a file """
command = [
f"{app.fastflix.config.ffprobe}",
"-v",
"quiet",
"-loglevel",
"panic",
"-print_format",
"json",
"-show_format",
"-show_stre... | 055ac6003642bc78d1fcabbbb89765d1cacb3d80 | 3,656,963 |
def is_standard_time_series(time_series, window=180):
"""
Check the length of time_series. If window = 180, then the length of time_series should be 903.
The mean value of last window should be larger than 0.
:param time_series: the time series to check, like [data_c, data_b, data_a]
:type time_ser... | 7fb3212c69efb076dbab9555cf1eab9698475f9b | 3,656,964 |
def get_comment_type(token, comment_syntax):
"""
SQLエンジン関連コメントTypeを返す
"""
if is_block_comment(token):
return comment_syntax.get_block_comment_type(token)
elif is_line_comment(token):
return comment_syntax.get_line_comment_type(token) | 0ddd68b4cd12909c5689f5620b785ccb8a45cbeb | 3,656,965 |
def get_country_code(country_name):
""" Return the Pygal 2-digit country code for the given country."""
for code, name in COUNTRIES.items():
if name == country_name:
return code
# If the country wasn't found, return None.
return None | 485684fe01ade5e2ad558523ca839a468c083686 | 3,656,967 |
def get_divmod(up, down, minute=False, limit=2):
"""
获取商
:param up: 被除数
:param down: 除数
:param minute: 换算成分钟单位
:param limit: 保留小数的位数
:return: 商
"""
if up == 0:
return 0
if down == 0:
return 0
if minute:
return round(up/down/60.0, limit)
return roun... | 253304cde82fd4a3aa70737f4caabb20b5166349 | 3,656,968 |
def find_kernel_base():
"""Find the kernel base."""
return idaapi.get_fileregion_ea(0) | 20315c1fecc8d2a4ecf7301ccedeca84d4027285 | 3,656,969 |
def get_padding(x, padding_value=0, dtype=tf.float32):
"""Return float tensor representing the padding values in x.
Args:
x: int tensor with any shape
padding_value: int value that
dtype: type of the output
Returns:
float tensor with same shape as x containing values 0 or 1.
... | d11650796b980a53a5790588ac123c5323b867bd | 3,656,970 |
import typing
def canonical_symplectic_form_inverse (darboux_coordinates_shape:typing.Tuple[int,...], *, dtype:typing.Any) -> np.ndarray:
"""
Returns the inverse of canonical_symplectic_form(dtype=dtype). See documentation for that function for more.
In particular, the inverse of the canonical symplectic... | 4ef3c820c7919fcd1bb7fda3fdf2482f3cd70c03 | 3,656,971 |
def update_with_error(a, b, path=None):
"""Merges `b` into `a` like dict.update; however, raises KeyError if values of a
key shared by `a` and `b` conflict.
Adapted from: https://stackoverflow.com/a/7205107
"""
if path is None:
path = []
for key in b:
if key in a:
i... | 201650bba4fcae21d353f88ff22a9559aea61ff4 | 3,656,972 |
import re
def tokenize(sent):
"""Return the tokens of a sentence including punctuation.
>>> tokenize("Bob dropped the apple. Where is the apple?")
["Bob", "dropped", "the", "apple", ".", "Where", "is", "the", "apple", "?"]
"""
return [x.strip() for x in re.split(r"(\W+)?", sent) if x and x.strip(... | 09456d2ae7d590ba8d6373a27993a52c0693027b | 3,656,973 |
def tree_unflatten(flat, tree, copy_from_tree=None):
"""Unflatten a list into a tree given the tree shape as second argument.
Args:
flat: a flat list of elements to be assembled into a tree.
tree: a tree with the structure we want to have in the new tree.
copy_from_tree: optional list of elements that ... | 711bc67a20835091360d0fbc64e0a8842eec53ba | 3,656,974 |
def ByteOffsetToCodepointOffset( line_value, byte_offset ):
"""The API calls for byte offsets into the UTF-8 encoded version of the
buffer. However, ycmd internally uses unicode strings. This means that
when we need to walk 'characters' within the buffer, such as when checking
for semantic triggers and similar,... | 0a826157c43cb73a5dff31c20c906144b4a0eaa6 | 3,656,975 |
def get_authed_tweepy(access_token, token_secret):
"""Returns an authed instance of the twitter api wrapper tweepy for a given user."""
social_app_twitter = get_object_or_404(SocialApp, provider='twitter')
auth = tweepy.OAuthHandler(social_app_twitter.client_id, social_app_twitter.secret)
auth.set_acce... | 33bbf0cabdf2bbd3fc543efc4d921119d29c7729 | 3,656,976 |
def suffix_for_status(status):
"""Return ``title`` suffix for given status"""
suffix = STATUS_SUFFIXES.get(status)
if not suffix:
return ''
return ' {}'.format(suffix) | a908d28c6e461dcc8277784e82e383642b5ecfa3 | 3,656,977 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.