content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from functools import reduce import operator def factorial(n): """Calculate n factorial""" return reduce(operator.mul, range(2, n+1), 1)
a58e0aad4e3a8baf06bbd1a6929a3aab2ab4e66e
3,600,451
from shapely.wkt import loads from shapely.geometry import LineString def plot(n, margin=None, ax=None, geomap=True, projection=None, bus_colors='cadetblue', bus_alpha=1, bus_sizes=2e-2, bus_cmap=None, line_colors='rosybrown', link_colors='darkseagreen', transformer_colors='orange', ...
ccc9590b21978c257a2a9ba0b076604de5052454
3,600,452
def logo_2bridged(fusion1, fusion2, positivities, half12_positive, half21_positive): """Create a Type 2, MISA, or negative Type 2 logo: yellow connector cycle interconnected with red and blue.""" styles = [('solid' if positive else 'dashed') for positive in positivities] tips = [('normal' if positive else '...
e8e91397392315b578f61a00ac6165cb5129d29c
3,600,453
import random def make_colors(num, seed=1, ctype=1): """Return `num` number of unique colors in a list, where colors are [r,g,b] lists.""" rand = random.Random(seed) colors = [] while len(colors) < num: colors.append(list(hex_to_rgb(random_unique_color(colors, ...
0f4ff3e4ff5deb8ee3a83700eaca6d0ea4206914
3,600,454
def fromstring(html, base_url=None, parser=None, **kw): """ Parse the html, returning a single element/document. This tries to minimally parse the chunk of text, without knowing if it is a fragment or a document. base_url will set the document's base_url attribute (and the tree's docinfo.URL) ...
72a1f63772240954353ed467009533201b949c22
3,600,455
def freq_saturation(truth,output): """ #provides saturation value - how many total notes did our model predict #requires notes array be of value 0-32 ~~~~ ARGUMENTS ~~~~ - truth : np.array - should be values 0-32 notes array - true note values - output : np.array - shoul...
d8a684cf51163041837289be87ce5edd0b32ac84
3,600,457
def _get_best_checkpoint(checkpoint_dir, latest_filename=None): """Find the filename of the best checkpoint file. Args: checkpoint_dir: Directory where the variables were saved. latest_filename: Optional name for the checkpoint state file that contains the best checkpoint filenames....
0f6302f227e4ad99a9491de9792f335d3c3a9737
3,600,459
def packagePath(): """Returns the root directory of the simulator package""" return rospkg.RosPack().get_path(PACKAGE_NAME)
5e718d5aa7c6ae75cf86daf4a896bb0a99cc375e
3,600,460
from typing import Optional from typing import Tuple from typing import Match import re def is_conversion_err(error: Exception) -> Optional[Tuple[str, int]]: """Check if error is caused by generic conversion error. Return a tuple of the converter type and parameter name if True, otherwise return None. ...
2e53420bb8a5715c75ee30a549453f40202d4ff7
3,600,461
import random def preenche_posicao_aleatoria(t): """list -> list Esta funcao recebe uma lista do tipo tabuleiro e preenche uma posicao livre (escolhida aleatoriamente) com um dos numeros 2 e 4, de acordo com as probabilidades ja indicadas""" x=tabuleiro_posicoes_vazias(t) v=x[int(random()*(len(x)-1))]...
362367b7a3e66a44d6aeece5e9242bedf688b196
3,600,462
def txt_file_to_list(genomes_txt): """ Read ids from a one column file to a list Args: genomes_txt:str: Path to file with the ids. """ with open(genomes_txt, 'r') as fin: genomes_list = [line.strip() for line in fin] return genomes_list
f79874dfbcb6a2a71be87b180e80513d480fcc8e
3,600,463
import typing def group(**kwargs) -> typing.Callable[[typing.Any], commands.Group]: """ Decorates a coroutine to make it into a command group name: str The name of the command. callback: coroutine The coroutine that is executed when the command is called. help: str The lon...
75154cc603b863c8039d923167fe4de125266036
3,600,464
def cubic_lattice( a, b, c, spacing ): """ Generate a cubic lattice. Args: a (Int): Number of lattice repeat units along x. b (Int): Number of lattice repeat units along y. c (Int): Number of lattice repeat units along z. spacing (Float): Distance bet...
d2fd739a5f5c8ff4bc792146da385bbdecb12cee
3,600,465
def decode(ciphertext, key1, key2): """ Decode the ciphertext with the 2 keys """ plaintext = '' for b in bytes_from_hex(ciphertext): plaintext += chr(b ^ key1) key1 = (key1 + key2) % 256 return plaintext
7f5311e8f794342e187490eb8281290e0cfeee96
3,600,466
def test_maxsize_none(): """Unlimited Caching.""" ac = AnyCache(maxsize=None) @ac.anycache() def myfunc(posarg, kwarg=3): # count the number of calls myfunc.callcount += 1 return posarg + kwarg myfunc.callcount = 0 eq_(myfunc(4, 2), 6) size1 = ac.size n = 5 ...
8ad07fe9af411b78b132bee73182fcb32a4b0ec7
3,600,467
def get_next_or_last_broadcast(tmp_date): """Возвращает дату следующего эфира, если он есть. Если нет, то дату последнего эфира :param: tmp_date - исходная дата :return: ближайшая дата """ select_min = db.func.min(Broadcast.date) # Выбор минимального where_next = Broadcast.date >= tmp_date # ...
172853d085e9f2b8c63c0673aa5d25384e9c3a85
3,600,468
def config1(): """Example config file""" config = r''' ! the following is a config file for 3 pulses and some custom ! data pulse: type = gauss, t_FWHM = 1.8, E_0 = 1.0, w_L = 0.2, & & oct_shape = flattop, ftrt = 0.2, oct_lambda_a = 100, & & oct_increase_factor = 10 * id = 1, t_0 = 0, oc...
703475289e053a061857cb5b72dda304c5f70ce6
3,600,469
def get_auth_backend(): """Returns the sole authentication backend.""" backends = auth.get_backends() if len(backends) != 1: raise ImproperlyConfigured("Expected exactly 1 backend (found {})".format(len(backends))) return backends[0]
248cd45ed6e90e7037c7e4640a5df47ce5258d94
3,600,470
def cvSetImageIOFunctions(*args): """ cvSetImageIOFunctions(CvLoadImageFunc _load_image, CvLoadImageMFunc _load_image_m, CvSaveImageFunc _save_image, CvShowImageFunc _show_image) -> int """ return _cv.cvSetImageIOFunctions(*args)
7d2e97348af035f827109e01246f1a5b70e1f2f4
3,600,472
def make_gene_dictionary( celltype_df, bulk_df, disp_min=0.5, bulk_min=1e-5, bulk_max=0.01, remove_mito=True, ): """ Finds highly variable genes across cell types and checks for expression thresholds within each bulk separately, returns a dictionary of...
ff71476fec80799f42abccd4c558c4e1d40b7f94
3,600,473
def oxfordcomma(listed, condition): """Format a list into a sentance""" listed = [f"'{str(entry)}'" for entry in listed] if len(listed) == 0: return "" if len(listed) == 1: return listed[0] if len(listed) == 2: return f"{listed[0]} {condition} {listed[1]}" return f"{', '....
c64ec05df35ccb6169363bf276fb874e61525c85
3,600,474
from typing import Dict from typing import Set from typing import Optional def _get_out_of_sample_arms( model: ModelBridge, generator_runs_dict: Dict[str, GeneratorRun], metric_names: Set[str], fixed_features: Optional[ObservationFeatures] = None, ) -> Dict[str, Dict[str, PlotOutOfSampleArm]]: """...
d7467ac51d691eb2060953454018b3542e6f84d7
3,600,475
def get_all_user_attributes(client): """ This command gets all users, chooses the first then, run a second get command that returns all the users attributes """ user_id = "" attributes = [] all_users = client.get_all_users() users_list = all_users.get("searchRecords") if isinstance(...
d92ccab35a61bec96e34d3ca4a4035d7688001a0
3,600,476
def get_backlog_msg(self, chan, msg): """get message from backlog""" if len(msg) < 1: msg = "1" try: back = int(msg) + 0 except: back = 1 if chan in self.backlog and len(self.backlog[chan]) >= back: return self.backlog[chan][0 - back] else: raise Backlog...
1040827e0a3eab8696f27feaae54b2bb73c1532a
3,600,478
def filter_red_pen(rgb, output_type="bool"): """ Create a mask to filter out red pen marks from a slide. Args: rgb: RGB image as a NumPy array. output_type: Type of array to return (bool, float, or uint8). Returns: NumPy array representing the mask. """ t = Time() result ...
0dd656841d4b23007de55199ba801bdfb423df72
3,600,479
def kmeans_plus_plus(X: np.ndarray, k: int, random_state: int = 42) -> np.ndarray: """ Create cluster centroids using the k-means++ algorithm. Args: X: The dataset to be used for centroid initialization. k: The desired number of clusters for which centroids are requi...
4766b6d2dfa17593c6d05e8e7342c9bf389caab3
3,600,480
import requests def logout(): """revoke current user's access_token and reset login session""" access_token = login_session.get('access_token', None) for key in [ 'access_token', 'gplus_id', 'username', 'email', 'picture' ]: if key in login_session: del login_session[k...
bb44650e27d0a68d8113323c313728af9f5836a2
3,600,481
def setup_loading(): """Establish how recordings are loaded.""" # Indicates if all information on a recording is loaded in bulk, or as needed load_all = True # If load_all is True, indicates what is loaded in bulk # Should be a subset of ["signals", "spatial", "units"] to_load = ["signals"] ...
8855e02ba57a79c72861796de3d0c3178232c2a8
3,600,482
from exploits import add_exploit, connect_exploits def process_exploits(filename=None): """ Process Nexpose exploits.xml file into the database """ log("Processing Nexpose exploits file: %s ..." % filename) try: exploits = etree.parse(filename) except etree.ParseError, e: rai...
07242bd7308e28659d53285c39405bc6dd3159f0
3,600,483
def retrieve_single_movie(imdb): """Return a specific movie based on IMDB id.""" if request.method == 'GET': movie = movie_collection.read(imdb) if movie: return jsonify(movie) elif request.method == 'PUT': movie = movie_collection.update(request.json) if movie...
378b8e249d44dfd1ecaa80e8f65753f5ae2f5eb4
3,600,484
import six import binascii def _read_ssh_ed25519_pubkey(keydata): """ Parse a Ed25519 SSH public key from a string into a raw public key. :param keydata: The public Ed25519 SSH key to parse. :type keydata: unicode :returns: The raw public keys (32 bytes). :rtype: binary """ if type(k...
ddeaa76388fce9b5700fd71d5f19130dfebb51fe
3,600,485
def migration(transactional_db): """ This fixture returns a helper object to test Django data migrations. The fixture returns an object with two methods; - `before` to initialize db to the state before the migration under test - `after` to execute the migration and bring db to the state after the ...
49df867892dbbd3fb89a49d8ddaac24190beb7d9
3,600,486
def read_memory(library, session, space, offset, width, extended=False): """Reads in an 8-bit, 16-bit, 32-bit, or 64-bit value from the specified memory space and offset. Corresponds to viIn* functions of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logi...
6b1926375a3d14276c2e9f266b10bdd683fca2bf
3,600,487
def dense_rank(x, na_option = "keep"): """Return the dense rank. This method of ranking returns values ranging from 1 to the number of unique entries. Ties are all given the same ranking. Example: >>> dense_rank(pd.Series([1,3,3,5])) 0 1.0 1 2.0 2 2.0 ...
53bd64e112741f20c0e62f44ba7f5bcf8cdb2f83
3,600,488
def rsqrt_decay(step, warmup_steps): """Decay based on the reciprocal of the step square root.""" return 1.0 / sqrt(max(step, warmup_steps))
3d4849e62d9dc789d907501fa8776645e9d554d7
3,600,489
import json import requests def delete_bulk_by_externalIds(tibody=None): """ Makes a POST request to delete multiple TI indicators by external IDs. Currently support 'Azure Sentinel' targetProduct only. :param tibody: Body of the POST request. :returns: json response. :raises ValueError: raises a...
cdce121d9bf8b04f1177e56f52ccc92547c0cf99
3,600,490
def contact_parent(): """ Contact parent. """ # Create an empty error. error = None # Create a form object. contact_form = ContactForm() # Select all the staff and tutors. contact_form.user.choices = [ (parent.parent_id, parent.get_full_name()) for parent in select_parents(...
50826ee8d73465bc98074adcead97ecc8718fe7e
3,600,491
def erbb2_context(): """Create test fixture for ERBB2 Gene Context.""" return { "id": "normalize.gene:ERBB2", "type": "GeneDescriptor", "label": "ERBB2", "gene": { "gene_id": "hgnc:3430", "type": "Gene" }, "xrefs": [ "ncbigene:2...
0a4ef3bf47d8ac622d6c2778bd33199f5da2a747
3,600,492
def get_repository(): """Return the shared instance of the package repository. Returns: PackageRepository: The package repository. """ global _repository if not _repository: _repository = PackageRepository() return _repository
ace15568a0b3876fc7eb3fda28ce465346696051
3,600,493
def create_nested_multiple(N,masses,semimajor_axes,eccentricities,inclinations,arguments_of_pericentre,longitudes_of_ascending_node): """ N is number of bodies masses should be N-sized array the other arguments should be (N-1)-sized arrays """ N_bodies = N N_binaries = N-1 particles = ...
21bf038744a77913115596880ff80ff613f0fde2
3,600,496
import codecs def decode_rot13(cipher: str): """Used to decode rot13""" return codecs.decode(cipher, 'rot_13')
3c20989614c6691c74294a93268745bbaccecf42
3,600,497
def parse_rec(filename,imgpath): """ Parse a PASCAL VOC xml file """ objects = [] # 还需要同时打开图像,读入图像大小 img = cv2.imread(imgpath) height, width, channels = img.shape with open(filename, "r", encoding='utf-8') as f1: dataread = f1.readlines() for annotation in dataread: o...
6dcf1af2728fcf8759b16d60dd53abadbefdb982
3,600,498
def _urlencode(params): """ A version of Python's urllib.urlencode() function that can operate on unicode strings. The parameters are first case to UTF-8 encoded strings and then encoded as per normal. """ return url_encode([i for i in _generate_smart_str(params)])
6aa5cfbfd3106cadcdb7db52489e9bd470bb288e
3,600,499
from rmgpy.data.kinetics.family import ReactionRecipe def _convert_3_atom_2_bond_path(start, mol): """ Searches for 3-atom-2-bond [X=X-X+] paths paths starting from the parameter atom. If a correct path is found, the starting atom receives an unpaired electron while the bonds in the delocalization pat...
b17985d982614c53ee4adeea06e7e5b361306690
3,600,500
import pandas as pd def indices_stats_df(sort_size=False, with_sql=False): """Return statistics on indices. See https://www.postgresql.org/docs/current/monitoring-stats.html """ result = execute_raw( r""" SELECT pt.tablename AS TableName, t.indexname AS IndexName, ...
c7d8d363d00b834c3900a92c70c3a350d83f2144
3,600,502
def peakgene_overlaps(combos, same_genes, normalize=False): """Count the number of genes that overlap when examing the hg19 & hg38 GISTIC runs' focal peaks.""" venn_numbers, gsu, gsi = [], [], [] for coh, ad in combos: print(coh) # put all significant genes in a list fnames = ['...
70e6ce4d185d97135fb0aff7c2712c08ad7b911e
3,600,503
import six def _create_intermediate_tables(docs, schema): """ return { table_name: { row_id_number: { column_name: cell_data, ... }, ... }, ... } """ INT = '#' def lookup(doc, keys): for key ...
8d53f65ecb7827a87627abe3bf07e03bed2d739a
3,600,504
from typing import Dict def plot_goal_ternary(df: pd.DataFrame, kpis: Dict[str, callable], goals: Dict[str, callable], control_params: set) -> None: """ Arguments --- df: Observation dataframe kpis: Dictionary of funtions that scores a given combi...
b2422dc2975cbf1da0fb59cc4d027492d1bb1f57
3,600,505
from unittest.mock import Mock def mock_channel_file( offered_by, channel_id, playlist_id, create_user_list=False, user_list_title=None ): """Mock video channel github file""" content = f"""--- offered_by: {offered_by} channel_id: {channel_id} playlists: - id: {playlist_id} {"create_user_list: true...
3042a7fc6f0fb622db8bf035a408672ddd6408ab
3,600,506
def cmdline(argv, flags): """A cmdopts wrapper that takes a list of flags and builds the corresponding cmdopts rules to match those flags.""" rules = dict([(flag, {'flags': ["--%s" % flag]}) for flag in flags]) return parse(argv, rules)
522879927ba5242f6c738428e3fa4294bb98ffe8
3,600,507
def get_globalLock_ratio(name): """Return the global lock ratio""" try: result = get_rate(NAME_PREFIX + 'globalLock_lockTime') / \ get_rate(NAME_PREFIX + 'globalLock_totalTime') * 100 except ZeroDivisionError: result = 0 return result
8824f867375175f38ec2fc586467bff7ff39b5a8
3,600,508
def tfx_to_tifix(in_arr, t_map, f_map): """Sum a (t, f, ...) array into a (ti, fi, ...) array.""" in_arr_shape = in_arr.shape n_time = in_arr_shape[0] n_chan = in_arr_shape[1] n_tint = np.max(t_map) + 1 n_fint = np.max(f_map) + 1 out_dtype = get_output_dtype(in_arr) trailing_dims = ...
6269c3dd824d8d23cbfccb6b03c076dc7c5d0323
3,600,509
import numpy def _planarEOM_dxdv(x,t,pot): """ NAME: _planarEOM_dxdv PURPOSE: implements the EOM, i.e., the right-hand side of the differential equation, for integrating phase space differences, rectangular INPUT: x - current phase-space position t - current time ...
3adf7f76598e76b5d32e2c83b8e906ad9182b815
3,600,511
import json def get_offset2docidx(doc = None, corenlp_file = None): """ This function gets the mapping from the document-level offset of a word to its document-level word index """ # get a dictonary of character offset to sentid if doc is None and corenlp_file is None: raise NameError("...
e228f8eb878581abe8f0679f9d1f99d6012eecd0
3,600,512
def trainerServerInput(tf_transform_output): """Creates an input function reading from raw data. Args: tf_transform_output: Wrapper around output of tf.Transform. Returns: The serving input function. """ raw_feature_spec = RAW_DATA_FEATURE_SPEC.copy() # Remove label since it is not...
6ebfeb7e930171de688241e666f96a1b45df6f19
3,600,514
from functools import reduce def reorder_spatial_and_reduce_axes(sch, op, axis_map, split_axis_list, reduce_split_axis_list, extents_info=None): """Reorder spatial and reduce axes """ pre = [] ones = [] for k, v in axis_map.items(): if not isinstance(v, (list, tuple)): if v.dom is None: ex...
69e198b07350ae678063b369fdd3a3cb52c91fd5
3,600,515
from functools import wraps def run_only_once(resolve_func): """ Make sure middleware is run only once, this is done by setting a flag in the `context` of `ResolverInfo` Example: class AuthenticationMiddleware: @run_only_once def resolve(self, next, root, info, *args, *...
9742318ca44ec92d7826d561968c87cea62db1bf
3,600,516
def content_type_headers(filename, content_type=None): """Returns a dict with the content-type header for a file. Guesses the mimetype for a filename and returns a dict containing the content-type header. .. code-block:: python >>> content_type_headers('example.txt') {'Content-Type': 'text/plain'} >>> con...
b429d4345052ec7836071f19c1e261bea88df8c1
3,600,518
def constructLinkedList(n): """ 方法功能:创建单链表 说明:上方的 removeDup() 对于升序、降序均有效,不妨建一个升序链表 """ head = LNode() cur = head for i in range(n): tmp = LNode() if i % 2 == 0: tmp.val = i else: tmp.val = i - 1 cur.next = tmp cur = tmp retu...
2df6ae23fc43716972651597f8d5f20f63979693
3,600,519
import time def ncesvd(matrix_train, embeded_matrix=np.empty((0)), iteration=4, rank=200, fb=False, seed=1, root=1.1, **unused): """ PureSVD algorithm :param matrix_train: rating matrix :param embeded_matrix: item or user embedding matrix(side info) :param iteration: number of random ...
bd0da84172b84bd636f5fda243c49e155300ebaa
3,600,520
def create_new_single_server(db, name, ip, section_id, colorId): """ Add new server to data base. """ query = ''' INSERT INTO servers(ip, name, section_id, color_id) VALUES("%s","%s","%s","%s") ''' % (ip, name, section_id, colorId) result = get_db_with_actions(db, query) creat...
46da87d7c5df2c89cfc75f08b3f651c19d9f52ca
3,600,521
import ctypes def corrDn(image, filt, edge_type='reflect1', step=(1, 1), start=(0, 0), stop=None): """Compute correlation of image with filt, followed by downsampling. These arguments should be 1D or 2D arrays, and image must be larger (in both dimensions) than filt. The origin of filt is assumed to be ...
9c4f844bfceb41c8d97f08fcaefbe29363e6ef4c
3,600,522
def ldapmask2filemask(ldm): """Takes the access mask of a DS ACE and transform them in a File ACE mask. """ RIGHT_DS_CREATE_CHILD = 0x00000001 RIGHT_DS_DELETE_CHILD = 0x00000002 RIGHT_DS_LIST_CONTENTS = 0x00000004 ACTRL_DS_SELF = 0x00000008 RIGHT_DS_READ_PROPERTY = ...
a461fd5bdc6498df345491f38885a63b0dcbefc2
3,600,523
import re def get_input_size(filename): """Gets input size and # of channels.""" with open(filename) as input_file: for line in input_file: match = re.match(r'^input.*\(None, (\d*), (\d*), (\d*)\)', line) if match is not None: x = int(match.group(1)) ...
3e753e5ac74babcbe4f48830cfde7a3002f7cc37
3,600,524
def consumption_per_minute(depth, bottle_size, sac=DEFAULT_BOTTOM_SAC, silent=True): """returns the consumption in bars/minute of a bottle of a given size for a given SAC""" sac = float(sac) ata = depth_to_ata(depth) liters_per_minute = ata * sac bars = liters_to_bars(liters_per_minute, bottle_s...
1455ac9baafcc2ecf940d78df798f04ca3a0e089
3,600,525
from typing import List import torch def javascript_dataloader( *args, augmentations: List[dict], sp: spm.SentencePieceProcessor, program_mode: str = "identity", subword_regularization_alpha: float = 0, max_length: int = 1024, max_target_length: int = 256, spm_unigram_path: str = None,...
e2a5c70be691e6c91bb21e9d72467495a48c1687
3,600,526
def define_features_tfidf(columns, training_data, testing_data = None, ngramrange=(1, 1)): """ Define the features for classification using TFIDF. Parameters ---------- column: String or list of strings if using multiple columns Names of columns of df that are used for...
b660c48a4d35ae671abc0b707b2746c70b2d62e5
3,600,527
def logout(): """Log out and return login form.""" app = current_app._get_current_object() app.logger.info('%s logged out', current_user.email) logout_user() flash('You have been logged out.') return redirect(url_for('auth.login'))
3fde7b0994468082117b6ff26eae7c97872ad0dc
3,600,528
def indexOfSmallestInt(listOfInts): """ return index of smallest element of non-empty list of ints, or False otherwise That is, return False if parameter is an empty list, or not a list parameter is not a list consisting only of ints By "smallest", we mean a value that is no larger than any other ...
63afb453b13ad4da75c83e9a7f6b409f58739d7e
3,600,530
def augment_spectrogram(sg): """Augments a spectrogram by randomly masking out time and frequency ranges, as described in the "SpecAugment" paper. """ sg = np.copy(sg) freq_len, time_len = sg.shape max_freq_len = np.ceil(MAX_MASK_PERCENT * freq_len) max_time_len = np.ceil(MAX_MASK_PERCENT *...
4f601fb357c3f2f614e1963b58820ec0464047bb
3,600,531
def field_with_classes(field, *classes): """ Adds the specified classes to the HTML element produced for the field. """ return field.as_widget(attrs = { 'class': ' '.join(classes) })
2b9929b2629fafaafbe1d2537afc0a9a601eed53
3,600,532
import tkinter as Tkinter import tkinter.filedialog as tkFileDialog def directory_from_gui( initialdir='.', title='Choose directory'): # pragma: no cover """ Opens dialog to one select directory Parameters ---------- initialdir : str, optional Initial directory, in which ...
e0b43a044c0e05815023de2275cc0ff1ffb01d8e
3,600,533
def first_pos(): """ This function will be used to reset the robot back to a home position. Initial variables will be collected from the user. """ # Reference the Empty state and return dictionary. global EMPTY global return_dict # Add gripper statuses to the return dictionary to set them to E...
4d8b4cdc2fe33d1766c43456a3847ebd2f8539c0
3,600,534
def query(query_string): """Run database query.""" db_host = "w-v-cabledb-0" db_user = "root" db_pass = "maxlab" db_name = "cabledb_test2" try: with MySQLdb.connect(db_host, db_user, db_pass, db_name) as db_session: db_session.execute(query_string) return db_session.fetchall() except MySQL...
c6d55b2bfc81d945a0c09622591c17ca361d1502
3,600,535
def _test_path_to_file_url(path): """ Convert a test Path to a "file://" URL. Args: path: a tests.lib.path.Path object. """ return 'file://' + path.resolve().replace('\\', '/')
b13025da535fe43e074f79411ab4be55c766a572
3,600,537
def instantiate(repo, name=None, filename=None): """ Instantiate the generator and filename specification """ default_transformers = repo.options.get('transformer', {}) # If a name is specified, then lookup the options from dgit.json # if specfied. Otherwise it is initialized to an empty list ...
6a280b91598d9e0dd41d99165d0474b3dcdde7f3
3,600,538
def extract_status_from_cell(cell_text): """ Extracts the candidates in the race from string. :return: a list of (candidate, party, elected) """ tokenizer = RegexpTokenizer(".+?\(.+?\)") tokens = tokenizer.tokenize(cell_text) res = set() for token in tokens: token = token.strip(...
ee2b52ed9df85c71407724d984c85cfb3cfd19ae
3,600,541
def get_kwargs_geomark(data): """ :param data: ser data dict :return: kwargs for development.DevelopmentGISLayer.geomark """ kwargs = { # 'project': data.get('project', None), 'layer_type': 'geomark', 'geomark': data.get('location_n_geomark', None), 'notes': data.get(...
14d294f624fd2e56eb8a5d36ab53662132ba94fc
3,600,543
def horizon_block_estimator(data, d_u, k, horizon_length, func, **kwargs): """Horizon estimator, but in block format: so instead of estimating a rolling horizon type of estimator, it is done on separate blocks. """ #calculate how many blocks are in the data block_number = int(np.floor(len(data)...
d2d4bf729eebab6a4fe077bcb15ee2c89bab409c
3,600,544
def SeqFISH(use_test_data: bool = False) -> Experiment: """ Loads a single field of view from a SeqFISH dataset generated from cultured mES cells. These data are published: `<https://doi.org/10.1016/j.cell.2018.05.035>`_ This dataset contains 1140 images acquired across 12 channels, 4 imaging roun...
af88f6beb95572c268b6321b5c01d4774e61ebbb
3,600,545
def isfloat(x): """Returns True if input is a float; False otherwise. Parameters ---------- x : any Input can be of any type. Returns ------- y : bool True is `x` is a float, False otherwise. Notes ----- A table showing what isfloat returns for various types: ...
c14a54924c83a1791a418d846a8f4981e0f94a2f
3,600,546
def TKN(token, wsL='', wsR=r'\s*'): """Syntactic Sugar for 'Series(Whitespace(wsL), Text(token), Whitespace(wsR))'""" return withWS(lambda: Text(token), wsL, wsR)
f3411ddb9cc01534b2bb652ab62509cfdd293f8f
3,600,547
def getScreen(): """Takes a screenshot and saves it as screenshot.png in the current working directory""" img=ImageGrab.grab() img.save("screenshot.png") return("screenshot.png")
1b07b33e97b10d4c0f79e6ab162e5a74da45bbb0
3,600,548
def make_date(last="1 year"): """Function that generates a value for a DateType field. Parameters ---------- last : str Interval for generated date relative to current timestamp. Default: '1 year' Returns ------- datetime.date.Date """ return make_timestamp(last).d...
95a46d6d69d745f00293b2d7cdaf6ebb8dd136b9
3,600,549
from typing import Dict import socket def create_labels(platform: Platform) -> Dict[str, str]: """Returns dict of topology and hostname labels""" labels = dict() # Topology labels labels["sockets"] = str(platform.sockets) labels["cores"] = str(platform.cores) labels["cpus"] = str(platform.cpus...
7f519ef9dc41a82639b69ad99e99ba0363454cc9
3,600,550
def insert_replacement_rows(df, replacement_rows_dict): """ A trick (suggested at https://stackoverflow.com/a/63736275/2668831) to insert rows with floating point row index to put them between the (standard, integer-valued) existing row indices. This is vectorised using numpy linspace (omitting the...
c7fa17d3b19cfbfa9e8ac29ec15f22c85baa3a09
3,600,551
import warnings def init_detector(config, checkpoint=None, device='cuda:0'): """Initialize a detector from config file. Args: config (str or :obj:`mmcv.Config`): Config file path or the config object. checkpoint (str, optional): Checkpoint path. If left as None, the model ...
d2d52e31aadf6a5aaeaa7bf9fe372c4b55bd443a
3,600,552
def fibonacci(number:int) -> int: """ Returns the n'th fibonacci sequence number >>> fibonacci(number=10) 55 """ # Initializing Magic Matrix a = [[1, 1, ], [1, 0]] # Initializing Identity Matrix res = [[1, 0], [0, 1]] # Fast Exponentiation (log(n) complexity) while...
636f2138a9e9396aaf238984a0b439e7b6bd740b
3,600,554
from datetime import datetime def day_ahead_belief_about_ex_post_time_slot_event( ex_post_time_slot_sensor: Sensor, test_source_a: BeliefSource ): """Define day-ahead belief about an ex post time slot event.""" return TimedBelief( source=test_source_a, sensor=ex_post_time_slot_sensor, ...
0113b08140839a01f61a757fbd8ad0285998e570
3,600,555
def get_docker_details(args): """ :type args: CommonConfig :rtype: dict[str, any] """ docker = find_executable('docker', required=False) info = None version = None if docker: try: info = docker_info(args) except SubprocessError as ex: display.warn...
4051e90ffa2d8d573ddc5583a3bf15357c461dd3
3,600,556
from IPython import get_ipython def is_ipython() -> bool: """Check if script is executed in IPython (incl. Jupyter) Examples: >>> is_ipython() True Returns: bool: [description] """ try: except BaseException: return False if get_ipython() is not None: ...
1fd1d1d3f0250e61b1fc93d8ca4ffd7bd2928ca5
3,600,557
def create_model_name(src): """Generate a name for a source object given its spatial/spectral properties. Parameters ---------- src : `~fermipy.roi_model.Source` A source object. Returns ------- name : str A source name. """ o = '' spatial_type = src['S...
d305dd26bc6017f3fce5db2a5267fa6e74df3bc6
3,600,558
def _det_and_inv(A): """Get matrix det and inv, with special cases for small matrices""" if tt.eq(A.ndim, 0): det = A inv = 1/A elif tt.eq(A.shape, (1,1)): det = A[0,0] inv = 1/A else: det = tt.nlinalg.det(A) inv = tt.nlinalg.matrix_inverse(A) return...
735f9341c285ce015d11efccc2565531a5af50d1
3,600,559
def sha384(data: __Union[str, bytes]) -> str: """Returns hexadecimal representation of sha384 hashed data""" if isinstance(data, str): data = data.encode("utf-8") return __hashlib.sha384(data).hexdigest()
d68f714ff38d3ac77c62f9a114508fe029500cc3
3,600,561
def hanning_filter(gtab, filter_width): """ create a hanning window The signal is premultiplied by a Hanning window before Fourier transform in order to ensure a smooth attenuation of the signal at high q values. Parameters ---------- gtab : GradientTable filter_width : int Return...
febd5c6f7808a19903cb6dc6b7b49236e9f1d5a0
3,600,562
def dtype(x): """Returns the dtype of a Keras tensor or variable, as a string. # Arguments x: Tensor or variable. # Returns String, dtype of `x`. # Examples ```python >>> from keras import backend as K >>> K.dtype(K.placeholder(shape=(2,4,5))) 'float32' ...
94669336a40b956d7d2291970de085ecab00b4cb
3,600,563
def _CreateSwarmingArgs(build, suite, board, priority, timeout_mins=None, run_skylab=False): """Create args for swarming client. Args: build: Name of the build, will be part of the swarming t...
28fa89fd713016f4b86d18b77fa55344f267f282
3,600,564
def get_theme(theme_id, api_key=None): """ Gets details about specific set theme. Args: theme_id: str or int Rebrickable theme ID. api_key: str or None Rebrickable API access key. If set to None the one set by rebrick.init() is used. ...
847653d5ba28ea4f8cd48ff842b342b8a9e52540
3,600,565
def csv_to_list(value): """ Converts the given value to a list of strings, spliting by ',' and removing empty strings. :param str value: the value to split to strings. :return: a list of strings. :rtype: List[str] """ return list(filter(None, [x.strip() for x in value.split(',')]))
dbfb90dccf8d48a46f528ca02e958306e8dcc266
3,600,566
def load_population_data(): """Load and prepare country populations with same keys as covid19 data.""" # Load population data populations_counties = pd.read_csv('https://www2.census.gov/programs-surveys/popest/datasets/' '2010-2019/counties/totals/co-est2019-alldata.cs...
cd8cf9ebcc1e1a1890b20d02c2e4611f8035858b
3,600,567