content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def gaussian_preferences(coords, sizes, scales, rstate=None):
"""
Generate gaussian preference distributions at coordinate and specified size
Parameters
----------
coords : array shaped (a, b)
Centroids of a faction voter preferences.
- rows `a` = coordinate for each ... | a48e0667d3e8f3ec8bc9893827875a0e60280030 | 3,612,500 |
def load_image(raw_path):
"""
Function loads images from a list of file paths into ndarrays
Params:
-------
raw_paths (str) -- Paths to the image files
"""
# Iterate through each path in list, load image, and store in an array
start = raw_path.find(FOLDER)
suffix = raw_path[start:]
img_path = DATA_DIR + '/... | c4dcd1896406c12f0914c8507c8a465cddbf2c18 | 3,612,501 |
def show_edit_sample_for_sampleset(request, sampleSetItemId):
"""
show the sample edit page
"""
logger.debug("views.show_edit_sample_for_sampleset sampleSetItemId=%s; " % (str(sampleSetItemId)))
sampleSetItem = get_object_or_404(SampleSetItem, pk=sampleSetItemId)
return show_samplesetitem_modal... | 5157612549c795c8825648f54a3064a60700d1b6 | 3,612,502 |
def hp_qloguniform(min, max, q):
""" Quantized log uniform (base 10) distribution with a quantum of q, bounded by min and max. Returns a
value like round(exp(uniform(low, high)) / q) * q.
:param min: Exponent of the minimum value in base 10 (e.g., -4 for 0.0001).
:param max: Exponent of the maximum va... | b6d250e29f63c6bf5d621c88e408c85b9446d505 | 3,612,503 |
def display_account():
"""
function to display existing account
"""
return User.display_account() | 80e77505df1c663028228e1282dd96e70b93e29c | 3,612,504 |
def mols_to_pngs(mols, basename="test"):
"""Helper to write RDKit mols to png files."""
filenames = []
for i, mol in enumerate(mols):
filename = "BACE_%s%d.png" % (basename, i)
Draw.MolToFile(mol, filename)
filenames.append(filename)
return filenames | 7fa9079a083a396acdac9c784b085bf6824528d7 | 3,612,505 |
def create_game():
"""Post a new game result to the database."""
game = validate_game_submission(request.headers, request.json)
db.session.add(game)
db.session.commit()
print("New game: %s " % str(game))
return jsonify(game.to_dict()), 201 | 5468c35556c2976134c7b0ac857d4832e51f7d24 | 3,612,506 |
def rep1(arg):
"""
Matches one or more occurrences of 'arg'.
"""
assert isinstance(arg, ContentModel)
arg.quant = ContentModel.QUANT_PLUS
return arg | 69147eaac824a5d53832d3b5233fb845f42a52d4 | 3,612,507 |
import re
def _search_host(host=None, domain=None,
username=None, password=None, **kwargs):
"""Find invalid customer routes received by host."""
result = []
driver = napalm.get_network_driver("ios")
try:
with driver(hostname="{}.{}".format(host, domain),
us... | 42b784b334435d24ff39aa53099ac3ab6c416deb | 3,612,508 |
import scipy
def wilcoxon(x,y):
"""
One-sided wilcoxon sign-rank test.
p-value is small if \EE x >> \EE y.
"""
d = np.array(x)-np.array(y)
d = np.compress(np.not_equal(d,0), d, axis=-1)
n = len(d)
inds = np.argsort(np.abs(d))
sign_diff = np.sign(d)
W = np.sum([sign_diff[inds[... | e839bb205a294f2227b0dc400351921bc289d982 | 3,612,509 |
from typing import Iterable
from typing import Sequence
def bucket(
nodes: Iterable[BaseNode],
contraction_order: Sequence[network_components.CopyNode]
) -> Iterable[BaseNode]:
"""Contract given nodes exploiting copy tensors.
This is based on the Bucket-Elimination-based algorithm described in
`arXiv:q... | be5f2e1683886a5a09118df6e0316148fcd37be8 | 3,612,510 |
def contains_charset(s: str) -> bool:
"""Judge if given str is a valid charset name, return a boolean.
The str could be charset name like 'utf-8' and the code page number
like '65001'. Letter case ignored."""
return EncodingInfo._all_charsets_lower_cased_name.__contains__(s.lower()) | 57637e0161ac9b8a0a043dfd10ead799f95eec44 | 3,612,511 |
def prioritize_file_types(k):
""" Give a proper priority to certain file types when sorting """
# BN databases should always go first
if k.endswith('.bndb'):
return 0
# Definition files matter more than raw files
if any(k.endswith(e) for e in ('.def', '.idt')):
return 5
return 10 | 97bb9f0257c81d0640c45961c8fd68fe2e1eaee2 | 3,612,512 |
def cvar_importance_sampling_biasing_density(pdf, function, beta, VaR, tau, x):
"""
Evalute the biasing density used to compute CVaR of the variable
Y=f(X), for some function f, vector X and scalar Y.
The PDF of the biasing density is
q(x) = [ beta/alpha p(x) if f(x)>=VaR
[ (1-b... | 8ad888bf1445fd4666385938b1f2e1125e30eeb2 | 3,612,513 |
import os
def is_descendant(path, start):
"""
pathはstartのサブディレクトリにあるか。
ある場合は相対パスを返す。
"""
if not path or not start:
return False
rel = join_paths(relpath(path, start))
if os.path.isabs(rel):
return False
if rel.startswith("../"):
return False
return rel | 4c74535b4946e6ef100251bba5c276bac1fb9882 | 3,612,514 |
import sys
import logging
def get_logger(log_file: str = 'nineturn.log', level_to_file: str = 'INFO'):
"""Return the nineturn logger. Not for used by library users."""
LOGGING = {
"version": 1,
"disable_existing_loggers": "false",
'filters': {'exclude_errors': {'()': _ExcludeErrorsFilt... | de2100683bce26cd7769cb0f4a5cbb826cb8a768 | 3,612,515 |
import numbers
def transforms_treeleaffeaturizer(
data,
predictor_model,
output_data=None,
model=None,
suffix=None,
label_permutation_seed=0,
**params):
"""
**Description**
Trains a tree ensemble, or loads it from a file, then maps a numeric
... | e28f90be69a862a058f802abb46b16c0e77e0497 | 3,612,516 |
from sage.functions.other import imag_part
def _sympysage_im(self):
"""
EXAMPLES::
sage: from sympy import Symbol, im
sage: assert imag_part(x)._sympy_() == im(Symbol('x'))
sage: assert imag_part(x) == im(Symbol('x'))._sage_()
"""
return imag_part(self.args[0]._sage_()) | 5dd609581d542205676acbe038e38c47eaa3828a | 3,612,517 |
async def fetch(url: str, session: network.Session) -> Comment:
"""
Asynchronously fetch a single comment to a deviation.
Args:
url: The URL to a comment.
session: A session to use for requesting data.
Returns:
A single comment.
Raises:
BadCommentPageError: If inst... | 0f941ffa7f08897aa3ba9d34876597a3bcc2dc0b | 3,612,518 |
from typing import Optional
from typing import Iterable
from typing import Any
def updater_fields(
fields: Optional[Iterable[str]] = None,
null_fields: Optional[Iterable[str]] = None,
updater_flag_preffix="update_",
**kwargs: Any,
) -> dict[str, Any]:
"""
Prepares the specified fields in **kwa... | 2f205aa8c94522a3cb82e63f3bbcb45df7fe11cf | 3,612,519 |
def reduce_angle(angle: Real) -> float:
"""
Move angle in radians to range (-π, π]
"""
if -PI < angle <= PI:
return angle
n = angle / TWOPI
n = ceil(n) if n < 0 else floor(n)
return angle - n * TWOPI | 8f02b1deba4ad729f4db20fc36b14bd7093773a2 | 3,612,520 |
def getATR(reader):
"""Return the ATR of the card inserted into the reader."""
connection = reader.createConnection()
atr = ""
try:
connection.connect()
atr = smartcard.util.toHexString(connection.getATR())
connection.disconnect()
except smartcard.Exceptions.NoCardException:
... | 3a690d1a4ddc9e8af70865511b76bab251984c7d | 3,612,521 |
def create_cnn_model(size_output=None, tf_print=False):
"""
create keras model with convolution layers of MobileNet and added fully connected layers on to top
:param size_output: number of nodes in the output layer
:param tf_print: True/False to print
:return: keras model object
"""
if s... | 67fd4b7ddef1cfd444993aa8a17a5ae13822f141 | 3,612,522 |
def get_vertex_ids(g, my_query, my_query_annot_field, row_or_col):
""" Extract vertices with the values in my_query in my_query_annot_field.
If row_or_col is "row", my_query will only be searched for in row vertices.
If row_or_col is "col", my_query will only be searched for in column
vertices. If row_o... | dc93142c4a7b33e950a8f238647809964bb288b0 | 3,612,523 |
def data_preparation_fr(country_attributes,reversed_dates=True):
"""
Creates an sorted dictionary of dates, new cases and tests for the French Covid-19 data
Parameters
----------
country_attributes : dict
A dictionary containing country attributes
reversed_dates : bool
A boolean... | a8e333185294dec5bed3238da3b08550f4cb8dbd | 3,612,524 |
import types
import ast
def get_segment_from_frame(caller_frame: types.FrameType, segment_type, return_locs=False) -> str:
"""Get a segment of a given type from a frame.
*NOTE*: All this is rather hacky and should be changed as soon as python 3.11 becomes widely
available as then it will be possible to g... | 3cf1c461611e5583ca588c0fbd326889e8d3d747 | 3,612,525 |
def distribute_mpi_all(dimension, mpi_comm=MPI.COMM_WORLD):
"""
Computes the start indexes and bin sizes of all splits to distribute
computations across an MPI communicator.
Parameters
----------
dimension : int
the size of the array to be distributed
mpi_comm : mpi4py.MPI.Comm, opt... | a5a1c404460927ff15e1026e29bbc07330ebea1f | 3,612,526 |
def gradient_cmap(colors, nsteps=256, bounds=None):
"""Return a colormap that interpolates between a set of colors.
Ported from HIPS-LIB plotting functions [https://github.com/HIPS/hips-lib]
"""
ncolors = len(colors)
# assert colors.shape[1] == 3
if bounds is None:
bounds = np.linspace(... | 01cf002e041b90abc90e1400fcc03b6375cdc4e5 | 3,612,527 |
import sys
def get_profile(sqshrc="~/.sqshrc", connector='Sybase',
hostname=None, username=None, password=None):
"""
get database, username, password from .sqshrc file e.g.
\set username="user"
"""
if connector == 'Sybase':
shost, suser, spass = None, None, None
_ =... | 924b2064f3cee042bb6303e223f1586676a8492b | 3,612,528 |
def confounder_ppca(X, latent_dim, holdout_portion):
"""
Function to estimate a substitute confounder using PPCA.
Adopted from the deconfounder_tutorial.ipynb
https://github.com/blei-lab/deconfounder_tutorial
Args:
X: A numpy array or pandas dataframe of the original covariates
d... | 70a31c1942ce3db50a95b0eae781493c6d4ab77e | 3,612,529 |
from typing import Tuple
import shutil
def create_job(user_folder: str, user_id: str, upload_file: str) -> Tuple[str, str, str]:
"""Upload several files and check they are properly created - utils method."""
file_service.setup_jobs_result_folder(user_id=user_id, job_id='test-job')
job_run_folder = join(us... | be02f87bdab1a2ba256a68c9d37f8f05c2728884 | 3,612,530 |
def get_vserver(svm_cx, vserver_name):
"""
Return vserver information.
:return:
vserver object if vserver found
None if vserver is not found
:rtype: object/None
"""
vserver_info = netapp_utils.zapi.NaElement('vserver-get-iter')
query_details = netapp_utils.zapi.NaElement.cre... | ae5972ea2c3ba354b9ee4589633b53839a0399b7 | 3,612,531 |
def saveData(dataset={}, filepath= 'defaultFilePath'):
"""
Saves the 'DATA' component of a dataset as an ascii file
in XAYAcore graph format.
"""
return xayacore.writeGraph(dataset['DATA'], filepath) | 3d73f492014861f2b3b488a638285813bdeca31a | 3,612,532 |
def _move_cols_to_front(data: pd.DataFrame, column_count: int = 1) -> pd.DataFrame:
"""
Move N columns from end to front of DataFrame.
Parameters
----------
data : pd.DataFrame
The input DataFrame
column_count : int, optional
The number of columns to move (the default is 1)
... | ee03bbfa24d06aab1a6f2d5c987a2e11c58cdafd | 3,612,533 |
def qual_vector(qual=None, capBQ=45, minBQ=0.25):
"""convert the base call quality score to related values for different genotypes
http://emea.support.illumina.com/bulletins/2016/04/fastq-files-explained.html
https://linkinghub.elsevier.com/retrieve/pii/S0002-9297(12)00478-8
@Note The parameter "q... | 42f8f4f3c038aa11a96683983cb220f710617e8b | 3,612,534 |
def load_runner(
tag: t.Union[str, Tag],
*,
predict_fn_name: str = "predict",
device_id: str = "CPU:0",
predict_kwargs: t.Optional[t.Dict[str, t.Any]] = None,
resource_quota: t.Union[None, t.Dict[str, t.Any]] = None,
batch_options: t.Union[None, t.Dict[str, t.Any]] = None,
model_store: "... | 1d7a8b4c12990d33c2d7d99d05c3843f35476ee0 | 3,612,535 |
def random_uuid() -> str:
"""description of random_uuid"""
return str(uuid4()) | b23c6a9f180f757af6a484ba91a0d9b6a820dc3d | 3,612,536 |
def _parse_see_args(dev_id, data):
"""Parse the payload location parameters, into the format see expects."""
kwargs = {
'gps': (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
'dev_id': dev_id
}
if ATTR_GPS_ACCURACY in data:
kwargs[ATTR_GPS_ACCURACY] = data[ATTR_GPS_ACCURACY]
if... | fb159ef6dee3a42ae433262382d5ddca87c7bf6b | 3,612,537 |
def _updateStartTimes(srow, delayDF, temkey):
"""
Update the starttimes to reflect the values trimed in alignement
"""
statsdict = srow.Stats
sdo = srow.Stats
for key in sdo.keys():
temtemkey = temkey.loc[temkey.NAME == key].iloc[0]
delaysamps = delayDF[delayDF.Events == key].ilo... | b72754a57eae43442b9f0f2df796b7128c36ee8b | 3,612,538 |
def playlist_detail(playlist_id, limit=1000):
"""
根据歌单id获取歌单的详情
Args:
playlist_id:
limit:最大歌曲数为1000
"""
for i in range(retry_times):
try:
base_url = 'http://music.163.com/api/playlist/detail?id=%s&limit=%s' % (playlist_id, limit)
res = requests.get(ba... | ea7c5e747186bef78e8346255ffbf4b41c85909f | 3,612,539 |
def checksum(s, m):
"""Create a checksum for a string of characters, modulo m"""
# note, I *think* it's possible to have unicode chars in
# a twitter handle. That makes it a bit interesting.
# We don't handle unicode yet, just ASCII
total = 0
for ch in s:
# no non-printable ASCII chars, including space... | 836e0f36ed3d87db8d3f2420230eb4f3f5d4d94c | 3,612,540 |
import os
def validate_path_file(path_file) -> bool:
"""Validate th path of a file."""
if os.path.exists(path_file) and os.path.isfile(path_file):
if os.access(path_file, os.R_OK):
return True
return False | be43216006f21abac9dfeffc840a33160ffba95e | 3,612,541 |
def vol_std(data):
""" Return standard deviation across voxels for 4D array `data`
Parameters
----------
data : 4D array
4D array from FMRI run with last axis indexing volumes. Call the shape
of this array (M, N, P, T) where T is the number of volumes.
Returns
-------
std_... | 64a031026d609ca759634308e1f70c4c24c34cb9 | 3,612,542 |
def parse_component_arg(parser, storage: Storage, component: str):
"""Wrapper around parse_storage_component() to parse CLI arguments into patch elements"""
try:
component = parse_storage_component(storage, component)
except ValueError:
parser.error(f"invalid component: {component}")
if ... | f3e4764354c5c5f1c6e0574259cc5fce963d1a2b | 3,612,543 |
from typing import ChainMap
def parse_flags(flags={}, preset="", **other) -> "int":
"""
Optimised for "parse_flags(**settings)" use-case,
returns a flags integer suitable for view.add_regions.
"""
preset = presets[preset].get("flags", {})
orsum_flags = 0
for flag_name, active in ChainMap(flags, preset, dict.... | 8a1dac9dd330ab583a0a16a42c78d7a4c7360ccd | 3,612,544 |
import os
def osPrefix():
"""Returns system prefix
Args:
No args
Returns:
linux/windows
Raises:
Nothing
"""
name = os.name
if name == "posix": return "linux"
return "windows" | 1acf588dc766e470c4bab90ea9c621a30c6695f0 | 3,612,545 |
def _get_uniprot_id(agent):
"""Get the Uniprot ID for an agent, looking up in HGNC if necessary.
If the Uniprot ID is a list then return the first ID by default.
"""
up_id = agent.db_refs.get('UP')
hgnc_id = agent.db_refs.get('HGNC')
if up_id is None:
if hgnc_id is None:
# I... | f59b19f86a2d8d48fa271f64892ec7453c98ec9e | 3,612,546 |
def adv_rk2(y, t, dt, scratch1, scratch2):
"""Advance the solution one step using the 2nd order R-K method"""
n = len(y)
scratch1 = rhs(y, t)
for i in range(n):
scratch2[i] = y[i] + dt*scratch1[i]
t2 = t + dt
scratch2 = rhs(scratch2, t2)
for i in range(n):
y[i] = y[i] + 0.5*d... | 3ee8051c08fcdb78715a20e0a6e90334e6054ac6 | 3,612,547 |
import sys
def _get_arg(num):
"""
:return:
A unicode string of the requested command line arg
"""
if len(sys.argv) < num + 1:
return None
arg = sys.argv[num]
if isinstance(arg, byte_cls):
arg = arg.decode('utf-8')
return arg | 79579ddbf292e1930ccbdec8aafdd149d87cc2af | 3,612,548 |
def calc_distance_matrix(mols):
"""
Calculate a full distance matrix for the given molecules. Identical molecules get a score of 0.0 with the maximum
distance possible being 1.0.
:param mols: A list of molecules. It must be possible to iterate through this list multiple times
:return: A NxN 2D array... | cb3c977de43dd5fda649bc06aad98298cf6cba25 | 3,612,549 |
import os
def fetch_environment(file_path, file_id, module_id):
"""Return file environment dictionary from *file_path*.
*file_id* represent the identifier of the file.
*module_id* represent the identifier of the module.
Update the *environment* if available and return it as-is if the file
is no... | 2f93f8a78d4793f7c02cb43acef17fdeeab106f2 | 3,612,550 |
from pathlib import Path
def retrieve_token() -> str:
"""Retrieves token from BEARER_TOKEN_PATH"""
bearer_file_path = Path(BEARER_TOKEN_PATH)
if not bearer_file_path.is_file():
with login_lock:
if not bearer_file_path.is_file():
return login()
with bearer_file_path.... | c6982f74f7ba716bb9d2d9481ce0c22a237f3e82 | 3,612,551 |
def classification_phi_gradient(input_to_class, data):
"""
This is about a very simple model: there's an input layer, and a softmax output layer. There are no hidden layers, and no biases.
This returns the gradient of phi (a.k.a. negative the loss) for the <input_to_class> matrix.
<input_to_class> is a ... | 4762e8d69f4473c1a0089cd2263a9b2dc0a1b508 | 3,612,552 |
import urllib
def getData(stops):
"""Retrieves data from the MTA's realtime feed, then creates a train object for each
train described in the feed and stores each train object in a master list.
"""
feed = gtfs_realtime_pb2.FeedMessage()
response = urllib.urlopen('http://datamine.mta.info/mta_esi.p... | aae39c253b24d7df00cb4f981fc7d0263dfe8088 | 3,612,553 |
def ringing(img2d, alpha=0.5, noiseSize=0, noiseValue=2, clip=True, seed=None):
"""
https://bavc.github.io/avaa/artifacts/ringing.html
:param img2d: 2d image
:param alpha: float, reconstruction quality (0-1) optimal values for tv ringing modeling is 0.3-0.99
:param noiseSize: float, noise size (0-1... | 2b7db2383eba12c20b0701d7a126c4e91066bee7 | 3,612,554 |
from typing import Sequence
from typing import List
from typing import cast
def try_rules(
context: Sequence[Expression],
goal: Expression,
general_rules: Sequence[Expression],
verbosity: int = 0,
) -> List[Expression]:
"""context and context_rules are disjoint, all in context_rules satisfy
is... | 6bfe3b3e46d5591f3a68ab9d6cf68eeacf4f8ca2 | 3,612,555 |
def dissimilarity_loss(latents, mask):
"""
Minimize the similarity between the different instrument latent representations
Arguments:
latents {torch.tensor} -- latent matrix from the encoder of shape: (B, 1, T', N)
mask {torch.tensor} -- boolean mask: True when the signal is 0.0; shape (B, ... | 988e86a535f70425975f178c3dbcd396b340990e | 3,612,556 |
def _stdin_ready_other():
"""Return True, assuming there's something to read on stdin."""
return True | 934e97ba18f9f60ad8e2d77f227dd98b70891b56 | 3,612,557 |
def text_objects(text, font, color):
"""
Function for creating text and it's surrounding rectangle.
Args:
text (str): Text to be rendered.
font (Font): Type of font to be used.
color ((int, int, int)): Color to be used. Values should be in range 0-255.
Returns:
Text surf... | a9ed3d8a68c80930e2594b4dbef06e828de10513 | 3,612,558 |
from typing import List
def split_list(a: List, chunk_size: int):
"""
split a large list to small chunk with the specified size
:param a:
:param chunk_size:
:return:
"""
chunks = []
list_length = len(a)
start_pos = 0
end_pos = start_pos + chunk_size
while end_pos <= list_l... | 24ec6e5c2a86deabb4abb9fd1c8e6a0f86cfb7ed | 3,612,559 |
import logging
def prepare_logger(logger_name, verbosity, log_file=None):
"""Initialize and set the logger.
:param logger_name: the name of the logger to create
:type logger_name: string
:param verbosity: verbosity level: 0 -> default, 1 -> info, 2 -> debug
:type verbosity: int
:param log_fi... | bd52f514f97c4c86925f29f42aa89b610f739818 | 3,612,560 |
def process_results(news_list):
"""
Function that processes the news result and transform them to a list of Objects
Args:
news_list: A list of dictionaries that contain news sources
Returns :
news_results: A list of news objects
"""
news_results = []
for news_item in news_l... | 0d2f5b3ca85d7b6aec770bc71de9f1ef749915d7 | 3,612,561 |
def slice_slice(old_slice, applied_slice, size):
"""Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
"""
step = (old_slice.step or 1) * (applied_slice.step or 1)
# For now, u... | 97cbf20100da58e3d6712b7fa9d9a2fb04c3322f | 3,612,562 |
import os
import toml
def load_spec():
"""Attempts to load the local build specification"""
if not os.path.exists(CONFIG):
raise SpecException("Config file not found: Please create" +
" '{}' in your project directory".format(CONFIG))
else:
spec = toml.load(CONFIG)
miss... | f0b3c2807915e51e445548d190b987ce4aff9913 | 3,612,563 |
import re
def _parse_compile_log(log):
"""parses the pdflatex compile log"""
if log is None:
return {}
IMAGES = {}
i = 0
image_found = False
for line in log.split('\n'):
if not image_found:
m = re.match("^File: (.*) Graphic file", line)
if m:
... | a3888ed3d2664866d47265f2c06720a8a3e757df | 3,612,564 |
def is_correct(list):
"""
判断一个list中单词是否正确
:param list:待识别的单词列表
:return: 正确的单词列表
"""
temp = []
rightlist = spell.known(list) # {'morning'}
global count
global num
count = count + len(list) - len(rightlist)
num = num + len(list)
for item in rightlist:
temp.append(item)... | 2a0e09b009c13b03810979c903969e2b4719879c | 3,612,565 |
def spellcheck(request):
"""
Spellcheck some POST data.
"""
jsondata = request.POST.get("data")
print "Spellcheck data: %s" % jsondata
if not jsondata:
return HttpResponseServerError(
"No data passed to 'spellcheck' function.")
data = json.loads(jsondata)
aspell =... | 80f50c26f4f777499018af02e8ad2939d0eb1af2 | 3,612,566 |
def contains(value, lst):
""" (object, list of list of object) -> bool
Return whether value is an element of one of the nested lists in lst.
>>> contains('moogah', [[70, 'blue'], [1.24, 90, 'moogah'], [80, 100]])
True
"""
found = False # We have not yet found value in the list.
for i in... | 9d3690943c05b4220afabfa65402b7f12c1cb279 | 3,612,567 |
import re
def filter_component_names(raw_npm_list):
"""Filter the raw NPM list to get list of proper component names."""
pattern = re.compile("^[0-9]+.")
components = []
for line in raw_npm_list.splitlines():
if pattern.match(line):
try:
i1 = line.index("[")
... | 7d8a102781a32ddd263d1c4364f261e6f1191e70 | 3,612,568 |
def dispImg(img):
"""
This does the min-max scaling the images to 0 and 1
"""
try:
h, w, d = img.shape
img_tmp = (img - np.min(img)) / (np.max(img) - np.min(img))
plt.matshow(img_tmp)
plt.show(block=False)
except ValueError:
try:
h, w = img.shape
... | b93bcbd644026cbb51082a2a3314d2340f8db278 | 3,612,569 |
import os
def get_all_matches(sub, twod, match_constraints, write_all=False):
"""
Returns all matches as a list of pymatgen structure objects
Writes all of them as POSCAR files in a directory 'all_interface_poscars'
"""
# variables from the keys
max_area = match_constraints['max_area']
max... | e9644a2a79c512e2398fca48a213e96eae07b45d | 3,612,570 |
import urllib
def download_metadata_file_for_1minute_data(metadatafile: str) -> BytesIO:
""" A function that simply opens a filepath with help of the urllib library and then writes the content to a BytesIO
object and returns this object. For this case as it opens lots of requests (there are approx 1000 differ... | 9fafc7c72c2b35055bbcc62b60254c01e442233d | 3,612,571 |
def check_format_input_obj(
inp,
allow: str,
recursive=True,
typechecks=False,
) -> list:
"""
Returns a flat list of all wanted objects in input.
Parameters
----------
input: can be
- objects
allow: str
Specify which object types are wanted, separate by +,
... | 306075bc72c1f79dc1e47997b8bcee33a3ee240f | 3,612,572 |
def sleeper(sleep_time):
""" Function to execute in parallel.
"""
sleep(sleep_time)
return {"sleep_time": sleep_time} | 4b158988eefc6300d02e2c1f110bfb842b0f3679 | 3,612,573 |
import os
import re
def get_bias(config, logtable):
"""Get bias image.
Args:
config (:class:`configparser.ConfigParser`): Config object.
logtable (:class:`astropy.table.Table`): Table of Observing log.
Returns:
tuple: A tuple containing:
* **bias** (:class:`numpy.nda... | 2098a1ea557b201f61a6e501d531b3be6accb271 | 3,612,574 |
def get_login_server_suffix(cli_ctx):
"""Get the Azure Container Registry login server suffix in the current cloud."""
try:
return cli_ctx.cloud.suffixes.acr_login_server_endpoint
except CloudSuffixNotSetException as e:
logger.debug("Could not get login server endpoint suffix. Exception: %s"... | 056cf67847f9c0272662a2b3fc3019e926095b27 | 3,612,575 |
import random
def construct_sent(word, table):
"""Prints a random sentence starting with word, sampling from
table.
>>> table = {'Wow': ['!'], 'Sentences': ['are'], 'are': ['cool'], 'cool': ['.']}
>>> construct_sent('Wow', table)
'Wow!'
>>> construct_sent('Sentences', table)
'Sentences ar... | 238a0391b104d15db50d33904308c827851ffb62 | 3,612,576 |
def process_sources(source_list):
"""
We now want to process the dictionary and
output a list of objects - news_results.
We process results will transform our dictionary into a list of objects.
"""
news_results = []
for source in source_list:
id = source.get('id')
print(id)
... | 47f5acfb5e98ca71b8c2605cb38229ba910d4b36 | 3,612,577 |
def _preprocess(expr, func=None, hint='_Integral'):
"""Prepare expr for solving by making sure that differentiation
is done so that only func remains in unevaluated derivatives and
(if hint doesn't end with _Integral) that doit is applied to all
other derivatives. If hint is None, don't do any different... | 49ff4fdce77f64a9e1f48d46b09452f88a8fcd1f | 3,612,578 |
def read_lisp_filter(path):
"""Reads a lisp filter from a file.
For example:
(> (/ (+ (- (field "00000") 4.4)
(field 23)
(* 2 (field "Class") (field "00004")))
3)
5.5)
"""
return read_description(path) | 411027ca42d6e81bc149ab1186bed5c21212195e | 3,612,579 |
def team_games(results, team='Northeastern'):
"""
Collect all games by given team.
Parameters
----------
results : TYPE
DESCRIPTION.
team : TYPE, optional
DESCRIPTION. The default is 'Northeastern'.
Returns
-------
teamGames : TYPE
DESCRIPTION.
"""
... | 93a7260cdb97cd1ac19348af3908010905953e6c | 3,612,580 |
import time
def sparse_rec_pogm(gradient_op, linear_op, prox_op, cost_op=None,
max_nb_of_iter=300, metric_call_period=5, sigma_bar=0.96,
metrics={}, verbose=0):
"""
Perform sparse reconstruction using the POGM algorithm.
Parameters
----------
gradient_op: i... | db168e6484727b99ebc5de8b22e167f0493cd303 | 3,612,581 |
def get_dataset_phase(prefixf):
"""
Return the execution time dataset
from a folder "prefixf" and return the
execution time for the phases
Also filter out the zero values.
"""
#start_time = timeit.default_timer()
tmp = pd.read_csv(prefixf+"/dataset_ph1.cs... | 759773a4ad4d5438d85526351c0cbaac30d3e89c | 3,612,582 |
import logging
def autocomplete_switches(
service_switches,
specified_tech_enduse_by,
s_tech_by_p,
enduses,
sectors,
crit_all_the_same=True,
regions=False,
f_diffusion=False,
techs_affected_spatial_f=False,
service_switches_from_capacity=... | 486b0ab5a8dc2630921a042f5bc729a209234cdc | 3,612,583 |
def UnbiasPmf(pmf, label=''):
"""Returns the Pmf with oversampling proportional to 1/value.
Args:
pmf: Pmf object.
label: string label for the new Pmf.
Returns:
Pmf object
"""
new_pmf = pmf.Copy(label=label)
for x, p in pmf.Items():
new_pmf.Mult(x, 1.0/x)
... | 1146d952bbac0ef3031e3259d98e0f343103598e | 3,612,584 |
def constant_init(value=0):
""" Constant Initializer
The resulting tensor is populated with values of type dtype, as specified by arguments value
following the desired shape.
The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length
of the l... | fc9788f68a9fe3a2bd96b52ff2c153a237ce6bb2 | 3,612,585 |
def ConfusionMatrix(ftrue, fpred, nf):
"""
CONFUSION MATRIX
Computes the confusion matrix of a discrete classification.
Written by Dario Grana (August 2020)
Parameters
----------
ftrue : array_like
true model
fpred : array_like
predicted model
nf : int
nu... | 332fa870544a3bbcfc842a78e6840837ed19a0ab | 3,612,586 |
def drop_na_1d(df, axis=0, how='all'):
"""
:param df:
:param axis: int;
:param how:
:return:
"""
if axis == 0:
axis_name = 'column'
else:
axis_name = 'row'
if how == 'any':
nas = df.isnull().any(axis=axis)
elif how == 'all':
nas = df.isnull().al... | c321191150208cddc49a150aa08f5f1e452f74dd | 3,612,587 |
def solve_1(x):
"""Returns the checksum (sum of the difference between the biggest and smallest number in each row)"""
return sum(map(get_diff, format_input(x))) | 90c904789f95318c4e57f3cd9e1d33aff3adc46d | 3,612,588 |
def resnet34(pretrained=False, filter_size=1, pool_only=True, **kwargs):
"""Constructs a ResNet-34 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(BasicBlock, [3, 4, 6, 3], filter_size=filter_size, pool_only=pool_only, **kwargs)
if pretrain... | 9653156bbbcd6773e5479ca31f2c95a9bf9edec5 | 3,612,589 |
def selvita_sukupuoli(hetu):
"""Selvittää järjestynumeron perusteella sukupuolen: parillinen -> nainen, pariton -> mies
Args:
hetu (string): Henkilötunnus
Returns:
string: Nainen tai mies
"""
# Otetaan hetusta järjestysnumero-osa
jarjestysnumero_str = hetu[7:10]
# Muuteta... | 243982f89e2e9edf4aa62972275a87e571327550 | 3,612,590 |
import re
def search_unknown(filename, dictionary):
""" Searches the words that are misspelled/not in the dictionary"""
numbers = re.findall('[\d]+', filename)
words = filename.lower().replace('?', ' ').replace('!',' ').replace('.',' ').replace('-',' ').replace(':',' ').replace(';',' ').replace(',',' ').replace('(... | 8e91ea65f7a1f04074e68d061677cfa365c762c2 | 3,612,591 |
def cpp_bindata_subtype_type_name(name):
# type: (unicode) -> unicode
"""Return the C++ type name for a bindata subtype."""
assert is_valid_bindata_subtype(name)
return _BINDATA_SUBTYPE[name]['bindata_enum'] | 3cdc6a5bb7fe2977f39a26d78c6bc6146a31301d | 3,612,592 |
def avg_spectra(im):
"""
avg_spectra(im)
Returns numpy.ndarray of mean spectrum, averaged over the image pixels
Parameters
----------
im : image passed as numpy array
Returns
-------
out : ndarray
An array object satisfying the specified requirements.
"""
... | 013bec790da9e27837fc83859c7b2e73c8845181 | 3,612,593 |
def moving_average(x, n, type='simple'):
"""
compute an n period moving average.
type is 'simple' | 'exponential'
"""
x = np.asarray(x)
if type == 'simple':
weights = np.ones(n)
else:
weights = np.exp(np.linspace(-1., 0., n))
weights /= weights.sum()
# print ("Weigh... | faa14d2ac7c0b08e1cdfaae33d18dd308083b11d | 3,612,594 |
def changeContagion(G, A, i):
"""
change statistic for Contagion (partner attribute)
*--*
"""
delta = 0
for u in G.neighbourIterator(i):
if A[u] == 1:
delta += 1
return delta | e6acd316f9fe618f7ca592c5aeae7b902fb774a4 | 3,612,595 |
def collect(config, pconn):
"""
All the heavy lifting done here
"""
branch_info = get_branch_info(config)
pc = InsightsUploadConf(config)
output = None
collection_rules = pc.get_conf_file()
rm_conf = pc.get_rm_conf()
blacklist_report = pc.create_report()
if rm_conf:
logg... | 222fc49ab5dc49eddeda5bc2e992ca931f9b30f4 | 3,612,596 |
def _check_verbosity(verbosity: str) -> str:
"""
Check function used by verbosity setter as a callback.
:param verbosity: verbosity level to apply to resto_client.
:raises ValueError: when verbosity has a wrong value
:returns: the uppercase verbosity level
"""
if verbosity is not None:
... | 449c3c632b0c9dba92aca5d42e49c750e4f21f02 | 3,612,597 |
import unittest
def local():
"""Run all local tests"""
suite = ServiceTestSuite()
suite.addTest(unittest.makeSuite(HomelandTestCase, 'test_local'))
return suite | ae8f24abf632c5b376e71151ef6ef813f1546d2d | 3,612,598 |
def cycle_check(classes):
"""
Checks for cycle in clazzes, which is a list of (class, superclass)
Based on union find algorithm
"""
sc = {}
for clazz, superclass in classes:
class_set = sc.get(clazz, clazz)
superclass_set = sc.get(superclass, superclass)
if class_set !=... | 8079f5e7044318570424a309b6cd16ce78b6e343 | 3,612,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.