content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def all_acc(y_true, y_pred): """ All Accuracy https://github.com/rasmusbergpalm/normalization/blob/master/train.py#L10 """ return K.mean( K.all( K.equal( K.max(y_true, axis=-1), K.cast(K.argmax(y_pred, axis=-1), K.floatx()) ), ...
f707ac258d21bb789bc0c4b8e792b8e42ba03e6f
48,310
def generate_identifier(signingkey): """Generates encoded version of the public key associated with signingkey. Args: signingkey (str): A private key. Returns: str: An encoded 'address' associated with the public key. """ return pybitcointools.pubtoaddr(pybitcointools.privtopub...
6c8311aee007d2732447f27b30b2cc628709bec9
48,312
def get_page(paginated_list): """ Take a github.PaginatedList.PaginatedList and then iterate through the pages to get all of its entries Args: paginated_list (github.PaginatedList.PaginatedList): PyGithub paginated list object Returns: `list`: All entries in the paginated ...
0510537b20c18b6b1be5b10ca014e13be7a19a1f
48,314
def acnt2(chain: pv.Chain, wallet: pv.Wallet) -> pv.Account: """ acnt2 is the fixture that returns the account of nonce 2. Args: chain (pv.Chain): The Chain object. wallet (pv.Wallet): The wallet object. Returns: pv.Account: The account. """ return wallet.get_account(ch...
3156dc4a140f6130682675a92d649d1f5d41d646
48,315
def _get_acc_data(): """ Датасет для графика акселерометра """ time = now() datax, datay, dataz = [_get_data_abstract("IMU", x, time) for x in ("xacc", "yacc", "zacc")] for x, y, z in zip(datax, datay, dataz): x["y"] /= 1000.0 y["y"] /= 1000.0 z["y"] /= 1000.0 latestUpdateT...
6c7fbf18bb5992f255a568af15268463d5ed893d
48,316
def git_ref(check=True): """ return name for current branch / tag If `check` is True, the execution end if git root not found. Otherwise `None` is returned. """ branch = _exec("git rev-parse --abbrev-ref HEAD".split(), check) if branch != "HEAD": return branch tag_ref = _exec("g...
6c4ac95859785404ced853739187bd7da4ebac83
48,317
def get_metadata_from_asset_name(asset_name: str) -> dict: """Get metadata for given asset""" url = f"{POOL_PM_URL}/asset/{POLICY_ID}.{asset_name}" response = get_request(url, headers=None) return response.get("metadata")
37068d9f3b021dc5c66ef9aa6e6ad13135bb010d
48,318
import math def prime(n): """Primality test by trial division.""" if n == 2: return True elif n < 2 or n % 2 == 0: return False else: return not any(n % x == 0 for x in range(3, math.ceil(math.sqrt(n)) + 1, 2))
3504217a7e8149867ec16ddf9c54f4fac736d592
48,321
def is_sukun(archar): """Checks for Arabic Sukun Mark. @param archar: arabic unicode char @type archar: unicode @return: @rtype:Boolean """ return archar == SUKUN
3ccedfb4b73c7d80bf24e0c9b8d04c6309eb9a29
48,323
def radio_util( data # type: "XDR Data" ): """Radio Utilization Counter - Type: Counter, Enterprise: 0, Format: 1002""" sample_data = {} # Cache sample_data["Elapsed Time Milliseconds"] = int(data.unpack_uint()) sample_data["On Channel Time Milliseconds"] = int(data.unpack_uint()) sample_data["On Channel Busy Ti...
5e5c90ca511db1babda427ea7218375542f77bce
48,324
import re from typing import OrderedDict def getNames(xml): """ get person, organization and place tags from PageXML. """ content = re.sub("<\?xml version.*?>", "", xml) try: root = et.fromstring(content) except Exception as e: print(e) return {"XMLERROR":"XMLERROR"} ...
5a0ba6ba9b3ec6c303adc1d27680e01dadecd64c
48,325
def get_xls(es_result, column_mapping): """ Creates a stream with the Excel file, the column headers, and the result rows :param es_result: The result of the ElasticSearch search :param column_mapping (dict): A dict mapping the column names in the original data, to the desired column headers for th...
8caa799586ef910818338f0e0e7300df267dbdd0
48,326
def average(numbers): """ :param list[float] numbers: a list of numbers :returns: the average of the given number sequence. an empty list returns 0. :rtype: float """ return float(sum(numbers)) / max(len(numbers), 1)
d86c6f24733d3032b82cb6c64c02eba37cc34a04
48,327
import six def _IsIdentityTypeMapping(type_mappings): """\ An identity type mapping is a special case where each of the input types matches the output type. """ for input_type, output_types in six.iteritems(type_mappings): if output_types != [input_type]: return False ret...
27f13266dc23c5d4bd78a27c240664208d4f8c8f
48,328
def inv_rotate(vec: Vector3, quat: Quaternion): """Rotates a vector by the inverse of a unit quaternion. Args: vec: (3,) a vector quat: (4,) a quaternion Returns: A vector rotated by quat^{-1} """ return rotate(vec, quat_inv(quat))
f77e301b5feff76bf73850189c48a14c00d61339
48,329
def play_manche_joueur(): """ cette fonction propose au joueur de jouier une manche si il fauit 1 , son score est annulé et la fonction retourne -1 Returns: le total de la cagnote """ cagnote=0 if input("voulez vous lancer un dé ? (y pour relancer, ou anykey pour arréter)\n")=="y": ...
0c0bc49093ba8d602e6617f10d616ad3f290d14f
48,330
def crossProduct(u, v): """ Calculates the cross product of two 3d vectors (as 1-d arrays). """ return np.cross(u, v)
e6da5b203f6617a7400f9b3f327434f70ca3f686
48,331
def vgg13_bn(backbone='vgg13_bn', pretrained=False, **kwargs): """VGG 13-layer model (configuration "B") with batch normalization Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ kwargs['cfg_key'] = 'B' kwargs['batch_norm'] = True kwargs['backbone'] = "vgg13...
a56f6b5d4899c1f6eb02c12d92ad4e2f57228c5d
48,332
from operator import sub def get_resource_type_by_url(url: str): """Get the resource type definition from a resource URL.""" url_parts = urlparse(url) url_path = url_parts.path resource_type = sub(r'/(core|rest|identity|auth|product-metadata)/v\d+/([^/]+)/?.*', r'\2', url_path) if resource_type ==...
9f525eb5f841d61db29d2ec2413cfa687c2c6287
48,333
def general_pool_fn(x): """ x[0]: function to call x[1] to x[n]: arguments of the function """ return x[0](*x[1:])
d398378d3d1671f0e58bff2bc8737ff07da0c3e3
48,334
def getfullname(val): """Get the module-qualified name of type or function val.""" return (val.__module__ or '<UNKNOWN_MODULE>') + '.' + getqualname(val)
3f8e9570219d5dcae45313e5bc530f8892b33a34
48,335
def dt_hms(d, n=3): """ Allow negative times """ try: sign = '+' if d > 0. else '-' x = abs(d) h = int(x) x = (x-h) * 60. m = int(x) s = (x-m) * 60. w = n + 3 return f"{sign}{h:02d}h {m:02d}m {s:0{w}.{n}f}s" except: return None
30c04b23ba304a1d8dffcdbe38035bdde24b1848
48,336
def get_file_contents(repo_path, file_path): """ Given an absolute file path, return the text contents of that file as a string. """ binary = get_file_contents_binary(repo_path, file_path) try: return binary.decode('utf-8') except UnicodeDecodeError: return binary.decode('lat...
b6d622724c1bb6675eb0c5ec43093d1bfca4bfbe
48,338
import torch def generate_param(n_dimensions: int): """Simulation of model's parameters""" nnz = 20 idx = np.arange(n_dimensions) W = torch.FloatTensor((-1) ** (idx + 1) * np.exp(-idx / 10.)).to(dtype=torch.float64) W[nnz:] = 0. return W
d1fd5f13d65de1368e7ccede89028ec46687c505
48,339
def cleanDf(df, badaa=None): """Remove all invalid sequences (containing badaa) from the alignment badaa is '-*BX#Z' by default""" return df.loc[[isvalidpeptide(s, badaa) for s in df.seq]]
73f485630828ed555502a8e810d3662ffe7512a8
48,340
def minify_css(s): """ Minify CSS code. @param s: css to minify @type s: L{str} @return: the minfied css @rtype: L{str} """ if csscompressor is None: raise NotImplementedError("Dependency 'csscompressor' required, but not found!") return csscompressor.compress( s...
82f78b63418c51b58b7e392db54d0d471de15fc3
48,342
def cumsum(a, axis=None, dtype=None, out=None): """Returns the cumulative sum of an array along a given axis. Args: a (clpy.ndarray): Input array. axis (int): Axis along which the cumulative sum is taken. If it is not specified, the input is flattened. dtype: Data type specifier...
145fd87072a7a196fb609b9d0d57e2321f0eab10
48,343
import math async def async_api_adjust_volume(hass, config, directive, context): """Process an adjust volume request.""" volume_delta = int(directive.payload["volume"]) entity = directive.entity current_level = entity.attributes.get(media_player.const.ATTR_MEDIA_VOLUME_LEVEL) # read current stat...
c71a67450860181799e9fac56379443b5df9fef2
48,344
import random def random_database(): """ Creates a random database in the testing Postgres instance and returns the name of the database. """ # Setup connection with default credentials for testing. with connect(dbname='holo', user='holocleanuser', password='abcd1234', host='localhost') as con...
1fdf929d2531a00e92a3b6801edea5d57cb8d622
48,345
def fscore(target_mat, decision_mat, beta=1., event_wise=False): """ Args: target_mat: n_hot matrix indicating ground truth events/labels (num_frames times num_labels) decision_mat: n_hot matrix indicating detected events/labels (num_frames times num_labels) even...
5bfc11a38d766797cbf5b93aa09b3dca31793f80
48,346
def _EraseTombstone(device, tombstone_file): """Deletes a tombstone from the device. Args: device: An instance of DeviceUtils. tombstone_file: the tombstone to delete. """ return device.RunShellCommand( 'rm /data/tombstones/' + tombstone_file, root=True)
00e6f316062785d7465f501ea743a2dc94864aef
48,347
def graphite_electrolyte_reaction_rate_Kim2011(T, T_inf, E_r, R_g): """ Reaction rate for Butler-Volmer reactions between graphite and LiPF6 in EC:DMC [1]. References ---------- .. [1] Kim, G. H., Smith, K., Lee, K. J., Santhanagopalan, S., & Pesaran, A. (2011). Multi-domain modeling of lit...
15efdc98d2f4b63b2d9482c404f465ec5bd52194
48,348
def initialize_node_details(storage_gui_ip, user, key_file): """ Initialize node details for cluster definition. :args: storage_gui_ip (str), user (string), key_file (string) """ node_details, node = [], {} node = {'ip_addr': storage_gui_ip, 'is_quorum': True, 'is_manager': True, 'is_gui...
cb3c82a5c0e9c418fac88f61473b44a60c0d7c12
48,349
def do_filter(parser, input_list): """ Filter flavor by applying parser on the flavor list :param input_list: list of input data in JSON format :param parser: jsonpath parser :return: list of matched flavors in JSON """ return [match.value for match in parser.find(input_list)]
9a5efe4e80a6fdf3afb0cff9616e4c480de8e26d
48,350
def module(script_in): """Decorate a python function or class as tvm script. Alias for tvm.script.tir for now. Returns ------- output : Union[Function, Module] The Function or Module in IR. """ return tir(script_in)
c9857bdc4a444090928a17f18b980eb03f73c99c
48,352
def shorten_class(class_name: str) -> str: """Returns a shortened version of the fully qualilied class name.""" return class_name.replace('org.chromium.', '.').replace('chrome.browser.', 'c.b.')
2064e6e0dc159bc130f84ce4a830857455d12ba4
48,353
from typing import List def get_words(content: str) -> List[str]: """ 文字列内に出現する名詞のリスト(重複含む)を取得する関数。 """ words = [] # 出現した名詞を格納するリスト。 node = tagger.parseToNode(content) while node: # node.featureはカンマで区切られた文字列なので、split()で分割して # 最初の2項目をposとpos_sub1に代入する。posはPart of Speech(品詞)の略...
cc05e06cef47fc3cce4b1ce79c4fd8d0a755cd59
48,354
import json def create_initial_parameters(instances, Ns): """ Create a list of initial parameters for spectra loaded from task instances. :param instances: A list of task instances where spectra were loaded. This should be length `N` long. :param Ns: A list containing the...
078ecf7ecc6c140d6fe2cb68cac28dca98526b56
48,356
def load_snps_by_region(chrom, start, end): """Retrieve snp information by region""" index = _get_index_from_chr(chrom) search_snps = Search().using(es).doc_type('snps').index(index).filter("range", position={"lte": end, "gte":start}) return {snp.position: snp.to_dict() for snp in search_snps.scan() }
e512eade4e5ca6cc8358306e4843258297566eef
48,357
def weight_function(run_params, displacement_norm): """Determine motion-dependent prediction weight of given supporter point. This method determines the weight to apply to each supporter point when using it for prediction of a target point based on the norm of its displacement vector. The larger the di...
2fdea32511ae8b4cedd47e79d7f8517a08a6b457
48,358
def _read_cp1251_file(fname): """ Returns: Возвращает список и ответ на вопрос - угадали ли мы кодировку? """ this_is_it = True sets = iow.get_utf8_template() sets['coding'] = 'cp1251' sets['name'] = fname # Если не та кодировка - возвращает пустой список readed_list =...
55834a71a4607a6f9bf6fc9f8216e6d17eef6bbd
48,359
def mixed_grad_color2gray(rgb_image): """EC: Convert an RGB image to gray image using mixed gradients.""" img = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2HSV) s = img[:, :, 1].reshape((img.shape[0], img.shape[1], 1)) / 255. v = img[:, :, 2].reshape((img.shape[0], img.shape[1], 1)) / 255. mask = np.ones_...
f8aefe4c836377f87b6d8ce0c4784da0c4115490
48,360
def PReadRec (inHis, recno, err): """ Read History record returns string * inHis = input Python History * recno = desired record * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inHi...
e315f91fa46b8ed99071f681dc490630c256c04a
48,361
def remove_leading_garbage_lines_from_reference_section(ref_sectn): """Sometimes, the first lines of the extracted references are completely blank or email addresses. These must be removed as they are not references. @param ref_sectn: (list) of strings - the reference section lines @retu...
09dc153b064cd8fcf613520ef432e51350928307
48,362
def ensure_csrf_cookie_cross_domain(func): """View decorator for sending a cross-domain CSRF cookie. This works like Django's `@ensure_csrf_cookie`, but will also set an additional CSRF cookie for use cross-domain. Arguments: func (function): The view function to decorate. """ def...
ecdeae3ebff37976c841887083c53f088f2b8b34
48,363
def _algorithm_kwargs(request): """Auto-parametrizes `_rl_algorithm_cls` for the `trainer` fixture.""" return dict(request.param)
fddb2a376449973f49d5a27cef04b3596e9cc3dd
48,364
from typing import Dict def convert_tsv_entries_to_dataframe(tsv_dict: Dict, header: str) -> pd.DataFrame: """ Converts entries from TSV file to Pandas DataFrame for faster processing. """ header_fields = header.strip().split("\t") data = {header: [] for header in header_fields} for line in tsv_dict.valu...
2fbbb125f5dfa8bad2efabc420295f0925d9786e
48,365
def decode_and_upload_base64_file(data, file_name): """ Function to decode base64 files Parameters ---------- date : str string of user inputted graduation date. Returns ------- string string of graduation date only with Month and Year. "...
3503ad48de0aa1278c859cd096e735e114eed9c3
48,366
def calc_sthovl_by_hkl_abc_cosines( h: float, k: float, l: float, a: float, b: float, c: float, cos_alpha: float, cos_beta: float, cos_gamma: float): """ Calculate sin(theta)/lambda for given reflections h, k, l and unit cell parameters defined as a, b, c, cos(alpha), cos(beta), cos(gamma). ...
a5b8d01b970fdd5fd09a8b157b925952987a14d7
48,367
def RE2Str(RE): """Helper for del_gnfa_states --- Given an RE as a tree, return the string equivalent of the RE. """ if type(RE) == str: if (RE == ""): return '""' # was return '@', but now no more '@' else: return RE elif type(RE) == tuple: ...
966d4dc06e597518ab7306ea3f5c970cf4534efa
48,368
import json def list_observations(model): """Return a JSON list of observations""" obs = model.get_observations() response.content_type = "application/json" return json.dumps(obs)
a82f1148ee72d5690a7488b26f2030da8cd85911
48,369
def add_api_config_to_queries(generated_query_strings, search_engines): """ Merges the two parameters and returns a list of dicts that include the api config. If only 1 API key is provided, it is assumed this is valid for many searches and is used for all queries If more than 1 is p...
209b14e98c2cb339f958fc7dfe456a4a40876c8c
48,370
def _get_first_model(structure: PdbStructure) -> PdbStructure: """Returns the first model in a Biopython structure.""" return next(structure.get_models())
fb3431655ef7f83aa50931f96696ffe296bb6501
48,371
def createDiffLineCV(video, cropx1, cropx2, cropy1, cropy2): """ Binarizes video and returns a frame to frame difference trace. Inputs: video - list of images cropx1 - int, crop pixel starting for first dimension cropx2 - int, crop pixel ending for first dimension cropy1 - int, crop pixel st...
fb6793f3b44e6b042df97588ceebc178ee8c2bb2
48,372
def convert_entity_schema(entity_schema): """ Convert entity schmea to record schema """ spots = list() asocs = list() spot_asoc_map = dict() for entity in entity_schema: spots += [entity] spot_asoc_map[entity] = list() return spots, asocs, spot_asoc_map
6e3cc2bbecbbd88312c1a486142d9e8a50a5e39a
48,373
def get_inchi_key(mol: Molecule) -> str: """Get an InChI key from a molecule.""" return inchi.generate(mol).getKey()
81d4065ee2364ebbdedfa69ebdd450cd372638fc
48,374
def process_raw_input(input, source='html'): """ Parameters ---------- input type Returns ------- processed text (str) """ if source == 'html': return '\n'.join(input) elif source == None: return input
f1e3b45ed8507b910f18f9a44856e17e530b4119
48,375
def get_pheno_list(serotype_hits, session): """ Function to return phenotype list from list of serotype hits (deduplicated) :param serotype_hits: list of serotype hits from stage 1 mash analysis :param session: DB session :return: list of deduplicated phenotypes or groups """ out_res = [] ...
335fafb66dd04be0b20775d086cbafd93900f080
48,376
def get_review_dates(app_reviews) -> pd.DataFrame: """Create a new dataframe, `reviewDates`, with the number of reviews for each app per year""" review_dates = ( app_reviews.groupby(["appId", "reviewYear"])["appId"] .count() .unstack() .reset_index() ) app_total_reviews ...
d92f7ed51a9c77f1ada409350d05872920489c3e
48,377
def validate(config): """ Validate the beacon configuration """ # Configuration for memusage beacon should be a list of dicts if not isinstance(config, list): return False, "Configuration for memusage beacon must be a list." else: _config = {} list(map(_config.update, con...
eddeb201e7789fdf3440513ca006813e49930a81
48,378
def mmd_t( dist_xx, dist_xy, dist_yy, batch_size, alpha=1.0, beta=2.0, var_target=None, name='mmd', do_summary=False, scope_prefix=''): """This function calculates the maximum mean discrepancy with t-distribution kernel The code is inspired by the Github page of following paper: Binkowski M...
6c5f935ebba86b2ed42b3039c5454795075fe17a
48,380
def reset_from_schedules(scheduler): """"Reset all scheduler jobs, using information from the JSON object :param scheduler: the TornadoScheduler instance to modify :type scheduler: TornadoScheduler :returns: True in case of success :rtype: bool""" ret = False try: scheduler.remove_a...
1bf1bd20bbba7af5fba156c6632d0b86a616feba
48,382
import pandas as pd from sklearn.metrics import roc_auc_score, roc_curve from sklearn.metrics import precision_recall_curve, average_precision_score def get_threshold_metrics(y_true, y_pred, drop_intermediate=False, disease='all'): """ Retrieve true/false positive rates and auroc/aup...
be44c49f1d0c8dbb6ef1543a538efb03d3cda3a4
48,383
from typing import Dict from typing import Any import requests def pull_astronaut_list(url: str ='http://api.open-notify.org/astros.json') -> Dict[str, Any]: """ Pull a list of astronauts via API. Defaults to open-notify's API. Args: url: the URL to pull data from. Returns: A dict co...
d008cd1d62a435086dbd8dc08baaa5323298f11c
48,384
def get_widget_for_attr(traits_ui, attr_name): """ Return the Qt widget in the UI which displays the attribute specified. """ x_editor = traits_ui.get_editors(attr_name)[0] qt_widget = x_editor.control return qt_widget
2bb2959963734bee48d067f41425808412bd2421
48,385
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload Bold config entry.""" if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): del hass.data[DOMAIN][entry.entry_id] return unload_ok
cfab6c4d2e7ff1fdb261b95641128dda0153be7e
48,386
def strip_url(url, origin_only=False): """ 参考 https://www.w3.org/TR/referrer-policy/#strip-url 去除敏感信息如username :param url: :param origin_only: :return: """ if not url: return None parsed_url = urlparse(url) netloc = parsed_url.netloc if origin_only and (parsed_url.use...
b424909e70d5078292c700a4605b9a493d22cb0a
48,387
def eval_single_file(simulation_output_dir): """ number of cells number of cells detected """ sim_dat_dir = simulation_output_dir[0:simulation_output_dir.rindex('/')] true_barcodes = get_barcodes_set( '%s/true_barcodes.txt' % (sim_dat_dir)) pred_barcodes = get_barcodes_set( '%s/threshold_paths.txt' % simul...
816aed4808fe21abb91b483ea7fc5aedf1c49d2a
48,388
def all(*args, span=None): """Create a new expression of the intersection of all conditions in the arguments Parameters ---------- args : list List of symbolic boolean expressions span : Optional[Span] The location of this operator in the source code. Returns -------...
f0cebfb241c10c2d53c58a8b4fb186e9d65a1b7a
48,389
def plot_all_answer_traces(inputtrace: np.ndarray, colors: list) -> list: """ This function plots the answer traces of all tests; one plot per test. :param inputtrace: Dataframe with the answer trace. Attributes of the dataframe: test, approach, answer, time. :param colors: List of colors to use for th...
26e5bcf8378a4b2ad77b202f2c11f8347bfffb31
48,390
from datetime import datetime def initialise_library(members, items, item_copies, library): """Takes in items that needs to be populated into the library, and conduct a series of pre-defined events by members (loan, renewal, return) The Library object after conducting the events is used to initialise...
0f5021358dd701790be75140673ede4634de1a41
48,391
def update_cache_bykey(cache_list, new_list, key='id'): """ Given a cache list of dicts, update the cache with a 2nd list of dicts by a specific key in the dict. :param cache_list: List of dicts :param new_list: New list of dicts to update by :param key: Optional, key to use as the identifier to upd...
b077a1c40cbf0a8848ff9e017a644c20e1d25199
48,392
def calc_theor_avg_mass(dictionary, cfg, prec=6, reducing_end=None) -> float: """Returns theoretical average mass for glycan in dictionary form""" reducing_end_tag_mass = 0.0 if reducing_end is not None: if reducing_end in cfg["reducing_end_tag_avg"].keys(): reducing_end_tag_mass = cfg["...
32a5aab08463366e8b43d13f2891489d94ab075a
48,393
def get_node_info(session, node_id): """Wrapper for HAPI_GetNodeInfo Fill an NodeInfo struct. Args: session (int): The session of Houdini you are interacting with. node_id (int): The node to get. Returns: NodeInfo: NodeInfo of querying node """ node_info = HDATA.NodeInf...
16b6200ec083da4cc15f57a02c53e0431cdc56a7
48,395
def Eliminar_Columnas(df, Dic): """ Recibe el dataframe y el listado de las columnas que se quieren eliminar """ df = df.drop(columns=Dic) return df
96c049508f196406807cc9102b87cb4aa4884650
48,396
def getCurrentUser(): """ Get the current user associated with whatever email is stored in session """ if 'email' not in session: return None email = mailsane.normalize(session['email']) if email.error: return None return getUser(str(email))
9709c927c3d4fb7e74911859962c521eeaf3e2de
48,397
def wgs84_to_web_mercator(df, lon="LON", lat="LAT"): """convert mat long to web mercartor""" k = 6378137 df.loc[:,"x"] = df[lon] * (k * np.pi/180.0) df.loc[:,"y"] = np.log(np.tan((90 + df[lat]) * np.pi/360.0)) * k return df
94ec56293ecc9510d4f6687b941253be359274ee
48,398
def process_medusa(line): """ Process a medusa line and return a dictionary :param line: A line from a medusa output file :returns dict: A dictionary based upon the content { 'ip' : ip address 'port': port info - can be port # or module name 'user': username, 'pass': password, ...
406fdaeee3ae91399095a9ae86feb5c3f9d66e60
48,399
def parse_tpl_file(tpl_file): """ parse a pest template file to get the parameter names Parameters ---------- tpl_file : str template file name Returns ------- par_names : list list of parameter names """ par_names = [] with open(tpl_file,'r') as f: try...
0797cfedbef07dcd118e13440691c287f952a740
48,400
def find_factors(n): """ Finds a list of factors of a number """ factList = {1, n} for i in range(2, int(n ** 0.5) + 1): if (n % i == 0): factList.add(i) factList.add(n // i) return sorted(factList)
0b8992bfe81bfd49c738b49380ceb0c8e7155b3f
48,401
def unique(a): """ Return the list with duplicate elements removed. Args: a (list): A list. Returns (list): The list with duplicate elements removed. """ # NOTES: # 1. Built-in function 'set()' can convert a list (ordered) into a set (unordered). # 2. B...
1aeac608e53ebc91cb0709b69fc8731f0ad39562
48,402
from typing import Tuple def sim_seird_decay( s: float, e:float, i: float, r: float, d: float, beta: float, gamma: float, alpha: float, n_days: int, decay1:float, decay2:float, decay3: float, decay4: float, step1_delta: int, fatal: float ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarra...
4217488020bfcf28020fc31aee898655a6cf191e
48,403
def do_quote_form(expressions, env): """Evaluate a quote form. """ check_form(expressions, 1, 1) # BEGIN Question 6B return expressions.first # END Question 6B
989df694053dfeeb774a9062aea3a27cb0ddcc38
48,404
def make_flatmap_image(braindata, height=1024, recache=False, **kwargs): """Generate flatmap image from volumetric brain data This Parameters ---------- braindata : one of: {cortex.Volume, cortex.Vertex, cortex.Dataview) Object containing containing data to be plotted, subject (surface id...
fc36acb5701e6b9346fe676b18cb109dad314d88
48,405
from typing import List def compute_i_k_index(citations: List[int], k: int = 10): """Given a list of citations (integers) compute the i-k-index (default i10).""" citations = np.asarray(citations) i_k_index = (citations > k).sum() return i_k_index
16ba1e7be56d10d2e5ff9e20d97df86ee482a899
48,406
from datetime import datetime def get_session_details_helper(client): """ Retrieve details regarding the current session within `client` :param client: ICAT client containing an authenticated user :type client: :class:`icat.client.Client` :return: Details of the user's session, ready to be conver...
2c1d714f6e131f7639a44a41ed6e0d45cb54b5b3
48,407
def resnet18(use_rp=False, width=1, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ if use_rp: print('model using random projection') model = ResNetRP(width, bb.BasicBlockRP, [2, 2, 2, 2], **kwargs) els...
cd51bc95741b3e5ea78145af71091658c8c8e25f
48,408
def assign_seller(request, campaign_id): """ Shows a list of sellers to assign contacts to. """ campaign = Campaign.objects.get(pk=campaign_id) campaign.count = ContactCampaignStatus.objects.filter(campaign=campaign, seller=None).count() message = "" if request.POST: seller_list = [...
1945384df939306fc5379ae2b071446116b85997
48,409
def _swissroll_dataset(): """Interwined spirals.""" sz = 100 Y = np.arange(sz) % 2 t = np.linspace(0, 4 * np.pi, sz) X = t[:, None] * np.vstack([np.cos(t + Y * np.pi), np.sin(t + Y * np.pi)]).T X += 0.2 * np.random.randn(*X.shape) return X, Y
388969317aff95be12fed6545f7f6eb8102bbce7
48,410
def load_mat_data(dataset_str): """ dataset_str: protein, metabolic, conflict, powergrid """ dataset_path = 'data/' + dataset_str + '.mat' mat = loadmat(dataset_path) if dataset_str == 'powergrid': adj = sp.lil_matrix(mat['G'], dtype=np.float32) feats = None return adj, feats ...
73cfc51aeeb9fdc08cd9a727402791c1bfc5e970
48,411
def filter_row_by_data_type(col_name, data_type=None, get_type=False): """ A Pandas UDF function that returns bool if the value match with the data_type param passed to the function. Also can return the data type :param col_name: Column to be process :param data_type: The data_type to be compared wi...
552e930bd3b56c71efd89be051f4faf7f783adac
48,412
def get_ajax_job_status_msg(jobid): """return the job status msg (as a string)""" # user's browser requesting job status msg global STAT_CODE_RUNNING if not validate_jobid(jobid): return Response("Invalid Job ID: %s" % jobid, mimetype='text/plain', headers = {'X-Dalton-Webapp':'OK'}) stat_co...
69d6eaa5753a69b714b03d93299ab3423d607921
48,413
import shelve def run(args, config, prog_args): """Run an experiment.""" name = args.name repo = pygit2.Repository('.') with shelve.open('.em', writeback=True) as emdb: exp_info = emdb.get(name) if exp_info: if exp_info['status'] == 'running': return _die(E...
259a27861b149daff3948f27883f672c64bb3ff3
48,414
from datetime import datetime def EarliestActiveTimestamp(): """Calculates the earliest timestamp of an active channel. Returns: A DateTime representing the earliest possible timestamp of an active channel. """ return datetime.now() - timedelta(hours=CHANNEL_LIFETIME_HOURS)
848eb41ebac30778ec3fac7bc3afd71b65d931b4
48,415
def get_avg_male_ellipse(exp): """Gets the average major and minor axis lengths of the ellipse fitted to the male for all males across all groups in an experiment. Parameters ---------- exp : FixedCourtshipTrackingExperiment Experiment to get average ellipses from. Returns ------- ...
c65bdd7883cea9007b233a46fa75d15c95fcedb9
48,416
def on_request(f, name=None): """ An interceptor which updates the context value of `REQUEST` during the enter stage. :param f: Callable to update the request. :param unicode name: Interceptor name. :rtype: Interceptor """ return middleware(f, None, name=name)
9dfe6bd77693d63ff60a9edc82700ae26a86a14d
48,417
import tokenize def build_model(): """Build the model Returns ------- sklearn.pipeline.Pipeline The model """ pipeline = Pipeline([ (const.FEATURES, FeatureUnion([ (const.TEXT_PIPELINE, Pipeline([ (const.VECT, CountVectorizer(tokenizer=tokenize)), ...
305642beb9250d12e3f1019b461eeb151e253fbb
48,418
import copy def extend_and_specialize(items, loader): # type: (List[Dict[Text, Any]], Loader) -> List[Dict[Text, Any]] """Apply 'extend' and 'specialize' to fully materialize derived record types.""" items = deepcopy_strip(items) types = {t["name"]: t for t in items} # type: Dict[Text, Any] ...
0480c3dd1dd8dfef4c460e592717f9d5c9eede72
48,419
import json def curl(url, tokens=None, headers=None, request_type="GET", data=None, parse=False, validate=False, soft_validation=False): """ :rtype type """ _headers = {} handler_chain = [] post_req = ["POST", "PUT"] get_req = ["GET", "DELETE"] print_url = Options.CURL_PRINT_ONLY is not None...
9ef6d5d2e18acb9d4037ce0faed0ddc185f56a67
48,420
def reorder_atoms(mol): """change index of the atoms to ensure atoms are ordered by ascending residue number """ order = [(i.GetPDBResidueInfo().GetName().strip(), i.GetPDBResidueInfo().GetResidueNumber()) for i in mol.GetAtoms()] # currently the atom name is not used in sorting order = [i[0] for i in s...
dc87436974482b1c815ff43b2c3030a31ad49e95
48,421