content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import math
def is_pentagon(x):
"""
Checks if x is a pentagon number
"""
n = (1 + math.sqrt(24*x + 1))/6
return(n == round(n)) | d765b841a4790371d2eb07bcb30bd13c5e5d344a | 661,512 |
def compute_user_vector_with_threshold(array, threshold=3.5):
"""Compute a user profile by summing only vectors from items with a
positive review.
Item vectors with a rating above a set threshold are included, other
vectors are discarded. The user profile is not normalized.
Args:
array (rdd ob... | 9bfe7bb6be20884f18b6a0995a6d1b46abd0757c | 661,513 |
def wrong_size():
"""
magic=0xA1B2C3D4 version=2, type=price, size=32
"""
return bytes([212, 195, 178, 161, 2, 0, 0, 0, 3, 0, 0, 0, 32, 0, 0, 0]) | 73b36580d6e921ea6edf9be4bcb051674d090ba1 | 661,514 |
def _get_shepp_array():
"""
Returns the parameters for generating modified Shepp-Logan phantom.
"""
shepp_array = [
[1., .6900, .920, .810, 0., 0., 0., 90., 90., 90.],
[-.8, .6624, .874, .780, 0., -.0184, 0., 90., 90., 90.],
[-.2, .1100, .310, .220, .22,... | 982cfedfc749e448bff09dd28bc477feacd8936c | 661,516 |
import math
def two_divider(num):
"""Solution to exercise P-1.30.
Write a Python program that can take a positive integer greater than 2
as input and write out the number of times one must repeatedly divide
this number by 2 before getting a value less than 2.
"""
if not isinstance(num, int) o... | 2bc6cdf305d2ed423e9bab0a5011dbb8a6c9efd1 | 661,517 |
import re
from datetime import datetime
def is_valid_timestamp(timestamp):
"""Checks whether timestamp is a string that is a proper ISO 8601 timestamp
Format for string is is YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]]
e.g. 2008-01-23T19:23:10+00:00
Parameters:
timesta... | c3fdb1cb1dfe069e8e4a69557ce7b2e85d2a843c | 661,518 |
def feasible(growth_rate):
"""Feasibility function for the individual. Returns True if feasible False
otherwise."""
if growth_rate > 1e-6:
return True
return False | 466635645a67a84a64e4dcc03f0dc66c1fea218b | 661,519 |
import os
def get_credentials():
"""Returns a creds dictionary filled with parsed from env"""
creds = {}
keystone_api_version = os.getenv('OS_IDENTITY_API_VERSION')
if keystone_api_version is None or keystone_api_version == '2':
keystone_v3 = False
tenant_env = 'OS_TENANT_NAME'
... | aa051a6b14195389c0febe5c62208573cfd6ab1a | 661,520 |
def knight_move(row, col):
"""knight_move (row, col) - returns all possible movements for the
knight in chess based on the parameters of its current row and column"""
# Deltas and Column Names
columns = ["A", "B", "C", "D", "E", "F", "G", "H"]
possible_moves = [(2, -1), (2, 1), (1, 2), (-1, 2), (-2... | b3803f95713dc2b720b2ece1de66626a4ca01228 | 661,521 |
def get_symlink_command(from_file, dest):
"""Returns a symlink command.
:param from_file:
:param dest:
"""
return 'ln -sf %s %s' % (from_file, dest) | 781e85d816488766244bf631513b4c01053534ec | 661,523 |
def is_kind_of_class(obj, a_class):
"""checks if an object is an instance of, or if the object is an instance
of a class that inherited from, the specified class"""
return (isinstance(obj, a_class) or issubclass(type(obj), a_class)) | 8eb04c13c1f8776aed8bd3bdc3e3c4764d090dc2 | 661,524 |
def str_list_to_dict(pairs_list):
"""
Parses strings from list formatted as 'k1=v1' to dict with keys 'k1', 'v1'.
Example: str_list_to_dict(['k=v', 'a=b']) —> {'k':'v', 'a': 'b'}
:param pairs_list: list of strings
:return: dict with parsed keys/values
"""
result = {}
for l in pairs_list:... | 3ace4d8d85258000cba67fe2417cf605158def00 | 661,525 |
def get_auth_type_from_header(header):
"""
Given a WWW-Authenticate or Proxy-Authenticate header, returns the
authentication type to use. We prefer NTLM over Negotiate if the server
suppports it.
"""
if "ntlm" in header.lower():
return "NTLM"
elif "negotiate" in header.lower():
... | 069aa3a04e9c6128f18b1c59c81e0abe469f0c45 | 661,526 |
import re
def parse_items(text, regexp):
"""Returns the list of parsed items
"""
if text is None:
return []
pattern = re.compile(regexp, flags=re.U)
return [term.strip() for term in pattern.split(text)] | 04ffd2ee1e60e99dab5b6971422572214b1b3a6c | 661,527 |
def get_relation_models(model):
"""
モデルのリレーション(OneToOneField, Foreignkey, ManyToManyField)を検出し、
リストで返す。リストの順番は検出順となる。
"""
relation_to, deps = [], []
for field in model._meta.fields:
if ( hasattr(field.rel, "to") ):
# save the OneToOneField or Foreignkey relation model.
... | 2e3935445b7f0f9744f128b698124a7d25087cd2 | 661,528 |
def bootstrap_icon(icon, **kwargs):
"""
Render an icon
"""
icon_class = 'icon-' + icon
if kwargs.get('inverse'):
icon_class += ' icon-white'
return {
'icon_class': icon_class,
} | c2b527fcaa367f5a66ceb0ebf22b0e0e1cb99ed0 | 661,529 |
def _as_specified(datetime_object,
format_string,
with_msec=False,
with_usec=False):
"""Return the datetime object formatted as specified"""
if with_usec:
return datetime_object.strftime(
'{0}.%f'.format(format_string))
#
if with_... | 6f7621c6a5bd784276643eda479ef7ac21c86f93 | 661,530 |
def _get_number_of_warmup_and_kept_draws_from_fit(fit):
"""Get number of warmup draws and kept draws."""
if 'warmup2' not in fit:
n_warmup = 0
n_draws = fit['n_save'][0]
else:
n_warmup = fit['warmup2'][0]
n_draws = fit['n_save'][0] - fit['warmup2'][0]
return n_warmup, n... | e1928cd5eb6eb47d1d1347ebf05f65434fb1336c | 661,531 |
import ast
def get_all_names(tree):
"""
Collect all identifier names from ast tree
:param tree: _ast.Module
:return: list
"""
return [node.id for node in ast.walk(tree) if isinstance(node, ast.Name)] | 643c6032c93c5ac562ba081bff4aabecc99febba | 661,532 |
from typing import List
from typing import Dict
import functools
def merge_list_of_dicts(list_of_dicts: List[Dict]) -> Dict:
"""A list of dictionaries is merged into one dictionary.
Parameters
----------
list_of_dicts: List[Dict]
Returns
-------
Dict
"""
if not list_of_dicts:
... | 81a05a7b16a4fa09d621e092fb525736811c63c9 | 661,533 |
from typing import Dict
import json
def load_user(filename: str) -> Dict:
"""Load json file with Discord userid and corresponding wellcome message
Args:
filename (str): filename of a json file
Returns:
Dict: {userid: text, date}
"""
with open(filename, 'r', encoding='utf-8') as f... | 69e5b05f09a1be58437f13bc150e102b7e41391f | 661,534 |
def check_matrix_empty(matrix, rows, cols):
""" Return True if the matrix is made up of 0's"""
for r in range(rows):
for c in range(cols):
if matrix[r][c] == 1:
return False
return True | 39226398c16278b07c85cd81076fdd3b56204893 | 661,536 |
import string
def find_words(text):
"""
text: string
Returns a list of words from input text
"""
text = text.replace("\n", " ")
for char in string.punctuation:
text = text.replace(char, "")
words = text.split(" ")
return words | 86c2691b9f0e57e758f7bc2d5b8fa51adcc1ebc0 | 661,537 |
def load_data():
"""
Returns a list of phone numbers and prices from a file.
"""
route_costs = []
with open('../../project/data/route-costs-4.txt', 'r') as f:
for line in f:
prefix, price = line.split(',')
route_costs.append((prefix, price))
return route_costs | d8ece30d767273528188b7a797cae1c3ee429b05 | 661,538 |
def hexdump(data: bytes) -> None:
"""
https://code.activestate.com/recipes/579064-hex-dump/
>>> hexdump(b'\x7f\x7f\x7f\x7f\x7f') #doctest: +NORMALIZE_WHITESPACE
0000000000: 7F 7F 7F 7F 7F .....
"""
def _pack(a):
"""
['7F', '7F', '7F', '7F', '7... | d0dab2898522292847b0b24a49fa23edb8ccdfb4 | 661,539 |
def get_portf_delete_data_toggle(uid):
""" Add this function inside a button or a href """
return_data = 'data-toggle="modal" data-target="#popup_delete_'+ str(uid) +'"'
return return_data | cc9594dea9c6a7751c752551aab212fa50715056 | 661,542 |
import math
def lr_scheduler(epoch, lr):
"""
Decay the learning rate every 50 epoch.
"""
drop = 0.5
epochs_drop = 25
lr = lr * math.pow(drop, math.floor((1 + epoch) / epochs_drop))
return lr | e4f63358c188d2e2de38c2084e8320ae86823fb6 | 661,543 |
def __pyexpander_helper3(*args, **kwargs):
"""a helper function needed at runtime.
This evaluates unnamed and named arguments.
"""
return (args,kwargs) | f3360b1b957ae71c00044fedbec348284745a862 | 661,544 |
def getDjangoURLPatterns():
"""Returns the URL patterns for the views in this module.
"""
patterns = [
(r'tasks/update/start$', 'soc.tasks.updates.start_update.startTasks'),
(r'tasks/update/start/([0-9_a-z]+)$',
'soc.tasks.updates.start_update.start_task'),
(r'tasks/update/run/([0-9_a-z]... | 499601add9bde84ce16e34b0776ae9d29bb5cd11 | 661,545 |
def get_note_head(note_path):
"""
Return first line of a text file
Parameters
----------
note_path : str
A text file path
Returns
-------
str
First line of the text file
"""
with open(note_path, "r") as f:
head = f.read()
return head | 987038ba80b0fdae7f209b172ed2daaf287ee19a | 661,546 |
def invert_y_tile(y, z):
"""
Convert from TMS to Google tile y coordinate, and vice versa
"""
return (2 ** z) - 1 - y | 45a7eb7146077c45582dc721182a09971b2e5dc9 | 661,547 |
def MassFlowProperty(self):
"""Mass flow (kg/hr)."""
return self.mol[self.index] * self.MW | 4d8000cc8c1b2876c9e07bc9799c0318e16f996b | 661,548 |
def encode_db_connstr(name, # pylint: disable=too-many-arguments
host='127.0.0.1',
port=5432,
user='postgres',
password='password',
scheme='postgresql'):
""" builds a database connection string """
con... | 5db05ad434f429714183da8d3d1c1ed058f1bff7 | 661,549 |
import copy
def override_config(config, kwargs):
""" Helper function to override the 'config' with the options present in 'kwargs'. """
config = copy.deepcopy(config)
for k, v in kwargs.items():
if k not in config.keys():
print('WARNING: Overriding non-existent kwargs key', k)
... | 42c3dce04fdf5d501ecdd1026cd7a75036bfca32 | 661,550 |
from typing import Counter
def system_call_count_feats(tree):
"""
arguments:
tree is an xml.etree.ElementTree object
returns:
a dictionary mapping 'num_system_calls' to the number of system_calls
made by an executable (summed over all processes)
"""
c = Counter()
in_all_secti... | 15f2e8cb7ce46a84732e2641b10c0e1bf9e4d0b2 | 661,551 |
import os
def path():
"""Checks for capture directory, creates if needed"""
current = '/home/pi/Documents/python/YardCam' # os.getcwd()
destination = current + '/captures'
if os.path.isdir(destination):
print('Photos will be placed in {} directory.'.format(destination))
else:
os.m... | e72d7630592c4a044c3d32faa27549111b0c7152 | 661,552 |
def create_marker_and_content(genome_property_flat_file_line):
"""
Splits a list of lines from a genome property file into marker, content pairs.
:param genome_property_flat_file_line: A line from a genome property flat file line.
:return: A tuple containing a marker, content pair.
"""
columns ... | 6084f8c3ea752d8e6901a3bd043a990da4193f19 | 661,553 |
def init_model_nn(model, params):
"""
## Description:
It initializes the model parameters of the received model
## Args
`model`: (Pytorch Model)
The model to be initialized
`params`: (dict)
Parameters used to initialize the model
## Returns:
The initialized model
"""
... | 46b1c51227a8cb07e8cb5456807459d1670e67a7 | 661,554 |
import pickle
def load_config(filename):
"""Loads in configuration file.
Args:
filename (string): The filename of the config file.
Returns:
object: A deserialised pickle object.
"""
with open(filename, 'rb') as file_ptr:
return pickle.load(file_ptr) | 1264149e7d6065ec7772818835d092415e9d52bc | 661,555 |
def _get_or_create_main_genre_node(main_genre_name, taxonomy_graph):
"""
Return the node for the main genre if it exists, otherwise create a new node and
make it a child of the root node.
"""
if main_genre_name in taxonomy_graph:
main_genre_node = taxonomy_graph.get_node(main_genre_name)
... | b3f999de588c6eef82290543b56b2b48e25230eb | 661,556 |
import subprocess
def partition(edc_path, graph_info, phi):
"""Run 'edc' and count edges cut.
"""
graph_string, graph_params = graph_info
result = subprocess.run([edc_path, f'-phi={phi}'],
input=graph_string,
text=True,
... | 768bd64d15ebbd69ab70053752c66daf03907658 | 661,557 |
def format_time(time_):
""" Returns a formatted time string in the Orders of magnitude (time)
Args:
time_: if -1.0 return 'NOT-MEASURED''
Returns:
str: formatted time: Orders of magnitude (time)
second (s)
millisecond (ms) One thousandth of one second
micros... | 0afd2d093a29ac446df1ed5f73ca110a52ee4e54 | 661,558 |
def kinetics_diff(reaction):
"""
Returns some measure of the discrepancy between two reactions in a model
"""
kinetics0 = reaction[0].kinetics
kinetics1 = reaction[1].kinetics
if kinetics0 and kinetics1:
diff = reaction[0].kinetics.discrepancy(reaction[1].kinetics)
else:
diff... | 756f114ec9469810a79a9299af49f3ab7c4c4f6f | 661,559 |
from datetime import datetime
def default(obj):
"""Encode datetime to string in YYYY-MM-DDTHH:MM:SS format (RFC3339)"""
if isinstance(obj, datetime):
return obj.isoformat()
return obj | 69ef19bf42e411fcc753214eb839d5de044e7d8f | 661,560 |
import math
def fiveGaussian(param, q):
""" param is a list """
val = 0.
qSqr = q * q
fourPi = 4. * math.pi
fac = 1. / (fourPi * fourPi)
for i in range(len(param[1])):
val += param[1][i] * math.exp(-qSqr * param[2][i] * fac)
val += param[0][2]
return val | 0e3b0d716bd2f8557f9d552bdfc3aad172c62092 | 661,561 |
import hashlib
def is_placeholder_image(img_data):
"""
Checks for the placeholder image. If an imgur url is not valid (such as
http//i.imgur.com/12345.jpg), imgur returns a blank placeholder image.
@param: img_data (bytes) - bytes representing the image.
@return: (boolean) True if placeholder image otherwise... | 59d92b6cbde9e72d6de19a300ce90f684cf6ca69 | 661,562 |
def list_to_lower(string_list):
"""
Convert every string in a list to lower case.
@param string_list: list of strings to convert
@type string_list: list (of basestring)
@rtype: list (of basestring)
"""
return [s.lower() for s in string_list] | 35097ddb6a665c50851bf6c98b60e9de88fb147b | 661,563 |
def get_exp_label(val, prefix="", decimal_remaining_val: bool=False, integer_mantissa=True, from_string=True, decimal_places=2) -> str:
"""
:param val: numeric label to format
:return: label formatted in scientific notation
Format a label in scientific notation, using Latex math font.
For exam... | 8852d4a6ff2f138f633494d85b755d89c2f68326 | 661,565 |
import os
def meter_status():
"""Get the meter status, if running in the meter-status-changed hook."""
return os.environ.get('JUJU_METER_STATUS') | cdeaf70767524b938899b2cc075103e3f5a7888b | 661,566 |
def is_handler_authentication_exempt(handler):
"""Return True if the endpoint handler is authentication exempt."""
try:
is_unauthenticated = handler.__caldera_unauthenticated__
except AttributeError:
is_unauthenticated = False
return is_unauthenticated | cbc5871084a961ada0225bdb5ee58eb2e6cce8bd | 661,567 |
import base64
def base64_encode(data):
"""Break a bytestring into lines separated by CLRFs, with maximum
line length specified by `max_length`. Note that `max_length`
includes length of the carriage return characters."""
assert (isinstance(data, bytes))
return str(base64.encodebytes(data), 'ascii... | cb6b03ed5f6b7c137fe0066bdc89869b34f0d031 | 661,568 |
import requests
def live_data(key):
"""
Requests latest covid-19 stats from rapidapi using requests.
Parameters
----------
key: rapidapi key
Returns
-------
response: A dictionary containing data in json format.
"""
# https://rapidapi.com/astsiatsko/api/coronavirus-monitor
... | c7905e39e3040d824c38e681ac4bf09ca1cb24fb | 661,569 |
import textwrap
def pike_tmp_package(pike_init_py):
"""Fixture: Create a Python package inside a temporary directory.
Depends on the pike_init_py fixture
:param pike_init_py: fixture with py.path.local object pointing to
directory with empty __init__.py
:return: t... | 28c30c4ce36a9e5ec745765a42712f49a334d98d | 661,570 |
def normalize_min_max(x, min_val=None, max_val=None):
"""
normalize vector / matrix to [0, 1].
:param x: a numpy array.
:param min_val: the minimum value in normalization. if not provided, takes x.min()
:param max_val: the maximum value in normalization. if not provided, takes x.max()
:return:
... | 4e4c9d24e48b214a7af725b17e0175a88e95c0ce | 661,571 |
import re
def parse_price(row, sale=False):
"""
Extract price data from `price`column
"""
row = row[1]["price"]
# Extract dollar amounts from string
row = re.findall(r"\$\d+", row)
if not row:
return None
elif len(row) == 1:
if sale:
return None
els... | 72221dc4ece0b35e59745df8c5c122fdaad75cad | 661,572 |
def p_ext_virus_phage_gens(B, t, N0):
"""
An approximate solution for the probability of extinction for phage clones, valid at large t
t is time in phage death generations. To convert to time in minutes, multiply
t by delta.
This is the NEUTRAL APPROXIMATION (p = 1/B)
"""
return ((B*t)/(B*t ... | fdae2b7745844524140cae024b2812d7d8ed3ea5 | 661,573 |
def sanitize_command_options(options):
"""
Sanitizes command options.
"""
multiples = [
'badges',
'exclude_badges',
]
for option in multiples:
if options.get(option):
value = options[option]
if value:
options[option] = [v for v in ... | 5a18854edaf56027c2358abbed90c5b897c2b3c2 | 661,574 |
def _get_nn_idx(row, neigh, radius, columns):
"""Retrieve the NN of a sample within a specified radius.
Parameters
----------
row : pd.Series
neigh : sklearn.NearestNeighbors
radius : float
columns : list
Returns
-------
list
Nearest Neighbors of given sample within rad... | 2fa5cbaa3a8d7d91e8c69b892dc26a3b42dcda66 | 661,575 |
def get_m2m_display(field_title, field):
"""
:param field_title: 显示manytomany字段的数据
:param field: 数据库表字段
:param time_format: 格式
:return:
"""
def inner(self, model=None, is_header=None, *args, **kwargs):
if is_header:
return field_title
query = getattr(model, field... | 6f1c70aa0c1edf967e29529a7985b0c8e2a2d80f | 661,576 |
def get_non_digit_prefix(characters):
"""
Get the non-digit prefix from a given list of characters.
:param characters: A list of characters.
:returns: A list of leading non-digit characters (may be empty).
Used by :func:`compare_strings()` as part of the implementation of
:func:`~deb_pkg_tools... | b1d0e321a4437654c58c073ca703127eeebd4793 | 661,577 |
def mdot(matrix, benchmark_information):
"""
Calculates a product between a matrix / matrices with shape (n1) or (a, n1) and a weight list with shape (b, n2)
or (n2,), where n1 and n2 do not have to be the same
"""
n1 = matrix.shape[-1]
weights_t = benchmark_information.T
n2 = weights_t.sha... | 0c3136d021ba65de173f891231838eb62bd255f9 | 661,578 |
def file_in(a, b, *args):
"""
Basic test: args are file ins
:param a:
:param b:
:param args:
:return:
"""
return 'OK' if a == open(args[0], 'r').read().strip() and b == open(args[1], 'r').read().strip() else 'NO' | e6a600f664ad0d713ec583b8b6df37f04e6aac8d | 661,579 |
import torch
def to_categorical(y, num_classes):
""" 1-hot encodes a tensor """
return torch.squeeze(torch.eye(num_classes)[y]) | 5e22c6e39bba32ed8ce561ec17d47f943c0637e7 | 661,580 |
def number_to_name(number):
"""
Converts an integer called number to a string.
Otherwise, it sends an error message letting you know that
an invalid choice was made.
"""
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "pap... | d711634578b8d67475044f8b24589944c81a16ca | 661,581 |
from operator import and_
def get_repository_metadata_by_changeset_revision( app, id, changeset_revision ):
"""Get metadata for a specified repository change set from the database."""
# Make sure there are no duplicate records, and return the single unique record for the changeset_revision.
# Duplicate re... | 092eb7aeb0bb6d52cc20bdf6a27ba089f6d6e47f | 661,583 |
import csv
def read(billing_csv_file):
"""
reads a billing_csv output file and returns a list
https://docs.python.org/2/library/csv.html
"""
return_list = []
with open(billing_csv_file) as csvfile:
fieldnames = ['namespace',
'start_time',
... | 0b2b85b5a2d24171bb6ef91807a2ada5c7383bdd | 661,584 |
def search_closet(items, colour):
""" (list of str, str) -> list of str
items is a list containing descriptions of the contents of a closet where
every description has the form 'colour item', where each colour is one word
and each item is one or more word. For example:
['grey summer jacke... | 24e7798c351ceef03c2299268373e917172bd5d2 | 661,585 |
import os
def _check_available(filename): # pragma: no cover
"""
Check to see if the filename exists and is a file
:param filename: str A fully qualified path and file
:returns: Boolean
"""
return os.path.exists(filename) and os.path.isfile(filename) | 10cffd652e6152df73d7ad5a44e4a458c52dbbd2 | 661,587 |
import pickle
def unpickle_it(pickle_path): # might throw the file not found exception
"""
function to unpickle the object from the given path
@param
pickle_path => the path where the pickle file is located
@return => the object extracted from the saved path
"""
with open... | 1096650fbdc5c4ce02168386a8f96f2fdf22c676 | 661,588 |
def makeSiblingTemplatesList(templates, new_template_file,
default_template=None):
"""Converts template paths into a list of "sibling" templates.
Args:
templates: search list of templates (or just a single template not in a
list) from which template paths will be extracted ... | a0cd622aba15305c8bfb47ebb9cfab71f757b585 | 661,589 |
def replace_format(string, **fmt):
"""Similar to `string.format(**fmt)` but ignores unknown `{key}`s."""
for k, v in fmt.items():
string = string.replace("{" + k + "}", v)
return string | e3151b0dbda941a9bf74e62853353fd420da25e1 | 661,590 |
import re
def n_credit(sentence):
"""
If a phrase in the form "X credit" appears in the sentence, and
X is a number, add a hyphen to "credit".
If "X-credit" appears, split it into "X" and "-credit".
Do not hyphenate "X credits" or "Y credit" where Y is not a number.
Run this after the tokenize... | 240743aa1a653ab8c50e505c28333964e1e85dc7 | 661,591 |
def choose_rows(rows):
"""Choose rows from the dataframe according to values in one of the columns."""
# Ensure that the object is not empty.
assert(len(rows) > 0)
# The following rows preferentially select data where the device_id=64 (i.e the GLONASS over the Trimble).
# Also select by data quali... | 84f646641a65674772b8126617e431df8378f90d | 661,592 |
def _is_this_combined_denovo_bsj_positive(parts):
""" junction orig_circOrLinear orig_decoyOrAnom orig_unmapped orig_pval swapped_circOrLinear swapped_decoyOrAnom swapped_unmapped swapped_pval total_reads
"""
if not parts:
return False
pv_threshold = 0.9
reads_rate_threshold = 0.1
orig_... | 402fc74cd59a7d2bf98bb302b6bda9adae971f37 | 661,593 |
def _convert_dict_to_list(d):
"""This is to convert a Python dictionary to a list, where
each list item is a dict with `name` and `value` keys.
"""
if not isinstance(d, dict):
raise TypeError("The input parameter `d` is not a dict.")
env_list = []
for k, v in d.items():
env_list... | 0eef0f65bda3a40a0538742f9a286b3d020c0862 | 661,594 |
def readrecipe(recipebook, index):
"""
Returns one recipe, for command line output
"""
try:
return recipebook.recipes[index].prettyprint()
except IndexError:
return "Error: no such recipe" | 32b46f34b152a05104c59ff8c95be7ad23abeff7 | 661,595 |
from typing import Sequence
from typing import Any
from typing import Optional
def binary_search_iter(seq: Sequence, value: Any) -> Optional[int]:
"""
Iterative binary search.
Notes
-----
Binary search works only on sorted sequences.
Parameters
----------
seq : Sequence
where... | a882a30aa8c8c5a55e2adf43234302da6ab6266c | 661,596 |
import csv
def csv_readline_to_list(csv_file):
"""
Read the CSV content by line.
Example:
csv content:
|name|age|
| a |21 |
| b |22 |
| c |23 |
| d |24 |
| e |25 |
ret = csv_readline_to_list("d/demo.csv")
Ret... | 7e6359df416174eb501868845edfbbcb5fe00e57 | 661,598 |
def sum_dice(dice:list):
"""dice: list -> int
Affiche et affiche la somme de dice en prenant en compte que les 6 = 5
"""
sum_dice = 0
for i in dice:
if i in ['vers', 6]:
sum_dice += 5
else:
sum_dice += i
return sum_dice | ca4e011ec9a0bbaa4b56687a48a8027bbb6b4fb4 | 661,599 |
import os
def uuid_root(uuid):
""" convert a uuid string to the mount point - only for linux
"""
#print(uuid)
idx = uuid.find('=') + 1
f = os.popen('blkid -U %s' % uuid[idx:])
lines = f.readlines()
f.close()
if len(lines) == 0:
return "//"
#print(lines)
dev = lines[0].s... | bd53e4d5ec025e9aeaa73404f3187a43636d10e1 | 661,600 |
def append_instr(qobj, exp_index, instruction):
"""Append a QasmQobjInstruction to a QobjExperiment.
Args:
qobj (Qobj): a Qobj object.
exp_index (int): The index of the experiment in the qobj.
instruction (QasmQobjInstruction): instruction to insert.
"""
qobj.experiments[exp_ind... | 87f341e9f378a9e79321ae1d34416087c2b38593 | 661,601 |
def cols_to_string_with_dubquotes(cols, backslash=False):
"""
Gets a string representation of a list of strings, using double quotes.
Useful for converting list of columns to a string for use in a query.
Backslashes are possible if the query will be passed as a string argument to (for instance) Shuttle... | aadf71c8c419466a3dbaa388baa17cba88f32aad | 661,602 |
def generate_payload(data_file):
"""
Generate a list of payloads to import into deep lynx
Args
data_file (string): location of file to read
Return
payload (dictionary): a dictionary of payloads to import into deep lynx e.g. {metatype: list(payload)}
"""
payload = dict()
... | fcb8c331e33f47dc2b2bea315ff473541248a509 | 661,603 |
import torch
def I():
"""Single-qubit Identification gate
-------
result : torch.tensor for operator describing Identity matrix.
"""
return torch.eye(2) + 0j | 85f7a39668ed192db7106d312eab801fcbf3374e | 661,604 |
def get_shock_sds_index_tuples(periods, factors):
"""Index tuples for shock_sd.
Args:
periods (list): The periods of the model.
factors (list): The latent factors of the model.
Returns:
ind_tups (list)
"""
ind_tups = []
for period in periods[:-1]:
for factor in... | bb249a0b885da103a7ec608807b0d8689dd5930f | 661,606 |
import os
def read_in_templates(path, email_object=None):
"""
Read in files and use them as templates
Provided externally to Email class to avoid large amounts of disk use
If attach is passed, it should be an Email object
"""
templates = {}
for fle in os.listdir(path):
with open(o... | cb823166fb97e50c87d26aaeae2a362c231e57da | 661,607 |
def applymap_numeric_columns(df, func):
"""Map a function elementwise to numeric columns.
All other columns are returned unchanged.
"""
columns = df._get_numeric_data().columns
df[columns] = df[columns].applymap(func)
return df | 08998e64f20f0433e13382d742d50e92fc846d2a | 661,608 |
def detect_non_informative_features(df_train, df_cv, df_test):
"""
Detection of features that do not carry any information
Parameters
----------
df_train: DataFrame
Contains training instances
df_cv: DataFrame
Contains crossval instances
df_test: DataFrame
Contains t... | da59b01b0ab9036d58e5ae072cfd2f39f0267392 | 661,609 |
import torch
def get_sample_region(boxes, stride, anchor_points, radius=1.5):
"""
This code is from
https://github.com/yqyao/FCOS_PLUS/blob/0d20ba34ccc316650d8c30febb2eb40cb6eaae37/
maskrcnn_benchmark/modeling/rpn/fcos/loss.py#L42
"""
# get mins and maxs value for center boarder
stride = s... | 2da2955aaa068809066fbe05236e95a25017a49c | 661,610 |
def cli(ctx):
"""Open a psql session to the database
Output:
None
"""
return ctx.gi.util.dbshell() | 45f022bda31015ea8da34f15b55915ecefc52404 | 661,611 |
def subs(text, subst):
"""Based on substitution dict, replace letters in text by their subst
First converts to lower case. Every non-letter is left intact"""
text = text.lower()
return ''.join([subst[l] if l in subst else l for l in text]) | 3d150c2e955166e03ed886b71d213a234ff67010 | 661,612 |
def map_to_last_intra(conditions,impulses,num_intra_event,terminal=True):
"""
This allows reuse of simBehave.acc.* routines for intra-event
conditions by mapping impulses (which should be in the same temporal
space as conditions) to the last intra-event in each intra-event set.
Note: this follows the same int... | 3478cde3947c7772176c69d283c9105d8f4468e7 | 661,613 |
def traitementPhrase(chaine):
"""Cette fonction traite une chaine en la coupant en deux au
bout de 50 caractéres. Elle retourne deux variables, la premiere
la chaine de moins de 51 caracteres et le reste. Il convient donc
d'executer la fonction autant que nécéssaire"""
listeMots = chaine.... | ea46cfd3bc075c5afd35aa6aa0e3d58a6920a076 | 661,614 |
import os
def _remote_health_check(remote_dir, remote_file):
"""Check the directory and file exist"""
# test remote directory exists
if not os.path.isdir(remote_dir):
return f"Remote directory does not exist: '{remote_dir}'"
# test uploaded file exists in remote directory
full_path_file ... | fbe7fa0abd7fb3ea2465590a395b3bfeef701348 | 661,617 |
import re
def regex_escape_text(text: str) -> str:
"""String to regex"""
document = re.escape(text)
document = document.replace('/', r'\/')
return document | 04084c84e70b67e05f625d259300a52b79dc85ff | 661,618 |
def transform_pos(word_pos):
"""Map POS tag to first character lemmatize() accepts"""
if word_pos == 'Noun':
return 'n'
elif word_pos == 'Verb':
return 'v'
elif word_pos == 'Adjective':
return 'a'
elif word_pos == '':
return '' | 3f871b679392c09e65bed90c425656050a599512 | 661,619 |
def longest_common_prefix(items1, items2):
"""
Return the longest common prefix.
>>> longest_common_prefix("abcde", "abcxy")
'abc'
:rtype:
``type(items1)``
"""
n = 0
for x1, x2 in zip(items1, items2):
if x1 != x2:
break
n += 1
return items1[:n] | 4f4a3724e50e37a632f2f761828d5edcd8c79f00 | 661,621 |
def get_mse_sorted(series1, series2):
"""
sorted but not normalized values
"""
assert len(series1) == len(series2)
mse = 0.0
series2_s = sorted(series2)
for index, data1 in enumerate(sorted(series1)):
diff = (data1 - series2_s[index])
mse += diff * diff
mse /= len(series1... | 1c728d71663d30492786143e0457ef7f4a4a04e7 | 661,623 |
def to_list(arr):
"""Transform an numpy array into a list with homogeneous element type."""
return arr.astype(type(arr.ravel()[0])).tolist() | 1773f2563533ebd76f9dd4acc8f446750f6e8a52 | 661,624 |
def hadjust(w, orientation):
"""Ostensibly, a function to reduce the vertical footprint of a widget
that is normally used in a vertical stack (usually a Splitter), when it
is instead used in a horizontal orientation.
"""
if orientation != 'horizontal':
return w
# This currently does not ... | 2f54ecaf9545a02c21bc00fb66a0d189c724b0ce | 661,625 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.