content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def gnome_sort(a): """ Sorts the list 'a' using gnome sort >>> from pydsa import gnome_sort >>> a = [5, 6, 1, 9, 3] >>> gnome_sort(a) [1, 3, 5, 6, 9] """ i = 0 while i < len(a): if i != 0 and a[i] < a[i-1]: a[i], a[i-1] = a[i-1], a[i] i -= 1 el...
05aca54513c6d441836aa7a60147b06b85b4e34d
51,007
def get_choices_roles(): """ Restituisce i ruoli utente (Admin/Operator) :return: """ try: return [(i.role, i.role) for i in agency.models.Role.objects.all().order_by('role')] except: return []
1212de6a8ae55a74a58eca3c79d4722f2c8ab043
51,008
def get_boxscore_from_game_id( cz_game_id : str ,**request_kwargs )->defaultdict: """Returns a curling boxscore (dict) based on the cz_game_id.""" url = 'https://www.curlingzone.com/game.php?1=1&showgameid=%s#1'%cz_game_id soup = make_soup(url=url,**request_kwargs) return _get_boxscore_from_g...
c2cdbd762ee2227b52294a3235e2f1a513d6e9a8
51,009
def lpf_smooth(s3d, a, b): """ :param s3d: K x J x 3 :param a: [5,] :param b: [5,] :return: """ lpf_num = len(a) s3d_y_ = [s3d[0].copy() for _ in range(lpf_num - 1)] s3d_x_ = np.pad(s3d, ((lpf_num - 1, 0), (0, 0), (0, 0)), 'edge') for i, s3d1f in enumerate(s3d_x_): if i ...
96debc682c2b31c48b0e8b99c9545c03768197fd
51,010
def STOK(df): """ Stochastic oscillator %K """ result = pd.Series((df['Close'] - df['Low']) / (df['High'] - df['Low']), name='SO%k') return out(SETTINGS, df, result)
d503f6ffd747bb40a20329c6f016c5e3185e81f2
51,011
def scaleLongSide(ip, longSide): """ Scale the image with respect to the longSide parameter (new size along the long side of the image should equal the longSide parameter) """ w = ip.width h = ip.height l = max(w,h) s = float(longSide)/l imp = ImagePlus('scaleLongSide',ip) IJ.run(imp, "Scale...", "x="+str(s)+" y...
59e217f9ace99ff13ed71bf4d5d242a97b1a8240
51,012
import joblib def load_pipeline(*, file_name: str) -> Pipeline: """Load a persisted pipeline.""" file_path = TRAINED_MODEL_DIR / file_name trained_model = joblib.load(filename=file_path) return trained_model
41cb259a03b0cbc4836f472bbbe0211ed0d03cd5
51,013
import logging def WIFI(frame, no_rtap=False): """calls wifi packet discriminator and constructor. :frame: ctypes.Structure :no_rtap: Bool :return: packet object in success :return: int -1 on known error :return: int -2 on unknown error """ pack = None try: ...
7a19774675cb251a156063ed4d1aeb70d9429430
51,014
import time def time_elapsed(func): """ 记录函数运行耗时的生成器 :param func: :return: """ @wraps(func) def wrapper(*args, **kwargs): timestamp = time.time() * 1000 ret = func(*args, **kwargs) now_ts = time.time() * 1000 elapsed = now_ts - timestamp print('%s c...
f83976cdc8a830aba6f24dbd34b33d0f30fc9718
51,016
def Weight(*args): """Weighting factor for this Sensor measurement with respect to other Sensors. Default is 1.""" # Getter if len(args) == 0: return lib.Sensors_Get_Weight() # Setter Value, = args lib.Sensors_Set_Weight(Value)
27129adee521053645364a2bdb6fe4681673697f
51,018
def load_from_arff(filename, labelcount, endian="big", input_feature_type='float', encode_nominal=True, load_sparse=False, return_attribute_definitions=False): """Method for loading ARFF files as numpy array Parameters ---------- filename : str path to ARFF file labelcount: integer ...
84bb27d193246eadec2cb9ec4ab61151570bd6b0
51,019
from typing import Callable from typing import Mapping from typing import List def hashimoto(dataset_lookup: Callable[[uint32_hash_array, int], uint32_hash]) -> Callable[[bytearray, bytearray, int, uint32_hash_array], Mapping[str, bytes]]: """ Decorator function. Returns the hashimoto algorithm. Args: ...
6cdad8a0552a99399bf32356af6f44c5005ed703
51,020
def run_in_thread_pool (*, callbacks = (), callbacks_kwargs = ()): """将函数放入线程池执行的装饰器""" def decorator (func): @wraps(func) def wrapper (*args, **kwargs): future = EXECUTOR.submit(func, *args, **kwargs) for index, callback in enumerate(callbacks): try: ...
311990156f275eb6932c921bc8fade3ea1413ec8
51,021
def evaluate_position(board, colour, legal_moves): """ Evaluation function for chess game """ white = chess.WHITE black = chess.BLACK pieces = {} # Counting pieces depeneding on colour wking = bin(board.occupied_co[white] & board.kings).count('1') wqueen = bin(board.occupied_co[white] & boar...
1b0dd2347a95a5c9f923d8d1950cf441e37adab0
51,022
def rotate_point_cloud_and_gt(batch_data,batch_gt=None): """ Randomly rotate the point clouds to augument the dataset rotation is per shape based along up direction Input: BxNx3 array, original batch of point clouds Return: BxNx3 array, rotated batch of point clouds "...
3f076281d14992a6c3651d3b80be8c205e1b9aae
51,023
def signal_resample( ser_raw:pd.Series, resample_method:str='linear', resample_timestep:str='100ms' ) -> pd.Series: """ Resample the data and fill the values following 3 methods: * linear will apply: * linear interpolation when 1 point is missing * Akima interpolation when more p...
7c408cd7e169c24f38b062786dee09ea41fc3e05
51,024
def client_script(): """ Reads qtwebchannel.js from disk and creates QWebEngineScript to inject to QT window. This allows for JavaScript code to call python methods marked by pyqtSlot in registered objects. Args: None. Returns: None. Raises: """ qwebchannel_js = QFile(...
c2627e9a95caa2b5faf183a98d50bca643e7f5bd
51,025
from functools import reduce def thread_first(val, *forms): """ Thread value through a sequence of functions/forms >>> def double(x): return 2*x >>> def inc(x): return x + 1 >>> thread_first(1, inc, double) 4 If the function expects more than one input you can specify those inputs in ...
80b500b80233ac17e41d809a4ffcf24a0173c63b
51,026
from typing import List def _get_parent_object(obj: dict, dotted_path: List[str]): """ Given a nested dictionary, return the object denoted by the dotted path (if any). In particular if dotted_path = [], it returns the same object. :param obj: the dictionary. :param dotted_path: the path to the ...
328a2baaab22b28b1f061609ff2720d461cdf3be
51,027
import re def vm_info(name): """ Wrapper around VBoxManage showvminfo Return all the information about an existing VM :param name: str :return: dict[str,str] """ try: INFO_PARSER = re.compile( r'^("(?P<quoted_key>[^"]+)"|(?P<key>[^=]+))=(?P<value>.*)$') info = {...
6b4e08af12420a305f6928dc133220658125f5cf
51,028
def fmod(x, y): """Return fmod(x, y), as defined by the platform C library. :type x: numbers.Real :type y: numbers.Real :rtype: float """ return 0.0
cd580ca8efe1e9bd3e5511613ccdcc59ebe55119
51,030
from typing import OrderedDict def load_observation(db, obs_id, dets=None, prefix=None): """Load the data for some observation. You can restrict to only some detectors. Coming soon: also restrict by time range / sample index. This specifically targets the pipe-s0001 sim format. Arguments: ...
d6e48317f2bc876afe15a169eadd570fc980d394
51,031
def get_tickers(fiat="ALL"): """ 마켓 코드 조회 (업비트에서 거래 가능한 마켓 목록 조회) :return: """ try: url = "https://api.upbit.com/v1/market/all" contents = _call_public_api(url)[0] if isinstance(contents, list): markets = [x['market'] for x in contents] if fiat == "K...
955831b785246a97547519c61276bd466f0835f4
51,034
def EulerFluxX(u): """Calculate the x-direction Euler flux from a solultion vector""" dens = u.dens() momX, momY, momZ = u.momX(), u.momY(), u.momZ() en = u.energy() pressure = u.pressure() x_flux = np.array( [ momX, momX * momX / dens + pressure, momX...
f38cabfe0524ac74fd08c57eff6c2ebd3c8901b0
51,035
def error_handler(fun): """ Assert异常装饰器,用来方便的进行断言式接口开发 """ def wrapper_fun(*args, **kwargs): try: return fun(*args, **kwargs) except AssertionError as e: return e.args[0] except Exception as e: return create_resp(code=8000, data=[], message=str...
df4a8c65c3c47eef252463a273698ab743c24ac9
51,036
def notfound(e): """404 template""" return render_template('404.html'), 404
ceb28334d35490d9af39fdb3a9100e9ff3c262d8
51,037
def read_pipes(): # type: () -> str """ Call to read_pipes. :return: The command read from the pipe """ o = _COMPSs.read_pipes() # noqa return o
412d738dee3a45d9c1770345f9ad56eebefc5554
51,038
from bs4 import BeautifulSoup async def get_relic_info(relic_name): """ Gets relic information and caches it, if not already cached. Also helps mantain a parts list. """ logger.info("Fetching relic info for %s." % relic_name) relic_infos = utils.get_json('relic_info') if relic_name in r...
0d2046b915f2dc8debfcd34f23d952f66ea9f505
51,039
def manchester_vermont_observed( awhere_api_key, awhere_api_secret, manchester_vermont_longitude, manchester_vermont_latitude, ): """Fixture that returns a geodataframe for the observed weather for Manchester, Vermont. """ # Define kwargs for Manchester, Vermont vt_kwargs = { ...
50ca693e86f151a08c897f5ebc2517e4c1ab09c9
51,040
def get_rv_xmatch(ra, dec, G_mag=None, dr2_sourceid=None): """ Given a single RA, dec, and optionally Gaia G mag, and DR2 sourceid, xmatch against spectroscopic catalogs to try and mine out an RV and error. Returns tuple of: (rv, rv_err, provenance) Presumably all RVs returned are helio...
3239caa15b2444e080da2c3830570b7b4b7eb7e8
51,041
import time import string from datetime import datetime def increment_name(mjd, lastname=None, suffixlength=4): """ Use mjd to create unique name for event. """ dt = time.Time(mjd, format='mjd', scale='utc').to_datetime() if lastname is None: # generate new name for this yymmdd suffix = stri...
3028fa8983f56f39d3ed75877cda32aad51be3d7
51,042
from tasks.models import Task def get_fields_for_annotation(prepare_params): """ Collecting field names to annotate them :param prepare_params: structure with filters and ordering :return: list of field names """ result = [] # collect fields from ordering if prepare_params.ordering: ...
c99ef78678c3fe004eab46efb5977211918efcbf
51,043
def topic_meta(topic, precinctNum): """ Return meta data about each precinct's election result output: { "percentTurnout": num, "registeredVoters": num, "totalVotes": num }, """ if precinctNum != 'all': return j...
1f63ff299ee9ad722295f2d764bffccccdc044d7
51,044
def check_for_previewimage(czi): """Check if the CZI contains an image from a prescan camera :param czi: CZI imagefile object :type metadata: CziFile object :return: has_attimage - Boolean if CZI image contains prescan image :rtype: bool """ att = [] # loop over the attachments fo...
8ea3b89e0cbf798d13054f0b418589820e1a6106
51,045
from typing import Union from typing import Iterable def check_spec(spec: Union[str, Iterable[str]]) -> bool: """Checks the spec against the hard constraints. Internally, Draco checks against the definitions, constraints, helpers, and hard constraints. :param spec: The specification to check """...
f21feb2ff4af0df098858bad5e0c8d24e4b9ca54
51,046
def get_closest_multiple_of_16(num): """ Compute the nearest multiple of 16. Needed because pulse enabled devices require durations which are multiples of 16 samples. """ return int(num) - (int(num) % 16)
333cbed27abbcb576541d5fb0b44bf85b78c9e78
51,048
def _convert_line_to_task(line: str) -> Task: """ Convert a line record to a task instance. Args: line A record line from the storage file Return A task instance """ id, message, time, project, category, links, started_at, finished_at = line.strip().split(sep) return ...
23986ef4d22006aca8a8e3148cfa888be79a6089
51,049
def TransformListFactory(name: str, transforms: tp.Sequence[Transform]): """Create a new TransformationList subclss with the given name that performs the specified transforms.""" return TransformListMetaclass(name, (TransformationList,), {}, transforms=transforms)
bc19ef5fecb17f30057787cab66d3f67e0e4df1e
51,050
from typing import List from typing import Tuple def max_subarray(arr: List[int]) -> Tuple[int, int]: """ :time: O(n) :space: O(n) """ max_val = max(x for x in arr) if max_val < 0: return max_val, max_val max_subsequence_sum = sum(x for x in arr if x > 0) max_subarray_sum = 0 ...
056b4c83191f57a36f0fdeb7474b2de2f6e8bb28
51,051
def AND_columns_with_NANFLAGs( df: pd.DataFrame, nan_val: int = 1, NANFLAG=-1 ) -> pd.Series: """see :func:`apply_bool_op_on_columns_with_NANFLAGs()`""" return apply_bool_op_on_columns_with_NANFLAGs( df, pd.Series.__and__, nan_val, NANFLAG )
a0c76a07828d40857026832c4d56965800d8435f
51,054
def split_container(path): """Split path container & path >>> split_container('/bigdata/path/to/file') ['bigdata', 'path/to/file'] """ path = str(path) # Might be pathlib.Path if not path: raise ValueError('empty path') if path == '/': return '', '' if path[0] == '/': ...
53b0d1164ecc245146e811a97017f66bb1f032a7
51,055
def load_data_dict(data_config): """ Load mapping information (dictionary) between raw data files to table names in the database. Parameters ---------- data_config : str Path of the config file that stores data dictionaries in yaml. This file should contains two dictionaries, on...
70e242bf59916abe14fb63791ef5312baa2e9e73
51,056
def alias_tuples_from_dict(aliases_dict): """ Convert from aliases dict we use in items, to a list of alias tuples. The providers need the tuples list, which look like this: [(doi, 10.123), (doi, 10.345), (pmid, 1234567)] """ alias_tuples = [] for ns, ids in aliases_dict.iteritems(): ...
3f35cf368c3e7bea8a309177c70013f3125f5220
51,058
from typing import Optional from typing import List def partial_trace( density_matrix: np.ndarray, targets: Optional[List[int]] = None, ) -> np.ndarray: """Returns the reduced density matrix for the target qubits. If no target qubits are supplied, this method returns the trace of the density matrix. ...
e7b192fd56e5ef72e765b51638331b83c884bde8
51,060
def lazy_pinyin(hans, style=Style.NORMAL, errors='default'): """不包含多音字的拼音列表. 与 gupinyin.pinyin 的区别是返回的拼音是个字符串, 并且每个字只包含一个读音. :param hans: 汉字 :type hans: unicode or list :param style: 指定拼音风格,默认是 gupinyin.Style.NORMAL 风格。 更多拼音风格详见 gupinyin.Style。 :param errors: 指定如何处理没有拼音的字符,...
477c5104ac2b29ddb9845992c505b1c0543754cd
51,061
def energy_degeneracy(N, m): """Calculate the number of Dicke states with same energy. The use of the `Decimals` class allows to explore N > 1000, unlike the built-in function `scipy.special.binom` Parameters ---------- N: int The number of two-level systems. m: float Tota...
46d41f1e3f13a49490c306237bef4e6279004f96
51,062
def sigmoid(x): """Implementation of the sigmoid (logistic) function. :param x: Function parameter. :type x: int or float """ return 1 / (1 + np.exp(-x))
01aab97de3b3eb4c368c6433c541f4b36340ad1d
51,063
def list_entities() -> (str, int): """ Точка входа для запроса на получение записи пользователя по id. Пример запроса: curl http://localhost:80/users :return: если база не пуста, то возвращает json с данными пользователей и код 200, иначе возвращает код 404 Формат возвращаемого...
6eadaedaa8a1b7a1c4bb8416aca67e1a39463304
51,064
def map_intervals(ref_itv, other_itv, gap_chars={"-", "."}): """ Map intervals of representative sequences on its aligned version Report contracted intervals that need to backpropagate in the other alignments at this level """ # extend contracted intervals contracted = other_itv.length < ref_itv...
6cabda95779cf8d1fadb6843307ace90bae08050
51,065
def convert_ros2_time_to_float(time_tuple): """ Converts time from tuple (ROS2) format to floating point number """ return float(time_tuple[0] + time_tuple[1]/TIME_CONVERSION_CONST_)
dd552feab86741380c63fb87993269d181cecc39
51,066
import concurrent def csv_render(domain): """Render and return the csv-formatted report.""" headers = ('Domain', 'Type', 'Tweak', 'IP', 'Error') csv_filename = 'dnstwister_report_{}.csv'.format(domain.to_ascii()) def local_resolve_candidate(candidate): domain = Domain(candidate['domain-name']...
7fceadab2420d522c3b1e755c2bc330689e2e6f5
51,067
def center(x, y, width, height): """ info: gets the center x, y :param x: int :param y: int :param width: int: 0 - inf :param height: int: 0 - inf :return: (int, int) """ return _get_center(x, width), _get_center(y, height)
faa0e1492bd2da2b87338d256b35e3021bd012fb
51,068
def get_prettyhandles_image(rankings): """return PIL image for rankings""" SMOKE_WHITE = (250, 250, 250) BLACK = (0, 0, 0) img = Image.new("RGB", (900, 450), color=SMOKE_WHITE) font = ImageFont.truetype("tle/assets/fonts/Cousine-Regular.ttf", size=30) draw = ImageDraw.Draw(img) x = 20 y...
6e00a619c7f968c96d26b445ede1f3a7394e86d4
51,069
def extract_cnn_features(net, mean, img, layer, blob = None): """ Extracts image features from a CNN using Caffe. net - caffe.Net instance mean - A numpy array with the mean values for each channel. Channels must be in BGR order and the scale of values is assumed to be [0,255]. ...
9599cf7fa7098f65b4f76570a5a7a84147df7038
51,070
from pyspark.sql import SQLContext from pyspark.sql import SparkSession def get_or_create_sc(type="sparkContext", name="CerebralCortex-Kernal", enable_spark_ui=False): """ get or create spark context Args: type (str): type (sparkContext, SparkSessionBuilder, sparkSession, sqlContext). (default="s...
05ed6be4b37678e54009d8f1e67d37c0e770cdda
51,071
def welchs_test_arrays(x1, x2): """ A spearate implementation that automatically calculates means, variances and the number of samples from the input lists of values. Not currently used in the code because the number of samples is calculated earlier, when the estimators were combined. It is kept as a s...
4f7ff1cd0e12772e83c1caf66df5daa021225987
51,072
def extrapolate_nsigma(ref_mag, SNR, nsigma=5): """ Fit a parabola to log10(SNR) vs ref_mag and extrapolate/interpolate to find the n-sigma magnitude limit. """ log10_SNR = np.log10(SNR) index = np.where(log10_SNR == log10_SNR) pars = np.polyfit(log10_SNR[index], ref_mag[index], 2) mag =...
3ac3b647565ce46ab8abc3dd089cea928c27e937
51,073
def extract_valid_voxels(gdf: gpd.GeoDataFrame): """ Given a GeoDataFrame gdf containing data from one source team, with columns "dst_ip", "geometry", process the Shapely objects contained in "geometry" and store only the voxels that have not been invalidated over their relevant time frames. ...
e529dfd7ad325dea4ba68e1c1236aef37d74f8e1
51,074
import warnings def apply_holms_test(imbalanced_experiment, control_oversampler=None): """Use the Holm's method to adjust the p-values of a paired difference t-test for every combination of classifiers and metrics using a control oversampler. Parameters ---------- imbalanced_experiment : obje...
04c1e6541bbeb0bec037bd7f2c010ac1cc9faf03
51,075
def read_gmt(filepath, gene_sets=(), drop_description=True, save_clean=False, collapse=False): """ Read GMT. :param filepath: str; filepath to a .gmt compress :param gene_sets: iterable: list of gene set names to keep :param drop_description: bool;...
7000fd7ba36fcc14be4d83b57b39a86580e21604
51,076
from nebula_website.views.db_stat import DPS_write_fn def test_DPS_write_fn(tmpdir): """ 1. max line 65536 """ def count_line(fn): c = 0 with open(fn, 'r') as f: for _ in f: c += 1 return c # 写入65534 + 1 行 # 实际也有 65535行 valid_count = 6553...
d26900bb2611a41bc276554d95dcc70d4972c5dd
51,077
def get_email_from_token(token, salt, secret, max_age=86400): """ Read an email from a timestamped token. Raises an exception if the token is more than 24 hours old or invalid """ ts = URLSafeTimedSerializer(secret) email = ts.loads(token, salt=salt, max_age=max_age) return email
a568a80f7843baa6067f21180cc967e5194eeb52
51,078
def template_match(source_image, template_image, region_center, option=0): """ template match @param source_image: np.array(input source image) @param template_image: np.array(input template image) @param region_center: list(if not None, it means source_image is part of origin target image, ot...
3e620eba2ab83e40e83bb97c833b4c6c3baa5ae9
51,079
def months_in_prison(popu): """Return array of months in prison for each person in population.""" return np.array([person["months_in_prison"] for person in popu.values()])
bc4b92aa09e9c08f6ce2308f75862d575086b821
51,080
def elementary(deriv_func): """Decorator to create an elementary operation This takes as an argument a function that calculates the derivative of the function the user is calculating. When the decorated function is called, `@elementary` also calls `deriv_func` and stores both the value and derivative i...
38ccc3889471c0880bc802cef535f45dbfd0a92d
51,081
def _singularize_copa_examples(dataset): """Converts COPA multi-choice examples to batch of single-answer examples.""" indexes = [] premises = [] questions = [] choices = [] labels = [] for example in dataset: for choice in ["choice1", "choice2"]: indexes.append(example["idx"]) premises.a...
1f680e0366b296a040e3450f00975c499d81672c
51,082
def test_skewt_shade_cape_cin(test_profile): """Test shading CAPE and CIN on a SkewT plot.""" p, t, tp = test_profile with matplotlib.rc_context({'axes.autolimit_mode': 'data'}): fig = plt.figure(figsize=(9, 9)) skew = SkewT(fig, aspect='auto') skew.plot(p, t, 'r') skew.plot...
035194fe3dbd049a40c1cc5e94980b0d3b0c1089
51,083
def get_client() -> RabbitmqClient: """Returns a RabbitmqClient instance.""" # Replace the parameters with proper values for host, port, login and password # Change the value of exchange if needed. # # For any parameter that is not given here, the client tries to use a value from an environment vari...
7aebab2405234f779f5b9a06e366ec6539fc8847
51,085
def get_animal_ids(id=None): """ Return the distinct animal ids :param id : id of the specific dataset """ if id is None: return jsonify({}) animal_ids = db.session.query(Movement_data.animal_id).filter_by(dataset_id=id).distinct(Movement_data.animal_id) result = [] for ...
07d279b79ea52b2cda236de7c6ff3b72ad90417f
51,086
def find_actors(hg, edge): """Returns set of all coreferences to actors found in the edge.""" actors = set() if is_actor(hg, edge): actors.add(main_coref(hg, edge)) if not edge.is_atom(): for item in edge: actors |= find_actors(hg, item) return actors
ba2c44de426619f21eceab1a3e39b9ea78161200
51,087
def rate_project(request, project_id): """ rate_project view function to process the user input rating information based on usability,content and design and return an average rating which will be stored in the database """ current_user=request.user # get project to be rated from the DB ...
049acdfd25e66970e24e82c2dc068d8d9b01a6d7
51,088
import fsspec def load_era5( var, lat, lon, time, reduce_func=None, resample="1D", ): """ Download and return an ERA5 variable for a defined time window. Parameters ---------- var : string Name of the ERA5 climate variable to download, e.g "air_temperature_at_2_metres" la...
79c79412bac5baafcb1442e730ac7a992dca8f83
51,089
import copy def stack_to_queue(stack): """ Convert queue to a stack """ input_stack = copy.deepcopy(stack) output_queue = ArrayQueue() while True: try: output_queue.add(input_stack.pop()) except KeyError: break return output_queue
839a94ce94f8e28d39d2c1df0c11673a0a378826
51,090
def sigma(S,T,P=0. | units.dbar): """ Density anomaly """ _S=S.value_in(units.psu) _T=T.value_in(units.Celsius) _P=P.value_in(units.dbar) return _seawater.sigma(_S,_T,_P) | units.kg/units.m**3
3d5a62ba17abc62ec5037f78efa767301b1decf4
51,091
import torch def laplacian_positional_encoding(g, pos_enc_dim): """ Graph positional encoding v/ Laplacian eigenvectors """ # Laplacian A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float) N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float) L = s...
644ae9c397e2e78d073b5f0edc04777e71a128e3
51,093
def create_2d_gaussian(dim, sigma): """ Source: https://github.com/vsvinayak/mnist-helper/blob/master/mnist_helpers.py This function creates a 2d gaussian kernel with the standard deviation denoted by sigma :param dim: integer denoting a side (1-d) of gaussian kernel :type dim: int :param s...
8b6ed5ce4621503c9624f4571e05c0357351e5db
51,094
import io import pkgutil def get_embedding(path): """ Get the dataset of ingredients as a dictionary. :return: a dictionary representing the embedding """ embedding_io = io.BytesIO(pkgutil.get_data(__name__, path)) return np.load(embedding_io, allow_pickle=True).item()
22fe9b285cf64cdac83192574cd631a9dd79b59f
51,095
import pickle def get_challenges_for_user_id(database, user_id, ctf_channel_id): """ Fetch a list of all challenges a user is working on for a given CTF. Return a list of matching Challenge objects. This should technically only return 0 or 1 challenge, as a user can only work on 1 challenge at a t...
acc2bfb7277040c0051f43931915794732371aac
51,096
def allowed_file(filename): """ allowed formats to be uploaded for mcdss """ return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
46d5f76264f57d4786fe4849ca992cf9fe3c8b6f
51,097
def parse_sph_header( fh ): """Read the file-format header for an sph file The SPH header-file is exactly 1024 bytes at the head of the file, there is a simple textual format which AFAIK is always ASCII, but we allow here for latin1 encoding. The format has a type declaration for each field a...
d0055b3dc276facd9acb361dfde167d8c123b662
51,098
def add_records(datalinks_records_list): """ upserts records into db :param datalinks_records_list: :return: success boolean, plus a status text for retuning error message, if any, to the calling program """ rows = [] for i in range(len(datalinks_records_list.datalinks_records)): fo...
db359c586ce70b536f5a2753c365987280ed72f6
51,099
def resolve_ident(name: str, env) -> str: """Finds the variable, list, procedure or sprite with specified name in env.""" for var in env["sprite"]["variables"]: if var["name"] == name: return "var", var["id"] for lst in env["sprite"]["lists"]: if lst["name"] == name: ...
99a3a6cb8af259b80ca5b22c368d9c8e452977f2
51,100
import json def bbox_to_geojson(bbox=None): """ :param bbox: A list [xmin, ymin, xmax, ymax] :returns: A geojson of the bbox. """ bbox = Polygon.from_bbox(bbox) geometry = json.loads(GEOSGeometry(bbox, srid=4326).geojson) return {"type": "Feature", "geometry": geometry}
e607690a0ba87778bdf41925d1caa8ec197fd1ad
51,101
def countDirectlyConnected(port: LPort, result: dict) -> int: """ Count how many ports are directly connected to other nodes :return: cumulative sum of port counts """ inEdges = port.incomingEdges outEdges = port.outgoingEdges if port.connectedAsParent or (port.children and not all(p.conne...
b4dd2f1deec222336f4498df34b9252eea25324b
51,102
def unmarshal(data_in): """Takes in binary data and maps builds the appropriate frame type, returning a frame object. :param bytes data_in: Raw byte stream data :rtype: tuple of bytes consumed, channel, and a frame object :raises: specification.FrameError """ # Look to see if it's a proto...
f5a4f7096453c696ec3eb6e7cd7925fc3719b5f4
51,103
def ip_interface(address): """Take an IP string/int and return an object of the correct type. Args: address: A string, integer, or a tuple of strings or integers representing the IP interface as an IP address and optional network prefix. Returns: An IPv4Interface or...
92509799cb5617b54de04b0560b3e1fbf68f6b54
51,104
def wrap_reclassify_by_pons(row, fasta, chr_prefixed, pons): """Wrap 'relassify_by_panel_of_non_somatic' so that this function is only applied to instances predicted 'somatic' Args: see 'relassify_by_panel_of_non_somatic' Returns: see 'relassify_by_panel_of_non_somatic' """ if row["predicted_cl...
9b8cb6dd13aa2463a1cb433ffd11bc0018e3f910
51,105
import gzip def read_rapsearch_aln(rpfile, linestocount, verbose=False): """ Read the rapsearch file and just return the query lines :param rpfile: rapsearch file to read :param linestocount: how many query lines to count :param verbose: more output :return: a query line """ if rp...
5b53ef5ac8b73933aa673fa5670d3c50e4fa610e
51,106
import numpy def acosine(a,b,weights): """Distance between two points based on the pearson correlation coefficient. By treating each data point as half of a list of ordered pairs it is possible to caluclate the pearson correlation coefficent for the list. Since the pearson correlation coefficen...
19ffa98cb12c1d4e8026e0763c76062d2c4b19c8
51,107
def conv_3x3(inputs, downsample=False): """ conv_3x3 """ return conv_base(inputs, (3, 3), downsample=downsample)
8b5aab7497d15faba0ad085e6f1d4834b5902c2d
51,108
def column(matrix, i): """ Returning all the values in a specific columns Parameters: X: the input matrix i: the column Return value: an array with desired column """ return [row[i] for row in matrix]
2a88c40d11e7fe7f28970acd4d995a8428126a4d
51,109
def cubicinout(x): """Return the value at x of the 'cubic in out' easing function between 0 and 1.""" if x < 0.5: return 4 * x**3 else: return 1/2 * ((2*x - 2)**3 + 2)
505f0c5b8dc7b9499450474dbb1991eec068b553
51,110
def get_sparse_graph(graph): """ Returns a sparse adjacency matrix in CSR format :param graph: undirected NetworkX graph :return: Scipy sparse adjacency matrix """ return nx.to_scipy_sparse_matrix(graph, format='csr', dtype=np.float, nodelist=graph.nodes)
d8b6a13d133ec37ba68482c73146e5b37a85316b
51,111
from typing import Optional def make_door_state(door_status: Optional[Door.Status]) -> State: """makes a simple state with a door""" grid = Grid.from_shape((2, 1)) if door_status: grid[0, 0] = Door(door_status, Color.RED) agent = Agent(Position(1, 0), Orientation.N) return State(grid, ag...
340794c1ecd2bb5bed19af9a472285ed0a6008f3
51,113
def remove_duplicates(string: str) -> str: """ Remove duplicate characters in a string :param string: :return: """ without_duplicates = "" for letter in string: if letter not in without_duplicates: without_duplicates += letter return without_duplicates
2caafc6b38cf2b920324bd976acb3caf90660c25
51,114
def interferometer(U): """Interferometer. Args: U (array): unitary matrix Returns: array: symplectic transformation matrix """ X = U.real Y = U.imag S = np.vstack([np.hstack([X, -Y]), np.hstack([Y, X])]) return S
f45ddb1e4ae0d9f8b118a9b6b0cecc655e4ed581
51,115
def make_tfd_dataframe(tfd_data_flat): """ This is just a quick function to make a nice DataFrame from the data. It makes it easy to manage. Syntax: tfd_data_df = make_tfd_dataframe(tfd_data_flat) Inputs: tfd_data_flat - Dictionary containing information about the file and channel along wit...
3c6d464dbbc4dfd2b713d58c36ecf258c7fcd90c
51,116
def process_medians(helst, shelst, authlst): """ >>> medians_he = [12, 130, 0, 12, 314, 18, 15, 12, 123] >>> medians_she = [123, 52, 12, 345, 0, 13, 214, 12, 23] >>> books = ["a", "b", "c", "d", "e", "f", "g", "h", "i"] >>> process_medians(helst=medians_he, shelst=medians_she, authlst=books) {'...
8262cd306b09d7ea201360a3c5abb6eef6dac966
51,117
def recalib(spec, figfilename, title, ref_spec, linelist, ref_calib, aperture_koffset=(1, 0), pixel_koffset=(1, None), xorder=None, yorder=None, maxiter=None, clipping=None, window_size=None, q_threshold=None, direction=None, fit_filter=None ): """Re-calibrate the wavelength of an in...
5f1c099551ea7d53fce222ea3aed852d33d1353f
51,118
def encode_payload_values(payload_dict): """This function URL-encoded any string-formatted payload values. .. versionadded:: 3.2.0 :param payload_dict: The JSON payload for an API call in dictionary format :type payload_dict: dict :returns: The JSON payload with URL-encoded string values """ ...
1f76d252e1206d0596d21a7f29733827865f0717
51,119