content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch def create_mock_target(number_of_nodes, number_of_classes): """ Creating a mock target vector. """ return torch.LongTensor( [np.random.randint(0, number_of_classes - 1) for node in range(number_of_nodes)] )
0892fcea085dab7df3633720c69466ac958f3e3d
55,668
def string_of_error(return_code: int) -> str: """Decode the TREXIO exit code. Argument is an integer return code that correspond to one of the TREXIO errors. Returns string that contains description of TREXIO ~return_code~. """ try: error_str = pytr.trexio_string_of_error(return_code) ...
ec6a391cdb1051080ebe93dfb07e5d59f5a9f996
55,669
from typing import Optional def get_float(message: str = "Choose a number", title: str = "Title", default_value: float = 0.0, min_: float = -10000, max_: float = 10000, decimals: int = 3) -> Optional[float]: """ Simple dialog to ask a user to select a floating point number within a certain r...
809fb85f96eed285c4a301a9a263866aa3fed697
55,670
def score_filter(predictions, min_score): """Remove prediction bounding boxes with probability under a threshold Parameters ---------- predictions : dict all predictions min_score : int threshold score Returns ------- dict filtered predictions """ new_p...
28f8c0604f3dabc76ffbda911357d0bdd5bd5331
55,672
import math def plot_connectivity( epoch, fig=None, locations=None, calc_type="correlation", pair_list=[], threshold=0, show_sphere=True, readjust_sphere="auto", colormap="RdBu_r", vmin=None, vmax=None, line_width=None, title=None, colorbar=True, caption=Non...
450362f28beb17dd36b066f786a8023abb8e939e
55,673
def consolidate(*levels): """ Arranges list of object dictionaries levels into a hierarchical data structure, based upon the attribute "parent" Must pass arguments in ascending order (e.g. children, parents, grandparents) """ # consolidated = list(levels) # modify copy consolidate...
7cb064d3651767732c979ba34952a0a8c8962eb0
55,674
def verbose_name_plural(obj): """Return model verbose name in plural mode.""" if isinstance(obj, models.Model): type(obj)._meta.verbose_name_plural return obj._meta.verbose_name_plural
df05ace5cd8927ba5549cf601148554bc69f34b0
55,675
import struct def decode_option(packet, offset): """Decode a navdata option.""" id_nr, size = struct.unpack_from("HH", packet, offset) end_offset = offset + size data = packet[offset + struct.calcsize("HH"):end_offset] return id_nr, data, end_offset
c0ada56ba1f227a9db74b6d090496b3cfdbb1041
55,676
def split_range_into_groups( n, group_size, which_group_complete="last"): """Partitions `n` elements into adjacent groups, each with `group_size` elements Group number starts from 0 and increments upward Can be used to generate groups for sliding window aggregation. ...
aba2d19fa52f44dc0817290efb9fcea9a9209845
55,677
import math def getsteps(tspan, h): """ Given a timespan and a timestep h, return the number of steps. """ t1, t2 = tspan return int(math.floor((t2-t1)/h))
a10e0a4302352be6eafb9fad8e00005b9c79dd27
55,678
def mds(data, variables=None): """ Python implementation of the MDS coordinates calculated by the CCG program corrmat when set to 'ordination' mode. MDS coordinates are calculate from the correlation matrix .. seealso:: 1. Deutsch, M. V, & Deutsch, C. V. (2013). A Program to Calculate and...
5cbe72605825bc49fd41addf3c13cdb143279808
55,679
from typing import Union def boolean(value: Union[bool, str, float] = False) -> bool: """ Return boolean from string. """ if isinstance(value, bool): return value elif isinstance(value, str): value = value.lower().strip()[0] if value in ["y", "t"]: return True ...
4f1db3e1224e0633c5d663e6ae85a8ae19c51624
55,680
from typing import List def solve( context: mgp.ProcCtx, points: List[mgp.Vertex], method: str = DEFAULT_SOLVING_METHOD ) -> mgp.Record(sources=List[mgp.Vertex], destinations=List[mgp.Vertex]): """ The tsp_module solver returns 2 fields whose elements at indexes are correlated * `sources` - element...
6662f6e353441dbfb360684829a30fd4c542f616
55,681
def convert_dataset_to_samples(dataset, max_span_length, ner_label2id=None, context_window=0, split=0): """ Extract sentences and gold entities from a dataset """ # split: split the data into train and dev (for ACE04) # split == 0: don't split # split == 1: return first 90% (train) # split =...
c060cccfbf6892999cf9ccd0ee2f72f0e2e9a6f8
55,683
def build_bin_mask(n,chrs,zoom_dict,chr_dict,chr_bin_range,bin_positions,axis=None): """build a 1D mask (x or y axis) based upon user chr/coor selection """ bin_mask=np.zeros(n,dtype=bool) # build bin mask based on user chr/zoom selection for c in chrs: c_ind=chr_dict[c] r=c...
bd651489e524c89826f8d59b4acab0dad66b3da0
55,685
def fill_nnz( mat: "sp.csr_matrix", all_nnz: "np.ndarray[int]", fill_value: float = 1e-9 ) -> sp.csr_matrix: """ Given an input sparse matrix and a superset of nonzero coordinates, fill the matrix to ensure all values in the set are stored explicitely with the value of fill_value. Parameters ...
08fa0f5de958adf0608a69937839e131ceaaba85
55,686
def maxima(array): """ get the index of the maximum value in a 2D array""" return np.unravel_index(array.argmax(), array.shape)
a64de68bbdda70a9dd789769f6c7334d23f9eb6a
55,687
def strip_noise_from_key_signature(key): """Removes any unneccessary characters (7,9,11,m,M etc...)""" #Change this to a map or something key = key.replace('9', '') key = key.replace('7', '') key = key.replace('5', '') key = key.replace('m', '') key = key.replace('M', '') return key
5aa910f96dce275f9e4b6af7926179e73a2c313d
55,688
def validate_digits(digits): """Validate digits parameter.""" if digits is None: return None try: digits = int(digits) except ValueError as e: raise ValidationError("Digits must be a valid integer value") from e if digits < 6 or digits > 8: raise ValidationError("Digi...
0b1ef0f6b71efeb7b08379ff3d899f5aaa6c7a46
55,689
def inet_aton(ipaddress): """ Convert an IP address in presentation format to its integer octet format """ return struct_unpack("<I", struct_pack("<B<B<B<B", \ *map(int, ipaddress.split("."))))[0]
12d97f46bc57d353c23124d2936d951475a6981a
55,690
def create_cdr(src_cdr, dst_visit): """ Create cdr """ dst_cdr, _ = dst.Cdr.get_or_create( cdr_id=src_cdr.cdr_id, subject_visit_id=dst_visit.subject_visit_id, memory=src_cdr.memory, orientation=src_cdr.orientation, judge_prob_solving=src_cdr.judge_prob_solving, c...
1f8d5431c6010a207efe5e305e60a3e0089a941a
55,692
def derived_something(): """ A docstring template to describe the function. This function is part of the unit test template Returns ------- An string with the word output """ print("This message shows that you have successfully imported \ the derived_something() function from the ...
97586600645d87c557a1ebeb83e0f9e3a5c1381f
55,693
def calculate_percent(x, y): """ 计算百分比 :param x: 分子 :param y: 分母 :return: 百分比 """ x = float(x) y = float(y) return safe_div(x, y) * 100
d63e33462995573f4bab1e8bdc35c6d3eea98f9d
55,694
def plot_histogram(filename, mydata, bins = 10, title = None, xlabel = None, ylabel = None, dpi = 150, figsize = (10,10), tfont = 17, lfont = 14): """ Plots a histogram for scalar timeseries. """ fig = plt.figure(figsize = figsize) plt.hist(mydata, bins = bins) if title: plt.title(title,...
06cd0b9a88fb4dbab67061a6cc188ba8bde50c3a
55,695
def _darknet_body(x, for_small=False): """Darknent body having 52 Convolution2D layers""" x = _darknet_conv_bn_act(32, (3, 3), "block1_conv1")(x) x = _darknet_resblocks(x, 64, 1, block_index=2, downsampling=not for_small) x = _darknet_resblocks(x, 128, 2, block_index=3) x = _darknet_resblocks(x, 256...
8fbfc4475c05c57c5c5119e601e3cdcf082b1280
55,696
from typing import List import random import string def get_addresses(n=50) -> List[dict]: """ Generate random addresses """ def _get_address() -> dict: return { "name": "John Doe", "companyName": "Test Co", "streetAddress": "{} Test St".format(random.randi...
e125abb419cfeb9e06c2c0930f5e3082baa01b72
55,697
def share_post_friends(request, author_id, post_id): """ **[Internal]** <br> ## Description POST to the endpoint to reshare a post. the server will create a new, reshared post, and forward it to the corresponding followers' inboxes. ## Request nothing, but requires to be authenticated as t...
54964d3179c25b3f8e2c4d317f69ad81996bf0b2
55,698
def equal_weighting(X, types): """ Calculate criteria weights using objective Equal weighting method Parameters ---------- X : ndarray Decision matrix with performance values of m alternatives and n criteria types : ndarray Returns ------- ndarray ...
a769da203c9c10a488d650c11272bb544b523133
55,699
def prelu(features, initializer=None, scope=None): """ Implementation of [Parametric ReLU](https://arxiv.org/abs/1502.01852) borrowed from Keras. """ with tf.variable_scope(scope, 'PReLU', initializer=initializer): alpha = tf.get_variable('alpha', features.get_shape().as_list()[1:]) pos ...
f0d4e9f32f314bdc541085e18e76c24cb7bb536a
55,700
def create(hilbert, site): """ Builds the boson creation operator acting on the `site`-th of the Hilbert space `hilbert`. If `hilbert` is a non-Bosonic space of local dimension M, it is considered as a bosonic space of local dimension M. :param hilbert: The hilbert space :param site: the ...
b775520a9b366e097cbfbedfd6b229580dfc52c3
55,701
async def list_items(): """ Get all items """ items = await get_all_objects('items') return items
e38e3f8f12928c10ce9b627f6ef5da7a2ce67c61
55,702
import re def url_matches(pattern): """An expectation for checking the current url. pattern is the expected pattern, which must be an exact match returns True if the url matches, false otherwise.""" def _predicate(driver): return bool(re.search(pattern, driver.current_url)) return _predic...
c7a613efff1828c5cf79471e3bc534f78fade3fc
55,703
def create() -> MailboxID: """ Create a new mailbox. :returns: The mailbox unique identifier """ mid = str(uuid4()) mailbox_registry = context_mailbox_registry.get() mailbox_registry[mid] = trio.open_memory_channel(0) return mid
dbb02fd1dcfd731f614b8ad6267eb31661f6ea1a
55,704
import math def layout_roboport_row(bus, width): """Return layout for a row of roboports covering an x region out to width, including the bus lines needed. """ layout = Layout("roboports") # Underpasses. Note these are shorter underpasses, without pumps. for bus_pos, line in enumerate(bus): bus_x = BUS_STAR...
d9d933fea140fc9e83cff893d38561533f18fbb5
55,705
def open_threads_window(*args): """ open_threads_window() -> TWidget * Open the threads window ( 'ui_open_builtin' ). @return: pointer to resulting window """ return _ida_kernwin.open_threads_window(*args)
838986349ea25321c3d36a6996d56a80f4d76ca3
55,706
def delete(ground_station_id): """JRPC method: configuration.gs.delete Deletes the ground station identified by the given 'ground_station_id'. It also deletes all channels associated to this ground station. :param ground_station_id: Identifier of the Ground Station """ segment_models.GroundStat...
763f13b68857113cb52c0d30c5e4f6efa44c6454
55,707
from sage.misc.superseded import deprecation def standard_form(sp): """ Deprecated in :trac:`14140`. Use :meth:`SetPartition.standard_form()` instead. EXAMPLES:: sage: map(sage.combinat.set_partition.standard_form, SetPartitions(4, [2,2])) doctest:1: DeprecationWarning: standard_form...
c6efcae436f517497e24cd0602e112da927426dd
55,708
def article(text, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", transla...
6eafaedf9d53ca0269162093688b301b8ed77d53
55,709
def question_reply_committees(): """ A list of those committees that have received questions and replies. We might want to generalise this at some point """ items = Committee.for_related(QuestionReply).all() return send_api_response(serializers.queryset_to_json(items, count=len(items)))
137b8b4abb3ae92d7b2344e43c00618f095f7a1e
55,710
def select_cross_event(slclist, event_date, num_igrams=None): """Choose a list of independent igrams spanning `event_date`""" insert_idx = np.searchsorted(slclist, event_date) num_igrams = num_igrams or len(slclist) - insert_idx # Since `event_date` will fit in the sorted array at `insert_idx`, then ...
c8b2c74115edf14e66b1c72a3798931d7a6a8300
55,712
def host_list_route(): """list hosts""" return render_template('storage/host/list.html')
22ad2c63f93b478280887c80b901d495533b56ee
55,713
import re def _prepare_date(from_date): """ Private function to prepare from_date by converting it to YYYY-MM-DD format. """ # check if from_date was provided and if it was provided in the right # format from_date_str = None if from_date is not None: if not isinstance(from_date...
2766138027a1a2cc89e66370d792e2a317f6aa21
55,714
def ssa_full(time_series, embedding_dim=20, reconstruct_components=np.arange(10)): """ combine SSA decomposition and reconstruction together """ pc, s, v = ssa_decompose(time_series, embedding_dim) time_series_reconstructed = ssa_reconstruct(pc, v, reconstruct_components) return time_series_re...
6ad6c0b02af9b0513dbdeb94d647c64481b7c31f
55,715
def create_corpus_dir(corpus): """Create the directory to hold the various forms of the corpus written to disk. :param corpus: a corpus model object. :returns: an absolute path to the directory for the corpus. """ corpus_dir_path = get_corpus_dir_path(corpus) h.make_directory_safely(corpus...
0b206cd7f3451806538971f6722f6dbd1cc6d742
55,717
from datetime import datetime def fixtures(request, week): """ render the fixtures full page """ #get closest week from today's date today = datetime.datetime.now().strftime(settings.DATE_FORMAT) if week: if not isWeekValid(week): raise Http404 else: we...
cf001f0409d017eb749d8e67c3e4075f737f58c4
55,718
import copy import torch def get_loss(cfg_loss): """ Build the loss with the proper parameters and return it. Parameters ---------- cfg_loss : dict Dictionary containing the name of the loss to use and it's specific configs. Returns ------- loss_function : function Th...
88bacc521eee93c2a8c8d73a829a57f5d02bfdbd
55,719
def coplanar_points(points: ty.Union[ty.List['Point'], np.ndarray], tol: ty.Optional[float] = None) -> bool: """Returns True if the poins are coplanar Parameters ---------- points : List[Point], np.ndarray The list of points or MxN array of point coords tol : float, None...
d0920136020b1e9424053be13a296d5c764f5aac
55,720
from datetime import datetime def dev_offline(file): """ do online prediction. each time make prediction for one instance. you can change to a batch if you want. :param line: a list. element is: [dummy_label,text_a,text_b] :return: """ def convert(line, bmeo_label, attr_label): fe...
1e9ee43d5399bcec423506987e8a0048078acfe9
55,721
def select(data: xarray.DataArray, max_seen_frac) -> xarray.DataArray: """ Removes stationary stations from data, based on histogram of SSID. 1. get a list of all the BSSIDs seen across time 2. get SSIDs that are not seen persistently vs. time The code below is not necessarily the most efficient ...
a232217f02345943bea2b365ffd70d9f54085730
55,722
def _fix_params(params): """For v1 api -- True is True but False is a string""" for key, val in params.items(): if val is False or str(val).lower() == 'false': params[key] = 'False' elif str(val).lower() == 'true': params[key] = True return params
1629cf618153c10169e2b963c99f06ef2e453075
55,725
def printDihedral(dihedral): """Generate dihedral line Parameters ---------- dihedral : dihedral Object dihedral Object Returns ------- dihedralLine : str dihedral line data """ V1 = dihedral.V1*0.5*kcalToKj V2 = dihedral.V2*0.5*kcalToKj V3 = dihedral.V3*0....
4d8ff81a6361e86d6ab8f7fc865aa8ea36a3aad1
55,726
def getNDEllipse(u, v, pt): """ Get an N-dimensional ellipse point cloud Parameters ---------- u: ndarray(1, N) First axis v: ndarray(1, N) Second axis pt: ndarray(M) Parameterization in the interval [0, 1] """ t = 2*np.pi*pt t = t[:, None] return np.c...
ef95d9eef5dba75a8eec46db3c07e6e1cf25b2c2
55,728
import csv def difference(old_file, new_file): """ Make a difference between an old csv file and a new one; get the full row if it's different :return: """ old_results = list(csv.reader(open(old_file, 'r'), delimiter=';')) new_results = list(csv.reader(open(new_file, 'r'), delimiter=';')) ...
dc5f346a17d96cf8c10b71135d8ed0d133d1089b
55,729
def bte_float_input(than, text='', error_text="Enter number between ", error_text_format_bool=True, error_text_format="Enter number great and less or equal than {}", pause=True, pause_text_bool=True, pause_text='Press Enter...', clear=True, error_text_input="Enter float number!",...
b7ae0e2846d998f5b928dfa791a557eb915cb01c
55,730
def get_public_key_bytes_compressed(public_key: ec.EllipticCurvePublicKey) -> bytes: """Return the bytes of a pubkey in the compressed format.""" return public_key.public_bytes(Encoding.X962, PublicFormat.CompressedPoint)
7661f0e28e3aec45508a1ba2dc3e5ce7501eae72
55,731
def __generate_adaptive_random_samples(input_points, aspect_ratio_scaling, centralized, num_samples=8182, bandwidth=0.2): """ Generates samples for Lloyd relaxation, following the density distribution of the input data. Args: input_points (List[float]): 1D-Arr...
0e9654e5773871e005d266e9ade2d9e44a1b4498
55,732
def split_nav_dataframe(nav_table, split_date): """ Split NAV pandas DataFrame into a training and a testing DataFrame according to a split_date, such that split_date becomes the last date of the training DataFrame. Args: - split_date (datetime.datetime) Returns: - train: th...
78c6ae901641b3508d2a9f9c790be6d576cf8458
55,733
def get_episodes_count(episode_list, max_val): """ This method is used to count the count of episode_list value which is bigger than 30 :param episode_list: :return: """ return len([x for x in episode_list if x > max_val])
fc49154c644c1807e818e0b598c680878e342767
55,734
def find_groups_in_cluster(clustervs, elementgroupList): """ A utility function to find vertices with the same cluster memberships. :param igraph.vertex clustervs: an igraph vertex instance :param list elementgroupList: a list containing the vertices to group :returns: a list-of-list...
7cc941d086d7be7c7395e21f6bde1cd4e5611851
55,735
def calculate_CE_per_group(samples, test_contribs, group_names, all_groups_toks, n_words_per_contrib): """ Calculates the Cross-Entropy between each combination of groups. :param samples: contributions for training snapshot models. :param test_contribs: contributions for comparing to snapshots. :pa...
8ae9ba2baffcdaae4d5b63ec2440bc30bbccfc50
55,736
def svn_io_file_checksum2(*args): """svn_io_file_checksum2(char const * file, svn_checksum_kind_t kind, apr_pool_t pool) -> svn_error_t""" return _core.svn_io_file_checksum2(*args)
35cd0c60bc9da84d401842d455e0079a9e69aac1
55,738
from datetime import datetime import logging def parse_date_arg(arg_str, oldest_allowed_date=None, max_days_since_now=None): """Parse request arg as date with limits on oldest allowed date or max days since now. Accepts date format %Y-%m-%d. Args: arg_str: str request arg to parse. oldes...
108e1c95968f50845156c9ae6a76373e661f1cd4
55,740
import csv def readbalfour(fname): """returns list of lists representing balfour csv""" with open(fname, "r") as f: reader = csv.reader(f, delimiter="\t", quotechar="\"") return list(reader)
d48071ff01bee67c13c38a6ca0ed22064b6bdca6
55,741
def computeCycleConsistencyLoss(x, x2, y, y2): """ This function is used to compute the cycle consistency loss The equation is Equation(6) in Chp6 :param x: :param x2: :param y: :param y2: :return: """ # MSE Loss and Optimizer criterion = nn.MSELoss() c_loss = criterion(x...
e8ccfdf19970034073ce94630caa3b7a2c13da6c
55,742
def post_kwargs(body: BodyModel, query: QueryModel): """ Basic example with both query and body parameters, response object serialization. This time using the decorated function kwargs `body` and `query` type hinting """ # save model to DB id_ = 3 return ResponseModel(id=id_, age=query.age,...
d7aac311a54bbfdd69af878c0af71318a0d9cda8
55,744
def getMeanDouble_Image8(Image): """getMeanDouble_Image8(Image) -> double""" return _ImageFunctions.getMeanDouble_Image8(Image)
d79ecce92a26af4e601e131d83fc5be2567a4eb2
55,745
def vbObjectInitialize(size=None, objtype=None, preserve=None): """Return a new object with the given size and type""" if size is None: size = [0] # # Create the object def getObj(): if len(size) == 1: return objtype() else: return vbObjectInitialize(...
aa68220018cf7982787c2e67598f89fe1383c4c4
55,746
def sam_to_sortbam_cl(data, tx_out_file, name_sort=False): """Convert to sorted BAM output. Set name_sort to True to sort reads by queryname """ samtools = config_utils.get_program("samtools", data["config"]) cores, mem = _get_cores_memory(data, downscale=2) tmp_file = "%s-sorttmp" % utils.spli...
3e3cbc5ed3c3b852c3846cc9a9b95c3144db96a3
55,747
import html from typing import Container def page(): """Creates a page for demands""" team_id, set_team_id = use_state("") epic_id, set_epic_id = use_state("") year_month, set_year_month = use_state("") days, set_days = use_state("") is_event, set_is_event = use_state(False) return html.di...
9788087f99d60ba0dcb1c6fc948f237be128432b
55,749
import torch def create_mock_data(num_nodes, num_features, num_classes=3, eta=0.1, p=0.2): """ Creating a mock feature matrix, edge index and edge weight. """ (A_p_scipy, A_n_scipy), labels = SSBM(num_nodes, num_classes, p, eta) X = torch.FloatTensor(np.random.uniform(-1, 1, (num_nodes, num_featur...
9ee11920e99f5ef3a857a72370a1e4de1d0fcb16
55,750
def loss_v0(args, pred, target, conf, cost): """loss version 0 Arguments are * args: command line arguments entered by user. * pred: prediction result of each exit point. * target: target prediction values. * conf: confidence value of each exit point. * cost: cost rate of ...
d9a6be3b321fe279e7e05cd28158bc202e4657c1
55,751
def rmsd(V, W): """ Calculate Root-mean-square deviation from two sets of vectors V and W. Parameters ---------- V : np.array (N,D) matrix, where N is points and D is dimension. W : np.array (N,D) matrix, where N is points and D is dimension. Returns ------- fit : f...
bab88a8e149f0f20c5c8aca4153b0da880517628
55,752
import json def sync_ckan_allowed_users_by_resource(*args, **kwargs): """Synchroniser `ckan-restricted` pour le cas particuliers des autorisations par organisation. """ def get_all_users_for_organisations(organisation__in): filter = {'organisation__in': organisation__in, 'or...
1398ef166793223980489aa73b60c0afe3c1b12b
55,753
import base64 def numpy_to_b64str(img, format="JPG"): """ Converts a numpy array into a base 64 string Args: img (np.array): the image represented as an Numpy Array format: The format of the image to be converted into Returns: str: base 64 representation of the numpy array/im...
f58f7e95d09fdca6e5d968dde368b7f01adc7081
55,754
def resource_schedule( tag_value: celtypes.Value, ) -> celtypes.Value: """ Reach into C7N and use the the :py:class:`c7n.filters.offhours.ScheduleParser` class to examine the tag's value, the current time, and return a True/False. This parser is the `parser` value of the :py:class:`c7n.filters.o...
162fa3cdd0d5ec6dbf8203acdbf6bd44e6744c22
55,755
import json def parse_history_event(directive_result): """Based on the type of event, parse the JSON.serializable portion of the event.""" event_type = directive_result.event_type if event_type is None: raise ValueError("EventType is not found in task object") if event_type == HistoryEventTyp...
fba04a9d2c1ddf8dbaad0b9c92a04847cb65ed87
55,756
def get_private_key(cert_arn): """ Checks if an ACM certificate has an associated private key stored in an SSM parameters, and returns the value. """ param_name = get_ssm_param_name(cert_arn) try: response = ssm.get_parameter( Name=param_name, WithDecryption=Tr...
1f392fb24ee912bc10b27ed4324657d5f69a633b
55,758
def unparse_vs(tup): """version list to string""" return '.'.join(map(str, tup))
4c4f4d8fb02bffd676b2a4d87118eaf55cb0afe8
55,761
import base64 def encryptstring(text, password): """ Encrypt a string according to a specific password. :type text: string :param text: The text to encrypt. :type pass: string :param pass: The password to encrypt the text with. """ enc = [] for i in enumerate(text): key_...
46142bc54828058bf131834fa13276da78e90842
55,762
from typing import Tuple def ts2xy(data_frame: pd.DataFrame, x_axis: str) -> Tuple[np.ndarray, np.ndarray]: """ Decompose a data frame variable to x ans ys :param data_frame: the input data :param x_axis: the axis for the x and y output (can be X_TIMESTEPS='timesteps', X_EPISODES='episodes' or...
444286f2391be76944d059cda4e0954b2f7d05c7
55,763
import fractions def strategy_for_grain_attribute(attr, grain_type=None): """Returns a default strategy for generating data compatible with a particular attribute of a particular grain_type :param attr: a string, the name of an attribute of one of the GRAIN subclasses :param grain_type: some grains types...
487ca42bcdcef1bc8beeccbdec623387ae522fc4
55,764
def ldns_dnssec_zone_sign_nsec3_flg_mkmap(*args): """LDNS buffer.""" return _ldns.ldns_dnssec_zone_sign_nsec3_flg_mkmap(*args)
aec6df122fd6eed61e21b39011f46091dcd8129d
55,766
import torch def DSConv(in_channels: int, out_channels: int, stride: int = 1, **kwargs): """Depth-wise separable convolution followed by a 2D convolution each followed by a batch normalization and ReLU activation. """ return torch.nn.Sequential( torch.nn.Conv2d( in_channels, in_cha...
89df37f79ff9bd6c6fe31c3001bb6d725fac8a2a
55,767
def hist_from_samples(x, num_bins=100): """Returns a histogram with the specified number of bins from the array of samples, x""" x_density = np.histogram(x.ravel(), bins=num_bins)[0] + 1 return x_density / np.sum(x_density)
086921df1def87718732523e4f54202c59a22a54
55,768
import torch def compute_cer(predictionBatch, targetBatch, predictionLenBatch, targetLenBatch): """ Function to compute the Character Error Rate using the Predicted character indices and the Target character indices over a batch. CER is computed by dividing the total number of character edits (comput...
696b64308eb2786d013f210cae0557087392c4ba
55,769
import torch def top_pool(x): # from right to left """ :param x:feature map x, a Tensor :return: feature map with the same size as x """ x_p = torch.zeros_like(x) x_p[:, :, :, -1] = x[:, :, :, -1] _, _, h, w = x.size() for col in range(w - 1, -1, -1): x_p[:, :, :, col] = x[:, ...
7222d018a59270daf4041109e7979718ff4c68a6
55,770
def test_learning_four_mode_Interferometer(): """Finding the optimal Interferometer to make a NOON state with N=2""" np.random.seed(11) ops = [ Sgate( r=np.random.uniform(size=4), phi=np.random.normal(size=4), r_trainable=True, phi_trainable=True, ...
900fd7daa53197b92e2e248ea8c4420a064a53e0
55,771
def slug(name): """ Slugifies a division name. """ return unidecode(str(name).lower().translate({ ord(' '): '_', ord("'"): '_', ord('-'): '_', # dash ord('—'): '_', # m-dash ord('–'): '_', # n-dash ord('.'): None, }))
44683b7cd04182a0d8e7fbc42072f1ecfa3b18fa
55,772
def status(request): """API view for status list""" data = list(Faculty.objects.values_list('status', flat=True).distinct().order_by('status')) # wrap in list(), because QuerySet is not JSON serializable return JsonResponse(data, safe=False)
39f419d31f4488e4d2e062d6a42117f9208ea9b4
55,773
def ns(relative_name): """Return a full name from a name relative to the tested module"s name space.""" return NS + "." + relative_name
3ab9f1213c6f3b139c29d11685d27ecf1b7bf587
55,774
def listofdict_topn_sorter(raw_listofdict, attr_key, reverse=True): """ 对 list of dict 数据结构排序 :param raw_listofdict: :param attr_key: 指定要排序的attr, eg 分数高低,成本高低. :param reverse: True 倒排从大到小. :return: 1) raw数据不变 2)排序后返回原始index 3)排序后可获得需求attr. """ sorted_res = sorted(enumerate(raw_listofdict...
8dfb7a60dd7e904d99a3896908cd213d34e1a922
55,775
from scipy.optimize import linear_sum_assignment as linear_assignment def eval_acc(y_true, y_pred): """ Calculate clustering accuracy. Require scikit-learn installed. # Arguments y: true labels, numpy.array with shape `(n_samples,)` y_pred: predicted labels, numpy.array with shape `(n_samp...
03935f1916f15627e2bbf4c016af252ba54b7854
55,777
def read_nii_bysitk(input_fid, peel_info = False): """ read nii to numpy through simpleitk peelinfo: taking direction, origin, spacing and metadata out """ img_obj = sitk.ReadImage(input_fid) img_np = sitk.GetArrayFromImage(img_obj) if peel_info: info_obj = { "spacin...
0a8af67bd348c9170cc0b5abddb691da433e0f5f
55,778
def build_user_secrets(seed: bytes, name: str, seed_method: SeedMethod = SeedMethod.SEED_METHOD_BIP39, password: str = '') -> KeyPairSecrets: """ Build a valid key pair secrets for User. :param seed: User key seed :param name: User key name :param seed_m...
bc138f2cc803d5029bf1db03d31454a2baf98ed9
55,779
def _get_answers_on_path(answers, schema, routing_path) -> AnswerStore: """ Get any answers that are on the routing path and return an answer store. """ answers_to_remove = [answer for answer in answers if not _is_answer_on_path(schema, answer, routing_path)] answers_on_path = answers.copy() f...
57578ff326246f34ab6da605f9b7304552f197ea
55,780
def e_mag2frac(errmag): """Convert mag error to fractionary flux error""" return 10.**(.4 * errmag) - 1.
470415550968f0db7dc016c41b4c1f0552ba9893
55,781
def compare_user(passed_user=None, user_list=None): """Check if supplied User instance exists in supplied Users list and, if so, return the differences. args: passed_user (User): the user instance to check for differences user_list (Users): the Users instance containing a list of Users instance...
9f00a7548bc67075b491305f0d43b4f8c859f62f
55,782
def choose_template_by_blasr(fasta_filename, out_filename, nproc=8, maxScore=-1000, min_number_reads=1): """ Choose the best template for gcon reference Pick the one that has the highest average hit identity to others Returns: FastaRecord of selected ref """ fd = Fa...
588f503d0cb910c7fc8db92e537e7c77568cdee1
55,783
def check_padding(query): """ Check for missing padding in base64 encoding and fill it up with "=". :param query: :return: query """ missing_padding = len(query) % 4 if missing_padding: query += "=" * (4 - missing_padding) return query
d8ad3c96074d311dbd5ba17bb93d7ca7a8b5ccab
55,784
import inspect def _get_method_classname(m): """Get class name for method, assuming method is bound and class has __dict__.""" for k, v in inspect.getmembers(m): if k == "__qualname__": return v return "<unknown>"
88edafc4e3319ad32e2a77feed4dfb7e14f1bd4c
55,785