content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import numpy as np from collections import OrderedDict import vigra import os import ilastik_main from ilastik.applets.dataSelection import DatasetInfo from ilastik.workflows.pixelClassification import PixelClassificationWorkflow def classify_pixel(input_data, classifier, threads=8, ram=4000): """ Runs a pre...
7a9aaa137e64d3bc7db49404eeaec7bb8c83d9d1
20,300
def invite_accepted_candidates(): """Invites accepted candidates to create an account and set their own password.""" form = InviteAcceptedCandidatesForm() if form.validate_on_submit(): selected = [ Candidate.query.filter_by(id=c).first() for c in form.selected_candidates.data.split(',') ] us...
7e4165f774f4594afa52cc97420c8b212175c6c9
20,301
def ramp_overlap(x0, y0, w0, h0, angle0, x1, y1, w1, h1, angle1): """Calculates the overlap area between two ramps.""" # Check if bounding spheres do not intersect. dw0 = _rect_diagonal(w0, h0) dw1 = _rect_diagonal(w1, h1) if not bounding_circles_overlap(x0, y0, dw0, x1, y1, dw1): return 0. # Check if...
78b261bacc4d90d40e2fc80e9f665d80de6b7574
20,302
def url_external(path, query): """Generate external URLs with HTTPS (if configured).""" try: api_url = request.url_root if settings.URL_SCHEME is not None: parsed = urlparse(api_url) parsed = parsed._replace(scheme=settings.URL_SCHEME) api_url = parsed.geturl(...
27e73834e47a08b4e22fe89587974da386826627
20,303
def get_bucket_metadata(bucket, user_settings=None, access=ServiceAccount.STORAGE): """ Retrieves metadata about the given bucket. :param str bucket: name of the Google cloud storage bucket :param dict user_settings: optional, A dictionary of settings specifying credentials for appropriate services. ...
9a587cf4ebba94499d21b7b734586dfd9228aa23
20,304
import re def remove_conjunction(conjunction: str, utterance: str) -> str: """Remove the specified conjunction from the utterance. For example, remove the " and" left behind from extracting "1 hour" and "30 minutes" from "for 1 hour and 30 minutes". Leaving it behind can confuse other intent parsing...
67313565c7da2eadc4411854d6ee6cb467ee7159
20,305
def othertitles(hit): """Split a hit.Hit_def that contains multiple titles up, splitting out the hit ids from the titles.""" id_titles = hit.Hit_def.text.split('>') titles = [] for t in id_titles[1:]: fullid, title = t.split(' ', 1) hitid, id = fullid.split('|', 2)[1:3] titles.a...
fa5bbb47d26adbc61817e78e950e81cc05eca4a6
20,306
import subprocess def unlock_device(password=None, device=None) -> bool: """ Unlocks a device given a device name and the password :param password: :param device: :return: True is sucess, False if error """ command_input = ["adb", "-s", device, "shell", "input", "text", password] comm...
cd591ccaeb49045845dbeb5152fdbb7d4846c63c
20,307
from ..preprocessing.windowers import _check_windowing_arguments def create_from_mne_epochs(list_of_epochs, window_size_samples, window_stride_samples, drop_last_window): """Create WindowsDatasets from mne.Epochs Parameters ---------- list_of_epochs: array-like list...
42c7671f7b353db165a41403b760362c0ca15d74
20,308
def definstance(name, ty, expr): """ Arguments: - `name`: a string - `ty`: a type of the form ClassName(t1,...,tn) """ root, _ = root_app(root_clause(ty)) if root.info.is_class: class_name = root.name c = defexpr(name, expr, type=ty, unfold=[class_name]) conf.cur...
1b692a9ac49bc6a68568ee232e6e516f83b64adf
20,309
import traceback def do(*args, **kwargs): """ Function to perform steps defined under ``nornir:actions`` configuration section at: * Minion's configuration * Minion's grains * Minion's pillar data * Master configuration (requires ``pillar_opts`` to be set to True in Minion config fi...
69ebb7939c1b8450935dd2e1fcdc14de40cebc0d
20,310
from typing import List def read_plaintext_inputs(path: str) -> List[str]: """Read input texts from a plain text file where each line corresponds to one input""" with open(path, 'r', encoding='utf8') as fh: inputs = fh.read().splitlines() print(f"Done loading {len(inputs)} inputs from file '{path}...
27b00f4dfcdf4d76e04f08b6e74c062f2f7374d0
20,311
def extract_tool_and_dsname_from_name(row): """ Extract Basecall (MB1.6K) into Basecall and MB1.6K, and 1600 three fields :param instr: :return: """ try: toolname, dsname = row['name'].strip().split(' ') dsname = dsname[1:-1] except: # No tag process toolname = row['...
f02b106da47544c522499af1ee8670870749fb20
20,312
def pyramid_pooling(inputs, layout='cna', filters=None, kernel_size=1, pool_op='mean', pyramid=(0, 1, 2, 3, 6), flatten=False, name='psp', **kwargs): """ Pyramid Pooling module. """ shape = inputs.get_shape().as_list() data_format = kwargs.get('data_format', 'channels_last') static_...
1484a686791cd017a53d182994e19b333ffc00b3
20,313
def df(r, gamma): """ divergence-free function """ eta = soft_threshold(r, gamma) return eta - np.mean(eta != 0) * r
bf4d0a5d8bcbb5fa80b66d1dd555f15a44117319
20,314
def clip_3d_liang_barsky(zmin, zmax, p0, p1): """Clips the three-dimensional line segment in the canonial view volume by the algorithm of Liang and Barsky. Adapted from James D. Foley, ed., __Computer Graphics: Principles and Practice__ (Reading, Mass. [u.a.]: Addison-Wesley, 1998), 274 as well as h...
2ffcb60a4b2b13344f2255f5d5d1816199c666a4
20,315
def RunLatencyTest(sending_vm, receiving_vm, use_internal_ip=True): """Run the psping latency test. Uses a TCP request-response time to measure latency. Args: sending_vm: the vm to send the tcp request. receiving_vm: the vm acting as the server. use_internal_ip: whether or not to use the private IP ...
5f235f0adefe988be564f8e6dce7edfd4f292be4
20,316
def get_descriptor_list(stackdriver): """Return a list of all the stackdriver custom metric descriptors.""" type_map = stackdriver.descriptor_manager.fetch_all_custom_descriptors( stackdriver.project) descriptor_list = type_map.values() descriptor_list.sort(compare_descriptor_types) return descriptor_li...
9b4b16f3d3b0330a786db0310f889f8ac132cb32
20,317
def dankerize(string: str, upper_case_ratio=0.2) -> str: """ Transform a string to lower case, and randomly set some characters to upper case and return the result. string: the string to dankerize upper_case_ratio: the upper_case/letter ratio """ ret = "" for i in range(len(...
55f186104166b0804cadae2df5fa19deaf36473b
20,318
def distance_constraints_too_complex(wordConstraints): """ Decide if the constraints on the distances between pairs of search terms are too complex, i. e. if there is no single word that all pairs include. If the constraints are too complex and the "distance requirements are strict" flag is set, ...
43429fd64dbf5fa118e2cbf1e381686e1a8518c9
20,319
def greedy_search(model, decoding_function, initial_ids, initial_memories, int_dtype, float_dtype, max_prediction_length, batch_size, eos_id, do_sample, ...
3324a45ce13181ea55c8588e497864526272475d
20,320
import time def database_mostcited(response: Response, request: Request=Query(None, title=opasConfig.TITLE_REQUEST, description=opasConfig.DESCRIPTION_REQUEST), morethan: int=Query(15, title=opasConfig.TITLE_CITED_MORETHAN, description=opasConfig.DESCRIPTION_CITED_MORET...
b18d3a3674cb5a52b7d3ea05db985774d7d25a4c
20,321
def format_event_leef(event): """Format an event as QRadar / LEEF""" syslog_header = f'<13>1 {event["actionTime"]} {hostname}' leef_header = f'LEEF:2.0|TrinityCyber|PTI|1|{event.pop("id")}|xa6|' fields = dict() fields["devTime"] = event.pop("actionTime") fields[ "devTimeFormat" ] =...
ca463c9e86d6b7880e992aa11cd4b6ae7592dab4
20,322
def _file_path(ctx, val): """Return the path of the given file object. Args: ctx: The context. val: The file object. """ return val.path
7c930f2511a0950e29ffc327e85cf9b2b3077c02
20,323
def Mapping_Third(Writelines, ThirdClassDict): """ :param Writelines: 将要写入的apk的method :param ThirdClassDict: 每一个APK对应的第三方的字典 :return: UpDateWritelines """ UpDateWriteLines = [] for l in Writelines: if l.strip() in list(ThirdClassDict.keys()): UpDateWriteLines.extend(Thir...
eb94db36d06104007cbbacf8884cf6d45fee46b5
20,324
def rotate_points_around_origin(points, origin, angle): """ Rotate a 2D array of points counterclockwise by a given angle around a given origin. The angle should be given in degrees. """ angle = angle * np.pi / 180 ox, oy = origin.tolist() new_points = np.copy(points) new_points[:, 0] ...
0e21c2a9d6c870202935f8dbd9e725d9586670c3
20,325
def get_names_to_aliases(inp) -> dict: """ Returns pair, - out[0] = dictionary of names to sets of aliases - out[1] = erros when calling names_to_links, i.e., when file-reading @param inp: string vault directory or names_to_links dictionary if string then get_names_to_links method is used ...
9648099dc8422abceb5c095191e90f3dad14c4fb
20,326
def length(vec): """ Length of a given vector. If vec is an scalar, its length is 1. Parameters ---------- vec: scalar or arr Input vector Returns ------- length: int Length of vec. If vec is an scalar, its length is 1. ...
d8baea0b5f5e0bdc30b9e5a5d76b06cd876c87ba
20,327
def build_eval_infeeds(params): """Create the TPU infeed ops.""" eval_size = get_eval_size(params) num_eval_steps = eval_size // params.eval_batch_size dev_assign = params.device_assignment host_to_tpus = {} for replica_id in range(params.num_replicas): host_device = dev_assign.host_device(replica=rep...
e62586dd8fe6358eaed9a0a2eaf43fd607c0323b
20,328
import json def get_featured_parks(request): """ Returns recommended parks as JSON """ featured_parks = Park.objects.filter(featured=True).prefetch_related('images') response = { 'featured_parks': [{'id': n.pk, 'name': n.name, 'image': n.thumbnail} for n in featured_parks] } return Htt...
a3b45fa5b467434bf375a46f420538e5d5d78688
20,329
def plot_accuracy(raw_all_grids_df, option=None): """ Input: raw condition df facets: None, 'subjects', Output: figure(s) that visualize the difference in accuracy btw. el and pl """ # Rearrange columns for better readability in temporal order of the experiment condition...
fcb269c9bb0f97ac2df5914d1f26837125501d00
20,330
from typing import Sequence from typing import Any def make_data_output(structures: Sequence[Artefact[bytes]]) -> Artefact[list[Any]]: """Take xyz structure from xtb and parse them to a list of dicts.""" def to_dict(xyz: bytes) -> dict[str, Any]: as_str = xyz.decode().strip() energy = float(a...
ca9e7fd187ff98a9c9c5146e12f9bc8b0e1c0466
20,331
def total_angular_momentum(particles): """ Returns the total angular momentum of the particles set. >>> from amuse.datamodel import Particles >>> particles = Particles(2) >>> particles.x = [-1.0, 1.0] | units.m >>> particles.y = [0.0, 0.0] | units.m >>> particles.z = [0.0, 0.0] | units.m ...
8eca23b7b1a8fc8a7722543f9193f0e4a3397f24
20,332
def svn_repos_get_logs3(*args): """ svn_repos_get_logs3(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start, svn_revnum_t end, int limit, svn_boolean_t discover_changed_paths, svn_boolean_t strict_node_history, svn_repos_authz_func_t authz_read_func, svn_log_message...
1dab074e8112e2be0d51709d5d3d93bfc11c8c7d
20,333
def insertTimerOnOutput (signal, type): """ Plug the signal sout of the return entity instead of `signal` to input signal to enable the timer. - param signal an output signal. - return an Timer entity. """ Timer = getTimerType (type) timer = Timer ("timer_of_" + signal.name) plug(sig...
c8914227e112916ac67faf532babb0119abc502f
20,334
from typing import List def anomaly_metrics(contended_task_id: TaskId, contending_task_ids: List[TaskId]): """Helper method to create metric based on anomaly. uuid is used if provided. """ metrics = [] for task_id in contending_task_ids: uuid = _create_uuid_from_tasks_ids(contending_task_i...
df67e16af8b0c018da347c47a430fbe137a8c353
20,335
import logging import json def alarm(): """.""" if request.method == 'POST': response = {'message': 'POST Accepted'} logging.info('alarm POSTED!') data = request.data logging.info(data) string = json.dumps(data) producer.send('SIP-alarms', string.encode()) ...
a4444c4bc3f761cfdeb98485c745b77e8227817e
20,336
def train_net(solver_prototxt, roidb, output_dir, pretrained_model=None, detection_pretrained_model =None, max_iters=40000): """Train a TD-CNN network.""" roidb = filter_roidb(roidb) sw = SolverWrapper(solver_prototxt, roidb, output_dir, pretrained_model=pretrained_model, detection_pretrained...
af85a78e4a477ab55e949fa0d6f6d44400d1f62f
20,337
def get_druminst_order(x): """helper function to determine order of drum instruments relies on standard sequence defined in settings """ y = shared.get_inst_name(x + shared.octave_length + shared.note2drums) return shared.standard_printseq.index(y)
8cad6cd10487d51b6edd74444115d63b7e599641
20,338
def find_nearest_idx(array, value): """ Find index of value nearest to value in an array :param np.ndarray array: Array of values in which to look :param float value: Value for which the index of the closest value in `array` is desired. :rtype: int :return: The index of the item in `arr...
3eb48426bf01c625419bbf87893b7e877fd0538d
20,339
def hard_tanh(x): """Hard tanh function Arguments: x: Input value hard_tanh(x) = {-1, for x < -2, tanh(x), for x > -2 and x < 2 1, for x > 2 } returns value according to hard tanh function """ return tf.maximum( tf...
3c93f09aaeb57ee9bf4d3ccdb2ebe790333f8f67
20,340
async def get_publications(publication_id: str, embedded: bool = False): """ Given a Publication ID, get the Publication record from metadata store. """ publication = await get_publication(publication_id, embedded) return publication
8c4c81776abc1d8268192c23b1dee6c8c10bcfb0
20,341
def RandomNormal(inp): """ Random normally distributed weight initialization. """ return np.random.randn(inp)
d6922748ece8ec880eec6ba1b701424cd6fdd149
20,342
def get_transceiver_description(sfp_type, if_alias): """ :param sfp_type: SFP type of transceiver :param if_alias: Port alias name :return: Transceiver decsription """ return "{} for {}".format(sfp_type, if_alias)
ccb29d937495e37bc41e6f2cf35747d2acfe0d47
20,343
def find_contiguous_set(target_sum: int, values: list[int]) -> list[int]: """Returns set of at least 2 contiguous values that add to target sum.""" i = 0 set_ = [] sum_ = 0 while sum_ <= target_sum: sum_ += values[i] set_.append(values[i]) if sum_ == target_sum and len(set...
64b6c1f99946856a33a79fed3d43395a5a9c1000
20,344
def nesoni_report_to_JSON(reportified): """ Convert a nesoni nway.any file that has been reportified to JSON See: tables.rst for info on what is stored in RethinkDB :param reportified: the reportified nway.any file (been through nway_reportify()). This is essentially a list of ...
b78d9e9c124104a4e4c634e8fc2926804a06629d
20,345
def DeferredLightInfoEnd(builder): """This method is deprecated. Please switch to End.""" return End(builder)
f2bad6ffea3170c53a13206ab43d8b7193ccb89d
20,346
import configparser from pathlib import Path import os def qiita_get_config(): """設定ファイルを読む.""" config = configparser.ConfigParser() path = Path(os.getenv('HOME'), '.qiita.ini') config.read_file(open(path)) return config
5464253eff2e2abe4f895d0eab679c00096b1bb3
20,347
def move_character(character: dict, direction_index=None, available_directions=None) -> tuple: """ Change character's coordinates. :param character: a dictionary :param direction_index: a non-negative integer, optional :param available_directions: a list of strings, optional :precondition: char...
cc5cc3115437d0dc4e9b7ba7845565ee8147be30
20,348
def expandednodeid_to_str(exnode): """SOPC_ExpandedNodeId or SOPC_ExpandedNodeId* to its str representation in the OPC-UA XML syntax.""" a = '' if exnode.ServerIndex: a += 'srv={};'.format(exnode.ServerIndex) nsu = string_to_str(ffi.addressof(exnode.NamespaceUri)) if nsu: a += 'nsu={...
062012a11128a42bbaeb8d7ff316a2a29a31928b
20,349
def scrap_insta_description(inst) -> str: """ Scrap description from instagram account HTML. """ description = inst.body.div.section.main.div.header.section.find_all( 'div')[4].span.get_text() return description
898fa0d1cb44606374b131b8b471178a22ab74ed
20,350
import time def merge_by_sim(track_sim_list, track_data_dic, track_list, reid_th): """ Merge by sim. Ref: https://stackoverflow.com/questions/30089675/clustering-cosine-similarity-matrix """ print('start clustering') merge_start_time = time.time() cost_matrix = get_cost_matrix(track_sim_l...
68478cb1367dcd2ef8a2550c54ea57e265bbbdf5
20,351
import os def get_ros_hostname(): """ Try to get ROS_HOSTNAME environment variable. returns: a ROS compatible hostname, or None. """ ros_hostname = os.environ.get('ROS_HOSTNAME') return ros_hostname if is_legal_name(ros_hostname) else None
fb34753b98d657e0db727bffee269125901e9d0d
20,352
def cycle(*args, **kargs): """ Returns the next cycle of the given list Everytime ``cycle`` is called, the value returned will be the next item in the list passed to it. This list is reset on every request, but can also be reset by calling ``reset_cycle()``. You may specify the list as...
6a1606d5fc65eb690c4ccbad3c662dc671219502
20,353
def calc_rmsd(struct1, struct2): """ Basic rmsd calculator for molecules and molecular clusters. """ geo1 = struct1.get_geo_array() ele1 = struct1.elements geo2 = struct2.get_geo_array() ele2 = struct2.elements dist = cdist(geo1,geo2) idx1,idx2 = linear_sum_assignmen...
cb368f6e4edaf223194f1e965a0f926f33e72330
20,354
def validate_flat_dimension(d): """Return strue if a 'key:value' dimension is valid.""" key, _, val = d.partition(':') return validate_dimension_value(val) and validate_dimension_key(key)
ee663bbdc62dab3d247c09ee5950dc63dafcad15
20,355
import six import os def file_size(f): """ Returns size of file in bytes. """ if isinstance(f, (six.string_types, six.text_type)): return os.path.getsize(f) else: cur = f.tell() f.seek(0, 2) size = f.tell() f.seek(cur) return size
f999382958a972abbcf593c02e8e8e3609d8f44a
20,356
def __get_from_imports(import_tuples): """ Returns import names and fromlist import_tuples are specified as (name, fromlist, ispackage) """ from_imports = [(tup[0], tup[1]) for tup in import_tuples if tup[1] is not None and len(tup[1]) > 0] return from_imports
28df8225ad9440386342c38657944cfe7ac3d3ca
20,357
def change_dt_utc_to_local(dt): """ change UTC date time to local time zone Europe/Paris """ return convert_utctime_to_timezone(dt,'%Y%m%dT%H%M%SZ','Europe/Paris','%Y%m%dT%H%M%S')
09b52fd15a4fd9512e05f0a2801927b7f8be385f
20,358
import logging import warnings def sarimax_ACO_PDQ_search(endo_var, exog_var_matrix, PDQS, searchSpace, options_ACO, low_memory=False, verbose=False): """ Searchs SARIMAX PDQ parameters. endo_var: is the principal variable. exog_var_matrix: is the matrix of exogenous vari...
acae883a3aaeb501646f121753924fb321f471e5
20,359
from typing import Any def convert_vue_i18n_format(locale: str, po_content: Any) -> str: """ done: will markdown be parsed to html in this method? Or should we do that on the fly, everywhere... It seems the logical place will be to parse it here. Otherwise the rest of the application becomes more ...
93d7351335cbfbc9407954a352aefceea54b84c0
20,360
def get_index(x, value, closest=True): """Get the index of an array that corresponds to a given value. If closest is true, get the index of the value closest to the value entered. """ if closest: index = np.abs(np.array(x) - value).argsort()[0] else: index = list(x).index(value) ...
19dc68407d576492f25235fc1efcc79895d8cb3f
20,361
def process_spawn(window, args): """ Spawns a child process with its stdin/out/err wired to a PTY in `window`. `args` should be a list where the first item is the executable and the remaining will be passed to it as command line arguments. Returns a process object. """ return (yield Trap.PR...
979599c767f3e391541e8fd02a168cd29659bcea
20,362
import json import re def insertTaskParams(taskParams, verbose=False, properErrorCode=False, parent_tid=None): """Insert task parameters args: taskParams: a dictionary of task parameters verbose: True to see verbose messages properErrorCode: True to get a detailed error co...
baa9f0c783361cec17cec9f6259e4f856aa0121d
20,363
def pref_infos(): """ to update user infos """ form = UserParametersForm() # print current_user if request.method == 'POST' : print log_cis.info("updating an user - POST \n") # for debugging purposes for f_field in form : log_cis.info( "form name : %s / form data : %s ", f_field.name, f_field....
afe57314da056187b60e3a2ac365a27bbef73d2b
20,364
def read_domains(file_name): """ 读取域名存储文件,获取要探测的域名,以及提取出主域名 注意:若是不符合规范的域名,则丢弃 """ domains = [] main_domains = [] no_fetch_extract = tldextract.TLDExtract(suffix_list_urls=None) file_path = './unverified_domain_data/' with open(file_path+file_name,'r') as fp: for d in fp.readl...
856a7e7d93023bf59981d51a6210b988236a14a9
20,365
def determine_last_contact_incomplete(end_time_skyfield, events, times, antenna): """ gibt letzten Kontakt vervollständigt und Anzahl der an events in unvollständiger Folge zurück :param end_time_skyfield: skyfield time :param events: array of int :param times: array of skyfield times :param ant...
8a234bed084fa829c7649de99b933a59c89cba5b
20,366
def lam_est(data, J, B, Q, L = 3, paras = [3, 20], n_trees = 200, include_reward = 0, fixed_state_comp = None, method = "QRF"): """ construct the pointwise cov lam (for both test stat and c.v.), by combine the two parts (estimated and observed) Returns ------- lam: (Q-1)-len list of fo...
3a1637f2e522e414e7ddc5c470310c1f2c460ce0
20,367
import os import csv def read_training_data(rootpath): """ Function for reading the images for training. :param rootpath: path to the traffic sign data :return: list of images, list of corresponding image information: width, height, class, track """ images = [] # images img_i...
e1bbe3d239f93d5daa4e0127ca7bb3f1f7bfd44e
20,368
def initialize_all(y0, t0, t1, n): """ An initialization routine for the different ODE solving methods in the lab. This initializes Y, T, and h. """ if isinstance(y0, np.ndarray): Y = np.empty((n, y.size)).squeeze() else: Y = np.empty(n) # print y0 # print Y Y[0] = y0 T = np.li...
552a92dd50aca926b1cb6c9e6aaafd1c1401b5c3
20,369
import random def _sequence_event(values, length, verb): """Returns sequence (finite product) event. Args: values: List of values to sample from. length: Length of the sequence to generate. verb: Verb in infinitive form. Returns: Instance of `probability.FiniteProductEvent`, together with a te...
1addd21c6c39451ac29f9bcf7551f070884e9328
20,370
def ndarrayToQImage(img): """ convert numpy array image to QImage """ if img.dtype != 'uint8': raise ValueError('Only support 8U data') if img.dim == 3: t = QtGui.QImage.Format_RGB888 elif img.dim == 2: t = QtGui.QImage.Format_Grayscale8 else: raise ValueError('Only ...
a08207266b03adff2dd66421572a0905f9525844
20,371
from datetime import datetime import re import base64 import uuid def object_hook(dct, compile_re=False, ensure_tzinfo=True, encoding=None): """ Object hook used by hoplite_loads. This object hook can encode the dictionary in the right text format. For example, json.loads by default will decode '{'he...
bfe93f67813bda8e77e93a7ee33b6dc3bcbfe16a
20,372
import uuid import os import shutil def grade_submissions(course_name, assignment_name): """Grade all submissions for a particular assignment. A .zip archive should be uploaded as part of the POST request to this endpoint. The archive should contain a single directory 'Submissions', which should contain a di...
20d38a30683c09c1a4e438da5b694774dcc71681
20,373
import requests import pickle def scrape_sp500_tickers(): """Scrape the wikipedia page for the latest list of sp500 companies Returns: [pickle]: [list of sp500 companies] """ #set get file to look at wikipedia's list of sp500 companies resp = requests.get('http://en.wikipedia.org/wiki/Lis...
0c318e84f488c93254256394b1fe5d57d58c81a5
20,374
def get_top_k_recs(user_reps, item_reps, k): """ For each user compute the `n` topmost-relevant items Args: user_reps (dict): representations for all `m` unique users item_reps (:obj:`np.array`): (n, d) `d` latent features for all `n` items k (int): no. of most relevant items R...
e209b8794fe3d8f8002dbbe48d858b335171c2f5
20,375
import logging import os import sys def logger(): """ Setting upp root and zeep logger :return: root logger object """ root_logger = logging.getLogger() level = logging.getLevelName(os.environ.get('logLevelDefault', 'INFO')) root_logger.setLevel(level) stream_handler = logging.StreamH...
b7f3af5555eae953825c42aed18869deafa9f38d
20,376
def some_function(t): """Another silly function.""" return t + " python"
2bd8adc315e97409758f13b0f777ccd17eb4b820
20,377
def build_model(args): """ Function: Build a deep learning model Input: args: input parameters saved in the type of parser.parse_args Output: """ if args['debug_mode'] is True: print("BUILDING MODEL......") model = Sequential() # Normalize model.add(Lambda(lambda x:...
3008918f1319b235c4bdf575f7df84251337ec65
20,378
def add_context_for_join_form(context, request): """ Helper function used by view functions below """ # If the client has already joined a market if 'trader_id' in request.session: # If trader is in database if Trader.objects.filter(id=request.session['trader_id']).exists(): tr...
aad1b592c6d28d9a69ec97a8be9d46f942cb3d7b
20,379
def create_list(inner_type_info: CLTypeInfo) -> CLTypeInfoForList: """Returns CL type information for a list. :param CLTypeInfo inner_type_info: Type information pertaining to each element within list. """ return CLTypeInfoForList( typeof=CLType.LIST, inner_type_info=inner_type_inf...
e74731984cc83172c60a79e1b1efe05d90a32342
20,380
def get_baseline(baseline_filename, plugin_filenames=None): """ :type baseline_filename: string :param baseline_filename: name of the baseline file :type plugin_filenames: tuple :param plugin_filenames: list of plugins to import :raises: IOError :raises: ValueError """ if not basel...
f4318ee676e0c670f152feef0884a220eb1a38ac
20,381
def del_ind_purged(*args): """ del_ind_purged(ea) """ return _ida_nalt.del_ind_purged(*args)
80133af5acff0a9c284ec7894abd10bafa2671a1
20,382
import random import hmac def hash_password(password, salthex=None, reps=1000): """Compute secure (hash, salthex, reps) triplet for password. The password string is required. The returned salthex and reps must be saved and reused to hash any comparison password in order for it to match the ...
cac468818560ed52b415157dde71d5416c34478c
20,383
from typing import Dict def create_scheduled_job_yaml_spec( descriptor_contents: Dict, executor_config: ExecutorConfig, job_id: str, event: BenchmarkEvent ) -> str: """ Creates the YAML spec file corresponding to a descriptor passed as parameter :param event: event that triggered this execution :p...
48e19b6637eafee72b0b3b04a1e31c8e6c163971
20,384
import argparse def _parse_args(): """ Parse arguments for the CLI """ parser = argparse.ArgumentParser() parser.add_argument( '--fovs', type=str, required=True, help="Path to the fov data", ) parser.add_argument( '--exp', type=str, ...
ecea45baba3c89e3fd81613a256c5be300e01051
20,385
def ArgMin(iterable, key=None, default=None, retvalue=False): """ iterable >> ArgMin(key=None, default=None, retvalue=True) Return index of first minimum element (and minimum) in input (transformed or extracted by key function). >>> [1, 2, 0, 2] >> ArgMin() 2 >>> ['12', '1', '123'] >> Arg...
9c2515c3a37ab82e2b5df6b5d8dcf5ded6ad15ad
20,386
import scipy def localize_peaks_monopolar_triangulation(traces, local_peak, contact_locations, neighbours_mask, nbefore, nafter, max_distance_um): """ This method is from Julien Boussard see spikeinterface.toolki.postprocessing.unit_localization """ peak_locations = np.zeros(local_peak.size, dtype=dty...
c751ec223423007b170ce0020f6c21c72cff3cc2
20,387
def format_dict_with_indention(data): """Return a formatted string of key value pairs :param data: a dict :rtype: a string formatted to key='value' """ if data is None: return None return jsonutils.dumps(data, indent=4)
085ac029aa73e5049eeec12e021997a5067966ce
20,388
import logging def get_logger(name, info_file, error_file, raw=False): """ Get a logger forwarding message to designated places :param name: The name of the logger :param info_file: File to log information less severe than error :param error_file: File to log error and fatal :param raw: If the...
ea4abed032c201cdac9489ded4c195287106e6b2
20,389
def _Rx(c, s): """Construct a rotation matrix around X-axis given cos and sin. The `c` and `s` MUST satisfy c^2 + s^2 = 1 and have the same shape. See https://en.wikipedia.org/wiki/Rotation_matrix#Basic_rotations. """ o = np.zeros_like(c) i = np.ones_like(o) return _tailstack2([[i, o, o],...
01d436bee07458ede0484ed745ccf72568214240
20,390
def is_fraud(data): """ Identifies if the transaction was fraud :param data: the data in the transaction :return: true if the transaction was fraud, false otherwise """ return data[1] == 1
115e45a10f3429b9c33bc81fd94c24eff712f618
20,391
import scipy def EvalBinomialPmf(k, n, p): """Evaluates the binomial pmf. Returns the probabily of k successes in n trials with probability p. """ return scipy.stats.binom.pmf(k, n, p)
0720359be48b514465eb3a10d3f271ac3c25dfb9
20,392
def add_prospect(site_id, fname, lname, byear, bmonth, bday, p_type, id_type='all'): """ Looks up a prospets prospect_id given their first name (fname) last name (lname), site id (site_id), site (p_type), and birthdate (byear, bmonth, bday). If no prospect is found, adds the player to the professional_prosp...
da53dd73cddf1fd08d3bf2ca237c460f83d9a66b
20,393
def reformat_icd_code(icd_code: str, is_diag: bool = True) -> str: """Put a period in the right place because the MIMIC-III data files exclude them. Generally, procedure ICD codes have dots after the first two digits, while diagnosis ICD codes have dots after the first three digits. Adopted from: https...
4992886b257dab5361f84dd0c7774f677466437f
20,394
def parse_parent(self): """Parse enclosing arglist of self""" gtor_left = tokens_leftwards(self.begin) gtor_right = tokens_rightwards(self.end) enc = Arglist() enc.append_subarglist_right(self) # _left could have worked equally well try: parse_left(enc, gtor_left) parse_right(...
aeae5b7d56614299d0d95d52a1cd7e8cecd036ff
20,395
def dump_annotation(ribo_handle): """ Returns annotation of a ribo file in bed format in string form. Parameters ---------- ribo_handle : h5py.File hdf5 handle for the ribo file Returns ------- A string that can be output directly as a bed file. """ boundaries ...
54c98527d02ad5a136c0bc29bc794c3819fe5426
20,396
def encode_snippets_with_states(snippets, states): """ Encodes snippets by using previous query states instead. Inputs: snippets (list of Snippet): Input snippets. states (list of dy.Expression): Previous hidden states to use. TODO: should this by dy.Expression or vector values? """...
1352ddb5ed745bae00d34cd23a43595f2c7ecc7b
20,397
import subprocess def get_openshift_console_url(namespace: str) -> str: """Get the openshift console url for a namespace""" cmd = ( "oc get route -n openshift-console console -o jsonpath='{.spec.host}'", ) ret = subprocess.run(cmd, shell=True, check=True, capture_output=True) if ret.return...
71c85926c5ca368eac615f7433c7dccca5780a19
20,398
def calculate_ani(blast_results, fragment_length): """ Takes the input of the blast results, and calculates the ANI versus the reference genome """ sum_identity = float(0) number_hits = 0 # Number of hits that passed the criteria total_aligned_bases = 0 # Total of DNA bases that passed the cri...
09b649dda337d2b812f5c5fd9ec75b34737e3f15
20,399