content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import List from re import T def reverse(ls: List[T]) -> List[T]: """ Reverses a list. :param ls: The list to be reversed :return: The reversed list """ for i in range(len(ls) // 2): ls[i], ls[len(ls) - 1 - i] = ls[len(ls) - 1 - i], ls[i] return ls
eacee56b5325178ec27a13283d64d0155c7a97ed
25,530
def test_get_annotations_not_5( test_gb_file, test_accession, coordination_args, monkeypatch ): """Test get_annotations when length of protein data is not 5.""" def mock_get_gb_file(*args, **kwargs): gb_file = test_gb_file return gb_file def mock_get_record(*args, **kwargs): re...
a9021af24ecb339ebea89d6ad7beb6e4097c5519
25,531
def increment_with_offset(c: str, increment: int, offset: int) -> str: """ Caesar shift cipher. """ return chr(((ord(c) - offset + increment) % 26) + offset)
50b10b6d3aff3dff157dfc46c368ae251ed060bb
25,532
import logging def uploadfiles(): """ function to upload csv to db :return: renders success.html """ # get the uploaded file uploaded_file = request.files['filename'] if uploaded_file.filename != '': csv_to_db(uploaded_file) return render_template('success.html') loggin...
5baa9dfb8930e70ebd37b502a211ae847194e08f
25,533
def static_html(route): """ Route in charge of routing users to Pages. :param route: :return: """ page = get_page(route) if page is None: abort(404) else: if page.auth_required and authed() is False: return redirect(url_for("auth.login", next=request.full_path...
52c74b63c5856a04b294f8e539b4be26deec0209
25,534
import math def getCenterFrequency(filterBand): """ Intermediate computation used by the mfcc function. Compute the center frequency (fc) of the specified filter band (l) This where the mel-frequency scaling occurs. Filters are specified so that their center frequencies are equally spaced on the m...
e043774093c4417658cdfd052d486ea5e30efb81
25,535
import numpy def phi_analytic(dist, t, t_0, k, phi_1, phi_2): """ the analytic solution to the Gaussian diffusion problem """ phi = (phi_2 - phi_1)*(t_0/(t + t_0)) * \ numpy.exp(-0.25*dist**2/(k*(t + t_0))) + phi_1 return phi
49fac597afa876f81ba5774bf82fedcfb88f6c7f
25,536
def geometric_median(X, eps=1e-5): """ calculate the geometric median as implemented in https://stackoverflow.com/a/30305181 :param X: 2D dataset :param eps: :return: median value from X """ y = np.mean(X, 0) while True: D = cdist(X, [y]) nonzeros = (D != 0)[:, 0] ...
9c8b0d69b4f66dc471bcb838b19ecac934493c54
25,538
def distance(bbox, detection): """docstring for distance""" nDetections = detection.shape[0] d = np.zeros(nDetections) D = detection - np.ones([nDetections,1])*bbox for i in xrange(nDetections): d[i] = np.linalg.norm(D[i],1) return d
21c4beea66df1dde96cd91cff459bf10f1b7a41e
25,539
from typing import TextIO from typing import Tuple def _read_float(line: str, pos: int, line_buffer: TextIO ) -> Tuple[float, str, int]: """Read float value from line. Args: line: line. pos: current position. line_buffer: line buffer for nnet3 file. ...
f0c76b2224a17854902aadbe7a715ca00da64932
25,540
def pk_to_p2wpkh_in_p2sh_addr(pk, testnet=False): """ Compressed public key (hex string) -> p2wpkh nested in p2sh address. 'SegWit address.' """ pk_bytes = bytes.fromhex(pk) assert is_compressed_pk(pk_bytes), \ "Only compressed public keys are compatible with p2sh-p2wpkh addresses. See BIP49...
10e9b2659df98b02b5030c1eec1820c9bbdd1a8b
25,542
def remove_imaginary(pauli_sums): """ Remove the imaginary component of each term in a Pauli sum :param PauliSum pauli_sums: The Pauli sum to process. :return: a purely hermitian Pauli sum. :rtype: PauliSum """ if not isinstance(pauli_sums, PauliSum): raise TypeError("not a pauli su...
2edd93f338d4e2dc1878953ced5edf954f509ccc
25,543
def log_sigmoid_deprecated(z): """ Calculate the log of sigmod, avoiding overflow underflow """ if abs(z) < 30: return np.log(sigmoid(z)) else: if z > 0: return -np.exp(-z) else: return z
576d7de9bf61aa32c3e39fc5ca7f4428b43519bb
25,544
def roty(t): """Rotation about the y-axis.""" c = np.cos(t) s = np.sin(t) return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]])
9c05a96c8c36fd3cd7eee1860574b9242d7543d6
25,545
def ranks_to_metrics_dict(ranks): """Calculates metrics, returns metrics as a dict.""" mean_rank = np.mean(ranks) mean_reciprocal_rank = np.mean(1. / ranks) hits_at = {} for k in (1, 3, 10): hits_at[k] = np.mean(ranks <= k)*100 return { 'MR': mean_rank, 'MRR': mean_reciprocal_rank, 'hi...
60ee20fdf43240e3f0aa0e414fd49bcc52f83446
25,546
def bias_correction(input_data, output_filename='', mask_filename='', method="ants", command="/home/abeers/Software/ANTS/ANTs.2.1.0.Debian-Ubuntu_X64/N4BiasFieldCorrection", temp_dir='./'): """ A catch-all function for motion correction. Will perform motion correction on an input volume depending on the 'm...
5236cff562dc50390146a5902a8f9924457e5426
25,547
def randperm2d(H, W, number, population=None, mask=None): """randperm 2d function genarates diffrent random interges in range [start, end) Parameters ---------- H : {integer} height W : {integer} width number : {integer} random numbers population : {list or num...
a3507c488740e0190673cb0bd920c0c0f15b77a1
25,548
def get_engine(db_credentials): """ Get SQLalchemy engine using credentials. Input: db: database name user: Username host: Hostname of the database server port: Port number passwd: Password for the database """ url = 'postgresql://{user}:{passwd}@{host}:{port}/{db}'.format( ...
ff66c10c7a79b0f5751979f0f5fc74c16d97eac0
25,549
def numpy_to_vtkIdTypeArray(num_array, deep=0): """ Notes ----- This was pulled from VTK and modified to eliminate numpy 1.14 warnings. VTK uses a BSD license, so it's OK to do that. """ isize = vtk.vtkIdTypeArray().GetDataTypeSize() dtype = num_array.dtype if isize == 4: if...
149da1f117968839801f2720c132451045b21fb6
25,550
def denormalize_ged(g1, g2, nged): """ Converts normalized ged into ged. """ return round(nged * (g1.num_nodes + g2.num_nodes) / 2)
214813120d552ef5ece10349978238117fe26cf3
25,551
from datetime import datetime import time def get_current_time(): """just returns time stamp """ time_stamp = datetime.datetime.fromtimestamp( time()).strftime('%Y-%m-%d %H:%M:%S') return time_stamp
236bd2b141c3686bb4c05a18a6d0f0ef3b15ea6b
25,552
import asyncio async def test_script_mode_2(hass, hass_ws_client, script_mode, script_execution): """Test overlapping runs with max_runs > 1.""" id = 1 def next_id(): nonlocal id id += 1 return id flag = asyncio.Event() @callback def _handle_event(_): flag.se...
76a251dc4f2f7aa17e280ee1bcb76aa8333388cb
25,554
def ease_of_movement(high, low, close, volume, n=20, fillna=False): """Ease of movement (EoM, EMV) It relate an asset's price change to its volume and is particularly useful for assessing the strength of a trend. https://en.wikipedia.org/wiki/Ease_of_movement Args: high(pandas.Series): da...
c25720e866b1d4635d7e8256b9ace94f78b463ed
25,555
def Document(docx=None, word_open_xml=None): """ Return a |Document| object loaded from *docx*, where *docx* can be either a path to a ``.docx`` file (a string) or a file-like object. Optionally, ``word_open_xml`` can be specified as a string of xml. Either ``docx`` or `word_open_xml`` may be specif...
565dd4f7f1d815f2e5ef97226d1175283ba942de
25,556
def css_tag(parser, token): """ Renders a tag to include the stylesheet. It takes an optional second parameter for the media attribute; the default media is "screen, projector". Usage:: {% css "<somefile>.css" ["<projection type(s)>"] %} Examples:: {% css "myfile.css" %} ...
b05deebf31c864408df33a41ba95016a06f48e2e
25,557
def camelcase(path): """Applies mixedcase and capitalizes the first character""" return mixedcase('_{0}'.format(path))
484bfcf8797637f56d5d0bdcad6c370f158773c0
25,558
import copy def ImproveData_v2 (Lidar_DataOld,Lidar_Data,Data_Safe,Speed,orientation,orientationm1): """ The function calculates new positions for obstacles now taking into account the car's relative speed in relation to each point. We need the accelerometer for that. Return: ...
2bd6c0f167e65ad4a461d75a95539b68dc0b1a70
25,559
def label_by_track(mask, label_table): """Label objects in mask with track ID Args: mask (numpy.ndarray): uint8 np array, output from main model. label_table (pandas.DataFrame): track table. Returns: numpy.ndarray: uint8/16 dtype based on track count. """ assert mask.s...
9190714e8cfc3955d1aeffd22d20574d14889538
25,560
import zipfile import xml def load_guidata(filename, report): """Check if we have a GUI document.""" report({'INFO'}, "load guidata..") guidata = None zdoc = zipfile.ZipFile(filename) if zdoc: if "GuiDocument.xml" in zdoc.namelist(): gf = zdoc.open("GuiDocument.xml") ...
3828d895a5abb9c6f783eee52d8c747f2f32c20c
25,561
def question_answers(id2line, convos): """ Divide the dataset into two sets: questions and answers. """ questions, answers = [], [] for convo in convos: for index, line in enumerate(convo[:-1]): questions.append(id2line[convo[index]]) answers.append(id2line[convo[index + 1]])...
f2654fcff2b9d90e78750cc8632eea9771361c4d
25,562
import copy def subgrid_kernel(kernel, subgrid_res, odd=False, num_iter=100): """ creates a higher resolution kernel with subgrid resolution as an interpolation of the original kernel in an iterative approach :param kernel: initial kernel :param subgrid_res: subgrid resolution required :retur...
8c62e9a09052faf2f52dc2141b0432b115c79417
25,563
import spacy.en import logging def get_spacy(): """ Loads the spaCy english processor. Tokenizing, Parsing, and NER are enabled. All other features are disabled. Returns: A spaCy Language object for English """ logging.info('Loading spaCy...') nlp = spacy.en.English(tagger=False,...
6abe2c9cb8cb0027c53c5e013d4127829b339699
25,564
import astroobs as obs import re from datetime import datetime def get_JDs(period='102', night=True, arrays=True, verbose=True): """ Get the Julian days for all ESPRESSO GTO runs in a given period. If `night`=True, return the JD of sunset and sunrise. This function returns the runs' start and end in ...
f21aea967e0d1a481d599bf7ffea2316d401a7ea
25,565
def normalize_breton(breton_string: str) -> str: """Applies Breton mutations.""" return (breton_string.strip().lower() @ DO_PREPROCESSING @ DO_SOFT_MUTATION @ DO_HARD_MUTATION @ DO_SPIRANT_MUTATION @ DO_POSTPROCESSING).string()
f5536f98c881d854fc279b81b5a6e99e4811165f
25,566
from keras.utils.data_utils import get_file from art import DATA_PATH def load_mnist(raw=False): """Loads MNIST dataset from `DATA_PATH` or downloads it if necessary. :param raw: `True` if no preprocessing should be applied to the data. Otherwise, data is normalized to 1. :type raw: `bool` :return: `...
fc661afef4062e14a90a3cbc1a837cd6f68b6039
25,567
def word_flag(*args): """ word_flag() -> flags_t Get a flags_t representing a word. """ return _ida_bytes.word_flag(*args)
765051d3c51974f24cf71a846ab3ffed4767a3d0
25,568
from typing import Optional from typing import Dict from typing import Iterable from typing import Union from typing import List def get_sequence_annotations( sequence: str, allow: Optional[set] = {"H", "K", "L"}, scheme: Optional[str] = "chothia", cdr1_scheme: Optional[Dict[str, Iterable]] = { ...
3f7d74693086e7603215d912083653005cdddb5a
25,570
import stat def skew(variable=None, weights=None, data=None): """Return the asymmetry coefficient of a sample. Parameters ---------- data : pandas.DataFrame variable : array-like, str weights : array-like, str data : pandas.DataFrame Object which stores ``variable`` and ``weights`...
08be7f2e9741855b699e847307c61b14ab6b3009
25,571
def deep_initial_state(batch_size, h_size, stack_size): """ Function to make a stack of inital state for a multi-layer GRU. """ return tuple(static_initial_state(batch_size, h_size) for layer in range(stack_size))
4d6bc65d2fcb158a99a08d88c755c81ca08433f3
25,572
def create_element(pan_elem, elem_type=None)->Element: """ Find the element type and call constructor specified by it. """ etype = 'ELEMENT TYPE MISSING' if elem_type is not None: etype = elem_type elif 't' in pan_elem: etype = pan_elem['t'] elif 'pandoc-api-version' in pa...
c5507a35e7a75676e450d0f960fd3b70c873440d
25,573
def load_weights(variables, file_name): """Reshapes and loads official pretrained Yolo weights. Args: variables: A list of tf.Variable to be assigned. file_name: A name of a file containing weights. Returns: A list of assign operations. """ with open(file_name, "rb") as f: ...
3d953792ae1e13285044f40dd840fe2400f20243
25,574
def parsing_sa_class_id_response(pdu: list) -> int: """Parsing TaiSEIA class ID response protocol data.""" packet = SAInfoResponsePacket.from_pdu(pdu=pdu) if packet.service_id != SARegisterServiceIDEnum.READ_CLASS_ID: raise ValueError(f'pdu service id invalid, {pdu}') return int.from_bytes(packe...
e55c6e7041349f036babfd7e9699bfcfe1ff5dea
25,575
def wrr(self) -> int: """ Name: Write ROM port. Function: The content of the accumulator is transferred to the ROM output port of the previously selected ROM chip. The data is available on the output pins until a new WRR is execute...
a019f176bba0e50d73906abd8a20862c4993b75f
25,576
def convert_to_signed_int_32_bit(hex_str): """ Utility function to convert a hex string into a 32 bit signed hex integer value :param hex_str: hex String :return: signed 32 bit integer """ val = int(hex_str, 16) if val > 0x7FFFFFFF: val = ((val+0x80000000) & 0xFFFFFFFF) - 0x80000000 ...
f8d39b20475c30f162948167f8534e367d9c58e8
25,577
def parent_node(max_child_node, max_parent_node): """ Parents child node into parent node hierarchy :param max_child_node: MaxPlus.INode :param max_parent_node: MaxPlus.INode """ max_child_node.SetParent(max_parent_node) return max_child_node
1a54d4c485e61361633165da0f05c8f871296ae6
25,578
import tensorflow as tf import torch def to_numpy_or_python_type(tensors): """Converts a structure of `Tensor`s to `NumPy` arrays or Python scalar types. For each tensor, it calls `tensor.numpy()`. If the result is a scalar value, it converts it to a Python type, such as a float or int, by calling `r...
34ea32fb2cf4fe8e45c429139876e7f1afc9f794
25,580
def _get_flow(args): """Ensure the same flow is used in hello world example and system test.""" return ( Flow(cors=True) .add(uses=MyTransformer, replicas=args.replicas) .add(uses=MyIndexer, workspace=args.workdir) )
625164c400f420cbb255cfdaa32f79c4862e23ea
25,581
def get_group_id( client: AlgodClient, txids: list ) -> list: """ Gets Group IDs from Transaction IDs :param client: an AlgodClient (GET) :param txids: Transaction IDs :return: gids - Group IDs """ # Get Group IDs gids = [] print("Getting gids...") try: w...
937b29f6b482ed1e62612a07cc80c17c6737c143
25,582
import logging import tqdm import multiprocessing def _simple_proc(st, sampling_rate=10, njobs=1): """ A parallel version of `_proc`, i.e., Basic processing including downsampling, detrend, and demean. :param st: an obspy stream :param sampling_rate: expected sampling rate :param njobs: number of...
aa24340d0d43ad8f6c042ed5e04bc94f2ec28cc3
25,583
from datetime import datetime def closing_time(date=datetime.date.today()): """ Get closing time of the current date. """ return datetime.time(13, 0) if date in nyse_close_early_dates(date.year) else datetime.time(16, 0)
40670512dbebfe65c3eb2b2790881fc91415aa40
25,584
def cos_fp16(x: tf.Tensor) -> tf.Tensor: """Run cos(x) in FP16, first running mod(x, 2*pi) for range safety.""" if x.dtype == tf.float16: return tf.cos(x) x_16 = tf.cast(tf.mod(x, 2 * np.pi), tf.float16) return tf.cos(x_16)
3212eb19e43fa733490d2cfcfffcc0094715022b
25,585
from typing import Callable def is_documented_by(original: Callable) -> Callable[[_F], _F]: """ Decorator to set the docstring of the ``target`` function to that of the ``original`` function. This may be useful for subclasses or wrappers that use the same arguments. :param original: """ def wrapper(target: _...
acd582112371ccfffd53762546415353abbd3129
25,586
def check_if_bst(root, min, max): """Given a binary tree, check if it follows binary search tree property To start off, run `check_if_bst(BT.root, -math.inf, math.inf)`""" if root == None: return True if root.key < min or root.key >= max: return False return check_if_bst(root.left,...
1bb4b601ef548aec9a4ab2cf5242bc5875c587a2
25,587
from typing import Union import pathlib from typing import Sequence from typing import Any import torchvision def create_video_file( root: Union[pathlib.Path, str], name: Union[pathlib.Path, str], size: Union[Sequence[int], int] = (1, 3, 10, 10), fps: float = 25, **kwargs: Any, ) -> pathlib.Path: ...
f11748ae86a80a5f4d9c859c313837fac7effa32
25,589
def aggregate(collection, pipeline): """Executes an aggregation on a collection. Args: collection: a `pymongo.collection.Collection` or `motor.motor_tornado.MotorCollection` pipeline: a MongoDB aggregation pipeline Returns: a `pymongo.command_cursor.CommandCursor` or ...
03ea889ea23fb81c6a329ee270df2ac253e90d69
25,590
def decryptAES(key, data, mode=2): """decrypt data with aes key""" return aes.decryptData(key, data, mode)
30f5b4173a8ed388a13481a2fd41293cd2304b21
25,591
import requests def __ipv6_safe_get(endpoint: str, addr: str) -> str: """HTTP GET from endpoint with IPv6-safe Host: header Args: endpoint: The endpoint path starting with / addr: full address (IPV6 or IPv4) of server Notes: * This is needed because the Py...
adb1c7c2300e9e41049a9eda957f264322095d9c
25,592
def format_advertisement(data): """ format advertisement data and scan response data. """ resolve_dict = { # FLAGS AD type st_constant.AD_TYPE_FLAGS: 'FLAGS', # Service UUID AD types st_constant.AD_TYPE_16_BIT_SERV_UUID: '16_BIT_SERV_UUID', st_constant.AD_TYPE_16_BIT_SERV...
a2b2740c45debe6c801ac80d99c8ed2b4537c205
25,593
def is_dicom_file(path): """Check if the given path appears to be a dicom file. Only looks at the extension, not the contents. Args: path (str): The path to the dicom file Returns: bool: True if the file appears to be a dicom file """ path = path.lower() for ext in DICOM_E...
2bd20b0f9bf40db24e9c6df4591127f59d07f882
25,594
import math def build_graph(df_list, sens='ST', top=410, min_sens=0.01, edge_cutoff=0.0, edge_width=150, log=False): """ Initializes and constructs a graph where vertices are the parameters selected from the first dataframe in 'df_list', subject to the constraints set by 'sens', 'top',...
b17b3f57ab21df0117e61a12005f401f81620368
25,595
def ranking_scores(prng=None, mix=False, permute=False, gamma=0.01, beta=5., N=100, l=1, means=None, stds=None): """ Generate the ranking scores. Parameters ---------- prng : random generator container Seed for the random number generator. mix : bool ...
40801599ab67d852740d5219d22debdbed91de39
25,596
def calculate_direction(G, cutoff, normalize=True): """ Calculate direction for entire network Parameters ---------- G : nx.graph Fault network cutoff : int, float Cutoff distance for direction normalize : bolean Normalize direction (default: True) Returns ...
9b64e0e8226579728f76ab510e672372cb708338
25,597
from datetime import datetime def generateVtBar(row): """生成K线""" bar = VtBarData() bar.symbol = row['code'] bar.exchange = '' bar.vtSymbol = bar.symbol bar.open = row['open'] bar.high = row['high'] bar.low = row['low'] bar.close = row['close'] bar.volume = row['volume'] ...
8431b313927692743d727ef9225e33899cc6c916
25,598
def coords_to_id(traversed): """calculate the id in level-order from the coordinates Args: input: traversed tree as list of dict Returns: traversed tree (dict) with id as key """ traversed_id = {} #print('coords to id, traversed ', traversed) for node in traversed: ...
91f993f9693e01983de1f7fa124dcb5cb39a92f9
25,600
def dataframe_to_ipy_image(df, f=None, **kwargs): """Create IPython Image from PIL Image. Args: df - dataframe to render f - operation to perform on PIL Image (e.g. f=lambda img: img.rotate(-90, expand=True)) kwargs - arguments to IPython.display.Image, such as width and height for html display ...
44348ac041067620bfa37cdedb22f3544e6bc940
25,601
def read_dmarkov(columns, rows, D, symbolization_type, division_order, suffix=["normal", "gaussian002"]): """ Reads the result files for the D-Markov algorithm. The function requires a configuration for the parameters of the D-Markov. The suffix parameter indicates if the non-modified files should be loaded...
c9fec2d46cbc8c3f4bcf7fc112779432dd6e9155
25,603
import torch def compute_output_shape(observation_space, layers): """Compute the size of the output after passing an observation from `observation_space` through the given `layers`.""" # [None] adds a batch dimension to the random observation torch_obs = torch.tensor(observation_space.sample()[None]) ...
865b9b90f39f5726feb16da70afc515071991fd7
25,604
def tenure_type(): """ RESTful CRUD controller """ return s3_rest_controller(#rheader = s3db.stdm_rheader, )
bfee3c2be579e1db6e8799b4a9d3156130b802a9
25,605
def _format_port(port): """ compute the right port type str Arguments ------- port: input/output port object Returns ------- list a list of ports with name and type """ all_ports = [] for key in port: one_port = {} one_port['name'] = key port...
2fa65686b6b764afc97a200a02baec65645c9879
25,606
import io def proc_cgroups(proc='self'): """Read a process' cgroups :returns: ``dict`` - Dictionary of all the process' subsystem and cgroups. """ assert isinstance(proc, int) or '/' not in proc cgroups = {} with io.open(_PROC_CGROUP.format(proc), 'r') as f: for cgroup_line i...
95cb24cbbb4167dd2fa26ce36d78e5f532f10c1a
25,608
import csv def load_csv_data( data_file_name, *, data_module=DATA_MODULE, descr_file_name=None, descr_module=DESCR_MODULE, ): """Loads `data_file_name` from `data_module with `importlib.resources`. Parameters ---------- data_file_name : str Name of csv file to be loaded fr...
3629dded45954c25e538c53b5c7bc5d0dfec0a39
25,609
def ptFromSudakov(sudakovValue): """Returns the pt value that solves the relation Sudakov = sudakovValue (for 0 < sudakovValue < 1) """ norm = (2*CA/pi) # r = Sudakov = exp(-alphas * norm * L^2) # --> log(r) = -alphas * norm * L^2 # --> L^2 = log(r)/(-alphas*norm) L2 = log(sudakovVal...
8ba504749f13ed1046799b5456d1f6f3c74bfc1e
25,610
def _set_lod_2(gml_bldg, length, width, height, bldg_center): """Adds a LOD 2 representation of the building based on building length, width and height alternative way to handle building position Parameters ---------- gml_bldg : bldg.Building() object A building object, where bldg is ...
309f66319c5cce07adbcb456548b3c29f707d96c
25,611
def send_mail(subject, message, from_email, recipient_list, html_message='', scheduled_time=None, headers=None, priority=PRIORITY.medium): """ Add a new message to the mail queue. This is a replacement for Django's ``send_mail`` core email method. """ subject = force_text(subject) ...
a97103e5e56463170122252073ebcc873306c708
25,613
def proxy_a_distance(source_X, target_X): """ Compute the Proxy-A-Distance of a source/target representation """ nb_source = np.shape(source_X)[0] nb_target = np.shape(target_X)[0] train_X = np.vstack((source_X, target_X)) train_Y = np.hstack((np.zeros(nb_source, dtype=int), np.ones(nb_targe...
fe0102cfd2a5a3cadb64a5ddfb7705e7b8440028
25,614
import json def load_metadata(stock_model_name="BlackScholes", time_id=None): """ load the metadata of a dataset specified by its name and id :return: dict (with hyperparams of the dataset) """ time_id = _get_time_id(stock_model_name=stock_model_name, time_id=time_id) path = '{}{}-{}/'.format(...
1171bf3a06327e907449872755315db8c34565c8
25,615
from typing import List import torch def evaluate(env: AlfEnvironment, algorithm: RLAlgorithm, num_episodes: int) -> List[alf.metrics.StepMetric]: """Perform one round of evaluation. Args: env: the environment algorithm: the training algorithm num_episodes: number of epis...
0218f1a38be8f897ac3b2a70036213877f5f7654
25,616
from pagure.hooks import BaseHook def get_plugin_names(blacklist=None, without_backref=False): """Return the list of plugins names. :arg blacklist: name or list of names to not return :type blacklist: string or list of strings :arg without_backref: whether or not to include hooks that have ba...
7f3b560334a5680fdcb4a47929613706bb699393
25,617
def is_autosync(*args): """ is_autosync(name, type) -> bool is_autosync(name, tif) -> bool Is the specified idb type automatically synchronized? @param name (C++: const char *) @param type (C++: const type_t *) """ return _ida_typeinf.is_autosync(*args)
0f7eacc9931897f5fc0f076d0e07e0f1e1e01bce
25,618
def scanboards(dirpath): """Scans the directory for board files and returns an array""" print("Scanning for JSON board data files...", end = "") files = [x for x in subfiles(dirpath) if x.endswith(".json") and not x.endswith("index.json")] print("Found {} in \"{}\"".format(len(files), dir...
9cfce78b06fef0b8f7ebaa3d1c5904dfd3e0ec56
25,619
def router_get_notification() -> dict: """Lista todas as configurações do BOT Telegram.""" logger.log('LOG ROTA', "Chamada rota /get_all.") return {"configuracoes": TelegramNotifier.make_current_cfg_dict()}
46faf67e02d537de49616085a1bcbb30f3087805
25,620
def script_filter_maximum_value(config): """ The scripting version of `filter_maximum_value`. This function applies the filter to the entire directory (or single file). It also adds the tags to the header file of each fits file indicating the number of pixels filtered for this filter. Parame...
8eccc2356c803d63c1ddfc7603e1dc784ccc49fe
25,621
import time def pretty_date(d): """ returns a html formatted pretty date """ special_suffixs = {1 : "st", 2 : "nd" , 3 : "rd", 21 : "st", 22 : "nd", 23 : "rd", 31 : "st"} suffix = "th" if d.tm_mday in special_suffixs: suffix = special_suffixs[d.tm_mday] suffix = "<sup>" + suffix + "</sup>" day = ti...
7d6675f115021ddd46b2a614e831c9fae8faf7ad
25,622
from datetime import datetime import dateutil def update(model, gcs_bucket, gcs_object): """Updates the given GCS object with new data from the given model. Uses last_modified to determine the date to get items from. Bases the identity of entities in the GCS object on their 'id' field -- existing ent...
66bde1371383f16c9449a3aec29e894e6a473d44
25,623
def member_requests_list(context, data_dict): """ Show request access check """ return _only_registered_user()
c3ffdf798aabc80b3bd91160e9a580ff38c9540d
25,626
def get_conductivity(sw_tdep,mesh,rvec,ham_r,ndegen,avec,fill,temp_max,temp_min,tstep,sw_tau,idelta=1e-3,tau0=100): """ this function calculates conductivity at tau==1 from Boltzmann equation in metal """ def calc_Kn(eig,veloc,temp,mu,tau): dfermi=0.25*(1.-np.tanh(0.5*(eig-mu)/temp)**2)/temp ...
0304781bac6160b353a90e5bce061faa89075bc0
25,627
from typing import List from typing import Union import time def time_match( data: List, times: Union[List[str], List[int], int, str], conv_codes: List[str], strptime_attr: str, name: str, ) -> np.ndarray: """ Match times by applying conversion codes to filtering list. Parameters ...
0480f5ca3e29ebcc4f44bef5a81db8fb36f78616
25,628
def find_best_input_size(sizes=[40]): """ Returns the average and variance of the models """ accuracies = [] accuracy = [] t = [] sigma = [] time = [] #sizes = np.arange(5, 80, 5) for size in sizes: #for size in [80]: accuracy = [] N = 20 for j in range(N): ...
3d22441d07b44779cde6c4347669a435568f0378
25,629
import torch def eval_acc(trainer, dataset="val"): """ """ trainer.model.eval() with torch.no_grad(): shot_count = 0 total_count = 0 for inputs,targets in trainer.val_dataset(): inputs = nested_to_cuda(inputs, trainer.device) targets = nested_to_cuda(tar...
452861ccb5805778d5dd0bc83226b73539b8aebb
25,630
def _floor(n, base=1): """Floor `n` to a multiple of `base`""" return n // base * base
49019e4aa925b4f77a7f13f9919d36948bd132cc
25,632
def fixed_timezone(offset): # type: (int) -> _FixedTimezone """ Return a Timezone instance given its offset in seconds. """ if offset in _tz_cache: return _tz_cache[offset] tz = _FixedTimezone(offset) _tz_cache[offset] = tz return tz
401303d1893bc2ab7bee19ba09161549a2cc7fb2
25,634
def getFactoriesInfo(): """ Returns a dictionary with information on how to create an object Sensor from its factory """ return {'Stitcher': { 'factory':'createStitcher' } }
75806002b1ada6bd1a87c9bde6b2e47f587d988d
25,635
from typing import Dict from typing import List from typing import Optional def pending_observations_as_array( pending_observations: Dict[str, List[ObservationFeatures]], outcome_names: List[str], param_names: List[str], ) -> Optional[List[np.ndarray]]: """Re-format pending observations. Args: ...
bc9bfff51b991b413b5861f55c8b0f55331ab763
25,636
def inverted_conditional_planar(input_dim, context_dim, hidden_dims=None): """ A helper function to create a :class:`~pyro.distributions.transforms.ConditionalPlanar` object that takes care of constructing a dense network with the correct input/output dimensions. :param input_dim: Dimension of inpu...
8bf5ae5dd6d8743a3eb1506b26dec5cf51af2bde
25,638
def create_category_index(categories): """Creates dictionary of COCO compatible categories keyed by category id. Args: categories: a list of dicts, each of which has the following keys: 'id': (required) an integer id uniquely identifying this category. 'name': (required) string representing category...
226a39189d4203e2861bbba7334d5b8bbaa3b7df
25,639
import torch def n_step_returns(q_values, rewards, kls, discount=0.99): """ Calculates all n-step returns. Args: q_values (torch.Tensor): the Q-value estimates at each time step [time_steps+1, batch_size, 1] rewards (torch.Tensor): the rewards at each time step [time_steps, batch_size, 1]...
3bbd6026046328dc8ef63ab3e871f6c47636cb80
25,640
import random def random_split_exact(iterable, split_fractions=None): """Randomly splits items into multiple sample lists according to the given split fractions. The number of items in each sample list will be given exactly by the specified fractions. Args: iterable: a finite iterable ...
2b7ae86e55b9be225e94cfc983295beeb3ed08cf
25,642
def computeMaskIntra(inputFilename, outputFilename, m=0.2, M=0.9, cc=1): """ Depreciated, see compute_mask_intra. """ print "here we are" return compute_mask_intra(inputFilename, outputFilename, m=m, M=M, cc=cc)
0eaf8b8845c12b1fc90cb032881dacf53a2c7d12
25,644
def read_space_delimited(filename, skiprows=None, class_labels=True): """Read an space-delimited file skiprows: list of rows to skip when reading the file. Note: we can't use automatic comment detection, as `#` characters are also used as data labels. class_labels: boolean if true, the last ...
be25b4f6c3c775f12fdfef7f334b4886c85a514e
25,645
def get_gas_price(endpoint=_default_endpoint, timeout=_default_timeout) -> int: """ Get network gas price Parameters ---------- endpoint: :obj:`str`, optional Endpoint to send request to timeout: :obj:`int`, optional Timeout in seconds Returns ------- int Ne...
b7f18a5a5044d8aeee7a63b702b01944cbff597b
25,646