content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def destr(screenString): """ should return a valid screen object as defined by input string (think depickling) """ #print "making screen from this received string: %s" % screenString rowList = [] curRow = [] curAsciiStr = "" curStr = "" for ch in screenString: if ch == '\n': # then we are done with...
38f540b3e8f6a16d2dbe7519ea5a43cbf2432b55
3,645,420
def analytical_solution_with_penalty(train_X, train_Y, lam, poly_degree): """ 加惩罚项的数值解法 :param poly_degree: 多项式次数 :param train_X: 训练集的X矩阵 :param train_Y: 训练集的Y向量 :param lam: 惩罚项系数 :return: 解向量 """ X, Y = normalization(train_X, train_Y, poly_degree) matrix = np.linalg.inv(X.T.dot(...
30f81cd74622889df64d6e67f023f67b3149504a
3,645,421
def formule_haversine(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """ Description: Calcule la distance entre deux points par la formule de Haversine. Paramètres: lat1: {float} -- Latitude du premier point. lon1: {float} -- Longitude du premier point. la...
03ac0c191aa17b9f20944a7de56febba77db1edc
3,645,422
def get_word_combinations(word): """ 'one-two-three' => ['one', 'two', 'three', 'onetwo', 'twothree', 'onetwothree'] """ permutations = [] parts = [part for part in word.split(u'-') if part] for count in range(1, len(parts) + 1): for index in range(len(parts) - count + 1): ...
5a4c042cc0f3dedb297e2513bf638eac4278e0a6
3,645,423
import tempfile def env_to_file(env_variables, destination_path=None, posix=True): """ Write environment variables to a file. :param env_variables: environment variables :param destination_path: destination path of a file where the environment variables will be stored. t...
c242ff4d6956922b2ccceecaef5b95640116e75a
3,645,424
def _phase_norm(signal, reference_channel=0): """Unit normalization. Args: signal: STFT signal with shape (..., T, D). Returns: Normalized STFT signal with same shape. """ angles = np.angle(signal[..., [reference_channel]]) return signal * np.exp(-1j * angles)
f4e9021f8942bebf97d35e529068792b7f956425
3,645,425
def maintenance_(): """Render a maintenance page while on maintenance mode.""" return render_template("maintenance/maintenance.html")
61b95cdeb1a16f216a60330d7501e5270e1342ba
3,645,426
def CanEditHotlist(effective_ids, hotlist): """Return True if a user is editor(add/remove issues and change rankings).""" return any([user_id in (hotlist.owner_ids + hotlist.editor_ids) for user_id in effective_ids])
dc29c74e2628930faffb12b6772046564ffb8218
3,645,427
from desimodel.io import load_fiberpos, load_target_info def model_density_of_sky_fibers(margin=1.5): """Use desihub products to find required density of sky fibers for DESI. Parameters ---------- margin : :class:`float`, optional, defaults to 1.5 Factor of extra sky positions to generate. So...
a50111f51c2ce081c3379e2b5506912326fafb55
3,645,428
def dice_counts(dice): """Make a dictionary of how many of each value are in the dice """ return {x: dice.count(x) for x in range(1, 7)}
427703283b5c0cb621e25f16a1c1f2436642fa9f
3,645,429
def SynthesizeData(phase, total_gen): """ Phase ranges from 0 to 24 with increments of 0.2. """ x_list = [phase] y_list = [] while len(x_list) < total_gen or len(y_list) < total_gen: x = x_list[-1] y = sine_function(x=x, amp=amp, per=per, shift_h=shift_h, shift_v=shift_v) x_lis...
e656767f7ebf13575571b5eb0592a0e11cbbfcf7
3,645,430
from pathlib import Path import difflib from datetime import datetime def compare(): """ Eats two file names, returns a comparison of the two files. Both files must be csv files containing <a word>;<doc ID>;<pageNr>;<line ID>;<index of the word> They may also contain lines with addit...
f6aa0421e84cf9d97a211904e64bd793ff7e989e
3,645,431
def draw_transform(dim_steps, filetype="png", dpi=150): """create image from variable transormation steps Args: dim_steps(OrderedDict): dimension -> steps * each element contains steps for a dimension * dimensions are all dimensions in source and target domain * each step i...
4738f9512065a9d0d6e33879954581cbf0940a11
3,645,432
import statistics def get_ei_border_ratio_from_exon_id(exon_id, regid2nc_dic, exid2eibrs_dic=None, ratio_mode=1, last_exon_dic=None, last_exon_ratio=2.5, ...
fd5239fabb81d328d644dbb8b56608eda15e78ce
3,645,433
def events(*_events): """ A class decorator. Adds auxiliary methods for callback based event notification of multiple watchers. """ def add_events(cls): # Maintain total event list of both inherited events and events added # using nested decorations. try: all_events = cl...
601f7d55ff4d05dd0aca552213dcd911f15c91b6
3,645,434
def _find_nearest(array, value): """Find the nearest numerical match to value in an array. Args: array (np.ndarray): An array of numbers to match with. value (float): Single value to find an entry in array that is close. Returns: np.array: The entry in array that is closest to valu...
7440447c4079563722b91771f07fcd3c3f5e0c3b
3,645,435
import requests from bs4 import BeautifulSoup def download_document(url): """Downloads document using BeautifulSoup, extracts the subject and all text stored in paragraph tags """ r = requests.get(url) soup = BeautifulSoup(r.text, 'html.parser') title = soup.find('title').get_text() document = ' '.join([p.get_...
8bb9055b40dd5554185ddec1d3218157a016bfd8
3,645,436
def rz_gate(phi: float = 0): """Functional for the single-qubit Pauli-Z rotation-gate. Parameters ---------- phi : float Rotation angle (in radians) Returns ------- rz : (2, 2) np.ndarray """ arg = 1j * phi / 2 return np.array([[np.exp(-arg), 0], [0, np.exp(arg)]])
c148a03f3525698c44e5f8aa14085bfeb29c72ef
3,645,437
from typing import List def dict_to_kvp(dictionary: dict) -> List[tuple]: """ Converts a dictionary to a list of tuples where each tuple has the key and value of each dictionary item :param dictionary: Dictionary to convert :return: List of Key-Value Pairs """ return [(k, v) for k, v in d...
2b856ebb218884a4975d316bebe27546070f2083
3,645,438
def convert_and_remove_punctuation(text): """ remove punctuation that are not allowed, e.g. / \ convert Chinese punctuation into English punctuation, e.g. from「 to " """ # removal text = text.replace("\\", "") text = text.replace("\\", "") text = text.replace("[", "") text = text.re...
2de1f930ca76da7fec3467469f98b0e0858e54a0
3,645,439
def create_random_context(dialog,rng,minimum_context_length=2,max_context_length=20): """ Samples random context from a dialog. Contexts are uniformly sampled from the whole dialog. :param dialog: :param rng: :return: context, index of next utterance that follows the context """ # sample dia...
d66ee8f185380801735644a7ce4528f398385e60
3,645,440
def dev_test_new_schema_version(dbname, sqldb_dpath, sqldb_fname, version_current, version_next=None): """ hacky function to ensure that only developer sees the development schema and only on test databases """ TESTING_NEW_SQL_VERSION = version_current != version_next...
ec57d6ccb39d76159ab80c6fdfe094b486d00777
3,645,441
def _get_distance_euclidian(row1: np.array, row2: np.array): """ _get_distance returns the distance between 2 rows (euclidian distance between vectors) takes into account all columns of data given """ distance = 0. for i, _ in enumerate(row1): distance += (row1[i] - row2[i]) ** 2...
13a3944becf717222eb6fc997ceb937ad37b30ab
3,645,442
import re def _get_ip_from_response(response): """ Filter ipv4 addresses from string. Parameters ---------- response: str String with ipv4 addresses. Returns ------- list: list with ip4 addresses. """ ip = re.findall(r'\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)...
ac36a3b729b0ce4ba13a6db550a71276319cbd70
3,645,443
from typing import Optional from typing import List import logging def create_processor( options: options_pb2.ConvertorOptions, theorem_database: Optional[proof_assistant_pb2.TheoremDatabase] = None, tactics: Optional[List[deephol_pb2.Tactic]] = None) -> ProofLogToTFExample: """Factory function for Proo...
898a72372a80546f4de277c5f3e3573c7f8edff6
3,645,444
def EscapeShellArgument(s): """Quotes an argument so that it will be interpreted literally by a POSIX shell. Taken from http://stackoverflow.com/questions/35817/whats-the-best-way-to-escape-ossystem-calls-in-python """ return "'" + s.replace("'", "'\\''") + "'"
132a3b1bb8a0e7b3c92ac15e2d68337eeef19042
3,645,445
def lsh(B_BANDS, docIdList, sig): """ Applies the LSH algorithm. This function first divides the signature matrix into bands and hashes each column onto buckets. :param B_BANDS: Number of bands in signature matrix :param docIdList: List of document ids :param sig: signature matrix :return: List of ...
ad6071e52d2c442764e57bb68e2f1e2d4c5a7c2e
3,645,447
def langevin_coefficients( temperature, dt, friction, masses): """ Compute coefficients for langevin dynamics Parameters ---------- temperature: float units of Kelvin dt: float units of picoseconds friction: float frequency in picoseconds masse...
680d5c8898ecb7c0627232c8c993bb0f64a2e9d3
3,645,448
def waitpid_handle_exceptions(pid, deadline): """Wrapper around os.waitpid()/waitpid_with_timeout(), which waits until either a child process exits or the deadline elapses, and retries if certain exceptions occur. Args: pid: Process ID to wait for, or -1 to wait for any child process. deadline: If non-...
2d15594c9b066b3e1000a6394503a9b8a88e5420
3,645,449
def preprocess(image, image_size): """ Preprocess pre-process the image by to adaptive_treshold, perspectiv_transform, erode, diletate, resize :param image: image of display from cv2.read :return out_image: output image after preprocessing """ # blurr blurred = cv2.GaussianBlur(im...
497d3d1a32be643486903d44621ff203503b726e
3,645,451
import urllib import json import time def download(distributor: Distributor, max_try:int = 4) -> list[TrainInformation]|None: """Download train information from distributor. If response status code was 500-599, this function retries up to max_try times. Parameters ---------- distributor : Distri...
1288e50807465164dd4aa2e082b4136abe81636c
3,645,452
def add_payloads(prev_layer, input_spikes): """Get payloads from previous layer.""" # Get only payloads of those pre-synaptic neurons that spiked payloads = tf.where(tf.equal(input_spikes, 0.), tf.zeros_like(input_spikes), prev_layer.payloads) print("Using spikes with payloads f...
4f7bd805e8659ddea0da63fd542edb6d52073569
3,645,453
def read_csv_to_data(path: str, delimiter: str = ",", headers: list = []): """A zero-dependancy helper method to read a csv file Given the path to a csv file, read data row-wise. This data may be later converted to a dict of lists if needed (column-wise). Args: path (str): Path to csv file ...
f60e163e770680efd1f8944becd79a0dd7ceaa08
3,645,454
def main_menu(update, context): """Handling the main menu :param update: Update of the sent message :param context: Context of the sent message :return: Status for main menu """ keyboard = [['Eintragen'], ['Analyse']] update.message.reply_text( 'Was möchtest du mach...
bafc092ec662286f417a9a5d2c47a675336c4825
3,645,455
def build_model(inputs, num_classes, is_training, hparams): """Constructs the vision model being trained/evaled. Args: inputs: input features/images being fed to the image model build built. num_classes: number of output classes being predicted. is_training: is the model training or not. ...
0ad57496d77e4406c5081982a2c02f2111cb5b57
3,645,456
import flask_monitoringdashboard def get_test_app_for_status_code_testing(schedule=False): """ :return: Flask Test Application with the right settings """ app = Flask(__name__) @app.route('/return-a-simple-string') def return_a_simple_string(): return 'Hello, world' @app.route('...
69951350c8b14cf02b1327773665d9080b0eeb48
3,645,457
def run_multiple_cases(x, y, z, door_height, door_width, t_amb, HoC, time_ramp, hrr_ramp, num, door, wall, simulation_time, dt_data): """ Generate multiple CFAST input files and calls other functions """ resulting_temps = np.array([]) for i in range(le...
1c056b4c991889b81324857788cda416f90a8cdc
3,645,459
def get_all(): """ Obtiene todas las tuplas de la relación Estudiantes :returns: Todas las tuplas de la relación. :rtype: list """ try: conn = helpers.get_connection() cur = conn.cursor() cur.execute(ESTUDIANTE_QUERY_ALL) result = cur.fetchall() ...
8b2248f09b02bf8fb4198bd36e743a5d052dd9f3
3,645,460
import warnings def load_fgong(filename, fmt='ivers', return_comment=False, return_object=True, G=None): """Given an FGONG file, returns NumPy arrays ``glob`` and ``var`` that correspond to the scalar and point-wise variables, as specified in the `FGONG format`_. .. _FGONG format: http...
17fcac5511a588351701f921dc8449d81a603fb6
3,645,461
import ctypes def dskb02(handle, dladsc): """ Return bookkeeping data from a DSK type 2 segment. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dskb02_c.html :param handle: DSK file handle :type handle: int :param dladsc: DLA descriptor :type dladsc: spiceypy.utils.support_types...
b08eed84bd518d35166ee28df8f87c06b08220c4
3,645,463
def train_node2vec(graph, dim, p, q): """Obtains node embeddings using Node2vec.""" emb = n2v.Node2Vec( graph=graph, dimensions=dim, workers=mp.cpu_count(), p=p, q=q, quiet=True, ).fit() emb = { node_id: emb.wv[str(node_id)] for node_id in...
7cea146b2971e973de2ecd365ad25c7f4fd57289
3,645,465
def approx_match_dictionary(): """Maps abbreviations to the part of the expanded form that is common beween all forms of the word""" k=["%","bls","gr","hv","hæstv","kl","klst","km","kr","málsl",\ "málsgr","mgr","millj","nr","tölul","umr","þm","þskj","þús"] v=['prósent','blaðsíð',\ 'grein','hát...
021c7de862b2559b55051bc7267113d77132e195
3,645,466
def matrix2array(M): """ 1xN matrix to array. In other words: [[1,2,3]] => [1,2,3] """ if isspmatrix(M): M = M.todense() return np.squeeze(np.asarray(M))
731317458f6ec7c068c1a9450447eba39e1423f9
3,645,467
def expected(data): """Computes the expected agreement, Pr(e), between annotators.""" total = float(np.sum(data)) annotators = range(len(data.shape)) percentages = ((data.sum(axis=i) / total) for i in annotators) percent_expected = np.dot(*percentages) return percent_expected
86562fec2b17df35401b8d8b7eafd759a13715e3
3,645,468
import numpy def maximization_step(num_words, stanzas, schemes, probs): """ Update latent variables t_table, rprobs """ t_table = numpy.zeros((num_words, num_words + 1)) rprobs = numpy.ones(schemes.num_schemes) for i, stanza in enumerate(stanzas): scheme_indices = schemes.get_schemes_f...
a0e23367d6dff50d79bb828a0af8a82b640400c8
3,645,469
import json def account_export_mydata_content(account_id=None): """ Export ServiceLinks :param account_id: :return: List of dicts """ if account_id is None: raise AttributeError("Provide account_id as parameter") # Get table names logger.info("ServiceLinkRecord") db_entry_...
d61dd638319479572ecea5335f0a9a7fc7156410
3,645,470
from typing import List def indicator_entity(indicator_types: List[str] = None) -> type: """Return custom model for Indicator Entity.""" class CustomIndicatorEntity(IndicatorEntity): """Indicator Entity Field (Model) Type""" @validator('type', allow_reuse=True) def is_empty(cls, valu...
f6c77ffd3b8415e07e0e64ab8120a084aab3e2c8
3,645,471
def z_to_t(z_values, dof): """ Convert z-statistics to t-statistics. An inversion of the t_to_z implementation of [1]_ from Vanessa Sochat's TtoZ package [2]_. Parameters ---------- z_values : array_like Z-statistics dof : int Degrees of freedom Returns -------...
4700f52263519169a4610daee8c0940489b2731e
3,645,472
def getInputShape(model): """ Gets the shape when there is a single input. Return: Numeric dimensions, omits dimensions that have no value. eg batch size. """ s = [] for dim in model.input.shape: if dim.value: s.append(dim.value) ...
628f61a995784b9be79816a5bbcde2f8204640be
3,645,473
def get_node_depths(tree): """ Get the node depths of the decision tree >>> d = DecisionTreeClassifier() >>> d.fit([[1,2,3],[4,5,6],[7,8,9]], [1,2,3]) >>> get_node_depths(d.tree_) array([0, 1, 1, 2, 2]) """ def get_node_depths_(current_node, current_depth, l, r, depths): depths ...
4a5a001600c0cb6b1b545be003708088bbd2d060
3,645,475
import attr from typing import Tuple def homo_tuple_typed_attrs(draw, defaults=None, legacy_types_only=False, kw_only=None): """ Generate a tuple of an attribute and a strategy that yields homogenous tuples for that attribute. The tuples contain strings. """ default = attr.NOTHING val_strat = ...
398e47ea6fb65ba0fab1e633ea27dc3cac30ed28
3,645,476
from typing import Dict from typing import Any from typing import Callable from typing import Union from typing import Tuple from typing import Optional def flatland_env_factory( evaluation: bool = False, env_config: Dict[str, Any] = {}, preprocessor: Callable[ [Any], Union[np.ndarray, Tuple[np.nd...
a2076ef15964e60b7a5e4cf885e5b92da594f0ac
3,645,477
import six def industry(code, market="cn"): """获取某个行业的股票列表。目前支持的行业列表具体可以查询以下网址: https://www.ricequant.com/api/research/chn#research-API-industry :param code: 行业代码,如 A01, 或者 industry_code.A01 :param market: 地区代码, 如'cn' (Default value = "cn") :returns: 行业全部股票列表 """ if not isinstance(code, ...
bf5606b93e17d5b5125f6afd133e86b5ded9a03d
3,645,478
def kewley_agn_oi(log_oi_ha): """Seyfert/LINER classification line for log([OI]/Ha).""" return 1.18 * log_oi_ha + 1.30
5e6b71742bec307ad609d855cced80ae08e5c35c
3,645,479
def XGMMLReader(graph_file): """ Arguments: - `file`: """ parser = XGMMLParserHelper() parser.parseFile(graph_file) return parser.graph()
ef9c1cb101b22f3302cf93db7447431fb1f5cfa8
3,645,480
def pt_encode(index): """pt: Toggle light.""" return MessageEncode(f"09pt{index_to_housecode(index)}00", None)
1e2143d7c356736082d4dc25b459630e8c97fe7a
3,645,481
from qtpy.QtCore import QUrl from qtpy.QtGui import QDesktopServices def start_file(filename): """ Generalized os.startfile for all platforms supported by Qt This function is simply wrapping QDesktopServices.openUrl Returns True if successfull, otherwise returns False. """ # We need to use ...
269704fdd5bbf4e3d3e35bec6e9862fe36602f22
3,645,484
def require_context(f): """Decorator to require *any* user or admin context. This does no authorization for user or project access matching, see :py:func:`authorize_project_context` and :py:func:`authorize_user_context`. The first argument to the wrapped function must be the context. """ d...
7a052ddf20b9afff055daed09dbe0963269d46f4
3,645,485
def failsafe_hull(coords): """ Wrapper of ConvexHull which returns None if hull cannot be computed for given points (e.g. all colinear or too few) """ coords = np.array(coords) if coords.shape[0] > 3: try: return ConvexHull(coords) except QhullError as e: if '...
dca4d35d98032f9c77da38a860c2209758babfda
3,645,486
def list_closed_poll_sessions(request_ctx, **request_kwargs): """ Lists all closed poll sessions available to the current user. :param request_ctx: The request context :type request_ctx: :class:RequestContext :return: List closed poll sessions :rtype: requests.Response (with voi...
90c2d660a18ed9fa9f10f092a415e5f94148eba1
3,645,487
from typing import List import struct def _wrap_apdu(command: bytes) -> List[bytes]: """Return a list of packet to be sent to the device""" packets = [] header = struct.pack(">H", len(command)) command = header + command chunks = [command[i : i + _PacketData.FREE] for i in range(0, len(command), ...
828521642b43758cf0c43f2c8af171d3463cacf5
3,645,488
from pathlib import Path def build_dtree(bins): """ Build the directory tree out of what's under `user/`. The `dtree` is a dict of: string name -> 2-list [inumber, element] , where element could be: - Raw bytes for regular file - A `dict` for directory, which recurses on """...
66248226318a6225ea17d82d535012447b33f7e5
3,645,489
def _compose_image(digit, background): """Difference-blend a digit and a random patch from a background image.""" w, h, _ = background.shape dw, dh, _ = digit.shape x = np.random.randint(0, w - dw) y = np.random.randint(0, h - dh) bg = background[x:x+dw, y:y+dh] return np.abs(bg - digit).as...
956e06623f0534bea93b446e9a742ae78aada69f
3,645,490
def permissions_vsr(func): """ :param func: :return: """ def func_wrapper(name): return "<p>{0}</p>".format(func(name)) return func_wrapper
a7e01f7711cab6bc46c004c4d062930c2a656eee
3,645,491
import scipy def tri_interpolate_zcoords(points: np.ndarray, triangles: np.ndarray, mesh_points: np.ndarray, is_mesh_edge: np.ndarray, num_search_tris: int=10): """ Interpolate z-coordinates to a set of 2D points using 3D point coordinates and a triangular mesh. If point is alo...
0a1702407c8a5b175b8fa8314eede203ac5a86ca
3,645,492
from typing import List def getServiceTypes(**kwargs) -> List: """List types of services. Returns: List of distinct service types. """ services = getServices.__wrapped__() types = [s['type'] for s in services] uniq_types = [dict(t) for t in {tuple(sorted(d.items())) for d in types}] ...
23bd7730b43c1d942450fc57c2a3c6f83f7c578c
3,645,493
from keras.callbacks import EarlyStopping, ModelCheckpoint import pylab as plt def train_model(train_data, test_data, model, model_name, optimizer, loss='mse', scale_factor=1000., batch_size=128, max_epochs=200, early_stop=True, plot_history=True): """ Code to train a given model and save out to the designated pa...
3d74e765065b8514dd43d0a0ba6f83542bc47b11
3,645,494
def get_pipeline_storage_es_client(session, *, index_date): """ Returns an Elasticsearch client for the pipeline-storage cluster. """ secret_prefix = f"elasticsearch/pipeline_storage_{index_date}" host = get_secret_string(session, secret_id=f"{secret_prefix}/public_host") port = get_secret_stri...
8b759f1c2b6fa2b525a0a20653bd1ff99441e893
3,645,495
def cqcc_resample(s, fs_orig, fs_new, axis=0): """implement the resample operation of CQCC Parameters ---------- s : ``np.ndarray`` the input spectrogram. fs_orig : ``int`` origin sample rate fs_new : ``int`` new sample rate axis : ``int`` the resample axis ...
d252fdc2587c48d15d7f41224df3bfcd9e17693c
3,645,496
def weights_init(): """ Gaussian init. """ def init_fun(m): classname = m.__class__.__name__ if (classname.find("Conv") == 0 or classname.find("Linear") == 0) and hasattr(m, "weight"): nn.init.normal_(m.weight, 0.0, 0.02) if hasattr(m, "bias") and m.bias is not...
f56aa9c988b93d30c6a78769bc0f2c86f0209cd8
3,645,497
def named(name): """ This function is used to decorate middleware functions in order for their before and after sections to show up during a verbose run. For examples see documentation to this module and tests. """ def new_annotate(mware): def new_middleware(handler): new_h...
0f1cef0788eae16bf557b5f7cb01bd52e913203d
3,645,498
def concatFile(file_list): """ To combine files in file list. """ config = getConfig() print('[load]concating...') df_list = [] for f in file_list: print(f) tmp = pd.read_csv(config['dir_raw']+f, index_col=None, header=0) df_list.append(tmp) df = pd.concat(df_list, axis=0, ignore_index=True) return df
c289db2e1a995f3b536f2d472eed550843980635
3,645,499
def multiply_str(char, times): """ Return multiplied character in string """ return char * times
cc69f0e16cba1b8c256301567905e861c05291ea
3,645,500
def calories_per_item(hundr, weight, number_cookies, output_type): """ >>> calories_per_item(430, 0.3, 20, 0) 'One item has 64.5 kcal.' >>> calories_per_item(430, 0.3, 20, 1) 'One item has 64.5 Calories.' >>> calories_per_item(1, 1000, 10, 1) 'One item has 1000.0 Calories.' >>> calories_...
9ca16eee8aa8a81424aeaa30f696fb5bec5e3956
3,645,501
def bitcoind_call(*args): """ Run `bitcoind`, return OS return code """ _, retcode, _ = run_subprocess("/usr/local/bin/bitcoind", *args) return retcode
efa585a741da1ba3bf94650de1d7296228c15e7e
3,645,502
def getItemProduct(db, itemID): """ Get an item's linked product id :param db: database pointer :param itemID: int :return: int """ # Get the one we want item = db.session.query(Item).filter(Item.id == itemID).first() # if the query didn't return anything, raise noresult exception ...
fbbd2b2108bba78af1abc4714653065e12906ee3
3,645,503
from typing import Optional def find_board(board_id: BoardID) -> Optional[Board]: """Return the board with that id, or `None` if not found.""" board = db.session.get(DbBoard, board_id) if board is None: return None return _db_entity_to_board(board)
16f687304d1008b3704d641a7e9e5e624475e045
3,645,504
from typing import Any def test_isin_pattern_0(): """ Test IsIn pattern which expresses the IsIn/OneOf semantics. """ inputs = Tensor(np.ones([42]), mindspore.float16) softmax_model = nn.Softmax() @register_pass(run_only_once=True) def softmax_relu_pass(): x = Any() softma...
78e169fcab894c3cf7956884bd3553983fda5bae
3,645,505
from datetime import datetime def ENsimtime(): """retrieves the current simulation time t as datetime.timedelta instance""" return datetime.timedelta(seconds= _current_simulation_time.value )
4dd971b3af9d0a2544e809ea7726521d9ce8e5b1
3,645,506
def solar_true_longitude(solar_geometric_mean_longitude, solar_equation_of_center): """Returns the Solar True Longitude with Solar Geometric Mean Longitude, solar_geometric_mean_longitude, and Solar Equation of Center, solar_equation_of_center.""" solar_true_longitude = solar_geometric_mean_longitude +...
a335bb82002846eb2bc2106675c13e9f3ee28900
3,645,507
import base64 def image_to_fingerprint(image, size=FINGERPRINT_SIZE): """Create b64encoded image signature for image hash comparisons""" data = image.copy().convert('L').resize((size, size)).getdata() return base64.b64encode(bytes(data)).decode()
83ff567bce0530b69a9b43c40ea405af825831ff
3,645,508
from datetime import datetime import pandas def get_indices( time: str | datetime | date, smoothdays: int = None, forcedownload: bool = False ) -> pandas.DataFrame: """ alternative going back to 1931: ftp://ftp.ngdc.noaa.gov/STP/GEOMAGNETIC_DATA/INDICES/KP_AP/ 20 year Forecast data from: http...
e8880caac96e9b3333c2f1f557b5918ee40cdbbe
3,645,509
import json def check(device, value): """Test for valid setpoint without actually moving.""" value = json.loads(value) return zmq_single_request("check_value", {"device": device, "value": value})
f08e80348f97531ed51207aff685a470ca62bc41
3,645,511
def get_projectID(base_url, start, teamID, userID): """ Get all the project from jama Args: base_url (string): jama instance base url start (int): start at a specific location teamID (string): user team ID, for OAuth userID (string): user ID, for OAuth Returns: (...
92deaf007530b67be6459c7fd0a0e196dbe18216
3,645,513
def to_world(points_3d, key2d, root_pos): """ Trasform coordenates from camera to world coordenates """ _, _, rcams = data_handler.get_data_params() n_cams = 4 n_joints_h36m = 32 # Add global position back points_3d = points_3d + np.tile(root_pos, [1, n_joints_h36m]) # Load the appropriat...
9b56b946569dac35231282009389a777e908d09f
3,645,514
def orbital_energies_from_filename(filepath): """Returns the orbital energies from the given filename through functional composition :param filepath: path to the file """ return orbital_energies(spe_list( lines=list(content_lines(filepath, CMNT_STR))))
669bfbe18bb8686e2f9fdc89dcdb3a36aeec6940
3,645,515
def _dict_merge(a, b): """ `_dict_merge` deep merges b into a and returns the new dict. """ if not isinstance(b, dict): return b result = deepcopy(a) for k, v in b.items(): if k in result and isinstance(result[k], dict): result[k] = _dict_merge(result[k], v) else:...
278bfa6f8895fda0ae86b0ff2014602a7e9225df
3,645,516
import stat import functools import operator def flags(flags: int, modstring: str) -> int: """ Modifies the stat flags according to *modstring*, mirroring the syntax for POSIX `chmod`. """ mapping = { 'r': (stat.S_IRUSR, stat.S_IRGRP, stat.S_IROTH), 'w': (stat.S_IWUSR, stat.S_IWGRP, stat.S_IWOTH), 'x...
9acfeb4d9b90a12d2308c0ec992cfbb47f11000c
3,645,517
def _can_contain(ob1, ob2, other_objects, all_obj_locations, end_frame, min_dist): """ Return true if ob1 can contain ob2. """ assert len(other_objects) == len(all_obj_locations) # Only cones do the contains, and can contain spl or smaller sphere/cones, # cylinders/cubes are too large ...
391119dae5e86efe0c99bae7c603a1f785c69c04
3,645,518
def twolmodel(attr, pulse='on'): """ This is the 2-layer ocean model requires a forcing in W/m2 pulse = on - radiative pulse W/m2 pulse = off - time varyin radaitive forcing W/m2/yr pulse = time - use output from simple carbon model """ #### Parameters #### yeartosec = 30.25*24*60*6...
4f6649a8df1febe54a6c04fdee938591a0c997b2
3,645,519
def maximumToys(prices, k): """Problem solution.""" prices.sort() c = 0 for toy in prices: if toy > k: return c else: k -= toy c += 1 return c
0ce709ff7b106b5379217cb6b7f1f481d27c94e7
3,645,520
def get_X_HBR_d_t_i(X_star_HBR_d_t): """(47) Args: X_star_HBR_d_t: 日付dの時刻tにおける負荷バランス時の居室の絶対湿度(kg/kg(DA)) Returns: 日付dの時刻tにおける暖冷房区画iの実際の居室の絶対湿度(kg/kg(DA)) """ X_star_HBR_d_t_i = np.tile(X_star_HBR_d_t, (5, 1)) return X_star_HBR_d_t_i
125d70ff96ce1a035df98d6995aa55ea3728ffa9
3,645,522
from typing import Optional from typing import Dict from typing import Callable from typing import Any def add_route(url: str, response: Optional[str] = None, method: str = 'GET', response_type: str = 'JSON', status_code: int = 200, headers: Option...
f103b6d6faffff4a816fdf7c3c0124ea41622fe1
3,645,523
def findUsername(data): """Find a username in a Element Args: data (xml.etree.ElementTree.Element): XML from PMS as a Element Returns: username or None """ elem = data.find('User') if elem is not None: return elem.attrib.get('title') return None
f7b6bb816b9eeeca7e865582935a157cdf276928
3,645,524
def GET(request): """Get this Prefab.""" request.check_required_parameters(path={'prefabId': 'string'}) prefab = Prefab.from_id(request.params_path['prefabId']) prefab.check_exists() prefab.check_user_access(request.google_id) return Response(200, 'Successfully retrieved prefab', prefab.obj)
07a7078cb73893309372c0a8d48857eefc77a41e
3,645,526
def fix_empty_strings(tweet_dic): """空文字列を None に置換する""" def fix_media_info(media_dic): for k in ['title', 'description']: if media_dic.get('additional_media_info', {}).get(k) == '': media_dic['additional_media_info'][k] = None return media_dic for m in tweet_dic...
436daaeb9b96b60867d27812ed7388892ab79b1a
3,645,527
import math def fibonacci(**kwargs): """Fibonacci Sequence as a numpy array""" n = int(math.fabs(kwargs.pop('n', 2))) zero = kwargs.pop('zero', False) weighted = kwargs.pop('weighted', False) if zero: a, b = 0, 1 else: n -= 1 a, b = 1, 1 result = np.array([a]) ...
055d157120866c9bfe74374d62cffcc8f599d4bb
3,645,529
def read_data(): """Reads in the data from (currently) only the development file and returns this as a list. Pops the last element, because it is empty.""" with open('../PMB/parsing/layer_data/4.0.0/en/gold/dev.conll') as file: data = file.read() data = data.split('\n\n') data.pop(-...
da75e237bbc7b2168cd5af76eefaf389b29d4b30
3,645,530
def argrelextrema(data, comparator, axis=0, order=1, mode='clip'): """ Calculate the relative extrema of `data`. Parameters ---------- data : ndarray Array in which to find the relative extrema. comparator : callable Function to use to compare two data points. Should tak...
66d565fad5672615f1340979a3c59e5abbbab3f5
3,645,531
import math def dijkstra(G, s): """ find all shortest paths from s to each other vertex in graph G """ n = len(G) visited = [False]*n weights = [math.inf]*n path = [None]*n queue = [] weights[s] = 0 hq.heappush(queue, (0, s)) while len(queue) > 0: g, u = hq.heap...
85069b177ac646f449ce8e3ccf6d9c5b9de7b2e3
3,645,532