content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def findTheDifference(self, s, t): # ! 118ms 遍历字符串
"""
:type s: str
:type t: str
:rtype: str
"""
return [item for item in t if item not in s or s.count(item) != t.count(item)][0] | 535f43850caba87481ff3049dd1278cd0f8e8aaa | 667,659 |
import os
def _get_iter_num(file_name):
"""
Extract number from our specified file name.
E.g., 'results_ckpt_iter_1108534.net_task_coord.txt' ---> '1108534'
"""
iter_num = os.path.basename(file_name).split('.net')[0].split('_')[-1]
return int(iter_num) | f728f2dcbb2825d1a51a07d6113044f3ef639fe5 | 667,661 |
def create_scenario_new_api(c, ui_table_name_in_db):
"""
:param c: the database cursor
:param ui_table_name_in_db:
:return:
"""
# Get and set the table caption for this table
table_caption = c.execute(
"""SELECT ui_table_caption
FROM ui_scenario_detail_table_metadata
WHER... | 69fec1a3cdf944c5cdd64af4e9c5c1b07a837dc5 | 667,663 |
from typing import List
def filter_duplicate_constructors(constructors : List[str]) -> List[str]:
"""Filters duplicate constructors based on whether it is a prefix of other constructor."""
result = []
# first sort constructors in ascending order by their length
constructors.sort(key=lambda x: le... | abb79b240f9eb0d34fe13235fa8f27c4a46ae714 | 667,664 |
def decode_path_segment(s):
"""Django decodes URL elements before passing them to views, but passes "%2f" ("/")
through undecoded.
Why..?
"""
return s.replace("%2f", "/").replace("%2F", "/") | 4d20e4a6cf8f5f1949be516f027213f482bc9018 | 667,665 |
import operator
def sortdictionary(d):
"""Sorts a dictionary."""
return sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True) | b084b82687d536d7730597daadf48e9a25090ae4 | 667,666 |
import re
def trim_xml_html_tags(data_str):
"""
Trim all HTML/XML tags and replace the special "panel" tag with a new line
:param data_str: input data string to trim
:return: Trimmed string
>>> trim_xml_html_tags('')
''
>>> trim_xml_html_tags(u'')
''
>>> trim_xml_html_tags(u'hello... | a085bc2e94a9fbf112df8e256ab101ee958e1a12 | 667,667 |
import argparse
def parse_arguments():
"""Parse command line arguments."""
parser = argparse.ArgumentParser(description="Make a custom GTF file.")
parser.add_argument("-i", "--input", help="Input GTF file.", required=True)
parser.add_argument("-o", "--output", help="Output GTF file.", required=True)
... | 7c40e435f344787bc97ac3820fc3061179e8dbb8 | 667,668 |
from pathlib import Path
def _transport_data(t):
"""Return data from "transport = data".
Transport 'file' returns a transfer directory (defaulting to
'$HOME/.CONSTELLATION/REST'.
Transport 'sftp' returns a hostname, directory tuple; the directory
defaults to '.CONSTELLATION/REST'."""
ix = t.... | 324ec3006eade25b75807f9592c71d44fa11d3f7 | 667,669 |
def nextf(f, offset=1):
"""Next token has feature f"""
def feature(s, i):
i += offset
return i < len(s) and f(s, i)
return feature | 64d1b9ff14df65497681ece4eda17dceefbf5123 | 667,670 |
def sint16_to_int(bytes):
"""
Convert a signed 16-bit integer to integer
:param bytes:
:return:
"""
return int.from_bytes(bytes, byteorder='little', signed=True) | 4ff2ddb42c7a7f9e8955bf79574cc1979650ef69 | 667,671 |
def specifier_kwargs(spec):
""" specifier kwargs
"""
_, kwargs, _, _, _ = spec
return kwargs | 5f96ecd6ad496e08a0c7f9c9a18768fc5fa1d037 | 667,672 |
def is_valid_tour(nodes, num_nodes):
"""Sanity check: tour visits all nodes given.
"""
return sorted(nodes) == [i for i in range(num_nodes)] | 7deb581c09e2d22f67c6abbb611b4a57ad6346d9 | 667,673 |
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple, E.g.
Sort on first entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 0)
>>> [(1, 2), (5, 1)]
Sort on second entry of tuple:
> sorted_by_key([(1, 2), (5,... | b0b76316d620edae4451b8521ea2090b1ede9eb7 | 667,674 |
import os
import sys
def user_entry():
"""
$WORD: word to be searched. Argparser
was not used because the gmail library
has it's own argparser instance.
"""
if 'WORD' not in os.environ:
print("ERROR - The environment variable 'WORD' was not exported")
sys.exit()
return os.e... | 968ef98e651a7773809e42e7516dd6dc3147d7ab | 667,675 |
def to_boolean(value):
"""
Utility function to convert a value to boolean.
:param value:
"""
# noinspection PyBroadException
try:
# Raises AttributeError if lower() is called on a bool.
return value.lower() == 'false'
except:
return bool(value) | a9404ae996e01b83f34e41853f92098d1c5abf31 | 667,676 |
import re
def exact_match_regex(name):
""" Convert string to a regex representing an exact match """
return '^%s$' % re.escape(name or '') | f4cdfe67b19710a970b49f1921a33d219b12ac0f | 667,677 |
import os
import torch
def get_world_size():
"""Find OMPI world size without calling mpi functions
:rtype: int
"""
if os.environ.get('PMI_SIZE') is not None:
return int(os.environ.get('PMI_SIZE') or 1)
elif os.environ.get('OMPI_COMM_WORLD_SIZE') is not None:
return int(os.environ.g... | 621d7c88cf1504fac8b51d5f192dff5aa37661da | 667,678 |
def create_attribute_filter(attribute_name: str, values: list) -> dict:
"""
Create a categorical attribute filter to be used in a trace filter sequence.
Args:
attribute_name:
A string denoting the name of the attribute.
values:
A list of values to be filtered.
R... | a450f3cbc04d45d9f32b2c1b88967c1ff88dbb6a | 667,679 |
def sort_key(attrs, node):
"""
Sort key for sorting lists of nodes.
"""
acc = 0
for i in range(len(attrs)):
if attrs[i] in node.attrs:
acc += 10**i
return acc | b431773cf18f4b99a0cc1b747681244172a78c43 | 667,680 |
def median(x):
""" Calculate sample Median without using numpy """
x = sorted(x)
m = int(len(x) / 2.0)
if len(x) % 2 == 0:
return (x[m] + x[m-1]) / 2.0
else:
return x[m] | 4def30a4522ddfdaae3add13e27995faf39486bb | 667,681 |
def list_product(combination):
"""
Calculates the product of all elements from the list.
Remark: deprecated, use geometric mean instead.
"""
score = 1
for tanimoto in combination:
score = score * tanimoto
return(score) | 984253a40fcf404c73de9f87db9c9b1bc55465b3 | 667,682 |
def get_test_response(client, method, params):
"""
Test the integration connection state
:param client: instance of client to communicate with server
:param method: Requests method to be used
:param params: Parameters for requests
:return: Test Response Success or Failure
"""
ret_val = '... | 352f8a4f007049cf9b6e215f695670c53dc69eae | 667,684 |
def do(*args):
"""
Returns the last argument passed to it. This is useful because
arguments are evaluated from left to right before a function call.
This can enable "imperative" style in a lambda expression. For example:
"""
return args[-1] | f30be4c819fb1472d80d13811e75f3dfd8a5936e | 667,685 |
def has_prefix(dict_lst, sub_s):
"""
Check if dictionary contains at least one word whose prefix equal to sub_s
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
cnt = 0
for i in range(len(dict_lst... | 9b209c89951b738c9a25805e2b6da25fc158bbd0 | 667,686 |
import re
def escape_string(string):
"""
Escape URL-acceptable regex special-characters.
"""
return re.sub('([.+*?=^!:${}()[\\]|])', r'\\\1', string) | eccce5505716711bf22cfeee715ebf86b02eb6ff | 667,687 |
import time
def utc_mktime(utc_tuple):
"""Returns number of seconds elapsed since epoch
Note that no timezone are taken into consideration.
utc tuple must be: (year, month, day, hour, minute, second)
"""
if len(utc_tuple) == 6:
utc_tuple += (0, 0, 0)
return time.mktime(utc_tuple) - tim... | c626999ce011720c95e18e6bf785bd701359b259 | 667,688 |
import numpy
def normalize(matrix):
"""Normalize matrix to a mean of 0 and standard devaiation of 1, for each dimension.
This improves numerical stability and allows for easier gradient descent.
Args:
matrix: numpy.matrix; A matrix of values.
We expect each row to be a point, and eac... | 5b89c414c4b61f64dee700f9f33ec46a3b4c1a43 | 667,689 |
def retain_symmetric(entries):
"""retain only symmetric positions"""
for type in entries.keys():
if type == 'neither':
continue
count_dict = {}
for i in entries[type]:
contig,position,context = i[:3]
try:
count_dict[context][contig][int... | 396bfc35c787f5ebca810ff930b5c44582de9730 | 667,690 |
def instance_group(group_type, instance_type, instance_count, name=None):
"""
Construct instance group
:param group_type: instance group type
:type group_type: ENUM {'Master', 'Core', 'Task'}
:param instance_type
:type instance_type: ENUM {'g.small', 'c.large', 'm.medium', 's.medium', 'c.2xlar... | b8f42f49a7cc5455cf57ce5c14d523fb85189b8f | 667,691 |
import pkgutil
def iter_namespace(ns_pkg):
"""Iterate a namespace."""
return pkgutil.iter_modules(ns_pkg.__path__, ns_pkg.__name__ + ".") | 28fc85dc38f51ce00f82f3cd4d420ceba571cc20 | 667,692 |
import pickle
def use_pretrain(name):
"""Load pretrained model
input:
name: string of gp model name
output:
model: pretrained model
"""
model = pickle.load(open("./saved_gp_models/{}.joblib".format(name), "rb"))
return model | 40f7e76b4ee9e7866e67182e55266625d4f11e31 | 667,693 |
def hasextension(fname):
"""Check if a filename has an extension"""
return fname.find('.')!=-1 | 1eb832a48e62c690c24265788ce7286ab73a5255 | 667,694 |
def get_file_text(file_path):
"""
Get the text stored in a file in a unique string (without parsing)
:param file_path: str
:return: str
"""
try:
with open(file_path, 'r') as open_file:
lines = open_file.read()
except Exception:
return list()
return lines | f1f769cd3f5fb475baf54c838e057a2bfa71bccb | 667,695 |
import os
def list_files(path, extension):
"""
This function is used to list all files having specified extension inside a given path.
:param path:
:param extension:
:return:
"""
if not isinstance(path, str):
raise TypeError("[ERROR]: 'path' must be 'str' type.")
if not isins... | 33d5e8657b086dd94df3cb656e1512fc524ab45e | 667,696 |
def _get_task_file_name(task):
"""Returns the file name of the compile task. Eg: ${issue}-${patchset}.json"""
return '%s-%s-%s.json' % (task['lunch_target'], task['issue'],
task['patchset']) | a7df31c6312da0fec18e76099af1020fdbcbe325 | 667,697 |
def _make_summary_statistic(attr):
"""Factory for making summary statistics, eg, mean, mode, stddev."""
def _fn(self):
if any(self._dist_fn_args): # pylint: disable=protected-access
raise ValueError(
'Can only compute ' + attr + ' when all distributions are '
'independent; {}'.format(... | c4bdb80403e7b1fe5fc6e5334904a905ee93c7ee | 667,698 |
import torch
def load_checkpoint(checkpoint_path: str):
"""
Loads a model checkpoint with the model on CPU and in eval mode.
:param checkpoint_path: Path to model checkpoint to load.
:return: Returns a tuple with the model, optimizer, epoch number, iteration number, and auc@0.05 of the loaded model.
... | ac275a6a6becf5b2622757fd6aa0a7eb9368ca29 | 667,699 |
def getPdbOccupancy(a):
""" return pdb atom occupancy"""
try:
return float(a[60:67])
except:
return 0.0 | 5cceca79bdcd83a83a6e2eb48f13c50b9b020deb | 667,700 |
def mod(a,b):
"""Replaces Python's modulo operator due to its use in comments"""
return a%b | aa4488cf39dd6d84eee990b4448e87126d401fc8 | 667,701 |
import codecs
def read_voca_file(file_path):
"""
Read vocabulary file
:param file_path: The path of vocabulary file
:return: vocabulary list
"""
vocas = list()
with codecs.open(file_path, "r", "utf-8") as voca_file:
for each_line in voca_file:
vocas.append(each_line.st... | 73e5e182093bcd7002feac1c3a7727d2813bc10d | 667,702 |
def MichaelisMenten(S, E0, k, K):
"""Definition for Michaelis Menten reaction with inputs E0 [mM], k [1/s] and K [mM]"""
return (-k*E0*S[0]/(K+S[0]), ) | ff1815244f94535581c456b5ea4dcb8e9139ba6d | 667,703 |
def memoprop(f):
"""
Memoized property.
When the property is accessed for the first time, the return value
is stored and that value is given on subsequent calls. The memoized
value can be cleared by calling 'del prop', where prop is the name
of the property.
"""
fname = f.__name__
... | 31249af7040cb1a05cf8f644d74ea3153b1ca1d6 | 667,704 |
from typing import Union
def _convert_params_to_array(params: dict) -> Union[dict, list]:
"""Convert a dictionary to a list of key-value pairs, unpacking
list values to their own keys. If none of the values are a list,
returns the dictionary untouched.
"""
if not any(isinstance(v, list) for v in p... | b351395715fa04ecf0148ecd70e0558f772213e1 | 667,705 |
def ciccatcodes(c):# {{{
"""
'Q17' 0 POST.DOCTORAL INT.
'Q29' -1 INTERNA DE FIN DE DOCTORADO
'Q30' -1 POSTGRADO TIPO I
'Q31' -1 POSTGRADO TIPO II
'Q32' -1 POSTGRADO TIPO I (3 AÑOS)
'Q33' -1 BECA INTERNA DOCTORAL
'Q51' 0 BECA INTERNA POSTDOCTORAL ESPECIAL
'Q52' 0 BECA INTERNA POSTD... | 1c0657ecb069f52a1b152041ce498d918d143a85 | 667,706 |
import re
def is_header(line):
"""true if we are in a header"""
if re.match('^@',line):
f = line.rstrip().split("\t")
if(len(f) > 9):
return False
return True
return False | 4bf0772ac808ddc9ad11a777961d67776dacefd9 | 667,708 |
import argparse
import ast
def parse_args():
"""
Deep Attention Matching Network Training Args. Default:Ubuntu Corpus
"""
parser = argparse.ArgumentParser("DAM Training Args")
parser.add_argument('--model_name', type=str, default="DAM_ubuntu", help='The model name.') # douban: DAM_douban
pars... | 4d504dfd5456dcefcfdd05f563e0b84e4974e50f | 667,709 |
def get_docker_job_options(job_options: dict) -> dict:
"""
Returns Docker-specific job options from general job options.
"""
keys = ["volumes", "interactive"]
return {key: job_options[key] for key in keys if key in job_options} | 418ecf5bba4dcf4ae7c7a4e813297b06d5e82bfe | 667,710 |
def last_occurrence_index(l, val, before_index=None):
"""
Find the last occurrence of some value, before_index will
not be included in the possible return value
:param l:
:param val: value to look for
:param before_index: exclusive ending of the range
:return: zero-based index
"""
... | a2e1ce2ad457f5003ac49c68a416afe5751ef187 | 667,711 |
def rename(file, newFile):
"""Renames a file, returns true/false.
:param file: string - file to rename
:param newFile: string - new filename, including the full path
Example::
success = xbmcvfs.rename(file,newFileName)"""
return bool(1) | 1b4cb8b61b2dab5a487adb6fa38dfa4ce87d8580 | 667,713 |
def octal_to_decimal(s):
"""s in form 0X<octal digits>
returns int in decimal"""
s = s[1:]
s = s[::-1] # reverse
sum = 0
for i, e in enumerate(s):
sum += (8 ** i) * int(e)
return sum | 1dcc9cf0635783a7634c9e7b228be88a622aa162 | 667,714 |
from pathlib import Path
import os
import sys
def root_path() -> Path:
""" Platform independent of finding the root directory
"""
# ? I think there's actually a standard library way of
# ? doing this.
root_str = os.path.splitdrive(sys.executable)[0]
return Path('/') if root_str == '' else Path... | da46047ce10e092b6b2bdad280bfddd1451c42b3 | 667,715 |
import os
def data_path():
"""
Get the path for the data directory.
:return: The path.
"""
if os.path.exists("data"):
path = "data"
else:
path = os.path.join(
os.path.dirname(os.path.realpath(__file__)),
"data",
)
return path | 28d38fe8ae96653dedef7056f71e78c89b1cc99b | 667,716 |
import os
import argparse
def check_existense(file_name):
"""Check file or directory name for existence."""
if not os.path.exists(file_name):
raise argparse.ArgumentTypeError("{0} is an invalid file or directory name".format(file_name))
return file_name | 94afc913caf7b909cfbe90ca6858e28a82cd84de | 667,717 |
def calc_flux(
energy,
attenuation=1.0,
photon_energy=9,
T_lenses=0.586,
T_apperture=0.75,
T_air=0.39,
):
""" "Calculate the photon flux at MID
Args:
energy (float): pulse energy in micro Joule.
attenuation (float, optional): attenuation factor through absorbers.
... | d88809f283ea798fbd3b7ded4bbfa7a0476647be | 667,718 |
def intersect_lines(line1, line2):
"""
https://stackoverflow.com/questions/3838329/how-can-i-check-if-two-segments-intersect/3838357#3838357
Thank you @ Martijn Pieters!
"""
max_f = 1.8e+300
if line2 is None: # Empty hitboxes
return False
X1, Y1 = line1[0]
X2, Y2 = line1[1]
... | 6822a117dd135854c1efee6f8354893ed312299b | 667,721 |
def is_quoted(value):
"""
Return a single or double quote, if a string is wrapped in extra quotes.
Otherwise return an empty string.
"""
ret = ""
if (
isinstance(value, str)
and value[0] == value[-1]
and value.startswith(("'", '"'))
):
ret = value[0]
retur... | 302ec7aa13a2e8c35a5aca5247b64e1eb4cbb5b7 | 667,722 |
def is_template_param(param):
""" Identifies if the parameter should be included in an input template
and returns the default value of the parameter if it exists.
"""
start = 0
ptype = 'local'
if isinstance(param, str):
param = param.strip()
if not param.split('global')[0]:
... | 762fceb18c21102d01841e48b5b926effe871c02 | 667,723 |
def progress_bar(completed, total, step=5):
""" Function returning a string progress bar. """
percent = int((completed / total) * 100)
bar = '[='
arrow_reached = False
for t in range(step, 101, step):
if arrow_reached:
bar += ' '
else:
if percent // t != 0:
... | 8d27569c0b4befa8b8949f92c7ea88333bbd09ba | 667,724 |
def _worst_ratio(df, solver, timeout, cluster):
"""
Given a df, a solver, timeout and cluster, return the number of missing
exact solutions and the worst approximation ratio.
"""
ratios = df.loc[(df['Cluster'] == cluster) &
(df['Solver'] == solver) &
(df['Time... | 859dbe18c836d43a69cd0acd2c18b5c86561a2fa | 667,725 |
import re
def get_synonyms(data):
"""Format synonyms as dicionary
exact and related synonyms are the keys, and their values are in lists
"""
if 'synonym' in data:
syn_dict = {}
exact = []
related = []
broad = []
for syn in data['synonym']:
if 'EXACT'... | 67e7a415958d49cf432f46ed9eee6b6fdd430cbf | 667,726 |
def filterResultList(phoneName,resultsList):
""" Takes in a phone name, and a list of PriceAPI search result dicitonaries. Returns a filtered list with
blacklisted sites removed (ebay, phone carries)
- only correct phones
- unlocked phones
- Price in USD
- has a set price
- returns None if th... | 94f07f262aea9c5cfa4389cf7cdb823f0e75f8a0 | 667,727 |
def list_workspaces(client):
"""Get a list of workspaces the user can access on the active server.
Args:
client (obj): creopyson Client
Returns:
list: List of workspaces
"""
return client._creoson_post("windchill", "list_workspaces", key_data="workspaces") | 82de46db12d155945e244e53ab510e392fdc3b5b | 667,728 |
import os
def out_name(arg, in_name, default_extension):
"""Determine an output name from args, input name and extension.
arg can be:
- none: return none (e.g. show image but don't store it)
- True: activate this output and determine a default name
- string:
- not a directory: use this as... | 60a59fc031f551d7d3d29aa78aa8d3eda2bc6978 | 667,729 |
import inspect
def getValidKeywords(kw, func):
""" returns a dictionary containing the keywords arguments (in a list?) valid for a function.
Parameters
----------
kw : (check)
(check)
func : (check)
(check)
Returns
-------
filename : str
Path to the audio examp... | 91db8c70892cd179eff300777107af2b4dc68879 | 667,730 |
def GetCommitCountInRegressionRange(get_repository, repo_url,
old_revision, new_revision):
"""Gets the number of commits in regression range."""
repository = get_repository(repo_url)
return len(repository.GetCommitsBetweenRevisions(old_revision, new_revision)) | 2e7343f7222dfeff4d1d3f05dfbc3a86fcc5e861 | 667,731 |
def editFile(linesIn):
"""
This function carries out the automatic file editing, adjusting lines in
Tapenade generated code as needed.
Parameters
----------
linesIn : list of string
Lines of original source code to be parsed
Returns
-------
linesOut : list of string
... | 4b5707b75950202bfdb643f89647899e06dd2b5b | 667,732 |
def add_period_cols(df):
"""
add to given `df` columns with month, day of week
and day of month based on index dates
Parameters
------------------------------------------------
`df`: pd.DataFrame
Returns
-------
pd.Dataframe
"""
df_new = df.copy()
d... | 0c43263227e363e432de8f662086e1b28bda51ac | 667,735 |
def uniqueNameEntry(dictionary, attribute):
"""function will continuously prompty user to enter a string until it is not equal to any 'attribute parameter' of a class from 'dictionary parameter'
and wil return the unique name"""
while True: #continuous loop
userEnteredName = str(input... | f863eb56fd9ad9efcb6c427af3962bfac4fc7413 | 667,737 |
def geradengleichung_zweipunkte(x1, y1, x2, y2, x):
"""Einfache Geradengleichung in Zweipunkteform"""
y = (y2 - y1) / (x2 - x1) * (x-x1) + y1
return y | a6949b1820bf7fd7e7973119a777e93cbadc521c | 667,738 |
def sequence_first(nth,term_number,common_difference):
"""Usage: Find first number from a sequence"""
return nth-(common_difference*(term_number-1)) | 8a6eeb6421da4d38bddb2d1db00a3ac2450cc1f0 | 667,740 |
def convert_ip(ip_str: str) -> float:
"""Convert innings pitched from the string representation to the float
:param ip_str: String representation of innings pitched
:returns: Float representation of innings pitched
"""
temp = ip_str.split(".")
return int(temp[0]) + int(temp[1]) * (1 / 3) | f118332b64eda55b23ce2ffef989e96326ba401e | 667,741 |
import functools
def unique(factory):
"""
Turns a factory function into a new factory function that guarentees unique return
values. Note this uses regular item equivalence to check uniqueness, so this may not
behave as expected with factories with complex return values.
Example use:
unique_n... | 50ef053df66e6795e2fb7f90ab6dfd089d795c7f | 667,742 |
def divide(input, denominator):
"""Take a string or bytes object and divide it into parts of "denominator"
length.
"""
result = []
for i in range(0, len(input), denominator):
chunk = input[i:i + denominator]
result.append(chunk)
return result | 58579718717959c0e53e7c26d3aceaa181014883 | 667,743 |
import os
def set_paths():
"""
Set the absolute path to required files on the current machine.
Returns
-------
reactionlist_path : str
path to the file `complete_reactionlist.dat`
rateconstantlist_path : str
path to the file `complet... | e388d94dff6d576d7028db0ac4f3bce15fbae559 | 667,744 |
def isletter(uchar):
"""判断一个unicode是否是英文字母"""
return (uchar >= '\u0041' and uchar <= '\u005a') or \
(uchar >= '\u0061' and uchar <= '\u007a') | d23c5272ecdb74f70028a4b64d9c51c2e5321276 | 667,745 |
def get_fun_elem_from_fun_inter(interface_list, fun_elem_list):
"""Get output_list = [[fun_elem_1, fun_elem_2, fun_inter]...] list from interface_list =
[[producer, consumer, fun_inter]...] and put value to False if (first, second, interface)
have been added to output_list (i.e. fun_elem_1/fun_elem_2 have b... | a9d8d999095a234354d66aca1e17ce31ad1cc53d | 667,746 |
import logging
def get_logger(args):
"""Creates the logger based on the provided arguments"""
logging.basicConfig()
logger = logging.getLogger(__name__)
logger.setLevel(args.log_level)
return logger | a39e7a96eceaf7d47413f996d90bb066df92232a | 667,747 |
def enhance(pattern, rules):
"""Apply the given rules to the input pattern (a list of strings.)
The output pattern is returned.
"""
assert len(pattern) == max([len(row) for row in pattern])
assert len(pattern) == min([len(row) for row in pattern])
if len(pattern) % 2 == 0:
unit = 2
... | f3cef6df6bd90d6fb7f8153ea4072a04a7ce5b79 | 667,748 |
def _parse_leaf_node_line(line):
"""
Return the leaf value given the string representation of a leaf node.
"""
return float(line.split('=')[1]) | dd6054c8c3b23a7d7fc02c97388be97a58c49be0 | 667,749 |
def side(a,b,c):
""" Returns a position of the point c relative to the line going through a and b
Points a, b are expected to be different
"""
d = (c[1]-a[1])*(b[0]-a[0]) - (b[1]-a[1])*(c[0]-a[0])
return 1 if d > 0 else (-1 if d < 0 else 0) | 569c2667f3c0fae74ec298c5a8e83ca632f82949 | 667,751 |
import os
def under_ci() -> bool:
""":return: True if we run in Jenkins."""
return 'JOB_NAME' in os.environ | 5892585945bff076ffcfd26b839465b0286e185b | 667,752 |
def onehot(indexes, N=None, ignore_index=None):
"""
Creates a one-representation of indexes with N possible entries
if N is not specified, it will suit the maximum index appearing.
indexes is a long-tensor of indexes
ignore_index will be zero in onehot representation
"""
if N is None:
... | df17a6a3b598e1086c312e3796efda7c9971f943 | 667,753 |
import posixpath
def api_path_join(*paths):
"""
Join API-style paths.
"""
return posixpath.join(*paths).strip('/') | 1034198db585049e23d7a074acb26f44c72d5d12 | 667,754 |
def binary_search(arr, key):
"""
Function to search an element 'key' in 'arr' array.
:param arr: A list of element to sort.
"""
left = 0
right = len(arr)-1
while left <= right:
mid = int(left + (right-left)/2)
if arr[mid] == key:
return mid
elif arr[mid] ... | 235cde32332fddec02dafea4f3b54d9ae51cccd5 | 667,755 |
import os
def get_api_key():
"""Get current API Key from environment"""
return os.environ.get("DYM_API_KEY") | 0d25330f54734762aab1caea44cfa5c31117819a | 667,756 |
def _dfsu_info(dfsu_object):
"""
Make a dictionary with .dfsu items and other attributes.
See class attributes
"""
itemnames = [
[
n.Name,
n.Quantity.UnitAbbreviation,
n.Quantity.ItemDescription,
n.Quantity.Item,
n.Quantity.Unit,
... | 99db1ad4e400c46073918e3aa108b1a1836897e6 | 667,757 |
def build_query(jinjafy, query, input):
"""builds neighborhood query.
:type jinjafy: `data.help.Jinjafy`
:param jinjafy: handler for jinja operations.
:type input: dict
:param input: values to be used in jinja rendering.
:rtype query: str
:param query: query after jinja rendered runs.
... | da0554de925fed89d36994438099b356c64fae20 | 667,758 |
def SIR_model(y, t, betta, gamma):
"""
Tradiional SIR model.
:param y:
:param t:
:param betta:
:param gamma:
:return:
"""
S,I,R = y
dS_dt = -betta*S*I
dI_dt = betta*S*I - gamma*I
dR_dt = gamma*I
return ([dS_dt, dI_dt, dR_dt]) | 623cb64b9c9c22ed5930bdc1fe2435178ec883d2 | 667,759 |
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs):
""" Finds the span of the knot over the input knot vector using binary search.
Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller.
The NURBS Book states that the knot span index always starts from zero, i.e. for... | 6050e7c09f290caa54bb6fb2f75082824c0faa85 | 667,760 |
def _autotuple(a):
"""Automatically convert the supplied iterable to a scalar or tuple as appropriate."""
if not hasattr(a, "__iter__"):
return a
if len(a) == 1:
return a[0]
return tuple(a) | 1e8be83634e4d026b70a5f590c75765d8bafa4ba | 667,762 |
def _loadfile(filename):
"""Returns a list of lines from `filename`"""
with open(filename, 'r') as fd:
lines = filter(lambda x: x,
map(lambda x: x.strip(), fd.readlines()))
return lines | ef11795224030a95b00ff67e021875a6d321c44c | 667,764 |
def ternary(condition, first_opernad, second_operand):
"""Same as `first_operand if condition else second_operand`"""
return first_opernad if condition else second_operand | 3d5210fbaa6fa0de0ffd4318328b2c10122254ba | 667,765 |
import pathlib
def git_path(repo_root, tail=None):
"""Returns a Path to the .git directory in repo_root
with tail appended (if present) or None if repo_root is not set.
"""
path = None
if repo_root:
path = pathlib.Path(repo_root) / ".git"
if tail is not None:
path = pat... | 6335deadff7613657ea3dcd7e5019bf863aba67d | 667,766 |
def min_max_scale(img):
"""TO BE FILLED..."""
return 2 * (img - img.min()) / (img.max() - img.min()) - 1 | 8265fd275f15daa5a96f477487cca40757d57c75 | 667,767 |
def read_labels(file_name):
"""
Read list of labels from file like this:
label1
label2
label3
...
"""
labels_tmp = []
try:
with open(file_name, 'r') as f:
labels_tmp = f.readlines()
labels_tmp = [(i.rstrip(), 0) for i in labels_tmp]
... | 247807c6a7a5e452b7bdb8a3874aabc889ef1ec9 | 667,768 |
def bare_spectrum(sweep, subsys, which=-1, **kwargs):
"""
Plots energy spectrum of bare system `subsys` for given ParameterSweep `sweep`.
Parameters
----------
sweep: ParameterSweep
subsys: QuantumSystem
which: int or list(int), optional
default: -1, signals to plot all wavefunction... | a441f5e838092aff6b7328c25d18357570d59c35 | 667,769 |
import torch
def accuracy(outputs, labels):
"""
Calculate model accuracy
* :param outputs(torch.tensor): Pytorch weights tensor
* :param labels(list(str)): List of known labels
:return (torch.tensor): Prediction accuracy
"""
_, preds = torch.max(outputs, dim=1)
return torch.te... | 737c5d82d0cec4955a47cfb879e6f1e0048f3408 | 667,770 |
def Salidas_Capa(Capa, xtrain):
"""Funcion que realzia el flujo hacia adelante en la red neuronal"""
Salida=[0]*len(Capa)
Tipo_Capa=Capa[0].num_entr
if Tipo_Capa==1:
for i in range(len(Capa)):
Salida[i]=Capa[i].Fordware(xtrain[i])
else:
for i in range(len(Capa)):
... | 3cdcc5dcfba945dd7188e50eee97bf5b7ac4de14 | 667,771 |
def attn(card, mode=None, files=None, seconds=None, payload=None, start=None):
"""Configure interrupt detection between a host and Notecard.
Args:
card (Notecard): The current Notecard object.
mode (string): The attn mode to set.
files (array): A collection of notefiles to watch.
... | 0f5313f56dfb91f407bdd5b428baf0890ebb9597 | 667,773 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.