content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def _default_link_table2table(left, right): """Find default reference link between left and right tables. Returns (keyref, refop). Raises exception.ConflictModel if no default can be found. """ if left == right: raise exception.ConflictModel('Ambiguous self-link for table %s' % left)...
a7d5b589f811512f70bb5ba00d611745d1c3a353
3,626,521
def quit_() -> None: """Quits the program, returns None.""" win.quit() win.destroy() return None
e98fac70384f46c5a5abbf6dd9ca90ee2b846fad
3,626,522
def create_lkas_ui(packer, main_on, enabled, steer_alert): """Creates a CAN message for the Ford Steer Ui.""" if not main_on: lines = 0xf elif enabled: lines = 0x3 else: lines = 0x6 values = { "Set_Me_X80": 0x80, "Set_Me_X45": 0x45, "Set_Me_X30": 0x30, "Lines_Hud": lines, "Ha...
16c226698160b14194daf63baf61bb3952e1cd59
3,626,523
def recover_password(user: schemas.UserBase) -> JSONResponse: """ Password Recovery """ db_user = get_active_user(email=user.email) if db_user is None: return JSONResponse(status_code=404, content={ "message": "The user with this email " "does not exist in...
03b270a743b8c262e8622860672493c649079b36
3,626,524
def plot_ellipses_MacAdam1942_in_chromaticity_diagram_CIE1960UCS( chromaticity_diagram_callable_CIE1960UCS=( plot_chromaticity_diagram_CIE1960UCS), chromaticity_diagram_clipping=False, ellipse_kwargs=None, **kwargs): """ Plots *MacAdam (1942) Ellipses (Observer PGN)* ...
04157ae011619f6bc9cb4207ff09e7edf86d91b9
3,626,525
import torch def get_pytorch_device() -> torch.device: """Checks if a CUDA enabled GPU is available, and returns the approriate device, either CPU or GPU. Returns ------- device : torch.device """ device = torch.device("cpu") if torch.cuda.is_available(): device = torch.devic...
0109f3146c96bec08bbe6fa62e5a8bc5638e461c
3,626,526
import logging def test_execution_store(cfg): """ Creates a proper test_execution store based on the current configuration. :param cfg: Config object. Mandatory. :return: A test_execution store implementation. """ logger = logging.getLogger(__name__) if cfg.opts("results_publishing", "data...
8684f2ea65019e9c49444bbc25a8e1b0f59e687e
3,626,527
import time import random def creat_order_num(user_id): """ 生成订单号 :param user_id: 用户id :return: 订单号 """ time_stamp = int(round(time.time() * 1000)) randomnum = '%04d' % random.randint(0, 100000) order_num = str(time_stamp) + str(randomnum) + str(user_id) return order_num
339764f7dc943c46d959a9bfdc6c48dc9ecd6bef
3,626,528
def get_rst_title_char(level): """Return character used for the given title level in rst files. :param level: Level of the title. :type: int :returns: Character used for the given title level in rst files. :rtype: str """ chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^') if...
b646b9e0010d87ece7f5c8c53c8abf89ca557a21
3,626,529
def python_to_ir(f, imports=None): """Compile a piece of python code to an ir module. Args: f (file-like-object): a file like object containing the python code imports: Dictionary with symbols that are present. Returns: A :class:`ppci.ir.Module` module .. doctest:: >>...
67ae702485ad664667b80efc8c3ff3d9ec13ab57
3,626,530
def get_endpoint_url(env, endpoint='public'): """Gets the Endpoint to use.""" endpoint_type = env.input('Endpoint (public|private|custom)', default=endpoint) endpoint_type = endpoint_type.lower() if endpoint_type == 'public': endpoint_url = SoftLayer.API_PUBLIC_ENDPOINT elif endpoint_type ...
37eec3f0d9499b079867af233922a49afe4c40cf
3,626,531
def compute_temperature_high_altitude(altitude: pint.Quantity) -> pint.Quantity: """Compute temperature in high-altitude region. Parameters ---------- altitude: quantity Altitude. Returns ------- quantity Temperature. """ r0 = R0 a = -76.3232 # K b = -19.94...
c626e901e291f66f03056b288ab05738adbb67d0
3,626,532
def _get_individual_lists(ws, ind_numbers = INDIVIDUAL_NUMBERS, behav_map = BEHAVIOR_MAPPING): """ returns {1 : [time, behav, start/stop] }""" start_row = _get_first_content_row(ws = ws) ret_dict = {} for j in range(start_row, ws.max_row + 1): if j % 100 == 0: print("******Proce...
3a68795d1083abd6f876a014a1e873341ba04b79
3,626,535
def normalize_prob_dictionary(prob_dict): """ Given a dictionary that describes probabilities of parameter values, normalize the probabilities so that they sum up to 1 :param dict: :return: """ sum = np.sum(list(prob_dict.values())) if sum > 0: for key in prob_dict.keys(): ...
57432f66c5bf569d080e251e877632b9cfbec743
3,626,537
def stsci_extraction_ranges(x1d, seg=''): """ Parameters ---------- x1d seg Returns ------- ysignal, yback """ cos, stis = _iscos(x1d), _isstis(x1d) xh, xd = x1d[1].header, x1d[1].data # below these will all be divided by 2 (except bk off). initially they specify the f...
6e2843656ae1955da36a1bca059fec7ae454d624
3,626,538
def ending_at(row_key: str) -> pbt_C.RowRange: """Create a row range ending at given row (inclusive). Args: row_key (str): The ending row key of the range (inclusive). Returns: RowRange: The row range which ends at `row_key` (inclusive). """ return pbt_C.ending_at_row_range(row_key)
b15b65c74bcf8524d3d1932dcde8dca678d5c967
3,626,539
def train_model(model, X_data_train, y_target_train, early_stopping): """ :param model: compiled model :param X_data_train: 3d array :param y_target_train: 1d array :param flag: true if googlnet (output expect 3d array) else false if 1d array for output :return: fitted model """ if earl...
1510c7887a503d9a1fca6faf7f2eadb583af70a1
3,626,540
import torch import torch.nn as nn def bn_model_pytorch(): """Same as bn_model but with PyTorch.""" bounds = (0, 1) num_classes = 10 class Net(nn.Module): def forward(self, x): assert isinstance(x.data, torch.FloatTensor) x = torch.mean(x, 3) x = torch.m...
f4e16cb8283fa5ad58a0c65bb94f295d14ebec0c
3,626,542
def check_point(x, y, d, length, alpha): """ Проверяет точку на принадлежность волноводу Точка в ск Федера """ if -d / 2 <= y <= d / 2: return 0 <= x <= length or is_inside_cone(x - length, y, d, alpha)
747db69665134096077bdc29ccd162de5c14bda5
3,626,543
def comments_list(request, locker_id, submission_id): """Returns a list of comments for the specified submission""" submission = get_object_or_404(Submission, pk=submission_id) if submission.locker.discussion_enabled(): is_owner = submission.locker.is_owner(request.user) is_user = submission...
b3202414cf2174e9329538c1f617a3734e5c97b2
3,626,545
def massage_spectrum(cov, shape): """given a spectrum cov[nl] or cov[n,n,nl] and a shape (stokes,ny,nx) or (ny,nx), return a new ocov that has a shape compatible with shape, padded with zeros if necessary. If shape is scalar (ny,nx), then ocov will be scalar (nl). If shape is (stokes,ny,nx), then ocov will be (sto...
18a7bf9b8704f1ada174b523fb9ddd3fdf135ff7
3,626,547
def get_device_by_label(session, label): """get Device by label Args: session: Active database session label: label to get device that matches Returns: device found or None """ return session.query(Resource).filter(Resource.label == label).one_or_none()
624acfd77be27d89f00f3e594f179c9a4f285639
3,626,548
from bs4 import BeautifulSoup def fetch_MX_exchange(sorted_zone_keys, s): """ Finds current flow between two Mexican control areas. Returns a float. """ req = s.get(MX_EXCHANGE_URL) soup = BeautifulSoup(req.text, 'html.parser') exchange_div = soup.find("div", attrs={'id': EXCHANGES[sorted...
c2316f6c3bbd4d823fd2e34057f2fa8df248e3a6
3,626,549
def mlp(X_train, targets): """Fully Connected Neural Network, known as MLP(Multi-Layer Perceptons). """ feature_number = X_train.shape[1] output_number = targets.shape[1] model = tf.keras.Sequential() model.add(Dense((output_number+feature_number)/2+40, input_dim=feature_numb...
37a651a0007a6d31cc5c277db49085b9bd303c25
3,626,550
def make_ir_context() -> ir.Context: """Creates an MLIR context suitable for JAX IR.""" context = ir.Context() mhlo.register_mhlo_dialect(context) chlo.register_chlo_dialect(context) return context
7e34ade63d47e763784277d05fcb8d979b28715b
3,626,551
def parse_patch(patch_string): """Parse a patch string and return the affected files.""" patch = DiffParser(patch_string.splitlines()) return patch.files
8b53d5443290fc6cdb1162ab0a607d42313ed9ba
3,626,553
def adjust_color_lightness_scalar(r, g, b, factor): """ r,g,b between 0 and 1 factor between 0 and +infty, but lightness bounded between 0 and 1 """ h, l, s = rgb_to_hls_scalar(r, g, b) l = max(min(l * factor, 1.0), 0.0) r, g, b = hls_to_rgb_scalar(h, l, s) return r,g,b
0e541f92c3df11a8bce1e5988d2a329ee15d933b
3,626,554
def get_sample_ids(fams): """ create a ditionary mapping family ID to sample, to subID Returns: e.g {'10000': {'p': 'p1', 's': 's1'}, ...} """ sample_ids = {} for i, row in fams.iterrows(): ids = set() for col in ['CSHL', 'UW', 'YALE']: col = 'SequencedA...
443e63b486a1bdb8a64595beda30f75468af7560
3,626,555
def mesh_conway_join(mesh): """Generates the join mesh from a seed mesh. Parameters ---------- mesh : Mesh A seed mesh Returns ------- Mesh The join mesh. Examples -------- >>> mesh = Mesh.from_polyhedron(6) >>> join = conway_join(mesh) >>> join.number_...
53f6358798f3421f98524fbcf166834a579a5f45
3,626,556
def calcbw(K, N, srate): """Calculate the bandwidth given K.""" return float(K + 1) * srate / N
13e99bcb729352feb66a34aac66e12b1c5e158ef
3,626,557
import requests import json def get_all_devices(auth): """ Function to get all devices for the account linked to the token :param auth: pyawair.auth.AwairAuth object which contains a valid authentication token :return: Object of Dict type which contains a list of all devices for this account """ ...
ec46bd1be167e8df4d6cce94bddd3725eca73b43
3,626,558
def supports_display(handler_input): # type: (HandlerInput) -> bool """Check if display is supported by the skill.""" #check the incoming request to the skill from the AVS to determine if the device the user invoked the skill on has a screen try: if hasattr(handler_input.request_envelope.context...
98c45257b034637549e687dfe5e500d5cc4ffcb7
3,626,559
def format_sqlexec(result_rows, maxlen): """ Format rows of a SQL query as a discord message, adhering to a maximum length. If the message needs to be truncated, a (truncated) note will be added. """ codeblock = "\n".join(str(row) for row in result_rows) message = f"```\n{codeblock}```" ...
3b98590c72245241ba488e07fdfdd20acae441cf
3,626,560
def is_calibration_produced(drs4_pedestal_run_id: int, pedcal_run_id: int) -> bool: """ Check if both daily calibration (DRS4 baseline and charge calibration) files are already produced. """ return ( drs4_pedestal_exists(drs4_pedestal_run_id) and calibration_file_exists(pedcal_run_id...
2ce3a469bb3fa84493379d758b9573c6170986da
3,626,561
def generate_initial_population(network_info, network_layout): """ Generates the initial population for network optimization. :param NetworkInfo network_info: Object storing global network information (information about the whole optimization) :param NetworkLayout ...
0c07f873f162ed8c87f9335fc1eadf8e84990311
3,626,564
def split_zip(zip_code): """ split the zip code into 5 and 4 digit codes """ if not valid_zip(zip_code): return None, None if len(zip_code) == 5: return zip_code[:5], None return zip_code[:5], zip_code[-4:]
86d6c37e2dce4a840e6198c9aa86c52716eff256
3,626,565
from typing import Dict from typing import Any from typing import Iterable import warnings def parse_initial_conditions( ic: Dict[str, Any], start_date_simulation: pd.Timestamp, virus_strains: Dict[str, Any], ) -> Dict[str, Any]: """Parse the initial conditions.""" ic = {**INITIAL_CONDITIONS} if i...
2e47bcff366870425b738381ac7abfb4c860103c
3,626,566
def rq2responses(request): """ Converts a request to a list of responses. :param request: Flask Request object :return: list of response strings """ i, responses = 0, [] for i in range(int(request.form['num_questions'])): name = Question.ID_FORMAT % i if request.form.get(nam...
83e42a33d6f3a23134819fcba16b4422ac7cffc3
3,626,567
def image_show(image, nrows=1, ncols=1, cmap='gray', **kwargs): """ Taken from : https://github.com/gmagannaDevelop/skimage-tutorials/blob/master/lectures/4_segmentation.ipynb """ fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(16, 16)) ax.imshow(image, cmap='gray') ax.axis...
b2293d254a942b5f6534cc7394031dbefb87978b
3,626,568
def normalize(arr): """Normalizes an array to its mean values. Parameters ---------- arr : array-like | shape = [N] The array to normalize. Returns ------- normalized_array : np.ndarray | shape = [arr.shape] """ return arr / np.mean(arr)
6021296c5a86f770be59de259945e2ac28532154
3,626,569
from typing import List from typing import Tuple def find_matching_parens( assertion_str, matched_quotes, errors: List[ValidationError] ) -> Tuple[List[Pair], List[ValidationError]]: """Find and return the location of the matching parentheses pairs in s. Given a string, s, return a dictionary of start: e...
07259774357cc04bd9ededdf0e1557207ed301ca
3,626,570
import re def regex_sub_groups_global(pattern, repl, string): """ Globally replace all groups inside pattern with `repl`. If `pattern` doesn't have groups the whole match is replaced. """ for search in reversed(list(re.finditer(pattern, string))): for i in range(len(search.groups()), 0 if ...
67e909778d9565d498fc3e7b3c9522378e971846
3,626,571
def _parse( filepath : str ) -> list: """ [summary] Arguments: filepath {str} -- [description] Returns: list -- [description] """ with open( filepath, 'r' ) as f: raw_data = f.read( ) # not readlines( ), as this needs to be one long string data = list( map( int, raw_data.split( ) ) ) return data
6814c4f45aee453f6387761ee7c4f3e64c669b1c
3,626,572
from typing import Optional def get_app_sec_eval(config_id: Optional[int] = None, security_policy_id: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetAppSecEvalResult: """ Use this data source to access information about an existing r...
2499b44e1b59ab989fb6b14a4d60145610a0d0b1
3,626,573
def write_merged_bioassembly(inpath, outdir, outname, force_rerun=False): """Utility to take as input a bioassembly file and merge all its models into multiple chains in a single model. Args: infile (str): Path to input PDB file with multiple models that represent an oligomeric form of a structure. ...
e53779b0c466a730028d91ff10779137a186c288
3,626,574
def get_final_loss(src_logits, src_one_hot_labels, dst_logits, finetune_one_hot_labels, global_step, loss_weights, inst_weights): """Gets the final loss for .""" if FLAGS.uniform_weight: inst_weights = 1.0 src_loss = get_loss(src_logits, inst_weights, src_one_hot_labels) ...
2b87a024394e983eea9dbd5a1df9b30a9bff74f4
3,626,575
def causal_kernel(alpha): """ The causal kernel. .. math:: w(\\tau) = [\\alpha^2 \\tau \\exp(- \\alpha \\tau)]_+ example: .. code-block:: python >>> kernel('causal', {'alpha': 0.4}) """ def causal(t): v = alpha**2 * t * np.exp(-alpha*t) v[v<0] = 0 return v return caus...
f49766f44f1532e11ef1ad88f162d1cf4bc03e0a
3,626,576
import numpy def read_nasa_planets(csv_filename, eliminate=('SWEEPS-11', 'HD 41004 B', 'PSR J1719-1438', 'K2-22'), fill_missing=manual_data, need_ages=Tr...
a39f96be4f5b2b9f8e3e642117f5338db542fabb
3,626,577
def e8(s: str) -> str: """ Encode Unicode string with stanard options """ return s.encode('utf-8', 'ignore')
ae28011d7d71c28399d81012fac26012693de9aa
3,626,578
import requests def download_seed_seqs(acc): """ Download seed sequences from PFAM. Input ----- acc : str Accession number of a Pfam domain Output ------ fasta : str Seed sequences in fasta format """ url = "http://pfam.xfam.org/family/%s/alignment/seed" % acc...
e067e5e6e0669812151a680d6f785b19be01fb01
3,626,580
import numpy def fit_spline(points, smoothing=None, order=None, force_endpoints=True): """Fit a parametric smoothing spline to a given set of x,y points. (Fits x(p) and y(p) as functions for some parameter p.) Parameters: points: array of n points x,y; shape=(n,2) smoothing: smoothing factor: 0 r...
e694736af14999881a9fd1cf3c8fd070802b137b
3,626,581
def get_list_of_teams(): """Get a list of all teams.""" teamlist = [] for team in cursor.execute('SELECT * from teams'): teamlist.append(team[0]) # man isn't it cool that order matters return teamlist
82121e2fc8a652c4ee3630a4cba80aeb4f026520
3,626,582
def linear_activation_forward(A_prev, W, b, activation): """ activation of forward propagation :param A_prev: np.array, activations from previous layer :param W: np.array, weights matrix of current layer :param b: np.array, biases vector of current layer :param activation: str, activation mode o...
a8290d71b1660c5a154cc47e3674560a24c6d2e8
3,626,583
def stoll_auc_subjects(ds, skip_samples=0, dur_samples=10000): """ Calculate AUC for each subject in a dataset using the Stoll (2013) classification method """ aucs = [] for sub in np.unique(ds.trials_ppid): tpr = [] fpr = [] tr = ds.trials[ds.trials_ppid == sub, :] ...
b3398c52d9f8d0fc8b90621b301e8d27770a18e6
3,626,584
def stations_level_over_threshold(stations, tol): """Returns a list of the tuples, each containing the name of a station at which the relative water level is above tol and the relative water level at that station""" output = [] for station in stations: relative_level = station.relative_water_l...
87be1329ea8b7e58796ebfe33a6f9e9503777227
3,626,585
def select_ensembl_species(species, table): """ Filters the species of interests, called group, from a table containing all the species in the Current release """ # Read the species table from Ensembl Genomes df = pd.read_csv(table, sep='\t', index_col=False) # Filter out the species that are ...
eb7f0a75842745a27b11296d602088770002eae8
3,626,588
def normalize_power_spectrum(Q): """transform spectrum to complex vectors with unit length Parameters ---------- Q : np.array, size=(m,n), dtype=complex cross-spectrum Returns ------- Qn : np.array, size=(m,n), dtype=complex normalized cross-spectrum, that i...
783fc5def698289f45721080c91ef74554604a4c
3,626,589
import torch def img2tensor( img: pillow.Image, size: tuple = None, ) -> torch.Tensor: """ Args: img: image to convert size: (W, H) of output tensor Returns: tensor of shape (1, 3, H, W) the first dimension (batch size) is neccesary for the CNN 3 cha...
d90bc998d1a476287b0e2c2444d3dce4a035b7c6
3,626,590
def handler(event, context): """ function handler """ if 'imageDiscard' in event and event['imageDiscard']: return None if 'imageLocation' not in event or len(event['imageLocation']) == 0: return None if 'imageObjects' not in event or len(event['imageObjects']) == 0: re...
82d723d913f1c2d0631157a27702a889faa4c1b4
3,626,591
def set_smb_netbios_name(session, smb_netbios_name, force="YES", return_type=None, **kwargs): """ Get VPSA cache :type session: zadarapy.session.Session :param session: A valid zadarapy.session.Session object. Required. :type smb_netbios_name: str :param smb_netbios_name: The smb ne...
964877297f8814da9ca9af92bb93b3bc7fd2718d
3,626,592
def _random_correlated_image(mean, sigma, image_shape, alpha=0.3, rng=None): """ Creates a random image with correlated neighbors. pixel covariance is sigma^2, direct neighors pixel covariance is alpha * sigma^2. Parameters ---------- mean : the mean value of the image pixel values. sigma :...
71a81630c29e271265b8bace4136a4fbce83137b
3,626,594
def diameter(aabb): """ Compute the length of the diameter of an AABB. :param aabb: AABB defined by its min and max point. :type aabb: Pair of n-dimensional vectors :return: Length of the diameter of the AABB. """ if not is_valid(aabb): return None return np.linalg.norm(aabb[1] ...
675c0a2a445c18b7d1da75f9f78cb7a529ed1a05
3,626,596
def deregister_device(device): """ Task that deregisters a device. :param device: device to be deregistered. :return: response from SNS """ return device.deregister()
44bec0e3ac356f150a0c4a6a0632939a20caafb0
3,626,597
async def peko(message): """peko""" """returns [content, embed, view]""" url = "https://holodex.net/api/v2/users/live" params = { "channels": "UC1DCedRgGHBdm81E1llLhOQ,UCdn5BQ06XqgXoAxIhbqw5Rg,UC5CwaMl1eIgY8h02uZw7u8A,UChAnqc_AY5_I3Px5dig3X1Q" } headers = {"Content-Type": "application/js...
674927c77fc6e4dc54a7eab6c4f42f7b64d84c00
3,626,598
def sequential_colors(n): """ Between 3 and 9 sequential colors. .. seealso:: `<https://personal.sron.nl/~pault/#sec:sequential>`_ """ # https://personal.sron.nl/~pault/ # as implemented by drmccloy here https://github.com/drammock/colorblind assert 3 <= n <= 9 cols = ['#FFFFE5', '#FFFB...
d2ad5f8993f8c7dac99a577b6115a8452ad30024
3,626,599
def _get_mask(Size, idxi, idxj, win_type): """Compute a mask of zeros with a window at a given position. """ idxi = np.array(idxi).astype(int) idxj = np.array(idxj).astype(int) win_size = (idxi[1] - idxi[0] , idxj[1] - idxj[0]) wind = build_2D_tapering_function(win_size, win_type) mask =...
cf6426646703601c23ab9d8491eff656e2effaf0
3,626,602
import shutil import logging def _check_tool(cfg: config.Config, bin_name: str, name: str, min_version: Version) -> bool: """Check availability and version of a tool.""" if not _check_availability(bin_name, name): return False bin_path = shutil.which(bin_name) assert bin_path i...
15520d3b94ffac6957ca297aa1f4ae49bff8a45d
3,626,604
def init_func_global() -> JobInitStateReturn: """ Init function for the job :return: INIT or NOT_INIT state for the job """ return JobInitStateReturn(True)
e00c448dcc3f84cd53844d9d4a425ff4545a8135
3,626,605
def get_orbit_from_metadata(mds): """Get orbit for a set of SLC ids. They need to belong to the same day.""" day_dt, all_dts, mission = util.get_date_from_metadata(mds) logger.info("get_orbit_from_metadata : day_dt %s, all_dts %s, mission %s" %(day_dt, all_dts, mission)) return fetch("%s.0" % all_dts[0...
ff0b9d1a2f2d99dc5332abcd0fc4d402e0dd693f
3,626,606
def fibonacci(n): """Return the n-th Fibonacci number""" if n in (0,1): return n return (fibonacci(n - 2) + fibonacci(n - 1)) # Can trace the recursive function with a decorator
ab01aabbc2ef5c5bf2f3f0b83f44675254b555c7
3,626,607
def random_color() -> np.ndarray: """Generate a random color (RGB).""" return np.array(np.random.rand(3))
f77b72075fbbd89d87f6507d06a2ac713d49daa2
3,626,608
def get_king_moves(): """Generate the king's movement range.""" return [(1, 0), (1, -1), (-1, 0), (-1, -1), (0, 1), (0, -1), (-1, 1), (1, 1)]
5e6f5fcb8c57846b9b2ab112c27f90fc13a6d6b4
3,626,609
def _unpack_topk(topk, lp, hists, attn=None): """unpack the decoder output""" beam, _ = topk.size() topks = [t for t in topk] lps = [l for l in lp] k_hists = [(hists[0][:, i, :], hists[1][:, i, :], hists[2][i, :]) for i in range(beam)] if attn is None: return topks, lps, ...
7e9012b62f25ec7f4a09387235a0161143ec5029
3,626,611
def share_map(map_url_hash): """Create shareable version of current map using crypotgraphic hash at end of address""" user_map = Map.query.filter(Map.map_url_hash == map_url_hash).one() map_id = user_map.map_id places_on_map = Place.query.filter(Place.map_id == map_id, Place.place_active == True).all() ...
a92384b52e0b9beb36c783d5fec4036983289aef
3,626,612
def _darknet_reshape(inputs, params, attrs, prefix): """Process the reshape operation.""" new_attrs = {} new_attrs['shape'] = attrs.get('shape') return get_relay_op('reshape')(*inputs, **new_attrs)
90049d596aeca37074e2d9946eb0f2d0c6bc8513
3,626,613
def CreateVectorObject(volumeRef, name): """ Creates a c4d.VolumeObject with the VolumeRef passed. Names this VolumeObject with the passed argument. :param volumeRef: The VolumeRef to use within the VolumeObject. :type volumeRef: maxon.frameworks.volume.VolumeRef :param name: The name of the in...
11099d54def62f560227d3a97ea628bf15c55931
3,626,615
def box2start_row_col(box_num): """ Converts the box number to the corresponding row and column number of the square in the upper left corner of the box :param box_num: Int :return: len(2) tuple [0] start_row_num: Int [1] start_col_num: Int """ start_row_num = 3 * (box_num // 3...
b11e7d4317e1dd32e896f1541b8a0cf05a342487
3,626,616
def safe_referrer(meta, default): """ Takes request.META and a default URL. Returns HTTP_REFERER if it's safe to use and set, and the default URL otherwise. The default URL can be a model with get_absolute_url defined, a urlname or a regular URL """ referrer = meta.get('HTTP_REFERER') i...
b70f7799bf13fc2ee9229f037553047dd60334be
3,626,617
import re def create_title(chunk, sep, tags): """Helper function to allow doconce jupyterbook to automatically assign titles in the TOC If a chunk of text starts with the section specified in sep, lift it up to a chapter section. This allows doconce jupyterbook to automatically use the section's text...
67bd80c10733d79f84ba38cd44155e73bb2a2efd
3,626,618
import math def get_marker_size(number): """Same scaling as for year 2019. Produces more overlap between circles. But this was considered OK, since it does reflect the reality. """ return SCALE * (5 * math.sqrt(number) + 5)
252c9549fa0c568dd88361cbf1a8cbc467972e08
3,626,619
import scipy import numpy def graph2VSM(graph): """ Convert an igraph model to a VSM Params: model the igraph model """ terms = graph.vcount() edges = graph.ecount() # Use sparse matrix representation if the matrix is less than 50% full # if terms > 20000 and graph.density() <...
e89b682d539879945fe5a1a970db1f8c56c27652
3,626,621
def recurrence_memo(initial): """ Memo decorator for sequences defined by recurrence See usage examples e.g. in the specfun/combinatorial module """ cache = initial def decorator(f): @wraps(f) def g(n): L = len(cache) if n <= L - 1: retur...
6cb4ea4a2183bb98b915d966692fc5be40cdf494
3,626,624
def update_project_users(post_data=None, slug=None): """update-project-users (Site admins/Site managers/Project managers only) Usage: update-project-users [-h] <slug> (<username> <access_mode>) ... Arguments: <slug> The slug of the project <username> The username of the user to either update o...
71548b9203f1ce42cb469dd1ea0c37eaff722b8c
3,626,625
def _gaussian(y_pred, y_true, scale): """ Computes the log-likelihood of each sample for a Gaussian GLM given the predicted expected values. """ return - 0.5 * (y_pred - y_true) ** 2 / scale ** 2 \ - 0.5 * np.log(2 * np.pi * scale**2)
0d3d1df54e1f785e696e39d649f6d8c1b10c80c4
3,626,627
from typing import Sequence def regression_report( y_true: Sequence, y_pred: Sequence, *, precision: int = 4, width: int = 32, use_percentage: bool = False, ) -> str: """ Returns detailed regression report as string :param y_true: sequence of ground truth values for regression pro...
6572f117b045414822ec391af292759d4dc9d7ea
3,626,628
def _extract_feats(data_test, model, what, skip=1, batch_size=16): """ :param data_test: test Dataset :param model: network model :param what: SK or IM :param skip: skip a certain number of image/sketches to reduce computation :return: a two-element list [extracted_labels, extracted_features] ...
5549c3131d98ae876609f52ad0dc581ec7c9bc76
3,626,629
def _getbkfile(repo): """Hook so that extensions that mess with the store can hook bm storage. For core, this just handles wether we should see pending bookmarks or the committed ones. Other extensions (like share) may need to tweak this behavior further. """ fp, pending = txnutil.trypending(re...
1c04da01ed277ab790f02cae0e282d8dc853e8a0
3,626,630
def perturb(graph_list, p): """ Perturb the list of (sparse) graphs by adding/removing edges. Args: p: proportion of added edges based on current number of edges. Returns: A list of graphs that are perturbed from the original graphs. """ perturbed_graph_list = [] for G_original i...
c3358dc0bbdcd75d5619ed1ee372d206ea7651b0
3,626,631
def hold_out_val(data, target, include_self=True, class_weight=None, features=None, cl='rf', verbose=False, random_state=None): """ performs simple hold-out validation :param data: list of datasets to evaluate :param verbose: if true print confusion matrix and classification report for ...
b4e934fa87add641067ff16cb3709f384d1675e8
3,626,632
import torch def train(model, train_loader, loss_func, optimizer, device): """ 训练模型 train model using loss_fn and optimizer in an epoch. model: CNN networks train_loader: a Dataloader object with training data loss_func: loss function device: train on cpu or gpu device """ total_lo...
610b03e10ebce886743a4b06c91a46de30ef586d
3,626,633
def sq_dist(x: np.ndarray, y: np.ndarray): """ distance functions for point-point distances :param x: nd array, T1 x D :param y: nd array, T2 x D :return: matrix with shape of (T1, T2) """ return np.sum((x[:, None, :] - y[None, :, :]) ** 2, axis=2)
97f3b6fc10dbf5f18c5eea4403f3662be8580097
3,626,634
import uuid def get_uuid(): """ Returns a uuid4 (random UUID) specified by RFC 4122 as a 32-character hexadecimal string """ return uuid.uuid4().hex
ce3f00569c3fa12aa203246bd5d3ae098f2dab2a
3,626,635
async def register_users(app, users): """Create multiple users from a list. Parameters ---------- app : aiohttp.web.Application The aiohttp application instance. users : list(dict) The list of new users with each user having username, password, permissions and cards (optional). ...
a7ca4cb451da4d542d9740f7e2d12511514a7612
3,626,636
def radmat_from_df_filter( df, radmat_field="signal", channel_i=None, return_df=False, **kwargs ): """ Apply the filter args from df_filter and return a radmat """ _df = df_filter(df, channel_i=channel_i, radmat_field=radmat_field, **kwargs) radmat = df_to_radmat(_df, channel_i=channel_i, radmat...
61782b513be331da08d7c9ceaada7c12ba83d3e6
3,626,637
def _populate_number_fields(data_dict): """Returns a dict with the number fields N_NODE, N_EDGE filled in. The N_NODE field is filled if the graph contains a non-`None` NODES field; otherwise, it is set to 0. The N_EDGE field is filled if the graph contains a non-`None` RECEIVERS field; otherwise, it is set ...
e80e506057ecbb9ab4987ce4383da494824f1d66
3,626,638
def tree_pretty_print(tree): """Pretty-print a tree of python objects. Examples:: >>> from pptree import Node >>> users = Node("users") >>> group = Node("group", users) >>> _ = Node("roles", group) >>> _ = Node("permissions", group) >>> _ = Node("comments", users) >>> print(tree_pr...
2598ae29d3d019c1c9613f4944d16c01f149529f
3,626,639
def branch_edit(request, branch_id): """/branch_edit/<branch> - Edit a Branch record.""" branch = models.Branch.get_by_id(int(branch_id)) if branch.owner != request.user: return HttpTextResponse('You do not own this branch', status=403) if request.method != 'POST': form = BranchForm(initial={'category':...
f9ce2ba616899174b4765c889d28a2cfa7d39787
3,626,640
def eul(f, u, x_0, d, param): """Integrate dynamics using forward Euler method x[k+1] = x[k] + delta*(f(x[k], u[k])) Input: dynamics f, control input u, initial condition x_0, step d Output: trajectory x """ if u.ndim == 1: return x_0 + d*(f(x_0, u, param)) N...
9ac8ad1fef149c96144ea9d2730752e0d18bc0bd
3,626,641
def input_network_name(): """ Prompt user to choose a network """ while True: network_name = input('network ({0})?'.format(','.join(NETWORK_NAMES))) if network_name in NETWORK_NAMES: return network_name
0a467259652a12aa2f4c71c57019aba8b02af889
3,626,642
import re def hashtag(phrase, plain=False): """ Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct. Allow suppression of style changes, e.g. for two-letter state codes. """ words = phrase.split(' ') if not plain: for i in range(len(words)): try: if not words[i]: del word...
b6e7ab647330a42cf9b7417469565ce5198edd4f
3,626,643