content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pass_api_client(function):
"""Create API client form API key and pass it to subcommand.
:param function: Subcommand that returns a result from the API.
:type function: callable
:returns: Wrapped function that prints subcommand results
:rtype: callable
"""
@functools.wraps(function)
... | 5,347,300 |
async def radius(ctx, system: str, radius: float, minRadius = 0.0):
"""Returns systems within a radius around a system"""
await bot.send_typing(ctx.message.channel)
coords = elite.friendly_get_coords(system)
systems = elite.get_systems_in_radius(coords, radius, minRadius)
if systems:
msg = '... | 5,347,301 |
def add_blocks(sender, **kwargs):
"""add extra blocks on save (dummy rendering happens too since CMSBaseModel
extends _CMSAbstractBaseModel). """
if isinstance(kwargs['instance'], CMSBaseModel):
ctype = ContentType.objects.get_for_model(kwargs['instance'])
for label_tuple in kwargs['inst... | 5,347,302 |
def _test(blocksize=256):
"""Tests one configuration of blocksize."""
print("Testing blocksize %d ... " % blocksize, end="")
padder = Padder(blocksize)
for size in (0, 1, blocksize - 2, blocksize - 1, blocksize):
data = b"a" * max(0, size - 1) + (b"b" if size else b"")
assert len(data) =... | 5,347,303 |
def reset_log_level_global_var():
"""Reset log level global var, in order to update the value from settings"""
# pylint: disable=global-statement
global __LOG_LEVEL__
__LOG_LEVEL__ = None | 5,347,304 |
def vecs_Xg_ig(x):
""" Vi = vec(dg/dxi * inv(g)), where g = exp(x)
(== [Ad(exp(x))] * vecs_ig_Xg(x))
"""
t = x.view(-1, 3).norm(p=2, dim=1).view(-1, 1, 1)
X = mat(x)
S = X.bmm(X)
#B = x.view(-1,3,1).bmm(x.view(-1,1,3)) # B = x*x'
I = torch.eye(3).to(X)
#V = sinc1(t)*eye(3) + si... | 5,347,305 |
def wide_factorial(x):
"""factorial returns x! = x * x-1 * x-2 * ...,
Args:
x: bytes to evaluate as an integer
Returns:
bytes representing the integer that is the result of the factorial applied on the argument passed
"""
return If(
BitLen(x) == Int(1), x, BytesMul(x, wide... | 5,347,306 |
def test_absent_rm_alias_failed():
"""
test alias.absent remove alias failure
"""
name = "saltdude"
ret = {
"comment": "Failed to remove alias {}".format(name),
"changes": {},
"name": name,
"result": False,
}
get_target = MagicMock(return_value=True)
rm_a... | 5,347,307 |
def spring_outpath(filepath: pathlib.Path) -> pathlib.Path:
"""Build a spring path based on a fastq file path"""
LOG.info("Create spring path from %s", filepath)
file_name = filepath.name
file_parent = filepath.parent
splitted = file_name.split("_")
spring_base = pathlib.Path("_".join(splitted[... | 5,347,308 |
def convert_gensim_to_word2vec_format(fileName):
"""Converts gensim exportation format to word2vec format"""
model = gensim.models.KeyedVectors.load(fileName)
word_vectors = model.wv
word_vectors.save_word2vec_format(fileName) | 5,347,309 |
def attach_tfidf_weights(storage, vocab, tf_arr):
"""Appends tf-idf weights to each word """
wordlist = vocab
storage_weighted = []
for i in range(len(storage)):
sys.stdout.write(str(i)+",")
sys.stdout.flush()
docweights = []
stor_list = storage[i].split()
for word in stor_list:
words = [word,0]
for... | 5,347,310 |
def env(config, endpoint):
"""Print RENKU environment variables.
Run this command to configure your Renku client:
$ eval "$(renku env)"
"""
access_token = config['endpoints'][endpoint]['token']['access_token']
click.echo('export {0}={1}'.format('RENKU_ENDPOINT', endpoint))
click.echo(... | 5,347,311 |
def expanded_bb( final_points):
"""computation of coordinates and distance"""
left, right = final_points
left_x, left_y = left
right_x, right_y = right
base_center_x = (left_x+right_x)/2
base_center_y = (left_y+right_y)/2
dist_base = abs(complex(left_x, left_y)-complex(right_x, right_y ) )
... | 5,347,312 |
def gen_file_get_url(token, filename):
"""
Generate httpserver file url.
Format: http://<domain:port>/files/<token>/<filename>
"""
return '%s/files/%s/%s' % (get_httpserver_root(), token, urlquote(filename)) | 5,347,313 |
def count_items():
"""
Get number of items in the DB
Per the AWS documentation:
DynamoDB updates this value approximately every six hours. Recent changes might not be reflected in this value.
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/dynamodb.html#DynamoDB.Client.de... | 5,347,314 |
def extract_uris(data):
"""Convert a text/uri-list to a python list of (still escaped) URIs"""
lines = data.split('\r\n')
out = []
for l in lines:
if l == chr(0):
continue # (gmc adds a '\0' line)
if l and l[0] != '#':
out.append(l)
return out | 5,347,315 |
def _load_fonts():
"""Load the fonts.
This will add the OpenSans fonts to the QFontDatabase.
Returns:
list: The registered font ids.
"""
font_root = os.path.join(os.path.dirname(__file__), "fonts")
fonts = [
"opensans/OpenSans-Bold.ttf",
"opensans/OpenSans-BoldItalic.... | 5,347,316 |
def handle_form_submission(ack, body, client, view):
"""
Handles what happens when the track submission form gets submitted
"""
# Perform validiation on the times before ack'ing
form_state = view['state']['values']
time_regex = '^([01]?[0-9]|2[0-3]):([0-5][0-9])$'
arrival = re.match(time_reg... | 5,347,317 |
def createConnection(ps, graph, e, q, maxIter):
"""
Try to build a path along a transition from a given configuration
"""
for i in range(maxIter):
q_rand = shootConfig(ps.robot, q, i)
res, q1, err = graph.generateTargetConfig(e, q, q_rand)
if not res:
continue
... | 5,347,318 |
def delete_division_item(ids, my_divname):
"""
Given division id, delete from db
Return deleted division entry.
"""
settings = utils.load_json_definition_file(SETTINGS_FILE)
success, dubconn = utils.open_monitoring_db(settings['dbhost'],
settings['... | 5,347,319 |
def extract_info(filepath,pdbid,info_id_list):
"""Returns a dictionary where the key is pocket ID (starting at zero) and the value is a dictionary of information points."""
pockets_info = {}
pocket_file = open(filepath+pdbid+'_out/'+pdbid+'_info.txt')
pocket_lines = pocket_file.readlines()
pocket_fi... | 5,347,320 |
def eval_shape_fcn(w, x, N1, N2, yte):
"""
compute class and shape function
:param w:
:param x:
:param N1:
:param N2:
:param yte: trailing edge y coordinate
:return:
"""
C = x**N1 * (1-x)**N2
n = len(w) - 1 # degree of Bernstein polynomials
S = np.zeros_like(x)
for... | 5,347,321 |
def _pickle_path(file_name):
"""Returns an absolute path to the specified pickle file."""
return project_root_path('pickles', file_name) | 5,347,322 |
def streamentry(parser, token):
"""
streamentry <entry_var>
"""
bits = token.split_contents()
bits.reverse()
tag_name = bits.pop()
try:
entry_var = bits.pop()
except IndexError:
raise template.TemplateSyntaxError, "%r is missing entry argument" % tag_name
... | 5,347,323 |
def mult_int_list_int():
"""
>>> mult_int_list_int()
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
"""
return 3 * [1, 2] * 2 | 5,347,324 |
def test_pseudonymize__integer__2():
"""It pseudonymizes the value `0`."""
from gocept.pseudonymize import integer
assert 8 == pseudo(0, integer) | 5,347,325 |
def _gcd_tf(a, b, dtype=tf.int64):
"""Calculates the greatest common denominator of 2 numbers.
Assumes that a and b are tf.Tensor of shape () and performs the extended
euclidean algorithm to find the gcd and the coefficients of Bézout's
identity (https://en.wikipedia.org/wiki/B%C3%A9zout%27s_identity)
Args:... | 5,347,326 |
def compute_running_mean(x, kernel_size):
""" Fast analogue of scipy.signal.convolve2d with gaussian filter. """
k = kernel_size // 2
padded_x = np.pad(x, (k, k), mode='symmetric')
cumsum = np.cumsum(padded_x, axis=1)
cumsum = np.cumsum(cumsum, axis=0)
return _compute_running_mean_jit(x, kernel_... | 5,347,327 |
def update_daily_traffic(traffic_data: list[list[int]]):
"""
Expected format for each traffic_data list item should match "day" value of the /about/traffic endpoint:
[timestamp (start of day), unique_pageviews, total_pageviews, subscribers]
"""
oldest_date = datetime.date.fromtimestamp(traffic_... | 5,347,328 |
def _historicDataUrll(symbol, sDate=(1990,1,1),eDate=date.today().timetuple()[0:3]):
"""
generate url
symbol: Yahoo finanance symbol
sDate: start date (y,m,d)
eDate: end date (y,m,d)
"""
urlStr = 'http://ichart.finance.yahoo.com/table.csv?s={0}&a={1}&b={2}&c={3}&d={4}&e={5}&f={6}... | 5,347,329 |
def _list_manager_owned_bidding_strategies(client, manager_customer_id):
"""List all cross-account bidding strategies in the manager account.
Args:
client: An initialized GoogleAdsClient instance.
manager_customer_id: A manager customer ID.
"""
googleads_service = client.get_service("Go... | 5,347,330 |
def _check_param_testcase_report(testcase_report, i):
"""
Check the testcase report generated for the ith parametrization of the
"parametrized" testcase from the "Suite" testsuite.
"""
assert testcase_report.passed
assert testcase_report.name == "parametrized__val_{}".format(i + 1)
assert te... | 5,347,331 |
def to_dict(eds, properties=True, lnk=True):
"""
Encode the EDS as a dictionary suitable for JSON serialization.
"""
nodes = {}
for node in eds.nodes:
nd = {
'label': node.predicate,
'edges': node.edges
}
if lnk and node.lnk is not None:
nd... | 5,347,332 |
def find_lineage(tax_id: int) -> Lineage:
"""Finds lineage for a single tax id"""
if tax_id % 50000 == 0:
_LOGGER.info("working on tax_id: %d", tax_id)
lineage = []
while True:
record = TAXONOMY_DICT[tax_id]
lineage.append((record["tax_id"], record["rank"], record["rank_name"]))... | 5,347,333 |
def modify(request):
"""
[メソッド概要]
グループのDB更新処理
"""
logger.logic_log('LOSI00001', 'None', request=request)
msg = ''
error_msg = {}
now = datetime.datetime.now(pytz.timezone('UTC'))
try:
with transaction.atomic():
json_str = json.loads(request.POST.get('json_str'... | 5,347,334 |
def _function_args_doc(functions):
"""
Create documentation of a list of functions.
Return: usage dict (usage[funcname] = list of arguments, incl.
default values), doc dict (doc[funcname] = docstring (or None)).
Called by function_UI.
"""
import inspect
usage = {}
doc = {}
... | 5,347,335 |
def get_loss(pred, label):
""" pred: B*NUM_CLASSES,
label: B, """
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=pred, labels=label)
classify_loss = tf.reduce_mean(loss)
tf.summary.scalar('classify loss', classify_loss)
tf.add_to_collection('losses', classify_loss) | 5,347,336 |
def mock_modules_list():
"""Standard module list without any issues"""
return [
{"name": "foo", "module_type": "app", "supported_platforms": ["macos"]},
{"name": "bar", "module_type": "app"},
] | 5,347,337 |
def https(remainder, params):
"""Ensure that the decorated method is always called with https."""
if request.scheme.lower() == 'https': return
if request.method.upper() == 'GET':
redirect('https' + request.url[len(request.scheme):])
raise HTTPMethodNotAllowed(headers=dict(Allow='GET')) | 5,347,338 |
def cal_iou(box1, box1_area, boxes2, boxes2_area):
"""
box1 [x1,y1,x2,y2]
boxes2 [Msample,x1,y1,x2,y2]
"""
x1 = np.maximum(box1[0], boxes2[:, 0])
x2 = np.minimum(box1[2], boxes2[:, 2])
y1 = np.maximum(box1[1], boxes2[:, 1])
y2 = np.minimum(box1[3], boxes2[:, 3])
intersection = np.ma... | 5,347,339 |
def hbonds_single_c(snap, id1, id2, cut1, cut2, angle, names=False):
"""
Binding of C++ routines in :mod:`.hbonds_c` for couting of hydrogen bonds in a single snapshot.
Args:
snap (:class:`.Snap`): single snapshot containing the atomic information
id1 (str): identifier for oxygen atoms (e.g... | 5,347,340 |
def _find_event_times(raw, event_id, mask):
"""Given the event_id and mask, find the event times.
"""
stim_ch = find_stim_channel(raw)
sfreq = raw.info['sfreq']
events = find_events(raw, stim_ch, mask, event_id)
times = [(event[0] - raw.first_samp) / sfreq for event in events]
return times | 5,347,341 |
def get_parameters():
"""Load parameter values from AWS Systems Manager (SSM) Parameter Store"""
parameters = {
"kafka_servers": ssm_client.get_parameter(
Name="/kafka_spark_demo/kafka_servers")["Parameter"]["Value"],
"kafka_demo_bucket": ssm_client.get_parameter(
Name="... | 5,347,342 |
async def get_accounts(context, names, observer=None):
"""Find and return lite accounts by `names`.
Observer: will include `followed` context.
"""
assert isinstance(names, list), 'names must be a list'
assert names, 'names cannot be blank'
assert len(names) < 100, 'too many accounts requested'
... | 5,347,343 |
def _worker(vecs, k, modelpath, curid, retval):
"""Worker to search for nearest embeddings.
"""
cur = current_process()
print('\n{} loading knn'.format(cur.name))
knn = joblib.load(modelpath)
print('\n{} searching...'.format(cur.name))
res = knn.kneighbors(vecs, n_neighbors=k, return_distanc... | 5,347,344 |
def softmax_crossentropy_logits(p, q):
"""see sparse cross entropy"""
return -(p * log_softmax(q)).sum(-1) | 5,347,345 |
def SieveOfEratosthenes(limit=10**6):
"""Returns all primes not greater than limit."""
isPrime = [True]*(limit+1)
isPrime[0] = isPrime[1] = False
primes = []
for i in range(2, limit+1):
if not isPrime[i]:continue
primes += [i]
for j in range(i*i, limit+1, i):
isPr... | 5,347,346 |
def update_submission_template(default_template, qtemplate):
"""
helper function for writing a CommonAdapter template fireworks
submission file based on a provided default_template which
contains hpc resource allocation information and the qtemplate
which is a yaml of commonly modified user argument... | 5,347,347 |
def GetHistory():
"""Obtain mapping from release version to docs/root/intro/deprecated.rst PRs.
Returns:
A dictionary mapping from release version to a set of git commit objects.
"""
repo = Repo(os.getcwd())
version = None
history = defaultdict(set)
for commit, lines in repo.blame('HEAD', 'docs/root/... | 5,347,348 |
def generate_chromosome(constraint = False, constraint_levers = [], constraint_values = [],
threshold = False, threshold_names = [], thresholds = []):
"""
Initialises a chromosome and returns its corresponding lever values, and temperature and cost.
**Args**:
- constraint (*b... | 5,347,349 |
def plot_cov(state_pred, cov_pred):
"""
Plot the covariances
:param state_pred: lit of all the previous positions
:param cov_pred: list of all the previous covariances
:return:
"""
state = []
cov = []
for i in range(len(state_pred)):
x = np.array([[state_pred[i][0]], [state... | 5,347,350 |
def save_data(df, database_filename):
"""save data to sql database"""
engine = create_engine('sqlite:///{}'.format(database_filename))
df.to_sql("MessagesCategories", engine, if_exists='replace', index=False) | 5,347,351 |
def make_link_request(data: dict, user_token: str):
"""
https://yandex.ru/dev/disk/api/reference/response-objects-docpage/#link
- it will not raise in case of error HTTP code.
- see `api/request.py` documentation for more.
:param data: Data of link to handle.
:param user_token: User OAuth toke... | 5,347,352 |
def load_sample_bathymetry(**kwargs):
"""
(Deprecated) Load a table of ship observations of bathymetry off Baja
California as a pandas.DataFrame.
.. warning:: Deprecated since v0.6.0. This function has been replaced with
``load_sample_data(name="bathymetry")`` and will be removed in
v0.9.... | 5,347,353 |
def add_bar_labels(ax, vertical=True, bar_label_fontsize=8):
"""Adds a value at the top of the bar showing the size of it"""
handles, labels = ax.get_legend_handles_labels()
# In order to support stacked bar charts by only add a value for the
# highest point (as stacked rectangles are counted individua... | 5,347,354 |
def main():
""" main """
parser = argparse.ArgumentParser(
description='This is a wrapper to test the resolver code')
parser.add_argument("-s",
"--servers",
default="8.8.8.8,1.1.1.1",
help="Resolvers to query")
parser.add_ar... | 5,347,355 |
def shift(obj, offset, excluded=(), op=operator.sub, verbose=False):
"""Shift soda.ir.Ref with the given offset.
All soda.ir.Ref, excluding the given names, will be shifted with the
given offset using the given operator. The operator will be applied pointwise
on the original index and the given offset.
Args... | 5,347,356 |
async def ticket_channel_embed(
_: hikari.InteractionCreateEvent, bot: hikari.GatewayBot
) -> hikari.Embed:
"""Provides an embed for individual ticket channels."""
description = (
"Thanks for submitting a ticket! We take all tickets "
"very seriously. Please provide a full explanation in thi... | 5,347,357 |
def count_branching_factor(strips_ops: List[STRIPSOperator],
segments: List[Segment]) -> int:
"""Returns the total branching factor for all states in the segments."""
total_branching_factor = 0
for segment in segments:
atoms = segment.init_atoms
objects = set(segme... | 5,347,358 |
def iou_overlaps(b1, b2):
"""
Arguments:
b1: dts, [n, >=4] (x1, y1, x2, y2, ...)
b1: gts, [n, >=4] (x1, y1, x2, y2, ...)
Returns:
intersection-over-union pair-wise, generalized iou.
"""
area1 = (b1[:, 2] - b1[:, 0] + 1) * (b1[:, 3] - b1[:, 1] ... | 5,347,359 |
def aggregate(data):
"""Aggregate the data."""
return NotImplemented | 5,347,360 |
def get_valid_columns(solution):
"""Get a list of column indices for which the column has more than one class.
This is necessary when computing BAC or AUC which involves true positive and
true negative in the denominator. When some class is missing, these scores
don't make sense (or you have to add an e... | 5,347,361 |
def fourier_transform(data, proc_parameters):
"""Perform Fourier Transform down dim dimension given in proc_parameters
.. Note::
Assumes dt = t[1] - t[0]
Args:
data (nddata): Data container
proc_parameters (dict, procParam): Processing parameters
Returns:
nddata: Fouri... | 5,347,362 |
def iupac_fasta_converter(header, sequence):
"""
Given a sequence (header and sequence itself) containing iupac characters,
return a dictionary with all possible sequences converted to ATCG.
"""
iupac_dict = {"R": "AG", "Y": "CT", "S": "GC", "W": "AT", "K": "GT",
"M": "AC", "B": "C... | 5,347,363 |
def test_deserialzing_an_invalid_bootcamp(bootcamp_valid_data):
"""
Verifies that parse_bootcamp_json_data does not create a new Course if the serializer is invalid
"""
bootcamp_valid_data.pop("course_id")
parse_bootcamp_json_data(bootcamp_valid_data)
assert Course.objects.count() == 0
asser... | 5,347,364 |
def reverse(arr, start, end):
"""Reverse an array arr between indices start and end (exclusive)."""
while start < end:
arr[start], arr[end - 1] = arr[end - 1], arr[start]
start += 1
end -= 1 | 5,347,365 |
def integer_list_to_named_tuple(list_of_integers):
"""
Converts a list of integers read from the ultrak498 into a named tuple
based upon the type. The type is determiend by the first integer in the
list. Since all tuples contain five fields, the list of integers must
have a length of five.
Re... | 5,347,366 |
def get_albums(): # noqa: E501
"""get_albums
Muestra todos los albums disponibles # noqa: E501
:rtype: List[Album]
"""
albums = DBAlbum.query.all()
results = [
Album(album.id, album.title, album.description) for album in albums]
return results | 5,347,367 |
def get_final_shape(data_array, out_dims, direction_to_names):
"""
Determine the final shape that data_array must be reshaped to in order to
have one axis for each of the out_dims (for instance, combining all
axes collected by the '*' direction).
"""
final_shape = []
for direction in out_dim... | 5,347,368 |
def create_assignment_payload(subsection_block):
"""
Create a Canvas assignment dict matching a subsection block on edX
Args:
subsection_block (openedx.core.djangoapps.content.block_structure.block_structure.BlockData):
The block data for the graded assignment/exam (in the structure of ... | 5,347,369 |
def return_random_initial_muscle_lengths_and_activations(InitialTension,X_o,**kwargs):
"""
This function returns initial muscle lengths and muscle activations for a given pretensioning level, as derived from (***insert file_name here for scratchwork***) for the system that starts from rest. (Ex. pendulum_eqns.refe... | 5,347,370 |
def update_box(form_data):
"""
Updates a box in the database.
Takes in form_data as the data being updated.
"""
update_query = "UPDATE boxes SET shelf_number = ? WHERE box_number = ?"
c.execute(update_query, form_data)
conn.commit() | 5,347,371 |
def test_input(test_page):
"""When an input is filled with the text 'Winamp'
Then the text in the input should be 'Winamp'
"""
test_page.navigate()
test_page.input_area.input.fill('Winamp')
assert 'Winamp' == test_page.input_area.input.element.value | 5,347,372 |
def add_top_features(df, vocab, n=10):
"""
INPUT: PySpark DataFrame, List, Int
RETURN: PySpark DataFrame
Take in DataFrame with TFIDF vectors, list of vocabulary words,
and number of features to extract. Map top features from TFIDF
vectors to vocabulary terms. Return new DataFrame with terms
... | 5,347,373 |
def java_solvability(level: MarioLevel, time_per_episode=20, verbose=False, return_trajectories=False) -> Union[bool, Tuple[bool, List[Tuple[float, float]]]]:
"""Returns a boolean indicating if this level is solvable.
Args:
level (MarioLevel): The level
time_per_episode (int, optional): How man... | 5,347,374 |
def set_values(imask, k, val):
""" Set all k values to val"""
Mp, Lp = imask.shape
for j in range(1,Mp-1):
for i in range(1,Lp-1):
if (imask[j,i] == k): imask[j,i] = val | 5,347,375 |
def get_trait_value(traitspec, value_name, default=None):
""" Return the attribute `value_name` from traitspec if it is defined.
If not will return the value of `default`.
Parameters
----------
traitspec: TraitedSpec
value_name: str
Name of the `traitspect` attribute.
default: any
... | 5,347,376 |
def remove_dict_keys(obj, remove_keys=[], empty_keys=False, recursive=False):
""" Modify a dictionary by removing items with matching and/or empty keys
Parameters
----------
obj: dict
Dictionary to modify by removing keys
remove_keys: list of str
Keys to remove
empty_keys: boo... | 5,347,377 |
def check_if_blank(cell_image: Image) -> bool:
"""Check if image is blank
Sample the color of the black and white content - if it is white enough
assume no text and skip. Function takes a small more centered section to
OCR to avoid edge lines.
:param cell_image: Image to OCR
:return: True or N... | 5,347,378 |
def get_tpr_from_threshold(scores,labels, threshold_list):
"""Calculate the recall score list from the threshold score list.
Args:
score_target: list of (score,label)
threshold_list: list, the threshold list
Returns:
recall_list: list, the element is recall score calculated by the
... | 5,347,379 |
def combined_w2v_labeling(apply_sub_clustering=False):
"""Combine words with w2v for labeling"""
reviews = get_reviews()
count_vectorizer = CountVectorizer(stop_words=STOPWORDS, tokenizer=valid_words_tokenizer)
count_vectorizer.fit(reviews)
features = count_vectorizer.get_feature_names()
# Get ... | 5,347,380 |
def updating_node_validation_error(address=False, port=False, id=False,
weight=False):
"""
Verified 2015-06-16:
- when trying to update a CLB node's address/port/id, which are
immutable.
- when trying to update a CLB node's weight to be < 1 or > 100
At leas... | 5,347,381 |
def gaussianDerivative(x):
"""This function returns the gaussian derivative of x
(Note: Not Real Derivative)
"""
return -2.0*x*(np.sqrt(-np.log(x))) | 5,347,382 |
def show_table(file: IO, spec: Dict):
"""Display the contents of a CSV file as a pandas DataFrame.
Parameters
----------
file: io.BytesIO
IO buffer containing the file content.
spec: dict
File output format specification.
"""
format = spec.get('format', {})
if not format... | 5,347,383 |
def parse_numbers(numbers):
"""Return list of numbers."""
return [int(number) for number in numbers] | 5,347,384 |
def add_server():
"""
Adds a server to database if not exists
"""
data = json.loads(request.data)
ip_addr = IPModel.get_or_create(address=data["ip_addr"])[0]
ServerModel.create(ip=ip_addr, port=data["port"])
return 'OK' | 5,347,385 |
def _fetch_files(data_dir, files, resume=True, verbose=1):
"""Load requested dataset, downloading it if needed or requested.
This function retrieves files from the hard drive or download them from
the given urls. Note to developpers: All the files will be first
downloaded in a sandbox and, if everything... | 5,347,386 |
def parse_cmdline(argv):
"""
Returns the parsed argument list and return code.
`argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
"""
if argv is None:
argv = sys.argv[1:]
# initialize the parser object:
parser = argparse.ArgumentParser(description='Checks for normal term... | 5,347,387 |
def get_continuum_extrapolation( # pylint: disable=C0103
df: pd.DataFrame,
n_poly_max: int = 4,
delta_x: float = 1.25e-13,
include_statistics: bool = True,
odd_poly: bool = False,
) -> pd.DataFrame:
"""Takes a data frame read in by read tables and runs a continuum extrapolation
for the spec... | 5,347,388 |
def _setup_animation(
animation, time_codes, joints, joints_transforms, topology, joint_count
):
"""Write joint animation to USD and bind the animation to a skeleton.
Reference:
https://graphics.pixar.com/usd/docs/api/_usd_skel__a_p_i__intro.html#UsdSkel_API_WritingSkels
Args:
animatio... | 5,347,389 |
def test_writing_core_attributes_of_faces_mesh():
"""Tests writing to the vectors, vertices and faces attributes of a vectors
mesh.
- `vectors` should be writeable, resizable, allow changes of dtypes but
always silently enforce C contiguous arrays.
- `vertices` should not be writeable.
- `fa... | 5,347,390 |
def setup():
"""
This will be called at the beggining, you set your stuff here
"""
ofSetBackgroundAuto(False)
global color, circles
color = ofColor(content['color1'].r,content['color1'].g,content['color1'].b)
for i in range(0, 20):
circle = Circle()
circle.setSpeed(content... | 5,347,391 |
def listvalues(d):
"""Return `d` value list"""
return list(itervalues(d)) | 5,347,392 |
def build_image(repo_url: str, tag: str, path: str) -> None:
"""
build_image builds the image with the given tag
"""
client = docker.from_env()
print(f"Building image: {tag}")
client.images.build(tag=tag, path=path)
print("Successfully built image!") | 5,347,393 |
def _non_blank_line_count(string):
"""
Parameters
----------
string : str or unicode
String (potentially multi-line) to search in.
Returns
-------
int
Number of non-blank lines in string.
"""
non_blank_counter = 0
for line in string.splitlines():
if li... | 5,347,394 |
def load(map_name, batch_size):
"""Load CaraEnvironment
Args:
map_name (str): name of the map. Currently available maps are:
'Town01, Town02', 'Town03', 'Town04', 'Town05', 'Town06', 'Town07',
and 'Town10HD'
batch_size (int): the number of vehicles in the simulation.
... | 5,347,395 |
def _save_seasons_emotions_to_file(seasons_episodes_subtitles_emotions: Dict[int, Dict[
int, List[TimeEmotion]]], output_file_path: str) -> None:
"""
Save dictionary seasons_episodes_subtitles_emotions to file
"""
with open(output_file_path, 'w') as output_file:
json.dump(_season_episode_emo... | 5,347,396 |
def decrypt_password(encrypted_password: str) -> str:
""" b64 decoding
:param encrypted_password: encrypted password with b64
:return: password in plain text
"""
return b64decode(encrypted_password).decode("UTF-8") | 5,347,397 |
def AppendRecentJetFile(jetFile):
""" Appends to a list of recent jet files """
addedFiles = []
fileList = GetRecentJetFiles()
config = ConfigParser.ConfigParser()
config.read(JetDefs.JETCREATOR_INI)
if config.has_section(JetDefs.RECENT_SECTION):
config.remove_section(JetDefs.RECE... | 5,347,398 |
def model_keplerian(positions, velocities, v_lsr=None, fit_method=None,
flag_singularity=True, flag_radius=None, flag_intervals=None,
return_stddevs=True, plot=False, debug=False):
"""Fit a Keplerian velocity profile to position-velocity-data.
Args:
positions (n... | 5,347,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.