content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import subprocess import sys import getpass def ssh_cmd(ssh_cfg, command): """Returns ssh command.""" try: binary = os.environ['SSH_BINARY'] except KeyError: if os.name != 'nt': binary = subprocess.check_output( 'which ssh', shell=True).decode(sys.stdo...
f7e110c76e26a462dd9929fc6fa4f2c025a2df44
26,300
import json def test_sensor_query(cbcsdk_mock): """Test the sensor kit query.""" def validate_post(url, param_table, **kwargs): assert kwargs['configParams'] == 'SampleConfParams' r = json.loads(kwargs['sensor_url_request']) assert r == {'sensor_types': [{'device_type': 'LINUX', 'archi...
878a060ad7f532522b8ef81f76701fbe0c7dc11b
26,301
import os def ExtractParametersBoundaries(Basin): """ ===================================================== ExtractParametersBoundaries(Basin) ===================================================== Parameters ---------- Basin : [Geodataframe] gepdataframe of catchment polygon, ...
cb79f39380116a28307763f85e696abef0c4f3b5
26,302
def encoder_apply_one_shift(prev_layer, weights, biases, act_type, name='E', num_encoder_weights=1): """Apply an encoder to data for only one time step (shift). Arguments: prev_layer -- input for a particular time step (shift) weights -- dictionary of weights biases -- dictionary of bia...
19ea3beec271e003f6d9ccadd4d508d97f6b7572
26,303
import uuid def db_entry_generate_id(): """ Generate a new uuid for a new entry """ return str(uuid.uuid4()).lower().replace('-','')
d5e90504a1927623b267082cd228981684c84e8d
26,304
import os def get_manager_rest_service_host(): """ Returns the host the manager REST service is running on. """ return os.environ[constants.REST_HOST_KEY]
21a5cd5d8c77e1ff3f6edd7b7d80d03edb2ab974
26,305
def angle_boxplus(a, v): """ Returns the unwrapped angle obtained by adding v to a in radians. """ return angle_unwrap(a + v)
9434d88d59956eeb4803bbee0f0fb3ad8acd1f5f
26,306
def color_gradient_threshold(img, s_thresh=[(170, 255),(170, 255)], sx_thresh=(20, 100)): """ Apply a color threshold and a gradient threshold to the given image. Args: img: apply thresholds to this image s_thresh: Color threshold (apply to S channel of HLS and B channel of LAB) sx_...
02bdfbd9a95dbfe726eac425e1b6efb78bfedb2b
26,307
def toeplitz(c, r=None): """ Construct a Toeplitz matrix. The Toeplitz matrix has constant diagonals, with c as its first column and r as its first row. If r is not given, ``r == conjugate(c)`` is assumed. Parameters ---------- c : array_like First column of the matrix. Whateve...
00c68daef087fded65e1feee375491db559c792f
26,308
def MQWS(settings, T): """ Generates a surface density profile as the per method used in Mayer, Quinn, Wadsley, and Stadel 2004 ** ARGUMENTS ** NOTE: if units are not supplied, assumed units are AU, Msol settings : IC settings settings like those contained in an IC object (see ...
bd1227f4416d093271571f0d6385c98d263c514e
26,309
def predict(x, P, F=1, Q=0, u=0, B=1, alpha=1.): """ Predict next state (prior) using the Kalman filter state propagation equations. Parameters ---------- x : numpy.array State estimate vector P : numpy.array Covariance matrix F : numpy.array() State Transitio...
fa638183a90583c47476cc7687b8702eb193dffb
26,310
from typing import Dict def footer_processor(request: HttpRequest) -> Dict[str, str]: """Add the footer email me message to the context of all templates since the footer is included everywhere.""" try: message = KlanadTranslations.objects.all()[0].footer_email_me return {"footer_email_me": mes...
3d38c4414cf4ddab46a16d09c0dcc37c57354cb1
26,311
def genome_2_validator(genome_2): """ Conducts various test to ensure the stability of the Genome 2.0 """ standard_gene_length = 27 def structure_test_gene_lengths(): """ Check length requirements for each gene """ gene_anomalies = 0 for key in genome_2: ...
7fe54b51673f3bc71cb8899f9a20b51d28d80957
26,312
import os def product_info_from_tree(path): """Extract product information from a directory Arguments: path (str): path to a directory """ log.debug('Reading product version from %r', path) product_txt = os.path.join(path, 'product.txt') if not os.path.isfile(product_txt): r...
321f604e737cecadedf8f6ac34b83d55902d0bf4
26,313
def to_poly(group): """Convert set of fire events to polygons.""" # create geometries from events geometries = [] for _, row in group.iterrows(): geometry = corners_to_poly(row['H'], row['V'], row['i'], row['j']) geometries.append(geometry) # convert to single polygon vt_poly =...
5482121dc57e3729695b3b3962339cb51c1613dc
26,314
def get_user(): """ Get the current logged in user to Jupyter :return: (str) name of the logged in user """ uname = env_vars.get('JUPYTERHUB_USER') or env_vars.get('USER') return uname
a7ece43874794bbc62a43085a5bf6b352a293ea2
26,315
import logging import time def get_top_articles(update=False): """ Retrieve 10 most recent wiki articles from the datastore or from memcache :param update: when this is specified, articles are retrived from the datastore :return: a list of 10 most recent articles """ # use caching to avoid run...
b5ac25e8d06acd48e3ee4157fcfcffd580cf421e
26,316
def bucket(x, bucket_size): """'Pixel bucket' a numpy array. By 'pixel bucket', I mean, replace groups of N consecutive pixels in the array with a single pixel which is the sum of the N replaced pixels. See: http://stackoverflow.com/q/36269508/513688 """ for b in bucket_size: assert float(b).is...
8ff3eda1876b48a8bdd4fbfe6b740ed7e3498c51
26,317
def create_msg(q1,q2,q3): """ Converts the given configuration into a string of bytes understood by the robot arm. Parameters: q1: The joint angle for the first (waist) axis. q2: The joint angle for the second (shoulder) axis. q3: The joint angle for the third (wrist) axis. Returns: The string of bytes. ...
26f9954a55686c9bf8bd08cc7a9865f3e4e602e3
26,318
def get_config(): """Provide the global configuration object.""" global __config if __config is None: __config = ComplianceConfig() return __config
cdaa82445b4f260c7b676dc25ce4e8009488603e
26,319
import array def size(x: "array.Array") -> "array.Array": """Takes a tensor as input and outputs a int64 scalar that equals to the total number of elements of the input tensor. Note that len(x) is more efficient (and should give the same result). The difference is that this `size` free function adds ...
2e80223a2468f0d9363ad2aa148d14a090c0d009
26,320
def linspace(start, stop, length): """ Create a pdarray of linearly spaced points in a closed interval. Parameters ---------- start : scalar Start of interval (inclusive) stop : scalar End of interval (inclusive) length : int Number of points Returns -------...
82d90c0f6dcdca87b5c92d2668b289a1db0b2e64
26,321
def _load_corpus_as_dataframe(path): """ Load documents corpus from file in 'path' :return: """ json_data = load_json_file(path) tweets_df = _load_tweets_as_dataframe(json_data) _clean_hashtags_and_urls(tweets_df) # Rename columns to obtain: Tweet | Username | Date | Hashtags | Likes | R...
7113b51ec7e35d2b11697e8b049ba9ef7e1eb903
26,322
def UNTL_to_encodedUNTL(subject): """Normalize a UNTL subject heading to be used in SOLR.""" subject = normalize_UNTL(subject) subject = subject.replace(' ', '_') subject = subject.replace('_-_', '/') return subject
51c863327eec50232d83ea645d4f89f1e1829444
26,323
def parse_cigar(cigarlist, ope): """ for a specific operation (mismach, match, insertion, deletion... see above) return occurences and index in the alignment """ tlength = 0 coordinate = [] # count matches, indels and mismatches oplist = (0, 1, 2, 7, 8) for operation, length in cigarlist: if operation...
4eceab70956f787374b2c1cffa02ea7ce34fe657
26,324
def _decode_token_compact(token): """ Decode a compact-serialized JWT Returns {'header': ..., 'payload': ..., 'signature': ...} """ header, payload, raw_signature, signing_input = _unpack_token_compact(token) token = { "header": header, "payload": payload, "signature": b...
e7dbe465c045828e0e7b443d01ea2daeac2d9b9a
26,325
def _top_N_str(m, col, count_col, N): """ Example ------- >>> df = pd.DataFrame({'catvar':["a","b","b","c"], "numvar":[10,1,100,3]}) >>> _top_N_str(df, col = 'catvar', count_col ='numvar', N=2) 'b (88.6%), a (8.8%)' """ gby = m.groupby(col)[count_col].agg(np.sum) gby = 100 * gby / gb...
d80e5f7822d400e88594a96c9e1866ede7d9843e
26,326
def insert_box(part, box, retries=10): """Adds a box / connector to a part using boolean union. Operating under the assumption that adding a connector MUST INCREASE the number of vertices of the resulting part. :param part: part to add connector to :type part: trimesh.Trimesh :param box: connector ...
76f29f8fb4ebdd67b7385f5a81fa87df4b64d4c7
26,327
import argparse def parse_args(): """Parse command line arguments.""" parser = argparse.ArgumentParser() parser.add_argument('--task', type=str, required=True) parser.add_argument('--spacy_model', type=str, default='en_core_web_sm') parser.add_argument('--omit_answers', action='store_true') pa...
905f9e46d17b45e28afeaf13769434ad75685582
26,328
def pnorm(x, p): """ Returns the L_p norm of vector 'x'. :param x: The vector. :param p: The order of the norm. :return: The L_p norm of the matrix. """ result = 0 for index in x: result += abs(index) ** p result = result ** (1/p) return result
110fea5cbe552f022c163e9dcdeacddd920dbc65
26,329
import os def get_arr(logdir_multiseed, acc_thresh_dict=None, agg_mode='median'): """ Reads a set of evaluation log files for multiple seeds and computes the aggregated metrics with error bounds. Also computes the CL metrics with error bounds. Args: logdir_multiseed (str): Path to the p...
11d17378bb9824a6e112335bfa2c9c219b3d9c18
26,330
def _kneighborsclassifier(*, train, test, x_predict=None, metrics, n_neighbors=5, weights='uniform', algorithm='auto', leaf_size=30, p=2, metric='minkowski', metric_params=None, n_jobs=None, **kwargs): """ For more info visit : https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsCl...
0a8ff00a5fc4978758432df34947895688b225cd
26,331
def overlap(batch_x, n_context=296, n_input=39): """ Due to the requirement of static shapes(see fix_batch_size()), we need to stack the dynamic data to form a static input shape. Using the n_context of 296 (1 second of mfcc) """ window_width = n_context num_channels = n_input batch_x =...
75936fe9ecb0f3e278fd6c990cab297c878006b1
26,332
def eval_on_train_data_input_fn(training_dir, hyperparameters): """ :param training_dir: The directory where the training CSV is located :param hyperparameters: A parameter set of the form { 'batch_size': TRAINING_BATCH_SIZE, 'num_epochs': TRAINING_EPOCHS, 'data_downsize': DATA_D...
07f9b33c936be5914b30697c25085baa25799d0d
26,333
import json def load_config(config_file): """ 加载配置文件 :param config_file: :return: """ with open(config_file, encoding='UTF-8') as f: return json.load(f)
85bab8a60e3abb8af56b0ae7483f2afe992d84b4
26,334
def decode(var, encoding): """ If not already unicode, decode it. """ if PY2: if isinstance(var, unicode): ret = var elif isinstance(var, str): if encoding: ret = var.decode(encoding) else: ret = unicode(var) els...
da59232e9e7715c5c1e87fde99f19997c8e1e890
26,335
from typing import List import os def read_annotation_files(annotation_files_directory: str, audio_files_directory: str, max_audio_files: int = np.inf, exclude_classes: List[str] = None) -> List[AudioFile]: """ Reads annotation files in a directory specified. :param annotation_f...
c4a89d10353c2e46be9a205d89918bc34f3a9a07
26,336
def vehicle_emoji(veh): """Maps a vehicle type id to an emoji :param veh: vehicle type id :return: vehicle type emoji """ if veh == 2: return u"\U0001F68B" elif veh == 6: return u"\U0001f687" elif veh == 7: return u"\U000026F4" elif veh == 12: return u"\U0...
8068ce68e0cdf7f220c37247ba2d03c6505a00fe
26,337
import functools def np_function(func=None, output_dtypes=None): """Decorator that allow a numpy function to be used in Eager and Graph modes. Similar to `tf.py_func` and `tf.py_function` but it doesn't require defining the inputs or the dtypes of the outputs a priori. In Eager mode it would convert the tf....
5ed18b1575ec88fe96c27e7de38b00c5a734ee91
26,338
from typing import List from typing import Dict def constituency_parse(doc: List[str]) -> List[Dict]: """ parameter: List[str] for each doc return: List[Dict] for each doc """ predictor = get_con_predictor() results = [] for sent in doc: result = predictor.predict(sentence=sent) ...
30dd8eca61412083f1f11db6dc8aeb27bc171de9
26,339
import os def ifFileExists(filePath): """ Cheks if the file exists; returns True/False filePath File Path """ return os.path.isfile(filePath)
2c4d6c332cff980a38d147ad0eafd1d0c3d902fc
26,340
def extract_results(filename): """ Extract intensity data from a FLIMfit results file. Converts any fraction data (e.g. beta, gamma) to contributions Required arguments: filename - the name of the file to load """ file = h5py.File(filename,'r') results = file['results'] keys = sorted_nicely(...
c4a9f4f66a53050ea55cb1bd266edfa285000717
26,341
async def bundle_status(args: Namespace) -> ExitCode: """Query the status of a Bundle in the LTA DB.""" response = await args.di["lta_rc"].request("GET", f"/Bundles/{args.uuid}") if args.json: print_dict_as_pretty_json(response) else: # display information about the core fields p...
2efb12b4bba3d9e920c199ad1e7262a24220d603
26,342
def determine_step_size(mode, i, threshold=20): """ A helper function that determines the next action to take based on the designated mode. Parameters ---------- mode (int) Determines which option to choose. i (int) the current step number. threshold (float) The ...
9b59ebe5eeac13f06662e715328d2d9a3ea0e9a2
26,343
def scroll_down(driver): """ This function will simulate the scroll down of the webpage :param driver: webdriver :type driver: webdriver :return: webdriver """ # Selenium supports execute JavaScript commands in current window / frame # get scroll height last_height = driver.execut...
7d68201f3a49950e509a7e389394915475ed8c94
26,344
from datetime import datetime def processing(): """Renders the khan projects page.""" return render_template('stem/tech/processing/gettingStarted.html', title="Processing - Getting Started", year=datetime.now().year)
53f6c69692591601dcb41c7efccad60bbfaf4cf7
26,345
def conv_unit(input_tensor, nb_filters, mp=False, dropout=0.1): """ one conv-relu-bn unit """ x = ZeroPadding2D()(input_tensor) x = Conv2D(nb_filters, (3, 3))(x) x = relu()(x) x = BatchNormalization(axis=3, momentum=0.66)(x) if mp: x = MaxPooling2D(pool_size=(3, 3), strides=(2, ...
7c24dae045c38c073431e4fab20687439601b141
26,346
import torch def combine_vectors(x, y): """ Function for combining two vectors with shapes (n_samples, ?) and (n_samples, ?). Parameters: x: (n_samples, ?) the first vector. In this assignment, this will be the noise vector of shape (n_samples, z_dim), but you shouldn't need to know ...
700ea418c6244dc745bf6add89ad786c4444d2fe
26,347
def expandMacros(context, template, outputFile, outputEncoding="utf-8"): """ This function can be used to expand a template which contains METAL macros, while leaving in place all the TAL and METAL commands. Doing this makes editing a template which uses METAL macros easier, becau...
04aad464f975c5ee216e17f93167be51eea8f6e6
26,348
def graph_papers(path="papers.csv"): """ Spit out the connections between people by papers """ data = defaultdict(dict) jkey = u'Paper' for gkey, group in groupby(read_csv(path, key=jkey), itemgetter(jkey)): for pair in combinations(group, 2): for idx,row in enumerate(pair...
43cae08f303707b75da2b225112fa0bc448306d9
26,349
def tariterator1(fileobj, check_sorted=False, keys=base_plus_ext, decode=True): """Alternative (new) implementation of tariterator.""" content = tardata(fileobj) samples = group_by_keys(keys=keys)(content) decoded = decoder(decode=decode)(samples) return decoded
8ea80d266dfe9c63336664aaf0fcac520e620382
26,350
def juego_nuevo(): """Pide al jugador la cantidad de filas/columnas, cantidad de palabras y las palabras.""" show_title("Crear sopa de NxN letras") nxn = pedir_entero("Ingrese un numero entero de la cantidad de\nfilas y columnas que desea (Entre 10 y 20):\n",10,20) n_palabras = pedir_entero("I...
ec42615c3934fd98ca5975f99d215f597f353842
26,351
def mk_sd_graph(pvalmat, thresh=0.05): """ Make a graph with edges as signifcant differences between treatments. """ digraph = DiGraph() for idx in range(len(pvalmat)): digraph.add_node(idx) for idx_a, idx_b, b_bigger, p_val in iter_all_pairs_cmp(pvalmat): if p_val > thresh: ...
f219d964ec90d58162db5e72d272ec8138f8991e
26,352
def body2hor(body_coords, theta, phi, psi): """Transforms the vector coordinates in body frame of reference to local horizon frame of reference. Parameters ---------- body_coords : array_like 3 dimensional vector with (x,y,z) coordinates in body axes. theta : float Pitch (or ele...
2e0e8f6bf3432a944a350fb7df5bdfa067074448
26,353
def negloglikelihoodZTNB(args, x): """Negative log likelihood for zero truncated negative binomial.""" a, m = args denom = 1 - NegBinom(a, m).pmf(0) return len(x) * np.log(denom) + negloglikelihoodNB(args, x)
8458cbc02a00fd2bc37d661a7e34a61afccb6124
26,354
def combine(m1, m2): """ Returns transform that combines two other transforms. """ return np.dot(m1, m2)
083de20237f484806c356c0b29c42ff28aa801f6
26,355
import torch def _acg_bound(nsim, k1, k2, lam, mtop = 1000): # John T Kent, Asaad M Ganeiber, and Kanti V Mardia. # A new unified approach forthe simulation of a wide class of directional distributions. # Journal of Computational andGraphical Statistics, 27(2):291–301, 2018. """ ...
45d96fee1b61d5c020e355df76d77c78483a3a0b
26,356
import os import shutil def anonymise_eeg( original_file: str, destination_file: str, field_name: str = '', field_surname: str = '', field_birthdate: str = '', field_sex: str = '', field_folder: str = '', field_centre: str = '', field_comment: str = '' ): """Anonymise an .eeg f...
d66e62448d0372754bd5a2e83e992c0e32122994
26,357
def melspecgrams_to_specgrams(logmelmag2 = None, mel_p = None, mel_downscale=1): """Converts melspecgrams to specgrams. Args: melspecgrams: Tensor of log magnitudes and instantaneous frequencies, shape [freq, time], mel scaling of frequencies. Returns: specgrams: Tensor of log magnitudes...
34090358eff2bf803af9b56c210d5e093b1f2900
26,358
from scipy.stats.mstats import gmean import numpy as np def ligandScore(ligand, genes): """calculate ligand score for given ligand and gene set""" if ligand.ligand_type == "peptide" and isinstance(ligand.preprogene, str): # check if multiple genes needs to be accounted for if isinstance(eval...
68141e9a837619b087cf132c6ba593ba5b1ef43d
26,359
def eval(x): """Evaluates the value of a variable. # Arguments x: A variable. # Returns A Numpy array. # Examples ```python >>> from keras import backend as K >>> kvar = K.variable(np.array([[1, 2], [3, 4]]), dtype='float32') >>> K.eval(kvar) array(...
a9b5473cc71cd999d6e85fd760018d454c194c04
26,360
from typing import Optional def triple_in_shape(expr: ShExJ.shapeExpr, label: ShExJ.tripleExprLabel, cntxt: Context) \ -> Optional[ShExJ.tripleExpr]: """ Search for the label in a shape expression """ te = None if isinstance(expr, (ShExJ.ShapeOr, ShExJ.ShapeAnd)): for expr2 in expr.shapeEx...
a1e9ba9e7c282475c775c17f52b51a78c3dcfd71
26,361
def poly_learning_rate(base_lr, curr_iter, max_iter, power=0.9): """poly learning rate policy""" lr = base_lr * (1 - float(curr_iter) / max_iter) ** power return lr
fdb2b6ed3784deb3fbf55f6b23f6bd32dac6a988
26,362
def parent_path(xpath): """ Removes the last element in an xpath, effectively yielding the xpath to the parent element :param xpath: An xpath with at least one '/' """ return xpath[:xpath.rfind('/')]
b435375b9d5e57c6668536ab819f40ae7e169b8e
26,363
from datetime import datetime def change_project_description(project_id): """For backwards compatibility: Change the description of a project.""" description = read_request() assert isinstance(description, (str,)) orig = get_project(project_id) orig.description = description orig.lastUpdated =...
c6b59cfbbffb353943a0a7ba4160ffb0e2382a51
26,364
import unittest def run_all(examples_main_path): """ Helper function to run all the test cases :arg: examples_main_path: the path to main examples directory """ # test cases to run test_cases = [TestExample1, TestExample2, TestExample3, Tes...
9a5176bff4e2c82561e3b0dbee467cd1dec0e63e
26,365
def get_queue(queue): """ :param queue: Queue Name or Queue ID or Queue Redis Key or Queue Instance :return: Queue instance """ if isinstance(queue, Queue): return queue if isinstance(queue, str): if queue.startswith(Queue.redis_queue_namespace_prefix): return Queue....
159860f2efa5c7a2643d4ed8b316e8abca85e67f
26,366
def ptttl_to_samples(ptttl_data, amplitude=0.5, wavetype=SINE_WAVE): """ Convert a PTTTLData object to a list of audio samples. :param PTTTLData ptttl_data: PTTTL/RTTTL source text :param float amplitude: Output signal amplitude, between 0.0 and 1.0. :param int wavetype: Waveform type for output si...
f4be93a315ff177cbdf69249f7efece55561b431
26,367
from typing import Union from pathlib import Path from typing import Tuple import numpy import pandas def read_output_ascii( path: Union[Path, str] ) -> Tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray]: """Read an output file (raw ASCII format) Args: path (str): path to the file ...
ef3008f6cf988f7bd42ccb75bfd6cfd1a58e28ae
26,368
def AliasPrefix(funcname): """Return the prefix of the function the named function is an alias of.""" alias = __aliases[funcname][0] return alias.prefix
771c0f665ddad2427759a5592608e5467005c26d
26,369
import logging import subprocess def run_command(*cmd_args, **kargs): """ Shell runner helper Work as subproccess.run except check is set to true by default and stdout is not printed unless the logging level is DEBUG """ logging.debug("Run command: " + " ".join(map(str, cmd_args))) if not ...
ce191b500176e263ecf1035f3ae467a334045757
26,370
from typing import Optional from typing import Tuple from typing import Callable def connect( sender: QWidget, signal: str, receiver: QObject, slot: str, caller: Optional[FormDBWidget] = None, ) -> Optional[Tuple[pyqtSignal, Callable]]: """Connect signal to slot for QSA.""" # Parameters e...
2ebeca355e721c5fad5ec6aac24a59587e4e86bd
26,371
import torch def get_detection_input(batch_size=1): """ Sample input for detection models, usable for tracing or testing """ return ( torch.rand(batch_size, 3, 224, 224), torch.full((batch_size,), 0).long(), torch.Tensor([1, 1, 200, 200]).repeat((batch_size, 1)), ...
710a5ed2f89610555d347af568647a8768f1ddb4
26,372
def build_tables(ch_groups, buffer_size, init_obj=None): """ build tables and associated I/O info for the channel groups. Parameters ---------- ch_groups : dict buffer_size : int init_obj : object with initialize_lh5_table() function Returns ------- ch_to_tbls : dict or Table ...
964bc6a817688eb8426976cec2b0053f43c6ed79
26,373
def segmentspan(revlog, revs): """Get the byte span of a segment of revisions revs is a sorted array of revision numbers >>> revlog = _testrevlog([ ... 5, #0 ... 10, #1 ... 12, #2 ... 12, #3 (empty) ... 17, #4 ... ]) >>> segmentspan(revlog, [0, 1, 2, 3, 4]) 17 >>...
51624b3eac7bba128a2e702c3387bbaab4974143
26,374
def is_stateful(change, stateful_resources): """ Boolean check if current change references a stateful resource """ return change['ResourceType'] in stateful_resources
055465870f9118945a9e5f2ff39be08cdcf35d31
26,375
import pwd import os def get_osusername(): """Get the username of the current process.""" if pwd is None: raise OSError("get_username cannot be called on Windows") return pwd.getpwuid(os.getuid())[0]
db72cb393a8fd79e5d2078b5597a0c037595b3f6
26,376
def get_session_from_webdriver(driver: WebDriver, registry: Registry) -> RedisSession: """Extract session cookie from a Selenium driver and fetch a matching pyramid_redis_sesssion data. Example:: def test_newsletter_referral(dbsession, web_server, browser, init): '''Referral is tracker for...
0faaa394c065344117cec67ec824ec5186252ee2
26,377
import sys def parse_argv(): """ Retrieve fields from sys.argv """ if len(sys.argv) == 2: main_file = sys.argv[1] with open(main_file) as main_file_handle: main_code = main_file_handle.read() return sys.argv[0], {main_file: main_code}, main_file, main_code, None, None, None...
fdc58acbe6dc4f7ccef929da7015269746986fed
26,378
from typing import Tuple def paper() -> Tuple[str]: """ Use my paper figure style. Returns ------- Tuple[str] Colors in the color palette. """ sns.set_context("paper") style = { "axes.spines.bottom": True, "axes.spines.left": True, "axes.spines.righ...
6e53247c666db62be1d5bf5ad5d77288af277d2d
26,379
import difflib def _get_diff_text(old, new): """ Returns the diff of two text blobs. """ diff = difflib.unified_diff(old.splitlines(1), new.splitlines(1)) return "".join([x.replace("\r", "") for x in diff])
bd8a3d49ccf7b6c18e6cd617e6ad2ad8324de1cc
26,380
import numpy as np import matplotlib.pyplot as plt from astropy.table import Table from astropy.time import Time import astropy.units as u from astropy.coordinates import SkyCoord from shapely.geometry import Polygon from descartes import PolygonPatch from astroquery.alma import Alma import os def alma_query(tab, mak...
3c4409f35b27939f332c31a57f4450b1229b7034
26,381
def GetStatus(operation): """Returns string status for given operation. Args: operation: A messages.Operation instance. Returns: The status of the operation in string form. """ if not operation.done: return Status.PENDING.name elif operation.error: return Status.ERROR.name else: retu...
c9630528dd9b2e331a9d387cac0798bf07646603
26,382
import argparse from datetime import datetime def get_args(args): """Get the script arguments.""" description = "tvtid - Feteches the tv schedule from client.dk" arg = argparse.ArgumentParser(description=description) arg.add_argument( "-d", "--date", metavar="datetime", ...
0068f54fc5660896a8ab6998de9da3909c8e1a6b
26,383
def ft2m(ft): """ Converts feet to meters. """ if ft == None: return None return ft * 0.3048
ca2b4649b136c9128b5b3ae57dd00c6cedd0f383
26,384
def show_colors(*, nhues=17, minsat=10, unknown='User', include=None, ignore=None): """ Generate tables of the registered color names. Adapted from `this example <https://matplotlib.org/examples/color/named_colors.html>`__. Parameters ---------- nhues : int, optional The number of break...
34b45185af96f3ce6111989f83d584006ebceb49
26,385
def get_all_lights(scene, include_light_filters=True): """Return a list of all lights in the scene, including mesh lights Args: scene (byp.types.Scene) - scene file to look for lights include_light_filters (bool) - whether or not light filters should be included in the list Returns: (list)...
4570f36bdfbef287f38a250cddcdc7f8c8d8665d
26,386
def get_df(path): """Load raw dataframe from JSON data.""" with open(path) as reader: df = pd.DataFrame(load(reader)) df['rate'] = 1e3 / df['ms_per_record'] return df
0e94506fcaa4bd64388eb2def4f9a66c19bd9b32
26,387
def _format_distribution_details(details, color=False): """Format distribution details for printing later.""" def _y_v(value): """Print value in distribution details.""" if color: return colored.yellow(value) else: return value # Maps keys in configuration to...
ccfa7d9b35b17ba9889f5012d1ae5aa1612d33b1
26,388
async def async_get_relation_id(application_name, remote_application_name, model_name=None, remote_interface_name=None): """ Get relation id of relation from model. :param model_name: Name of model to operate on :type model_name: str :...
2447c08c57d2ed4548db547fb4c347987f0ac88b
26,389
from operator import or_ def get_timeseries_references(session_id, search_value, length, offset, column, order): """ Gets a filtered list of timeseries references. This function will generate a filtered list of timeseries references belonging to a session given a search value. The length, offset, and...
67011d7d1956259c383cd2722ae4035c28e6a5f3
26,390
import os import re def get_current_version(): """Get current version""" base_dir = os.path.abspath(os.path.dirname(__file__)) version_file = os.path.join(base_dir, "evaluations", "__init__.py") with open(version_file, 'r') as opened_file: return re.search( r'^__version__ = [\'"]([...
b1e6a9acfe59b7603c82c93868e634d93ae4cd86
26,391
def mxprv_from_bip39_mnemonic( mnemonic: Mnemonic, passphrase: str = "", network: str = "mainnet" ) -> bytes: """Return BIP32 root master extended private key from BIP39 mnemonic.""" seed = bip39.seed_from_mnemonic(mnemonic, passphrase) version = NETWORKS[network].bip32_prv return rootxprv_from_see...
ceb5f5e853f7964015a2a69ea2fdb26680acf2b3
26,392
import os import codecs import sys import platform def setup_ebook_home(args, conf): """ Setup user's ebook home, config being set with this order of precedence: - CLI params - ENV vars - saved values in ogre config - automatically created in $HOME """ ebook_home = None # 1) l...
1d18e120304bb2b21df7252c6ea8c4e09fdf6314
26,393
def translate_text( text: str, source_language: str, target_language: str ) -> str: """Translates text into the target language. This method uses ISO 639-1 compliant language codes to specify languages. To learn more about ISO 639-1, see: https://www.w3schools.com/tags/ref_language_codes.as...
ed82dbb2fd89398340ed6ff39132f95758bfab97
26,394
def evt_cache_staged_t(ticket): """ create event EvtCacheStaged from ticket ticket """ fc_keys = ['bfid' ] ev = _get_proto(ticket, fc_keys = fc_keys) ev['cache']['en'] = _set_cache_en(ticket) return EvtCacheStaged(ev)
86543ca98257cab28e4bfccef229c8d8e5b6893b
26,395
from typing import Dict def _get_setup_keywords(pkg_data: dict, keywords: dict) -> Dict: """Gather all setuptools.setup() keyword args.""" options_keywords = dict( packages=list(pkg_data), package_data={pkg: list(files) for pkg, files in pkg_data.items()}, ) keyw...
34f2d52c484fc4e49ccaca574639929756cfa4dc
26,396
import six def flatten(x): """flatten(sequence) -> list Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables). Examples: >>> [1, 2, [3,4], (5,6)] [1, 2, [3, 4], (5, 6)] >>> flatten([[[1,2,3], (42,...
041807c1622f644c062a5adb0404d14589cc543b
26,397
from clawpack.visclaw import colormaps, geoplot from numpy import linspace from clawpack.visclaw.data import ClawPlotData from clawpack.visclaw import gaugetools import pylab import pylab from numpy import ma from numpy import ma import pylab import pylab from pylab import plot, xticks, floor, xlabel def setplot(plot...
a777686f5b8fafe8c2a109e486242a16d25a463b
26,398
from typing import Dict import json def load_spider_tables(filenames: str) -> Dict[str, Schema]: """Loads database schemas from the specified filenames.""" examples = {} for filename in filenames.split(","): with open(filename) as training_file: examples.update(process_dbs(json.load(tr...
1575d0afd4efbe5f53d12be1c7dd3537e54fc46c
26,399