content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def skip_check(): """ Check if an environment variable was used to skip this actor """ if os.getenv('LEAPP_SKIP_CHECK_OS_RELEASE'): reporting.create_report([ reporting.Title('Skipped OS release check'), reporting.Summary('Source RHEL release check skipped via LEAPP_SK...
a0e538d0e7013897f9324445d0cdbda1def5c234
41,300
def triagToNormal(triag, M): """Convert triangular matrix to a regular matrix""" ar = np.arange(M) mask = ar[:, None] <= ar[None, :] x, y = np.nonzero(mask) new = np.zeros((M, M), dtype=triag.dtype) new[x, y] = triag return new + new.T
fd1a4419983c4546ec1befd821200e0df9257cb1
41,301
def search_users_by_id(dataset_path: str, users: list): """ Searches the number of movies and genres that a given user or a group of users watched. The number of movies watched are calculated by counting the number of movies that the user rated. The number of genres watched are calculated by counting a...
a0eed8dc370e0849fdbb3bea239d42920ca31911
41,302
import os def get_fsl_metrics(datadir, subject_list): """ Calculates both dice similarity coefficients between FNIRT masks and ground truth lesionmasks as well as SSIM between FNIRT and FLIRT images. Input: data directory, subjects to calculate DSC and SSIM Output: list of DSCs and SSIM for each ...
38cd389a1f0c2f87b22f121cce1a2818a2a48b74
41,303
from typing import Deque from typing import List from typing import Tuple import concurrent def execute_parallel_functions_in_threads(tasks_groups: Deque[List[ThreadedFunctionData]], max_workers, timeout=None)\ -> List[Tuple[Future, str, str]]: """ This function takes a Queue (tasks_groups: Deque[List...
b91a1768ac85aeeac955bc5abc6faaf817b89741
41,304
import requests def _download(pep_number): """ Fetches PEP files as HTML from python.org. """ # PEP URLs look like https://www.python.org/dev/peps/pep-0123/ url = f'https://www.python.org/dev/peps/pep-{_format_pep_number(pep_number)}/' response = requests.get(url) if response.status_code ...
46640e6522595b97c0629f894b0acf50c62ac2b6
41,305
def stretched_flow_para_function( x, beta, relaxation_rate, alpha, flow_velocity, baseline=1 ): """ flow_velocity: q.v (q vector dot v vector = q*v*cos(angle) ) """ Diff_part = np.exp(-2 * (relaxation_rate * x) ** alpha) Flow_part = ( np.pi ** 2 / (16 * x * flow_velocity) ...
f02a23886721f24a72ddca8a042e06ec67a4a68b
41,306
def svn_path_is_url(path): """svn_path_is_url(char const * path) -> svn_boolean_t""" return _core.svn_path_is_url(path)
94b6a0cfa4e438bce113fd266d57d3eb70c729a1
41,307
import os def random_key_generator(key_length): """ Creates a random key with key_length written in hexadecimal as string Paramaters ---------- key_length : int Key length in bits Returns ------- key : string Key in hexadecimal as string """ return bytes...
80c8e9e6949cfd1e5ead274c0b89bc0d40e1f926
41,308
def process_error(err): """Special handling for consent_required""" body = err.body.decode('utf8') if "consent_required" in body: consent_scopes = ' '.join(DsConfig.permission_scopes()) consent_url = f"{DsConfig.auth_server()}/oauth/auth?response_type=code&scope={consent_scopes}&client_id={D...
0cec9d39bd9726c0700a45fc194babcecb82d133
41,309
import logging import io import csv def get_sheet(sheet_id, gid=None, use_cache=True): """Returns a list of rows from a sheet.""" query_dict = get_query_dict() force_cache = RELOAD_ACL_QUERY_PARAM in query_dict cache_key = 'google_sheet:{}:{}'.format(sheet_id, gid) logging.info('Loading Google She...
6130fafbe1f586ada863e74b08a424e7b07ff836
41,310
def _make_geometry_1_file(filename): """See n.comment for details.""" n = netCDF4.Dataset(filename, "w", format="NETCDF3_CLASSIC") n.Conventions = "CF-" + VN n.featureType = "timeSeries" n.comment = ( "Make a netCDF file with 2 node coordinates variables, each of " "which has a corr...
430e978060b741a1460000ff66c7fa4bf67bca7c
41,311
def conv_forward_im2col(x, w, b, conv_param): """ A fast implementation of the forward pass for a convolutional layer based on im2col and col2im. """ N, C, H, W = x.shape num_filters, _, filter_height, filter_width = w.shape stride, pad = conv_param["stride"], conv_param["pad"] # Check ...
0b7ac991415fdbbbc6a31f92370c3561cefb9a0f
41,312
def get_model(pretrained=True): """Function to obtain a pytorch resnet50 model with modified final layer Args: pretrained (bool): whether to use pretrained weights of the resnet50 model Returns: model (pytorch model): a pytorch model with resnet50 architecture with ...
9809bd57a700dbf78847b9ec0dd09da8d2623353
41,313
import torch from typing import Optional from typing import Union from typing import List def dilation_dependent(input_tensor: torch.Tensor, structuring_element: torch.Tensor, origin: Optional[Union[tuple, List[int]]] = None, border_value: Union[int...
5e7af35cf37c41ffaf9afffe978c73521856e10b
41,314
def audio_process(songname: str) -> pd.DataFrame: """ :rtype: DataFrame of all the features """ y, sr = librosa.load(songname, mono=True, duration=30) rmse = librosa.feature.rms(y=y) chroma_stft = librosa.feature.chroma_stft(y=y, sr=sr) spec_cent = librosa.feature.spectral_centroid(y=y, s...
e1f517c588e42ac0381065d4fde5f331e528061d
41,315
def estimate_fundamental_matrix(points_a, points_b): """ Calculates the fundamental matrix. Try to implement this function as efficiently as possible. It will be called repeatedly in part 3. You must normalize your coordinates through linear transformations as described on the project webpage befor...
fc569386cd300b948adb876ef01d389d1cea5395
41,316
def qg8_chunk_get_type(chunk: qg8_chunk): """ Return the chunk type as an integer """ if not isinstance(chunk, qg8_chunk): raise TypeError("Argument is not a qg8_chunk") return chunk.type
7dc2bbc77d152f4727dcf951a4ba897b0606d9ba
41,317
def agg_func(data:pd.DataFrame, object_column:str, agg_list=['nunique', 'count'])->pd.DataFrame: """ Parameters ---------- data:pd.DataFrame : object_column:str : agg_list : (Default value = ['nunique', 'count'] : Returns ------- A dataframe with...
41448ed189311bd121aac9ef37bde4ef20c47c8c
41,318
def get_audits(): """Get OS hardening login.defs audits. :returns: dictionary of audits """ audits = [TemplatedFile('/etc/login.defs', LoginContext(), template_dir=TEMPLATES_DIR, user='root', group='root', mode=0o0444)] return audits
cbc12d52fde5d9ec92536799a46d3b0a9fd0d242
41,319
import os def draw_component_loss_barchart_s3(ctype_resp_sorted, scenario_tag, hazard_type, output_path, fig_name): """ Plots bar charts of direct economic losses for com...
93c59cea545a7e4015b87dad2d538decb6ddb6bf
41,320
def username_exists(username): """ Checks if a username aldready exists :param username: username to be checked :return: Boolean indicating whether the username exists or not :rtype: boolean """ return not User.query.filter_by( username=username).first() is None
717dc8cd2f5807c49c892ffd98e4e35f79886094
41,321
def buy_ticket(email,price,name,quantity): """ Update user balance :param email: email of user :param price: price of ticket :param name: name of ticket :param quantity: quantity to buy """ user=User.query.filter_by(email=email).first() user.balance=int(float(user.balance)-float(pric...
bf8b5378243b9c3fd8caff7e52a71c985ca47c4f
41,322
from operator import truth def test_validators(): """Tests of validatorfuncs.py that aren't covered elsewhere""" # PercentageString with raises(Invalid, match="Not a valid percentage string"): validatorfuncs.PercentageString("mess%") # ListOfType testfunc = validatorfuncs.ListOfType(int) ...
20707f0eae6491d4acd1b16c59380d5f90d54e01
41,323
import libpysal import warnings def rand_precision_mat(lat_row, lat_col, max_neighbors=8, rho=1): """Generate a random spatial precision matrix. The spatial precision matrix is generated using a rectengular lattice of dimensions `lat_row` x `lat_col`, and thus the row and colum size of the matrix is ...
8afffaee98a07a95ad6e5e0ad2f69cc9d51169ef
41,324
from typing import List def generate_df(cols_to_keep: List[str]) -> pd.DataFrame: """Generates the cleaned dataframe.""" df = pd.read_csv(CSV_URL) for col in INTEGRAL_COLS: df[col] = df[col].astype('Int64') if col.endswith('_flag'): assert get_unique_values(df[col]) == [0, 1, p...
f3c2ed950e09e2d6f52a90fd66035a6067a90a01
41,325
import logging import requests from bs4 import BeautifulSoup def scrape_attackdex( save_csv: bool = True, file_path: str = 'data/attackdex.csv' ) -> pd.DataFrame: """Return dataframe of scraped attack data from serebii.net""" gen_dict = { 1: '-rby', 2: '-gs', 3: '', ...
e634b4a0dd1d36811a408d09ee88b9c92e1b30cf
41,326
def get_ppm_df(): """Get a pandas dataframe containing all PPM data. Returns: pd.DataFrame: PPM Pandas dataframe """ if app.mongo is None: return None docs = app.mongo.get("PPM") if docs is None: return None ppm_dict = { "date": [], "total": [], ...
0f894522cd489b792c68d9935e4c998d08ad1b69
41,327
from datetime import datetime def utc2local(utc_dtm): """ UTC 时间转本地时间( +8:00 ) :param utc_dtm: :return: """ local_tm = datetime.fromtimestamp(0) utc_tm = datetime.utcfromtimestamp(0) offset = local_tm - utc_tm return utc_dtm + offset
0070c3ae1e37071cbf57806ca18576f81abb64e0
41,328
def make_serviceitem_servicedll(servicedll, condition='contains', negate=False, preserve_case=False): """ Create a node for ServiceItem/serviceDLL :return: A IndicatorItem represented as an Element node """ document = 'ServiceItem' search = 'ServiceItem/serviceDLL' content_type = 'strin...
96513dafa74e7a59b602a4087528794aa540f681
41,329
import math def load_dataset_with_augmentation(source_dir, augmentation=None, min_count=None): """ Wczytanie sampli z opcjonalną augmentacją. Użyć parametru augmentation albo min_count, nie obu na raz. :param source_dir: katalog źródłowy z plikami PNG. :param augmentation: krotność augmentacji. :...
03e8487a7894a651954c2db635c337fe6e8c8c9d
41,330
def get_mse(prices, predictions): """Get the mean squared error of a network by analysing actual price and the network's corresponding predictions. :rtype: float64 :param prices: the prices that the predictions aim to mimic :param predictions: the predictions :return: the mean-squared error of the c...
ec1fbe8e053d29ea95c9ccb268e9590f1a640f45
41,331
import json def find_k_neighbors(): """Receiving input and returning closest neighbors""" input_dict = json.loads(request.get_json()) # print(pd.json_normalize(input_dict).info()) result = KNN.kneighbors( TRANSFORMER.transform(pd.json_normalize(input_dict)), return_distance=False) ...
4001322aa054c623a29fa61e60ada0e7182084d9
41,332
def get_databases(task=None): """Get list of databases Parameters ---------- task : str, optional Only returns databases providing protocols for this task. Defaults to returning every database. Returns ------- databases : list List of database, sorted in alphabetica...
a1ff0e6e6b4cf3282bcc61ff7e52538bd057c19c
41,333
def dimensions(image: np.ndarray, kernel: np.ndarray, padding:int, strides:int) -> np.ndarray: """ See https://medium.com/analytics-vidhya/2d-convolution-using-python-numpy-43442ff5f381 :param image: :param kernel: :param padding: :param strides: :return: """ x_kern_shape = kernel.sh...
007cc47f76a253adaf2f02ade01082670119ae8a
41,334
from operator import add def intcode_comp(puzzle_input, phase_setting, input_signal): """Compute based on the intcode instructions below # position mode: # 1: positional add # 2: positional multiply # 3: get input and save it at location of parameter # 4: output value located a...
dfeab35af6210994d846d1d79916700b6e0e959b
41,335
import ctypes def copy(cell: SpiceCell) -> SpiceCell: """ Copy the contents of a SpiceCell of any data type to another cell of the same type. https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/copy_c.html :param cell: Cell to be copied. :return: New cell """ assert isinstance(c...
39f82d10170190b209e8a0fe5061e9aba6877317
41,336
import glob import collections import sys def get_list_of_audios(folder_path, audio_extension = 'wav', confirm_with_transcript = True, verbose = False): """ Confirm_with_transcript requires: file path in first column To-do: check if in csv file the header_none...
0314dc6c9dd0afd509fb51235dbe74fc35b5fb15
41,337
def get_hash_hex(raw_hash): """Creates a nice hex representation of a raw req""" return raw_hash.encode('iso-8859-1').encode('hex')
a7c0e873617cae2481fecc32a2051ad1fc6a9519
41,338
from typing import Any import copy def new_document(source_path: str, settings: Any = None) -> nodes.document: """Return a new empty document object. This is an alternative of docutils'. This is a simple wrapper for ``docutils.utils.new_document()``. It caches the result of docutils' and use it on seco...
5bda163d426a9a7c2f419a282ab4c4e4907700cf
41,339
def guild_only() -> AC: """A :func:`.check` that indicates this command must only be used in a guild context only. Basically, no private messages are allowed when using the command. This check raises a special exception, :exc:`.ApplicationNoPrivateMessage` that is inherited from :exc:`.ApplicationC...
a61f3e0f05acfb51842982dd41cd63d82345ed0b
41,340
def importable_name(cls): """ >>> class Example(object): ... pass >>> ex = Example() >>> importable_name(ex.__class__) 'jsonpickle.util.Example' >>> importable_name(type(25)) '__builtin__.int' >>> importable_name(None.__class__) '__builtin__.NoneType' >>> importable_n...
96fe43ab1c47b506c21bcb938ea34eeefaedac5a
41,341
import os def loadDictDDIs(path_file:str): """ load the ddi source if the pickle file already existe :param path_file: path of the picke file :type path_file: str :return: dictionary with the ddis sources ids :rtype: dict[(domain_id_a, domain_id_b)] : id sources """ dict_ddis_sour...
6ffeb86eb867b6605ec77097b8d68a4a0526971b
41,342
def gen_client(api_id: str, api_hash: str) -> Client: """Generates Client instance, nothing special Args: api_id (str): Telegram App API ID api_hash (str): Telegram App API Hash key Returns: Pyrogram::Client """ return Client( "tgresender", api_id=api_id, ...
7bd70964c3bb098cc70d2efc178cb038d04321e3
41,343
from typing import Iterable from typing import List def encode_argument_text_from_spans(arguments: Iterable[Argument], tokens: List[str]) -> str: """ Return a string for the CSV field 'answer' """ return SPAN_SEPARATOR.join([span_to_text(span, tokens) for span in arguments])
9421a6a0f9aad8f9a8c33046a207d9ae941cf218
41,344
def get_folder_size_human(path, container: DockerContainer): """disk usage in human readable format (e.g. '2,1GB')""" cmd_folder_size = "du -sh {}".format(path) result = DockerUtils.run_cmd(cmd=cmd_folder_size, container=container) return result.split()[0].decode('utf-8')
8945627c13c841ec8b42896f8285b8d600518598
41,345
def is_input_type(graphql_type: "GraphQLType") -> bool: """ Determines whether or not the "GraphQLType" is an input type. :param graphql_type: schema type to test :type graphql_type: GraphQLType :return: whether or not the "GraphQLType" is an input type. :rtype: bool """ return isinstanc...
ff21d013848159cfa9a286af991fd79267c930e7
41,346
import json def cartao_trello(request, pedido=None, desc=None): """Responsavel por enviar ao cartao trello.""" cliente = TrelloClient(api_key=API_KEY, api_secret=API_TOKEN) my_boards = cliente.get_board('kyL57xiF') lista = my_boards.all_lists() pedido = json.dumps(pedido, cls=UUIDEncoder) des...
ce558a948a747488cd6ef020e4f4e0174e2da91e
41,347
from typing import OrderedDict import math def data_reorg_half_daily(instrument_type) -> pd.DataFrame: """ 将每一个交易日主次合约合约行情信息进行展示 :param instrument_type: :return: """ # engine = Config.get_db_engine(Config.DB_SCHEMA_PROD) engine = Config.get_db_engine(Config.DB_SCHEMA_DEFAULT) sql_str...
e765b5a7041d59012c1006588fe7daf265bd4325
41,348
import sys import math def assign_boxes_to_levels(boxlist, min_level, max_level, canonical_box_size, canonical_level): """ Map each box in `box_lists` to a feature map level index and return the ass...
c8ff3c468f7411eea5a2b069ca29dc803d844beb
41,349
def spectral_maxpeaks(sign, FS): """Compute number of peaks along the specified axes. Parameters ---------- sig: ndarray input from histogram is computed. fs: int sampling frequency of the signal Returns ------- num_p: float total number of peaks """ f, ...
2f61e97daf08e177a13a2b98c0dec43e4ea421fb
41,350
import inspect def get_calling_module(point=2): """ Return a module at a different point in the stack. :param point: the number of calls backwards in the stack. :return: """ frm = inspect.stack()[point] function = str(frm[3]) line = str(frm[2]) modulepath = str(frm[1]).split('/') ...
638006a14fb062810db34beefcd906b898ba45a5
41,351
def _pad_keys_tabular(data, sort): """Pad only the key fields in data (i.e. the strs) in a tabular way, such that they all take the same amount of characters Args: data: list of tuples. The first member of the tuple must be str, the rest can be anything. Returns: list with the strs padded with space cha...
eba58694354a89e0a6d808c08f964755f3b11822
41,352
from typing import Optional def depth_based_median( X: FDataGrid, depth_method: Optional[Depth] = None, ) -> FDataGrid: """Compute the median based on a depth measure. The depth based median is the deepest curve given a certain depth measure. Args: X: Object containing different samp...
07025e781693c213c715aed5a8eac47fdbbb51af
41,353
def get_read_only_permission_name(model: str) -> str: """ Create read only permission human readable name. :param model: model name :type model: str :return: read only permission human readable name :rtype: str """ return f"{settings.READ_ONLY_ADMIN_PERMISSION_NAME_PREFIX.capitalize()}...
81e02b47079fc41fc5e4148a811aad12b2e5646a
41,354
from typing import OrderedDict def _determine_colnums_to_yield(colnames, fname, dtype_fname): """Return a list of integers storing the column numbers of the ASCII history file corresponding to the ordered sequence determined by the input ``colnames``. """ colnames = np.atleast_1d(colnames) colname...
6a5c9d16f64fa5b067885aff9d95b3df5eccbe27
41,355
def get_all_countries(): """Returns all countries""" url = BASE_URL + "all" return _get(url=url)
c3c6bb17e1191635a022d0a119defcaf0daff944
41,356
async def find_channel(ctx, userstr, interactive=False, collection=None, chan_type=None): """ Find a guild channel given a partial matching string, allowing custom channel collections and several behavioural switches. Parameters ---------- userstr: str String obtained from a user, expec...
c07ce7c31e7c99cce0517901dcd7d3abb18720ac
41,357
def df_params_generator(number_of_facilities, number_of_tasks, seed=0): """ Generate instance parameters for the df problem set mentioned in [1]. Parameters ---------- number_of_facilities: int the number of facilities to schedule on number_of_tasks: int the number of tasks to a...
370cba6ce19e5a5a9a556df165d554e4445da7e5
41,358
from typing import Counter def mass_timeseries(cur, facility, flux): """Returns dictionary of mass timeseries of each isotope at a facility. Parameters ---------- cur : sqlite cursor sqlite cursor facility : str name of facility flux : str direction of flux Returns...
4cd53bab4918cd3558b61b4353957da40ccf99a2
41,359
import os def get_credentials(account_id): """ Using STS assume role to obtain the temporary credentials of another AWS account returns dict: 'error' : None if credentials is acquired successfully. Otherwise, it contains error message """ # get the cross account role name cross_ac...
ffa367702c5ecffb6a5117bac5407ede5cdc4b13
41,360
def generate_config(context): """ Creates the Cloud SQL instance, databases, and user. """ properties = context.properties res_name = properties.get('name', context.env['name']) project_id = properties.get('project', context.env['project']) instance = get_instance(res_name, project_id, properties)...
df624472b40bf983329ca8e1a58e9b9d55e95e65
41,361
import uuid import os import time def post_exposure(): """ Upload an exposure resource --- description: Uploads an exposure resource by posting an exposure tar file. The tar file can be compressed or uncompressed. produces: - application/json responses: 200: ...
c803c1c618e340f64df7df45556cc29ea62fd7a2
41,362
def loads(strng, root_name=DEFAULT_ROOT_NAME, single_root_node=False, id_mapper=None): """load a config from a string. Args: strng: the string containing the config file root_name: the tag for the top-level node that is added implicitly single_root_node: if true, no implicit t...
0c8fdb9886b051161cdb321abbad150e453d69b2
41,363
from pathlib import Path def create_server_arguments( configuration: configuration_module.Configuration, start_arguments: command_arguments.StartArguments, ) -> Arguments: """ Translate client configurations and command-line flags to server configurations. This API is not pure since it needs ...
0bf2d8c34b81e9b7800b1c6b95a044f1c11b13bf
41,364
def getLabels(kmeans, options): """@brief Labels all centroids of kmeans object to their color names @param kmeans KMeans object of the class KMeans @param options DICTIONARY options necessary for labeling @return colors LIST colors labels of centroids of kmeans object @return ind ...
8b5be98b82c0bc47369e3b980a81e512f84e31e9
41,365
def replace_surrogate_encode(mystring, exc): """ Returns a (unicode) string, not the more logical bytes, because the codecs register_error functionality expects this. """ decoded = [] for ch in mystring: # if PY3: # code = ch # else: code = ord(ch) # ...
e56d0267378ca5e29cc5ed55e359c384c84400a0
41,366
def _heom_state_dictionaries(dims, excitations): """ Return the number of states, and lookup-dictionaries for translating a state tuple to a state index, and vice versa, for a system with a given number of components and maximum number of excitations. Parameters ---------- dims: list ...
819c4e63f389ec8755e0ea92a98ee1c1e8749c08
41,367
import os def get_file_names(path): """ Given a dir path, returns a list of files in this dir, not includes its child dir :param path: :return: """ names = [] if os.path.exists(path): for (dirpath, dirnames, filenames) in os.walk(path): names.extend(filenames) ...
574cbe862f16347809675895bddeb1d5c3b6cfff
41,368
def _get_num_els_in_scene_range(zarr_dataset: ChunkedDataset, scene_index_start: int, scene_index_end: int) -> dict: """ Get numbers of scenes, frames, agents, tl_lights in a set of scene in a zarr Args: zarr_dataset (ChunkedDataset): zarr dataset to use for computing number of elements scen...
561c9c58c9627bc56902ca6a9a904b6bfa063f22
41,369
def fill_nulls_w_own_distribution(column: Series) -> Series: """Finds the distribution of filled values in a column and fill its nulls with the same distribution :param pandas.Series column: column to fill nulls :return pandas.Series: column with nulls filled """ # Copy to avoid direct changes in ...
c1168b39b380c21758d6c1700a7d020fd1fbf008
41,370
def compute_data_term_gradient_vectorized(warped_live_field, canonical_field, live_gradient_x, live_gradient_y, scaling_factor=10.0): """ Vectorized method to compute the data term gradient :param live_gradient_x: x-component of the gradient of the warped_live_field...
42861bc4a357e533c78a397b788228eca26b216a
41,371
from pathlib import Path def find_mount(path: Path): """Given a path, derive its mountpoint path""" mount_path = path while not mount_path.is_mount(): mount_path = mount_path.parent logger.debug(f"Found mount for {path}: {mount_path}") return mount_path
4a5b3716fa22fdb6d2fd941024ea46db77e579be
41,372
def pid(db, record): """File system location.""" return recid_minter(record.id, record)
5757419926629dc3862914202b2a37ff0c6777f4
41,373
from typing import Tuple def find_start_end(cus_list, pattern) -> Tuple: """ Find the start & end of pattern in cus_list. If none, return 0,0. :param cus_list: :param pattern: :return: """ for i in range(len(cus_list)): if cus_list[i] == pattern[0] and cus_list[i:i + len(pattern)] ...
e4d9c30c9050cb35a0123e7467d3c68c48c7887d
41,374
def timecoverage(): """ Time intervals of GLDAS data """ return [ ('All Available Times', 'alltimes'), (2019, 2019), (2018, 2018), (2017, 2017), (2016, 2016), (2015, 2015), (2014, 2014), (2013, 2013), (2012, 2012), (2011, 20...
f6f279c8f223a361785cc3a72cebfa02101f099f
41,375
from ..jupyter.pv_ipygany import check_colormap import sys import logging def make_mapper(mapper_class): """Wrap a mapper. This makes a mapper wrapped with a few convenient tools for managing mappers with scalar bars in a consistent way since not all mapper classes have scalar ranges and lookup table...
47ff9763ebe91c052d9b8ca54f605283f0ea06b6
41,376
def CDL3LINESTRIKE(data: xr.DataArray) -> xr.DataArray: """ Three-Line Strike (Pattern Recognition) Inputs: data:['open', 'high', 'low', 'close'] Outputs: double series (values are -1, 0 or 1) """ return multiple_series_call(talib.CDL3LINESTRIKE, data, ds.TIME, ds.FIELD, [f.OPEN...
e6e240952ba8e81f1c0ef3bd4e10e0b9186ca5eb
41,377
from typing import Union def check_ess_certid(cert: x509.Certificate, certid: Union[tsp.ESSCertID, tsp.ESSCertIDv2]): """ Match an ``ESSCertID`` value against a certificate. :param cert: The certificate to match against. :param certid: The ``ESSCertID`` value. ...
268af8462decec09ab2a20be14f5319439b55bb3
41,378
import bz2 import base64 def passx_decode(passx): """decode the obfuscated plain text password, returns plain text password""" return bz2.decompress(base64.b64decode(passx.encode("ascii"))).decode("ascii")
b8b2138c55dd28734661484a231128e6f3ccbbb7
41,379
def cloudfront_restriction_type(restriction_type): """ Property: GeoRestriction.RestrictionType """ valid_values = ["none", "blacklist", "whitelist"] if restriction_type not in valid_values: raise ValueError( 'RestrictionType must be one of: "%s"' % (", ".join(valid_values)) ...
d8f7a248800d0b93f0ceee60cd40227d92614341
41,380
def variance_scaling_initializer(tensor, factor=2.0): """ Variance scaling initializing using FAN_AVG, similar to the one in TF :param tensor: A tensor of arbitrary shape. :param fan_in: int :param fan_out: int :param factor: A scalar, the scaling factor. :returns: A tensor with the same shape ...
ed5b2f278cfd33858f59cd8ebdf48814426f5436
41,381
import tokenize import collections import random def convert_single_example(example, tokenizer, is_training): """Converts a single NqExample into a list of InputFeatures.""" tok_to_orig_index = [] orig_to_tok_index = [] all_doc_tokens = [] features = [] for (i, token) in enumerate(example.doc_tokens): ...
04eaa4652246803bb8a96ac2f2eac7a8b188ee92
41,382
from typing import Union from typing import Tuple def calcCog(argument: Union[str, list]) -> Tuple[float, float, float]: """ calculates the Center of Geometry of a given selection or list of atoms Args: argument (str or list): either a PyMOL-selection name or a List of atoms Returns: ...
8694f5949c21ced81b8a7d7e8dc4c89842a1ea2c
41,383
import subprocess as subp from typing import OrderedDict import sys import os def IMcleaner(dpath, site, scheck, coords, verbose, test = False, dsinfom = "LANDSAT_5_7_8"): """ Function to clean the data up and make the visualisation better """ # ========== setup the key params ========== SF = 0.0001 # Scal...
9c2a7dcfdeaac2490cd3dbc038742a20d3d81d27
41,384
import sys import subprocess def isort( config: c2cciutils.configuration.ChecksIsortConfig, full_config: c2cciutils.configuration.Configuration, args: Namespace, ) -> bool: """ Run isort check on all files including Python files without .py extension. config is like: ignore_patterns_re:...
f33dc30254d36a429f8e2e6dfc3eba36f4ce54b2
41,385
import threading def create_image_server(): """ Create flask image debug server. Warning! This is a very hacky flask server. Make sure to only run this once as it uses global stare Returns: Dictionary into which you can insert images with string keys """ threading.Thread(target=lambd...
4d78f3733923a17252c6163616918dd09961f416
41,386
import scipy def find_peaks(signal, fs, min_separation=270, window_width=2500, noise_level=1.25): """Find peaks from pulse oximeter or ECG. Args: signal: Pulse oximeter or ECG data. fs: Sampling frequency (Hz) of the signal. min_separation: Strict minimum time between peaks (ms). ...
c892561960c5ebe299de30fa67012b12d5dcd743
41,387
def evaluate_rm_gold(prediction, ground_truth): """ Evaluation matrix. :param prediction: a dictionary of labels. e.g {0:[1,0],1:[2],2:[3,4],3:[5,6,7]} :param ground_truth: a dictionary of labels :return: """ pos_gt = 0.0 pos_pred = 0.0 true_pos = 0.0 for i in ground_truth: ...
98eeb3fa0ffe4f9b3d0863a41bd3ca5d6c4a036f
41,388
from pathlib import Path def is_git_bundle(path: Path) -> bool: """Indicate if a path is a valid git bundle.""" with TemporaryDirectory(prefix=f"{__name__}.is_git_bundle.") as dirname: with local.cwd(dirname): git("init") return bool(git["bundle", "verify", path] & TF)
b1120f27111ed4f31bb408ee31b230e6cefaa733
41,389
import os def find_file(path, ext, index=0, sort='getctime'): # unused """ Search files by extension, sort by time created and return indexed file. """ files = [x for x in os.listdir(path) if x.endswith(ext)] files = sorted(files, key=lambda x: os.path.getctime(os.path.join(path, x)), reverse=True) n...
70788d966294e8886148e16114b698f1786db48d
41,390
def checksum_file(summer, path): """ Calculates the checksum of the file 'path' using the provided hashlib digest implementation. Returns the hex form of the digest. """ with open(path, "rb") as f: # Read the file in 4KB chunks until EOF. while True: chunk = f.read(4096) if not chunk: ...
729b8f895fe74856e83046d0fd5177e584f835f2
41,391
def camel_case(value): """Convert an identifier to CamelCase""" return "".join(ele.title() for ele in value.split("_"))
e7c74ebe7611eb567f3eae8f16fb01aadd201252
41,392
def parallelize (imgs, func, cores=2): """ Execute a function for each image in parallel. This function assumes 'imgs' is multi-frames of grayscale images for the current version. Parameters ---------- imgs : numpy.ndarray (3d) or list of numpy.ndarray(2d) Input multi-frame images. ...
acd5f64501dbe13d46b7b4fafe6df4f3300c7e56
41,393
def getter_function_spectrum(filename): """ partial does not use kwargs so our options are limitted here """ return Spectrum(filename=filename, is_ucd=False)
6e3f547378cf8bbbd9b67f9031380870c23040ef
41,394
def cov_cluster_robust(jac, hess, design_info): """Cluster robust standard errors. A cluster is a group of observations that correlate amongst each other, but not between groups. Each cluster is seen as independent. As the number of clusters increase, the standard errors approach robust standard errors...
98cc96890597e336d5b43b24e8d30fd1893ae9ed
41,395
import re from datetime import datetime def fix_time_units( timeunits ): """Sometimes we get time units which aren't compatible with cdtime. This function will (try to) fix them. The input argument is a string, e.g. "months since Jan 1979" and the return value is another string, e.g. "months since 19...
64f452b35857c741a04689d670f8c3502dd2d82d
41,396
def binary_encoding(string, encoding = 'utf-8'): """ This helper function will allow compatibility with Python 2 and 3 """ try: return bytes(string, encoding) except TypeError: # We are in Python 2 return str(string)
7982f27c266479b757e3a73e9463acd88b98abcf
41,397
def get_all_overlays_config(self) -> list: """Get all configured overlays in Orchestrator .. list-table:: :header-rows: 1 * - Swagger Section - Method - Endpoint * - overlays - GET - /gms/overlays/config :return: Returns list of dictionaries...
3c77c14096373792bdaf5c39ffdc3f9d58b0af0d
41,398
def load_densityoperator(filename): """ Load a C++QED state vector file from the given location. Returns a tuple with a list of densityoperators and a list of times. *Usage* >>> svs,times = load_statevector("ring.sv") :param filename: Path to the C++QED state vector file that should be loade...
c1a3ba6484b86adfa76c8abd28f580f89d2103c8
41,399