content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def where_op(condition, x, y): """Return a tensor of elements selected from either :attr:`x` or :attr:`y`, depending on :attr:`condition`. If the element in condition is larger than 0, it will take the `x` element, else it will take the `y` element .. note:: The tensors :attr:`condition`, :at...
c4a34284c8105b8b0319f3e33db9d9ea0d74b0d2
3,626,800
def get_out_dir(key: str) -> str: """ Return the output directory :param key: output product """ return OTD[key]
e510603d93cb72d916c3afab8aeb36756a563326
3,626,801
def jet_fire_api521(Tvessel): """ Incident heat flux of 100 kW/m2 """ alpha = 0.75 e_flame = 0.33 e_surface = 0.75 h = 40 Tflame = 900 + 273.15 Tradiative = 1100 + 273.15 return stefan_boltzmann(alpha, e_flame, e_surface, h, Tflame, Tradiative, Tvessel)
e7d95073f9e899b8f48e5fc6fcd9505e622dea98
3,626,802
def ewma(values, window): """ Numpy-based implementation of EMA """ weights = np.exp(np.linspace(-1., 0., window)) weights /= weights.sum() ema = np.convolve(weights, values)[window-1:-window+1] return ema
a544b9a37bf227dcd12246d5ebd83d4788b217c9
3,626,803
import torch def prepare_loss_weights( labels, pos_cls_weight=1.0, neg_cls_weight=1.0, loss_norm_type=LossNormType.NormByNumPositives, dtype=torch.float32, ): """get cls_weights and reg_weights from labels. """ cared = labels >= 0 # cared: [N, num_anchors] positives = labels > ...
0f3a8bd3d9149c6264aa73f5a4daa0291f56d2e8
3,626,804
from typing import Optional import subprocess def capture_output( command: str, ip: Optional[str] = None, **kwargs ) -> ADBCommandResult: """ Execute an adb command on the given device and return the result :param command: command to execute :param ip: device id :param kwargs: if ...
1f3077177c34a5fc6d1ac96638f34f4f88a51f4e
3,626,805
def add_to_leftmost(branch, val): """adds value to the leftmost part of the branch and returns the modified branch and 0. OR returns unchanged change and val if the val cannot be added""" if val == 0: return branch, val if type(branch) is int: return branch + val, 0 # add to children...
1c2c3bdccfcb6f4966b9bf9228f092ee17ca49f9
3,626,806
def normalize_list_of_dict_into_dict(alist): """ Info is generated as a list of dict objects with a single key. @alist - the list in question. @return - normalized dict with multiple keys """ result = {} for element in alist: for key in element.keys(): ...
8de00b0923d07b99085ca3b4d694960aae9fc7f5
3,626,807
import hashlib def hashhex(s): """Returns a heximal formated SHA1 hash of the input string.""" h = hashlib.sha1() h.update(s) return h.hexdigest()
0d2b0dd9c54b71f3668b971fb81f9d78223acbb2
3,626,808
import os import errno from typing import OrderedDict import sys def prerank(rnk, gene_sets, outdir='gseapy_out', pheno_pos='Pos', pheno_neg='Neg', min_size=15, max_size=500, permutation_n=1000, weighted_score_type=1, ascending=False, figsize=[6.5,6], format='pdf', graph_num=20, seed=None): ...
f9ccadecba9f3c7b656dd5ce72c62051f807f0fd
3,626,809
import argparse def get_args(): """Get our arguments""" parser = argparse.ArgumentParser() parser.add_argument('filename', metavar='F', type=str, nargs=1, help='File to load') parser.add_argument('-a', '--annealing', action='store_true', default=False, ...
33e82867f37b1934f9622076459402beb2cb3214
3,626,810
import os def read_results(folder, name): """ reads in cluster results """ tree_fname = os.path.join(folder, name + '.dg_01') clu_fname = os.path.join(folder, name + '.dg_01.lab') tree = np.loadtxt(tree_fname) clu = np.loadtxt(clu_fname) return clu, tree
462fa9eae6b2616dde237e1fde86033b88c04b37
3,626,811
def planets(id='', name=''): """ Return a planet. Like: Hoth, Naboo, etc. """ response = Render.show(id, name, 'planets') return response
1e1944d58b50cf3fed7efc6fe23b888837689a57
3,626,812
def literal(string): """ If `string` is a valid literal in NTriples syntax, return its value, lang tag and type. Use `None` if there is no language tag or no datatype. If `string` is not a valid literal return `None`. """ match = literal.pattern.match(string) if not match: return Non...
a0d805d7b3365366b85c0ce576f75a69680251be
3,626,813
import logging def make_error_logger(name, level, filename): """ Création d'un Logger d'erreur :param name: nom du logger :param level: niveau de logging :param filename: nom du fichier d'erreur :return: logger """ formatter = logging.Formatter("%(asctime)s %(levelname)s - %(messa...
0d78faa4657af348c06755298c2e1d3f717cd092
3,626,814
def correlate(a, b, shift, demean=True, normalize=True, domain='freq'): """ Cross-correlation of signals a and b with specified maximal shift. :type a: :class:`~numpy.ndarray`, :class:`~obspy.core.trace.Trace` :param a: first signal :type b: :class:`~numpy.ndarray`, :class:`~obspy.core.trace.Trace`...
ff0a4adcde2f62f7de94c31702dd2605ae8f390c
3,626,815
def get_user_idle_time(): """ Return the amount of time (in seconds) that the user is said to be idle. This is normally obtained from a lack of keyboard and/or mouse input. """ if system == 'Windows': return get_user_idle_time_windows() elif system == 'Darwin': return get_user_idle_time_mac() raise NotImplem...
bcdb1a9710721b94f2c6c490a8ac9d453cda412a
3,626,816
from typing import Dict from typing import Any from typing import Iterable from typing import Optional from typing import Tuple def kwargs_from_config( config: Dict[str, Any], required_keys: Iterable[str], optional_keys: Iterable[str], renames: Optional[Iterable[Tuple[str, str]]] = None, ) -> Dict[str...
b3acef60b87dc8bb4c00157c169d1968c8751100
3,626,817
def as_array(a, dtype=DEFAULT_FLOAT_DTYPE): """ Converts given :math:`a` variable to *ndarray* with given type. Parameters ---------- a : object Variable to convert. dtype : object Type to use for conversion. Returns ------- ndarray :math:`a` variable conver...
5efde6e83812dec9ad16283cf13b4d3d07ba5cd8
3,626,818
def round_filters(filters, global_params): """Round number of filters based on depth multiplier.""" multiplier = global_params.width_coefficient divisor = global_params.depth_divisor min_depth = global_params.min_depth if not multiplier: return filters filters *= multiplier min_dept...
057d209906cde8287051ea48cf3d97af76e66cf2
3,626,819
from typing import List def equal_opportunity(confusion_matrix_list: List[np.ndarray], tolerance: float = 0.2, label_index: int = 0) -> np.ndarray: """ Checks for equal opportunity between all of the sub-populations. This function checks if **true positive rate...
f861293ece13ea5dc14c6397fbf99a991bf0f672
3,626,820
def determine_qc_protocol(project): """ Determine the QC protocol for a project Arguments: project (AnalysisProject): project instance Return: String: QC protocol for the project """ # Standard protocols if project.info.paired_end: protocol = "standardPE" else: ...
6862ab84450d4d4d0ca74ee178b90f5eacb303fb
3,626,821
def entitydata_list_url_query(viewname, kwargs, query_params, more_params): """ Helper function for generatinglist URLs """ list_url=reverse(viewname, kwargs=kwargs) return uri_with_params(list_url, query_params, more_params)
5264a2f45befc9662f22a1febc5451d35881c984
3,626,822
def _adaptive_order_weno3_robust(q, i, j, recons, keep_positive, eps=1.0e-17, c1=1.0, c2=...
dc772944d6eb13a02752d995f738b385a01fd7a0
3,626,823
import torch def patch_and_fit_physio(time_series, replicates, patch=3, mask=None, mode='gn', verbose=0): """Extract patches from an fMRI time + replicate series and fit parameters. Parameters ---------- time_series : (replicates, *input_shape) tensor_like fMRI time s...
f22083e42927d0661a315a0825b1b4344be75e53
3,626,824
def verify_file_exists(file_name, file_location): """ Function to verify if a file exists :type file_name: String :param file_name: The name of file to check :type file_location: String :param file_location: The location of the file, derive from the os module :rtype: Boolean :return: r...
8ac4869f3f758d9342f9047a6212851f7f463f35
3,626,825
import math def plot_cdfs(x, y, ccdf=False): """plot cumulative density functions for each column in x, based on the classification specified in y. Parameters ---------- x : DataFrame the experiments to use in the cdfs y : ndaray the categorization for the data ccdf : boo...
3b98d7b3d474a374d17438b5263af53c20b24b83
3,626,826
def make_shell_context(): """Pre-populate the shell environment when running run.py shell.""" return dict(app=keeper_app, db=db, models=models)
9344b3d30f36c0c1a5b10847d93a92c10e58872c
3,626,827
import contextlib def _MaybeClosing(fileobj): """Returns closing context manager, if given fileobj is not None. If the given fileobj is none, return nullcontext. """ return (contextlib.closing if fileobj else NullContext)(fileobj)
05db3f9168d69c94513c95f0da396500319e079e
3,626,828
def get_project_page(pid, cache_directory=settings.CACHE_DIRECTORY): """Get a project page rendered in HTML given a project ID. Args: pid (int): project ID. cache_directory (str): the directory where cached projects are stored. Returns: A string containing the HTML for ...
bff55a1c6e51742cca264199b4ac669fe4b8b855
3,626,829
def is_slot_bound(module, device, slot): """Checks whether a specific slot in a given device is bound to clevis. Return: <boolean> <error>""" _unused, err = get_jwe(module, device, slot) if err: return False, err return True, None
c103ae94ef86bad7eb3c3e33818faf20003e18b4
3,626,830
def to_matplotlib(img): """Returns a view of the image from Bob format to matplotlib format. This function works with images, batches of images, videos, and higher dimensional arrays that contain images. Parameters ---------- img : numpy.ndarray A N dimensional array containing an image...
f769af6d407d16543dc9ec98d8cc35338db47231
3,626,831
def energy_distance(x, y, **kwargs): """ energy_distance(x, y, *, exponent=1) Computes the estimator for the energy distance of the random vectors corresponding to :math:`x` and :math:`y`. Both random vectors must have the same number of components. Parameters ---------- x: array_like ...
a36d4277ed5cd9da049f129a2d8fa2b50a062ed3
3,626,832
import os import os.path as op from glob import glob from warnings import warn def bids_scan_file_walker(dataset=".", include_types=None, warn_no_files=False): """ Traverse a BIDS dataset and provide a generator interface to the imaging files contained within. :author: @chrisfilo https://github....
f3a4f3e1c96073e89fd69ff2768570c1f0667f9f
3,626,833
def train_step(net, optim, batch): """ one training step """ (loss, net), grads = pax.value_and_grad(loss_fn, has_aux=True)(net, batch) net, optim = opax.apply_gradients(net, optim, grads) net = net.replace(rnn=net.gru_pruner(net.rnn)) net = net.replace(o1=net.o1_pruner(net.o1)) net = ne...
3f3e9fa1f8487bafd0e0b70a673ef3af989e3dfc
3,626,834
def insert_dim(arg, pos=-1): """insert 1 fake dimension inside the arg before pos'th dimension""" shape = [i for i in arg.shape] shape.insert(pos, 1) return arg.reshape(shape)
921cd27894df9910dbc12b31db6eb1f73d47f180
3,626,835
def encode_captions(captions): """ Convert all captions' words into indices. Input: - captions: dictionary containing image names and list of corresponding captions Returns: - word_to_idx: dictionary of indices for all words - idx_to_word: list containing all words - vocab_size...
2ba216c844723b0925b46d0db7bc8afd6ce0f5b4
3,626,836
import logging def post_dataset(conn, dataset_name, project_id=None, description=None, across_groups=True): """Create a new dataset. Parameters ---------- conn : ``omero.gateway.BlitzGateway`` object OMERO connection. dataset_name : str Name of the Dataset being c...
cd0e57d8184683c403002de085fa5122c1e3458d
3,626,837
def load_stop_words(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words. """ stop_words = [] for line in open(stop_word_file): if...
8127aeec8db8f7bc87130ea0d1e5faa4998ac86f
3,626,838
def run_gcloud_command(cmd, project_id): """Execute a gcloud command and return the output. Args: cmd (list): a list of strings representing the gcloud command to run project_id (string): append `--project {project_id}` to the command. Most commands should specify the project ID, for those that don't...
324345a3fdf687c3d36711c918060715fedfa79a
3,626,839
def convert_gmx_flow_1_to_2(flow: GmxFlow, width: float) -> GmxFlow: """Convert flow data from 'GMX_FLOW_1' to 'GMX_FLOW_2'. This changes the field 'M' to represent the mass density instead of the total mass in the bin. Thus we also require the width of the system, in order to calculate the bin volume....
d1e005bf8adc73c27e4454730a744fb6b464100b
3,626,840
def NullFlagHandler(feature): """ This handler always returns False """ return False
7d37ecc8518144b27b43580b7273adf5f68dfdfb
3,626,841
def add_image(axes, path): """Add the image given by ``path`` to the plot ``axes``. :param axes: represents an individual plot :param path: path to the image :type axes: matplotlib.pyplot.Axes :type path: str :return: mpimg.AxesImage """ try: img = Image.open(path) retur...
fa574ede75a5f2389380e906090e2d91c92944e9
3,626,842
from datetime import datetime def abandonAffaire_reopenParentAffaire_view(request): """ Abandon child_affaire, reopen parent child_affaire and reattribute numbers to parent child_affaire. """ settings = request.registry.settings etape_abandon_id = settings['affaire_etape_abandon_id'] etape_re...
c2993de78590f708fc4d7e8c0ed08008a21103b6
3,626,843
from typing import Optional import logging import functools def get_dataset( *, batch_size, eval_batch_size, num_shards, dtype_str='float32', # pylint: disable=unused-argument shuffle_seed=0, rng=None, dataset_configs=None, dataset_service_address: Optional[str] = None): # pylint...
621ac7541489a08511e8e0e2ae4474a1591d3132
3,626,844
import copy def find_paths(orbital_graph, starting_node, ending_node, visited_nodes=None): """Recursively find all the paths from starting_node to ending_node in the graph Paths are returned as a list of paths, where paths are a list of nodes. An empty list means that no valid path exists. """ pat...
55a47542c3d70bbc1f5c722c1e87908e10b3d0e5
3,626,845
def rp_from_filename(filename, split_char=ELT_SPLIT, rp_regex=REGEX_RP): """Gets the Rp (proton radius?) label from the file name, returns None if not found. :param filename: the name of the file to parse :param split_char: the character which separates filename elements :param ...
e5cae3428e6a7a30cceab779845b127df52c2ad1
3,626,846
def check_duplication(request): """API check_duplication""" check_type = request.POST.get('check_type') name = request.POST.get('username') if check_type == 'id': min_limit = settings.ID_MIN_LENGTH max_limit = settings.ID_MAX_LENGTH else: min_limit = settings.NICKNAME_MIN_LE...
2ef45506ada6b54cc86b1734a0301e6e48bb5ca6
3,626,847
def _merge_numeric_stats( left, right, feature_name): """Merge two partial numeric statistics and return the merged statistics.""" # Check if the types from the two partial statistics are not compatible. # If so, raise an error. if (left.type is not None and right.type is not None and left.type !=...
1eb4ea5a425ea70ae4e02da267d2553a8440376b
3,626,848
import logging def get_pod_names(client, namespace, name): """Get pod names from k8s. """ core_api = k8s_client.CoreV1Api(client) resp = core_api.list_namespaced_pod( namespace, label_selector=to_selector({TF_JOB_NAME_LABEL: name})) logging.info("list_namespaced_pod: %s", str(resp)) pod_names = [] f...
6228ed3a596093260c0b17a95201068b2d70c1d6
3,626,849
def calculate_drawdown(input_series: pd.Series, is_returns: bool = False) -> pd.Series: """Calculate the drawdown (MDD) of historical series. Note that the calculation is done on cumulative returns (or prices). The definition of drawdown is DD = (current value - rolling maximum) / rolling maximum ...
95e128f00f3667e5a22bd114074525feb6063e1c
3,626,850
def search_traversal(**kwargs): """Search Traversal in Database""" db_inst = app.config['ARANGO_CONN'] db_inst.get_database() graph = db_inst.get_graph(kwargs.get('graph_name')) try: traversal_results = graph.traverse( start_vertex=kwargs.get('start_vertex'), directi...
971751adb1970a0bead9e632e00181a4bc3914a9
3,626,851
def find_matching_nodes(search_for, search_in, matches=[]): """ Search Vertex tree 'search_in' for the first isomorphic occurance of the Vertex tree search_for Return a list of [(x,y)...] for node in search_for (x) matched with a pair (y) from search in, such as the two graphs preserve their ...
9e6696533f7b5e313075fadade8b42fe6f09f0cf
3,626,852
def getStrategicManagementBodies(project): """Returns the strategic management bodies for a given project.""" return getManagementBodies(project, MANAGEMENT_BODY_CATEGORY_STRATEGIC)
526c60342f348f327436f4e1bdcb5c90c7820cbe
3,626,853
def clip(x, min_value, max_value): """Element-wise value clipping.""" if max_value is not None and max_value < min_value: max_value = min_value if max_value is None: max_value = np.inf min_value = _to_tensor(min_value, x.dtype.base_dtype) max_value = _to_tensor(max_value, x.dtype.bas...
58ba70a6212b2ab3b37f37aa8a4611bab262be81
3,626,854
import cmd import subprocess def dotnet_restore(path=""): """Restore the dotnet solution from the root of the project via dotnet restore """ if path: cmd.append(path) info("Restoring nuget packages (via %s" % " ".join(cmd)) result = subprocess.run(cmd) status = result.returncode if ...
7cf78f998c1d9c2bb79a1e28c984fc20f6a8ac28
3,626,855
def SendMessage(service, user_id, message): """Send an email message. Args: service: Authorized Gmail API service instance. user_id: User's email address. The special value "me" can be used to indicate the authenticated user. message: Message to be sent. Returns: Se...
9c8c9985fe80b22a94678c354774ebe0453fe860
3,626,856
def getPolicy(lunaToken, policyName, network, account_key=''): """ Gets a specific policy on a given network in JSON format """ session.headers.update({'Luna-Token': lunaToken}) if network == 'staging': get_policy_endpoint = "/imaging/v2/network/staging/policies/" + policyName else: get...
52a9c7496813b55e74c19a084a367a5f242a379a
3,626,857
import re def clean_str(string): # Remove punctuation """ Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = re.sub(r"[^\u4e00-\u9fff]", " ", string) string = re.sub(r"\s{2,}", "...
025a17cfc81217b6115f049694ff205c5a5e93ab
3,626,858
from typing import List from typing import Tuple def extract_ops(page: PageObject) -> List[Tuple]: """extract all operators""" content = page.getContents() if not isinstance(content, ContentStream): content = ContentStream(content, page.pdf) return list(content.operations)
402ec35f7de36dce93ae56b13d535ea8cebc1916
3,626,859
import requests def get_project_info(project_name, dnac_jwt_token): """ This function will retrieve all templates associated with the project with the name {project_name} :param project_name: project name :param dnac_jwt_token: DNA C token :return: list of all templates, including names and ids ...
61ff47100853175c76ecf05117d7016842a6745d
3,626,860
import google import os def main(args): """This functions annotates a PDF document using the Document AI API""" if not args.project_id: _, project_id = google.auth.default() args.project_id = project_id parent = f"projects/{args.project_id}/locations/{args.multi_region_location}" clien...
34c6937f59758519bcb7b22e6dd59ff912e49116
3,626,861
import textwrap import six def generate(tag_cls): """ generate generates documentation for given wrapper tag class :param tag_cls: wrapper_tag class :return: """ doc = textwrap.dedent(tag_cls.__doc__ or '').strip() arguments_doc = "" for ag, arguments in six.iteritems(ArgumentsGroup...
3b2fb93caa37552f4b4eaff1fc4a1c1d1d1412dd
3,626,862
def load_data(database_filepath): """Load data from SQLite into memory. """ engine = create_engine(f'sqlite:///{database_filepath}') df = pd.read_sql_table("Messages", engine) X = df["message"] Y = df.drop(["message", "id", "original", "genre"], axis=1) return X, Y, Y.columns
e8e338d7c08113cd11f1e1efcb16f4687de354c7
3,626,863
def column_thresh(C, eps): """ cleans out C, removes all values below eps. otherwise """ n1 = C.shape[1] for i in range(n1): if la.norm(C[:,i], 2) < eps: # norm here defaults to 2 norm for vector C[:,i]=0 else: C[:,i]=C[:,i]-eps*C[:,i]/la.norm(C[:,i],2) ...
ba53b3a728ff363a684c0974676430c3850d2c43
3,626,864
def distance_between_points(p1, p2): """ Function that computes the euclidean distance between to points. Returns: float: distance value """ return ((p1['x']-p2['x']) * (p1['x'] - p2['x']) + (p1['y']-p2['y']) * (p1['y']-p2['y'])) ** 0.5
b8cb563f13f64f0511525e5428d47d9228220915
3,626,865
def sigmoid(z): """ Compute the sigmoid of z Arguments: z -- A scalar or numpy array of any size. Return: s -- sigmoid(z) """ #(≈ 1 line of code) # s = ... # YOUR CODE STARTS HERE s = 1/(1+np.exp(-z)) # YOUR CODE ENDS HERE return s
868599c3550a0e575d9a39632e0990f3dfc2f782
3,626,866
from typing import Tuple from typing import Dict import copy def _decompose_expressions(circ: Circuit) -> Tuple[Circuit, bool]: """Rewrite a circuit command-wise, decomposing ClassicalExpBox.""" bit_heap = BitHeap() reg_heap = RegHeap() # add already used heap variables to heaps for b in circ.bits...
8dad1b0e438930541e0604a48114b8d5628db97d
3,626,867
def get_trailing_app_metrics(args): """ Returns trailing app_name metrics for a given time period. Args: args: dict The parsed args from the request args.limit: number The max number of apps to return args.time_range: one of "week", "month", "all_time" Returns: [{ name: ...
e0b6f89a83af7250baa16926fcf644ca7b5b0e51
3,626,868
def get_all_related_objects(opts): """ Django 1.8 changed meta api, see https://docs.djangoproject.com/en/1.8/ref/models/meta/#migrating-old-meta-api https://code.djangoproject.com/ticket/12663 https://github.com/django/django/pull/3848 :param opts: Options instance :return: list of relatio...
bc3cc8ec4b83a26ff5c409eb840733ca7bdfaaea
3,626,869
import fastapi async def fetch_dialog( customer_id: str, dialog_id: str, db: motor_asyncio.AsyncIOMotorClient = fastapi.Depends(mongodb.get_database), ) -> utils.OrjsonResponse: """ Fetch a dialog. - **customer_id**: customer id of the dialog to return - **dialog_id**: dialog id of the di...
4fd8f66df8375b5620c400c88446206e5acf337b
3,626,870
def _get(pseudodict, key, single=True): """Helper method for getting values from "multi-dict"s""" matches = [item[1] for item in pseudodict if item[0] == key] if single: return matches[0] else: return matches
f68156535d897dd719b05d675e66cadc284ce1a3
3,626,871
from typing import Counter def guess_domain(tree, blacklist=_DOMAIN_BLACKLIST, get_domain=get_domain): """ Return most common domain not in a black list. """ domains = [get_domain(href) for href in tree.xpath('//*/@href')] domains = [d for d in domains if d and d not in blacklist] if not domains: ...
0d0c0ab8876092e8e06783cd9b4adaf50d9996cf
3,626,872
from xmodule.modulestore.django import modulestore from openedx.core.djangoapps.content.block_structure.models import BlockStructureModel from openedx.core.djangoapps.content.block_structure.exceptions import BlockStructureNotFound def get_course_last_published(course_key): """ We use the CourseStructure tabl...
c7a8e503553790ed05ca84a8bfa7ac6decf3bc0d
3,626,873
def rgb_to_hex(rgb_triplet): """ Convert a 3-tuple of integers, suitable for use in an ``rgb()`` color triplet, to a normalized hexadecimal value for that color. Examples: >>> rgb_to_hex((255, 255, 255)) '#ffffff' >>> rgb_to_hex((0, 0, 128)) '#000080' """ return '#%02x%02x%02x...
53a21a387e19c8cf989cec868f8862bfcb2dbaed
3,626,874
def dec2stringTime(decim, precision=5): """ Convert a decimale time or coordinate to a formatted string. Parameters ---------- decim : int, float precision : int Returns ------- String formatted HH:MM:SS.SSSSS """ return hms2stringTime(*dec2sex(decim), precision=precision)
d7ea8334f021dc302c1291556bd5d6a8bb921b46
3,626,875
def getCartShape(dimension, communicator=None): """ Returns :samp:`getCartShapeForSize(dimension, communicator.Get_size())`. :type dimension: int :param dimension: Spatial dimension for returned cartesian layout. :type communicator: :obj:`mpi4py.MPI.Comm` :param communicator: If :samp:`None...
fe26d0bef1f7e244b1bcbf78cc7754b04790f121
3,626,876
def gumbel_log_survival(x): """Returns log P(g > x) for a standard Gumbel g. log P(g > x) = log(1 - P(g < x)) = log(1 - exp(-exp(-x))). The implementation is more numerically robust than a naive implementation of that formula. Args: x: The cutoff Gumbel value. """ # Adapted from # https://gist.githu...
416069914e011f82db4d47dd667c95b8f2539a2d
3,626,877
import platform def platform_is(requested_platform: str) -> bool: """ Compare requested platform with current platform. Common platforms: - Win / Windows - Mac / macOS / Darwin - Linux - Unix (Mac, SunOS, BSD unix's) - *nix / posix (Not Windows) :return: True if current platform m...
8e9ca64fc9053369da100da46083685cb6dcd47a
3,626,878
def prepare_bert(content, max_len, bow_vocab_size=1000, vectorizer=None, ctx=mx.cpu()): """ Utility function to take text content (e.g. list of document strings), a maximum sequence length and vocabulary size, returning a data_train object that can be used by a SeqBowEstimator object for the call to fit...
76f6ebc3d874668507e8e7b9326a82dbd1b01997
3,626,879
import Qconfig import functools import unittest import os def requires_qe_access(func): """ Decorator that signals that the test uses the online API: * determines if the test should be skipped by checking environment variables. * if the test is not skipped, it reads `QE_TOKEN` and ...
8c29a089ef2098fe8e22c572b5d6f53fd16c702c
3,626,880
def to_homogeneous(t, is_point): """Makes a homogeneous space tensor given a tensor with ultimate coordinates. Args: t: Tensor with shape [..., K], where t is a tensor of points in K-dimensional space. is_point: Boolean. True for points, false for directions Returns: Tensor with shape [..., K+...
484668c34b6c61e7e2479ea44c7beb4a0111676b
3,626,881
import zipfile def name_from_archive(archive_path): """ Name From Archive """ archive = zipfile.ZipFile(archive_path, allowZip64=True) xml_data = archive.read("manifest.xml") elem = etree.fromstring(xml_data) return elem.get("uuid")
34c4e89cb75d86cd0d703a79ac0ed70b223a91c0
3,626,882
import glob def datedfile(filename,date): """ select file based on observation date and latest version Parameters ---------- filename: text file name pattern, including "yyyymmdd_vnn" place holder for date and version date: yyyymmdd of observation Returns: file name """ filelist = ...
203cf848e351ef9b8b77bda62d5850b35485762a
3,626,883
import random import string def random_user(n): """generate a random user id of size n""" chars = [] for i in range(n): chars.append(random.choice(string.ascii_lowercase)) return ''.join(chars)
21d8ec2ef8b275ffca481e4553ec396ff4010653
3,626,884
def playerStandings(): """Returns a list of the players and their win records, sorted by wins. The first entry in the list should be the player in first place, or a player tied for first place if there is currently a tie. Returns: A list of tuples, each of which contains (id, name, wins, matches...
7b8d50b1b4dbc592e2792f248df6f848c9c3aac6
3,626,885
import logging def load_statistics( input_path: Text) -> statistics_pb2.DatasetFeatureStatisticsList: """Loads data statistics proto from file. Args: input_path: Data statistics file path. The file should be a one-record TFRecord file or a plain file containing the statistics proto in Proto T...
a86b6cfd25b6e77db78419afad41aa6b7e456b7e
3,626,886
from typing import Counter def get_counter(request): """ Get the Counter object associated with a request. Raise AjaxError if session is invalid or counter is not found. """ if "counter" not in request.session: raise AjaxError(RET_UNAUTHORIZED, _(u"Not logged in.")) counter_id = requ...
6d676880fccb47b05c1936e26c8be819136ad399
3,626,887
def _get_parse_input(parse_args, args_in, dict_in): """Return default for parse_input. This is to decide if context_parser should run or not. To make it easy on an API consumer, default behavior is ALWAYS to run parser UNLESS dict_in initializes context and there is no args_in. If dict_in specifi...
64dcfd32a3d9f66749a27d4b26bd5fb3a66edf28
3,626,888
from typing import Dict from typing import List import logging import re def get_haiku( text: str, inflect_p, pronounce_dict: Dict, syllable_dict: Dict, emoticons_list: List, guess_syl_method: str, ) -> str: """Attempt to turn a string into a haiku. Returns haiku if able, otherwise ret...
0405dc44095945b7414940c61a5d15238661514b
3,626,889
import argparse def get_parser(): """ Creates and returns the argument parser for jExam Returns: ``argparse.ArgumentParser``: the argument parser for jExam """ parser = argparse.ArgumentParser() parser.add_argument("master", type=str, help="Path to exam master notebook") parse...
03e433f3b3cdb371dff74489f619f0e65311f5dd
3,626,890
def is_average_pooling(layer): """Checks if layer is an average-pooling layer.""" AVERAGEPOOLING_LAYERS = ( keras_layers.AveragePooling1D, keras_layers.AveragePooling2D, keras_layers.AveragePooling3D, keras_layers.GlobalAveragePooling1D, keras_layers.GlobalAveragePooling2...
7a0d91d291b13006341a86bf3864b612bad247c2
3,626,891
import os def find_source_filename(source_name, dir_path): """Find the filename matching the source/module name in the specified path. For example searching for "queue" might return "queue.py" or "queue.pyc" """ source_filenames = [ os.path.join(dir_path, source_name + ext) for ...
0360e57d4071c389d28768946551ad041236e6e3
3,626,892
def MergeDictsRecursively(original_dict, merging_dict): """ Merges two dictionaries by iterating over both of their keys and returning the merge of each dict contained within both dictionaries. The outer dict is also merged. ATTENTION: The :param(merging_dict) is modified in the process! :para...
43174a7f5163a36eb850bc2c4d0f557790920189
3,626,893
def eq_assoc(u, v, eq=core.eq, n=None): """ Goal for associative equality >>> from logpy import run, var, fact >>> from logpy.assoccomm import eq_assoc as eq >>> fact(commutative, 'add') # declare that 'add' is commutative >>> fact(associative, 'add') # declare that 'add' is associative ...
b7ba81dbd73091dc6a2e01ec5136c80cf3c49c88
3,626,894
import six def printer(func=None, **options): """ Decorator used to print whatever text is returned in the caller function. When a list or a tuple are returned, then the contents are iterated and printed. Options: dedent - whether or not to dedent the text (default: ...
632cfb59fbc213b3c8f69f05d6f8ff686207a6e3
3,626,895
import logging import sys import time def stdoutlogger(name, level=logging.INFO): """ Return a standard python logger with a stdout handler attached and using a prefix format that will make logging consistent between scripts. """ logger = logging.getLogger(name) logger.setLevel(level) ...
865f00a0baebf5032b1820893b0a062ff61ac501
3,626,896
import argparse def parse_args(): """ Parse command line arguments for CLI :return: namespace containing the arguments passed. """ parser = argparse.ArgumentParser() parser.add_argument( '--login', type=str, required=True, help="Full path to file containing JSO...
0982407f808c9af9996bae0a36e8ae252cae0df6
3,626,897
from StringIO import StringIO from io import StringIO def strio(): """ This was difficult to get right in doctests when porting to Python 3. """ try: except ImportError: return StringIO()
9900b0a15da617278e3a5a1de8ef45a417e4e813
3,626,898
def getJamLengthMeters(detID): """getJamLengthMeters(string) -> double Returns the jam length in meters within the last simulation step. """ return _getUniversal(tc.JAM_LENGTH_METERS, detID)
750d7579ffded917e18faa5ec2f991576606aaf8
3,626,899