content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def append_unique(func): """ This decorator will append each result - regardless of type - into a list. """ def inner(*args, **kwargs): return list( set( _results( args[0], func.__name__, *args, ...
ed656c500f95b03e8036605e9af5cc739830ff7b
3,657,687
def _get_unique_figs(tree): """ Extract duplicate figures from the tree """ return _find_unique_figures_wrap(list(map(_get_fig_values(tree), tree)), [])
ba8a40766981bca9ca23fd3ec681f1a8d52ad85b
3,657,688
def read_fssp(fssp_handle): """Process a FSSP file and creates the classes containing its parts. Returns: :header: Contains the file header and its properties. :sum_dict: Contains the summary section. :align_dict: Contains the alignments. """ header = FSSPHeader() sum_dict ...
4ac2c61ed40f14102d0ae1a8a3b6fa8e69252f27
3,657,689
import json def LoadJSON(json_string): """Loads json object from string, or None. Args: json_string: A string to get object from. Returns: JSON object if the string represents a JSON object, None otherwise. """ try: data = json.loads(json_string) except ValueError: data = None return ...
598c9b4d5e358a7a4672b25541c9db7743fcd587
3,657,690
import inspect import re def _dimensions_matrix(channels, n_cols=None, top_left_attribute=None): """ time,x0 y0,x0 x1,x0 y1,x0 x0,y0 time,y0 x1,y0 y1,y0 x0,x1 y0,x1 time,x1 y1,x1 x0,y1 y0,y1 x1,y1 time,y1 """ # Generate the dimensions matrix from the docstring. ds = i...
2c119c74e7e37827d6813437d9e0d8bbd97cbbc7
3,657,691
def is_monotonic_increasing(x): """ Helper function to determine if a list is monotonically increasing. """ dx = np.diff(x) return np.all(dx >= 0)
6d0afe3a6a70d57ec4ae09e20164c34c0739855f
3,657,692
import copy def cluster_size_threshold(data, thresh=None, min_size=20, save=False): """ Removes clusters smaller than a prespecified number in a stat-file. Parameters ---------- data : numpy-array or str 3D Numpy-array with statistic-value or a string to a path pointing to a nifti-fil...
3b946a639e2dae1c47fb78ad30dded32b0dd5f06
3,657,693
def convert_df(df): """Makes a Pandas DataFrame more memory-efficient through intelligent use of Pandas data types: specifically, by storing columns with repetitive Python strings not with the object dtype for unique values (entirely stored in memory) but as categoricals, which are represented by repeated...
7f6f2c20762963dceb0f52d36b7b724c5a89d8d4
3,657,694
def run_add(request): """Add a run.""" if request.method == "POST": form = forms.AddRunForm(request.POST, user=request.user) run = form.save_if_valid() if run is not None: messages.success( request, u"Run '{0}' added.".format( run.name) ...
c1eca5702e93e3a0751b2b22de18aa1aa4c88db7
3,657,695
def map_aemo_facility_status(facility_status: str) -> str: """ Maps an AEMO facility status to an Opennem facility status """ unit_status = facility_status.lower().strip() if unit_status.startswith("in service"): return "operating" if unit_status.startswith("in commissioning"): ...
43e1d5e5ea984d36260604cf25f4c7b90d5e56f1
3,657,696
def demand_monthly_ba(tfr_dfs): """A stub transform function.""" return tfr_dfs
74bbb3d732b64a30f0529f76deedd646cc7d4171
3,657,697
def render_page(page, title="My Page", context=None): """ A simple helper to render the md_page.html template with [context] vars, and the additional contents of `page/[page].md` in the `md_page` variable. It automagically adds the global template vars defined above, too. It returns a string, usuall...
fd2e427f096324b2e9a17587f498626a2ebfb47e
3,657,698
def _SortableApprovalStatusValues(art, fd_list): """Return a list of approval statuses relevant to one UI table column.""" sortable_value_list = [] for fd in fd_list: for av in art.approval_values: if av.approval_id == fd.field_id: # Order approval statuses by life cycle. # NOT_SET == 8 ...
15ce3c6191495957674ab38c2f990d34f10ecdf6
3,657,699
import re from typing import Sequence def resolve_pointer(document, pointer: str): """ Resolve a JSON pointer ``pointer`` within the referenced ``document``. :param document: the referent document :param str pointer: a json pointer URI fragment to resolve within it """ root = document # D...
c37323b19547f4cb8e20eb8c391d606e77c68b66
3,657,700
def load_config_file(config_file): """ Loads the given file into a list of lines :param config_file: file name of the config file :type config_file: str :return: config file as a list (one item per line) as returned by open().readlines() """ with open(config_file, 'r') as f: config_doc...
6a6e0199566e9ea27db309b2164f323cd5f57fdc
3,657,701
def retrieve_analysis_report(accession, fields=None, file=None): """Retrieve analysis report from ENA :param accession: accession id :param fields: comma-separated list of fields to have in the report (accessible with get_returnable_fields with result=analysis) :param file: filepath to save the content...
4adde7fea75c26f809d5efc1b5ff04b31ff9fa87
3,657,702
import copy def visualize_cluster_entropy( doc2vec, eval_kmeans, om_df, data_cols, ks, cmap_name="brg" ): """Visualize entropy of embedding space parition. Currently only supports doc2vec embedding. Parameters ---------- doc2vec : Doc2Vec model instance Instance of gensim.models.doc2vec....
5e91167fa23c09ada2f81d5e388e5d95a84fe283
3,657,704
def delete_student_meal_plan( person_id: str = None, academic_term_id: str = None): """ Removes a meal plan from a student. :param person_id: The numeric ID of the person. :param academic_term_id: The numeric ID of the academic term you're interested in. :returns: String containing ...
75cd875b751b5af0ccbf71c090712f73b866f29b
3,657,705
import torch def colorize(x): """Converts a one-channel grayscale image to a color heatmap image. """ if x.dim() == 2: torch.unsqueeze(x, 0, out=x) return if x.dim() == 3: cl = torch.zeros([3, x.size(1), x.size(2)]) cl[0] = gauss(x, .5, .6, .2) + gauss(x, 1, .8, .3) ...
0b5c95bc296fcdc3ed352d656984a3f46fa66fad
3,657,706
from typing import Counter def local_role_density( annotated_hypergraph, include_focus=False, absolute_values=False, as_array=False ): """ Calculates the density of each role within a 1-step neighbourhood of a node, for all nodes. Input: annotated_hypergraph [AnnotatedHypergraph]: An anno...
75ccc0e51ad627f3bd6f2f664bfaa93fd9e532d8
3,657,707
import re import requests def get(url: str) -> dict: """ author、audioName、audios """ data = {} headers = { "Accept": "application/json, text/plain, */*", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9", "Connection": "keep-alive", "Ho...
5dd97f4974b1fdc0a89ad36bbb14ad5c26e1582d
3,657,708
import glob def get_subject_mask(subject, run=1, rois=[1030,2030], path=DATADIR, space=MRISPACE, parcellation=PARCELLATION): """ Get subject mask by run and ROI key to apply to a dataset (rois are in DATADIR/PARCELLATION.tsv) inputs: subject - sid00...
2838c8067dff1878af2b7f874cffa3cd4fc5adf1
3,657,709
def social_auth(user): """ Return True if specified user has logged in with local account, False if user uses 3rd party account for sign-in. """ return True if user.password is not settings.SOCIAL_AUTH_USER_PASSWORD else False
197fccbe875de1e4ea08a28a2f7927160d9dae6e
3,657,710
def update_post(post_id): """ The route used to update a post. It displays the create_post.html page with the original posts contents filled in, and allows the user to change anything about the post. When the post has been successfully updated it redirects to the post route. """ post = Post.que...
2761f2fdc9ad50f96c36e8ee13f87f67275b360e
3,657,711
def lrelu(x, leak=0.2, scope="lrelu"): """ leaky relu if x > 0: return x else: return leak * x :param x: tensor :param leak: float, leak factor alpha >= 0 :param scope: str, name of the operation :return: tensor, leaky relu operation """ with tf.variable_scope(scope): ...
25757c70ae7d37b568b16ea9d489a5d15b68042f
3,657,712
from typing import Callable from typing import Optional def enable_async(func: Callable) -> Callable: """ Overview: Empower the function with async ability. Arguments: - func (:obj:`Callable`): The original function. Returns: - runtime_handler (:obj:`Callable`): The wrap functi...
82b44b7e3bc3b59e6d0a12aca7983f3c2b0f6468
3,657,713
from io import StringIO def get_past_data_from_bucket_as_dataframe(): """Read a blob""" bucket_name = "deep_learning_model_bucket" blob_name = "past_data.csv" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob = bucket.blob(blob_name) return_data = bl...
74ca2fddbd94efc51652974cc2e62a699e92ea80
3,657,714
def align_junction_LeftRight(viral_seq, bp_pos, ri_pos, align_to="L"): """If align_to="L", put all the ambiguous nucleotides in the 'body' part of the junction defined by bp_pos and ri_pos, that is the junction point is moved as close to the 5' end (of viral_seq) as possible. If align_to="R", do the op...
92634e4ff6ca6600fb91046202c240d87aac1135
3,657,715
def poisson2vpvs(poisson_ratio): """ Convert Poisson's ratio to Vp/Vs ratio. Parameters ---------- poisson_ratio : float Poisson's ratio. Returns ------- vpvs_ratio : float Vp/Vs ratio. """ return sqrt(2 * (poisson_ratio - 1) / (2 * poisson_ratio - 1))
9f0f41ec3dd5be539dca341ed2ec4b091aeee730
3,657,717
def vs30_to_z1pt0_cy14(vs30, japan=False): """ Returns the estimate depth to the 1.0 km/s velocity layer based on Vs30 from Chiou & Youngs (2014) California model :param numpy.ndarray vs30: Input Vs30 values in m/s :param bool japan: If true returns the Japan model, otherwise the Ca...
f4f985c2e0aa533cac8afd8533bfad126edbaf01
3,657,718
def empowerment(iface, priority=0): """ Class decorator for indicating a powerup's powerup interfaces. The class will also be declared as implementing the interface. @type iface: L{zope.interface.Interface} @param iface: The powerup interface. @type priority: int @param priority: The prio...
2f63892e539928951ca462239cfd014bdd8b0409
3,657,719
def multigauss_and_bgd_jacobian(x, *params): """Jacobien of the multiple Gaussian profile plus a polynomial background to data. The degree of the polynomial background is fixed by parameters.CALIB_BGD_NPARAMS. The order of the parameters is a first block CALIB_BGD_NPARAMS parameters (from low to high Legend...
e4347f50da3bd94ec4aac49c5af3ead4e08fed3b
3,657,720
def get_empty_config(): """ Return an empty Config object with no options set. """ empty_color_config = get_empty_color_config() result = Config( examples_dir=None, custom_dir=None, color_config=empty_color_config, use_color=None, pager_cmd=None, edito...
f744d770822bd6d58777d346674ea6c16b665701
3,657,721
def parse(sql_string): """Given a string containing SQL, parse it and return the normalized result.""" parsed = select_stmt.parseString(sql_string) parsed.from_clause = _normalize_from_clause(parsed.from_clause) parsed.where_clause = _normalize_where_clause(parsed.where_clause) return parsed
96a369262bfd852ab7da484c86a2cd06b121d4be
3,657,722
from pathlib import Path def check_overwrite(path: str, overwrite: bool = False) -> str: """ Check if a path exists, if so raising a RuntimeError if overwriting is disabled. :param path: Path :param overwrite: Whether to overwrite :return: Path """ if Path(path).is_file() and not overwrit...
961affdcc87b055cdd5acb9a28547ef87ae426b9
3,657,723
import struct def bytes_to_text(input): """Converts given bytes (latin-1 char + padding)*length to text""" content = struct.unpack((int(len(input)/2))*"sx", input) return "".join([x.decode("latin-1") for x in content]).rstrip("\x00")
f058847886fc3a488c54b8e01c3d7506f6d76510
3,657,724
def flatten_conv_capsule(inputs): """ :param inputs is output from a convolutional capsule layer inputs.shape = [N,OH,OW,C,PH] C is channel number, PH is vector length :return shape = [N,OH*OW*C,PH] """ inputs_shape = inputs.shape l=[] for i1 in range(inputs_shape[1]): for i...
8be5319c85311122ef728af5266dd9aecf549be0
3,657,725
def LookupValue(values, name, scope, kind): """Like LookupKind, but for constant values.""" # If the type is an enum, the value can be specified as a qualified name, in # which case the form EnumName.ENUM_VALUE must be used. We use the presence # of a '.' in the requested name to identify this. Otherwise, we pr...
211a4b161c74971d59d256db28935e33005f1782
3,657,726
def SI1452(key, Aleph=u'\u05d0', Tav=u'\u05ea'): """ Minimalist caps action Make sure latin capital letters are produced in keys carrying them (additionally, make Hebrew-letter keys go to level 2) """ if Aleph<=key.level_chars[1]<=Tav or u'A' <=key.level_chars[2]<=u'Z': return...
51c14d32d090d25e5625582e32d8bbd45d9a819b
3,657,727
def new_topic(request): """添加新主题""" if request.method != 'POST': form = TopicForm() # 如果不是POST请求, 表示首次请求, 返回空表单 else: # POST提交了数据, 对数据进行处理 form = TopicForm(request.POST) # 根据请求传入的数据创建一个表单对象 # is_valid()函数核实用户填写了所有必不可少的字段(表单字段默认都是必不可少的), # 且输入的数据与要求的字段类型一致 i...
b4e6524f0c8d4fdc6d88bd879f61c7430112ae9f
3,657,728
from pathlib import Path async def get_xdg_data_dir(app=None): """Return a data directory for this app. Create the directory if it does not exist. """ if app is None: app = await get_package_name() data_home = Path(await get_xdg_home('XDG_DATA_HOME')) data_dir = data_home / app i...
fe73abc5e91bf2c3c4a1dfd745981b1e0733aa5a
3,657,730
def patch_subscription(subscription, data): """ Patches the given subscription with the data provided """ return stage_based_messaging_client.update_subscription( subscription["id"], data)
68575f24a0e0a881b8c3a9572a496b2ba6293be2
3,657,731
def update_game(game_obj, size, center1, center2): """ Update game state """ new_game_obj = game_obj.copy() if center1 is not None: new_game_obj['rudder1_pos'] = center1 if center2 is not None: new_game_obj['rudder2_pos'] = center2 # Check if hitting corner init_vel = n...
33646593e6743d11174f72be6f4b825633fe8782
3,657,732
import requests def download_thumb(se: requests.Session, proxy: dict, addr: str) -> str: """下载缩略图 Args: se: 会话对象 proxy: 代理字典 addr: 缩略图地址 Returns: 成功时返回缩略图的本地绝对路径,失败时返回空字符串 """ header = {'User-Agent': USER_AGENT} try: with se.get(addr, ...
06971178c80376bb9c7bf30ca6cc8ad8c2a4b6b9
3,657,734
def iter_dir_completions(arg): """Generate an iterator that iterates through directory name completions. :param arg: The directory name fragment to match :type arg: str """ return iter_file_completions(arg, True)
e29544ea7886b08c03d6ba79374d0576b5af701e
3,657,735
def climate_eurotronic_spirit_z_fixture(client, climate_eurotronic_spirit_z_state): """Mock a climate radio danfoss LC-13 node.""" node = Node(client, climate_eurotronic_spirit_z_state) client.driver.controller.nodes[node.node_id] = node return node
7d24ada11d4ed30dd62d7bf160757f8909f7d4c8
3,657,736
def xi_eta_to_ab(ξ, η): """ function to transform xi, eta coords to a, b see Hesthaven function 'rstoab' @param xi, eta vectors of xi, eta pts """ a, b = np.zeros_like(ξ), np.zeros_like(η) singular = np.isclose(η, 1.0) nonsingular = np.logical_not(singular) a[nonsingular] = 2*(1. + ξ[non...
3664e90754ab9ebb86cc76f585e8383d76d6d75d
3,657,737
def mulaw_to_value(mudata): """Convert a mu-law encoded value to linear.""" position = ((mudata & 0xF0) >> 4) + 5 return ((1 << position) | ((mudata & 0xF) << (position - 4)) | (1 << (position - 5))) - 33
2ccca7f13861c7a212ac3a1dd2afc439839b19a7
3,657,739
from typing import Iterable from typing import Set import re import click def init_exclusion_regexes(paths_ignore: Iterable[str]) -> Set[re.Pattern]: """ filter_set creates a set of paths of the ignored entries from 3 sources: .gitguardian.yaml files in .git files ignore in .gitignore """ ...
54c7dd9b064fd2582545b82b2f8df324448e49f3
3,657,740
def validate_watch(value): """Validate "watch" parameter.""" if not value: return None if isinstance(value, str): value = [_ for _ in value.split("\n") if _] return value
203b77f376a747cbd10f0c674897f912bb75618f
3,657,741
def diatomic_unitary(a, b, c): """ Unitary decomposed as a diatomic gate of the form Ztheta + X90 + Ztheta + X90 + Ztheta """ X90 = expm(-0.25j*np.pi*pX) return expm(-0.5j*a*pZ)@X90@expm(-0.5j*b*pZ)@X90@expm(-0.5j*c*pZ)
38bbd194f2179aff1874190dbbb95546790f9d91
3,657,742
def is_x_y_in_hidden_zone_all_targets(room_representation, camera_id, x, y): """ :description Extend the function is_x_y_in_hidden_zone_one_target, 1.for every target in the room :param 1. (RoomRepresentation) -- room description of the target...
a682a2ac99798c3c8d7ad23881f965ffa33071bf
3,657,743
def _create_pure_mcts_player( game: polygames.Game, mcts_option: mcts.MctsOption, num_actor: int ) -> mcts.MctsPlayer: """a player that uses only mcts + random rollout, no neural net""" player = mcts.MctsPlayer(mcts_option) for _ in range(num_actor): actor = polygames.Actor( None, ga...
8faf70a43e0734362dfd3aba0c0575758945eb09
3,657,744
def get_fans_users(): """ 获取用户的粉丝 :return: """ user_id = request.argget.all("user_id") page = str_to_num(request.argget.all("page", 1)) pre = str_to_num(request.argget.all("pre", 20)) s, r = arg_verify(reqargs=[("user id", user_id)], required=True) if not s: return r data...
0af36e4f2b3051975f834df554ff09e9d539ec82
3,657,745
import re def test_invalid_patterns(list, pattern): """ Function to facilitate the tests in MyRegExTest class :param list: list with strings of invalid cases :param pattern: a regular expression :return: list with the result of all matches which should be a list of None """ newList = [] ...
94a8232d66ff4c705e7a587aedc9d1cbe0b4f072
3,657,746
def remove_constant_features(sfm): """ Remove features that are constant across all samples """ # boolean matrix of whether x == first column (feature) x_not_equal_to_1st_row = sfm._x != sfm._x[0] non_const_f_bool_ind = x_not_equal_to_1st_row.sum(axis=0) >= 1 return sfm.ind_x(selected_f_inds...
ae8c6e1d14b7260c8d2491b2f8a00ba352d7375a
3,657,748
def flatten(x): """ Flatten list an array. Parameters ---------- x: list of ndarray or ndarray the input dataset. Returns ------- y: ndarray 1D the flatten input list of array. shape: list of uplet the input list of array structure. """ # Check input ...
4efb7c740cb197bf9e8e094a9e6b6e38badb5a25
3,657,749
def sample_automaton(): """ Creates a sample automaton and returns it. """ # The states are a python Set. Name them whatever you want. states = {"0","1","2"} # Choose one of the states to be the initial state. You need to give this a Set, but that Set usually only contains one state. init_state = {"0"} ...
f0b7da88825c88841e55dd1ebaf46d5979eaa0fb
3,657,750
def mae(data, data_truth): """Computes mean absolute error (MAE) :param data: Predicted time series values (n_timesteps, n_timeseries) :type data: numpy array :param data_truth: Ground truth time series values :type data_truth: numpy array """ return np.mean(np.abs(data - data_truth))
76fce7e40adbfbf28f3d08df4117502baa01cbed
3,657,751
def _find_ntc_family(guide_id): """Return a String of the NTC family """ guide_id_list = guide_id.split('_') return '_'.join(guide_id_list[0:2])
2b340694c2379682b232e49c9b0f1f0a91c778cf
3,657,752
def CreateFilletCurves(curve0, point0, curve1, point1, radius, join, trim, arcExtension, tolerance, angleTolerance, multiple=False): """ Creates a tangent arc between two curves and trims or extends the curves to the arc. Args: curve0 (Curve): The first curve to fillet. point0 (Point3d): A ...
fee4c009db83ff77d6369e8e88d2bd3bc1d64390
3,657,753
from typing import List from typing import Tuple import json from typing import Dict def select_ads() -> jsonify: """ select ads """ try: if INSERTED_FILES_NUM == 0 or INSERTED_FILES_NUM != PROCESSED_FILES_NUM: raise Exception('server is not ready') weights: List[Tuple[str...
7e65b21792c6b80e90dcb16bab644a329e8f7eb5
3,657,754
from typing import Dict from typing import List from typing import Any def _xpath_find(data: Dict, xparts: List, create_if_missing: bool = False) -> Any: """ Descend into a data dictionary. :arg data: The dictionary where to look for `xparts`. :arg xparts: Elements of an Xpath split w...
24bd5e04c5ba8bd7dc4950c3f655241d4d4e8d65
3,657,755
def r_mediate(y, t, m, x, interaction=False): """ This function calls the R function mediate from the package mediation (https://cran.r-project.org/package=mediation) y array-like, shape (n_samples) outcome value for each unit, continuous t array-like, shape (n_samples) ...
c07afc4c2569566d67e652e8de4a5ee770a49218
3,657,756
def default_props(reset=False, **kwargs): """Return current default properties Parameters ---------- reset : bool if True, reset properties and return default: False """ global _DEFAULT_PROPS if _DEFAULT_PROPS is None or reset: reset_default_props(**kwargs) ...
43a7015bd8089082d17ca7625748a8789b3eb52a
3,657,757
def ReadFlatFileNGA(xlsfile): """ Generate NGA flatfile dictionary for generate usage """ # read in excel flatfile book = xlrd.open_workbook(xlsfile) sh = book.sheet_by_index(0) # 'Flatfile' sheet name keys = sh.row_values(0) for itmp in range( len(keys) ): keys[itmp] = keys[i...
8ed4c66a541cb5fcebce6965c1f9b9a514bea1ae
3,657,758
def _chr_ord(x): """ This is a private utility function for getBytesIOString to return chr(ord(x)) """ return chr(ord(x))
8529686bf3a40cd1f2c32f458ebdba17a9b35a05
3,657,759
def vkToWchar (m): """ Mapping from virtual key to character """ ret = [] retTbl = ['/* table of virtual key to wchar mapping tables */', 'static VK_TO_WCHAR_TABLE aVkToWcharTable[] = {'] def generate (n, g, defPrefix=''): defname = f'aVkToWch{defPrefix}{n}' ret.extend ([f'...
b0b938720c13ed45c32dcd402f43e93f24aaa111
3,657,760
def load_glove_vectors(glove_file="/home/yaguang/pretrained_models/glove.6B.50d.txt"): """Load the glove word vectors""" word_vectors = {} with open(glove_file) as f: for line in f: split = line.split() word_vectors[split[0]] = [float(x) for x in split[1:]] return word_ve...
a7bb1650885e12f436273b012d0c1c381e1be311
3,657,761
def _ParseFileVersion(file_version): """Convert the string file_version in event.proto into a float. Args: file_version: String file_version from event.proto Returns: Version number as a float. """ tokens = file_version.split("brain.Event:") try: return float(tokens[-1]) ...
43e4cfdc116ae5e687e4c0f6ed55bc8b7518f6b1
3,657,762
import gzip def get_file_format(input_files): """ Takes all input files and checks their first character to assess the file format. Returns one of the following strings; fasta, fastq, other or mixed. fasta and fastq indicates that all input files are of the same format, either fasta or fastq. othe...
901ed1ca81563321eb9a16e6a36fbebb12f3b2ea
3,657,763
def get_nominal_hour(train_num): """Get the nominal hour for a train num (most frequent)""" res = database.get().query(""" SELECT count(*) as count, substr(date, 12, 5) as hour FROM results WHERE num = '%s' GROUP BY hour ORDER BY count DESC LIMIT 1; """ % train_num) return next(r...
c51fba63b03e2aa930399077143ff77e1fe5f485
3,657,764
def compute_cgan_metrics(img_y, img_g, i = 0): """ Computes accuracy, precision, recall, f1, iou_score for passed image, return None in case of div 0 img_y: ground truth building footprint semantic map img_g: generated image i: 0 for entire image, 1 for inner (excluding border) N...
be900b303d333ec1c7233d59779c8006333fba36
3,657,766
def learning(spiking_neurons, spike_times, taup, taum, Ap, Am, wmax, w_init): """ Takes a spiking group of neurons, connects the neurons sparsely with each other, and learns the weight 'pattern' via STDP: exponential STDP: f(s) = A_p * exp(-s/tau_p) (if s > 0), where s=tpost_{spike}-tpre_{spike} :param ...
7324a2290e7ec14146be28d2b5a14e10b6ec44e4
3,657,767
import optparse def build_arg_parser2(): """ Build an argument parser using optparse. Use it when python version is 2.5 or 2.6. """ usage_str = "Smatch table calculator -- arguments" parser = optparse.OptionParser(usage=usage_str) parser.add_option("--fl", dest="fl", type="string", help='AMR ...
7118b337bda7b9b170bf3eedf230a5fcd323a17b
3,657,768
def _write_log(path, lines): """ :param path: log file path :param lines: content :return status:Bool """ try: with open(path, 'w') as file: logi('open file {log_path} for writting'.format(log_path=path)) file.writelines(lines) except Exception as e: l...
f98d87939a23549a82370ce81e7bf28b1ac52b10
3,657,769
def update_meal_plan(plan_id: str, meal_plan: MealPlan): """ Updates a meal plan based off ID """ meal_plan.process_meals() meal_plan.update(plan_id) # try: # meal_plan.process_meals() # meal_plan.update(plan_id) # except: # raise HTTPException( # status_code=404,...
cf201280d6f89aac5d412af3344e4ba89b29d1ed
3,657,770
def clean_data(df): """ INPUT: df - Panda DataFrame - A data frame that contains the data OUTPUT: df - Panda DataFrame - A Cleaned Panda Data frame """ #split categories into a data frame and take the first row cat = df.categories.str.split(';', expand=True) row = cat.iloc[...
7d19cf395094fe780da6204f10f80528526083d0
3,657,771
def vec2transform(v): """Convert a pose from 7D vector format ( x y z qx qy qz qw) to transformation matrix form Args: v pose in 7D vector format Returns: T 4x4 transformation matrix $ rosrun tf tf_echo base os_lidar - Translation: [-0.084, -0.025, 0.050] - Rotation: in Quaternion [...
e3a6023fe2b6bedc7b023d08bb22abd406bb9612
3,657,772
import re def cleanup_name_customregex(cname, customregex=None, returnmatches=False): """Cleanup the input name given a custom dictionary of regular expressions (format of customregex: a dict like {'regex-pattern': 'replacement'}""" if customregex is None: customregex = {'_': ' ', ...
15cbaf0cb439ba8aa3a550cc7713e19e34d714d4
3,657,773
import math def compute_recommended_batch_size_for_trustworthy_experiments(C: int, H: int, W: int, safety_val: float) -> int: """ Based on inequality with safety_val=s: N' >= s*D' the recommended batch size is, assuming N'=B*H*W and D'=C (so considering neurons as filter, patches as data): ...
80f11adb87b252a31aba590c38e60350535025ae
3,657,774
def filter_gradient(t, h_, n_std=3): """Filter outliers by evaluating the derivative. Take derivative and evaluate outliers in derivative. """ h = h_.copy() # NOTE: This must be a separate step # dh/dt = 0 -> invalid dhdt = np.gradient(h) invalid = np.round(dhdt, 6) == 0.0 dhdt[inv...
4e4547f38c2886f33c3b42442ff37b9100dda9c7
3,657,775
def generate_valve_from_great_vessel( label_great_vessel, label_ventricle, valve_thickness_mm=8, ): """ Generates a geometrically-defined valve. This function is suitable for the pulmonic and aortic valves. Args: label_great_vessel (SimpleITK.Image): The binary mask for the great ve...
4a40ab9513e6093486a914099316e80a8a24f58e
3,657,777
def current_decay(dataframe,two_components=False): """ Fits 95% peak to: A(t) = A*exp(-t/Taufast) + B*exp(-t/Tauslow) +Iss Parameters ---------- dataframe : A pandas dataframe Should be baselined two_components : True/False When False, a single exponential component ...
048e001b23344b2ac72f6683b0ca1ca66af8dcbd
3,657,778
import ctypes def get_n_mode_follow(p_state, idx_image=-1, idx_chain=-1): """Returns the index of the mode which to follow.""" return int(_MMF_Get_N_Mode_Follow(p_state, ctypes.c_int(idx_image), ctypes.c_int(idx_chain)))
30a548369b4fd708b3c8c73549b79951c9435667
3,657,779
def divide(lhs, rhs): """Division with auto-broadcasting Parameters ---------- lhs : tvm.Tensor or Expr The left operand rhs : tvm.Tensor or Expr The right operand Returns ------- ret : tvm.Tensor or Expr Returns Expr if both operands are Expr. Otherwise...
d4a6f3b28eaa35faa300a64e5a81ac64aa6740cb
3,657,781
import gzip import pickle def load(filename): """Loads a compressed object from disk """ file = gzip.GzipFile(filename, 'rb') buffer = b'' while True: data = file.read() if data == b'': break buffer += data object = pickle.loads(buffer) file.close() ...
8a2b9bff8297fdf2824f962df9202b8e08c8d8a1
3,657,782
from multiprocessing import Queue from .rabbitmq import Queue from .beanstalk import Queue from .redis_queue import Queue def connect_message_queue(name, url=None, maxsize=0): """ create connection to message queue name: name of message queue rabbitmq: amqp://username:password@host:5...
4cb3ea808de8ffd5c157c4fbbf95e78d1ad2b075
3,657,783
def load_document(filepath): """ Description:Opens and loads the file specified by filepath as a raw txt string; assumes valid text file format. Input: String -> filepath of file from current directory Output: Entire contents of text file as a string """ #assert(filepath.endswith(".txt")), "Function: Load ...
b44a3af09ec7c776a1d3bd1a90efe3deb90da821
3,657,784
def get_user(request, uid): """ GET /user/1/ """ if uid != 1: return JsonResponse({"code": 10101, "message": "user id null"}) data = {"age": 22, "id": 1, "name": "tom"} return JsonResponse({"code": 10200, "data": data, "message": "success"})
92ef79cf015de5556d1c5715e57cb550a42ef1ca
3,657,785
import collections import tokenize def count_ngrams(lines, min_length=1, max_length=3): """ Iterate through given lines iterator (file object or list of lines) and return n-gram frequencies. The return value is a dict mapping the length of the n-gram to a collections.Counter object of n-gram tuple...
514a313b96d139c3483dc07999f60d1abafd0d91
3,657,786
def notas(*n, sit = False): """ -> Função para analisar notas e situação de vários alunos. :param n: notas (uma ou mais) :param sit: situação (valor opcional) :return: dicionário com várias informaçoes sobre o aluno. """ r = {} r['total'] = len(n) r['maior'] = max(n) r['menor'] =...
f151c90e22e5eac1c69b59240906e7bf55943321
3,657,787
import numpy def accuracy(output, labels_test): """How many correct predictions?""" TP, TN, FP, FN = confusionMatrix(labels_test, numpy.sign(output)) return float(TP + TN) / (TP + TN + FP + FN)
f3801bbe3590e9d271403795d23a737d642fbed8
3,657,788
def metric_pairs(request): """Pairs of (dask-ml, sklearn) accuracy metrics. * accuracy_score """ return ( getattr(dask_ml.metrics, request.param), getattr(sklearn.metrics, request.param) )
e82b799c06e41c4fea19cd33e9d836b1b03d02df
3,657,789
import time from datetime import datetime def MyDuration(duration, initial_time=None): """ Usecase: a timestamp is provided as when an access token expires, then add it to the current time, then showing it as a human-readable future time. Alternatively specify a *initial_ti...
d81a12295c2715ab9ed93595ccee2af2474c671e
3,657,790
def orthogonal_init(shape, gain=1.0): """Generating orthogonal matrix""" # Check the shape if len(shape) < 2: raise ValueError("The tensor to initialize must be " "at least two-dimensional") # Flatten the input shape with the last dimension remaining # its original s...
4d7b1f81a13228e4185d59e0fd23ba629888a232
3,657,791
def application(env, start_response): """The callable function per the WSGI spec; PEP 333""" headers = {x[5:].replace('_', '-'):y for x, y in env.items() if x.startswith('HTTP_')} if env.get('CONTENT_TYPE', None): headers['Content-Type'] = env['CONTENT_TYPE'] if env.get('CONTENT_LENGTH', None): ...
1c5cbb62316b4170bbd54ef8fa404eccc32b8441
3,657,792
def angle_normalize(x): """ Normalize angles between 0-2PI """ return ((x + np.pi) % (2 * np.pi)) - np.pi
0c39dcf67a5aae2340a65173e6a866e429b4d176
3,657,793
import torch def load_data(BASE_DIR, DATA_DIR): """ Loads data necessary for project Arguments: BASE_DIR (str) -- path to working dir DATA_DIR (str) -- path to KEGG data Returns: tla_to_mod_to_kos (defaultdict of dicts) -- maps tla to series of dicts, keys are KEGG modules and values are lists of KOs in...
d32a6be8cae02ac6ab5903f055326f27d0a549c5
3,657,794
def disable_app(app, base_url=DEFAULT_BASE_URL): """Disable App. Disable an app to effectively remove it from your Cytoscape session without having to uninstall it. Args: app (str): Name of app base_url (str): Ignore unless you need to specify a custom domain, port or version t...
2a2a00609b0acb6090219d24fcc7d24ed8f7dc7e
3,657,795