content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import torch def get_default_device(): """ Using GPU if available or CPU """ if torch.cuda.is_available(): return torch.device('cuda') else: return torch.device('cpu')
ff65f896938b9e53b78d3a6578883129bc886204
31,700
def build_stateless_broadcaster(): """Just tff.federated_broadcast with empty state, to use as a default.""" return tff.utils.StatefulBroadcastFn( initialize_fn=lambda: (), next_fn=lambda state, value: ( # pylint: disable=g-long-lambda state, tff.federated_broadcast(value)))
6d78f3f452551cb2eb7640bb09ee7541c5a752bd
31,701
def getTestSuite(select="unit"): """ Get test suite select is one of the following: "unit" return suite of unit tests only "component" return suite of unit and component tests "all" return suite of unit, component and integration tests "pending" ...
1816286c04b8b7a2e994522622a5f567869cad48
31,702
from typing import Union from pathlib import Path def find_mo(search_paths=None) -> Union[Path, None]: """ Args: search_paths: paths where ModelOptimizer may be found. If None only default paths is used. Returns: path to the ModelOptimizer or None if it wasn't found. """ default_m...
4657e15649692415dd10f2daa6527cade351d8fc
31,703
def autoaugment(dataset_path, repeat_num=1, batch_size=32, target="Ascend"): """ define dataset with autoaugment """ if target == "Ascend": device_num, rank_id = _get_rank_info() else: init("nccl") rank_id = get_rank() device_num = get_group_size() if device_num ...
596eb26fe376298327900a240d07c89f6914f76d
31,704
def dropout_mask(x, sz, dropout): """ Applies a dropout mask whose size is determined by passed argument 'sz'. Args: x (torch.Tensor): A torch Variable object sz (tuple(int, int, int)): The expected size of the new tensor dropout (float): The dropout fraction to apply This method us...
ae6aebad62fa97014227f4ac68bca68f2eafe95f
31,705
def two_body_mc_force_en_jit(bond_array_1, c1, etypes1, bond_array_2, c2, etypes2, d1, sig, ls, r_cut, cutoff_func, nspec, spec_mask, bond_mask): """Multicomponent two-body force/energy kernel accelerated with Numba's njit de...
c027a874b1662d0b9c954302cc3d0b26f77f9a21
31,706
def customize_hrm_programme(**attr): """ Customize hrm_programme controller """ # Organisation needs to be an NS/Branch ns_only(current.s3db.hrm_programme.organisation_id, required=False, branches=False, ) return attr
3ef74f74e09b9c4498700b9f0d20245829d48c42
31,707
def freq_count(line, wrddict, win, ctxcounter, wrdcounter): """ Counts words and context words of a string. line: The sentence as a string. wrddict: Word index mapping. win: Word context window size. ctxcounter: Context Counter. wrdcounter: Word Counter. """ if not (isinstance(line, ...
87ebe01058f8958f5ffe06e0944068c10b26ae44
31,708
def _onehot_encoding_unk(x, allowable_set): """Maps inputs not in the allowable set to the last element.""" if x not in allowable_set: x = allowable_set[-1] return list(map(lambda s: x == s, allowable_set))
3b386c6640bd5e37a6ab2276e090c8ea56eed5ce
31,709
import re def getChironSpec(obnm, normalized=True, slit='slit', normmech='flat', returnFlat=False): """PURPOSE: To retrieve a CHIRON spectrum given the observation name (obnm).""" #extract the date (yymmdd) from the obnm: date = re.search(r'chi(\d{6})', obnm).group(1) #extract the core of the ob...
a29090e0838f93feeb8ad758beb1bd563b78178e
31,710
import posixpath def api_routes(api_classes, base_path='/_ah/api', regex='[^/]+'): """Creates webapp2 routes for the given Endpoints v1 services. Args: api_classes: A list of protorpc.remote.Service classes to create routes for. base_path: The base path under which all service paths should exist. If ...
47cd1da8300f010e1c3ef7ee8bca21d7139a40ad
31,711
def WrapReportText(text): """Helper to allow report string wrapping (e.g. wrap and indent). Actually invokes textwrap.fill() which returns a string instead of a list. We always double-indent our wrapped blocks. Args: text: String text to be wrapped. Returns: String of wrapped and indented text. "...
4818f0d777c8165fd7a762033379741781bf48af
31,712
import math def point_in_wave(point_x, frequency, amplitude, offset_x, offset_y): """Returns the specified point x in the wave of specified parameters.""" return (math.sin((math.pi * point_x)/frequency + offset_x) * amplitude) + offset_y
5a91c9204819492bb3bd42f0d4c9231d39e404d8
31,713
def tile(A, reps): """ Construct an array by repeating A the number of times given by reps. If `reps` has length ``d``, the result will have dimension of ``max(d, A.ndim)``. If ``A.ndim < d``, `A` is promoted to be d-dimensional by prepending new axes. So a shape (3,) array is promoted to (1, ...
446247517aaaaecff377571a14384a2bbd0c949f
31,714
import requests def get_super_user_token(endpoint): """ Gets the initialized super user token. This is one time, cant get the token again once initialized. Args: endpoint (str): Quay Endpoint url Returns: str: Super user token """ data = ( f'{{"username": "{consta...
bf5782fe3cc563b70d7fbd925b4f06e9d29fba1a
31,715
import torch def to_input_variable(sequences, vocab, cuda=False, training=True): """ given a list of sequences, return a tensor of shape (max_sent_len, batch_size) """ word_ids = word2id(sequences, vocab) sents_t, masks = input_transpose(word_ids, vocab['<pad>']) if type(sents_t[0][0]) !=...
3dea99cdf94a06ce3f1b1be02a49f0d8396cb140
31,716
def create_extreme_conditions_test_matrix(model, filename=None): """ Creates an empty test matrix for evaluating extreme conditions tests. After running this function, the user should edit the file and save with a separate filename to avoid overwriting. Todo: it would be good to make this automati...
d58e5ca0455c20b9b1dddb7b5bd448683294961f
31,717
def map_to_docs(solr_response): """ Response mapper that only returns the list of result documents. """ return solr_response['response']['docs']
2661b9075c05a91c241342151d713702973b9c12
31,718
def get_config_type(service_name): """ get the config type based on service_name """ if service_name == "HDFS": type = "hdfs-site" elif service_name == "HDFS": type = "core-site" elif service_name == "MAPREDUCE": type = "mapred-site" elif service_name == "HBASE": type = "hbase-site...
96793f932334eb8e4a5460767a80ee6a989cee22
31,719
def regression_model(X, y, alpha=.5): """ trains a simple ridge regession model Args: X: y: alpha: Returns: model """ reg = linear_model.Ridge(alpha=alpha, fit_intercept=True) # reg = linear_model.Lasso(alpha = alpha,fit_intercept = True) reg.fit(X, y) r...
f15741ac95a8738e031d6eb77f9d5bed76f4958d
31,720
def array2d_export(f, u2d, fmt=None, **kwargs): """ export helper for Util2d instances Parameters ---------- f : str filename or existing export instance type (NetCdf only for now) u2d : Util2d instance fmt : str output format flag. 'vtk' will export to vtk **kwargs : ke...
59c7962d24a688eabebe069500f49d01aef80c28
31,721
def not_daily(request): """ Several timedelta-like and DateOffset instances that are _not_ compatible with Daily frequencies. """ return request.param
e30563d0b6ee62cd995908045ddc356ca58b5796
31,722
from pandas.core.reshape.concat import concat import itertools from typing import List def get_dummies( data, prefix=None, prefix_sep="_", dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None, ) -> "DataFrame": """ Convert categorical variable into dummy/ind...
a3be8d5a3f56d438d1182254749b2967d7bf48fd
31,723
import io def get_call_xlsx(call, submitted=False, proposals=None): """Return the content of an XLSX file for all proposals in a call. Optionally only the submitted ones. Optionally for the given list proposals. """ if proposals is None: title = f"Proposals in {call['identifier']}" ...
2077b0b38262d4dff83ebaccc808da3a4e728992
31,724
import os def example_filename(fn): """ Return the full path of a data file that ships with gffutils. """ return os.path.join(HERE, 'test', 'data', fn)
2058bc3fd3c6e603f249855b9f55111f015b70c3
31,725
def to_array(t): """ Converts a taco tensor to a NumPy array. This always copies the tensor. To avoid the copy for dense tensors, see the notes section. Parameters ----------- t: tensor A taco tensor to convert to a NumPy array. Notes ------- Dense tensors export python's ...
29df47e3535c610954e8f1bae828af80ad6ae9f7
31,726
def perform_operation(operator_sign: str, num1: float, num2: float) -> float: """ Perform the operation on the two numbers. Parameters ---------- operator_sign : str Plus, minus, multiplication or division. num1 : float Number 1. num2 : float Number 2. Returns ...
e515a103a47b32e2a7197e10a1ad7a395433e7d9
31,727
def whitespace_tokenize(subtokens): """An implementation of BERT's whitespace tokenizer that preserves space.""" return split_subtokens_on( subtokens, lambda char: char.isspace(), are_good=True)
09e451a80b8df66ce0a4401bf3ff681dc9c1b1da
31,728
def moon_phase( ephemerides: skyfield.jpllib.SpiceKernel, time: skyfield.timelib.Timescale ) -> float: """Calculate the phase angle of the Moon. This will be 0 degrees at new moon, 90 degrees at first quarter, 180 degrees at full moon, etc. """ sun = ephemerides[Planets.SUN.value] earth = ...
8a24d3166816ba42f150866f89fbbfa98f418ed1
31,729
def fib_functools(n): """Return nth fibonacci number starting at fib(1) == 0 using functools decorator.""" # incorrect fib, but the tests expect it if n == 0: return 1 if n in [1, 2]: return n-1 return fib(n - 1) + fib(n - 2)
335908076cff922e9a27dbb2a50e88901fd7e637
31,730
def sync_filter(func, *iterables): """ Filter multiple iterable at once, selecting values at index i such that func(iterables[0][i], iterables[1][i], ...) is True """ return tuple(zip(*tuple(i for i in zip(*iterables) if func(*i)))) or ((),) * len( iterables )
7a2ab5e6356dadff0fe78d3f2bb0da584e0ff41b
31,731
def visit_hostname(hostname): """ Have a chance to visit a hostname before actually using it. :param hostname: The original hostname. :returns: The hostname with the necessary changes. """ for processor in [hostname_ssl_migration, hostname_tld_migration, ]: hostname = processor(hostname...
dd8d57a88bd5951d9748c362112954e4549cdd6c
31,732
async def wait_for_other(client): """Await other tasks except the current one.""" base_tasks = aio.all_tasks() async def wait_for_other(): ignore = list(base_tasks) + [aio.current_task()] while len(tasks := [t for t in aio.all_tasks() if t not in ignore]): await aio.gather(*task...
ab276973862fd89ba935d70fb2fb72dbd6fe7cfa
31,733
import os def find_stored_stat(directory, this_func, oresult): """ Compute stats from the data saved in a directory Input: directory -- location of json files to be scanned. this_func -- function to be run against the entries found oresult -- dictionary saving the results of this_...
1726997fe091e62c02395536bc1746fba4420f02
31,734
def register_series(series, ref, pipeline): """Register a series to a reference image. Parameters ---------- series : Nifti1Image object The data is 4D with the last dimension separating different 3D volumes ref : Nifti1Image or integer or iterable Returns ------- transformed_li...
3afefd4cf1f33cba1d04bd49437e33cfcfbdb578
31,735
import random def normal27(startt,endt,money2,first,second,third,forth,fifth,sixth,seventh,zz1,zz2,bb1,bb2,bb3,aa1,aa2): """ for source and destination id generation """ """ for type of banking work,label of fraud and type of fraud """ idvariz=random.choice(zz2) ...
469c0a88a77b083d666e938d4d13199987918e1d
31,736
def linear_diophantine(a, b, c): """Solve ax + by = c, where x, y are integers 1. solution exists iff c % gcd(a,b) = 0 2. all solutions have form (x0 + b'k, y0 - a'k) Returns ------- None if no solutions exists (x0, y0, a', b') otherwise """ # d = pa + qb p, q, d = extended_euc...
6b5fdebe7508249978ea97f0a40330d2ed2243b8
31,737
from operator import and_ def count_per_packet_loss(organization_id, asset_type=None, asset_status=None, data_collector_ids=None, gateway_ids=None, device_ids=None, min_signal_strength=None, max_signal_strength=None, min_packet_loss=None...
bc202c8e0e77921f74281ff58857659279dba8f7
31,738
def sample_nodes(g, p): """ Obtains a sampled network via Bernoulli node sampling. For each node in g, sample it with probability p, and add edge (i, j) only if both nodes i and j have been sampled. Parameters ---------------- g: a networkx graph object p: sampling probability for each node...
d623d232425b9d6099b49506c2ccec09ef512b1d
31,739
import os from datetime import datetime from pathlib import Path def JAlien(commands: str = '') -> int: """Main entry-point for interaction with AliEn""" global AlienSessionInfo, _JSON_OUT import_aliases() wb = None # Command mode interaction if commands: AlienSessionInfo['exitcode'] ...
b2d20fab45d1e598dd713343d69f45a36eecbcd0
31,740
import re def _slug_strip(value, separator=None): """ Cleans up a slug by removing slug separator characters that occur at the beginning or end of a slug. If an alternate separator is used, it will also replace any instances of the default '-' separator with the new separator. """ if sepa...
ade4274643191ee702fe39ccefccc5d68ed3a8cb
31,741
def get_segments_loudness_max(h5, songidx=0): """ Get segments loudness max array. Takes care of the proper indexing if we are in aggregate file. By default, return the array for the first song in the h5 file. To get a regular numpy ndarray, cast the result to: numpy.array( ) """ if h5.root.anal...
a65111b565686a57add325cc4c29d16b37aa89e8
31,742
def take_along_axis(arr, indices, axis): """ Takes values from the input array by matching 1d index and data slices. This iterates over matching 1d slices oriented along the specified axis in the index and data arrays, and uses the former to look up values in the latter. These slices can be differe...
84492b7ac09b26510dfe3851122587a702753b04
31,743
def _is_possible_grab(grid_world, agent_id, object_id, grab_range, max_objects): """ Private MATRX method. Checks if an :class:`matrx.objects.env_object.EnvObject` can be grabbed by an agent. Parameters ---------- grid_world : GridWorld The :class:`matrx.grid_world.GridWorld` instance ...
a57d120747199b84b3047d822547b5367d2b9905
31,744
def euclidean_distance_matrix(embeddings): """Get euclidean distance matrix based on embeddings Args: embeddings (:obj:`numpy.ndarray`): A `ndarray` of shape `[num_sensors, dim]` that translates each sensor into a vector embedding. Returns: A `ndarray` of shape `[nu...
5b50248a94eb926078a20fd5efbac83f115c26b0
31,745
def get_actor_id(name): """ Get TMDB id for an actor based on their name. If more than one result (likely), fetches the first match. TMDB results are sorted by popularity, so first match is likely to be the one wanted. """ search = tmdb.Search() search.person(query=name) # get id o...
ac75cbaac7dec85fd965d8cc421c6bbba8fc5f67
31,746
import json def generate_prompt( test_case_path, prompt_path, solutions_path, tokenizer, starter_path=None ): """ Generate a prompt for a given test case. Original version from https://github.com/hendrycks/apps/blob/main/eval/generate_gpt_codes.py#L51. """ _input = "\nQUESTION:\n" with ope...
ecd3218839b346741e5beea8ec7113ea2892571e
31,747
def projects_upload_to(instance, filename): """construct path to uploaded project archives""" today = timezone.now().strftime("%Y/%m") return "projects/{date}/{slug}/{filename}".format( date=today, slug=instance.project.slug, filename=filename)
01f97cf5994cca7265ede0a4b5c73672f61e2f90
31,748
def assign_employee(id): """ Assign a department and a role to an employee """ check_admin() employee = Employee.query.get_or_404(id) form = EmployeeAssignForm(obj=employee) employee.department = form.department.data employee.role = form.role.data db.session.add(employee) ...
f88a1b49cadf73d8a62c0be23742fd03cace36cd
31,749
import copy def autofocus(field, nm, res, ival, roi=None, metric="average gradient", minimizer="lmfit", minimizer_kwargs=None, padding=True, num_cpus=1): """Numerical autofocusing of a field using the Helmholtz equation. Parameters ---------- field: 1d or 2d ndarray ...
a954f96cf8c3c16dbdfb9ea31c22e61cac2a9245
31,750
def ZeroPaddedRoundsError(handler=None): """error raised if hash was recognized but contained zero-padded rounds field""" return MalformedHashError(handler, "zero-padded rounds")
b0ff8bb894505041382aaf2d79f027708c7a2134
31,751
def get_adj_mat(G): """Represent ppi network as adjacency matrix Parameters ---------- G : networkx graph ppi network, see get_ppi() Returns ------- adj : square sparse scipy matrix (i,j) has a 1 if there is an interaction reported by irefindex ids : list same length as adj, ith index con...
95ee8df6be45f12df8da93c7fed10a3c8a32a058
31,752
def load_ndarray_list(fname): """Load a list of arrays saved by `save_ndarray_list`. Parameters ---------- fname : string filename to load. Returns ------- la : list of np.ndarrays The list of loaded numpy arrays. This should be identical tp what was saved by `save_nd...
fc76373d45c8934bd81d6ac7e144dff97ae6d1c9
31,753
def save_result(data, format, options=UNSET) -> ProcessBuilder: """ Save processed data to storage :param data: The data to save. :param format: The file format to save to. It must be one of the values that the server reports as supported output file formats, which usually correspond to the sho...
be9e8f36869cbe2fdf7b938dfd59cf7b8743ff2a
31,754
def load_suites_from_classes(classes): # type: (Sequence[Any]) -> List[Suite] """ Load a list of suites from a list of classes. """ return list( filter( lambda suite: not suite.hidden, map(load_suite_from_class, classes) ) )
6c4b45c7ab99a3e3f7742f247ea65552c7c70927
31,755
import torch def update(quantized_model, distilD): """ Update activation range according to distilled data quantized_model: a quantized model whose activation range to be updated distilD: distilled data """ print('******updateing BN stats...', end='') with torch.no_grad(): for bat...
70e4cd9032e12f1f461c1cd13ac81ead06091728
31,756
from sys import path def save_chunks(chunk_sound, out_path, video_id): """ Saves chunked speech intervals as WAV file. :param chunk_sound: A parselmouth.praat Sound object # :param adjustment: The padding time on either side of target speech :param out_path: The output path of the wav file :param...
dda57e949e5a4a907082eb833dc6c91fd9fa7ec2
31,757
def _get_color(value): """To make positive DFCs plot green, negative DFCs plot red.""" green, red = sns.color_palette()[2:4] if value >= 0: return green return red
888edb2307bd6f4da65c6c1d5c0a40cb146dfa8c
31,758
def parse_feed(feed: str) -> list: """ Parses a TV Show *feed*, returning the episode files included in that feed. :param feed: the feed to parse :return: list of episode files included in *feed* """ try: root = ElementTree.fromstring(feed) except ElementTree.ParseError as error: ...
6fec9c1d71d3ae31480103dd2e6a2f5d81e12287
31,759
import subprocess def release_job(job_id): """ Release a job :param job_id: int, job id :return: if success, return 1, else return 0 """ try: step_process = subprocess.Popen(('qrls', str(job_id)), shell=False, stdout=subprocess.PIPE, stderr=subpr...
245ff5217cb6c62f01b5293e859facbf30f35d61
31,760
def head_finder(board_matrix): """ Function: head_finder() Description: this will find the head of your snake Input: board_matrix: This is an list of lists that represents the current board of Battle snake. Follows board_matrix[y][x] Output: head_xy: ...
e4682ac3b91e2023d3c9fe979762211df9978eec
31,761
def copy_emb_weights(embedding, idx2word, embedding_weights, emb_index_dict, vocab_size): """Copy from embs weights of words that appear in our short vocabulary (idx2word).""" c = 0 for i in range(vocab_size): w = idx2word[i] g = emb_index_dict.get(w, emb_index_dict.get(w.lower())) i...
e5d361efd342cc7e194ee325fdf4a98831121576
31,762
def cost_aggregation(c_v, max_d): """ the formula Lr(p,d) = C(p,d) + min[Lr(p-r, d),Lr(p-r, d-1)+p1,Lr(p-r,d+1)+p1,miniLr(p-r, i)+p2] - minkLr(p-r,k) :param c_v: :param max_d: :return: sum of all the Lr """ (H, W, D) = c_v.shape p1 = 10 p2 = 120 Lr1 = ...
71ff7bbbea8c3faebc8269d707198240c258c9c3
31,763
def send_approved_resource_email(user, request, reason): """ Notify the user the that their request has been approved. """ email_template = get_email_template() template = "core/email/resource_request_approved.html" subject = "Your Resource Request has been approved" context = { "sup...
52571470104e802ef9bcc491fa614a9420710df5
31,764
from sphinx.util.nodes import traverse_parent import warnings def is_in_section_title(node: Element) -> bool: """Determine whether the node is in a section title""" warnings.warn('is_in_section_title() is deprecated.', RemovedInSphinx30Warning, stacklevel=2) for ancestor in traverse_pa...
fb1e981e9ec8ad26cb49a144eb696d035dcbc2e8
31,765
def common_mgr(): """ Create a base topology. This uses the ExtendedNMLManager for it's helpers. """ # Create base topology mgr = ExtendedNMLManager(name='Graphviz Namespace') sw1 = mgr.create_node(identifier='sw1', name='My Switch 1') sw2 = mgr.create_node(identifier='sw2', name='My S...
e181b231bc859a6595417bbc63b695a00d7c3ae7
31,766
def reshape_array_h5pyfile(array,number_of_gatesequences,datapoints_per_seq): """reshaping function""" new_array = np.reshape(array,(number_of_gatesequences,datapoints_per_seq),order='F') #order is important, for data as column, #use order F, this will give an number_of_gatesequences x datapoints_per_seq ma...
c05edd9963396362f3f36f4293e28eb05fe22359
31,767
def build_value_counts_query(table: str, categorical_column: str, limit: int): """ Examples: SELECT {column_name}, COUNT (*) as frequency FROM `{table}` WHERE {not_null_str...
605e25310e3c91c693d72e7e4eae3c513cea2a8b
31,768
from pathlib import Path def get_model_benchmarks_data(benchmark_runlogs_filepath: Path): """ Return Python dict with summary of model performance for one choice of training set size. """ benchmark_genlog = read_json(benchmark_runlogs_filepath) benchmark_runlog = read_json(benchmark_runlogs_fi...
494e94a371a682e84f211204b189f3d17727f1c0
31,769
import collections def make_labels(module_path, *names, **names_labels): """Make a namespace of labels.""" return collections.Namespace( *((name, Label(module_path, name)) for name in names), *((n, l if isinstance(l, Label) else Label(module_path, l)) for n, l in names_labels.items()...
aaf0d204442bb9b712c2cf17babe45fd46905c8d
31,770
import socket def check_port_occupied(port, address="127.0.0.1"): """Check if a port is occupied by attempting to bind the socket and returning any resulting error. :return: socket.error if the port is in use, otherwise False """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: ...
4bf302f89793df47a28cb2bd608abd4344f40ff2
31,771
def test_heterogeneous_multiagent_env( common_config, pf_config, multicomponent_building_config, pv_array_config, ev_charging_config ): """Test multiagent env with three heterogeneous agents.""" building_agent ={ "name": "building", "bus": "675c", "cls": MultiCompone...
75939f0e548001ab34f411d15ae822cc7b1c1790
31,772
import requests from bs4 import BeautifulSoup def find_sublinks(artist_link): """Some artists have that many songs so we have multiple pages for them. This functions finds all subpages for given artist e.g if we have page freemidi/queen_1 script go on that page and seek for all specific hyperlinks. ...
3b24623d1cdbf4bf83f92a6e741576ff74e3facb
31,773
from unittest.mock import patch def class_mock(request, q_class_name, autospec=True, **kwargs): """Return mock patching class with qualified name *q_class_name*. The mock is autospec'ed based on the patched class unless the optional argument *autospec* is set to False. Any other keyword arguments are ...
08bd1aacf75784668845ace13af6514461850d1a
31,774
import inspect def kwargs_only(fn): """Wraps function so that callers must call it using keyword-arguments only. Args: fn: fn to wrap. Returns: Wrapped function that may only be called using keyword-arguments. """ if hasattr(inspect, 'getfullargspec'): # For Python 3 args = inspect.getful...
cc5bb7d4d31d1bb392c306410c3c22267e93e891
31,775
def _labeling_complete(labeling, G): """Determines whether or not LPA is done. Label propagation is complete when all nodes have a label that is in the set of highest frequency labels amongst its neighbors. Nodes with no neighbors are considered complete. """ return all(labeling[v] in...
130454cbb4a3bc77dfb94f97f20ad11e3239fb82
31,776
import _random def get_random_id_str(alphabet=None): """ Get random integer and encode it to URL-safe string. """ if not alphabet: alphabet = BASE62 n = _random(RANDOM_ID_SOURCE_BYTES) return int2str(n, len(alphabet), alphabet)
51d27c2838ccdd506e23aa2e707ac304e80c249c
31,777
def multivariate_normal_pdf(x, mean, cov): """Unnormalized multivariate normal probability density function.""" # Convert to ndarray x = np.asanyarray(x) mean = np.asanyarray(mean) cov = np.asarray(cov) # Deviation from mean dev = x - mean if isinstance(dev, np.ma.MaskedArray): ...
ce3c9171ee7cf78660118ecdab1949efce402827
31,778
def remove_below(G, attribute, value): """ Remove attribute below certain value Parameters ---------- G : nx.graph Graph attribute : str Attribute value : float Value Returns ------- G : nx.graph Graph """ # Assertions ...
8d60ce75d8334d5de52b877a9fcd6a9c826c7418
31,779
def format_header(header_values): """ Formats a row of data with bolded values. :param header_values: a list of values to be used as headers :return: a string corresponding to a row in enjin table format """ header = '[tr][td][b]{0}[/b][/td][/tr]' header_sep = '[/b][/td][td][b]' return ...
5b7cd734a486959660551a6d915fbbf52ae7ef1e
31,780
from typing import List from typing import Tuple import os def plot_confusion_matrix(cm: ndarray, classes: List[str], savefolder: str, filename: str = utils.timestamp() + '.png', figsize: Tuple[int, int] = (30,20))...
0d30a30d64844ca747b786fcb9257a2fdf438684
31,781
import random def getRandomWalk(initial_position: int, current_path: np.ndarray, adjacency_matrix: np.ndarray, heuristic: np.ndarray, pheromone: np.ndarray, alpha: float, max_lim: int, Q: float or None, R: float or None) -> np.ndarray: """ Function that given an array indic...
a19a33cea8aadd58d99f87bb3ef111ce33df1ce7
31,782
def sample_circle(plane="xy", N=100): """Define all angles in a certain plane.""" phi = np.linspace(0, 2 * np.pi, N) if plane == "xy": return np.array([np.cos(phi), np.sin(phi), np.ones_like(phi)]) elif plane == "xz": return np.array([np.cos(phi), np.ones_like(phi), np.sin(phi)]) eli...
1546c3e74b5ef1f7d43fa3352a708b5f7acf03ae
31,783
from pathlib import Path from datetime import datetime def generate_today_word_cloud(path='images/'): """ generate today word cloud Args: path (str, optional): [description]. Defaults to 'images/'. """ terms_counts = get_term_count() if terms_counts: word_cloud = generate_word...
f606135b181235eba5df4367d8721ff73e98af48
31,784
import importlib def load_attr(str_full_module): """ Args: - str_full_module: (str) correspond to {module_name}.{attr} Return: the loaded attribute from a module. """ if type(str_full_module) == str: split_full = str_full_module.split(".") str_module = ".".join(split_full[:...
f96dd56c73745e76ccc9c48dda4ba8a6592ab54b
31,785
from typing import Dict from typing import List import math def conv(node: NodeWrapper, params: Dict[str, np.ndarray], xmap: Dict[str, XLayer]) -> List[XLayer]: """ONNX Conv to XLayer Conv conversion function""" logger.info("ONNX Conv -> XLayer Conv (+ BiasAdd)") assert len(node.get_out...
7b004f41d103796ed01bc46e7dcff156171b35bd
31,786
def yices_bvconst_int32(n, x): """Conversion of an integer to a bitvector constant, returns NULL_TERM (-1) if there's an error. bvconst_int32(n, x): - n = number of bits - x = value The low-order bit of x is bit 0 of the constant. - if n is less than 32, then the value of x is truncated to ...
b676ea0ea5b25f90b60f2efd67af553d835daa9b
31,787
from scipy.special import comb def combination(n, k): """ 组合数 n!/k!(n-k)! :param n: :param k: :return: """ return comb(n, k, exact=True)
b87f9037decd765680e0e2d5b5dfea336e014b61
31,788
def insert_prize(conn, number, prize): """ Insert de premios """ try: cur = conn.cursor() logger.debug('INSERT PRIZE - "%s" / "%s"', number, prize) cur.execute(INSERT_PRIZE_QUERY, (number, prize, prize)) conn.commit() cur.close() return True except mysql.conn...
f75e4f5b78e189aebb794c11f7b7bd00d3bb4101
31,789
def create_carray(h5file_uri, type, shape): """Creates an empty chunked array given a file type and size. h5file_uri - a uri to store the carray type - an h5file type shape - a tuple indicating rows/columns""" h5file = tables.openFile(h5file_uri, mode='w') root = h5file...
ca4c9605905a44b5f3027024f78cc855136472b0
31,790
def sort_dictionary_by_keys(input_dict): """ Sort the dictionary by keys in alphabetical order """ sorted_dict = {} for key in sorted(input_dict.keys()): sorted_dict[key] = input_dict[key] return sorted_dict
225df2c16d2b21740603c224319ad4b0eaa0899d
31,791
def sorted_instructions(binview): """ Return a sorted list of the instructions in the current viewport. """ addrs = [] instructions = [] for ii in binview.instructions: if ii[1] not in addrs: instructions.append(instr(ii)) addrs.append(ii[1]) del addrs in...
5f8602b80a73fc4b66bbb6d2e70070f2e9e35397
31,792
def quick_sort(seq): """ Реализация быстрой сортировки. Рекурсивный вариант. :param seq: любая изменяемая коллекция с гетерогенными элементами, которые можно сравнивать. :return: коллекция с элементами, расположенными по возрастанию. Examples: >>> quick_sort([0, 5, 3, 2, 2]) [0, 2, 2, 3,...
46b56b5d29ca31a872e1805b66f4529a8bf48c6b
31,793
def _geocode(address): """ Like :func:`geocode` except returns the raw data instead. :param str address: A location (e.g., "Newark, DE") somewhere in the United States :returns: str """ key = _geocode_request(address) result = _get(key) if _CONNECTED else _lookup(key) if _CONNECTED ...
f6cee8c606c5fe014c6c67787e0a9bcee70a0281
31,794
def easeOutBack(n, s=1.70158): """A tween function that overshoots the destination a little and then backs into the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to...
bc5a0e34c2f7a16492c0456d8c28725888c6822c
31,795
def normalize_query_result(result, sort=True): """ Post-process query result to generate a simple, nested list. :param result: A QueryResult object. :param sort: if True (default) rows will be sorted. :return: A list of lists of RDF values. """ normalized = [[row[i] for i in range(len(row))...
1df57ef889be041c41593766e1ce3cdd4ada7f66
31,796
from typing import List def count_jobpairs(buildpairs: List) -> int: """ :param buildpairs: A list of build pairs. :return: The number of job pairs in `buildpairs`. """ counts = [len(bp['jobpairs']) for bp in buildpairs] return sum(counts)
30c345698400fd134456abcf7331ca2ebbfec10f
31,797
def unravel_params(nn_params, input_layer_size, hidden_layer_size, num_labels, n_hidden_layers=1): """Unravels flattened array into list of weight matrices :param nn_params: Row vector of model's parameters. :type nn_params: numpy.array :param input_layer_size: Number of units in th...
40703668ad74e4f6dbaf5c9c291da0c1c9528f60
31,798
def is_op_stack_var(ea, index): """ check if operand is a stack variable """ return idaapi.is_stkvar(idaapi.get_flags(ea), index)
b041cc56d8a0f772223b96cf5fa8bd6e338c777f
31,799