content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def group_node_intro_times(filt, groups, n_sents):
"""
Returns lists of addition times of nodes into particular groups
"""
devs = [[] for _ in range(len(set(groups)))]
for i in range(len(groups)):
intro = int(filt[i, i])
devs[groups[i]].append(intro/n_sents) # still normalize additi... | b5da0e97c76683201a9b81fce1b1f1c7f25e4d6d | 3,640,500 |
def svn_client_version():
"""svn_client_version() -> svn_version_t const *"""
return _client.svn_client_version() | 2ffab063bce4e32010eb1f3aa57306e60a0f2417 | 3,640,501 |
import os
def get_slice_name(data_dir, imname, delta=0):
"""Infer slice name with an offset"""
if delta == 0:
imname = imname + '.npy'
#print('imname0000',imname )
return imname
delta = int(delta)
dirname, slicename = imname.split(os.sep)
#slice_idx = int(slicename[:-4])
... | e62988a20af829a5c821b0f8e0de971d8257f3cc | 3,640,502 |
import os
import tqdm
def download(name, destination=None, chunksize=4096, force=False):
"""
Checks if there is an actual version of the specified file on the device,
and if not, downloads it from servers.
Files, theirs checksums and links to them must be specified
in the tps.downloader._content d... | 62781bba6908f2e103115a01580c6df284f3aeb3 | 3,640,503 |
def getportnum(port):
"""
Accepts a port name or number and returns the port number as an int.
Returns -1 in case of invalid port name.
"""
try:
portnum = int(port)
if portnum < 0 or portnum > 65535:
logger.error("invalid port number: %s" % port)
portnum = -1... | 7a5e287a0014afc1fa2933fcaae389a3c8aa50e8 | 3,640,504 |
def getParafromMinibatchModel(X_train, Y_train, X_test, Y_test, learning_rate = 0.0001,
num_epochs = 1500, minibatch_size = 32, print_cost = True):
"""
Implements a three-layer tensorflow neural network: LINEAR->RELU->LINEAR->RELU->LINEAR->SOFTMAX.
Arguments:
X_train -- training set, of s... | 2716d4a02b0ce5a0a7a640f80a51f180d280eb0d | 3,640,505 |
def add_land(
ax=None, scale="10m", edgecolor=None, facecolor=None, linewidth=None, **kwargs
):
"""Add land to an existing map
Parameters
----------
ax : matplotlib axes object, optional
scale : str, optional
Resolution of NaturalEarth data to use ('10m’, ‘50m’, or ‘110m').
edgecolo... | c2a5e97a7e6cb76ffe4a70b754fe86c59b71eb05 | 3,640,506 |
import CLSIDToClass
def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on!
"""Given a COM prog_id, return an object that is using makepy support, building if necessary"""
disp = win32com.client.Dispatch(prog_id)
if not disp.__dict__.get("CLSID"): # Eeek - no makepy suppo... | 9f9ed2d87ab5c0329ce729a4fca3078daf6e8d17 | 3,640,507 |
def _parallel_predict_log_proba(estimators, estimators_features, X, n_classes):
"""Private function used to compute log probabilities within a job."""
n_samples = X.shape[0]
log_proba = np.empty((n_samples, n_classes))
log_proba.fill(-np.inf)
all_classes = np.arange(n_classes, dtype=np.int)
for... | a42510017d8b14ddf8f97de5902f6e1fb223da0d | 3,640,508 |
import numpy
def _get_circles(img, board, pattern):
"""
Get circle centers for a symmetric or asymmetric grid
"""
h = img.shape[0]
w = img.shape[1]
if len(img.shape) == 3 and img.shape[2] == 3:
mono = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
else:
mono = img
flag = cv2.CA... | c2a3d207d73a600250c65480b5cba7a4d9e62a04 | 3,640,509 |
def sort_coords(coords: np.ndarray) -> np.ndarray:
"""Sort coordinates based on the angle with first coord from the center.
Args:
coords (np.ndarray):
Coordinates to be sorted. The format of coords is as follows.
np.array([[x1, y1, z1], [x2, y2, z2], [x3, y3, z3]]
Returns:
... | a05390e56e57e66e6f288096fd4583bee26da88f | 3,640,510 |
import warnings
def to_fraction(value, den_limit=65536):
"""
Converts *value*, which can be any numeric type, an MMAL_RATIONAL_T, or a
(numerator, denominator) tuple to a :class:`~fractions.Fraction` limiting
the denominator to the range 0 < n <= *den_limit* (which defaults to
65536).
"""
... | 6ee8c13ab17e08480f13012a834d5d928a7d4f51 | 3,640,511 |
def find_closest(myList, myNumber):
"""
Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
# adapted from
# https://stackoverflow.com/questions/12141150/from-list-of-integers-get-number-closest-to-a-given-value
"""
sortList = sorted(myList)
... | 0e4b6e2932aa4bb1886627e831d90d3a339b73b6 | 3,640,512 |
from pathlib import Path
def remove_uuid_file(file_path, dry=False):
"""
Renames a file without the UUID and returns the new pathlib.Path object
"""
file_path = Path(file_path)
name_parts = file_path.name.split('.')
if not is_uuid_string(name_parts[-2]):
return file_path
name_part... | f2c8aa77595081ff968596340b45f61c490d16ec | 3,640,513 |
def get_9x9x9_scramble(n=120):
""" Gets a random scramble (SiGN notation) of length `n` for a 9x9x9 cube. """
return _MEGA_SCRAMBLER.call("megaScrambler.get999scramble", n) | 7f5d11ad8cec05de5165fa0f90da40a7d9f17d97 | 3,640,514 |
import re
def youku(link):
"""Find youku player URL."""
pattern = r'http:\/\/v\.youku\.com\/v_show/id_([\w]+)\.html'
match = re.match(pattern, link)
if not match:
return None
return 'http://player.youku.com/embed/%s' % match.group(1) | efcf1394cc02503a1ae18d91abee34777958e545 | 3,640,515 |
from typing import Optional
def get_default_service_account(project: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetDefaultServiceAccountResult:
"""
Use this data source to retrieve default service account for this project
:param str pro... | 0d0c859771a11fe9a0772b9dd4aa2597a9081bd3 | 3,640,516 |
def combinationSum(candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result = []
candidates = sorted(candidates)
def dfs(remain, stack):
if remain == 0:
result.append(stack)
return
for item in candidates:
if item > remain:
break
if stack... | e8739c196c84aa7d15712ba1007e602a330fd625 | 3,640,517 |
from django.core.files.base import ContentFile
from django_webdav_storage.compat import PY3, TEXT_TYPE
import uuid
import os
def create_file(webdav_storage):
"""
Creates a file with a unique prefix in the WebDAV storage
"""
def inner(filename, content=b'', prefix=''):
if all((PY3, isinstance(... | 6e36df5f901380878dd321b2bf3f797fb1a6ca78 | 3,640,518 |
import re
def get_Xy(sentence):
"""将 sentence 处理成 [word1, w2, ..wn], [tag1, t2, ...tn]"""
words_tags = re.findall('(.)/(.)', sentence)
if words_tags:
words_tags = np.asarray(words_tags)
words = words_tags[:, 0]
tags = words_tags[:, 1]
return words, tags # 所有的字和tag分别存为 data... | 9d850f74af6417c0172cb944b0e1ce4e3d931a96 | 3,640,519 |
def create_gap_token(rowidx=None):
"""returns a gap Token
Parameters
----------
rowidx: int (Optional)
row id
Returns
-------
Token
"""
return TT.Token(token_type=SupportedDataTypes.GAP, value='', rowidx=rowidx) | 08f18bfcbf54e8861c684943111e22c33af2c69f | 3,640,520 |
def get_local_bricks(volume: str) -> Result:
"""
Return all bricks that are being served locally in the volume
volume: Name of the volume to get local bricks for
"""
vol_info = volume_info(volume)
if vol_info.is_err():
return Err(vol_info.value)
local_ip = get_local_ip()
... | d49db6aac12d976a1cfbd72540862be6406f85c9 | 3,640,521 |
def unionWCT(m=6, n=6):
""" @ worst-case family union where
@m>=2 and n>=2 and k=3
:arg m: number of states
:arg n: number of states
:type m: integer
:type n: integer
:returns: two dfas
:rtype: (DFA,DFA)"""
if n < 2 or m < 2:
raise TestsError("number of states must both gr... | 2b93c22e380c0ed52db2c9dfb9042785541b5885 | 3,640,522 |
def week_changes (after, before, str_dates, offset = 0, limit = 3) :
"""Yield all elements of `str_dates` closest to week changes."""
return unit_changes (after, before, str_dates, "week", offset, limit) | 0b744db3f2cc581ea1fd2c59bbdc569339b88737 | 3,640,523 |
def getHiddenStatus(data):
"""
使用Gaussian HMM对数据进行建模,并得到预测值
"""
cols = ["r_5", "r_20", "a_5", "a_20"]
model = GaussianHMM(n_components=3, covariance_type="full", n_iter=1000,
random_state=2010)
model.fit(data[cols])
hiddenStatus = model.predict(data[cols])
return hiddenStatus | 4a613e426b8a4f16e02f535aebc2752d4a99ae25 | 3,640,524 |
def format_time(data, year):
"""Format any time variables in US.
Parameters
----------
data : pd.DataFrame
Data without time formatting.
year : int
The `year` of the wave being processed.
Returns
-------
data : pd.DataFrame
Data with time formatting.
"""
... | 858d7e48143a16e644d4f1241cd8918385dc7c5f | 3,640,525 |
def get_connection(sid):
"""
Attempts to connect to the given server and
returns a connection.
"""
server = get_server(sid)
try:
shell = spur.SshShell(
hostname=server["host"],
username=server["username"],
password=server["password"],
por... | 933aa768640455ed21b914c4cb432436a7225e4e | 3,640,526 |
import sys
import math
def compare_apertures(reference_aperture, comparison_aperture, absolute_tolerance=None, attribute_list=None, print_file=sys.stdout, fractional_tolerance=1e-6, verbose=False, ignore_attributes=None):
"""Compare the attributes of two apertures.
Parameters
----------
reference_ape... | 2e167a2e70a26fac23d17c0f464d9cb1cdc14509 | 3,640,527 |
from typing import List
def tail(filename: str, nlines: int = 20, bsz: int = 4096) -> List[str]:
"""
Pure python equivalent of the UNIX ``tail`` command. Simply pass a filename and the number of lines you want to load
from the end of the file, and a ``List[str]`` of lines (in forward order) will be return... | e5f94cdc349610189c85c82c66589c243063f5a6 | 3,640,528 |
def initialized(name, secret_shares=5, secret_threshold=3, pgp_keys=None,
keybase_users=None, unseal=True):
"""
Ensure that the vault instance has been initialized and run the
initialization if it has not.
:param name: The id used for the state definition
:param secret_shares: THe nu... | c2b88bb8875ded7c7274b0695a9de9fb287b0b57 | 3,640,529 |
def plot(plot, x, y, **kwargs):
"""
Adds series to plot. By default this is displayed as continuous line.
Refer to matplotlib.pyplot.plot() help for more info. X and y coordinates
are expected to be in user's data units.
Args:
plot: matplotlib.pyplot
Plot to which series sho... | 1e861243a87b61461fb49dcadf19ec9099fa5a1f | 3,640,530 |
def glyph_by_hershey_code(hershey_code):
"""
Returns the Hershey glyph corresponding to `hershey_code`.
"""
glyph = glyphs_by_hershey_code.get(hershey_code)
if glyph is None:
raise ValueError("No glyph for hershey code %d" % hershey_code)
return glyph | 54a8c9657466f2348e93667e8a638c3e44681adb | 3,640,531 |
def _get_prefab_from_address(address):
"""
Parses an address of the format ip[:port] and return return a prefab object connected to the remote node
"""
try:
if ':' in address:
ip, port = address.split(':')
port = int(port)
else:
ip, port = address, 22
... | 3520dcca249073433ece88a4d9b31e8c2d73eb86 | 3,640,532 |
def interval_to_errors(value, low_bound, hi_bound):
"""
Convert error intervals to errors
:param value: central value
:param low_bound: interval low bound
:param hi_bound: interval high bound
:return: (error minus, error plus)
"""
error_plus = hi_bound - value
error_minus = value ... | ffee403968ddf5fd976df79a90bdbb62474ede11 | 3,640,533 |
from typing import Any
from typing import cast
def log_enabled_arg(request: Any) -> bool:
"""Using different log messages.
Args:
request: special fixture that returns the fixture params
Returns:
The params values are returned one at a time
"""
return cast(bool, request.param) | 9ff97ab8f5cc8e3a0c548e613b75b5da050eb53d | 3,640,534 |
def expsign(sign, exp):
"""
optimization of sign ** exp
"""
if sign == 1:
return 1
assert sign == -1
return -1 if exp % 2 else 1 | d770aaa2a4d20c9530a213631047d1d0f9cca3f7 | 3,640,535 |
def convert_format(tensors, kind, target_kind):
"""Converts data from format 'kind' to one of the formats specified in 'target_kind'
This allows us to convert data to/from dataframe representations for operators that
only support certain reprentations
"""
# this is all much more difficult because o... | 8925d002395da05c6b5a7374a7288cc0511df1cb | 3,640,536 |
import urllib
import re
def template2path(template, params, ranges=None):
"""Converts a template and a dict of parameters to a path fragment.
Converts a template, such as /{name}/ and a dictionary of parameter
values to a URL path (string).
Parameter values that are used for buildig the path are con... | daf628ab6ef1a6fddb612c0f4c817085ac23ce2c | 3,640,537 |
from typing import Union
from typing import Dict
from typing import Any
def calculate_total_matched(
market_book: Union[Dict[str, Any], MarketBook]
) -> Union[int, float]:
"""
Calculate the total matched on this market from the amounts matched on each runner at each price point. Useful for historic data w... | 7bc3d4680e5507d1400e94ab30213c0cc6d817bb | 3,640,538 |
import argparse
def parse_args(args):
"""Build parser object with options for sample.
Returns:
Python argparse parsed object.
"""
parser = argparse.ArgumentParser(
description="A VCF editing utility which adds ref and all sequences to a SURVIVOR fasta file.")
parser.add_argument(... | 36f9e13a65f13659e32dcfda9fbbca6d52ffd0e6 | 3,640,539 |
import re
def _newline_to_ret_token(instring):
"""Replaces newlines with the !RET token.
"""
return re.sub(r'\n', '!RET', instring) | 4fcf60025f79811e99151019a479da04f25ba47c | 3,640,540 |
def _ComputeLineCounts(old_lines, chunks):
"""Compute the length of the old and new sides of a diff.
Args:
old_lines: List of lines representing the original file.
chunks: List of chunks as returned by patching.ParsePatchToChunks().
Returns:
A tuple (old_len, new_len) representing len(old_lines) and... | ba99714016b69d87f260c8e7b8793468a2f7b04d | 3,640,541 |
def _read_int(file_handle, data_size):
"""
Read a signed integer of defined data_size from file.
:param file_handle: The file handle to read from at current position
:param data_size: The data size in bytes of the integer to read
:returns: The integer read and decoded
"""
return int.from_... | 4d2a7e82e9daa828c0e5b180250834f2fa9977d5 | 3,640,542 |
import numpy
def quaternion_to_matrix(quat):
"""OI
"""
qw = quat[0][0]
qx = quat[1][0]
qy = quat[2][0]
qz = quat[3][0]
rot = numpy.array([[1 - 2*qy*qy - 2*qz*qz, 2*qx*qy - 2*qz*qw, 2*qx*qz + 2*qy*qw],
[2*qx*qy + 2*qz*qw, 1 - 2*qx*qx - 2*qz*qz, 2*qy*qz - 2*qx*qw],
[2*qx*qz - 2*qy*qw, 2*... | 67f02ea97db1af4a763c3a97957f36de29da0157 | 3,640,543 |
def get_cart_from_request(request, create=False):
"""Returns Cart object for current user. If create option is True,
new cart will be saved to db"""
cookie_token = request.get_signed_cookie(
Cart.COOKIE_NAME, default=None)
if request.user.is_authenticated():
user = request.user
... | d22c2587a20c12bac1fe713d40ddf069bfc5f40e | 3,640,544 |
def make_concrete_rule(rule_no, zone_map, direction, zone, rule, concrete_port):
"""Take a rule and create a corresponding concrete rule."""
def make_rule(target_zone, port):
return ConcreteRule(source_rules=[rule], rule_no=rule_no, target_zone=target_zone,
direction=directi... | b7b1babc32c2d81193e62e90b5fd751ad8575ff1 | 3,640,545 |
from typing import List
def downcast(df: pd.DataFrame, signed_columns: List[str] = None) -> pd.DataFrame:
"""
Automatically check for signed/unsigned columns and downcast.
However, if a column can be signed while all the data in that column is unsigned, you don't want to downcast to
an unsigned column... | 2eb2494e5a59630c4e20d114aac076c971f287a6 | 3,640,546 |
import sys
def get_setting(name):
"""
Hook for getting Django settings and using properties of this file as the
default.
"""
me = sys.modules[__name__]
return getattr(settings, name, getattr(me, name, None)) | 8bb594469a81f66c8e490b73a53db88cef4ca537 | 3,640,547 |
from typing import Optional
def entity_type(entity: dict) -> Optional[str]:
"""
Safely get the NGSI type of the given entity.
The type, if present, is expected to be a string, so we convert it if it
isn't.
:param entity: the entity.
:return: the type string if there's an type, `None` otherwis... | e4d27b7499710951959cfef5c1191c6744bd02ce | 3,640,548 |
def read_private_key_data(bio):
"""
Read enough data from bio to fully read a private key.
(The data read is thrown away, though.)
This is required since the format does not contain the actual length
of the privately-serialized private key data. The knowledge of what
to read for each key type... | de1e38c49fe81449b90b14ccab0b2aaf7de121bc | 3,640,549 |
def list_check(lst):
"""Are all items in lst a list?
>>> list_check([[1], [2, 3]])
True
>>> list_check([[1], "nope"])
False
"""
t = [1 if isinstance(x, list) else 0 for x in lst]
return len(lst) == sum(t) | 9e2c55cb6e15f89ff2b73a78d5f15310d3cac672 | 3,640,550 |
def check_for_peaks_in_residual(vel, data, errors, best_fit_list, dct,
fitted_residual_peaks, signal_ranges=None,
signal_mask=None, force_accept=False,
params_min=None, params_max=None, noise_spike_mask=None):
"""Try fit... | 0cc000f140514dd7c9c52df4636f287b80c66b9e | 3,640,551 |
from typing import Dict
def build_encoded_manifest_from_nested_directory(
data_directory_path: str,
) -> Dict[str, EncodedVideoInfo]:
"""
Creates a dictionary from video_id to EncodedVideoInfo for
encoded videos in the given directory.
Args:
data_directory_path (str): The folder to ls to ... | 2a908eb33b140e73d27bca02da449d09e4ac4c5d | 3,640,552 |
def derive_question(doc):
"""
Return a string that rephrases an action in the
doc in the form of a question.
'doc' is expected to be a spaCy doc.
"""
verb_chunk = find_verb_chunk(doc)
if not verb_chunk:
return None
subj = verb_chunk['subject'].text
obj = verb_chunk['object'].text
if verb_chunk['verb'].tag_ ... | 876e6733f8cf3d9accf3af1af89241ded4a02481 | 3,640,553 |
def recover_label(pred_variable, gold_variable, mask_variable, label_alphabet, word_recover, sentence_classification=False):
"""
input:
pred_variable (batch_size, sent_len): pred tag result
gold_variable (batch_size, sent_len): gold result variable
mask_variable (batch_si... | 7f3efef4a0e9041e329c8d1c0c5641bf0c79ff58 | 3,640,554 |
def RegenerateOverview(*args, **kwargs):
"""
RegenerateOverview(Band srcBand, Band overviewBand, char const * resampling="average", GDALProgressFunc callback=0,
void * callback_data=None) -> int
"""
return _gdal.RegenerateOverview(*args, **kwargs) | 8f05fcb7a12bf09d432b65b9cf049d2ff5cf23b1 | 3,640,555 |
import imp
def import_code(code, name):
""" code can be any object containing code -- string, file object, or
compiled code object. Returns a new module object initialized
by dynamically importing the given code. If the module has already
been imported - then it is returned and not import... | 309fb1e214225dcdf742bc5ea7d21cb502b05ae9 | 3,640,556 |
def two(data: np.ndarray) -> int:
"""
Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating,
then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in
decimal, not binary.)
"""
... | 723984bf673ab23697ccff69e0c7e2529cce2e81 | 3,640,557 |
import six
def get_lr_fit(sess, model, x_train, y_train, x_test, num_steps=100):
"""Fit a multi-class logistic regression classifier.
Args:
x_train: [N, D]. Training data.
y_train: [N]. Training label, integer classes.
x_test: [M, D]. Test data.
Returns:
y_pred: [M]. Integer class prediction of... | a60654d15e8f0f1c5e7ab11bc9c3e17f3440d286 | 3,640,558 |
import random
def make_block_trials(ntrials_block):
"""Creates a matrix of pseudo-random balanced trial parameters for a block of trials.
Parameters
----------
ntrials_block : int
Number of trials in the block.
Returns
-------
block : 2d array
Matrix of trial parameters (... | ed504af676a660befd3b548e9148e4a6cbc93183 | 3,640,559 |
def view_user(user_id: int):
"""Return the given user's history."""
return render_user(manager.get_user_by_id(user_id)) | 70b88f25b63697682650ae60591e4eee16253433 | 3,640,560 |
def first(c) -> col:
"""
In contrast to pyspark.sql.functions.first this function uses column name as alias
without prefixing it with the aggregation function name.
"""
if isinstance(c, str):
return F.first(c).alias(c)
columnName = c._jc.toString()
return F.first(c).alias(columnName... | 0b7b0bb0d3e2f56c400f3a026f39cb2459b0e54f | 3,640,561 |
def translate(root_list, use_bag_semantics=False):
"""
Translate a list of relational algebra trees into SQL statements.
:param root_list: a list of tree roots
:param use_bag_semantics: flag for using relational algebra bag semantics
:return: a list of SQL statements
"""
translator = (Trans... | b7a25d8af2e47ba134a6dbf490a0255391b330c1 | 3,640,562 |
import jsonschema
def replace_aliases(record):
"""
Replace all aliases associated with this DID / GUID
"""
# we set force=True so that if MIME type of request is not application/JSON,
# get_json will still throw a UserError.
aliases_json = flask.request.get_json(force=True)
try:
js... | a19335af1836f1899565b874640cdd0858247bcc | 3,640,563 |
def pos_tag(docs, language=None, tagger_instance=None, doc_meta_key=None):
"""
Apply Part-of-Speech (POS) tagging to list of documents `docs`. Either load a tagger based on supplied `language`
or use the tagger instance `tagger` which must have a method ``tag()``. A tagger can be loaded via
:func:`~tmto... | a990acc4caa33c7615c961593557b43ef6d5a6d0 | 3,640,564 |
def NOBE_GA_SH(G,K,topk):
"""detect SH spanners via NOBE-GA[1].
Parameters
----------
G : easygraph.Graph
An unweighted and undirected graph.
K : int
Embedding dimension k
topk : int
top - k structural hole spanners
Returns
-------
SHS : list
The t... | a1f3f8f041e4a89b9d09037479574c27505dd7fa | 3,640,565 |
import torch
def calculate_correct_answers(model, dataloader, epoch):
"""Calculate correct over total answers"""
forward_backward_func = get_forward_backward_func()
for m in model:
m.eval()
def loss_func(labels, output_tensor):
logits = output_tensor
loss_dict = {}
#... | 24e3196cd172719d16524b0bbd6c0848fec3c44e | 3,640,566 |
from typing import Dict
from typing import Tuple
from typing import Any
import re
def set_template_parameters(
template: Template, template_metadata: TemplateMetadata, input_parameters: Dict[str, str], interactive=False
):
"""Set and verify template parameters' values in the template_metadata."""
if inter... | fb14c28f754305e6907cff40086b2ffe55a55526 | 3,640,567 |
def calc_roll_pitch_yaw(yag, zag, yag_obs, zag_obs, sigma=None):
"""Calc S/C delta roll, pitch, and yaw for observed star positions relative to reference.
This function computes a S/C delta roll/pitch/yaw that transforms the
reference star positions yag/zag into the observed positions
yag_obs/zag_obs. ... | e1cf3c1377a3613b9ea1fc76e7c9eecac1a6e175 | 3,640,568 |
def make_query_abs(db, table, start_dt, end_dt, dscfg, mode, no_part=False, cols=None):
"""절대 시간으로 질의를 만듦.
Args:
db (str): DB명
table (str): table명
start_dt (date): 시작일
end_dt (date): 종료일
dscfg (ConfigParser): 데이터 스크립트 설정
mode: 쿼리 모드 ('count' - 행 수 구하기, 'preview' ... | 113049d37ceaf1cbf9b9149b1d3a4278dad96aa6 | 3,640,569 |
import warnings
def tgl_forward_backward(
emp_cov,
alpha=0.01,
beta=1.0,
max_iter=100,
n_samples=None,
verbose=False,
tol=1e-4,
delta=1e-4,
gamma=1.0,
lamda=1.0,
eps=0.5,
debug=False,
return_history=False,
return_n_iter=True,
choose="gamma",
lamda_criter... | d49e9882070e8fa28395fe47afac54e83cfc7021 | 3,640,570 |
def validate_task_rel_proposal(header, propose, rel_address, state):
"""Validates that the User exists, the Task exists, and the User is not
in the Task's relationship specified by rel_address.
Args:
header (TransactionHeader): The transaction header.
propose (ProposeAddTask_____): The Task... | d9511f0cad43cbb7a2bc9c08b9f1d112d2d4bf7b | 3,640,571 |
import json
def all_cells_run(event_str: str, expected_count: int) -> bool:
"""Wait for an event signalling all cells have run.
`execution_count` should equal number of nonempty cells.
"""
try:
event = json.loads(event_str)
msg_type = event["msg_type"]
content = event["content... | c3e1bb23f38ffdd09d4cc2ea3326d40b7cf54034 | 3,640,572 |
from typing import Union
def to_forecasting(
timeseries: np.ndarray,
forecast: int = 1,
axis: Union[int, float] = 0,
test_size: int = None,
):
"""Split a timeseries for forecasting tasks.
Transform a timeseries :math:`X` into a series of
input values :math:`X_t` and a series of output val... | 7d77df1f52ee5a499b635dd9575ab08afaa7dda2 | 3,640,573 |
def build_task_environment() -> dm_env.Environment:
"""Returns the environment."""
# We first build the base task that contains the simulation model as well
# as all the initialization logic, the sensors and the effectors.
task, components = task_builder.build_task()
del components
env_builder = subtask_e... | 91618e066ef92a396ea2dc8f6ff36c9a98356e29 | 3,640,574 |
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
except ValueError:
nums.append(target)
nums.sort()
return nums.index(target) | 56a719b1595502a773c108d26c597fb5ac0201bb | 3,640,575 |
def resource(author, tag) -> Resource:
"""Resource fixture"""
return Resource(
name="Sentiment Algorithm",
url="https://raw.githubusercontent.com/MarcSkovMadsen/awesome-streamlit/master/src/pages/gallery/contributions/marc_skov_madsen/sentiment_analyzer/sentiment_analyzer.py",
is_awesom... | b4eb6bd4c8409e83d0ebb75f0dc390ce7d669512 | 3,640,576 |
def del_list(request, list_id: int, list_slug: str) -> HttpResponse:
"""Delete an entire list. Danger Will Robinson! Only staff members should be allowed to access this view.
"""
task_list = get_object_or_404(TaskList, slug=list_slug)
# Ensure user has permission to delete list. Admins can delete all l... | 5183bc65bbb3025ec84511fa0fab32abab8da761 | 3,640,577 |
def model_softmax(input_data=None,
output_targets=None,
num_words=3000,
num_units=128,
num_layers=2,
num_tags=5,
batchsize=1,
train=True
):
"""
:param input_data:
... | a3991206b0cdae621e1095a1d1dc4493d600bc26 | 3,640,578 |
from typing import AnyStr
from typing import List
from typing import Dict
def get_metric_monthly_rating(metric: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the monthly price for a metric.
:metric (AnyStr) A string... | e73c56015a9320e9ce08b0f1375a7cea70dcc0f0 | 3,640,579 |
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= tf.transpose(mask)
return tf.reduce_mean(t... | f95f917ff4dd5835c84167f7bf3ea76a4cf6536b | 3,640,580 |
def u0(x):
"""
Initial Condition
Parameters
----------
x : array or float;
Real space
Returns
-------
array or float : Initial condition evaluated in the real space
"""
return sin(pi * x) | bd55cc7226a4d2ca941b8718d62025f6f2e157b6 | 3,640,581 |
import json
def jsonify(value):
"""
Convert a value into a JSON string that can be used for JSONB queries in
Postgres.
If a string happens to contain the character U+0000, which cannot be
represented in a PostgreSQL value, remove the escape sequence representing
that character, effectively st... | 7fff497b302822f8f79f0e68b2576c26458df99c | 3,640,582 |
import os
import json
import urllib3
import certifi
def add_generated_report_header(report_header):
"""
Upload report history and return the id of the header that was generated
on the server.
Parameters
----------
report_header:
Required Parmeters:
A dictionary of paramet... | d1c1923e4a61ae82f4f9319b471a18ed2bcbf562 | 3,640,583 |
def generate_dataset(type = 'nlp', test=1):
"""
Generates a dataset for the model.
"""
if type == 'nlp':
return generate_nlp_dataset(test=test)
elif type == 'non-nlp':
return generate_non_nlp_dataset() | 5e8998a6c9e10775367be3d6d4a722f3e24c6be1 | 3,640,584 |
def search(isamAppliance, comment, check_mode=False, force=False):
"""
Retrieve snapshots with given comment contained
"""
ret_obj = isamAppliance.create_return_object()
ret_obj_all = get(isamAppliance)
for obj in ret_obj_all['data']:
if comment in obj['comment']:
logger.deb... | 174c12af4eb26fc2cbeef263564f58c8638daf16 | 3,640,585 |
def getAsciiFileExtension(proxyType):
"""
The file extension used for ASCII (non-compiled) proxy source files
for the proxies of specified type.
"""
return '.proxy' if proxyType == 'Proxymeshes' else '.mhclo' | cb2b27956b3066d58c7b39efb511b6335b7f2ad6 | 3,640,586 |
def dist(s1, s2):
"""Given two strings, return the Hamming distance (int)"""
return abs(len(s1) - len(s2)) + sum(
map(lambda p: 0 if p[0] == p[1] else 1, zip(s1.lower(), s2.lower()))) | ef7b3bf24e24a2e49f0c7acfd7bcb8f23fa9af2e | 3,640,587 |
import pickle
def read_bunch(path):
""" read bunch.
:param path:
:return:
"""
file = open(path, 'rb')
bunch = pickle.load(file)
file.close()
return bunch | aec87c93e20e44ddeeda6a8dfaf37a61e837c714 | 3,640,588 |
def cluster_analysis(L, cluster_alg, args, kwds):
"""Given an input graph (G), and whether the graph
Laplacian is to be normalized (True) or not (False) runs spectral clustering
as implemented in scikit-learn (empirically found to be less effective)
Returns Partitions (list of sets of ints)
"""
... | 83114156a0b5517d31e2b2c2ffb7fc0837098db8 | 3,640,589 |
def col_index_list(info, key, value):
"""Given a list of dicts 'info', return a list of indices corresponding to
columns in which info[key] == value. Use to build lists of default columns,
non-exportable columns, etc."""
index_list = list()
if info != None:
for i in range(0, len(info)):
... | af46b03c2fe5bce2ceb7305fd670ce1f0f52ae38 | 3,640,590 |
def sparse_softmax_cross_entropy(logits, labels, weights=1.0, scope=None):
"""Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`.
`weights` acts as a coefficient for the loss. If a scalar is provided,
then the loss is simply scaled by the given value. If `weights` is a
tensor of size [`b... | dcae4206bdcb147d5bdd4611170f12ba4e371d70 | 3,640,591 |
import os, tempfile
import sys
def curl(url, headers={}, data=None, verbose=0):
"""Use curl to make a request; return the entire reply as a string."""
fd, tempname = tempfile.mkstemp(prefix='scrape')
command = 'curl --include --insecure --silent --max-redirs 0'
if data:
if not isinstance(data,... | 66d8e1d9291bc6d153eaac43961c940521417136 | 3,640,592 |
def retr_radihill(smax, masscomp, massstar):
"""
Return the Hill radius of a companion
Arguments
peri: orbital period
rsma: the sum of radii of the two bodies divided by the semi-major axis
cosi: cosine of the inclination
"""
radihill = smax * (masscomp / 3. / massstar)*... | 5010f66026db7e2544b85f70fd1449f732c024b4 | 3,640,593 |
def load_feature_file(in_feature):
"""Load the feature file into a pandas dataframe."""
f = pd.read_csv(feature_path + in_feature, index_col=0)
return f | 95bb40cc381dab3c29cf81c40d308104e9e4035b | 3,640,594 |
def add_observation_noise(obs, noises, stds, only_object_noise=False):
"""Add noise to observations
`noises`: Standard normal noise of same shape as `obs`
`stds`: Standard deviation per dimension of `obs` to scale noise with
"""
assert obs.shape == noises.shape
idxs_object_pos = SENSOR_INFO_PNP... | 926de82261b6cbd702e3f19f201f82c1a94ca72b | 3,640,595 |
import json
def test_domains(file_path="../../domains.json"):
"""
Reads a list of domains and see if they respond
"""
# Read file
with open(file_path, 'r') as domain_file:
domains_json = domain_file.read()
# Parse file
domains = json.loads(domains_json)
results = {}
for... | 69c6792ee86e90dfdf08a866d2d8e04022dde8c7 | 3,640,596 |
from typing import Dict
from typing import Any
def mix_dirichlet_noise(distribution: Dict[Any, float],
epsilon: float,
alpha: float) -> Dict[Any, float]:
"""Combine values in dictionary with Dirichlet noise. Samples
dirichlet_noise according to dirichlet_alpha i... | f779566b27107f86a92952470c949c69edb623be | 3,640,597 |
def get_video_ID(video_url: str) -> str:
"""Returns the video ID of a youtube video from a URL"""
try:
return parse_qs(urlparse(video_url).query)['v'][0]
except KeyError:
# The 'v' key isn't there, this could be a youtu.be link
return video_url.split("/")[3][:11] | c185a6c5a2c8a5bb4e2d6efd57f325023b030cda | 3,640,598 |
def profiling_csv(stage, phases, durations):
"""
Dumps the profiling information into a CSV format.
For example, with
stage: `x`
phases: ['a', 'b', 'c']
durations: [1.42, 2.0, 3.4445]
The output will be:
```
x,a,1.42
x,b,2.0
x,c,3.444
```
"""
as... | d40ee5601aa201904741870ce75c4b5bfde0f9bc | 3,640,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.