content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def create_connection(host, username, password): """ create a database connection to the SQLite database specified by db_file :return: Connection object or None """ try: conn = mysql.connect(host=host, # your host, usually db-guenette_neutrinos.rc.fas.harvard.edu ...
09c540115ce788d1f5fd09d789327ac6951cb9a2
7,600
def Dadjust(profile_ref, profile_sim, diffsys, ph, pp=True, deltaD=None, r=0.02): """ Adjust diffusion coefficient fitting function by comparing simulated profile against reference profile. The purpose is to let simulated diffusion profile be similar to reference profile. Parameters ---------- ...
d8b13e8d785a31219197936a9bd7b5d275f23351
7,601
def setup_test(): """setup test""" def create_test_tables(db): """create test tables""" db(""" create table if not exists person ( id integer PRIMARY KEY AUTOINCREMENT, name varchar(100), age integer, kids integer, ...
539ca396ba3098e79ec5064ccde7245d91106ef2
7,602
def compute_levenshtein_blocks(seq1, seq2, max_complexity=1e8): """Compute the Levenshtein blocks of insertion, deletion, replacement. """ # TODO: better method for dealing with long sequences? l1, l2 = len(seq1), len(seq2) if l1 * l2 > max_complexity: return [("change", (0, l1), (0, l2))] ...
78b12b0cdffdf42403ace31d33d30c1e0a0e23d4
7,603
def mapdict_values(function, dic): """ Apply a function to a dictionary values, creating a new dictionary with the same keys and new values created by applying the function to the old ones. :param function: A function that takes the dictionary value as argument :param dic: A dictionary...
03abbe7d7ec32d70ad0d4729913037f2199e977c
7,604
from typing import Optional async def callback( request: Request, code: str = None, error: Optional[str] = Query(None), db: AsyncSession = Depends(get_db), ): """ Complete the OAuth2 login flow """ client = get_discord_client() with start_span(op="oauth"): with start_span(...
f7d76c385360f6d2113cd7fb470344c1e7c96027
7,605
def align_centroids(config, ref): """Align centroids""" diff_centroids = np.round(ref.mean(axis=0) - config.mean(axis=0)) # diff_centroids = np.round(diff_centroids).astype(int) config = config + diff_centroids return config
cd579a911cb4ae59aa274836de156620305e592a
7,606
def _make_headers_df(headers_response): """ Parses the headers portion of the watson response and creates the header dataframe. :param headers_response: the ``row_header`` or ``column_header`` array as returned from the Watson response, :return: the completed header dataframe """ headers_d...
621d46da0de2056ac98747a51f2ac2cbfdd52e5e
7,607
def getMemInfo() -> CmdOutput: """Returns the RAM size in bytes. Returns: CmdOutput: The output of the command, as a `CmdOutput` instance containing `stdout` and `stderr` as attributes. """ return runCommand(exe_args=ExeArgs("wmic", ["memorychip", "get", "capacity"]))
c57312d83182349e0847d0eb49606c401a3a0d27
7,608
def svn_swig_py_make_editor(*args): """svn_swig_py_make_editor(PyObject * py_editor, apr_pool_t pool)""" return _delta.svn_swig_py_make_editor(*args)
2041342a1bef3ea0addb004e1bd4539c58445c66
7,609
def register_confirm(request, activation_key): """finish confirmation and active the account Args: request: the http request activation_key: the activation key Returns: Http redirect to successful page """ user_safety = get_object_or_404(UserSafety, activation_key=activation...
c677f246ff3088d58912bc136f1d2461f58ba10b
7,610
def get_best_z_index(classifications): """Get optimal z index based on quality classifications Ties are broken using the index nearest to the center of the sequence of all possible z indexes """ nz = len(classifications) best_score = np.min(classifications) top_z = np.argwhere(np.array(clas...
90b10dda47c071a3989a9de87061694270e67d69
7,611
import glob def mean_z_available(): """docstring for mean_z_available""" if glob.glob("annual_mean_z.nc"): return True return False
d53f8dc6fe540e8f74fd00760d1c810e510e53b8
7,612
import time def wait_for_url(monitor_url, status_code=None, timeout=None): """Blocks until the URL is availale""" if not timeout: timeout = URL_TIMEOUT end_time = time.time() + timeout while (end_time - time.time()) > 0: if is_url(monitor_url, status_code): return True ...
7d7ca1fd51d4415c58ab3928bd163401fb548b9a
7,613
import requests import io import tarfile def sources_from_arxiv(eprint): """ Download sources on arXiv for a given preprint. :param eprint: The arXiv id (e.g. ``1401.2910`` or ``1401.2910v1``). :returns: A ``TarFile`` object of the sources of the arXiv preprint. """ r = requests.get("http://a...
b26c46009b23c5a107d6303b567ab97492f91ad9
7,614
import subprocess import os def nvidia_smi_gpu_memused(): # pragma: no cover """Returns the GPU memory used by the process. (tested locally, cannot be tested on Travis CI bcs no GPU available) Returns ------- int [MiB] """ # if theano.config.device=...
147fb1c537e00ca88f567a4ab0701bafd8624e0d
7,615
def render(): """ This method renders the HTML webside including the isOnline Status and the last 30 database entries. :return: """ online = isonline() return render_template("index.html", news=News.query.order_by(News.id.desc()).limit(30), online=online)
4b0584d33fb84f05afbbcfe016d7428c4f75a4d3
7,616
import aiohttp async def execute_request(url): """Method to execute a http request asynchronously """ async with aiohttp.ClientSession() as session: json = await fetch(session, url) return json
1845fed4acce963a0bc1bb780cdea16ba9dec394
7,617
from typing import List def game_over(remaining_words: List[str]) -> bool: """Return True iff remaining_words is empty. >>> game_over(['dan', 'paul']) False >>> game_over([]) True """ return remaining_words == []
8d29ef06bd5d60082646cef00f77bbabfbac32eb
7,618
import csv def read_manifest(instream): """Read manifest file into a dictionary Parameters ---------- instream : readable file like object """ reader = csv.reader(instream, delimiter="\t") header = None metadata = {} for row in reader: if header is None: header...
afa6c2bb0a9d81267b1d930026a229be924a1994
7,619
def get_backbone_from_model(model:Model, key_chain:list) -> nn.Cell: """Obtain the backbone from a wrapped mindspore Model using the key chain provided. Args: model(Model): A Model instance with wrapped network and loss. key_chain(list[str]): the keys in the right order according to ...
0ddabf30c50e9d58ce18b0010107d92f8518b9bc
7,620
def dv_upper_lower_bound(f): """ Donsker-Varadhan lower bound, but upper bounded by using log outside. Similar to MINE, but did not involve the term for moving averages. """ first_term = f.diag().mean() second_term = logmeanexp_nodiag(f) return first_term - second_term
a7f9a3910a934f836204c5c47d9139be31860ec1
7,621
def create_training_files_for_document( file_name, key_field_names, ground_truth_df, ocr_data, pass_number): """ Create the ocr.json file and the label file for a document :param file_path: location of the document :param file_name: just the document name.ext ...
4832e28904f2c950ceb5526eaa8ab61568c55a8c
7,622
def incoming(ui, repo, source="default", **opts): """show new changesets found in source Show new changesets found in the specified path/URL or the default pull location. These are the changesets that would have been pulled if a pull at the time you issued this command. See pull for valid source f...
9bf41cdc4de5c82634fae038940951ad738fd636
7,623
import time def timeout(limit=5): """ Timeout This decorator is used to raise a timeout error when the given function exceeds the given timeout limit. """ @decorator def _timeout(func, *args, **kwargs): start = time.time() result = func(*args, **kwargs) duration =...
c68fee9530512ce1603ec7976f4f1278205b1f92
7,624
from typing import Union def OIII4363_flux_limit(combine_flux_file: str, verbose: bool = False, log: Logger = log_stdout()) -> \ Union[None, np.ndarray]: """ Determine 3-sigma limit on [OIII]4363 based on H-gamma measurements :param combine_flux_file: Filename of ASCII fil...
109f887693df16661d7766840b0026f7e9bca82d
7,625
import numpy def convert_units_co2(ds,old_data,old_units,new_units): """ Purpose: General purpose routine to convert from one set of CO2 concentration units to another. Conversions supported are: umol/m2/s to gC/m2 (per time step) gC/m2 (per time step) to umol/m2/s mg/m3 to um...
38ce2987bfa4c5505fe64779ce752617862138fd
7,626
def query_urlhaus(session, provided_ioc, ioc_type): """ """ uri_dir = ioc_type if ioc_type in ["md5_hash", "sha256_hash"]: uri_dir = "payload" api = "https://urlhaus-api.abuse.ch/v1/{}/" resp = session.post(api.format(uri_dir), timeout=180, data={ioc_type: provided_ioc}) ioc_dicts ...
171bff1e9b1bfdf8ac6b91a4bbbd7226f80c8c4c
7,627
def arrow_to_json(data): """ Convert an arrow FileBuffer into a row-wise json format. Go via pandas (To be revisited!!) """ reader = pa.ipc.open_file(data) try: frame = reader.read_pandas() return frame.to_json(orient='records') except: raise DataStoreException("Unabl...
d49ee49b7071d0b857feeb878c99ce65e82460e9
7,628
import pathlib def get_wmc_pathname(subject_id, bundle_string): """Generate a valid pathname of a WMC file given subject_id and bundle_string (to resolve ACT vs noACT). The WMC file contrains the bundle-labels for each streamline of the corresponding tractogram. """ global datadir ACT_str...
fcc570e3e59b99b94de95dc4f15c1fee2fe0f0f2
7,629
def _union_polygons(polygons, precision = 1e-4, max_points = 4000): """ Performs the union of all polygons within a PolygonSet or list of polygons. Parameters ---------- polygons : PolygonSet or list of polygons A set containing the input polygons. precision : float Desired prec...
f6951a67a2ed4099b5321b98517810de43024036
7,630
from typing import Callable from re import T from typing import Optional def parse_or_none( field: str, field_name: str, none_value: str, fn: Callable[[str, str], T], ) -> Optional[T]: """ If the value is the same as the none value, will return None. Otherwise will attempt to run the fn with f...
4a0c2d8ec819fe6b8a9a24a60f54c62cb83e68ac
7,631
def get_lattice_parameter(elements, concentrations, default_title): """Finds the lattice parameters for the provided atomic species using Vagars law. :arg elements: A dictionary of elements in the system and their concentrations. :arg title: The default system title. :arg concentrations: The concentrat...
34e914e38b8c4d25d9ed5fd09f435d7358f99a99
7,632
import string def tokenize(text): """ Tokenizes,normalizes and lemmatizes a given text. Input: text: text string Output: - array of lemmatized and normalized tokens """ def is_noun(tag): return tag in ['NN', 'NNS', 'NNP', 'NNPS'] def is_verb(tag): return tag ...
672af73d594c7a134226f4ae9a265f19b14ced34
7,633
def bandpass_filterbank(bands, fs=1.0, order=8, output="sos"): """ Create a bank of Butterworth bandpass filters Parameters ---------- bands: array_like, shape == (n, 2) The list of bands ``[[flo1, fup1], [flo2, fup2], ...]`` fs: float, optional Sampling frequency (default 1.) ...
4cbe3acb30a0f08d39e28b46db520fdac420010d
7,634
def get_couch_client(https: bool = False, host: str = 'localhost', port: int = 5984, request_adapter: BaseHttpClient = HttpxCouchClient, **kwargs) -> CouchClient: """ Initialize CouchClient Parameters ---------- htt...
db242556c11debc9dff57929182d3e6932ef13d1
7,635
def compute_rmse(loss_mse): """ Computes the root mean squared error. Args: loss_mse: numeric value of the mean squared error loss Returns: loss_rmse: numeric value of the root mean squared error loss """ return np.sqrt(2 * loss_mse)
a81024cd402c00b0d6f3bfaccc089695fb5f4e0a
7,636
def __detect_geometric_decomposition(pet: PETGraphX, root: CUNode) -> bool: """Detects geometric decomposition pattern :param pet: PET graph :param root: root node :return: true if GD pattern was discovered """ for child in pet.subtree_of_type(root, NodeType.LOOP): if not (child.reducti...
27d90b6ced48a0db081d9881e39600d641855343
7,637
def add_two_frags_together(fragList, atm_list, frag1_id, frag2_id): """Combine two fragments in fragList.""" new_id = min(frag1_id, frag2_id) other_id = max(frag1_id, frag2_id) new_fragList = fragList[:new_id] # copy up to the combined one new_frag = { # combined frag 'ids': fragList[frag1...
9c226883d6c021e151c51889017f56ea6a4cba3a
7,638
from typing import Tuple import tqdm from sys import stdout import tarfile def load_dataset( file: str, out_dir: str = "/tmp", download: bool = True, url: str = None, labels: str = "labels", verbose: int = 2, ) -> Tuple[ndarray, ndarray, ndarray, ndarray]: """Load Dataset from storage or c...
17ad37b04c5dc14f0575d07cf677d6335058bf8b
7,639
def concatenate(arrays, axis=0): """ Joins a sequence of tensors along an existing axis. Args: arrays: Union[Tensor, tuple(Tensor), list(Tensor)], a tensor or a list of tensors to be concatenated. axis (int, optional): The axis along which the tensors will be joined, if...
a85db3673d3a50d76374b809b583a8ca5325d4c3
7,640
import json def get_answer(): """ get answer """ # logger M_LOG.info("get_answer") # exist answer in dict ? if "answer" in gdct_data: # convert to JSON l_json = json.dumps(gdct_data["answer"]) M_LOG.debug("Requested answer: %s", str(l_json)) # remove ans...
7f4b97b2a470d491326cdd341475bc15987fa299
7,641
def default_todo_data(): """Словарь с данными пользователя поумолчанию""" return {"title": "Молоко", "description": "Купить молоко в Ашане 200 литров", "created_datetime": "2041-08-12T00:00:00.000Z"}
2cd873f266d758c8d8510418fd173f35f4b366ab
7,642
def generate_new_key(access_key, secret_key, user_to_rotate): """generates a new key pair and returns the access key and secret key""" LOGGER.info("Begin generate new key") iam_client = boto3.client('iam', aws_access_key_id=access_key, aws_secret_access_key=secret_key) resp = iam_client.create_access_ke...
41fff2da39408661f329d2e1f47488dce8d76652
7,643
def withCHID(fcn): """decorator to ensure that first argument to a function is a Channel ID, ``chid``. The test performed is very weak, as any ctypes long or python int will pass, but it is useful enough to catch most accidental errors before they would cause a crash of the CA library. """ # It...
98ac8fdc812a8e9b7706e1932db662819e830597
7,644
import inspect def current_user_get(): """ユーザー情報取得 user info get Returns: Response: HTTP Respose """ app_name = multi_lang.get_text("EP020-0001", "ユーザー情報:") exec_stat = multi_lang.get_text("EP020-0017", "取得") error_detail = "" try: globals.logger.debug('#' * 50) ...
f2bf2c81b176e985973dad9e5841ecd1af599a48
7,645
def asin(a: Dual) -> Dual: """inverse of sine or arcsine of the dual number a, using math.asin(x)""" if abs(a.value) >= 1: raise ValueError('Arcsin cannot be evaluated at {}.'.format(a.value)) value = np.arcsin(a.value) ders = dict() for k,v in a.ders.items(): ders[k] = 1/(np.sqrt(1-a.value**2))*v r...
6b15e737ae5beb69f8963aa752d7fba761dce56f
7,646
def hydrotopeQ(cover,hydrotopemap): """Get mean values of the cover map for the hydrotopes""" grass.message(('Get mean hydrotope values for %s' %cover)) tbl = grass.read_command('r.univar', map=cover, zones=hydrotopemap, flags='gt').split('\n')[:-1] #:-1 as last line hast line br...
371dc496a4bb2e33fc382dddaea66e83aa613abc
7,647
import re def convert_to_seconds(duration_str): """ return duration in seconds """ seconds = 0 if re.match(r"[0-9]+$", duration_str): seconds = int(duration_str) elif re.match(r"[0-9]+s$", duration_str): seconds = int(duration_str[:-1]) elif re.match(r"[0-9]+m$", duration_...
222905e6089510c6f204c6ea710572a5b2132d28
7,648
def get_chunk_n_rows(row_bytes: int, working_memory: Num, max_n_rows: int = None) -> int: """Calculates how many rows can be processed within working_memory Parameters ---------- row_bytes : int The expected number of bytes of memory that will be consum...
b7c2ab10c59edb6c2541e31264b28e06266d2fc3
7,649
import re def elasticsearch_ispartial_log(line): """ >>> line1 = ' [2018-04-03T00:22:38,048][DEBUG][o.e.c.u.c.QueueResizingEsThreadPoolExecutor] [search17/search]: there were [2000] tasks in [809ms], avg task time [28.4micros], EWMA task execution [790nanos], [35165.36 tasks/s], optimal queue is [35165], cur...
7263be4a74f1a92a6347393f62d9b67300d30c30
7,650
def find_signal_analysis(prior, sparsity, sigma_data): """ Generates a signal using an analytic prior. Works only with square and overcomplete full-rank priors. """ N, L = prior.shape k = np.sum(np.random.random(L) > (1 - sparsity)) V = np.zeros(shape=(L, L - k)) while np.linalg.matrix_...
49a7c26b6bc934d3588ae25c99eb62e0b544616f
7,651
from typing import List import asyncio import requests def download_images(sorted_urls) -> List: """Download images and convert to list of PIL images Once in an array of PIL.images we can easily convert this to a PDF. :param sorted_urls: List of sorted URLs for split financial disclosure :return: im...
3efde31975c7912e16ab2d990417c2aa753ca5bf
7,652
def get_molecules(struct, bonds_kw={"mult":1.20, "skin":0.0, "update":False}, ret="idx"): """ Returns the index of atoms belonging to each molecule in the Structure. """ bonds = struct.get_bonds(**bonds_kw) ## Build connectivity matrix graph = np.z...
99b67f95114ddd6c712c8fe63a0713a914b8888f
7,653
def cdivs(a,b,c,d,e,f,al1,al2,al3,x11,x21,x22,x23,x31,x32,x33): """Finds the c divides conditions for the symmetry preserving HNFs. Args: a (int): a from the HNF. b (int): b from the HNF. c (int): c from the HNF. d (int): d from the HNF. e (int): e from the HNF. ...
20a0044050964c5705f3bce2297f2724d6f12f71
7,654
def numeric_field_list(model_class): """Return a list of field names for every numeric field in the class.""" def is_numeric(type): return type in [BigIntegerField, DecimalField, FloatField, IntegerField, PositiveIntegerField, PositiveSmallIntegerField, S...
a501c2a7bc87f7cdea8945a946937f72cc0576a9
7,655
import tokenize def _get_lambda_source_code(lambda_fn, src): """Attempt to find the source code of the ``lambda_fn`` within the string ``src``.""" def gen_lambdas(): def gen(): yield src + "\n" g = gen() step = 0 tokens = [] for tok in tokenize.generate_tok...
5192a299bf88c9fdc070fae28e585cda3a09aadc
7,656
import requests import json def retrieve_keycloak_public_key_and_algorithm(token_kid: str, oidc_server_url: str) -> (str, str): """ Retrieve the public key for the token from keycloak :param token_kid: The user token :param oidc_server_url: Url of the server to authorize with :return: keycloak public...
87e706b56c63b991e1524b5d6ffcec86d6a9bc67
7,657
def read_conformations(filename, version="default", sep="\t", comment="#", encoding=None, mode="rb", **kw_args): """ Extract conformation information. Parameters ---------- filename: str Relative or absolute path to file that contains the RegulonDB information. Returns ---...
3588ee68a8a498dbfb1f85d65a8eff65b5ff5ed1
7,658
def maskRipple(inRpl, outFile, mask): """maskRipple(inRpl, outFile, mask) Sets the individual data items to zero based on the specified mask. If mask.getRGB(c,r)>0 / then copy the contents at(c,r) of inRpl to outFile.rpl. Otherwise the contents of outFile / is set to all zeros.""" outRpl = "%s.rpl...
65d5464e9de469cf45b47991ed838a79c587d965
7,659
def GetCurrentScene() -> Scene: """ Returns current scene. Raises SpykeException if current scene is not set. """ if not _currentScene: raise SpykeException("No scene is set current.") return _currentScene
82a065e4cbd0aa4b326d53b3360aac52a99ac682
7,660
import argparse import sys import os def Login(): """Performs interactive login and caches authentication token. Returns: non-zero value on error. """ ConfirmUserAgreedToS() parser = argparse.ArgumentParser() parser.add_argument('--browser', action='store_true', help=('Use brow...
7b305746fa128bcdce834ee036e5e231f5f72223
7,661
def timeago(seconds=0, accuracy=4, format=0, lang="en", short_name=False): """Translate seconds into human-readable. :param seconds: seconds (float/int). :param accuracy: 4 by default (units[:accuracy]), determine the length of elements. :param format: index of [led, literal, dict]. ...
b6a5858c3f5c5291b03654d076eb3f1e835f78c0
7,662
def generate_headline(ids=None): """Generate and return an awesome headline. Args: ids: Iterable of five IDs (intro, adjective, prefix, suffix, action). Optional. If this is ``None``, random values are fetched from the database. Returns: Tuple of parts a...
09fda0075b036ea51972b2f124733de9f34671fc
7,663
import webbrowser def open_in_browser(path): """ Open directory in web browser. """ return webbrowser.open(path)
41328b2b478f0bd69695da1868c412188e494d08
7,664
def lstm_cell_forward(xt, a_prev, c_prev, parameters): """ Implement a single forward step of the LSTM-cell as described in Figure (4) Arguments: xt -- your input data at timestep "t", numpy array of shape (n_x, m). a_prev -- Hidden state at timestep "t-1", numpy array of shape (n_a, m) c_prev ...
9d1ae3ea6da9de6827b5ecd9f8871ee8aae26d30
7,665
def encode_letter(letter): """ This will encode a tetromino letter as a small integer """ value = None if letter == 'i': value = 0 elif letter == 'j': value = 1 elif letter == 'l': value = 2 elif letter == 'o': value = 3 elif letter == 's': ...
6c72c4c9e44c93d045296ab1f49c7783f2b4fc59
7,666
async def register_log_event( registration: LogEventRegistration, db: Session = Depends(get_db) ): """ Log event registration handler. :param db: :param registration: Registration object :return: None """ reg_id = str(uuid4()) # Generate message for registration topic msg = Log...
62b84b9efa88512634d9c7a050e7c61ff06ba71a
7,667
def cvAbsDiffS(*args): """cvAbsDiffS(CvArr src, CvArr dst, CvScalar value)""" return _cv.cvAbsDiffS(*args)
b888683d1522c46c9dc7738a18b80f56efe975d3
7,668
from . import views # this must be placed here, after the app is created def create_template_app(**kwargs): """Create a template Flask app""" app = create_app(**kwargs) app.register_blueprints() return app
fbbb0018cd4da6897842f658ba3baf207e5614cc
7,669
def mse(predict, actual): """ Examples(rounded for precision): >>> actual = [1,2,3];predict = [1,4,3] >>> np.around(mse(predict,actual),decimals = 2) 1.33 >>> actual = [1,1,1];predict = [1,1,1] >>> mse(predict,actual) 0.0 """ predict = np.array(predict) actual = np.array(actu...
c42ee6d5531d40f727c41463f938c9c8f4ec6e84
7,670
import random def make_demo_measurements(num_measurements, extra_tags=frozenset()): """Make a measurement object.""" return [ make_flexural_test_measurement( my_id=__random_my_id(), deflection=random.random(), extra_tags=extra_tags ) for _ in range(num_measu...
10c452936e889a8553afd1a9a570e34abae73470
7,671
from re import S def _nrc_coron_rescale(self, res, coord_vals, coord_frame, siaf_ap=None, sp=None): """ Function for better scaling of NIRCam coronagraphic output for sources that overlap the image masks. """ if coord_vals is None: return res nfield = np.size(coord_vals[0]) psf_...
3b4e8596177e126955c7665333dd1305603f4e66
7,672
from .serializers import DocumentRelationSerializer def re_list(request): """ Returns the available relation tasks for a specific user Accessed through a JSON API endpoint """ cmd_str = "" with open('mark2cure/api/commands/get-relations.sql', 'r') as f: cmd_str = f.read() # Start ...
458b9fc9e784144e96ef8b4203e8b7b868c3350a
7,673
import os import time def run_tc(discover): """ BeautifulReport模块实现测试报告 :param discover: 测试套件 :return: """ if not os.path.exists(path_conf.REPORT_PATH): os.makedirs(path_conf.REPORT_PATH) fileName = path_conf.PROJECT_NAME + '_' + time.strftime('%Y-%m-%d %H_%M_%S') + '.html' tr...
da601470bf901905f5ca43e1b6bdeec5d330eafa
7,674
def csv_to_blob_ref(csv_str, # type: str blob_service, # type: BlockBlobService blob_container, # type: str blob_name, # type: str blob_path_prefix=None, # type: str charset=None # type: str ): ...
c0df47839e963a5401204bcd422c7f78a94efc87
7,675
def col_rev_reduce(matrix, col, return_ops=False): """ Reduces a column into reduced echelon form by transforming all numbers above the pivot position into 0's :param matrix: list of lists of equal length containing numbers :param col: index of column :param return_ops: performed operations are retu...
ab97078f0c92537532673d3dba3cb399d932342e
7,676
from typing import Dict import math def calculate_correlations(tetra_z: Dict[str, Dict[str, float]]) -> pd.DataFrame: """Return dataframe of Pearson correlation coefficients. :param tetra_z: dict, Z-scores, keyed by sequence ID Calculates Pearson correlation coefficient from Z scores for each tetra...
8acc745fb35f41b38ba186e8f367ea895191f894
7,677
def rowfuncbynumber(tup,othertable, number): """tup is the tuple of row labels for the current row. By default it is passed back unmodified. You can supply your own rowfunc to transform it when the tables being merged do not have the same structure or if you want to prevent the merging of certain rows...
bd64c52489a9786b4c1de2c9ee7c95643b2a5fe9
7,678
import os def save_book_metadata() -> FlaskResponse: """ XHR request. Update the information about a book. Raises: 404: if the user is not admin or the request is not POST. """ if not is_admin(): abort(404) # pragma: no cover if not ( all( x in request.for...
df92df8dbc817df1778b5d25c71f6d66a46463b5
7,679
def query_category_members(category, language='en', limit=100): """ action=query,prop=categories Returns all the members of a category up to the specified limit """ url = api_url % (language) query_args = { 'action': 'query', 'list': 'categorymembers', 'cmtitle': category...
4a09d73cce237152405031004e967192ad3f8929
7,680
from typing import List def _tokenize_text(text: str, language: str) -> List[str]: """Splits text into individual words using the correct method for the given language. Args: text: Text to be split. language: The configured language code. Returns: The text tokenized into a list of words. """ i...
284f1a7625de149b7f97ce51dcf88110ebae02b0
7,681
def ml64_sort_order(c): """ Sort function for measure contents. Items are sorted by time and then, for equal times, in this order: * Patch Change * Tempo * Notes and rests """ if isinstance(c, chirp.Note): return (c.start_time, 10) elif isinstance(c, Rest): re...
752a68796a12835661cfce5b2cfe5cba3ad5d7ef
7,682
def binary_logistic_loss_grad(linear_o, y): """Derivative of the binary_logistic_loss w.r.t. the linear output""" # Sometimes denom overflows, but it's OK, since if it's very large, it would # be set to INF and the output correctly takes the value of 0. # TODO: Fix overflow warnings. denom = 1 + np....
8c7aabfedafbd08f0e82b5d8a01837a70ab314ac
7,683
def electron_mass_MeVc2(): """The rest mass of the electron in MeV/c**2 https://en.wikipedia.org/wiki/Electron """ return 0.5109989461
4496ddcc35a0aa6528cc19e47233f5a81626fefe
7,684
def opensearch_plugin(request): """Render an OpenSearch Plugin.""" host = "%s://%s" % ("https" if request.is_secure() else "http", request.get_host()) # Use `render_to_response` here instead of `render` because `render` # includes the request in the context of the response. Requests # often include...
5df7e8a8bb89ff5e83b51f1bc4b634db9dea6930
7,685
from datetime import datetime def serialize_time(output_value: datetime.time) -> str: """ Serializes an internal value to include in a response. """ return output_value.isoformat()
81fc648eaf27efc47531f9895a9523aa5f012cf6
7,686
from . import persist def find_posix_python(version): """Find the nearest version of python and return its path.""" if version: # Try the exact requested version first path = find_executable('python' + version) persist.debug('find_posix_python: python{} => {}'.format(version, path)) ...
c3bbfa6d4dba5321242ada0f73acccd701bc9796
7,687
def decode_binary(state_int): """ Decode binary representation into the list view :param state_int: integer representing the field :return: list of GAME_COLS lists """ assert isinstance(state_int, int) bits = int_to_bits(state_int, bits=GAME_COLS*GAME_ROWS + GAME_COLS*BITS_IN_LEN) res = ...
a2dd5462031eeb82d9e3b59565d41b2b06e8e2d8
7,688
def clean_features(vgsales): """ This function cleans up some of the dataset's features. The dataset is quite messy as many values are missing from both categorical and numerical features. Many of these features are difficult to impute in a reasonable manner. <class 'pandas.core.frame.DataFrame...
ffcae20af436d4012381c4933c841c3689fbbca0
7,689
def get_object(proposition): """[75] Returns the object of a given proposition """ return proposition[2][0]
dc9d5fe007bb66ee92cddd964bb29b897a561c8c
7,690
import hmac def __verify_hmac(data: bytes, ohmac: bytes, key: bytes) -> bool: """ This function verifies that a provided HMAC matches a computed HMAC for the data given a key. Args: data: the data to HMAC and verify ohmac: the original HMAC, normally appended to the data key: ...
6381bb70e35cccafdb3dcafc2428ca5ca850364a
7,691
def create_block_option_from_template(text: str, value: str): """Helper function which generates the option block for modals / views""" return {"text": {"type": "plain_text", "text": str(text), "emoji": True}, "value": str(value)}
23f0cf455e659eddeca0b4eda732995feeac6341
7,692
from typing import Any import json def get_token_payload(token: str) -> Any: """Extract the payload from the token. Args: token (str): A JWT token containing the session_id and other data. Returns: dict """ decoded = json.loads(_base64_decode(token.split('.')[0])) ...
1b9b03f8e9db6940cc44725025c1ed2ccf751e89
7,693
import torch def create_mock_target(number_of_nodes, number_of_classes): """ Creating a mock target vector. """ return torch.LongTensor([np.random.randint(0, number_of_classes-1) for node in range(number_of_nodes)])
e226d9e7d1944b0736952d5952e8ef3438a1e54b
7,694
def initFindAndFit(parameters): """ Initialize and return a SplinerFISTAFinderFitter object. """ # Create spline object. spline_fn = splineToPSF.loadSpline(parameters.getAttr("spline")) # Create peak finder. finder = SplinerFISTAPeakFinder(parameters = parameters, ...
6f045b664157437fb33ab3804b84fe1c7d1deb4e
7,695
def UpdateDatabase(asset, images, status): """Update the database entries of the given asset with the given data.""" return {'asset': asset}
1d7d42355410be7481e706e47d7810755974dadc
7,696
def get_max_word_length(days: dict, keys: list) -> int: """ Находит длину самого длинного слова. """ max_word_len = 0 for key in keys: if days.get(key): for _, data in days.get(key).items(): value = data.split(" ") for word in value: ...
8a98c7384839f10fdfa713c535b3bf7765416b4c
7,697
def rateCBuf(co2: float, par: float, params: dict, rates: dict, states: dict) -> float: """ Rate of increase of carbohydrates in the buffer During the light period, carbohydrates produced by photosynthesis are stored in the buffer and, whenever carbohydrates are available in the buffer...
33a6c5fcc6d9d1a0641d197dffa1ee5fd6afd038
7,698
import hashlib import json def get_config_tag(config): """Get configuration tag. Whenever configuration changes making the intermediate representation incompatible the tag value will change as well. """ # Configuration attributes that affect representation value config_attributes = dict(fram...
2cab6e9473822d0176e878114ceb3fda94d1e0f7
7,699