content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import requests
def getAccessToken(myKey):
""" Gets the Access Token using the Refresh Token """
params = {'api_token': myKey}
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post('https://console.cloud.vmware.com/csp/gateway/am/api/auth/api-tokens/authorize', param... | 27abc96d88df9a576e742418147976e00969cc23 | 649,708 |
def crop_resized_image(image):
"""We resize the images to half of their original size, 640x380. However, in order
to use the image with VGG16, each dimension should be devisible by 16 as we have 4
pooling layers. We therefore need to crop the images in a consistant way to the size
of 640x368."""
ret... | 2881598271a712bb6fd92a0970512e741aa97be8 | 649,709 |
def fix_links(links):
"""
The fix_links function removes multiple references to the same article
allowing only one representant
"""
if links:
result = [links[0]]
for i in range(1,len(links)):
test = [True for elem in result if elem in links[i]]
if not test:
... | bb5c890c9c257d67bc661b9b2b324952f6c1e7db | 649,710 |
def best_fit(X, Y):
"""
Calculate linear line of best fit coefficients (y = kx + c)
"""
xbar = sum(X)/len(X)
ybar = sum(Y)/len(Y)
n = len(X) # or len(Y)
numer = sum([xi*yi for xi, yi in zip(X, Y)]) - n * xbar * ybar
denum = sum([xi**2 for xi in X]) - n * xbar**2
if denum != 0:
... | 8e742308975c7147daa01d801430d246582a19ca | 649,711 |
def rawLibraryLogic(data):
"""Returns a tuple of the data in a library logic file."""
versionString = data[0]
scheduleName = data[1]
architectureName = data[2]
deviceNames = data[3]
problemTypeState = data[4]
solutionStates = data[5]
indexOrder = data[6]
ex... | 1efb700ab0aa23fec7df5fd80ab0c91cda8007ba | 649,712 |
import itertools
def augment_graph(graph, reads_dict, add_reads=False, min_mappings=0):
"""Add read nodes to graph according to read mapping file
Args:
graph (networkx Graph): contig assembly graph
reads_dict (str): Dict of read objects
add_reads: add read nodes if True, otherwise add... | 254bc07b09044e3467c13b85d5bd72f6e76210a6 | 649,713 |
import os
def data_path(filename, reinit=False):
""" In case these paths change depending on test methods?"""
data_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data'))
return os.path.join(data_dir, filename) | f7c52988858b977197b65f104efaaafbb6430ab8 | 649,714 |
def determine_stock_unit(flow_unit: str, time_unit: str = "h"):
"""For example:
>>> determine_stock_unit("m3/h") # m3
>>> determine_stock_unit("kW") # kWh
"""
return (
flow_unit.rpartition(f"/{time_unit}")[0]
if flow_unit.endswith(f"/{time_unit}")
else f"{flow_unit}{time_un... | 0f447ee976d790bc7f804f90c209332196ba7cc8 | 649,715 |
def send_str_cmd(sock, cmd_str):
"""send one or multiple string commands separated by \n"""
cmd = cmd_str.encode("ascii")
cmd = cmd.replace(b"\n", b"\r")
cmd += b"\r"
return sock.sendall(cmd) | 86f37fdee2e4bcbfba360f70d30b572c8b463b33 | 649,716 |
def add_cold(c):
"""
:param c: int, temp < 16 and != -100
:return: c + 1
"""
c += 1
return c | ec98e2fb931c90ccf5bdc4e48c1ed7a0b6ebb3a2 | 649,717 |
import struct
def formatVarInt(n):
""" Encodes an variable-length integer in Bitcoin's custom integer format for transactions"""
if n < 0xfd:
return struct.pack('<B', n)
elif n < 0xffff:
return struct.pack('<cH', '\xfd', n)
elif n < 0xffffffff:
return struct.pack('<cL', '\xfe',... | 8f3b34e1e452effa2bf5e7e137e25475f13350a0 | 649,719 |
import os
def get_path_for_fit_script(model_type):
"""
Interface to find the path of training scripts.
For now they are expected to be in the same folder-system as calling .py script.
Args:
model_type (str): Name of the model.
Returns:
filepath (str): Filepath pointing to traini... | 79e39eb3f73f36293c045edb40ab933079ea2298 | 649,720 |
def select_device(on_gpu: bool) -> str:
"""Selects the appropriate device as requested.
Args:
on_gpu (bool): Selects gpu if True.
Returns:
str:
"gpu" if on_gpu is True otherwise returns "cpu"
"""
if on_gpu:
return "cuda"
return "cpu" | a52de9949e549584bd06b31b58051ca3cf29483e | 649,721 |
def get_value(tixi, xpath):
""" Check first if the the xpath exist and that a value is stored
at this place. Returns this value. It returns a:
- float value if the value can be read as a float
- boolean if the value is 'True'/'False',
- otherwise a string
Source :
* TIXI functions: http... | 4fd9ba4e9c90b2f486db16f5a7fd7d3e8b884d1b | 649,722 |
def _find_og_ent(ent, base_ents):
"""Find the original entity referenced by $ref entity."""
id = ent["$ref"]
return next(bent for bent in base_ents if ("$id" in bent) and bent["$id"] == id) | b986452077ae6bd0b86ecdcbdf2a262ac32a8c0f | 649,723 |
def integral_insert_realignment(insert_alignment, insert_length):
"""
Check whether insert realigned without gaps to the reference.
Inserts are only considered as ITDs if they realign to the reference
in one piece (to their respective second tandem).
Args:
insert_alignment (str): Alignment... | ce3724a10df3bb843d2941e380a5e11fb2846279 | 649,724 |
import torch
def inner_product_normalized(x, y):
"""
Calculate the inner product between the given normalized vectors,
giving a result between -1 and 1.
"""
return torch.sum(x * y, dim=-1).clamp(min=-1, max=1) | d2b57bba4d04ef4ecbd3aa4c7fa0f4957671c2cd | 649,725 |
import mpmath
def cart_to_RSH_coeffs(l):
"""
Generates a coefficients [ coef, x power, y power, z power ] for each component of
a regular solid harmonic (in terms of raw Cartesians) with angular momentum l.
See eq. 23 of ACS, F. C. Pickard, H. F. Schaefer and B. R. Brooks, JCP, 140, 184101 (2014)
... | 95b0a9de562e9797a1d58686078a4451c9e9b304 | 649,727 |
def create_queries_subset(eval_size):
"""
Create queries to extract a evaluation and training dataset from a preprocess BigQuery table.
Parameters
----------
eval_size : float
fraction of the data to the evaluation dataset
Returns
-------
eval_query: str
query for the e... | f5e16663549051d9a59fecc74d6440ded9026548 | 649,728 |
def DecodePrivate(curve, bb):
"""
Decode a private key from bytes. Note that the length must match the
expected value (32 bytes for both do255e and do255s) and the value
is verified to be in the proper range (1 to r-1, with r being the
prime order of the do255* group).
"""
sk = curve.SF.Deco... | 6b0f4fb2f3e2ccc8e6deebadfb79cf05afa2315f | 649,729 |
from typing import Dict
def get_default_vmc_config() -> Dict:
"""Get a default VMC training configuration."""
vmc_config = {
"nchains": 2000,
"nepochs": 200000,
"nburn": 5000,
"nsteps_per_param_update": 10,
"nmoves_per_width_update": 100,
"std_move": 0.25,
... | 9c4835dc83688d65b6302caa1fedacebe9ce2afa | 649,730 |
import math
def float_zero(a):
"""Test if a equals zero, a more tolerant version than
:py:func:`float_equal(a, 0)`.
"""
return math.isclose(a, 0, abs_tol=1e-6) | 483c6a3cf5b8805bf7313c0b2f9a7d412d6b2f5c | 649,731 |
def example_distribution_config(ref):
"""Return a basic example distribution config for use in tests."""
return {
"CallerReference": ref,
"Origins": {
"Quantity": 1,
"Items": [
{
"Id": "origin1",
"DomainName": "asdf.... | 0658a70defe608929c6c71032308847ac87033a0 | 649,732 |
def filter_words(words: str, sep='/', k=2) -> str:
"""
filter words with less then k values
:param words:
:param sep:
:param k:
:return:
"""
list_words = words.split(sep)
list_words = [word.lower() for word in list_words if len(word) >= k]
words = " ".join(list_words)
return... | 78dd7c76d812ad8d4b7ee10f3cb3afbca4b8caa4 | 649,733 |
def get_hero_name(heroes_list, counter):
"""Получаем имя и класс героя из списка."""
return heroes_list[counter] | cf65c805e22c86df4659fdc28c063b509625d15c | 649,736 |
def subgraph(graph, nodes):
"""Induce a sub-graph over the given nodes.
:param BELGraph graph:
:param set[BaseEntity] nodes:
:rtype: BELGraph
"""
sg = graph.subgraph(nodes)
# see implementation for .copy()
result = graph.fresh_copy()
result.graph.update(sg.graph)
for node, dat... | 6cee740bcbaf2dced7ac0113bdee6464bc43445b | 649,737 |
def dicreaseColor(img):
"""
减色处理,8位量化图片转为2位量化,取值为32,96,160,244
:param img: 输入图片
:return: 输出图片
"""
return img // 64 * 64 + 32 | 0dcddc58200fe99ac1af5cc02203ed9b54206ec6 | 649,738 |
def annotation_order(positions, annotations, id1, id2, gaussians, nb_pos, max_zoom):
"""
Returns whether or not annotation 1 is visited before annotation 2
:param positions: positions
:param annotations: reference annotations
:param id1: index of 1st annotation
:param id2: index of 2nd annotatio... | 191fd62f6f79eea1cc7df3695f614fcd3d6a9e28 | 649,740 |
def loadPayout(service):
"""Shows basic usage of the Sheets API.
Creates a Sheets API service object and prints the names and majors of
students in a sample spreadsheet:
https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
"""
spreadsheetId = '1JHZepSOgSRnnt... | 7791400daf0bb582b91b5a52bb04a32eef369f94 | 649,741 |
import os
def which(executable_name):
"""Gets the full path to the given executable.
If the given path exists in the CWD or is already absolute it is returned.
Otherwise this method will look through the system PATH to try to find it.
Args:
executable_name: Name or path to the executable.
Returns:
... | 287acb23615d869067f5e4cddbb2e63fc356f402 | 649,742 |
import sqlite3
import math
def get_term_entropy(conn: sqlite3.Connection, term:str):
"""Compute the entropy score of a terms
Args:
conn (sqlite3 / Connection): sqlite3.Connection
term (str): HPO Terms
"""
# Get total diseases count => correspond to disease count of root node ... | aa0264aaf2df8b7ed4ce686180530f4137c88384 | 649,743 |
def parse_args(arg_list, keywords):
"""
parses a list of args, for either plain args or keyword args
args matching the keyword take the next argument as a value
missing values or duplicate keywords throw ValueError
returns a list and a dict
>>> args, kwargs = parse_args(arglist, ('keya', 'keyb')... | c6b70ada106b9b2e9b9c2ad3a9526450193c0039 | 649,744 |
def helper_parse_if(if_string : str):
"""
Parses the if_string manually to test for equality between its
members.
>>> helper_parse_if("this == this")
True
>>> helper_parse_if("2>3")
False
>>> helper_parse_if("40 >= 40")
True
"""
try:
i... | 9d5c8c445946819b0a7597edaae81f51f74cd06b | 649,745 |
from typing import Union
import uuid
def str_to_uuid(in_uuid: Union[str, uuid.UUID]) -> uuid.UUID:
"""
Convert str uuid to uuid.UUID.
Provided as a convenience function if the identifier must be changed in the future.
Args:
in_uuid (str or uuid.UUID): The uuid to be converted.
Returns:
... | c735a08b2f3e0876ff640afe9b2e710cfaed136f | 649,746 |
def plugin_second_label():
"""Another labeled plug-in function"""
return "second" | 283f7f669e4ac3c5db733467051407d0ada0bbdf | 649,747 |
def remove_duplicates_list(raw_list):
"""Return a list with just unique items.
Only works with a list of items, not with nested lists.
Args:
raw_list (list): List with duplicate items.
Returns:
unique_list (list):: List with only one instance of each item.
"""
... | bcca231ea46fb7da089196794402c0d1a8b082f7 | 649,748 |
def xor_bytes(bts1: bytes, bts2: bytes) -> bytes:
"""Make a xor by bytes
@param bts1:
@param bts2:
@return:
"""
return bytes([byte1 ^ byte2 for byte1, byte2 in zip(bts1, bts2)]) | 815b6446c653fcb6ef97a135e61497b77a0e9dac | 649,749 |
def liste_tout_dans_node(node):
"""Liste toutes les VMs et containers d'un certain b."""
# Attributs spécifiques à 'containers' et 'vms':
# container : pid
# virtual : lock, maxswap, swap, type
liste_containers = node.getNodeContainerIndex(node.name)['data']
liste_vms = node.getNodeVirtualIndex... | 8ab25ea8627a121311a9ea3e579702253327f6e7 | 649,750 |
from datetime import datetime
def _count_total_hours(start: datetime, stop: datetime):
"""Count the number of times each hour slot has occurred."""
if start is None or stop is None:
return [0] * (24 * 7)
start_hour = 24 * start.weekday() + start.hour
stop_hour = 24 * stop.weekday() + stop.hou... | a26d182d504f26b4318eba1373d6fe0a7d064aa7 | 649,752 |
def count_hosts(meetings):
""" Dedicated fuction to only count
specific hosts
"""
# Create an empty dictionary for hosts
host_dict = dict()
for item in meetings['items']:
# Check if the host is already counted
if item['hostEmail'] not in host_dict.keys():
host_dic... | 38a082641e306da9e2c65657f17272107c732986 | 649,753 |
import six
import ast
def dict_or_none(val):
"""Attempt to dictify a value, or None."""
if val is None:
return {}
elif isinstance(val, six.string_types):
return dict(ast.literal_eval(val))
else:
try:
return dict(val)
except ValueError:
return {} | dc64646cc463b301c12f51c7dc87e5991405ee70 | 649,754 |
def addMiddlePoints(p1, p2, n = 2):
""" Function to calculate the middle point between two points
Args:
p1: (Required) set of coordinates of first point
p2: (Required) set of coordinates of second point
n: (Required) number of divisions
"""
x_1 = p1[0]
y_1 = p1[1]
... | af007dc1c80b13d5047bd71dfcf94d08e3b4cb0d | 649,755 |
def is_service_named(service_name: str, service: dict) -> bool:
"""Handles a case where DC/OS service names sometimes don't contain the first slash.
e.g.: | SDK service name | DC/OS service name |
|--------------------------+-------------------------|
| /data-services/cassandra ... | 28a72b1030950c4df773664af17873dd16b7a038 | 649,756 |
def _has_base(cls, base):
"""Helper for _issubclass, a.k.a pytypes.issubtype.
"""
if cls is base:
return True
elif cls is None:
return False
try:
for bs in cls.__bases__:
if _has_base(bs, base):
return True
except:
pass
return False | b75e6ef8e27ecbed8fa7cb69242e67ac916a228f | 649,757 |
def kewley_comp_nii(log_nii_ha):
"""Composite classification line for log([NII]/Ha)."""
return 0.61 / (log_nii_ha - 0.47) + 1.19 | 64352b84752a42d9fdb882ea4395937226116483 | 649,758 |
def mergeBusy(groupedEvents):
"""
events = dict
args: a list of lists of events
ret: a list of lists of events, that have over lapping events merged
Events will contain only {"start": startTime, "end": endTime, AND "summary" : "busy"}
"""
#print("groupedEvents is:", groupedEvents)
mergedBlocks = [] ... | d77acbf0f9581f5500e24b80d9c0100ae3291611 | 649,759 |
def holt_winters_configs(seasonal=[None]):
"""'This method sets up the Holt Winter's parameter space for the Grid Search
Parameters
----------
data: list
Seasonal values
Returns
-------
list
parameter space
"""
models = list()
# define config lists
t_params ... | 03ceea1ef742af998079deb1c05c40430947358e | 649,760 |
def singleton(cls):
""" class decorator to implement singleton pattern
@singleton
class A: pass
a1 = A()
a2 = A.instance()
assert a1 is a2
"""
# pylint: disable=too-few-public-methods
class SingleCls(cls):
''' inner wrapper class '''
inst = N... | 20775402a6fd5573be792ac01635be6265473212 | 649,761 |
def mrr(ground_truth, prediction):
"""
Compute Mean Reciprocal Rank metric. Reciprocal Rank is set 0 if no predicted item is in contained the ground truth.
:param ground_truth: the ground truth set or sequence
:param prediction: the predicted set or sequence
:return: the value of the metric
"""
... | 2a2b72a3dbe5897239143c1fae47988beda3797b | 649,762 |
def get_cpe_version(cpe: str):
"""Return the version entry of the given CPE"""
split_cpe = cpe.split(":")
if len(split_cpe) > 4:
return split_cpe[4]
return "" | 11cfc2073e61294e30041619c87323e6d75b1223 | 649,763 |
import math
def round_to_significant(num, sig_figs):
"""Return (rounded_num, format_precision).
rounded_num is num rounded to sig_figs significant figures.
format_precision is the number of digits to format after the decimal.
"""
sig_digit = int(math.floor(math.log10(abs(num))))
sig_digit -= ... | 0d74e29e984a91c9a64625faa5dd586483b8aad4 | 649,764 |
def select_span(cropped_length, original_length, center_point):
"""
Given a span of original_length pixels, choose a starting point for a new span
of cropped_length with center_point as close to the center as possible.
In this example we have an original span of 50 and want to crop that to 40:
... | b6b51833512bcbd31076b45581a805574961235e | 649,765 |
def load_data(df, output_path):
"""Collect data.
:param df: DataFrame to print.
:param output_path: output file path
:return: None
"""
(
df
.repartition(100)
.write
.mode('overwrite')
.text(output_path)
)
return None | d11d951fad46d840788dce90180199520709c2fa | 649,766 |
def shift_box(box: list,
x: float,
y: float) -> tuple:
"""
Shift original box by coordinates.
:param box: Original box.
:param x: X shift value.
:param y: Y shift value.
:return: Shifted box
"""
return box[0] - x, box[1] - y, box[2], box[3] | 1ac92038a4e79ae6b9ef6c6bccdaaec5be3ff6d2 | 649,767 |
import numpy
import logging
def get_oil_type_cargo(cargo_info, facility, vessel_type, random_generator):
"""Randomly choose cargo oil type based on facility and vessel type
by querying information in input yaml_file.
:param dict cargo_info: Cargo oil type attribution information from the output of a
... | 8da6cf448fa198c482a7704668c1ce48a2703a77 | 649,768 |
import time
def datetime_to_timestamp_in_milliseconds(d):
"""convert a naive datetime object to milliseconds since Epoch.
"""
return int(time.mktime(d.timetuple()) * 1000) | 87cdabee20d40f399311a846444cc98d1b878fe4 | 649,769 |
def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
"""Returns True if the cubic Bezier p entirely lies within a distance
tolerance of origin, False otherwise. Assumes that p0 and p3 do fit
within tolerance of origin, and just checks the inside of the curve."""
# First check p2 then p1, as p2 ha... | 8ca693e036ef3740c55dcb49643b54852a395c5e | 649,770 |
def ncread_ts(ncvar, tidx_start=None, tidx_end=None):
"""Read in timeseries [ntime] from a netCDF variable.
:ncvar: (netCDF variable) input variable
:tidx_start: (int) starting index
:tidx_end: (int) ending index
:returns: (numpy array) timeseries data
"""
# read in profile
nsize = ncv... | e19eff9d60231f861cb842aac863cdcdd16efcc3 | 649,772 |
def _sort_dictionary(input: dict, reverse: bool = False) -> dict:
"""Rebuild a dictionary with the same keys and values but where the keys are inserted in sorted order. This can be useful for display purposes."""
sorted_keys = sorted(input, reverse=reverse)
return {k: input[k] for k in sorted_keys} | 251df6050e0b2624bbbc5360f800f5c597da9dfd | 649,773 |
def leiaDinheiro(msg):
"""
-> Valida a entrada de um valor monetário, isto é de um float com vírgula ou ponto, pelo teclado
:param msg:mensagem que será impressa na tela para a entrada de dados
:return:valor recebido
"""
while True:
numReal = False
virgPont = 0
... | 84e281dec2814188fc04339a5f6fa94dad8a34a9 | 649,774 |
def qual_to_prob(qual_score):
"""This function takes an ascii character and as an input and returns
the error probability"""
return 10**(-qual_score/10) | c97421ec5d6e52c1be926456d1f77fb4b6072a4a | 649,775 |
def add_metadata_to_production_exchanges(
data, fields=("location", "unit"), matching_fields=("name", "unit", "location")
):
"""Add metadata to exchanges based on linked activities"""
get_key = lambda x: tuple([x.get(f) for f in matching_fields])
mapping = {get_key(ds): ds for ds in data}
for ds in... | 3e2bc31f4ed8e393ee78ed9b500338fc0a9ac586 | 649,776 |
import base64
def decode_authn_string(authn_string):
"""Decodes a hexadecimal authentication string into a MongoDB connnection URI"""
return base64.urlsafe_b64decode(authn_string.encode('utf-8')).decode('utf-8') | dbc4952a140882a621c82c5f639221e60a015f89 | 649,777 |
def get_application_instance_name(application):
"""
Return the name of the application instance.
"""
return "{}-{}".format(application.image.project.name, application.name) | e877677b831740f7bd156dc840593e69e185e411 | 649,778 |
def isiterable(target):
"""
Check if target object is iterable
:param target:
:return: true if target is iterable. Otherwise, return false
"""
try:
iter(target)
except:
return False
else:
return True | c091597444c929fef99d5491f969e617526071db | 649,780 |
def obtain_psimi_to_method(cnx, key_attribute_table):
"""
Obtain dictionary uE_prot : {'psi-mi code' : 'method_name' }
"""
print('\n.....Obtaining dictionary of PSI-MI codes to Method names.....\n')
cursor = cnx.cursor()
query = (''' SELECT K.value, P.value FROM externalEntitypsimi_name ... | 304cc2695c0e4b2a09e4104349de8748b14e4af4 | 649,781 |
import logging
def load_data(data_dir, mode='train'):
"""Read the data from dir."""
filein = open(data_dir, 'rb').read().decode(encoding='utf-8')
text = []
for line in filein.strip().split('\n'):
sent = line.split() + ['<eos>']
text += sent
logging.info('Length of {} text: {} words'.format(mode, len... | 02bb85fef38b69340766c85baa5d914621122fe8 | 649,782 |
def false_positive(y_true, y_pred):
"""
Function to calculate False Positives
:param y_true: list of true values
:param y_pred: list of predicted values
:return: number of false positives
"""
# initialize
fp = 0
for yt, yp in zip(y_true, y_pred):
if yt == 0 and yp == 1:
... | fd66ca4d12c8c2896bc74b0fd45f3bcd689ab3cc | 649,783 |
from typing import List
def ls_rstrip_list(list_of_strings: List[str], chars: str = "") -> List[str]:
"""
strips list elements on the end of a list, were the value is chars
>>> testlist = ['','','a','b','c','','']
>>> ls_rstrip_list(testlist)
['', '', 'a', 'b', 'c']
>>> testlist = []
>>> l... | 0fbe830904fa828f3353b709fba0765895a8168e | 649,784 |
def apim_get(client, resource_group_name, name):
"""Show details of an APIM instance """
return client.api_management_service.get(resource_group_name, name) | f2e10eb14633efbbcb95eb0f996a9203ddc5e133 | 649,785 |
def edits1(word):
"""
Return all strings that are one edit away
from the input word.
"""
alphabet = 'abcdefghijklmnopqrstuvwxyz'
def splits(word):
"""
Return a list of all possible (first, rest) pairs
that the input word is made of.
"""
return [(word[:i]... | f37960f233bf9c4e6a6ca1d6e217104e3b4ba481 | 649,786 |
def _save_word(connection, cursor, word):
"""
保存单词数据.
:param connection:
:param cursor:
:param word:
:return:
"""
sql_str = "INSERT INTO word(word) VALUES ('%s')" % word
try:
cursor.execute(sql_str)
connection.commit()
return cursor.lastrowid
except Except... | 73aea47f0d1084b753514014c4a6ea4b066c0210 | 649,787 |
def CheckEnforcedChanges(input_api, output_api, committing, enforced):
"""Enforces changes based on the provided rules.
|enforced| is a list of 2-tuples, where each entry is a list of file
names relative to the repository root. If all of the files in
the first list have been changed, then all of the files in t... | 4e693c9aeaed7238bf20f612732105666149f5aa | 649,789 |
def list_concat(*lists):
"""
joins multiple lists into a single list. Always returns a copy.
"""
# base python: lists are concatenated with "+"
ret = list()
for l in lists:
ret.extend(l)
return ret | 10df69a98751341780b019c365bf882adf5236bc | 649,790 |
def _accept_html(accept):
"""
Returns True if the request asked for HTML
"""
return hasattr(accept, 'accept_html') and accept.accept_html() | 754da225788de57cbb2220a3f8590012bd182eb0 | 649,791 |
import subprocess
import re
def get_default_conda_env_path():
"""
Get the system's default conda environment path.
:returns: Returns either the path as a string or "0" in case no path was found.
"""
tmp = subprocess.Popen("conda info", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
... | f848c81c62c9e88d1357c52676c1cd32a6649f68 | 649,792 |
def simple_board(boards):
"""Generate the simplest board encoding
The board will be encoded into a 81-vector, with -1, 0, 1 values.
The boards are actually already given in this format
"""
return boards | 82377299a35e30d66acbb0d83db214d1d0d4174f | 649,794 |
import torch
def kl_divergence(z, mu, std):
"""
Copyright 2020 William Falcon
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.... | 520dc39570b935305d19f695613555fd58a805e6 | 649,796 |
def get_experiment_dry_run_list():
""" :return: Files expected in the experiment directory after the dry run. """
return [
"log_experiment_dryrun.txt"
] | f4fc9922192dd5ed8075a9806316675b10690970 | 649,798 |
import numpy
def centerCoordinates(coordinates, index):
"""
Center the coordinates around the given index.
:param coordinates: The coordinates of the system.
:param index: The index of the center to use as origin.
:type index: int
:returns: The coordinates centered at the specified index.
... | c70bbf7ef01627a48ad945e6a72a84aca5d90115 | 649,800 |
def _calculate_interconnected_value(vij, vik, vil, vkj, vkk, vkl, vlj, vlk, vll):
"""Calculate an interconnected S-parameter value
Note:
The interconnect algorithm is based on equation 6 in the paper below::
Filipsson, Gunnar. "A new general computer algorithm for S-matrix calculation
... | a40a2c8b49bcf475d8b8ac206fd7a93abe5545a6 | 649,801 |
def only_once(f):
"""
This isn't threadsafe, might need some guards on this later, but
it's currently only for use in setting up logging,
which is also not threadsafe.
Don't use on other things without accounting for this.
"""
has_called = False
def wrapped(*args, **kwargs):
no... | 91fed3c43690a5dba4d48f369d2a8d6f13d3bf1a | 649,802 |
import cmath
def rotate_by(z: complex, angle: float) -> complex:
"""Rotate z around the origin by an angle"""
return z * cmath.rect(1,angle) | 14952cefcf85674c659de5a8fff3970f12e26696 | 649,803 |
def mapToDict(dictShape, x):
"""
Make a dict over two lists.
Parameters
----------
dictShape : list of any
The labels of the returned dict.
x : list of any
The values of the returned dict.
Returns
-------
dict
Each key in dictShape corresponds to the value i... | 13f01062e667a029c46eb104857f40473c502a20 | 649,804 |
def lenRange(start, stop, step=1):
"""
Get the length of values for a given range
Args:
start (int):
stop (int):
step (int):
"""
return (stop - start + step - 1 + 2 * (step < 0)) // step | c0fc13bec1cf982f1a2491925e42fceafa05fd90 | 649,805 |
def get_series_from_file(path):
"""Get list of (size, cxy_time) from a CSV file"""
with open(path) as f:
f.readline() # Discard header line
series = []
for line in f:
line = line.strip()
size = float(line.split(',')[1])
time = float(line.split(',')[... | f5ff49466006cd65a4c3dc18c8bdd8fe9f93ddda | 649,806 |
def versiontuple(v):
"""Convert a string of package version in a tuple for future comparison.
:param v: string version, e.g "2.3.1".
:type v: str
:return: The return tuple, e.g. (2,3,1).
:rtype: tuple
:Example:
>>> versiontuple("2.3.1") > versiontuple("10.1.1")
>>> False
... | 4bcc9b368be4eb0d9f906e41797d2793a90c0de2 | 649,807 |
def getKeyWord(mic, question, confirmation):
"""
Asks user the supplied question, and then states the confimation question
Will run until the user confirms or cancels the keyword
"""
while True:
word = mic.ask(question)
if mic.checkForCancel():
return
mic.... | a5f13a6e8c96e2119df4138ebae793676889ea14 | 649,808 |
def _block_to_bed_line(block):
""" tchrom, trun, trun + size, tstrand, qchrom, qrun, qrun + size, qstrand, chain_id + '.' + str(bc), chain_score
:param block:
:return:
"""
return '{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\n'.format(*block) | d675fa1223d03ea93aa3301731a0451e3796942c | 649,809 |
def check_uniqueness_in_rows(board: list):
"""
Check buildings of unique height in each row.
Return True if buildings in a row have unique length,
False otherwise.
"""
for row in board:
row = row[1:][:-1].replace("*", "")
for num in row:
if row.count(num) > 1:
... | c30ea2f1de9c2afe4018913cbec96fe72923e7a3 | 649,810 |
import re
def _clean_word_name(word):
"""Cleans the text for a word name, returns None if no match
Prevents us from adding entries that are just prefixes of suffixes, e.g.
-phobia.
"""
p = re.compile('(^[\w]+[\w-]*[\w]+)')
match = p.search(word)
if match is None:
#Make sure we are... | 0ecb9f43b026dd690f9656ab2c3c3ead262c3c94 | 649,811 |
def triplets(n):
"""
>>> triplets(5)
[(1, 1, 2), (1, 2, 3), (1, 3, 4), (2, 2, 4)]
"""
return [(x, y, z) for x in range(1, n) for y in range(x, n)
for z in range(y, n) if x+y==z] | f954d98f61ab0409ff23ad64844562713d83ee0f | 649,812 |
import os
def get_architecture():
"""
Helper function to get the architecture x86_64 vs. x86.
"""
return os.uname()[4] | ac542d76531945c33c8c74c7e8e0b402bb87d091 | 649,813 |
def _gen_package(overlay, pkg, distro, preserve_existing, collector):
"""This is just a stub. We just add to the collector"""
collector.append(pkg)
# return new installer, name it.
return True, pkg | 81ee11c52a717f5d3b129c971ea9d1a2d4a83304 | 649,814 |
def expose(command=None, add_client=False):
"""
Decorator to expose a function. If add_client is True, the client
object will be added to the command list as first argument.
"""
def decorator(func):
func._toolkit_rpc = command or func.__name__
func._toolkit_rpc_param = (add_client,)
... | 2a5f7201530891816e6f87f6ddfde94208cace97 | 649,815 |
def name_with_unit(var=None, name=None, log=False):
"""
Make a column title or axis label with "Name [unit]".
"""
text = ""
if name is not None:
text = name
elif var is not None:
text = str(var.dims[-1])
if log:
text = "log\u2081\u2080(" + text + ")"
if var is no... | f37b41d88db72fb1698ce36d824cd51fdf23ac66 | 649,816 |
def get_title(title_raw):
"""
Extracts title from raw string
"""
return title_raw.replace('\xa0', ' ').split('\n')[0].split('## ')[1] | 15d4463e506a1f4b7e849ffa43aefeef9c2b9b3b | 649,817 |
def _file_resumen_headers(element):
"""
devuelve el contenido de los subelements columns en el element file_resumen
"""
ee = element.findall('column')
if ee:
tmp = [(int(e.text.strip()), e.get('header')) for e in ee]
cols = [ tmp1[0] - 1 for tmp1 in tmp ]
headers = [ tmp1[1] ... | 39e8c63942dbf0dd00d7b4d986b5914799bade45 | 649,818 |
import os
def get_all_files(path, ignore=None):
"""get all files including hidden"""
all_files = []
if ignore is None:
ignore = []
for root, _, files in os.walk(path):
for filename in files:
if filename not in ignore:
all_files.append(os.path.join(root, file... | 4b83631a3a04f17bdca83c91fc0da7f4ce1ae38e | 649,819 |
import struct
def get_init_packet(initpacketlist):
"""
uint16_t device_type
uint16_t device_rev
uint32_t app_version
uint16_t softdevice_len
uint16_t softdevice [1] (array)
uint16_t Checksum: CRC-16-CCITT for the image to transfer
"""
init_packet_format = 'HHIH' + initpacke... | 75d1d9cdf968fb9cf4079c18274755f769884d8c | 649,820 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.