content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def logout(request): """Logs out the user""" user_logout(request) return redirect(auth_views.login)
739ef6b3b4daded0af786f8261072e05e8bba273
3,643,667
import math def workout_train_chunk_length(inp_len: int, resampling_factor: int = 1, num_encoders: int = 5, kernel: int = 8, stride: int = 2) -> int: """ Given inp_len, return the chunk ...
a7e7f42aa9670f1bda98c588e50052db0f4eb90f
3,643,669
def asin(e): """ :rtype: Column """ return col(Asin(parse(e)))
7c7fb32e84d7a9af74bc64eed2f111fd2030a499
3,643,670
def ft32m3(ft3): """ft^3 -> m^3""" return 0.028316847*ft3
74f55f722c7e90be3fa2fc1f79f506c44bc6e9bc
3,643,672
def max_shading_elevation(total_collector_geometry, tracker_distance, relative_slope): """Calculate the maximum elevation angle for which shading can occur. Parameters ---------- total_collector_geometry: :py:class:`Shapely Polygon <Polygon>` Polygon corresponding to t...
f3e623607ae1c2576fa375146f4acc6186189d8c
3,643,674
def tensor_scatter_add(input_x, indices, updates): """ Creates a new tensor by adding the values from the positions in `input_x` indicated by `indices`, with values from `updates`. When multiple values are given for the same index, the updated result will be the sum of all values. This operation is almo...
38707efab3d2f947cbc44dacb6427281d3b652cb
3,643,675
def test100(): """ CIFAR-100 test set creator. It returns a reader creator, each sample in the reader is image pixels in [0, 1] and label in [0, 9]. :return: Test reader creator. :rtype: callable """ return reader_creator( paddle.v2.dataset.common.download(CIFAR100_URL, 'cifar'...
f43e27a7ce1ec40dfc50d513de5406b2683a566b
3,643,676
def _calculate_target_matrix_dimension(m, kernel, paddings, strides): """ Calculate the target matrix dimension. Parameters ---------- m: ndarray 2d Matrix k: ndarray 2d Convolution kernel paddings: tuple Number of padding in (row, height) on one side. If you...
77b5cabd7101b957a27fc422d1ed1715525400a0
3,643,677
def any_email(): """ Return random email >>> import re >>> result = any_email() >>> type(result) <type 'str'> >>> re.match(r"(?:^|\s)[-a-z0-9_.]+@(?:[-a-z0-9]+\.)+[a-z]{2,6}(?:\s|$)", result, re.IGNORECASE) is not None True """ return "%s@%s.%s" % (any_string(max_length=10), ...
8575d02d3c9a777bc2cf27f1344676cad5514d5e
3,643,678
def transform_pts_base_to_stitched_im(pts): """Project 3D points in base frame to the stitched image Args: pts (np.array[3, N]): points (x, y, z) Returns: pts_im (np.array[2, N]) inbound_mask (np.array[N]) """ im_size = (480, 3760) # to image coordinate pts_rect = ...
c6397451e458af086fe316c6933ca27641daac26
3,643,679
def get_equal_static_values(*args): """get_equal_static_values(FileConstHandle input, FileConstHandle out) -> bool""" return _RMF.get_equal_static_values(*args)
8f929f0eae16e620b5025ad34b4437d836d8d671
3,643,680
def quaternion_to_rotation_matrix(quaternion): """ This converts a quaternion representation of on orientation to a rotation matrix. The input is a 4-component numpy array in the order [w, x, y, z], and the output is a 3x3 matrix stored as a 2D numpy array. We follow the approach in "3D Math P...
95a8dd9d0a9510710e7b6ed676a5f03e26b2da96
3,643,681
def load_subject(filename: str, mask_niimg): """ Load a subject saved in .mat format with the version 7.3 flag. Return the subject niimg, using a mask niimg as a template for nifti headers. Args: filename <str> the .mat filename for the subject...
e3cdb751cebd7407b694555adfb21e7a6a224c50
3,643,682
def pretty_duration(seconds): """Return a human-readable string for the specified duration""" if seconds < 2: return '%d second' % seconds elif seconds < 120: return '%d seconds' % seconds elif seconds < 7200: return '%d minutes' % (seconds // 60) elif seconds < 48 * 360...
8e34addedeeb98e1e028fa9374fcc8c4f134a9f7
3,643,684
def plot_ecdf(tidy_data, cats, val, title, width=550, conf_int=False): """ Plots an ECDF of tidy data. tidy_data: Set of tidy data. cats: Categories to plot val: The value to plot title: Title of plot width: width of plot conf_int: Whether or not to bootstrap a CI. """ p = bokeh...
11ef82111ad300826f47f6ce91ea588911a790c8
3,643,685
from operator import concat def upsert(left, right, inclusion=None, exclusion=None): """Upserts the specified left collection with the specified right collection by overriding the left values with the right values that have the same indices and concatenating the right values to the left values that have different ...
b4754c01ff521b892107afd8dd12b015bd4e293a
3,643,686
from typing import Counter def train(training_data): """Trains the model on a given data set. Parameters ---------- training_data Returns ------- """ counts = Counter(training_data) model = {} # sort counts by lowest occurrences, up to most frequent. # this allows higher...
328901b090392097d22b21a948691787e0128d48
3,643,687
from datetime import datetime def get_description(): """ Return a dict describing how to call this plotter """ desc = dict() desc['data'] = True desc['cache'] = 86400 desc['description'] = """This chart totals the number of distinct calendar days per month that a given present weather conditio...
0927644a801a2829a97fbc6e78ef70fff1e8edfe
3,643,688
import logging from datetime import datetime import time def check_cortex(ioc, ioc_type, object_id, is_mail=False, cortex_expiration_days=30): """Run all available analyzer for ioc. arguments: - ioc: value/path of item we need to check on cortex - ioc_type: type of the ioc (generic_relation and corte...
c647ab09bd97dda75dc4073634ac4a68cbf8613a
3,643,689
def _env_corr_same(wxy, Xa, Ya, sign=-1, log=True, x_ind=None, y_ind=None): """ The cSPoC objective function with same filters for both data sets: the correlation of amplitude envelopes Additionally, it returns the gradients of the objective function with respect to each of the filter coefficients....
2004e3ab1f9c81466e8dc946b04baf5a692b169d
3,643,690
def create_resource(): """Hosts resource factory method""" deserializer = HostDeserializer() serializer = HostSerializer() return wsgi.Resource(Controller(), deserializer, serializer)
ed49ae9fecce67fcd3c4fa1a2eac469eb97e239b
3,643,691
def get_ref_kmer(ref_seq, ref_name, k_len): """ Load reference kmers. """ ref_mer = [] ref_set = set() for i in range(len(ref_seq) - k_len + 1): kmer = ref_seq[i:(i + k_len)] if kmer in ref_set: raise ValueError( "%s found multiple times in reference %s, at p...
72b75dccfba122a986d50e144dea62bfafe0fb50
3,643,692
def get_distutils_build_or_install_option(option): """ Returns the value of the given distutils build or install option. Parameters ---------- option : str The name of the option Returns ------- val : str or None The value of the given distutils build or install option. If ...
7f0d72e1c30c752761eb8c7f8f0ffeb875183d4d
3,643,693
def CMDset_close(parser, args): """Closes the issue.""" auth.add_auth_options(parser) options, args = parser.parse_args(args) auth_config = auth.extract_auth_config_from_options(options) if args: parser.error('Unrecognized args: %s' % ' '.join(args)) cl = Changelist(auth_config=auth_config) # Ensure t...
6711ba947e9d839217a96568a0c07d1103646030
3,643,694
def gchip(k_k, b_b, c_c): """gchip(k_k, b_b, c_c)""" yout = b_b*c_c*nu_f(1, b_b, k_k)**((c_c+1)/2)*\ cos((c_c+1)*atan(b_b*k_k)) return yout
81fa674a2fb03875e39f2968986104da06a5ea44
3,643,695
def create_component(ctx: NVPContext): """Create an instance of the component""" return ProcessUtils(ctx)
ec9d4539583dbdeaf1c4f5d8fce337077d249ab2
3,643,696
import ipaddress def is_valid_ip(ip: str) -> bool: """ Args: ip: IP address Returns: True if the string represents an IPv4 or an IPv6 address, false otherwise. """ try: ipaddress.IPv4Address(ip) return True except ValueError: try: ipaddress.IPv6Addre...
aa1d3b19828dd8c3dceaaa8d9d1017cc16c1f73b
3,643,697
def complete_tree(leaves): """ Complete a tree defined by its leaves. Parmeters: ---------- leaves : np.array(dtype=np.int64) Returns: -------- np.array(dtype=np.int64) """ tree_set = _complete_tree(leaves) return np.fromiter(tree_set, dtype=np.int64)
4bfc1ae01efd9595ef875613bd00d76f7c485421
3,643,698
import torch def pick_best_batch_size_for_gpu(): """ Tries to pick a batch size that will fit in your GPU. These sizes aren't guaranteed to work, but they should give you a good shot. """ free, available = torch.cuda.mem_get_info() availableGb = available / (1024 ** 3) if availableGb > 14:...
31d970697b417b40f8ef5b41fdeacc0e378543a0
3,643,699
def getTensorRelativError(tA, pA): """Get the relative error between two tensors.""" pA_shape = np.shape(pA) tA_shape = np.shape(tA) assert (pA_shape == tA_shape), "Arrays must be same shape" err = np.max(np.abs(np.array(pA)-np.array(tA))) return err
ea79bcebd5a39c020cdb5b35ee36dfe20b2f9c71
3,643,700
import itertools def eliminations(rct_gras, prd_gras): """ find eliminations consistent with these reactants and products :param rct_gras: reactant graphs (must have non-overlapping keys) :param prd_gras: product graphs (must have non-overlapping keys) Eliminations are identified by forming a bond b...
3acfb77d48223e1e31f7ce9b563bc5d86102b5b2
3,643,701
def sigmoid(*columns): """Fit a Sigmoid through the data of the last scan. The return value is a pair of tuples:: ((a, b, x0, c), (d_a, d_b, d_x0, d_c)) where the elemets of the second tuple the estimated standard errors of the fit parameters. The fit parameters are: * a - amplitude of ...
e9d031d07a8ef00b73634bb44ed6a94a1788f7c9
3,643,702
import re def MakeSamplesFromOutput(metadata, output): """Create samples containing metrics. Args: metadata: dict contains all the metadata that reports. output: string, command output Example output: perfkitbenchmarker/tests/linux_benchmarks/nccl_benchmark_test.py Returns: Samples containin...
2210caaf37a2fbfe768133e767754fb600435b0b
3,643,704
def tree_to_newick_rec(cur_node): """ This recursive function is a helper function to generate the Newick string of a tree. """ items = [] num_children = len(cur_node.descendants) for child_idx in range(num_children): s = '' sub_tree = tree_to_newick_rec(cur_node.descendants[child_idx])...
751d46dbb4e3a5204900601164410b5bf7f0578b
3,643,706
import torch def mdetr_efficientnetB3(pretrained=False, return_postprocessor=False): """ MDETR ENB3 with 6 encoder and 6 decoder layers. Pretrained on our combined aligned dataset of 1.3 million images paired with text. """ model = _make_detr("timm_tf_efficientnet_b3_ns") if pretrained: ...
0e80da12a9fec55ccdbfdb3dcf78806bff2c6f20
3,643,707
import math import itertools def _check_EJR_brute_force(profile, committee): """ Test using brute-force whether a committee satisfies EJR. Parameters ---------- profile : abcvoting.preferences.Profile A profile. committee : iterable of int A committee. Returns -------...
f993daf9628ecad18fe25894ccd5fb8882d3e596
3,643,708
def read_stanford_labels(): """Read stanford hardi data and label map""" # First get the hardi data fetch_stanford_hardi() hard_img, gtab = read_stanford_hardi() # Fetch and load files, folder = fetch_stanford_labels() labels_file = pjoin(folder, "aparc-reduced.nii.gz") labels_img = nib...
8c9e5a3586125e7ffe3f9fe36b734ca7c19de53f
3,643,709
import urllib def _WrapRequestForUserAgentAndTracing(http_client, trace_token, trace_email, trace_log, gcloud_ua): """Wrap request with user-agent, and trace reporting. Args: http_client: The ...
d6a2a4c127670aa8409cb39a81833a5a5e3fba90
3,643,710
def indexData_x(x, ukn_words): """ Map each word in the given data to a unique integer. A special index will be kept for "out-of-vocabulary" words. :param x: The data :return: Two dictionaries: one where words are keys and indexes values, another one "reversed" (keys->index, values->words) ...
3f6ffd97d33400c3418b78ad3b383766cc07bee3
3,643,711
def BFS_TreeSearch(problem): """ Tree Search BFS Args->problem: OpenAI Gym environment Returns->(path, time_cost, space_cost): solution as a path and stats. """ node = Node(problem.startstate, None) time_cost = 0 space_cost = 1 if node.state == problem.goalstate: return buil...
b2523dea8b9813e2582a0acef27b0d46bb1a14b9
3,643,712
from typing import Tuple from typing import Optional def _objective_function(extra_features: jnp.ndarray, media_mix_model: lightweight_mmm.LightweightMMM, media_input_shape: Tuple[int, int], media_gap: Optional[int], ...
f8ae8185d84d811dc1d5796aa8374127d2f16ea5
3,643,714
from typing import Union from functools import reduce def decode_block(block: np.ndarray) -> Union[np.ndarray, bool]: """ Decode a data block with hamming parity bits. :param block: The data block to be decoded :return the decoded data bits, False if the block is invalid """ if not block.siz...
c9ed9eb03271e2222aa62260461aaa7ee90eb842
3,643,715
def occupancy(meta, ax=None): """ Show channel occupancy over time. """ if ax is None: f, ax = plt.subplots() f.set_figwidth(14) f.suptitle("Occupancy over time") start_time = meta.read_start_time.min() / 10000 / 60 end_time = meta.read_end_time.max() / 10000 / 60 to...
f6505a5bf7ff417194457ee2e04118edea9e6738
3,643,716
def reg1_r_characteristic(r, s, alpha, beta, c, h): """ evaluate x - ((4/3)r - (2/3)s)t in region 1, equation 19 """ # when s < 0 the expression can be factored and you avoid the # difference of nearly equal numbers and dividing by a small number # equation 74 rr = r/c ss = s/c pol...
9802483289387b7996665fe8f061d4393ff0daaf
3,643,717
from typing import Tuple def olf_gd_offline_in_z(X: np.ndarray, k: int, rtol: float = 1e-6, max_iter: int = 100000, rectY: bool = False, rectZ: bool = False, init: str = 'random', Y0=None, Z0=None, verbose: bool = False, alpha=1, ...
2397b0d24fa8fa9b8ddb9d7dd8553bd076feeb39
3,643,718
def get_cluster_codes(cluster: pd.Categorical) -> pd.Series: """Get the X location for plotting p-value string.""" categories = cluster.cat.categories.rename("cluster") return pd.Series(range(len(categories)), index=categories, name="x")
bb6899e5245c14e47ac855fef95775c282a8ed0f
3,643,720
import math import copy def _expand_configurations_from_chain(chain, *, pragma: str = 'pytmc', allow_no_pragma=False): """ Wrapped by ``expand_configurations_from_chain``, usable for callers that don't want the full product of all configurations. """ def hand...
b1282a9cf65875be3e91c3f0eb09a73f0130ccf9
3,643,721
import base64 def encrypt(data=None, key=None): """ Encrypts data :param data: Data to encrypt :param key: Encryption key (salt) """ k = _get_padded_key(key) e = AES.new(k, AES.MODE_CFB, k[::-1]) enc = e.encrypt(data) return base64.b64encode(enc)
668a5e94ea6d1adddb038f5cab1f0d165bb98bb0
3,643,722
def box_in_k_largest(boxes, box, k): """Returns True if `box` is one of `k` largest boxes in `boxes`. If there are ties that extend beyond k, they are included.""" if len(boxes) == 0: return False boxes = sorted(boxes, reverse=True, key=box_volume) n = len(boxes) prev = box_volume(boxes[...
e941513e47db5fb09e21b96933c629cf3c39bf49
3,643,724
def diagonal(a, offset=0, axis1=0, axis2=1): """ Returns specified diagonals. If `a` is 2-D, returns the diagonal of a with the given offset, i.e., the collection of elements of the form a[i, i+offset]. If `a` has more than two dimensions, then the axes specified by axis1 and axis2 are used to dete...
64ada8a83fd1162e7d84e84007be0263cd71bd0c
3,643,725
def available_number_of_windows_in_array(n_samples_array, n_samples_window, n_advance): """ Parameters ---------- n_samples_array n_samples_window n_advance Returns ------- """ stridable_samples = n_samples_array - n_samples_window if stridable_samples < 0: print("...
cab937efe4408d4707b601d4a0a68782d062ab36
3,643,726
import torch def tensor_to_image(tensor: torch.tensor) -> ndarray: """ Convert a torch tensor to a numpy array :param tensor: torch tensor :return: numpy array """ image = TENSOR_TO_PIL(tensor.cpu().clone().squeeze(0)) return image
fb3f16ec6cee1c50d2b7e6f2e31bd94aa300cdfd
3,643,727
def shimizu_mirioka(XYZ, t, a=0.75, b=0.45): """ The Shinizu-Mirioka Attractor. x0 = (0.1,0,0) """ x, y, z = XYZ x_dt = y y_dt = (1 - z) * x - a * y z_dt = x**2 - b * z return x_dt, y_dt, z_dt
60e5b52e1755de8bcc966364d828d47b05af3723
3,643,728
def draw_cap_peaks_rh_coord(img_bgr, rafts_loc, rafts_ori, raft_sym, cap_offset, rafts_radii, num_of_rafts): """ draw lines to indicate the capillary peak positions in right-handed coordinate :param numpy array img_bgr: the image in bgr format :param numpy array rafts_loc: the locations of rafts ...
c180a23d7ad6a04d8e56a61a0cb5e058bf1e5d95
3,643,729
def pack_bidirectional_lstm_state(state, num_layers): """ Pack the hidden state of a BiLSTM s.t. the first dimension equals to the number of layers. """ assert (len(state) == 2 * num_layers) _, batch_size, hidden_dim = state.size() layers = state.view(num_layers, 2, batch_size, hidden_dim).trans...
de102ce55deceb5ca7211def122dc2767c35cdd3
3,643,731
import copy def _create_record_from_template(template, start, end, fasta_reader): """Returns a copy of the template variant with the new start and end. Updates to the start position cause a different reference base to be set. Args: template: third_party.nucleus.protos.Variant. The template variant whose ...
62c9ff204cff3887daad0df4f710cc54f9c8dad9
3,643,732
import time def convert_time(time_string): """ Input a time in HH:MM:SS form and output a time object representing that """ return time.strptime(time_string, "%H:%M")
f34b46fe8cd242ee12a9768102486cba243d94df
3,643,735
from typing import Union import torch def get_distributed_mean(value: Union[float, torch.Tensor]): """Computes distributed mean among all nodes.""" if check_torch_distributed_initialized(): # Fix for runtime warning: # To copy construct from a tensor, it is recommended to use # sourceT...
9643b522e838a3a0aabcfab7021d4bac7d58e21d
3,643,736
def js_div(A, B): """ Jensen-Shannon divergence between two discrete probability distributions, represented as numpy vectors """ norm_A = A / A.sum() norm_B = B / B.sum() M = (norm_A+norm_B)/2 return 0.5 * (kl_div(norm_A,M)+kl_div(norm_B,M))
1e4ac763d01f3ae3d25907d24229301d464de527
3,643,737
from typing import Dict def _build_request_url( base: str, params_dict: Dict[str, str]) -> str: """Returns an URL combined from base and parameters :param base: base url :type base: str :param params_dict: dictionary of parameter names and values :type params_dict: Dict[str, str]...
30e27cf55692884be408218403c2f94279516ad2
3,643,738
def aesDecrypt(key, data): """AES decryption fucnction Args: key (str): packed 128 bit key data (str): packed encrypted data Returns: Packed decrypted data string """ cipher = python_AES.new(key) return cipher.decrypt(data)
15c70d0699a22bf58ca191ba2fea2d5eb7942b1b
3,643,739
def __format_number_input(number_input, language): """Formats the specified number input. Args: number_input (dict): A number input configuration to format. language (dict): A language configuration used to help format the input configuration. Returns: dict: A formatted number inpu...
0cd76b74396c013d7f76ae5ae11ace56db6552ab
3,643,740
def get_players(picks): """Return the list of players in the team """ players = [] for rd in picks: play = list(rd.keys()) players = players+play players = list(set(players)) return players
79963bc19af662d44d4eaf29a04995ede331706c
3,643,741
def verify_file_details_exists(device, root_path, file, max_time=30, check_interval=10): """ Verify file details exists Args: device ('obj'): Device object roo...
da0e33ca67b9e70dc4b5345ba626a193bcdefdbd
3,643,742
import collections from typing import Literal def generateVoID(g, dataset=None, res=None, distinctForPartitions=True): """ Returns a new graph with a VoID description of the passed dataset For more info on Vocabulary of Interlinked Datasets (VoID), see: http://vocab.deri.ie/void This only makes ...
66f8b5824017fd41995783c75de72451d22ea023
3,643,743
def extract_screen_name_from_twitter_url(url): """ Function returning the screen_name from a given Twitter url. Args: url (str) : Url from which we extract the screen_name if found. Returns: str : screen_name if the url is a valid twitter url, None otherwise. """ parsed_twitt...
3bbc00f2b4fb0aa0b49154d37802a50204f05ccf
3,643,744
def sub_vectors(a, b): """Subtracts two vectors. Args: pos1 (tuple[int]): first position pos1:(tuple[int]): second position Returns: tuple[int]: element wise subtraction Examples: >>> sub_vectors((1,4,6), (1,3,7)) (0, 1, -1) """ return tuple(a[i] - b[i]...
02c35bf46311142a3f3e90cd803d908c6ff63896
3,643,745
def get_prediction_info(predicted_one_hot, predicted_int, y_test, PLOTS_DIR, filename = "test_file"): """ Saves useful information for error analysis in plots directory :param predicted_one_hot: :param predicted_int: :param y_test: :param PLOTS_DIR: :return: """ def get_info_for_labe...
76d95c3793ee29c211d7f32e727e9bf046c075eb
3,643,746
def save_excel_file(): """File save dialog for an excel file. Returns: str: file path """ return pick_excel_file(save=True)
392c014a959a6d61cfa02ca041d0496560df4dec
3,643,747
def load_app_paths(file_path=None, dir_path=None, user_file_path=None, user_dir_path=None, default=None, paths=None, **kwargs): """Parse and merge user and app config files User config will have precedence :param file_path: Path to the base config file :param dir_path: Path to the e...
d5f6fe9b8db396f95656d80fea19dc0f95fba642
3,643,748
def search_playlists(spotify_token, playlist): """ :param spotify_token: :param playlist: :return: """ return _search(spotify_token, query=playlist, type='playlist', limit=9, market='ES', offset=0)
cf2ab61a4f967c8cb570471c3fdea2c772d85e8d
3,643,749
import re def text_pre_process(result): """ 이미지에서 인식된 글자를 정제 합니다. 특수문자 제거, 1-2단어 제거, 줄바꿈 및 공백 제거 :param result: 이미지에서 인식된 글자 :return: 문자를 전처리한 결과 """ copy = str(result) copy2 = copy.replace("\n", "") copy3 = re.sub('[^ㄱ-힗]', '', copy2) # re.sub('[^A-Za-z0-9]', '', copy2) result = re.sub('[-=+,#}/\{:^$.@...
c9a25fb19a723d38eb19a8a086a2134369223ea1
3,643,750
def get_conventional_std_cell(atoms): """Given an ASE atoms object, return the ASE atoms object in the conventional standard cell. It uses symmetries to find the conventional standard cell. In particular, it gives a structure with a conventional cell according to the standard defined in W. Setyawan, an...
78bf131e8f195bd25b424627d6cce2d5295de248
3,643,752
def get_if_rcnn(inputs: Tensor): """ :param inputs: Tensor from Input Layer :return: """ # get back bone outputs if_backbones_out = backbones(inputs) return if_backbones_out
02507f10e4dc791b1f201d2c08d3925f2a2dacb5
3,643,753
import string import secrets def method_3(num_chars: int): """ Pythonicish way of generating random password Args: num_chars (int): Number of Characters the password will be Returns: string: The generated password """ chars = string.ascii_letters + string.digits + string.punc...
03fc383ef8c45f1bc618daf4b70646ea824e31df
3,643,754
def get_animation_for_block( block_start: int, frame_num: int, total_frames: int, duration: int=5, ): """Generate CSS to pop a block from gray to red at the right frame block_start: int frame_num: int total_frames: int duration: int # seconds""" animation_function = gray_...
9ce9a36a5c7ca5161b89a3306c7e38c9c03d2ee0
3,643,755
def find_student_by_username(usuario_id, test=False): """Consulta toda la información de un estudiante según su usuario.""" query = 'SELECT * FROM estudiante WHERE id_usuario = %s' return execute_sql(query, args=[usuario_id], rows=1, test=test)
ecc67992aef2257d35ccc6dfa05c01afc3d40bb3
3,643,756
def reduce_mem_usage(df, use_float16=False): """ Iterate through all the columns of a dataframe and modify the data type to reduce memory usage. """ start_mem = df.memory_usage().sum() / 1024 ** 2 print("Memory usage of dataframe is {:.2f} MB".format(start_mem)) for col in df.columns: ...
842e9c134cd5211fdbe75b0626efa48f68d90c35
3,643,757
def create_global_step() -> tf.Variable: """Creates a `tf.Variable` suitable for use as a global step counter. Creating and managing a global step variable may be necessary for `AbstractTrainer` subclasses that perform multiple parameter updates per `Controller` "step", or use different optimizers on different...
786ac18f78f092e099844d99b33f5232f53d8a8a
3,643,759
def rl_label_weights(name=None): """Returns the weight for importance.""" with tf.variable_scope(name, 'rl_op_selection'): num_classes = get_src_num_classes() num_choices = FLAGS.num_choices logits = tf.get_variable( name='logits_rl_w', initializer=tf.initializers.zeros(), shape...
b1157c508cb256ab9608ebd78dfbb1ef90cec2b5
3,643,760
from scipy.stats import mannwhitneyu from statsmodels.sandbox.stats.multicomp import multipletests from typing import List import tqdm def run_de_test(dataset1: Dataset, dataset2, test_cells: List[str], control_cells: List[List[str]], test_label: str = None, control_group_labels: list...
422082785845918f7e999125b7e57e6c1fbcb535
3,643,761
def say_hello_twice(subject): """Says hello twice using `say_hello`.""" return say_hello(subject) + " " + say_hello(subject)
66a6fafca01f6ddc6304fef15aea27bb15c23416
3,643,762
def get_zones(ec2): """ Return all available zones in the region """ zones = [] try: aws_zones = ec2.describe_availability_zones()['AvailabilityZones'] except ClientError as e: print(e.response['Error']['Message']) return None for zone in aws_zones: if zone['State'] == 'available': ...
acd023bcf5863aff0cd562f6c097062d9693738d
3,643,763
import torch def x_gate(): """ Pauli x """ return torch.tensor([[0, 1], [1, 0]]) + 0j
736d72d832380ea5a1d6c4a840cb6aa0050638e5
3,643,764
def merge_dictionaries(default_dictionary, user_input_dictionary, path=None): """Merges user_input_dictionary into default dictionary; default values will be overwritten by users input.""" return {**default_dictionary, **user_input_dictionary}
ea600efcd69e920ae536fa2f22a4c883a71d8ad3
3,643,765
def create_frequencyvector(T_end, f_max_requested): """ A function to create the vector of frequencies we need to solve using the reflectivity method, to achieve the desired length of time and highest modelled frequency. NOTE: Because we require the number of frequencies to be odd, the maximum frequency may...
d402840259bdc0049c580e057a6de815dfaa02f1
3,643,766
def get_fiber_protein_intake( nutrients_lower_lists, nutrients_middle_lists,nutrients_upper_lists): """Gets financial class-wise fibee and protein intake data.""" lower_fiber_prot = nutrients_lower_lists.map(lambda x: (x[1], x[3])) middle_fiber_prot = nutrients_middle_lists.map(lambda x: (x[1], x[3...
990293236a10ed18960393b39dbfb46652fca51d
3,643,767
def _add_fvar(font, axes, instances, axis_map): """ Add 'fvar' table to font. axes is a dictionary mapping axis-id to axis (min,default,max) coordinate values. instances is list of dictionary objects with 'location', 'stylename', and possibly 'postscriptfontname' entries. axisMap is dictionary mapping axis-id...
20836c91121603610f5bfb19777e4b6f440f2007
3,643,768
import tqdm def init_nornir(username, password): """INITIALIZES NORNIR SESSIONS""" nr = InitNornir( config_file="network_automation/topology_builder/graphviz/config/config.yml" ) nr.inventory.defaults.username = username nr.inventory.defaults.password = password managed_devs = nr.filt...
edf6a45a2ce9dc7799351892c1b53ab2b949607c
3,643,769
def _format_rest_url(host: str, append: str = "") -> str: """Return URL used for rest commands.""" return f"http://{host}:8001/api/v2/{append}"
1d5ace3919da004e648cb6c7d6d80fe72903c0e1
3,643,770
from typing import Optional from typing import Set def get_synonyms(prefix: str) -> Optional[Set[str]]: """Get the synonyms for a given prefix, if available.""" entry = get_resource(prefix) if entry is None: return None return entry.get_synonyms()
44e4fc7259f9536dc192a08566b8db7f9256f916
3,643,772
def results(request): """ Returns the actual body of the search results, for AJAX stuff """ query = request.GET.get("q", "") if len(query) >= 4: ctx = _search_context(query, request.user) return TemplateResponse(request, "search/results.html", ctx) return TemplateResp...
a6282dd489e3406ebc8b2349159b58d4cb0e1fd4
3,643,773
def is_correlated(corr_matrix, feature_pairs, rho_threshold=0.8): """ Returns dict where the key are the feature pairs and the items are booleans of whether the pair is linearly correlated above the given threshold. """ results = {} for pair in feature_pairs: f1, f2 = pair.split("__"...
18afa0cc24f5d9205cde3c8ad23f70d73b5c395b
3,643,774
def find_password(liste, login): """ """ for user in liste: if user[0] == login: return user[1] return None
8f61072a8b1cc34eb27c1665b1cd34aeb6630ce2
3,643,775
def sample_weather_scenario(): """ Generate a weather scenario with known values for the wind condition. """ times = pd.date_range('1/1/2000', periods=72, freq='6H') latitude = np.linspace(0, 10, 11) longitude = np.linspace(0, 10, 11) wsp_vals = np.full((72, 11, 11), 10.0) wdi_vals = np....
124f43b090149bb23e52a88a03c441d1311c5bea
3,643,776
import torch def ToTensor(pic): """Converts a PIL.Image or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]. """ if isinstance(pic, np.ndarray): img = torch.from_numpy(pic.transpose((2, 0, 1))) return img.float().div(255) if pic.mode ==...
c3ed682c520f17f24169377b2a3016510e9724f9
3,643,778
def part2(data): """ >>> part2([[43, 19], [2, 29, 14]]) 105 >>> part2([[9, 2, 6, 3, 1], [5, 8, 4, 7, 10]]) 291 >>> part2(read_input()) 32528 """ deck_one = tuple(data[0]) deck_two = tuple(data[1]) _, winning_deck = combat(deck_one, deck_two) return score(winning_deck)
226eb835030716cdfa30310e53bc76c5dd3a4e7e
3,643,779
def dehyphenate(string): """Remove hyphenated linebreaks from 'string'.""" return hyphen_newline_re.sub("", string)
6894fd7972c3990fd00e5818e0b30e48e78017e0
3,643,781
def grounder(img, dtype=None): """Tries to remove absolute offset 'img' must be a 3 colors image""" shape = img.shape """ # Mise en forme a = img.reshape((shape[0] * shape[1], 3)) min = np.zeros(a.shape) max = np.zeros(a.shape) # Minimas/maximas min[:,0] = min[:,1] = min[:,2] =...
55a022a26f457cf0ec76d4ed8fa37f470db31e11
3,643,782
def arch_prob(arch, dims, **kwds): """ Returns the combined probability of for arch given values """ values = dict(kwds) dimkeys = list(dims.keys()) assert isinstance(arch, (tuple, list)), "Archictecture must be tuple or list" serial = isinstance(arch, list) probs = [None] * len(arch) for i, subarch in ...
94778c471d4ae3fe534af50543ef9465a6b2e793
3,643,783