content stringlengths 39 14.9k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def get_char_codes(text):
"""Change text to list of character codes of the characters."""
return [ord(letter) for letter in text] | 7dda64e752b92503e83ab4e4d7fa77749235cc2a | 678,164 |
import gzip
import bz2
def open_file(file_name, flags='r'):
"""Opens a regular or compressed file (decides on the name)
:param file_name a name of the file, it has a '.gz' or
'.bz2' extension, we open a compressed stream.
:param flags open flags such as 'r' or 'w'
"""
if fi... | cf20f393cf12bc2a7d446dae2afd72a24272b463 | 678,166 |
def _average_gradients_across_replicas(replica_context, gradients):
"""Computes the average gradient across replicas.
This computes the gradient locally on this device, then copies over the
gradients computed on the other replicas, and takes the average across
replicas.
This is faster than copying the gradi... | b9fed78a7efdb3452477b30a485b5147db15de0c | 678,167 |
def all_data(request, data, data_missing):
"""Parametrized fixture giving 'data' and 'data_missing'"""
if request.param == 'data':
return data
elif request.param == 'data_missing':
return data_missing | b915255d6b7a3585a5ccee057b37a80fea6dfcf0 | 678,168 |
import torch
def make_prediction(neural_net, save_path, images, classes, p = True):
"""
function to make prediction
--------------------------
parameters:
neural_net: a torch neural network
save_path: path to load neural network from
images: images to predict class of
classes: the pos... | 90ae9ea05bd20d26f75ba571458174f77aea7624 | 678,170 |
def _extract_month_from_filename(fname):
"""Extract month number from precipitation file name"""
return str(fname[7:].split('.tif')[0]) | b01b5c6e537bc0de431bc854ae878ccfe62e71d8 | 678,171 |
def format_pkg_data(master_package_data: list):
""" Format and parse the reponse from pypi.org so we can build a dictionary of needed data for
each package. Example response string (pkg_data variable below) looks like this:
b' <a href="https://files.pythonhosted.org/packages/9f/a5/eec74d8d1016e6c2042ba31... | 6b69c03392f5fbb22d26ada635cc303ec64f8626 | 678,172 |
def bytes_to_text(byte_array, encoding='UTF-8'):
"""
Decode a byte array to a string following the given encoding.
:param byte_array: Byte array to decode.
:param encoding: String encoding (default UTF-8)
:return: a decoded string
"""
return bytes(byte_array).decode(encoding) | e3a65f2f0f3e7833dba6a476b1516db148e51136 | 678,173 |
import logging
def has_file_handlers(logger):
"""To check if a log file has a file handler
Parameters:
* logger (object): Logger file object
Returns:
* bool: True if logger is a file handler logger
"""
for handler in logger.handlers:
if isinstance( handler, logging.FileHandler ):
retu... | c99e141d98fbc210bb4f52e0c9583dee79009370 | 678,174 |
def get_gse_gsm_info(line):
"""
Extract GSE and GSM info
Args:
line: the entry to process
Returns:
the GSE GSM info tuple
"""
parts = line.strip().split(",")
if parts[0] == "gse_id":
return None
return parts[0], parts[1:] | f03eb86316382fba0d5f55bd09e7fc15f84c0078 | 678,178 |
def filter_title_transcriptions(df):
"""Filter the title transcriptions."""
df = df[df['motivation'] == 'describing']
df = df[df['tag'] == 'title']
return df | bf31ac36d204cd4c8e645e5f878fbf551e3c8b8c | 678,179 |
def draw_batches(data, batch_size=128):
""" Create a list of batches for the given data.
Args:
data: the dataframe returned by load_data
batch_size: number of samples to include in each batch
Returns:
a list of batches. Each batch is a part of the data dataframe with
batch_... | 5eeca78dcac797b62f4498281d306648523ebb57 | 678,184 |
import glob
def count_traj_files(path, extension):
"""
path : string
Path of directory containing trajectory files.
extension : string
File extension type for trajectory files.
EX) 'dcd', 'xtc', ...
"""
return len(glob.glob1(path,"*."+extension)) | f3609858a68311b8294d7be59ee5c159eb2a53f6 | 678,185 |
import random
import string
def create_temporary_cache_directory_name() -> str:
"""Create a temporary cache directory name."""
temp_directory_name = ''.join([random.choice(string.ascii_letters) for i in range(10)])
return ".tmp-" + temp_directory_name | f88196e367ba4611cf1176fad584fb7edb779a62 | 678,190 |
def get_dict_value(dict_var, key, default_value=None, add_if_not_in_map=True):
"""
This is like dict.get function except it checks that the dict_var is a dict
in addition to dict.get.
@param dict_var: the variable that is either a dict or something else
@param key: key to look up in dict
@param ... | f54b8e52d8330b673f506426e0c6d8430a3f97f5 | 678,195 |
def cleanly(text: str):
"""
Splits the text into words at spaces, removing excess spaces.
"""
segmented = text.split(' ')
clean = [s for s in segmented if not s == '']
return clean | 4425bb9ee3414e669d5cb0a925f09bc29fadcd49 | 678,197 |
def freestyle_table_params(rows, aging):
"""Returns parameters for OpenSQL freestyle request"""
return {'rowNumber': str(rows), 'dataAging': str(aging).lower()} | f764202958acc29b4d21d481406ee029eedb28f6 | 678,199 |
def manhattan(point1, point2):
"""Computes distance between 2D points using manhattan metric
:param point1: 1st point
:type point1: list
:param point2: 2nd point
:type point2: list
:returns: Distance between point1 and point2
:rtype: float
"""
return abs(point1[0] - point2[0]) + ab... | ed1d0b6ba47e107f2540b634d338de91d7048cec | 678,201 |
def strip_if_scripts(if_outscript, if_inscript):
"""
Given an OutScriptIf and an InScriptIf satisfying it, return the "active" parts
of them. I.e., if if_inscript.condition_value=True, return the "true" branch, else
the "false" branch.
:return: a 2-tuple of (OutScript, InScript)
"""
# extra... | 5bcb9832761ee7eee4b703923c847e303e4c3547 | 678,203 |
def getadminname(s,admindf):
"""Convert adminname from id_num to actual str name
"""
extractednamelist=admindf[admindf.id==s].name.values
if extractednamelist:
adminname=extractednamelist[0]
else:
adminname=None
return adminname | e3a2b1ed96d877fee91ac37438f7cf31087565c2 | 678,207 |
def lap_time_to_seconds(time_str):
"""Returns the lap time string as a float representing total seconds.
E.g. '1:30.202' -> 90.202
"""
min, secs = time_str.split(':')
total = int(min) * 60 + float(secs)
return total | 8a0e6332aaf181c702d6608921a986223d5ec1b7 | 678,215 |
def process_instance(el):
"""
Process each 'process instance' element from the .mxml file
and returns as dict
"""
resp = []
for entry in el[1:]:
r = {
"TraceId": el.get("id")
}
for item in entry:
if item.tag == 'Data':
r[ite... | 502e7072ecdb89beae39d779e68138f4299c9027 | 678,217 |
def Score(low, high, n):
"""Score whether the actual value falls in the range.
Hitting the posts counts as 0.5, -1 is invalid.
low: low end of range
high: high end of range
n: actual value
Returns: -1, 0, 0.5 or 1
"""
if n is None:
return -1
if low < n < high:
retu... | 31e669223c2573c2fc8c28bf8b91570582de97d3 | 678,219 |
def _matches_section_title(title, section_title):
"""Returns whether title is a match for a specific section_title.
Example:
_matches_section_title('Yields', 'yield') == True
Args:
title: The title to check for matching.
section_title: A specific known section title to check against.
"""
title =... | babe15b50ffbe46f7cc95469117a4b034e20ec0a | 678,222 |
def _find_private_network(oneandone_conn, private_network):
"""
Validates the private network exists by ID or name.
Return the private network ID.
"""
for _private_network in oneandone_conn.list_private_networks():
if private_network in (_private_network['name'],
... | f8a2835423a1738e518e7ee4ece1afc60df009ba | 678,224 |
def postprocess(output_val):
"""
This postprocess simply returns the input ``output_val``.
:param output_val: dictionary mapping output_data to output_layers
:return: ``output_val``
"""
return output_val | 5188abd27c2c37ca646a4641d0f19f22558fee70 | 678,225 |
def mm2m(millimeters):
"""millimeters -> meters"""
return millimeters/1000 | 4c31ed9df60b76ab0f7c8f0393c72f804da9aab1 | 678,226 |
import torch
def _gen_mask(valid_step: torch.Tensor, batch_size: int, seq_len: int):
"""
Mask for dealing with different lengths of MDPs
Example:
valid_step = [[1], [2], [3]], batch_size=3, seq_len = 4
mask = [
[0, 0, 0, 1],
[0, 0, 1, 1],
[0, 1, 1, 1],
]
"""
as... | a4ff58133dd576ea833b34180007f466a329dd72 | 678,228 |
import logging
def norm_range(voltage):
"""Check to see if the voltage values are within the acceptable normal range
The normal range for the voltage readings is +/- 300 mV. Within the
assignment, it was asked that if a voltage reading were found to be outside
of this range, then add a warning entry ... | 65a891c17421899612928cb8ec6c5f4f32db4f6b | 678,229 |
def is_test_directory_name(directory_name):
"""
Returns whether the given directory name is a name of a test directory.
Parameters
----------
directory_name : `str`
A directory's name.
Returns
-------
is_test_directory_name : `bool`
"""
if directory_name == 'tes... | f3de8256181176df743de2d04fb4987b8b4dc07d | 678,230 |
def waterGmKgDryToPpmvDry(q):
"""
Convert water vapor Grams H2o / Kg dry air to ppmv dry air.
"""
Mair = 28.9648
Mh2o = 18.01528
return (q*1e3*Mair)/Mh2o | eb5b11b02133295eef691e9c0c91fe13332e6df9 | 678,232 |
def read_file(path):
"""
Read file at `path`.
Return a list of lines
"""
lines = []
with open(path, 'r') as srcfile:
return srcfile.read().split('\n') | 4c011a3e2a45d8d46ac3592a4f72a82ee03075ec | 678,233 |
def _get_fields(attrs, field_class, pop=False):
"""
Get fields from a class.
:param attrs: Mapping of class attributes
:param type field_class: Base field class
:param bool pop: Remove matching fields
"""
fields = [
(field_name, field_value)
for field_name, field_value in at... | 65219d144954232161345b26bf085b2e4f2f2dce | 678,238 |
from typing import List
def recall_score(relevant: List, recovered: List) -> float:
"""Recall score is: which of the total relevant documents where recovered"""
# Recovered relevant
rr = [d for d in recovered if d in relevant]
return len(rr) / len(relevant) | 8db00c547e7a4d1c8b4e43f663a7a37f11850e35 | 678,239 |
from typing import Dict
from typing import List
def get_retrohunt_rules(r: Dict) -> List[str]:
"""Extracts rules used within a retrohunt."""
rules = []
for line in r.get("attributes", {}).get("rules", "").splitlines():
line = line.strip()
if "rule" in line[:4]:
line = line.spli... | 78f122542d3a925efb018cb2787a7000d3914c81 | 678,240 |
import click
def require_region(ctx, param, value):
"""
Require region to be set in parameter or in context
:param ctx: Context
:param param: Click Parameter
:param value: Parameter value
:return: Parameter value
"""
if not value and not ctx.obj.config.region:
raise click.BadPa... | 4c48ba51a3a683d831b3d4425566967e9e828253 | 678,245 |
def torr_to_pascal(torr):
"""Convert Torr to Pascal."""
return torr * 101325.0 / 760.0 | 8050507ee06f5703af15385506b7cc6285053ac9 | 678,246 |
def get_item(d, k):
"""attempts to get an item from d
at key k. if d is a list and the key is the list selector [],
then tries to return the first item from the list.
if the list is empty, returns None."""
try:
return d[k]
except KeyError:
if k.endswith('[]'):
lst = d... | e301c56a3e4cc8526a0f526b79f7b53c8749b34c | 678,247 |
import random
def return_random_from_word(word):
"""
This function receives a TextMobject,
obtains its length:
len(TextMobject("Some text"))
and returns a random list, example:
INPUT: word = TextMobjecT("Hello")
length = len(word) # 4
rango = list(range(length)) # [0,1,2,3]
... | 34e0ddd5978fa5a0f35d333856f4b89cdee4e118 | 678,249 |
def transition_model(corpus, page, damping_factor):
"""
Return a probability distribution over which page to visit next,
given a current page.
With probability `damping_factor`, choose a link at random
linked to by `page`. With probability `1 - damping_factor`, choose
a link at random chosen fr... | 1d43b53b60ed5c9f99bf05eafad8ca8b8e96aaea | 678,250 |
def is_link_field(field):
"""Return boolean whether field should be considered a link."""
return "." in field | ad68eb6ae3b795fea64575272fde7df6be501007 | 678,252 |
def minForestSizeTLCovers(tlcovs):
"""
Prune top-level covers for minimum forest size
Inputs:
tlcovs: A list of top-level covers as returned by explain.
Outputs:
tlcovs_fs_min: The pruned top level covers.
fs_min: The minimum forest size found.
"""
fs_min = min(sum(ts) fo... | 059f200a22ca2c6cfa40e5562f7a9beb12222a8f | 678,255 |
def get_all(model, scenario):
"""
:param model: a database model with fields scenario and name which are unique together
:return: a dictionary of the fields of the given model corresponding to the current simulation,
with their name fields as key.
"""
records = model.objects.filter(scenario=sce... | ac53802ce77dabe070f18c6c4aaac8fdf213d950 | 678,257 |
def convert_from_bytes_if_necessary(prefix, suffix):
"""
Depending on how we extract data from pysam we may end up with either
a string or a byte array of nucleotides. For consistency and simplicity,
we want to only use strings in the rest of our code.
"""
if isinstance(prefix, bytes):
p... | 6466bf121c93b2428646b4b7c45542aa94fce4f7 | 678,259 |
def get_display_settings_for_lid(local_identifier, label):
""" Search a PDS4 label for Display_Settings of a data structure with local_identifier.
Parameters
----------
local_identifier : str or unicode
The local identifier of the data structure to which the display settings belong.
label :... | 4349d97cf600f24d274d02121b72e3461422b96a | 678,260 |
from typing import List
import re
def find_assets(html: str) -> List[str]:
"""
Return a list of assets found in the given HTML string
"""
return re.findall(
r'"([^"]+\.(?:css|js|jpg|jpeg|gif|tiff|png|bmp|svg|ico|pdf))"',
html, flags=re.IGNORECASE) | 511fb8cadc6acbbeb5d86f2568a0a5a31f76dd7d | 678,262 |
def get_float_format(number, places=2):
"""
Return number with specific float formatting
"""
format_string = '{:.' + str(places) + 'f}'
return format_string.format(number) if number % 100 else str(number) | b21d3b3ec20d7440ed220eea2d25e79e08ceb635 | 678,266 |
def scheme_ij(u, u_n, u_nm1, k_1, k_2, k_3, k_4,
f, dt2, Cx2, Cy2, x, y, t_1,
i, j, im1, ip1, jm1, jp1):
"""
Right-hand side of finite difference at point [i,j].
im1, ip1 denote i-1, i+1, resp. Similar for jm1, jp1.
t_1 corresponds to u_n (previous time level relative to u).
... | ce612b7b18ccc2b8a601861ea1c5f35d2a35cc38 | 678,267 |
import csv
import itertools
def gen_csv(f):
"""peek at rows from a csv and start yielding when we get past the comments
to a row that starts with an int"""
def startswith_int(row):
try:
int(row[0][0])
return True
except (ValueError, IndexError):
return F... | 83798fbe9e79382f7711a968f5e3a1c519efd7cb | 678,268 |
def countissue(s):
"""Count number of issues"""
if s:#check if Nonetype.
if s=='None':
#if type(s)==str or type(s)==float:#Handle
return 0
else:
return len(s)
else:#if empty
return 0 | e1960898476b7a20377293d413b10c9f0ab9b1bb | 678,270 |
def to_float(value):
"""
Noneを0.0に置き換えfloat化する。
引数:
value 対象値
戻り値:
置き換え済みfloat値
"""
if value is None:
return 0.0
else:
return float(value) | 3b047a1e09ded7b99955c99ab9db02063cd6f7f0 | 678,272 |
from enum import Enum
def AgeEnum(ctx):
"""Age Enumeration."""
return Enum(
ctx,
what=-2,
unset=-1,
dark=0,
feudal=1,
castle=2,
imperial=3,
postimperial=4,
dmpostimperial=6,
default='unknown'
) | 264f8aeafb300aa73821fecd7391c7f17e80e68e | 678,273 |
def fibo_even_sum(limit: int) -> int:
"""Compute the sum of the even fibonacci numbers that are <= limit
using a while loop with accumulator and trial division.
:param limit: Max value of the fibonacci range to sum.
:return: Sum of the even fibonacci numbers that are <= limit.
"""
even_sum = 0
... | 356ce6ffd6b586e81a8db4844517f0601a385888 | 678,279 |
import re
def _convert_camelcase(name, seperator=' '):
"""ExtraCondensed -> Extra Condensed"""
return re.sub('(?!^)([A-Z]|[0-9]+)', r'%s\1' % seperator, name) | 0933fb0de25bc3f0fe2b4653123b2b50f04ab1b1 | 678,280 |
def spaceship(a,b):
"""3-way comparison like the <=> operator in perl"""
return (a > b) - (a < b) | f2e33d9ebbbf9cd4e1636fa4e3d62398218425e4 | 678,281 |
def _repo_fixture(request) -> str:
"""Create a repository name from the test function name."""
return request.node.nodeid.replace("/", "-").replace(":", "-").replace(".py", "") | eb3fec394bf84e970770ca2022f2b79e05279c7c | 678,282 |
def outputids2words(id_list, vocab, article_oovs):
""" Maps output ids to words,
including mapping in-article OOVs from their temporary ids to the original OOV string
(applicable in pointer-generator mode).
Args:
id_list: list of ids (integers)
vocab: Vocabulary object
... | 6a06d118db7b9462284ea11c4c59445768b919c7 | 678,283 |
def convert_scan_dict_to_string(scan_dict):
"""
converts parsed ImageScanStatus dictionary to string.
:param scan_dict: {'HIGH': 64, 'MEDIUM': 269, 'INFORMATIONAL': 157, 'LOW': 127, 'CRITICAL': 17, 'UNDEFINED': 6}
:return: HIGH 64, MEDIUM 269, INFORMATIONAL 157, LOW 127, CRITICAL 17, UNDEFINED 6
""... | 011a040261e61d7f9b926554ecd6149f50aaa8c1 | 678,285 |
import math
def entropy(data):
"""
Calculate entropy, used by entropy_graph()
"""
h = 0
bins = [0 for x in range(0, 256)]
length = len(data)
for v in data:
bins[ord(v)] += 1
for x in range(0, 256):
p_x = float(bins[x]) / length
if p_x > 0:
h += - p... | 286326d9c583c644b8043249f09e294537493a5e | 678,288 |
def increment_count(val):
""" Increments the value by 1. """
return val + 1 | 107dc447d5e749daae5b1d0f578a213088d5ba84 | 678,294 |
import hashlib
def md5sum(infile):
"""Calculate the md5sum of a file
"""
# Implementation taken from: http://stackoverflow.com/a/4213255
md5 = hashlib.md5()
with open(infile,'rb') as f:
for chunk in iter(lambda: f.read(128*md5.block_size), b''):
md5.update(chunk)
return md5... | 475ad58c71d361a6dfec9127dbbddc53fb60cd21 | 678,298 |
import json
import collections
def extract_from_json(path, key, values, proc=(lambda x: x)):
"""Extracts and parses data from json files and returns a dictionary.
Args:
path: string, path to input data.
key: string, name of key column.
values: string, name of column containing values to extract.
... | 93068d5e27a439a0b1d908d5b8f5362c06a21859 | 678,299 |
def get_areas(objects):
"""
Get rounded area sizes (in m^2) of the geometries in given objects.
The results are rounded to two digits (dm^2 if the unit is metre)
and converted to string to allow easy comparison with equals.
"""
return {str(obj): '{:.2f}'.format(obj.geom.area) for obj in objects... | 4e5428ad6d53568edd154ccc1427d96dc1210351 | 678,300 |
def vec_to_str(vec):
"""
Convert a vec (of supposedly integers) into a str
"""
return ''.join(map(str, map(int, vec))) | 1093cbd9c944f45464f7f2b52ef01de39bea8932 | 678,301 |
import math
def _deck_name(current_cnt, total_cnt):
""" Get deck name for DriveThruCards.
"""
if total_cnt > 130:
return 'deck{}/'.format(min(math.floor((current_cnt - 1) / 120) + 1,
math.ceil((total_cnt - 10) / 120)))
return '' | 39d92172b463e5efe83fb7b93fad695bbaa08c2d | 678,307 |
def _can_show_deleted(context):
"""
Calculates whether to include deleted objects based on context.
Currently just looks for a flag called deleted in the context dict.
"""
if hasattr(context, 'show_deleted'):
return context.show_deleted
if not hasattr(context, 'get'):
return Fals... | dc8833bb7a1fa45fa016f31f99efce22a7c05f1a | 678,308 |
def sort_dict_by_value(d, increase=True):
"""sort dict by value
Args:
d(dict): dict to be sorted
increase(bool, optional): increase sort or decrease sort. Defaults to True.
Returns:
[type]: [description]
Examples:
>>> d = Dict()
>>> d.sort_dict_by_value({"a": 1... | c2fbfca5fa572c3f030e14ea74e8c1ae29e3e6d7 | 678,309 |
def _squeeze(lines, width):
"""
Squeeze the contents of a cell into a fixed width column, breaking lines on spaces where possible.
:param lines: list of string lines in the cell
:param width: fixed width of the column
:return: list of lines squeezed to fit
"""
if all(len(line) <= width for ... | 6e4c6f6f991dfbf02a145b1d304bbb1bc345b021 | 678,312 |
def irc_split(line):
"""Split an event line, with any trailing free-form text as one item."""
try:
rest_pos = line.index(' :')
bits = line[0:rest_pos].split(' ') + [line[rest_pos + 2:]]
except ValueError:
bits = line.split(' ')
return bits | 42a9bf33e7ca0d85f1ddfa242e661d984f3c88ce | 678,314 |
def energy_capacity_rule(mod, g, p):
"""
The total energy capacity of dr_new operational in period p.
"""
return mod.DRNew_Energy_Capacity_MWh[g, p] | 39254e81cbbcff85773af4415c33a5896191e4cd | 678,316 |
def bollinger_bands(price_col, length=20, std=1.96):
"""
Calculate Bollinger Bands
:param price_col: A series of prices
:param length: Window length
:param std: Standard deviation
:return: A 3-tuple (upper band, mid, lower band)
"""
mid = price_col.rolling(window=length).mean()
upper... | b48008c4ed44c9386e03d4e2906a1663cdbe4e82 | 678,321 |
def get_census_params_by_county(columns):
"""Returns the base set of params for making a census API call by county.
columns: The list of columns to request."""
return {"get": ",".join(columns), "for": "county:*", "in": "state:*"} | 7fed3bb9b75e9396b18f85a33ef9a57cc6408b9f | 678,322 |
def incremental_mean(mu_i, n, x):
"""
Calculates the mean after adding x to a vector with given mean and size.
:param mu_i: Mean before adding x.
:param n: Number of elements before adding x.
:param x: Element to be added.
:return: New mean.
"""
delta = (x - mu_i) / float(n + 1)
mu... | 8f1db96c12856f5bcdbf3cb154b93be944a6b289 | 678,330 |
def get_object_id_value(spall_dict):
"""
get the best value for OBJID
:param spall_dict:
:return:
"""
if "BESTOBJID" in spall_dict.keys():
return spall_dict["BESTOBJID"]
else:
return spall_dict["OBJID"] | a0809d787115c8ef64eba373c9c5c65438cc839a | 678,332 |
def first(seq, pred=None):
"""Return the first item in seq for which the predicate is true.
If the predicate is None, return the first item regardless of value.
If no items satisfy the predicate, return None.
"""
if pred is None:
pred = lambda x: True
for item in seq:
if pr... | f545ab4deb8c6d8103dd46dc85e0afd1f2597c6e | 678,333 |
def multiple_benchmark_thetas(benchmark_names):
"""
Utility function to be used as input to various SampleAugmenter functions, specifying multiple parameter benchmarks.
Parameters
----------
benchmark_names : list of str
List of names of the benchmarks (as in `madminer.core.MadMiner.add_ben... | b4e2fad24c6b8303f8985ed9cd8e4a352b70da38 | 678,334 |
def convertWCS(inwcs,drizwcs):
""" Copy WCSObject WCS into Drizzle compatible array."""
drizwcs[0] = inwcs.crpix[0]
drizwcs[1] = inwcs.crval[0]
drizwcs[2] = inwcs.crpix[1]
drizwcs[3] = inwcs.crval[1]
drizwcs[4] = inwcs.cd[0][0]
drizwcs[5] = inwcs.cd[1][0]
drizwcs[6] = inwcs.cd[0][1]
... | ca5f490ffac73d9510ccbeb927ddc818cafbf5a9 | 678,335 |
def is_eligible_for_exam(mmtrack, course_run):
"""
Returns True if user is eligible exam authorization process. For that the course must have exam
settings and user must have paid for it.
Args:
mmtrack (dashboard.utils.MMTrack): a instance of all user information about a program.
course... | 2ee804ac8f338186bd543584b207cde440a109c5 | 678,337 |
import math
def calc_tf_padding(x,
kernel_size,
stride=1,
dilation=1):
"""
Calculate TF-same like padding size.
Parameters:
----------
x : tensor
Input tensor.
kernel_size : int
Convolution window size.
stride : in... | 4d1ac3cdf451fdfc86fa4b41a217f6813b401252 | 678,340 |
def get(server_id, **kwargs):
"""Return one server."""
url = '/servers/{server_id}'.format(server_id=server_id)
return url, {} | 03416fc01f5a618b92701a3a17d2809237fda23a | 678,341 |
def bytes_to_human_readable(num, suffix='B'):
"""
Convert number of bytes to a human readable string
"""
for unit in ['','k','M','G','T','P','E','Z']:
if abs(num) < 1024.0:
return '{0:3.1f} {1}b'.format(num, unit)
num /= 1024.0
return '{0:3.1f} {1}b'.format(num, 'Y') | 07245d978543664e62c4abb4a617a0e1cbf48638 | 678,342 |
from typing import Tuple
import math
def measure_to_ma2_time(measure: float, resolution: int) -> Tuple[int, int]:
"""Convert measure in decimal form to ma2's format.
Ma2 uses integer timing for its measures. It does so by taking
the fractional part and multiplying it to the chart's
resolution, then r... | d10e47c0e2c91288676a14890663509468bbe95d | 678,345 |
import uuid
from datetime import datetime
def make_event(name, payload, safe=True, idempotent=True):
"""
Build an event structure made of the given payload
"""
return {
"id": str(uuid.uuid4()),
"name": name,
"created": datetime.utcnow().isoformat(),
"safe": safe,
... | 9b6d8677354416f27a78448ff16ba54565c12bdb | 678,346 |
def as_dict(val, key):
"""Construct a dict with a {`key`: `val`} structure if given `val` is not a `dict`, or copy `val` otherwise."""
return val.copy() if isinstance(val, dict) else {key: val} | 15057a88fc69aab0e12ba73065e6dccf040077b5 | 678,351 |
def multiply(number_1: int, number_2: int) -> int:
"""Multiply two numbers_together"""
return number_1 * number_2 | b87ffd7c48d64b7b0dbd0d9e9acb65e90e7ed9fa | 678,353 |
def resolve_obj_path(obj_path: str) -> tuple:
"""Resolve object module and attribute names from dot notated path.
Example:
>>> _resolve_obj_path("uuid.uuid4")
("uuid", "uuid4")
>>> _resolve_obj_path("foo.bar.baz.uuid4")
("foo,bar.baz", "uuid4")
"""
module_name, attribute... | 7107b831cabdeeab4c1fcf826371794a69da5523 | 678,356 |
def incrochet(strg):
""" get content inside crochet
Parameters
----------
strg : string
Returns
-------
lbra : left part of the string
inbr : string inside the bracket
Examples
--------
>>> strg ='abcd[un texte]'
>>> lbra,inbr = incrochet(strg)
>>> assert(lbra=='ab... | 2c589fd1b6f1a840cf1bda6513a521ab3cafcb0d | 678,358 |
def fuselage_form_factor(
fineness_ratio: float,
ratio_of_corner_radius_to_body_width: float = 0.5
):
"""
Computes the form factor of a fuselage as a function of various geometrical parameters.
Assumes the body cross section is a rounded square with constant-radius-of-curvature fillets.
... | e82891f60c0eef03f5787d38186a7c050b78c4b5 | 678,361 |
from typing import Dict
from typing import Any
import re
def get_entrypoint(doc: Dict[str, Any]) -> Dict[str, Any]:
"""Find and return the entrypoint object in the doc."""
# Search supportedClass
for class_ in doc["supportedClass"]:
# Check the @id for each class
try:
class_id ... | 45c085568867c2ce800f92d46e685cf7872f6e89 | 678,367 |
def get_species_mappings(num_specs, last_species):
"""
Maps species indices around species moved to last position.
Parameters
----------
num_specs : int
Number of species.
last_species : int
Index of species being moved to end of system.
Returns
-------
fwd_species_... | 3d0c83b4eae2d22ad13c14ce6d307e3bda7dcbb1 | 678,369 |
def get_data_view_status(data_view_id):
"""
URL for retrieving the statuses of all services
associated with a data view.
:param data_view_id: The ID of the desired data views
:type data_view_id: str
"""
return "data_views/{}/status".format(data_view_id) | 7185dd6266d08aebe7791cc82338ee8336522951 | 678,370 |
def merge_args_and_kwargs(param_names, args, kwargs):
"""Merges args and kwargs for a given list of parameter names into a single
dictionary."""
merged = dict(zip(param_names, args))
merged.update(kwargs)
return merged | 46f4e0249979579d592aea504796fbc556e40f1b | 678,374 |
from pathlib import Path
def baddir(path: Path) -> bool:
"""
tells if a directory is not a Git repo or excluded.
A directory with top-level file ".nogit" is excluded.
Parameters
----------
path : pathlib.Path
path to check if it's a Git repo
Results
-------
bad : bool
... | 027366d5c1ddf1f55e2011709d826561d86950de | 678,379 |
import re
def findWords(line):
"""Parse string to extract all non-numeric strings"""
return re.findall(r'[a-z]*[A-Z]+', line, re.I) | 3c5e7c3ea455b569cd8ee9cc5ec0f4b07311b34c | 678,380 |
import torch
def hz_to_mel(freqs: torch.Tensor):
"""
Converts a Tensor of frequencies in hertz to the mel scale.
Uses the simple formula by O'Shaughnessy (1987).
Args:
freqs (torch.Tensor): frequencies to convert.
"""
return 2595 * torch.log10(1 + freqs / 700) | 02ac7b5af09a12ae0040ea612c6e1a1d478baf35 | 678,381 |
import csv
def get_run_parameter_value(param_name, contents):
"""
Parses outfile contents and extracts the value for the field named as `param_name` from the last row
"""
# read the header + the last line, and strip whitespace from field names
header = ','.join([c.lstrip() for c in contents[0].sp... | 7dec2ff99b2fa2caf4c4c77599cb9efbce6be1a4 | 678,383 |
def escapeToXML(text, isattrib = False):
"""Borrowed from twisted.xish.domish
Escape text to proper XML form, per section 2.3 in the XML specification.
@type text: L{str}
@param text: Text to escape
@type isattrib: L{bool}
@param isattrib: Triggers escaping of characters necessary for use... | 5642d5cc1df1f1a8966f2ad2043e4e5b034b6a92 | 678,384 |
def normalize(a):
"""Normalize array values to 0.0...255.0 range"""
a = a.astype(float)
lo, hi = a.min(), a.max()
a -= lo
a *= 255.0 / (hi - lo)
return a.round() | 6b35428ab9eb254bbd18319b63f1dd604722e9b0 | 678,385 |
def _nested_lambda_operator_base(string, lambda_operator1, lambda_operator2):
"""
Funcao base que constroi uma consulta usando dois operadores lambda do Odata.
Args:
string (str): String "cru" que serve de base para construir o operador.
Ex.: customFieldValues/items/customFieldItem eq '... | 10832da19bd8f2a622129368395b10a5df901baa | 678,387 |
import json
def dethemify(topicmsg):
""" Inverse of themify() """
json0 = topicmsg.find('{')
topic = topicmsg[0:json0].strip()
msg = json.loads(topicmsg[json0:])
return topic, msg | 527cd8c3bb5a9ae75600b19050ca388b9321c630 | 678,389 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.