content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import logging def read_burris(fh): """ Read Burris formatted file, from given open file handle. Accepts comma or tab-separated files. Parameters ---------- fh : TextIOWrapper open file handle Returns ------- ChannelList """ all_survey_data = ChannelList() ...
4519cf73be5663a70e76e083aa9f735f427248a6
17,211
import re def _remove_invalid_characters(file_name): """Removes invalid characters from the given file name.""" return re.sub(r'[/\x00-\x1f]', '', file_name)
49a9f668e8142855ca4411921c0180977afe0370
17,212
def load_actions( file_pointer, file_metadata, target_adim, action_mismatch, impute_autograsp_action ): """Load states from a file given metadata and hyperparameters Inputs: file_pointer : file object file_metadata : file metadata row (Pandas) target_adim ...
0b8b5dc259fa0645069cc57b4510355ec6897ab6
17,214
def send_message(hookurl: str, text: str) -> int: """ Send a message on the channel of the Teams. The HTTP status is returned. parameters ---------- hookurl : str URL for the hook to the Teams' channel. text : str text to send. returns ------- int HTTP...
8ffef50d745fafd125b556e9fb1ceff2cb438a4e
17,215
def np_fft_irfftn(a, *args, **kwargs): """Numpy fft.irfftn wrapper for Quantity objects. Drop dimension, compute result and add it back.""" res = np.fft.irfftn(a.value, *args, **kwargs) return Quantity(res, a.dimension)
fbfdfe470f09106e9589709ebae5fa19ba8a2732
17,216
def get_codec_options() -> CodecOptions: """ Register all flag type registry and get the :class:`CodecOptions` to be used on ``pymongo``. :return: `CodecOptions` to be used from `pymongo` """ return CodecOptions(type_registry=TypeRegistry(type_registry))
a0acd3e719ae0a4be463c71cba5eb86914348248
17,217
def get_frame_lims(x_eye, y_eye, x_nose, y_nose, view, vertical_align='eye'): """Automatically compute the crop parameters of a view using the eye and nose and reference. Note that horizontal/vertical proportions are currently hard-coded. Parameters ---------- x_eye : float x position of t...
20b3c5d74b7d4dd4b2b63c9d32f7325a199d3dee
17,218
def split(time: list, value: list, step, group_hours, region=None, whole_group=False): """ Split and group 'step' number of averaged values 'hours' apart :param time: time per value (hour apart) :param value: values corresponding to time :param step: number of group times set for each index ...
a8f8cf51d241a532e6a925d4323abb281215f543
17,220
def launch_ebs_affinity_process(instanceid, instance_infos, ebs_configs): """ Manage the ebs affinity process. :param instanceid string The instance id :param instance_infos dict Informations about the instance :param ebs_config dict The EBS parameters :return None """ ...
ec30f4748417cee8f9fe96c2c47cf78dd10be59f
17,221
def get_all(isamAppliance, check_mode=False, force=False): """ Retrieve a list of mapping rules """ return isamAppliance.invoke_get("Retrieve a list of mapping rules", "/iam/access/v8/mapping-rules")
e48aa65f5212ea32e84c40e326633cf2971d378a
17,222
def get_oyente(test_subject=None, mutation=None): """ Run the Oyente test suite on a provided script """ is_request = False if not test_subject: test_subject = request.form.get('data') is_request = True o = Oyente(test_subject) info, errors = o.oyente(test_subject) if len(errors) > 0: errors = [{'lin...
f264262c22314ac26b56369f4d7741effb4cf09e
17,223
def search_for_example(search_string: str) -> tuple: """Get the Example for a Particular Function""" function = match_string(search_string) if function: function = function.strip() sql = f"SELECT example, comment FROM example WHERE function='{function}'" data = execute(sql) ...
16eb034369954017b1b51a206d48af40f5768ef6
17,224
def WildZumba(x,c1=20,c2=0.2,c3=2*np.pi) : """ A separable R**n==>R function, assumes a real-valued numpy vector as input """ return -c1 * np.exp(-c2*np.sqrt(np.mean(x**2))) - np.exp(np.mean(np.cos(c3*x))) + c1 + np.exp(1)
589f90f174d61269c2c019ef678f51c498c68ff8
17,225
def import_xlsx(filename, skip_variation=False): """Импортирует параметры пиков, хроматограммы и варьируемых параметров, если они указаны. Parameters ---------- filename : str Имя xlsx файла. skip_variation : bool, default = False Пропустить блок Variation даже если он есть. Re...
75b32618274fb2ab7ede9f525856fdc13e8c97ee
17,226
from typing import Union from typing import Optional def _get_dataset_builder( dataset: Union[str, tfds.core.DatasetBuilder], data_dir: Optional[str] = None) -> tfds.core.DatasetBuilder: """Returns a dataset builder.""" if isinstance(dataset, str): dataset_builder = tfds.builder(dataset, data_dir=data...
0f17169541604e69a614ddfeee4c8a963834ed8e
17,227
def write_bbox(scene_bbox, out_filename): """Export scene bbox to meshes Args: scene_bbox: (N x 6 numpy array): xyz pos of center and 3 lengths out_filename: (string) filename Note: To visualize the boxes in MeshLab. 1. Select the objects (the boxes) 2. Filters -> Po...
c7504260306495e6252569a3cb83f61ca084de26
17,228
def label_rotate(annot, rotate): """ anti-clockwise rotate the occ order annotation by rotate*90 degrees :param annot: (H, W, 9) ; [-1, 0, 1] :param rotate: value in [0, 1, 2, 3] :return: """ rotate = int(rotate) if rotate == 0: return annot else: annot_rot = np.rot9...
e37a2e9dddc5f19898691fe22d02978d1954d435
17,229
def allocate_available_excess(region): """ Allocate available excess capital (if any). """ difference = region['total_revenue'] - region['total_cost'] if difference > 0: region['available_cross_subsidy'] = difference region['deficit'] = 0 else: region['available_cross_s...
19a3d7fbc776ae5b5b47ecfc32db14bf4abd949e
17,230
def items(dic): """Py 2/3 compatible way of getting the items of a dictionary.""" try: return dic.iteritems() except AttributeError: return iter(dic.items())
2664567765efe172591fafb49a0efa36ab9fcca8
17,231
import json import binascii def new_settingsresponse_message(loaded_json, origin): """ takes in a request - executes search for settings and creates a response as bytes :param loaded_json: :param origin: is this a response of drone or groundstation :return: a complete response packet as bytes ...
812444353a50ffeb468398d8681e81a74cb9d7e9
17,232
def list_icmp_block(zone, permanent=True): """ List ICMP blocks on a zone .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt '*' firewlld.list_icmp_block zone """ cmd = "--zone={0} --list-icmp-blocks".format(zone) if permanent: cmd += " --permanent" ...
9f0f8c2e7a688263ddd31c8384babba25e2300e6
17,233
def dependencies_found(analysis_id, execution_id): """ Installation data from buildbot. Requires a JSON list of objects with the following keys: * installer: The system used to install the dependency. * spec: The full specification used by the user to request the package. ...
8983e53dd558b42272d4886412e918e7b192754e
17,234
def set_augmentor(): """ Set the augmentor. 1. Select the operations and create the config dictionary 2. Pass it to the Augmentor class with any other information that requires 3. Return the instance of the class. :return: """ config = {'blur': {'values': ('gaussian', 0.7, 1.0), 'prob': ...
77c64cec87af2d41a4cc6dc55600ab5eaedad247
17,235
def get_global_event_logger_instance(): """Get an event logger with prefilled fields for the collection. This returns an options configured event logger (proxy) with prefilled fields. This is almost CERTAINLY the event logger that you want to use in zaza test functions. :returns: a configured Log...
66228b15dd4d1ac9468834124e4ba073a846580f
17,236
def plot_market_entry(cat_entry_and_exit_df, cat_entry_and_exit_df_2): """ returns a plot with the entry and exit of firms per category """ # get the limits so everything is on the same scale df = pd.concat([cat_entry_and_exit_df, cat_entry_and_exit_df_2]) limits = [-df.exit.max() - 0.3, df.entr...
c1b1ad00c1dbdde804e4d594dda4ae6525c7779f
17,237
import io def find_elements_by_image(self, filename): """ Locate all the occurence of an image in the webpage. :Args: - filename: The path to the image to search (image shall be in PNG format). :Returns: A list of ImageElement. """ template = cv2.imread(filename, cv2.IMREAD_U...
23137766b68068c8cb78bb57127bfa6040bace70
17,238
from typing import Set from typing import Sequence def compile_tf_signature_def_saved_model( saved_model_dir: str, saved_model_tags: Set[str], module_name: str, exported_name: str, input_names: Sequence[str], output_names: Sequence[str]) -> Modules: """Compiles a SignatureDef SavedModel to each backend ...
ed1a1efc28c9ae473d76c700ab7781f141fc3765
17,239
def origtime2float(time): """ converts current datetime to float >>> import datetime >>> t = datetime.datetime(2010, 8, 5, 14, 45, 41, 778877) >>> origtime2float(t) 53141.778876999997 """ t3fmt = time.strftime("%H:%M:%S:%f") return time2float(t3fmt)
03cadf1f686fde1dd46cbb52fd71adcc2f06585c
17,240
def discrete_fourier_transform1(freq, tvec, dvec, log=False): """ Calculate the Discrete Fourier transform (slow scales with N^2) The DFT is normalised to have the mean value of the data at zero frequency :param freq: numpy array, frequency grid calculated from the time vector :param tvec: numpy a...
b5e1bafe1ba2b8863ac97bb95c204ca84877b8fd
17,241
from typing import List def ngram_overlaps(a: List[str], b: List[str], threshold: int = 3) -> List[int]: """ Compute the set over overlapping strings in each set based on n-gram overlap where 'n' is defined by the passed in threshold. """ def get_ngrams(text): """ Get a set of all...
87621e28a4a5d2cba5bb66c6bfa9834c711a7ecf
17,242
def ssq_cwt(x, wavelet='morlet', scales='log', nv=None, fs=None, t=None, ssq_freqs=None, padtype='symmetric', squeezing='sum', difftype='direct', difforder=None, gamma=None): """Calculates the synchrosqueezed Continuous Wavelet Transform of `x`. Implements the algorithm described in Sec....
8af5caea64e9a861f7702f52c50681e61322658c
17,243
import random import logging import time def request_retry_decorator(fn_to_call, exc_handler): """A generic decorator for retrying cloud API operations with consistent repeatable failure patterns. This can be API rate limiting errors, connection timeouts, transient SSL errors, etc. Args: fn_to_cal...
0813cc19d9826275917c9eb701683a73bfe597f9
17,244
from datetime import datetime def last_day_of_month(d): """ From: https://stackoverflow.com/a/43088/6929343 """ if d.month == 12: return d.replace(day=31) return d.replace(month=d.month+1, day=1) - datetime.timedelta(days=1)
a97ce3bdbcd9d5cb707919750ecc818de04deb7e
17,248
import google def get_access_token(): """Return access token for use in API request. Raises: requests.exceptions.ConnectionError. """ credentials, _ = google.auth.default(scopes=[ 'https://www.googleapis.com/auth/cloud-platform', 'https://www.googleapis.com/auth/cloud-platform...
907aacd6d9976390b2896149179c84ea9bd3d0fc
17,250
def unknown_action(player: Player, table: dynamodb.Table) -> ActionResponse: """ Do nothing because the action could not be resolved. In the message list, returns a message saying the action was bad. :return: Original inputs matching updated inputs, and a message """ message = ["Action could no...
ea2a03d140eea2853b77da492ea0f403fc9c6ad9
17,252
def forecast_marginal_bindglm(mod, n, k, X=None, nsamps=1, mean_only=False): """ Marginal forecast function k steps ahead for a binomial DGLM """ # Plug in the correct F values F = update_F(mod, X, F=mod.F.copy()) # F = np.copy(mod.F) # if mod.nregn > 0: # F[mod.iregn] = X.reshape(mo...
dc8c82fc17465c4a22e7bc5d46cf9b5abd9abd54
17,253
def import_file(isamAppliance, id, filename, check_mode=False, force=False): """ Importing a file in the runtime template files directory. """ warnings = [] check_file = _check(isamAppliance, id) if check_file != None and force == False: warnings.append("File {0} exist.".format(id)) ...
3978e5476a7344ef4c92d2cec3852a57850380df
17,254
def get_func_from_attrdict(func_name : str, attrdict : AttrDict) -> ObjectiveFunction1D: """ Given a string func_name, attempts to find the corresponding entry from attrdict. :param func_name :param attrdict :returns Objective Function """ for key, val in attrdict.items(): if val.n...
bb4b03371d5fbb642864d7c9e77d4172fee92315
17,255
from fdk import runner import io def event_handle(handle_code): """ Performs HTTP request-response procedure :param handle_code: customer's code :type handle_code: fdk.customer_code.Function :return: None """ async def pure_handler(request): log.log("in pure_handler") heade...
03ca9cff4b7993e92c146565cb697a080d40c5ef
17,256
import torch def load_precomputed_embeddings(det_df, seq_info_dict, embeddings_dir, use_cuda): """ Given a sequence's detections, it loads from disk embeddings that have already been computed and stored for its detections Args: det_df: pd.DataFrame with detection coordinates seq_info_d...
685eb63ca23d634345304575a148e72a8172567e
17,257
def _model_gpt(size=0, dropout_rate=0.0, attention_dropout_rate=0.0): """Configs for a variety of Transformer model sizes.""" num_layers = [1, 3, 6, 12, 24, 36, 48][size] dim = [64, 128, 512, 768, 1024, 1280, 1600][size] num_heads = int(dim / 64) # Always dim 64 per head return _transformer( emb_dim=di...
7bc9eab929b8c48ca4b8ff671e9e0885c0d2bc44
17,258
def test_module(client, demisto_args: dict): """ Test the OMWS Client connection by attempting to query a common username """ d = client.query_profile_data("maneenus") if d: return 'ok' else: raise DemistoException("Incorrect or empty API response")
59e653c8fb5c40ee84a5945e5e4b0410418248ec
17,259
def as_string(raw_data): """Converts the given raw bytes to a string (removes NULL)""" return bytearray(raw_data[:-1])
6610291bb5b71ffc0be18b4505c95653bdac4c55
17,260
import math def generate_trapezoid_profile(max_v, time_to_max_v, dt, goal): """Creates a trapezoid profile with the given constraints. Returns: t_rec -- list of timestamps x_rec -- list of positions at each timestep v_rec -- list of velocities at each timestep a_rec -- list of accelerations a...
5851cfab06e20a9e79c3a321bad510d33639aaca
17,262
import logging def get_logger(name: str, format_str: str = aps_logger_format, date_format: str = aps_time_format, file: bool = False) -> logging.Logger: """ Get logger instance Args: name: logger name format_str|date_format: to configure logging...
06d673473c7014d6373003bf924fdf2dc9965baf
17,265
import torch def to_tensor(args, device=None): """Convert an arg or sequence of args to torch Tensors """ singleton = not isinstance(args, (list, tuple)) if singleton: args = [args] tensor_args = [] for arg in args: if isinstance(arg, torch.Tensor): tensor_args.app...
d85d842c095aa3c942f94e61c79d2bbeb49bc41d
17,266
def main(self): """ to run: kosmos 'j.data.bcdb.test(name="meta_test")' """ bcdb, _ = self._load_test_model() assert len(bcdb.get_all()) == 0 assert len(bcdb.meta._data["url"]) == 7 s = list(j.data.schema._url_to_md5.keys()) assert "despiegk.test" in s m = bcdb.model_get(u...
7f88d33bd6cc2df5284201d859718a8a06e6a4e4
17,267
def snake_head_only(): """ |===========| |···········| |···········| |···········| |···········| |···········| |···········| |·······o···| |···········| |···········| |···········| |···········| |===========| """ return Snake.from_dict( **{ ...
c08ffd0a86ec9d5a40d2649dd63a2b60019a6791
17,268
import six def str_to_bool(s): """Convert a string value to its corresponding boolean value.""" if isinstance(s, bool): return s elif not isinstance(s, six.string_types): raise TypeError('argument must be a string') true_values = ('true', 'on', '1') false_values = ('false', 'off',...
c228321872f253ce3e05c6af9284ec496dea8dcf
17,269
def id_feat_pred_mz_rt(cursor, mz, rt, ccs, tol_mz, tol_rt, tol_ccs, esi_mode, norm='l2'): """ id_feat_pred_mz_rt description: identifies a feature on the basis of predicted m/z and retention time parameters: cursor (sqlite3.Cursor) -- cursor for querying lipids.db mz (float) -- m/z ...
72818a631b155e1c50d53b26c1749bf8f68767f7
17,270
def Arrow_bg(self): """ The function that will create the background for the dropdown arrow button. For internal use only. This function is therefore also not imported by __init__.py """ #Just leave the making of the buttons background to the default function. Not gonna bother re-doing that here (be...
4b09c197666aa5ea15713d98ae7c38e1b0ffa0e0
17,272
def get_bounds_5km_to_1km( itk_5km, isc_5km ) : """ return the 1km pixel indexes limits in the 5km pixel [ itk_5km, isc_5km ] footprint """ # set the (track,scan) indexes of the 5km pixel in the 5km grid itk_1km = itk_5km_to_1km ( itk_5km ) isc_1km = isc_5km_to_1km ( isc_5km ) # set the 1k...
7fd175787f075d7ed9b3e8ed04565f38877de1e4
17,274
import torch def batch_hard_triplet_loss(labels, embeddings, margin, squared=False): """Build the triplet loss over a batch of embeddings. For each anchor, we get the hardest positive and hardest negative to form a triplet. Args: labels: labels of the batch, of size (batch_size,) embedding...
37d20237580463e668cee77c96f732f2d0211aef
17,275
def categorical_sample_logits(logits): """ Samples (symbolically) from categorical distribution, where logits is a NxK matrix specifying N categorical distributions with K categories specifically, exp(logits) / sum( exp(logits), axis=1 ) is the probabilities of the different classes Cleverly ...
f93752b11de02b1b61f60b3ff5c12dd9c15f7d8f
17,276
def sort_results(boxes): """Returns the top n boxes based on score given DenseCap results.json output Parameters ---------- boxes : dictionary output from load_output_json n : integer number of boxes to return Returns ------- sorted dictionary """ r...
20f30e5846de4ce46073c3d32573d283576489e0
17,277
from datetime import datetime def get_date(d : str) -> datetime.datetime: """A helper function that takes a ModDB string representation of time and returns an equivalent datetime.datetime object. This can range from a datetime with the full year to second to just a year and a month. Parameters ...
44fb951ecb96102c631f88dc888aac11d11c8bad
17,278
def var_policer(*args): """Returns a variable policer object built from args.""" return VarPolicer(args)
a346e041118f1be2ed6b0acd2c9e3d04603031df
17,279
def winner(board): """ Returns the winner of the game, if there is one. """ #looking horizontal winner i = 0 while i < len(board): j = 1 while j <len(board): if board[i][j-1]==board[i][j] and board[i][j] == board[i][j+1]: return board[i][j] ...
31ab2cf04dfe269598efdd073762505643563a96
17,280
import signal def freqz_resp_list(b, a=np.array([1]), mode='dB', fs=1.0, n_pts=1024, fsize=(6, 4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying...
207ad7ad59a3260df9d5df80c1b8e1bee4c33a3e
17,281
import socket def _nslookup(ipv4): """Lookup the hostname of an IPv4 address. Args: ipv4: IPv4 address Returns: hostname: Name of host """ # Initialize key variables hostname = None # Return result try: ip_results = socket.gethostbyaddr(ipv4) if len(...
7771887dbfcd60e73b8fce0ce4029fcd7058a7d1
17,282
def get_service_node(service): """ Returns the name of the node that is providing the given service, or empty string """ node = rosservice_get_service_node(service) if node == None: node = "" return node
7a8df548e119e8197f92340d228fdc7855494670
17,283
import warnings from io import StringIO def _download_nasdaq_symbols(timeout): """ @param timeout: the time to wait for the FTP connection """ try: ftp_session = FTP(_NASDAQ_FTP_SERVER, timeout=timeout) ftp_session.login() except all_errors as err: raise RemoteDataError('Er...
9b34571086ac3e738e29b3ed130ab2d0c7303657
17,284
def sessions(request): """ Cookies prepeocessor """ context = {} return context
562f4e9da57d3871ce780dc1a0661a34b3279ec5
17,285
import logging def dynamax_mnn(src: nb.typed.Dict, trg: nb.typed.Dict, src_emb: np.ndarray, trg_emb: np.ndarray, src_k: np.ndarray, trg_k: np.ndarray) -> np.ndarray: """ Run Dynamax-Jaccard in both directions and infer mutual neighbors. :param src nb.typed.Dict: src_id2poi...
174f603df09cbe7a8ee91de29de48ccaf2573b31
17,286
def resnet152(pretrained=False, progress=True, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet progress (bool): If True, displays a progress bar of the download to stderr """ return _resnet('resnet152', DistillerBott...
5e3435eea1a18c028d422abef57d9e88d88e609f
17,287
import torch def _load_model(featurizer_path): """Load the featurization model Parameters ---------- featurizer_path: str Path to the saved model file Returns ------- The loaded PyTorch model """ # load in saved model ...
21c29c9320b482bb33e82f97723d04bb53364ba1
17,288
def grid0_baseline(num_runs, render=True): """Run script for the grid0 baseline. Parameters ---------- num_runs : int number of rollouts the performance of the environment is evaluated over render : bool, optional specifies whether to use the gui during e...
8cb8a01309bb8ea3aae467d8a6c8a81ce295ab94
17,289
def read_aims(filename): """Method to read FHI-aims geometry files in phonopy context.""" lines = open(filename, 'r').readlines() cell = [] is_frac = [] positions = [] symbols = [] magmoms = [] for line in lines: fields = line.split() if not len(fields): con...
bcf5f00e57ed249c10667ad0b883986cb1b36865
17,290
def test(model, issue_batches): """ return accuracy on test set """ session = tf.get_default_session() num_correct = 0 num_predict = 0 for epoch, step, eigens, labels in issue_batches: feeds = { model['eigens']: eigens, } guess = session.run(model['gues...
0d8ae672766567a6665089c2d7d5004e25d80755
17,291
def evaluate_sample(ResNet50_model, X_train, Y_train, X_val_b,Y_val_b,X_data,Y_data,checkpoint_path): """ A function that accepts a labeled-unlabeled data split and trains the relevant model on the labeled data, returning the model and it's accuracy on the test set. """ # shuffle the training set: ...
c5f86feede372f078e9c88bac688c790de6578d6
17,292
import six import base64 def Base64WSEncode(s): """ Return Base64 web safe encoding of s. Suppress padding characters (=). Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type unicode to string type first. @param s: string to encode as Base64 @type s: string @retur...
cb28001bddec215b763936fde4652289cf6480c0
17,293
def onlyWikipediaURLS(urls): """Some example HTML page data is from wikipedia. This function converts relative wikipedia links to full wikipedia URLs""" wikiURLs = [url for url in urls if url.startswith('/wiki/')] return ["https://en.wikipedia.org"+url for url in wikiURLs]
df9ecbb73dfc9a764e4129069a4317517830307a
17,294
def get_image_filename_index(): """ Obtain a mapping of filename -> filepath for images :return: """ index_path = osp.join(SEG_ROOT, 'privacy_filters', 'cache', 'fname_index.pkl') if osp.exists(index_path): print 'Found cached index. Loading it...' return pickle.load(open(index_p...
002b6fd4dea1b00bb758377e71de0e67f5d979d3
17,295
def merge_coordinates(coordinates, capture_size): """Merge overlapping coordinates for MIP targets. Parameters ---------- coordinates: python dictionary Coordinates to be merged in the form {target-name: {chrom: chrx, begin: start-coordinate, end: end-coordinate}, ..} capture_size: ...
8af4a34fc8ce1a01ddcd4d4f257815ef5f852911
17,296
def Emojify_V2(input_shape, word_to_vec_map, word_to_index): """ Function creating the Emojify-v2 model's graph. Arguments: input_shape -- shape of the input, usually (max_len,) word_to_vec_map -- dictionary mapping every word in a vocabulary into its 50-dimensional vector representation word_t...
111a0c97e9a8c75aa6a7191ee89cbda69a84794c
17,297
def de_parser(lines): """return a dict of {OfficalName: str, Synonyms: str, Fragment: bool, Contains: [itemdict,], Includes: [itemdict,]} from DE lines The DE (DEscription) lines contain general descriptive information about the sequence stored. This information is generally sufficient to identify ...
d22158e365c52976ed638c27a0a85d8a047d743d
17,299
def roundPrecision(number, precision=4): """ Rounds the given floating point number to a certain precision, for output.""" return float(('{:.' + str(precision) + 'E}').format(number))
3bac0b54f1f8320c158ce0ddc14db7bbd092d2ff
17,300
def stringToNumbers(string, separators=[","], commentSymbol="#"): """ Return a list of splitted string and numbers from string "string". Numbers will be converted into floats. Text after "#" will be skipped. --- string: the string to be converted. --- separators: a list of additional separators other than whitesp...
dea1fb1d3257d00eaa637e1b80f23ad0e6475c38
17,302
import json def friend_invitation_by_facebook_send_view(request): # friendInvitationByFacebookSend """ :param request: :return: """ voter_device_id = get_voter_device_id(request) # We standardize how we take in the voter_device_id recipients_facebook_id_array = request.GET.getlist('recipien...
6aeb2852b9e299bc8ddd5d03fbff2d0200e5c4a0
17,303
import json def inv_send_received(r, **attr): """ Confirm a Shipment has been Received - called via POST from inv_send_rheader - called via JSON method to reduce request overheads """ if r.http != "POST": r.error(405, current.ERROR.BAD_METHOD, next = URL(),...
645281e0e2023bd454021058e0c0ed79a61223b2
17,304
import numbers def filter_table(table, filter_series, ignore=None): """ Filter a table based on a set of restrictions given in Series of column name / filter parameter pairs. The column names can have suffixes `_min` and `_max` to indicate "less than" and "greater than" constraints. Parameter...
5e5692c46e2dd207eca8d752912dff2b712cce18
17,305
def analogy_computation_2d(f_first_enc, f_first_frame, f_current_enc, first_depth): """Implements the deep analogy computation.""" with tf.variable_scope('analogy_computation'): frame_enc_diff = f_first_frame - f_first_enc fr...
376176b8c17cf9e2f9611943b1fb18da4359748d
17,306
def format_to_TeX(elements): """returns BeautifulSoup elements in LaTeX. """ accum = [] for el in elements: if isinstance(el, NavigableString): accum.append(escape_LaTeX(el.string)) else: accum.append(format_el(el)) return "".join(accum)
2df2c4979fc65656b8ef7f4b514a9c4e036b3fa1
17,307
from typing import OrderedDict def namedlist(typename, field_names, verbose=False, rename=False): """Returns a new subclass of list with named fields. >>> Point = namedlist('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22)...
0d7e567e69c9d5c0038f4258b37f17ff1e6fb5b1
17,308
from typing import List def has_good_frames(frames: List[MonitoredFrame]) -> bool: """ Find a frame with a score larger than X """ return any([frame.score and frame.score > 3 for frame in frames])
16e9e2bce53ae957254121438c2c4e4f8add2142
17,309
def updateHistory(conn, author, message_id, backer): """ Updates the history Returns success """ c = conn.cursor() c.execute(prepareQuery("INSERT INTO votes_history (user_id, message_id, backer) VALUES (?,?,?)"), (int(author), int(message_id), int(backer), )) conn.commit() return c.rowco...
6e0f06ace0e3600c307fe3f5848da583c930bbe8
17,310
import six def pyc_loads(data): """ Load a .pyc file from a bytestring. Arguments: data(bytes): The content of the .pyc file. Returns: PycFile: The parsed representation of the .pyc file. """ return pyc_load(six.BytesIO(data))
99b4b7d07d00a0c5098f1a3ded7c1929e2a4b231
17,311
import numpy def time_series_figure(time_series, polynomial, drift, snr): """ Return a matplotlib figure containing the time series and its polynomial model. """ figure = plt.figure() plot = figure.add_subplot(111) plot.grid() plt.title("Drift: {0: .1f}% - SNR: {1: .1f}dB".format( ...
132aaf22108999e75ec6ca797753724d3198b2c8
17,312
def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" class metaclass(type): def __new__(cls, name, this_bases, d): return meta(name, bases, d) return type.__new__(metaclass, 'temporary_class', (), {})
0f20f8414adf1d324fbe8541a27cad2219e87794
17,313
def log(cm_uuid: UUID): """ :GET: returns the most recent logs for the specified control module. accepts the following url parameters - limit: the number of logs that should be returned - offset: offset the number of logs that should be returned - log_type: the type of log that should be...
fa129b78497f44a4781e5fa2103abbb232294a7a
17,314
def RetrieveResiduesNumbers(ResiduesInfo): """Retrieve residue numbers.""" # Setup residue IDs sorted by residue numbers... ResNumMap = {} for ResName in ResiduesInfo["ResNames"]: for ResNum in ResiduesInfo["ResNum"][ResName]: ResNumMap[ResNum] = ResName ResNumsList = [] ...
e9f522af368a8a058792b26f9cf53b1114e241ef
17,315
def get_data_with_station(station_id): """ *** Returns Pandas DataFrame *** Please Input Station ID: (String)""" print("\nGETTING DATA FOR STATION: ",station_id) ftp = FTP('ftp.ncdc.noaa.gov') ftp.login() ftp.cwd('pub/data/ghcn/daily/all') ftp.retrbinary('RETR '+station_id+'.dly',...
093b6f7d88335e3ef591cedee7c362bf3b1468d6
17,316
def _canonicalize(path): """Makes all paths start at top left, and go clockwise first.""" # convert args to floats path = [[x[0]] + list(map(float, x[1:])) for x in path] # _canonicalize each subpath separately new_substructures = [] for subpath in _separate_substructures(path): leftmos...
3f5aa9a4ac75417935415b5dcc561a1057b465e5
17,317
from typing import Tuple def extract_meta(src: bytes) -> Tuple[int, int]: """ Return a 2-tuple: - the length of the decoded block - the number of bytes that the length header occupied. """ v, n = uvarint(src) if n <= 0 or v > 0xFFFFFFFF: raise CorruptError if v > 0x7FFFFFFF: ...
4bb02fd1c8b9870b450fcbca790fa94870a82cf2
17,318
def metric_source_configuration_table(data_model, metric_key, source_key) -> str: """Return the metric source combination's configuration as Markdown table.""" configurations = data_model["sources"][source_key].get("configuration", {}).values() relevant_configurations = [config for config in configurations ...
718a69df60272b7cdfafdbfeff3136a1aac49707
17,319
import requests import json def search(keyword, limit=20): """ Search is the iTunes podcast directory for the given keywords. Parameter: keyword = A string containing the keyword to search. limit: the maximum results to return, The default is 20 results. ...
922cd7dfaea30e7254c459588d28c33673281dac
17,320
def job_checks(name: str): """ Check if the job has parameters and ask to insert them printing the default value """ p = job_parameters(name) new_param = {} if p: ask = Confirm.ask( f"Job [bold green] {name} [/bold green] has parameters, do you want to insert them?", ...
2f64820ec6b180cc6c626fab0616774d7e9086b2
17,321
import re def post(): """Post new message""" error = None if request.method == 'POST'\ and request.form['message'] != '' and request.form['message'] is not None: user_zid = session['logged_in'] post_message = request.form['message'] post_privacy = request.form['post_pri...
b59c5fb30d4b6ce499d0199fb794be38c5c2dfdf
17,322
def data_context_connectivity_context_connectivity_serviceuuid_end_pointlocal_id_connection_end_pointtopology_uuidnode_uuidnode_edge_point_uuidconnection_end_point_uuid_get(uuid, local_id, topology_uuid, node_uuid, node_edge_point_uuid, connection_end_point_uuid): # noqa: E501 """data_context_connectivity_context_...
24fe9a977542f52d8bc8cc765c63ce32882d9f76
17,323
def softmax(logits): """Take the softmax over a set of logit scores. Args: logits (np.array): a 1D numpy array Returns: a 1D numpy array of probabilities, of the same shape. """ if not isinstance(logits, np.ndarray): logits = np.array(logits) # 1D array logits = logit...
7e1897748172e095ac58ce7111bed73caa4e2cb6
17,324