content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import yaml def setup_config( config_directories=None, config_file=None, default_filename="icap-server-opentc.yml" ): """Setup configuration """ config_found = False config_file_path = None if config_file: config_file_path = config_file if os.path...
135f197e762bdfb0162df8188af7c1dbbe2b73eb
3,619,000
def get_matcher(obj): """Return an object suitable for comparing against other objects using the "==" operator. If special comparison handling is implemented, a MatcherObject or MatcherTuple will be returned. If the object is already suitable for this purpose, the original object will be returned u...
c0ac74d0ec43c974c17080a35eaeaeaefffaeb07
3,619,001
def _ns(tag, namespace=NAMESPACES['phy']): """Format an XML tag with the given namespace (PRIVATE).""" return '{%s}%s' % (namespace, tag)
2724c1af73b78b4cb8e8fb27205c8d0a257a79f1
3,619,002
import functools import attr def Compose(X, Y): """Compose two type constructors X and Y into a single type constructor Kind: .. code-block:: Compose :: (* -> *) -> (* -> *) -> * -> * That is, it takes two type constructors and one concrete type to create a concrete type. Another way t...
bc530c0b591260782732827481411cde6719ff40
3,619,003
from typing import Union def get(key: str, locale: str = config.get('locale')) -> Union[dict, list, str]: """Get the translation corresponding to that key and language""" return container[locale][key]
66699e3c4016775ad4712da86398a6324d775da3
3,619,004
import dateutil.parser def get_entry_end_date(e): """Returns end date for entry""" return dateutil.parser.parse(e['time_end'])
a9b8bdae873de0ef97de49e342cd4f3bbd8117f6
3,619,005
def remove_stripe_based_sorting(sinogram, size, dim=1): """ Algorithm 3 in the paper. Remove stripes using the sorting technique. Work particularly well for removing partial stripes. Angular direction is along the axis 0. Parameters ---------- sinogram : float 2D array size : in...
e47a8ea1c4b62262301f6066814af892b3a03626
3,619,006
def index(request): """Chat index page.""" return HttpResponse("Testing")
d3d2db1e11e443ad32119431a6cc9b201a051b1d
3,619,007
from typing import Dict def compress_counts( counts: Dict[StateTuple, float], tol: float = 1e-6, round_to_int: bool = False ) -> CountsDict: """Filter counts to remove states that have a count value (which can be a floating-point number) below a tolerance, and optionally round to an integer. :par...
fd9d8865ba864ed8155ef9317d01ab0636a491bc
3,619,008
import torch from typing import Optional def allreduce_nonblocking(tensor: torch.Tensor, average: bool = True, is_hierarchical_local=False, name: Optional[str] = None) -> int: """ A function that performs nonblocking averaging or summation of the input tensor over all the Bluefog...
9d87df05da876d8567105309532c1e33f1c3a4e4
3,619,009
def _streaming_false_negatives(predictions, labels, weights=None, metrics_collections=None, updates_collections=None, name=None): """Computes the total number of false positives. If `weights` is `None`, weights default to ...
d582f4f6169de573a8989eebe5c7619ac476eec9
3,619,010
import os def get_file_path(instance, file): """ Get the file path where will be stored in :param instance: database object of this db record :param file: file object. :return: path of file system which will store the file. """ file_ext = file.split(".")[-1] filename = "%s.%s" % (hash_...
49a06cc174a03d969980c4e355be3fd7081a102d
3,619,011
def getOneFilter(psi, count, scale, mode): """ Methdod used to visualize one filter parameters: psi -- dictionnary that contains all the wavelet filters count -- key to identify one wavelet filter in the psi dictionnary scale -- scattering scale mode -- mode between fouri...
dc833c40fb64fddf4172ecb485ace1de4d44d221
3,619,012
from pathlib import Path def get_launch_agents_dir() -> Path: """Returns user LaunchAgents directory.""" launch_agents_dir = Path.home() / "Library" / "LaunchAgents" assert launch_agents_dir.is_dir() return launch_agents_dir
d11bc00c986bd5440549e71fdae9ed1f98f18d21
3,619,013
def sample_categorical_crossentropy(y_true, y_pred, class_weights=None, axis=None, from_logits=False): """Categorical crossentropy between an output tensor and a target ten...
b5d430494b46b9e84fb429f260f6b759361fe858
3,619,014
from typing import Callable def ope(actual_series: TimeSeries, pred_series: TimeSeries, intersect: bool = True, reduction: Callable[[np.ndarray], float] = np.mean) -> float: """ Overall Percentage Error (OPE). Given a time series of actual values :math:`y_t` and a time series of predi...
2b99e9e3cd9d44519be22c901909effc9468d50b
3,619,015
def build_constraint_matrix(cons, d): """ Build constraint matrix. The constraint matrix is a matrix P that is the vertical stack of all the preserved marginals. Parameters ---------- cons : iter of iter List of variable indices to preserve. d : dit.Distribution Distrib...
53d5d015ecbad46381c6337bf2d87a608a949153
3,619,016
import random def randomStrategy(G, k, l, randomSeed=None): """ title:: randomStrategy description:: Generate random initial strategy. See compare_heuristic_script.py for example use. attributes:: G Graph object (networkx) k Number of ...
2479224d5f67fe02bb8f4740b74c99c3ad89c936
3,619,017
def eddy_loss(i, t=0.31*1e-6, w=4.29*1e-6, f=50, I_c=115): """ :param t: thickness of the conductor :param w: width of the conductor :param f: Hz :param Ic: A :return: """ return 4*mu_0**2./pi*t*w*f**2/C_RHO*I_c**2
6aadaa2189fb467c0c23b550a0930a3fbdc73021
3,619,018
import random def get_hashtag() -> str: """ Create string with special and random hashtags """ hash_tags = "" for item in SPECIALHASHTAGS: hash_tags += " " + item hash_tags += " " + random.choice(HASHTAGS) return hash_tags
5c25a021701bc8307be805d2872bbc9e581b9277
3,619,019
def count_pos_BAM(rw, path_bam_tumoral, path_bam_normal): """ Adds read counts of dinucleotide positions calling another function that runs samtools :param rw: row with the variant info :param path_bam_tumoral: path to the tumoral BAM :param path_bam_normal: path to the normal BAM :return: row ...
a732124c796528445b149d58c50f32dba37612ff
3,619,020
import pandas def find_centers_of_ordered_list(ls): """ to find label positions for plotting. ls must be ordered! """ uniqs = pandas.unique(ls) positions = [] for u in uniqs: idxs = [] # list of indices of corresponding values for index, elements in enumerate(ls): ...
4ecfceeddb1017bbd88ac79531b1c099b76d557d
3,619,021
import aiohttp async def get_url(bot, urls, headers={}, read_response=True, get_bytes=False): """Uses aiohttp to asynchronously get a url response, or multiple.""" async def fetch(url, read_method='text'): if not url: # Why return (None, None) async with session.get(str(url)) as ...
70e2a5c67623db0f4b53d1acac6e11da7cd797d4
3,619,022
def translate_fun_Number(x): """Converts Number(string) to __extrafunc_Number(string) Args: x (str): JavaScript code to translate. Returns: str: Translated JavaScript code. Examples: >>> from ee_extra import translate_fun_parseFloat >>> translate_fun_parseFloat(x =...
e1354411067e583dc948c95b8d0318083e943ba8
3,619,023
def pad_2d_array(arr, n_column, value=-1): """Pad 2D array with columns composed of -1. Argument: arr: A 2D array denoting the stimulus set. n_column: The total number of columns that the array should have. value (optional): The value to use to pad the array. Returns: ...
61dd20797c9e9c678d2dc425707b79d974bffaac
3,619,024
import argparse def mtsdecomp_parser(): """Command-line interface to decompress a file.""" parser = argparse.ArgumentParser(description='Decompress a raw binary file.') parser.add_argument( 'cdata', type=str, help='path to the input compressed binary file (.cbin)') parser.add_argumen...
4208285ca8d1dd8016183c1cd8c7f474ea21870a
3,619,025
def yddot_d_z(mu, state, r_15_inv, r_25_inv): """ Partial of x acceleration with respect to z Args: mu (float): three body constant state (np.array): 6 dimensional state vector of (x, y, z, dx, dy, dz) r_15_inv (float): 1 / norm(r_1)^(5) where r_1 is the vector from the ...
18281dc5dffdef99e38c33e28cc26a0e9d9aa262
3,619,026
def decypher(text): """ Decypher file name into descriptive label for legend """ # name shortcuts help_dict = {"h": "Target/Hunt AI", "p": "Probabilistic AI", "r": "Random AI"} final = "" t_split = text.split("-") final += help_dict[t_split[0]] # hunt/target AI branch if t_spli...
bf4db039bcc86d8d874a29dbf301cc91fa461560
3,619,027
from typing import OrderedDict def get_chattering_species(atom_followed="C"): """ return chattering species the chatteing reaction infomation is just for reference, will not use it as long as the paired chattering species is provided, should be fine better make them in the same order """ f...
334b92ac2db17047c8c934b13961615aafda3621
3,619,028
def processHostname(hostname): """ Check if the received hostname is a bot, based on our list """ if regexp_hostname.search(hostname.lower()): return True return False
1b2026098731db9c9fd9a0b493d1fa883beef6c8
3,619,029
from typing import List def format_beneficial_tags( all_sorted_selection: List[MetadataPrioritySet] ) -> List[str]: """Formats the operators so that only combinations of tags that have 'beneficial' results (ie. operators with only rarity 4, 5, 6) are formatted into the returned list of messages.""...
2c41d9e719eff7565b0d4e865075bae42d7aeb88
3,619,030
def guided_wavelength(freq, line_width, line_gap, substrate_thickness, film_thickness, dielectric_constant=11.45): """A simple calculator to determine the guided wavelength of a planar CPW transmission ...
dc4e62dc9cd19ed07fb09273f4ddd58078a13712
3,619,031
from typing import Optional def get_build_hash(fallback: Optional[str] = None) -> str: """Get build hash""" build_hash = environ.get(ENV_GIT_HASH_KEY, fallback if fallback else "") if build_hash == "" and fallback: return fallback return build_hash
4888b0a43639c88a43321d0ae61e35bea328348a
3,619,032
from typing import Optional def segment_mean(data: jnp.ndarray, segment_ids: jnp.ndarray, num_segments: Optional[int] = None, indices_are_sorted: bool = False, unique_indices: bool = False): """Returns mean for each segment. Args: data: the ...
de146b43a335915eb8041b1cbab7cce538d9efe6
3,619,033
import re def compute_rq_type(oslevel, empty_list): """Compute rq_type. return: Latest when oslevel is blank or latest (not case sensitive) Latest when oslevel is a TL (6 digits) and target list is empty TL when oslevel is xxxx-xx(-00-0000) SP when oslevel is xxxx-xx-x...
753e54d4858a8d1248958c15bbd6b1a0cbc9b02e
3,619,034
def custom_repr(repr_text): """Function decorator to allow setting a custom repr for a class method. References: https://stackoverflow.com/a/32215277 """ # the decorator itself def method_decorator(method): # Wrap the method in our own descriptor. class CustomReprDescripto...
95f4a0cd4077571919be5933b6c205df539a61bd
3,619,035
import json def translate(request, locale, slug, part=None, template='translate.html'): """Translate view.""" log.debug("Translate view.") invalid_locale = invalid_project = False # Validate locale try: l = Locale.objects.get(code__iexact=locale) except Locale.DoesNotExist: i...
eb5d8225dd8bdd1438dec86a8e1a9f8c4a2c01c9
3,619,036
def color_map_cyclic(color_normalized: float) -> (float, float, float): """ Maps normalized value to color, cyclic. Note: For JIT to work, this must be declared at the top level. @param color_normalized: Normalized color value @return: R, G, B """ hue = (color_normalized + 1 / 6) % 1 x...
9be1c9b8b4f7e9dccf16fed54525ca8932bd7ee9
3,619,037
import socket def check_connection(server="lbry.io", port=80, timeout=2): """Attempts to open a socket to server:port and returns True if successful.""" log.debug('Checking connection to %s:%s', server, port) try: server = socket.gethostbyname(server) socket.create_connection((server, port...
9a3c359fc9241a77af40ba3a46b141f751b602ac
3,619,038
def get_model_names(): """ Returns all available model names as a list of strings. """ model_names = [] for key, value in default_models.items(): model_names.append(key) return model_names
af9b0a9c43e43b6a692bf6153ea6c2be940398cb
3,619,039
def cli(): """ Manually check whether names are available on PyPI. Runs an infinite loop in the command line, where a name can be input and the avilability status of that name on PyPI is printed. Notes ----- Please note that the input name is presently un """ while (True): # UI Lo...
b9a7828dfe020f45161e64b481a6865db32bbf82
3,619,040
def itransduce(xform, rf, init, coll=_Undefined): """ itransduce(xform, rf, init, coll) -> reduction result *itransduce(xform, rf, coll) -> reduction result* Returns the result of reducing an iterable with a transformation. Reduces `coll` using a transformed reducing function equal to ``xform(...
3fc0f34aacbc597e65e5e10f60b64d4699f6f1fe
3,619,041
def lseek_syscall(fd, offset, whence): """ http://linux.die.net/man/2/lseek """ # check the fd if fd not in filedescriptortable: raise SyscallError("lseek_syscall","EBADF","Invalid file descriptor.") # if we are any of the odd handles(stderr, sockets), we cant seek, so just report we are at 0 if ...
e5f595dd4a6578288a1a6723d51248d4fc9cd988
3,619,042
from typing import Sequence from typing import Tuple def convert_to_embedded( compressed_messages: Sequence[ndarray], message_shape: Sequence[int], tail_capacity: int, ) -> Tuple[ndarray, ndarray]: """ Embed a truncated list of byte arrays into equal-size arrays. Args: compressed_mess...
7f93b62909f6629bf1a144ea175ec22166c1bffd
3,619,043
def lambda_handler(event, context): """ Manages Let's Encrypt certificates in ACM. """ cert = find_latest_cert() if not cert or get_days_remaining(cert) <= 30: cert_data = provision_cert() cert = import_cert(cert_data) return { 'Certificate': cert.Certificate, ...
38173baf7f3bf55d60e6c0d9e5d7fff8cecd0278
3,619,044
def get_full_contentsection_list(course, filter_children=True): """Return a list of ContentSections with material and a list of all material for this course.""" level2_items = {} # level2_items gets filled lazily groups_with_children = set([]) # ContentGroups that h...
1f131dbfee7c54ba20c59fbbf010d1855d05f361
3,619,045
def vaecf(users_number: int, items_number: int): """ :param users_number: :param items_number: :return: """ input_layer = tf.keras.layers.Input(shape=(items_number,), name='UserScore') enc = tf.keras.layers.Dense(512, activation='selu', name='EncLayer1')(input_layer) lat_space = tf.ke...
ebf00562f55be1df785dfea71d3dfb5150338447
3,619,046
def mode(series): """Computes the mode.""" if series.isnull().all(): return np.nan return series.mode()[0]
01deea60914eadae08e90b2b1bc89533bf665843
3,619,047
def lbeta(x, y, name=None): """Returns log(Beta(x, y)). This is semantically equal to lgamma(x) + lgamma(y) - lgamma(x + y) but the method is more accurate for arguments above 8. The reason for accuracy loss in the naive computation is catastrophic cancellation between the lgammas. This method avoids t...
89e311e48f8a5ce89a57daf877c478a0d4dc9a74
3,619,048
def _xor_guess_key_size(ct, top_results=5, max_key_size=64): """Returns a list of the most likely key sizes for a ciphertext xored with a repeating key. """ distances = [] for ksize in range(2, max_key_size+1): chunks = chunked(ct, ksize) hammings = [hamming_bin(chunks[i], chunks[i+...
75957c55fedd0747e27f400001f12464bfe60f3a
3,619,049
def filter_even_devices(nr): """ Filter the hosts inventory, using a filter function to find devices which match what is considered an even number host. :param nr: An initialised Nornir inventory, used for processing. :return target_hosts: The targeted nornir hosts after being processed throug...
b3f1d9aaa670cb12b7d0b11ee976a9ef0305e879
3,619,050
import re def convert_input_paths(argo_json): """ argo aggregation is not valid json as properties are not enclosed in quotes: flow/step/[{task-id:flow-step-3119439657},{task-id:flow-step-195521861},{task-id:flow-step-3020891073}] Parameters ---------- argo_json Returns ------- l...
2a1e5ddd378546343d5532f304145cb2157244b5
3,619,051
def _constant_i32(value: int): """Emits a constant i32 value.""" return d.ConstantOp( d.IntegerType.get_explicit(32), ir.IntegerAttr.get(ir.IntegerType.get_signless(32), value)).result
1461327750d5d22c13cc2034701f5f14e8e4d2b5
3,619,052
def replace_var(content, variables_mapping): """将 url 中带有参数的变量替换为真实的值 :param content: url 地址,如 https://mubu.com/list?code=$code :param variables_mapping: 要替换的真实的值 :return: """ matched = variable_regex_compile.match(content) if not matched: return content var_name_code = matched[1...
a32893f81d1d0d726f2ef5316c91881cd370bf3c
3,619,053
def get_ur(df): """ Method of getting user-rating pairs Parameters ---------- df : pd.DataFrame, rating dataframe Returns ------- ur : dict, dictionary stored user-items interactions """ ur = defaultdict(set) for _, row in df.iterrows(): ur[int(row['user'])].add(int(...
5a7ff213dc813f56660195100962f3536211b9be
3,619,054
def field_popularity(data): """ Computes the number of different fields that each paper is about by taking the number of fields in 'fields_of_study' Input: - df['fields_of_study']: dataframe (dataset); 'fields_of_study' column [pandas dataframe] Output: - Field varie...
9fdefa880d2bc39c6f18d68cec2a85685a7cb164
3,619,055
def pubmed_local10k(): """Hparams for Meena local attention model.""" hparams = sparse_transformer_local() hparams.max_length = 10240 hparams.batch_size = 10240 hparams.max_target_length = 512 hparams.hidden_size = 256 hparams.embedding_dims = 256 hparams.num_encoder_layers = 4 hparams.num_decoder_lay...
6a8ca09d46d5932d0740fe4ab3a090aa29909590
3,619,056
from typing import Mapping def update_dict(d, u): """Return updated dict. http://stackoverflow.com/a/3233356 :param d: dict :type d: dict :param u: updated dict. :type u: dict :rtype: dict """ for k, v in u.items(): if isinstance(v, Mapping): r = update_dict(...
5c855e4d66afee04887fccea2ee8154cd8e40ea5
3,619,057
import random from datetime import datetime def individual_run(individual: Network) -> Network: """ An individual run """ random.seed(datetime.now()) mario = SuperMario() player = Joypad(JoypadSpace(mario, MOVEMENT)) while mario.ram[0x0009] < INITIAL_THRESHOLD: player.press((Butto...
15d1e4cd6aa2b07674ffb25a03ca43f97bad84c7
3,619,058
import numpy import pandas def parseBamReadcountIndel(row): """Parsing indels only""" # first split ref data ref_split = row[row['REF']].split(':') ref_split = ref_split[:1] + [float(x) for x in ref_split[1:]] # now arrgegate information for alt allels possib_alt = ['INDEL', 'INDEL1', 'INDEL2'...
a14b3cd5573ca2381b6284e8420a78b9d0763c48
3,619,059
def loadDataFrame(filename, logger): """ Loads the file into a pandas dataframe Args: filename - Path to file """ dataframe = pd.read_excel(io=filename, header=0, na_values=['[]', '', 'NaN']) logger.info("Finished Loading File: {} ".format(filename.split('\\')[-1])) return dataframe
5c994c1f9d4db5a54224ad616c4d28476d241894
3,619,060
import requests def get_ui_search_gene_project_donor_counts(url): """ if we look at the implementation of this endpoint, there are no filters http://bit.ly/2hfku5a So, redact the response strip off all projects not in white list """ # if no whitelist_projects, abort whitelist_projects = _w...
02aed723e17c86e9ab669f7b563488c6d1651958
3,619,061
def ocvh_smemo(for_each_device=False): """ Makes a function memoizing the result for each argument and device. This decorator provides automatic memoization of the function result. Args: for_each_device (bool): If True, it memoizes the results for each device. Otherwise, it memo...
8560f187fdffd83e77cf889084aefe54f9cb4205
3,619,062
def apply_exif_orientation(image): """ Reads an image Exif data for orientation information. Applies the appropriate rotation with PIL transposition. Use before performing a PIL .resize() in order to retain correct image rotation. (.resize() discards Exif tags.) Accepts a PIL image and returns ...
b5cb3fe31c554fa45d9525c46f3b8f8f3973af3e
3,619,063
def normalize_v4_address(source): """ IPv4 アドレスを整形する。 :param source: IPv4 アドレスと思われる文字列 :type source: str :return: 整形した IPv4 アドレス :rtype: str """ try: v4 = IPv4Address(source) except AddressValueError as _: return None return str(v4)
bba116ac1fd2abd23b60df98efca1b5e4301ffe9
3,619,064
import matplotlib.pyplot as plt def _jacobian(params, pose0, fixed_pt3d, n_cams, n_pts, cam_idxs, pt3d_idxs, pts2d, K, px_err_sd): """ cost function jacobian, from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6891346/ """ params = np.hstack((pose0, params)) poses, pts3d = _unpack(params, n_cams, ...
4658cf59a1635eb06589ec4c358e30a43e9e8523
3,619,065
def _cursor(host, dictCur = False): """Cursor Returns a cursor for the given host Args: host (str): The name of the host dictCur (bool): If true, cursor will use dicts Return: Cursor """ # Get a connection to the host oCon = _connection(host) # Try to get a cursor on the connection try: if dictCur...
fb309ee64f0d95eafca7afe715de6620cb6dea32
3,619,066
from pathlib import Path def get_solar_charge_state() -> str: """ Gets the current state of the charging system Returns: The charge state object as a json string """ current_state = Path('current_state.json').read_text() return current_state
0621aff9e6ae77b48811b2879f644ff3e4e4ee91
3,619,067
from datetime import datetime def get_lambda_execs_in_last_min(): """ Use CloudWatch to see how many lambdas are currently running (take the average over the last minute). Returns: (int): Average number of currently running lambdas. """ utc_zone = timezone(timedelta(hours=0)) now...
60e2ee45f532c474792f0249cbedb5094478ce4f
3,619,068
def get_fixture_value(request, fixture_name): """ Returns the value associated with fixture named `fixture_name`, in provided `request` context. This is just an easy way to use `getfixturevalue` or `getfuncargvalue` according to whichever is available in current `pytest` version. :param request: ...
11e2b5f67595ecf102f7a8f28cc4aa151a8ebca5
3,619,069
import os import shutil def train_test_split(source_dir_path, destination_dir_path, class_names, val_ratio, test_ratio, same_file_number=False, no_files_in_folder=1345): """ Categorizes your folder containing the image files into test, train and validation sets depending on the arguments,...
3457e0a342df9dab678e24f2f4763689909da6a7
3,619,070
def ParametricCrossCap(**kwargs): """Generate a cross-cap. ParametricCrossCap generates a cross-cap which is a non-orientable self-intersecting single-sided surface. This is one possible image of a projective plane in three-space. Return ------ surf : pyvista.PolyData ParametricCr...
ea581de824121908bdb9dac752b64d32b994413e
3,619,071
import random def random_member_id(): """ Return a zero-padded string from 00000000 to 99999999 that's not in use by any Member. """ def random_id(): return str("{0:08d}").format(random.randint(0, 99_999_999)) member_id = random_id() while Member.objects.filter(member_id=member_...
cbf9c54d8b6ac7f96daef138f8439608fcb38761
3,619,072
def has_role(package_path, role, identity): """True if |identity| has |role| in some |package_path|.""" assert impl.is_valid_package_path(package_path), package_path assert is_valid_role(role), role if auth.is_admin(identity): return True for acl in get_package_acls(package_path, role): if identity in...
e45a8e5452661bf96452dbb9a4e807158b36f484
3,619,073
def _add_o_makedup_bam_parser_options(p): """Add a bam as output of `pbsv1 markduplicates`""" return __add_makedup_bam_parser_options(p, str)
15b9fda402de523e94b043d2d1b6bc8d9c0566da
3,619,074
def image_to_vec(image_rgb: np.ndarray) -> np.ndarray: """Construct a RGB color vector from a 2D RGB image. Args: image_data (np.ndarray): image data as a ndarray or ndarray-like image_data.shape = (num_x_pixels, num_y_pixels, num_channels) Returns: np.ndarray: one row for each...
057f91a0f74f4a24623994d1356820208f51a9be
3,619,075
def animate(gens, interval=200): """Animate a set of 1d CA generations.""" # we'll need these num_cols = len(gens[0]) num_rows = len(gens) # set up figure fig, ax = plt.subplots(figsize=(num_cols*0.3, num_rows*0.3)) plt.close() ax.set_xlim([-1, num_cols]) ax.set_xticks(np.a...
90e3eba1655d4fa4348e9ec0df0170f385e3a95c
3,619,076
def load_user(user_id): """Check if user is logged-in on every page load.""" """Check if user is logged-in on every page load.""" if user_id is not None: query = 'match (n:User) where ID(n)={userid} return n' user = db.graph.run(query, parameters={'userid': user_id}).evaluate() user2...
f65c2caca06eae2cbef23031e76970adbfb3666e
3,619,077
def create_recurrent_merge_branch_model( vocab_size: int, embedding_size: int = 96, num_lstm_layers: int = 1, lstm_size: int = 670, shared_embedding: bool = False) -> tf.keras.Model: """Constructs a recurrent model with an initial embeding layer. The output is the average of the two branches,...
4b2c3dc9ee1d11229acf54827b3424f25247294b
3,619,078
def _convert_to_initializer(initializer): """Returns a TensorFlow initializer. * Corresponding TensorFlow initializer when the argument is a string (e.g. "zeros" -> `tf.zeros_initializer`). * `tf.constant_initializer` when the argument is a `numpy` `array`. * Identity when the argument is a TensorFlow initia...
1d9ee4c8dce6c5509f4148290bd64ba77b4bd222
3,619,079
def parseInpatientClaimData(obj, elem): """ Parse InpatientClaim data from xml element. Parameters: - obj : the claim data object - elem : the xml element containing claim data Return the claim data object """ parseData(obj, elem, inpatientClaimDataInstance, InPatientClaimMappi...
4e95f221c18cfaed9650e3721b505e3c8705d558
3,619,080
def _unicode(ctx, text): """ Returns a numeric code for the first character in a text string """ text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
e23133c5342acd8e11d6707f39138744443d0823
3,619,081
def parse_config(config): """ Parse config file so that it is in the correct form for the environment class """ parsed_config = {} subnets = config["subnets"] subnets.insert(0, 1) parsed_config["subnets"] = subnets parsed_config["num_services"] = config["num_services"] parsed_config[...
08670c9ef50b8f63a94ca1a984988263faf98d35
3,619,082
def loadFeatures(inpath, maxFeatures=-1, noMix=False, discardDerivs=False): """ Given the filepath of an input CSV feature file, this function reads all features from the file and stores them in a Numpy matrix suitable for use with SciKit classifiers. It returns the feature matrix and the list of labels for...
56bfe5975e08bd2e26be7cc4d59a9b593897f2b8
3,619,083
import codecs import os def read(*parts): """ Assume UTF-8 encoding and return the contents of the file located at the absolute path from the REPOSITORY joined with *parts. """ with codecs.open(os.path.join(PROJECT, *parts), "rb", "utf-8") as f: return f.read()
a12806fa8ae4cb0b7a122480ab3d71c0bc8bc248
3,619,084
def quote_ident(column: str): """ --------------------------------------------------------------------------- Returns the specified string argument in the format that is required in order to use that string as an identifier in an SQL statement. Parameters ---------- column: str Colu...
cdfe1f7e108904ef35c1733b91fea1a51e239570
3,619,085
def find_opt_end(options): """ Find the end of an option (;) handling escapes. """ offset = 0 while True: i = options[offset:].find(";") if options[offset + i - 1] == "\\": offset += 2 else: return offset + i
5e3404ffb2b776402a598351374f3390500edef3
3,619,086
def gas_fvf(z, temp, pressure): """ Calculate Gas FVF For range: this is not a correlation, so valid for infinite intervals """ temp = temp + 459.67 Bg = 0.0282793 * z * temp / pressure return(Bg)
375ac4aeac7f5177aab6e1bb4c2ab604b80778d2
3,619,087
def index(): """Return index page. The index page presents: - a header with the title of the website and a button that takes you to the login page. If you are logged in it logs you out. - a categories menu that displays all available categories. - a column with the latest items added. """ ...
c0ac79147fbaef61ce15a0bdf6467da9ac9a024a
3,619,088
def build_auxiliary_edge_connectivity(G): """Auxiliary digraph for computing flow based edge connectivity If the input graph is undirected, we replace each edge (`u`,`v`) with two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute 'capacity' for each arc to 1. If the input graph is...
598affab124771953dbf146a26814e89aef01f23
3,619,089
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: # model.load_state_dict(model_zoo.load_url(model_urls['resnet18']...
7de9843bfb5927394b79d466fc3472cdd12ebd31
3,619,090
import colorsys import random def save_draw_bbox(image, bboxes_,score_,label_, xml_path, iname, classes=classes, show_label=False): """ bboxes: [x_min, y_min, x_max, y_max, probability, cls_id] format coordinates. """ k = 0 num_classes = len(classes) image_h, image_w, _ = image.shape ...
2ee57bdfcf1c9b372b420024e992b10d5dd57f9d
3,619,091
def partition(A, p, r): """procedura partition Parametri: A (int): lista di numeri interi p (int): indice di inzio dell'array(o sottoarray) r(int): indice di fine dell'array(o sottoarray) Valore di Ritorno: int: indice del pivot """ x = A[r] ...
0cca35d4f1e010fb606a56272046217c5e231714
3,619,092
def printSchoolYear(year1): """Return a print version of the given school year. """ if year1: return "%d–%d" % (year1 - 1, year1)
93879512567a2be3e3cf541b747178b422be0590
3,619,093
import functools import io import sys def check_print(assert_in: str = "", length: int = -1): """Captures output of print function and checks if the function contains a given string""" def checker(func): @functools.wraps(func) def wrapper(*args, **kwargs): capturedOutput = io.Stri...
2b295c59609b8581e641d6c99608c95144e9b403
3,619,094
def dahua_brightness_to_hass_brightness(bri_str: str) -> int: """ Converts a dahua brightness (which is 0 to 100 inclusive) and converts it to what HASS expects, which is 0 to 255 inclusive """ bri = 100 if not bri_str: bri = int(bri_str) current = bri / 100 return int(current *...
d1d8d02f896edc4a16fbb1b26c99416b60764fc6
3,619,095
def connected_to_db(): """ Queries the database to check if the connection is live :return: Boolean """ try: session = Session() session.execute(text('SELECT 1')) session.close() return True except: return False
85ec38ff2648829d30f2300061c4e5b67e291f6e
3,619,096
from pathlib import Path from tempfile import gettempdir import os def setup_xprahtml5(): """ Setup commands and and return a dictionary compatible with jupyter-server-proxy. """ # from random import choice # from string import ascii_letters, digits global _xprahtml5_passwd, _xprahtml5_aesk...
e08312a25ea9e4a83959dd5ae2c138f5011cd9dd
3,619,097
def color_segmentation(segmentation): """ Converts a segmentation map to a color image. Args: segmentation: a 3-dim numpy array represents a RGB image Returns: colored segmentation map """ color_map = [ [0, 0, 0], [255, 0, 0], [0, 255, 0], [0, 0,...
57cb74ce8b1e468690af2bc2adecc69653bad416
3,619,098
import os def read(rel_path): """Read a file so python does not have to import it. Inspired by (taken from) pip's `setup.py`. """ here = os.path.abspath(os.path.dirname(__file__)) # intentionally *not* adding an encoding option to open, See: # https://github.com/pypa/virtualenv/issues/201#issuecommen...
647a9b5fd1e921cc47858393cced797d82820ebe
3,619,099