content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def calc_coord_distances(locations):
"""Calculate distances of all locations(latitude longitude).
Expects flat list, not pairs of points"""
n = len(locations)
coord_distances = np.empty((n, n))
for i in range(n - 1):
coord_distances[i, i] = 0.0
for j in range(i + 1, n):
d... | 5,298,200 |
def rotate_components(rx, ry, rz, nodes=None):
"""Rotate the given nodes' components the given number of degrees about each axis.
:param rx: Degrees around x.
:param ry: Degrees around y.
:param rz: Degrees around z.
:param nodes: Optional list of curves.
"""
if nodes is None:
nodes... | 5,298,201 |
def download_wallpaper(url, picture_dir, filename):
"""
Downloads URL passed, saves in specified location, cleans filename.
"""
filename = filename + "." + url.split(".")[-1]
outpath = os.path.join(picture_dir, filename)
try:
f = urllib.request.urlopen(url)
print(f"Downloading {u... | 5,298,202 |
def game(game_id):
"""Details of a specific game."""
with session_scope() as session:
game = session.query(Game, Image, System, Company, User).filter(
Game.image_id == Image.id).filter(
Game.system_id == System.id).filter(
Game.publisher_id == Company.id).... | 5,298,203 |
def shaping_test(font):
"""Test shaping output"""
from vharfbuzz import Vharfbuzz
from collidoscope import Collidoscope
from stringbrewer import StringBrewer
vhb = Vharfbuzz(font)
col = Collidoscope(font, {
"cursive": True,
"marks": True,
"faraway": True,
"adjacentmar... | 5,298,204 |
def inditomqtt(indiserver, mqtt_id, mqttserver, subscribe_list=[]):
"""Blocking call that provides the indiserver - mqtt connection. If subscribe list is empty
then this function subscribes to received data from all remote mqtt_id's. If it
contains a list of mqtt_id's, then only subscribes to their data.
... | 5,298,205 |
def mult_vector(vector, coeff):
""" multiplies a 2D vector by a coefficient """
return [coeff * element for element in vector] | 5,298,206 |
def unregister_all(db):
"""
Unregisters this node from all stored nodes and deletes them from
the database.
"""
logging.info("Leaving network mesh...")
try:
[node.client.unregister(config.ST_OWN_NAME) for node in get_all(db)]
# only server errors are possible, ignore them since we're... | 5,298,207 |
def undoInfo(*args, **kwargs):
"""
This command controls the undo/redo parameters.
Returns: `string` If querying undoName or redoName
`int` If querying state, infinity, or length
"""
pass | 5,298,208 |
def ratio_dananwpp2_at_houchiweir():
"""
Real Name: Ratio DaNanWPP2 At HouChiWeir
Original Eqn: Allocation DaNan WPP2/Total WPP Allocation At HouChiWeir
Units: m3/m3
Limits: (None, None)
Type: component
Subs: None
"""
return allocation_danan_wpp2() / total_wpp_allocation_at_houchiw... | 5,298,209 |
def clean_data(self):
"""Make all the data arrays the same length, in case the log file
did not finish a full time step (e.g. you killed the job early or are
monitoring a job in progess. Furthermore, delete redundant time steps
corresponding to when MMUT restarts"""
def get_length(data):
... | 5,298,210 |
def compute_beta_zero_node(alpha):
"""Compute beta values for ZERO node.
https://arxiv.org/pdf/1510.06495.pdf Section III.C.
"""
return np.ones(alpha.size, dtype=np.double) * INFINITY | 5,298,211 |
def finance():
"""Finance bundle commands.""" | 5,298,212 |
def get_ann_info(self, image_id=None, ann_id=None):
""" Retrieves the annotation informations given an image id or annotation id
if image_id provided, returns a list of annotation infos
if ann_id provided, returns a single annotation info
"""
if image_id is not None:
return deepcopy([self.a... | 5,298,213 |
def _is_any_geom_pass_contype_conaffinity_check(model: mujoco.wrapper.MjModel,
body1_id: int, body2_id: int):
"""Returns true if any geom pair passes the contype/conaff check."""
body1_geomadr = model.body_geomadr[body1_id]
body2_geomadr = model.body_geomadr[body2_i... | 5,298,214 |
def sample_sphere(n=100, center=(0, 0, 0), minr=0, maxr=1, mintheta=0, maxtheta=2*np.pi, minphi=0, maxphi=1):
"""Function to Sample points Between Two concentric Spheres using Inverse Transform Samples
Reference: https://github.com/girishdhegde/random.fun/tree/master/sampling
http://corysim... | 5,298,215 |
def extract_non_constant_subtree(expr, variables):
"""
Extract a non-constant sub-tree from an equation.
"""
last = expr
while True:
last = expr
# expr = remove_root_constant_terms(expr, variables, 'add')
expr = remove_root_constant_terms(expr, variables, "mul")
# exp... | 5,298,216 |
def deploy_kuma(kube_context, name, mode):
"""Deploy Kuma into on a Kubernetes cluster
Depending on the mode it takes different paths
"""
sh.kubectl.config(['use-context', kube_context])
logging.info('Installing Kuma on:' + name)
kds_global_address = get_kds_global_address()
args = ['contr... | 5,298,217 |
def get_date_whereclause(date_colname, startdate, enddate):
"""This is to change the date format function to use on the actual queries
sqlite and mysql use different methodnames to do their date arithmetic"""
ret = " %s > '%s' AND %s < '%s' " % (date_colname,startdate.strftime('%Y-%m-%d'),
... | 5,298,218 |
def map_label_colors(array, ignore_vals=[0]):
"""
Maps unique values in a mask to colors
Colors from 12-class paired
http://colorbrewer2.org/#type=qualitative&scheme=Paired&n=12
"""
colset = [(166, 206, 227),
(31, 120, 180),
(178, 223, 138),
(51, 160, 44... | 5,298,219 |
def LoadTraceFile(filename):
"""
Load a previously recorded binary trace file
@param filename: trace file
"""
return idaapi.load_trace_file(filename) | 5,298,220 |
def makeImageAuto(inarray):
"""Combines float_uint8 and image2array operations
ie. scales a numeric array from -1:1 to 0:255 and
converts to PIL image format"""
return image2array(float_uint8(inarray)) | 5,298,221 |
def get_effective_answer_words(answer_words, format_spec):
"""
If needed, modify answer_words using format spec to add padding chars
"""
if format_spec == model.ModelOutputFormat.sequence:
return answer_words + ["<stop>"]
else:
return answer_words | 5,298,222 |
def scan_single_repo(repo, summary, output_csv, num=100):
"""Print location results for single GitHub repository.
Printing can either be by contributor or by country.
Output can optionally be stored as a csv.
Args:
repo - URL of repo
summary - whether to print results by country, i.e. ... | 5,298,223 |
def ami_copy(region):
"""
Define a fixture to manage the copy and deletion of AMI.
This AMI is used to test head node and compute node AMI update
"""
copy_ami_id = None
client = boto3.client("ec2", region_name=region)
def _copy_image(image_id, test_name):
nonlocal copy_ami_id
... | 5,298,224 |
def write_cookie(cls, COOKIE_NAME, COOKIE_VALUE, path, expires=7200):
"""
Write a cookie
@path = could be a cls.request.path to set a specific path
@expires = seconds (integer) to expire the cookie, by default 2 hours ()
expires = 7200 # 2 hours
expires = 1209600 # 2 weeks
expires = 2629743 ... | 5,298,225 |
def newton_rhapson(f, df, x0, epsilon=1e-5):
"""Găsește o soluție a funcției f cu derivata df, aplicând
metoda lui Newton, pornind din punctul x0.
"""
# Primul punct este cel primit ca parametru
prev_x = x0
# Aplicăm prima iterație
x = x0 - f(x0) / df(x0)
# Continuăm să calculăm până av... | 5,298,226 |
def test_publisher_with_no_broker(RE, hw):
"""
Test the case of no Kafka broker.
"""
beamline_name = str(uuid.uuid4())[:8]
(
nslsii_beamline_topic,
kafka_publisher_thread_exit_event,
subscription_token,
) = nslsii._subscribe_kafka_queue_thread_publisher(
RE=RE,
... | 5,298,227 |
def appendToFile(fileName: str, content: str):
"""Writes content to the given file."""
with open(fileName, "a") as f:
f.write(content)
return None | 5,298,228 |
def kaldi_normalize(word, vocab):
"""
Take a token extracted from a transcript by MetaSentence and
transform it to use the same format as Kaldi's vocabulary files.
Removes fancy punctuation and strips out-of-vocabulary words.
"""
# lowercase
norm = word.lower()
# Turn fancy apostrophes i... | 5,298,229 |
def mc_prediction(policy, env, num_episodes, discount=1.0):
"""
Monte Carlo prediction algorithm. Calculates the value function
for a given policy.
Args:
policy: A function that maps an observation to action probabilities.
env: OpenAI gym environment.
num_episodes: Number of... | 5,298,230 |
def table_col_info(cursor, tableName, printOut=False):
"""
Returns a list of tuples with column informations:
(id, name, type, notnull, default_value, primary_key)
"""
cursor.execute('PRAGMA TABLE_INFO({})'.format(tableName))
info = cursor.fetchall()
if printOut:
print("Column Info:... | 5,298,231 |
def _apply_regex(regex, full_version):
"""
Applies a regular expression to the given full_version and tries to capture
a group
:param regex: the regular expression to apply
:param full_version: the string that the regex will apply
:return: None if the regex doesn't match or the result of the g... | 5,298,232 |
def sample_unit_sphere(N):
""" generate a set of points distributed on the unit sphere
Parameters
----------
N : int
Number of points
Returns
-------
array_like
A set of points distributed on the unit sphere
"""
dlong = np.pi*(3-np.sqrt(5))
dz = 2.0/N
lon ... | 5,298,233 |
def visualization_plot(figdata, i, add_label, spec_colnames, plot_color='grey', ylabel='Percent', ylim=-999):
"""Plot Bar Graph or Line Graph
-i: column name
-tmp_cut: data directly used for plot
-add_label: label added to X label
-spec_colnames: interpretation on short column name ... | 5,298,234 |
def refresh_session(autoProfile):
"""Refresh the `oldSession` role credentials.
Parameters
----------
- oldSession - the session to refresh;
- roleArn - the role_arn used to make the assume_role call;
- sessionName - what to name the assumed role session;
Returns
-------
The refres... | 5,298,235 |
def test_random_affine_md5():
"""
Test RandomAffine with md5 comparison
"""
logger.info("test_random_affine_md5")
original_seed = config_get_set_seed(55)
original_num_parallel_workers = config_get_set_num_parallel_workers(1)
# define map operations
transforms = [
py_vision.Decode... | 5,298,236 |
def indices(a, func):
"""
Get indices of elements in an array which satisfies func
>>> indices([1, 2, 3, 4], lambda x: x>2)
[2, 3]
>>> indices([1, 2, 3, 4], lambda x: x==2.5)
[]
>>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3)
[1, 2]
>>> indices([1, 2, 3, 4], lambda x: x in [2, 4])
... | 5,298,237 |
def matrix_tie_parent(registry, xml_parent, data):
"""yaml: matrix-tie-parent
Tie parent to a node.
Requires the Jenkins :jenkins-wiki:`Matrix Tie Parent Plugin
<Matrix+Tie+Parent+Plugin>`.
Note that from Jenkins version 1.532 this plugin's functionality is
available under the "advanced" option ... | 5,298,238 |
def get_deployment_config(app):
"""
Gets deployment configuration for the current environment.
Sets ENV_NAME and WIPE_ES as side-effects.
:param app: handle to Pyramid app
:return: dict of config options
"""
deploy_cfg = {}
current_prod_env = ENV_WEBPROD # this could change for CGAP d... | 5,298,239 |
def build_adiabatic_eq_library(flamelet_specs, verbose=True):
"""Build a flamelet library with the equilibrium (infinitely fast) chemistry assumption,
equivalently with Gibbs free energy minimization.
Parameters
----------
flamelet_specs : FlameletSpec or dictionary of arguments for a FlameletS... | 5,298,240 |
def build_openapi(
method: str,
path: str,
resp_code: str,
parameters: List[Tuple[str, str]] = None,
request: str = None,
response: str = None,
media_type: str = "application/json",
example: bool = True,
reference: bool = False,
title: str = "Generated by InducOapi",
version:... | 5,298,241 |
def my_decorated_function(name, value): # ...check_value(fix_name(negate_value(my_decorated_function)))
"""my original function."""
print("name:", name, "value:", value)
return value | 5,298,242 |
def delete_user(user_name):
""" delete an iam user """
# get the user
user = get_user(user_name)
# create a client
client = boto3.client("iam")
# Attached managed policies ( DetachUserPolicy )
for policy in user["policies"]:
policy_arn = policy["PolicyArn"]
response = clien... | 5,298,243 |
def fit_gauss2d(data):
"""
Fit a 2-dimensional anisotropic Gaussian to an image.
Parameters
----------
data : array_like
A two dimensional array_like object
Returns
-------
sigx : float
The standard deviation of the long axis
sigy : float
The standard devia... | 5,298,244 |
def write_hash_dir(topdirname, output_filename):
""" Write CSV file representing dir_hash to output_file in CSV format. """
dir_hash = compute_dir_hash(topdirname)
try:
output_file = open(output_filename, "w")
output_file.write("Filename,Hash\n")
for filename in sorted(dir_hash):
... | 5,298,245 |
def rename_iname(knl, old_iname, new_iname, existing_ok=False, within=None):
"""
:arg within: a stack match as understood by
:func:`loopy.match.parse_stack_match`.
:arg existing_ok: execute even if *new_iname* already exists
"""
var_name_gen = knl.get_var_name_generator()
does_exist = ... | 5,298,246 |
def get_words_forward(text, sep=None):
"""Get words (from text at right side of caret)"""
tokens = split_tokens(text)
words = extract_words_from_tokens(tokens, sep)
return ''.join(words) | 5,298,247 |
def assert_forward_results_depend_on_random_state(
model: torch.nn.Module, forward_kwargs: Dict[str, Any],
) -> None:
"""
Checks that
- forward passes with different seeds give different results (because the model uses dropout).
- forward passes with the same seed give the same result.
"""
w... | 5,298,248 |
def check_str_isalnum(string: str) -> ResultComparison:
""" post: _ """
return compare_results(lambda s: s.isalnum(), string) | 5,298,249 |
def get_architecture_string():
"""Return a string representing the operating system and the python
architecture on which this python installation is operating (which may be
different than the native processor architecture.."""
return '%s%s' % (platform.system().lower(),
platform.architecture()[0... | 5,298,250 |
def record_images_for_url(job_id, url, images):
"""
Records images that we've found while crawling.
:param str job_id: A job's UUID4 ID string.
:param str url: The URL that the image was found at.
:param set images: The images found while crawling this URL.
"""
conn = yield _get_job_data_co... | 5,298,251 |
def update_rule_candidates_(
rules_w_stats: List[Tuple[Rule, ChildRuleStats]],
remaining_vocab: Set[ExamplePair],
forget_lhs: Iterable[Rule] = None,
) -> None:
"""Update `rules_w_stats` in place (!)"""
prune_idxs = []
forget_lhs = forget_lhs or ()
lhs_to_forget = {r.lhs for r in forget_lhs}
... | 5,298,252 |
def polyfit(dates, levels, p):
"""Given the water level time history (dates, levels) for a station the function computes a least-squares fit of a polynomial of degree p to water level data.
It returns a tuple of (i) the polynomial object and (ii) any shift of the time (date)"""
try:
# Create ... | 5,298,253 |
def update_episodio():
"""
Aggiorna i dati di un episodio esistente
"""
nome = request.form['nome']
descrizione = request.form['descrizione']
tag = request.form['tag']
file = request.files['file']
id = request.form['id']
file_path = ''
# controlla che i dati necessari siano ins... | 5,298,254 |
def escape_text(txt):
"""
Escape text, replacing leading spaces to non-breaking ones and newlines to <br> tag
"""
lines = []
for line in txt.splitlines():
lead_spaces = re.match(r'^\s+', line)
if lead_spaces: # Replace leading spaces with non-breaking ones
lines.append(l... | 5,298,255 |
def nim_update(module):
"""
Update nim clients (targets) with a specified lpp_source
In case of updating to the latest TL or SP the synchronous mode is forced
Interim fixes that could block the install are removed
return: a return code (O if Ok)
"""
global NIM_CHANGED
lpp_source = NI... | 5,298,256 |
def get_coord(filename, pix_x,pix_y,timeFrame=0):
"""
Converts pixel values to solar coordinates
Parameters
----------
filename : str
name of the data cube
pix_x, pix_y : int
pixel location to convert
timeFrame : int
selected frame to the coordinates for (Default val... | 5,298,257 |
def setup_dataframes():
""" Set up dataframes for agents (df_a) and night shift info (df_n). """
global min_week_average_hours
min_week_average_hours = 100 # This will form a baseline for agent history.
agents = input_json["agents"]
df_a = pd.DataFrame(
data=None,
columns=[
... | 5,298,258 |
def get_candle():
"""
Function returns array (list of arrays if param 'limit' > 1) with next data:
Start time (type int) (WARNING!For correct subsequent work with the field, it must be divided by 1000)
open (type float) Open price
high (type float) High pri... | 5,298,259 |
def _clean_output_json(output_json: str) -> str:
"""Make JSON output deterministic and nicer to read."""
try:
output = json.loads(output_json)
except json.JSONDecodeError:
raise ValueError(
f"Instead of JSON, output was:\n--- output start ---\n{output_json}\n--- output end ---"
... | 5,298,260 |
def setup(channel, omAddress, arraysize):
"""
Enables I2C communication between Raspberry Pi and the temperature sensor.
Parameters:
channel(int): Raspberry Pi i2c channel
omAddress(int): Omron I2C address
arraysize(int): Size of thermal array
"""
global BUFFER_LENGTH
global tdata_r... | 5,298,261 |
async def get_default_playing(in_guild):
"""Search for a suitable waiting channel on new guild entry
Parameters
----------
in_guild :
Discord Guild to determine default channel for
"""
channels = in_guild.voice_channels
words = ["active","play","stream"]
chans = [c for c in ch... | 5,298,262 |
def test_devices_invalid_status(flask_app, app, db): # pylint: disable=unused-argument
""" To verify that de_registration device fails
with restricted status"""
headers = {'Content-Type': 'multipart/form-data'}
request_data = copy.deepcopy(DE_REG_REQ_DATA)
request_data['file'] = 'de-reg-test-f... | 5,298,263 |
def normalize_empirically(X_O, characters, keyslots, capitalization_constraints=1):
"""
Normalize empirically for the result to be between 0 and 1.
First minimizes and maximizes the keyboard problem for the given cost (X_O) and then normalizes all values in X_O
to minimally/maximally sum up to 0/1. ... | 5,298,264 |
async def top(message: discord.Message, *options):
""" By default displays your or the selected member's 5 highest rated plays sorted by PP.
You can also add "nochoke" as an option to display a list of unchoked top scores instead.
Alternative sorting methods are "oldest", "newest", "combo", "score" and "a... | 5,298,265 |
def load_staging_log_data(cur):
"""Load s_event staging table from log_data.
The ./data/log_data folder must be populated with event files.
Each event file contains multiple JSON records so a pandas dataframe is used.
"""
base_path = os.getcwd() + '/data/log_data'
for root, dirs, files in os.wal... | 5,298,266 |
def encrypt_payment_id(payment_id, public_key, secret_key):
"""
Encrypts payment_id hex.
Used in the transaction extra. Only recipient is able to decrypt.
:param payment_id:
:param public_key:
:param secret_key:
:return:
"""
derivation_p = crypto.generate_key_derivation(public_key, s... | 5,298,267 |
def list_csv_content_view(request):
"""
Homepage of the website. Displays uploaded CSV file in table form.
:param request: HTTPRequest object
:return: HttpResponse object
"""
if request.method == 'GET':
headings = [f.name for f in MuseumAPICSV._meta.get_fields()]
museum_api_csv_o... | 5,298,268 |
def vertical(x, ymin=0, ymax=1, color=None, width=None, dash=None, opacity=None):
"""Draws a vertical line from `ymin` to `ymax`.
Parameters
----------
xmin : int, optional
xmax : int, optional
color : str, optional
width : number, optional
Returns
-------
Chart
"""
li... | 5,298,269 |
def one_hot(labels, classes):
"""Apply One-Hot encoding to labels."""
return np.eye(classes)[labels] | 5,298,270 |
def get_os_credentials():
"""
Get OpenStack credentials from the environment
:return: str or None for the OS_AUTH_URL, OS_TOKEN, OS_USERNAME, OS_PASSWORD, OS_USER_DOMAIN_NAME and OS_TENANT_ID
"""
return get_os_auth_url(), get_os_token(), get_os_username(), get_os_password(), get_os_user_domain_name(... | 5,298,271 |
def reindex_colors(colors, labels):
"""Reindex the colors array using labels presented in a label image.
Because the labels in a label image are not necessarily a series of
consecutive integers, the ``1, ..., num_labels`` rows of the original colors
will be mapped to ``label1, lebel2, ..., labeln`` row... | 5,298,272 |
def filter_factory(global_conf, **local_conf):
"""Return a WSGI filter app for use with paste.deploy."""
conf = global_conf.copy()
conf.update(local_conf)
def auth_filter(app):
return TAuthProtocal(app, conf)
return auth_filter | 5,298,273 |
def _send_c_store_rsp(event):
"""Logging handler when a C-STORE-RSP is sent.
**C-STORE Response Elements**
| (U) Message ID
| (M) Message ID Being Responded To
| (U) Affected SOP Class UID
| (U) Affected SOP Instance UID
| (M) Status
Parameters
----------
event : events.Event
... | 5,298,274 |
def compute_codebook(descriptor_space, num_codewords):
"""Compute codebook for bag of features descriptor using k-means.
The descriptor space is a collection of local geometry descriptors. This
needs to be in the format of a matrix, rather than a list or a tensor.
"""
if isinstance(descriptor_space... | 5,298,275 |
def contours(path):
"""Returns a list of contours in the path.
A contour is a sequence of lines and curves
separated from the next contour by a MOVETO.
For example, the glyph "o" has two contours:
the inner circle and the outer circle.
>>> path = Bezier(None)
>>> path.moveto(0, 0)
>>>... | 5,298,276 |
def gen_dcppm(nr, B, k, ep, gamma, xmax = None):
"""
Input
-----
nr: number of nodes in each community
B: number of communities
k : average degree of the network
ep: the strength of the assortative structure, a real value in [0,1]
gamma: shape parameter of the trunca... | 5,298,277 |
def stations_within_radius(stations, centre, r):
"""This function uses haversine to first compute the distance from the given centre to the station
and then selects the stations which are closer than the given radius distance. The function then
returns a list of stations (MonitoringStations) in an unsorted ... | 5,298,278 |
def test_finder_installs_pre_releases_with_version_spec():
"""
Test PackageFinder only accepts stable versioned releases by default.
"""
req = InstallRequirement.from_line("bar>=0.0.dev0", None)
links = ["https://foo/bar-1.0.tar.gz", "https://foo/bar-2.0b1.tar.gz"]
finder = PackageFinder(links,... | 5,298,279 |
def lowless(dem):
"""
LOWESS (Locally Weighted Scatterplot Smoothing)
"""
lowess = sm.nonparametric.lowess
y = dem
x = np.arange(0, y.size)
w = lowess(y, x, frac=1/3)
return w[:, 1] | 5,298,280 |
def FetchByProjectAndTestName(project_name, test_name):
"""Fetches the first test with the given name."""
q = StorageMetadata.all()
q.filter('project = ', project_name)
q.filter('test_name = ', test_name)
return q.get() | 5,298,281 |
def translate(filename, topnode, outfilename, realtype):
"""
Translates a lustre file into a python
"""
if not realtype in ['real', 'float16', 'float32', 'float64']:
raise Exception('Unsupported real type ' + realtype)
# Parse lustre into AST
ast = lusp.parse(filename)
# Compute node... | 5,298,282 |
def download_blob(bucket_name: str, source_blob_name: str, destination_file_name: str):
"""
Downloads a blob from the bucket.
Parameters
----------
bucket_name : str
Your bucket name
source_blob_name : str
Storage object name
destination_file_name : str
local path to... | 5,298,283 |
def test_save_fg_append(tfg):
"""Check saving fg data, appending to file."""
file_name = 'test_fooofgroup_append'
save_fg(tfg, file_name, TEST_DATA_PATH, True, save_results=True)
save_fg(tfg, file_name, TEST_DATA_PATH, True, save_results=True)
assert os.path.exists(os.path.join(TEST_DATA_PATH, fi... | 5,298,284 |
def _parseparam(s: bytes) -> Generator[bytes, None, None]:
"""Generator which splits the input on ;, respecting double-quoted sequences
Cargo-culted from `cgi`, but works on bytes rather than strings.
Args:
s: header to be parsed
Returns:
The split input
"""
while s[:1] == b";... | 5,298,285 |
def parse_args():
"""Parse the input arguments, use '-h' for help"""
parser = ArgumentParser(description=('Produce VCFs and corresponding stutter'
' frequencies for a given set of STR loci. Also provides a bed file for each'
' locus defining a region around that locus.'))
parser.add_argument(
... | 5,298,286 |
def check_connection(server, port):
""" Checks connection to server on given port """
try:
sock = socket.create_connection((server, port), timeout=5)
except socket.error:
return False
else:
sock.close()
return True | 5,298,287 |
def make_tensor(name: str, vals: np.ndarray) -> ITensorProto:
"""
Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values ... | 5,298,288 |
def closeChannel(channel):
"""Close a previously open SSH connection.
Args:
channel (obj): The client object returned by the open function.
"""
channel.close() | 5,298,289 |
def _add_private_key(
click_context: click.core.Context,
type_: str,
file: Optional[str] = None,
password: Optional[str] = None,
connection: bool = False,
) -> None:
"""
Add private key to the wallet.
:param click_context: click context object.
:param type_: type.
:param file: p... | 5,298,290 |
def skip_inline(view, point):
"""Return True si il y a text between start of line and point"""
line_reg = view.line(point)
line = view.substr(sublime.Region(line_reg.a, point)).strip()
if line == "":
return False
else:
return True | 5,298,291 |
def load_image(fname):
"""Load named file, returning (data, metadata).
Keep temporarily for backward-compatibility...
"""
return load_tiff(fname) | 5,298,292 |
def tile(xi, yi, zoom):
"""Generates a box corresponding to a tile used for "slippy maps"
Parameters:
-----------
xi : int
The tile's X-index
- Range depends on zoom value
yi : int
The tile's Y-index
- Range depends on zoom value
zoom : int
The tile's z... | 5,298,293 |
def _rescale_layout(coords, bbox):
"""Transpose the layout of a component into its bounding box"""
min_x, min_y = np.min(coords, axis=0)
max_x, max_y = np.max(coords, axis=0)
if not min_x == max_x:
delta_x = max_x - min_x
else: # graph probably only has a single node
delta_x = 1.0
... | 5,298,294 |
def empirical_cdf(values, v):
"""
Returns the proportion of values in ``values`` <= ``v``.
"""
count = 0.0
for idx, v0 in enumerate(values):
if v0 < v:
count += 1
return count / len(values) | 5,298,295 |
def centerpoint(s):
"""
s is 2-d integer-valued (float or int) array shape
return is a (2-tuple floats)
correct for Jinc, hex transform, 'ff' fringes to place peak in
central pixel (odd array)
pixel corner (even array)
"""
return (0.5*s[0] - 0.5, 0.5*s[1] -... | 5,298,296 |
def _calculate_compliance(results):
"""
Calculate compliance numbers given the results of audits
"""
success = len(results.get('Success', []))
failure = len(results.get('Failure', []))
control = len(results.get('Controlled', []))
total_audits = success + failure + control
if total_audit... | 5,298,297 |
def calculate_log(current_count, smallest_count, largest_count, max_size, min_size):
""" Calculate ratio (logarithmic version). """
return ((log10(current_count) / log10(largest_count)) * (max_size
-min_size) + min_size) | 5,298,298 |
def test_benchmark_GetPreprocessFunction_mock(benchmark):
"""Benchmark GetPreprocessFunction."""
benchmark(
preprocessors.GetPreprocessorFunction,
"deeplearning.clgen.preprocessors.preprocessors_test" ":MockPreprocessor",
) | 5,298,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.