content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
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
import os def test_file(rel_path): """ Return the absolute path of the given test file. """ return os.path.join(PACKAGE_DIR, "tests", rel_path)
a27b67b6972b0e204ecaf0cf3b316ee34a316ec2
55,711
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 filter_stories(stories, triggerlist): """ Takes in a list of NewsStory-s. Returns only those stories for whom a trigger in triggerlist fires. """ # TODO: Problem 10 # This is a placeholder (we're just returning all the stories, with no filtering) # Feel free to change this line! ...
c52ef4718a144941a11dca22011fb4501e01d9b4
55,716
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 HostInfoToMessage( host_info_entity, devices=None, host_update_state_entity=None): """Convert a HostInfo entity into a HostInfoMessage.""" device_infos = [ToMessage(device) for device in devices or []] next_cluster_ids = list(host_info_entity.clusters or []) device_count_summaries = [ ToMessage(c)...
b1e161a9d4f7c847e06db8e549bece18fe7d27e2
55,723
import torchvision def deeplabv3_resnet50_features(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on Coco """ model = torchvision.models.segmentation.deeplabv3_resnet50(pretrained=pretrained, aux_loss=False) # bac...
6b8fa9a95067a2a48bf64786ef4b2268f1d7f75f
55,724
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
import os import subprocess def pull(path, url=None, username=None, password=None): """Fetch from and integrate with another repository or a local branch. If <url> is not given, will try to get the url of origin. Parameter: path : (str) Path from where git pull command will be executed ...
17dcaa97e21779709ad7c4a2392c667fcfc1be1c
55,727
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
import os def background_subtraction_parallel(frames_dir, background_path, num_processors=None): """Generate foregrounds corresponding to frames Args: frames_dir: path to directory containing frames background_dir: path to the background image num_processors: int returns: c...
a9bfc781bd94b03494b36d764543e5d0bcbd8d1a
55,737
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
def main(args): """ Commandline logic :param args: commandline arguments :type args: list|tuple :return: success returns 0 and failure returns 1 :rtype: int """ #/* ======================================================================= */# #/* Defaults #/* ===============...
c49bd5b1dfba487677912879903ea647b1ff4abb
55,739
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
import sys def large_surfaces_index(surface_dots_positions, eps): """Seach if there are more than one surfaces in surface_dots_positions, than return a np.array of booleans with True for index of atoms for the surfaces more points. surface_dots_positions: np.array with R3 dots. eps: minimun distan...
3eb4e103d68473235a9252eb1ed3f6b71362d6c2
55,743
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
from re import DEBUG import os def mip(input, bitmask, m=None, a=None): """ Maximum (minimum) intensity projection (MIP) along dimensions specified by bitmask. :param bitmask int: :param input array: :param m bool: minimum :param a bool: do absolute value first """ usage_string = "...
cfd1da18b042fe2e1f930e66988af372ec5ee03e
55,748
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
from re import DEBUG import sys def minres(ctx, institution, requirement_id): """ minres : MINRES (num_classes | num_credits) display* tag?; This is actually only a header production """ if DEBUG: print(f'*** minres({class_name(ctx)}, {institution}, {requirement_id})', file=sys.s...
abe470f185be43029a4fd4af1d0935c91f899a21
55,757
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 clip_range(img_numpy): """ Cut off outliers that are related to detected black in the image (the air area) """ # Todo median value! zero_value = (img_numpy[0, 0, 0] + img_numpy[-1, 0, 0] + img_numpy[0, -1, 0] + \ img_numpy[0, 0, -1] + img_numpy[-1, -1, -1] + img_numpy[-1, -1, 0...
b8a6916b7adb059614e1689b1ace1c942810b123
55,759
from typing import List import os def get_packages( path: str, ) -> List[str]: """Get list of packages under a path.""" packages = [] for file_or_dir in os.listdir(path): file_or_dir_path = os.path.join(path, file_or_dir) if os.path.isdir(file_or_dir_path): dir_name = file_...
0bb6397cd80e3549ca6f0f74007367a40ba5d2c1
55,760
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
import os def commonprefix(path1,path2): """Determine common prefix path for path1 and path2 Use this in preference to os.path.commonprefix as the version in os.path compares the two paths in a character-wise fashion and so can give counter-intuitive matches; this version compares path components...
9122b8339ae53e4a646af7783dba388e83a41756
55,765
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
def product_energy(cmdp, capacity, targets=[]): """Explicit encoding of energy into state-space The state-space of the newly created MDP consists of tuples `(s, e)`, where `s` is the state of the input CMDP and `e` is the energy level. For a tuple-state `(s,e)` and an action $a$ with consumption (in th...
c3f7dacb9608917ebfe1e2a1eb3155769e757796
55,776
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
import pip def parse_pip_version(pip_version=None): """ :return: (major,minor,micro) pip version """ if not pip_version: try: pip_version = pip.__version__ except AttributeError as e: raise Exception('Failed to get pip version: ', str(e)) if not pip_ver...
8c71356b8ccf6bbbcc980732df84bd168b1df8f9
55,786
import ast import sys def check(codeString, filename, verbosity=1): """ Check the Python source given by C{codeString} for flakes. @param codeString: The Python source to check. @type codeString: C{str} @param filename: The name of the file the source came from, used to report errors. ...
e4caf603ee46749e071e3af2477a4a587097335f
55,787
import subprocess def get_git_hash(): """Get short git hash, with "+" suffix if local files modified""" h = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).strip().decode("utf-8") # Add '+' suffix if local files are modified exitcode, _ = subprocess.getstatusoutput("git diff-index --...
ff05a71e4dd3001335e29de77c43df21a1698120
55,788
import string from functools import reduce from operator import concat import secrets def secret_token(size: int = 32) -> str: """ Generates a cryptographically secure, urlsafe random token based on the size. :param size: Size of the token, defaults to 32. :type size: int, optional :return: Toke...
2d7261a53911ce0764f022350753a6376b4f08e3
55,789
def get_per_class_matrix(y, classes=None): """ Create a (num_classes x num_examples) binary matrix representation of the true and predicted y values. If classes is None, class values will be extracted from y. Values that are not present at all will not receive a column -- this is to allow computatio...
1a517b73e98a3a6561910b6a215d1a0a47875743
55,790
def import_file(path=None, destination_frame="", parse=True, header=(-1, 0, 1), sep="", col_names=None, col_types=None, na_strings=None): """Have H2O import a dataset into memory. The path to the data must be a valid path for each node in the H2O cluster. If some node in the H2O cluster cannot s...
3f55bd3f78eadbaf7d5fd6ec1a1464bd5cde0e7e
55,791
def nms(bboxes, score_threshold, iou_threshold, sigma=0.3, method='nms'): """ :param bboxes: 假设有N个bbox的score大于score_threshold,那么bboxes的shape为(N, 6),存储格式为(xmin, ymin, xmax, ymax, score, class) 其中(xmin, ymin, xmax, ymax)的大小都是相对于输入原图的,score = conf * prob,class是bbox所属类别的索引号 :return: best_bboxes 假设NM...
d98d8c72474b8fb110abdbd025c575371029eb94
55,792
def _language_in_list(language, targets, max_distance=10): """ A helper function to determine whether this language matches one of the target languages, with a match score above a certain threshold. The languages can be given as strings (language tags) or as Language objects. `targets` can be any i...
fd714a4085f3e691fdfd7806a5ecf7b784b74a87
55,793
def test_ap_cipher_ccmp(dev, apdev): """WPA2-PSK/CCMP connection""" return check_cipher(dev[0], apdev[0], "CCMP")
0204ceb1db9529f133893d6d9a9a76355d460043
55,794
import sys import os import tempfile def can_symlink(): """Return whether running process can create symlinks.""" if sys.platform != 'win32': # Platforms other than Windows should allow symlinks without issues. return True if not hasattr(os, 'symlink'): # Older Python versions do ...
531de5c7fe92ba5dbd6fb149500e143034189098
55,795
def align(l, alignto=4): """Aligned length to nearest multiple of 4.""" return (l + alignto - 1) & ~(alignto - 1)
2bef7f1c3486c9e633138178d80216bf750ff2ed
55,796
def get_static_wx_help_page(): """ Return static WX help page. """ return \ """ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <!-- Natural Language Toolkit: Wordnet Interface: Graphical Wordnet Browser Copyright (C) 2001-2011 NLTK Proj...
6e94152f082cf4ba74756f5a5524513a6880f97e
55,797
def vtree_to_dot(vtree, mgr, litnamemap=None, show_id=False): # type: (Vtree, SddManager, Optional[LitNameMap], bool) -> str """Generate (alternative) Graphviz DOT string for given Vtree. This method is an alternative to Vtree.dot(). :param vtree: Vtree to plot :param mgr: SddManager associated wi...
db99f7c61773ef281541239387950f1d1a34e82f
55,798
import pandas import numpy def process_cpu(datapoint_streams): """ Process a CPU data retured by engine :param1 datapoint_streams: will have 1 stream with CPU data if there will be any data to process return: dataframe with #timestamp and util column """ cpu = None for stream in datapoint_streams...
6603231f55329fb03a0da2539ef3627f855cf168
55,799