content
stringlengths
22
815k
id
int64
0
4.91M
def index_objects( *, ids, indexer_class, index=None, transforms=None, manager_name=None ): """ Index specified `ids` in ES using `indexer_class`. This is done in a single bulk action. Pass `index` to index on the specific index instead of the default index alias from the `indexed_class`. ...
5,334,000
def get_attrs_titles_with_transl() -> dict: """Returns attribut titles and translation""" attr_titles = [] attrs = Attribute.objects.filter(show_in_list=True).order_by('weight') for attr in attrs: attr_titles.append(attr.name) result = {} for title in attr_titles: result[title] ...
5,334,001
def update(op, table, model): """Upgrade database schema and/or data, creating a new revision.""" # this hacky check for table to exist is needed because once in future # we'll drop object_folders table and we have object_folders data migrated # inside two modules (ggrc and ggrc_workflows), and migrations for o...
5,334,002
def kde_KL_divergence_2d(x, y, h_x, h_y, nb_bins=100, fft=True): """Uses Kernel Density Estimator with Gaussian kernel on two dimensional samples x and y and returns estimated Kullback- Leibler divergence. @param x, y: samples, given as a (n, 2) shaped numpy array, @param h: width of the Gaussian k...
5,334,003
def gml_init(code): """ Initializes a Group Membership List (GML) for schemes of the given type. Parameters: code: The code of the scheme. Returns: A native object representing the GML. Throws an Exception on error. """ gml = lib.gml_init(code) if gml == ffi.NULL: ...
5,334,004
def before_run(func, force=False): """ Adds a function *func* to the list of callbacks that are invoked right before luigi starts running scheduled tasks. Unless *force* is *True*, a function that is already registered is not added again and *False* is returned. Otherwise, *True* is returned. """ ...
5,334,005
def calc_z_scores(baseline, seizure): """ This function is meant to generate the figures shown in the Brainstorm demo used to select the 120-200 Hz frequency band. It should also be similar to panel 2 in figure 1 in David et al 2011. This function will compute a z-score for each value of the seizure p...
5,334,006
def get_column(data, column_index): """ Gets a column of data from the given data. :param data: The data from the CSV file. :param column_index: The column to copy. :return: The column of data (as a list). """ return [row[column_index] for row in data]
5,334,007
def analytic_solution(num_dims, t_val, x_val=None, domain_bounds=(0.0, 1.0), x_0=(0.5, 0.5), d=1.0, k_decay=0.0, k_influx=0.0, trunc_order=100, ...
5,334,008
def measurement_output_parser(raw_bytes, sender_addr): """ Prints the measurement on screen :param raw_bytes: byteArray from the WlanMeter """ response = JSONResponse.from_encoded(raw_bytes) measurement = EMeterData.from_json(response.json) print("{}, {}, {}, {}, {}, {}".format(measurement.d...
5,334,009
def test_id_g023_id_g023_v(mode, save_output, output_format): """ TEST :Identity-constraint Definition Schema Component : key category, field points to element from imported schema """ assert_bindings( schema="msData/identityConstraint/idG023.xsd", instance="msData/identityConstraint...
5,334,010
def safe_gas_limit(*estimates: int) -> int: """Calculates a safe gas limit for a number of gas estimates including a security margin """ assert None not in estimates, "if estimateGas returned None it should not reach here" calculated_limit = max(estimates) return int(calculated_limit * constants...
5,334,011
def test_GET_request_not_chunked(httpserver, transfer_encoding_header): """ Test that setting the chunked attribute of httpserver to NO causes the response not to be sent using chunking even if the Transfer-encoding header is set. """ httpserver.serve_content( ('TEST!', 'test'), ...
5,334,012
def main(): """Main function, it implements the application loop""" # Initialize pygame, with the default parameters pygame.init() # Define the size/resolution of our window res_x = 640 res_y = 480 # Create a window and a display surface screen = pygame.display.set_mode((res_x, res_y))...
5,334,013
def ingressacltemplate_update(ctx, ingressacltemplate_id, key_value): """Update key/value for a given ingressacltemplate""" params = {} for kv in key_value: key, value = kv.split(':', 1) params[key] = value ctx.obj['nc'].put("ingressacltemplates/%s?responseChoice=1" % ...
5,334,014
def integer_years(dates: typing.Any) -> typing.List[int]: """Maps a list of 'normalized_date' strings to a sorted list of integer years. Args: dates: A list of strings containing dates in the 'normalized_date' format. Returns: A list of years extracted from "dates". """ if not isi...
5,334,015
def test_user_cannot_delete_record_in_unowned_zone(shared_zone_test_context): """ Test user cannot delete a record that in an unowned zone """ client = shared_zone_test_context.dummy_vinyldns_client unauthorized_client = shared_zone_test_context.ok_vinyldns_client rs = None try: rs ...
5,334,016
def export_all(node_label, project_id, file_format, db, without_id): """ Export all nodes of type with name ``node_label`` to a TSV file and yield rows of the resulting TSV. Args: node_label (str): type of nodes to look up, for example ``'case'`` project_id (str): project to look under ...
5,334,017
def add_wmts_gibs_basemap(ax, date='2016-02-05'): """http://gibs.earthdata.nasa.gov/""" URL = 'http://gibs.earthdata.nasa.gov/wmts/epsg4326/best/wmts.cgi' wmts = WebMapTileService(URL) # Layers for MODIS true color and snow RGB # NOTE: what other tiles available?: TONS! #https://wiki.earthdata....
5,334,018
def encode_position( batch_size: int, axis: list, max_frequency: float, num_frequency_bands: int, sine_only: bool = False, ) -> torch.Tensor: """ Encode the Fourier Features and return them Args: batch_size: Batch size axis: List containing the size of each axis ...
5,334,019
def expr_erode(src, size = 5): """ Same result as core.morpho.Erode(), faster and workable in 32 bit. """ expr = _morpho_matrix(size, mm = 'min') return core.akarin.Expr(src, expr)
5,334,020
def print_grid(zone_names, options): """ Print the tzgrid. @param zone_names list of zones to print @param options command line options to control printing behavior """ tzs = [] for name in zone_names: tz = gettz(name) tzs.append(tuple([name, gettz(name)])) size = label...
5,334,021
def response_modification(response): """ Modify API response format. """ if ( status.is_client_error(response.status_code) or status.is_server_error(response.status_code) ) and (status.HTTP_400_BAD_REQUEST != response.status_code): return response # Modify the response d...
5,334,022
def test_lookahead_final_acceptance_fractions(): """Test `pyabc.visualization.plot_lookahead_final_acceptance_fractions`""" for relative, fill in itertools.product([True, False], [True, False]): pyabc.visualization.plot_lookahead_final_acceptance_fractions( sampler_df, history, relative=rela...
5,334,023
def http_request( url, json_string, username = None, password = None, timeout = None, additional_headers = None, content_type = None, cookies = None, gzipped = None, ssl_context = None, debug = None ): """ Fetch data from webserver (POST request) :param json_stri...
5,334,024
def perform_svn(): """Create svn repo.""" targ = "gcc-trunk" url = "svn://gcc.gnu.org/svn/gcc/trunk" if flag_google: targ = "gcc-google-4.9" url = "svn://gcc.gnu.org/svn/gcc/branches/google/gcc-4_9" elif flag_49_branch: targ = "gcc-4.9" url = "svn://gcc.gnu.org/svn/gcc/branches/gcc-4_9-branch"...
5,334,025
def process_source_lineage(grid_sdf, data_sdf, value_field=None): """ performs the operation to generate the """ try: subtypes = arcpy.da.ListSubtypes(data_sdf) st_dict = {} for stcode, stdict in list(subtypes.items()): st_dict[stcode] = subtypes[stcode]['Name'] ...
5,334,026
def episode(src, dest): """Clone an episode's properties from SRC to DEST, assuming they both are from the same season """ props = [ wp.INSTANCE_OF, wp.PART_OF_THE_SERIES, wp.ORIGINAL_NETWORK, wp.ORIGNAL_LANGUAGE_OF_FILM_OR_TV_SHOW, wp.COUNTRY_OF_ORIGIN, ...
5,334,027
def class_to_mask(classes: np.ndarray, class_colors: np.ndarray) -> np.ndarray: """クラスIDの配列をRGBのマスク画像に変換する。 Args: classes: クラスIDの配列。 shape=(H, W) class_colors: 色の配列。shape=(num_classes, 3) Returns: ndarray shape=(H, W, 3) """ return np.asarray(class_colors)[classes]
5,334,028
def make(T): """ T = 0 folder = 'trainT-0' """ if T==-1: folder = 'test' else: folder = 'trainT-'+str(T) log_ = log[log.order_number_rev>T] cnt = log_.groupby(['user_id', 'product_id']).size() cnt.name = 'cnt' cnt = cnt.reset_index() # chance ...
5,334,029
def get_vocab(iob2_files:List[str]) -> List[str]: """Retrieve the vocabulary of the iob2 annotated files Arguments: iob2_files {List[str]} -- List of paths to the iob2 annotated files Returns: List[str] -- Returns the unique list of vocabulary found in the files """ vocab =...
5,334,030
def reset_monotonic_time(value=0.0): """ Make the monotonic clock return the real time on its next call. .. versionadded:: 2.0 """ global _current_time # pylint:disable=global-statement _current_time = value
5,334,031
def taylor_green_vortex(x, y, t, nu): """Return the solution of the Taylor-Green vortex at given time. Parameters ---------- x : numpy.ndarray Gridline locations in the x direction as a 1D array of floats. y : numpy.ndarray Gridline locations in the y direction as a 1D array of floa...
5,334,032
def static_initial_state(batch_size, h_size): """ Function to make an initial state for a single GRU. """ state = jnp.zeros([h_size], dtype=jnp.complex64) if batch_size is not None: state = add_batch(state, batch_size) return state
5,334,033
def get_desklamp(request, index): """ A pytest fixture to initialize and return the DeskLamp object with the given index. """ desklamp = DeskLamp(index) try: desklamp.open() except RuntimeError: pytest.skip("Could not open desklamp connection") def fin(): desklamp...
5,334,034
def conj(x): """ Calculate the complex conjugate of x x is two-channels complex torch tensor """ assert x.shape[-1] == 2 return torch.stack((x[..., 0], -x[..., 1]), dim=-1)
5,334,035
def label_clusters(img, min_cluster_size=50, min_thresh=1e-6, max_thresh=1, fully_connected=False): """ Label Clusters """ dim = img.dimension clust = threshold_image(img, min_thresh, max_thresh) temp = int(fully_connected) args = [dim, clust, clust, min_cluster_size, temp] processed_arg...
5,334,036
def update_schema(schema_old, schema_new): """ Given an old BigQuery schema, update it with a new one. Where a field name is the same, the new will replace the old. Any new fields not present in the old schema will be added. Arguments: schema_old: the old schema to update schema_ne...
5,334,037
def get_estimators(positions_all, positions_relevant): """ Extracts density estimators from a judged sample of paragraph positions. Parameters ---------- positions_all : dict of (Path, float) A sample of paragraph positions from various datasets in the NTCIR-11 Math-2, and NTCIR-12 ...
5,334,038
def write_relation_row(mcf_file, row, drug_is_first, genes_pharm_to_dcid, drugs_pharm_to_dcid): """Writes mcf string of a row from drug_gene_df or gene_drug_df to file. Determines the drug dcid and gene dcids, then retreives the ChemicalCompoundGeneAssociation mcf for each gene dcid ...
5,334,039
def drift_correction(ds, ds_lo): ## testing a drift time correction code # t1df = ds.get_t1df() # t1df.reset_index(inplace=True) # t2df = ds.get_t2df() """ Take a single DataSet and window it so that the output file only contains events near an expected peak location. """ # a user...
5,334,040
def openbabel_force_field(label, mol, num_confs=None, xyz=None, force_field='GAFF', return_xyz_strings=True, method='diverse'): """ Optimize conformers using a force field (GAFF, MMFF94s, MMFF94, UFF, Ghemical) Args: label (str): The species' label. mol (Molecule, ...
5,334,041
def _wait_for_exit(please_stop): """ /dev/null PIPED TO sys.stdin SPEWS INFINITE LINES, DO NOT POLL AS OFTEN """ try: import msvcrt _wait_for_exit_on_windows(please_stop) return except: pass cr_count = 0 # COUNT NUMBER OF BLANK LINES try: # NO LONGE...
5,334,042
def parse_flarelabels(label_file): """ Parses a flare-label file and generates a dictionary mapping residue identifiers (e.g. A:ARG:123) to a user-specified label, trees that can be parsed by flareplots, and a color indicator for vertices. Parameters ---------- label_file : file A flare...
5,334,043
def remove_background(data, dim="t2", deg=0, regions=None): """Remove polynomial background from data Args: data (DNPData): Data object dim (str): Dimension to perform background fit deg (int): Polynomial degree regions (None, list): Background regions, by default entire region ...
5,334,044
def run_as3_deffered(): """ run the AS3 deferred deployment script """ deploy_script_name = "%s/%s" % ( os.path.dirname(os.path.realpath(__file__)), AS3_DELAYED_DEPLOYMENT_SCRIPT) if not is_startup_injected(AS3_DELAYED_DEPLOYMENT_SCRIPT): LOG.info( 'injecting f5-appsvcs-extension...
5,334,045
def deferral_video(message, video_url): """Функция пропустить видео""" conn = get_connection() c = conn.cursor() c.execute( "UPDATE channel_list SET rating = Null WHERE video_url IN(?);", (video_url,), ) markup = types.ReplyKeyboardMarkup( one_time_keyboard=True, resize_k...
5,334,046
def get_hmm_datatype(query_file): """Takes an HMM file (HMMer3 software package) and determines what data type it has (i.e., generated from an amino acid or nucleic acid alignment). Returns either "prot" or "nucl". """ datatype = None with open(query_file) as infh: for i in infh: ...
5,334,047
def detect_min_threshold_outliers(series, threshold): """Detects the values that are lower than the threshold passed series : series, mandatory The series where to detect the outliers threshold : integer, float, mandatory The threshold of the minimum value that will be consid...
5,334,048
def select_sort(L: List[int or float or long]): """ 假设 L 是列表,其中的元素可以用 > 进行比较 对 L 进行升序排序 """ suffix_start = 0 while suffix_start != len(L): for i in range(suffix_start, len(L)): if L[i] < L[suffix_start]: L[suffix_start], L[i] = L[i], L[suffix_start] su...
5,334,049
def new_datetime(d): """ Generate a safe datetime from a datetime.date or datetime.datetime object. """ kw = [d.year, d.month, d.day] if isinstance(d, real_datetime): kw.extend([d.hour, d.minute, d.second, d.microsecond, d.tzinfo]) return datetime(*kw)
5,334,050
def _to_str(x): """Converts a bool tensor to a string with True/False values.""" x = tf.convert_to_tensor(x) if x.dtype == tf.bool: return tf.where(x, 'True', 'False') return x
5,334,051
def inpaintn(x,m=100, x0=None, alpha=2): """ This function interpolates the input (2-dimensional) image 'x' with missing values (can be NaN of Inf). It is based on a recursive process where at each step the discrete cosine transform (dct) is performed of the residue, multiplied by some weights, and then th...
5,334,052
def amend_pinmux_io(top: Dict, name_to_block: Dict[str, IpBlock]): """ Process pinmux/pinout configuration and assign available IOs """ pinmux = top['pinmux'] pinout = top['pinout'] targets = top['targets'] temp = {} temp['inouts'] = [] temp['inputs'] = [] temp['outputs'] = [] ...
5,334,053
def obtain_bboxs(path) -> list: """ obatin bbox annotations from the file """ file = open(path, "r") lines = file.read().split("\n") lines = [x for x in lines if x and not x.startswith("%")] lines = [x.rstrip().lstrip() for x in lines] # get rid of fringe whitespaces bboxs = [] for...
5,334,054
def test_supremacy_coalitions(supremacy): """Test an API call to get coalitions""" result = supremacy.coalitions() if result: assert isinstance(result, dict), "Result should be a dict"
5,334,055
def Timeline_Integral_with_cross_before(Tm,): """ 计算时域金叉/死叉信号的累积卷积和(死叉(1-->0)不清零,金叉(0-->1)清零) 这个我一直不会写成 lambda 或者 apply 的形式,只能用 for循环,谁有兴趣可以指导一下 """ T = [Tm[0]] for i in range(1,len(Tm)): T.append(T[i - 1] + 1) if (Tm[i] != 1) else T.append(0) return np.array(T)
5,334,056
def list_image_paths() -> Generator[str, None, None]: """List each image path in the input directory.""" return list_input_directory(INPUT_DIRECTORIES["image_dir"])
5,334,057
def _clear_server_blackout(zkclient, server): """Clear server blackout.""" path = z.path.blackedout_server(server) zkutils.ensure_deleted(zkclient, path)
5,334,058
def a_star(graph: Graph, start: Node, goal: Node, heuristic): """ Standard A* search algorithm. :param graph: Graph A graph with all nodes and connections :param start: Node Start node, where the search starts :param goal: Node End node, the goal for the search :return: shortest_path: list|False Either a ...
5,334,059
def buildAndTrainModel(model, learningRate, batchSize, epochs, trainingData, validationData, testingData, trainingLabels, validationLabels, testingLabels, MODEL_NAME, isPrintModel=True): """Take the model and model parameters, build and train the model""" # Build and compile model # To use other optimi...
5,334,060
def setup_namespace(doctest_namespace): """Configure the global doctest_namespace fixture.""" doctest_namespace["coxeter"] = coxeter
5,334,061
def gaussian_temporal_filter(tsincr: np.ndarray, cutoff: float, span: np.ndarray, thr: int) -> np.ndarray: """ Function to apply a Gaussian temporal low-pass filter to a 1D time-series vector for one pixel with irregular temporal sampling. :param tsincr: 1D time-series vecto...
5,334,062
def get_mactable(auth): """ Function to get list of mac-addresses from Aruba OS switch :param auth: AOSSAuth class object returned by pyarubaoss.auth :return list of mac-addresses :rtype list """ url_mactable = "http://" + auth.ipaddr + "/rest/" + auth.version + "/mac-table" try: ...
5,334,063
def presentations(): """Shows a list of selected presentations""" return render_template( 'table.html', title='Presentations', data=PRESENTATIONS, target='_blank', )
5,334,064
def get_consensus_mask(patient, region, aft, ref=HIVreference(subtype="any")): """ Returns a 1D vector of size aft.shape[-1] where True are the position that correspond to consensus sequences. Position that are not mapped to reference or seen too often gapped are always False. """ ref_filter = traje...
5,334,065
def validate_close(close): """ Validates the given closer. Parameters ---------- close : `callable` The closer to validate. Raises ------ TypeError If `close` is not async callable or accepts not 1 parameter. """ if close is None: raise TypeError...
5,334,066
def parse_arguments(): """ Parse arguments """ parser = argparse.ArgumentParser() parser.add_argument( "-i", type=str, dest="input_pics", help="A file consists of pics path with each pic on a single line.", ) parser.add_argument("-o", type=str, dest="output_gif", help...
5,334,067
def return_next_entry_list_uri(links): """続くブログ記事一覧のエンドポイントを返す""" for link in links: if link.attrib["rel"] == "next": return link.attrib["href"]
5,334,068
def none(**_): """ Input: anything Return: 0.0 (float) Descr.: Dummy method to handle no temperature correction""" return 0.0
5,334,069
def test_parse_exception_i(): """Test parse exception.""" def exception_raise(): """A function that raises an exception.""" raise ValueError("expected") try: exception_raise() except Exception as e: out = parse_exception(e) expected = [ "Traceback (most rec...
5,334,070
def fill_one_side(fname, idx0, idx1): """fill idx0:idx1 of variable CO2_TRACER1 in boundary file with name fname with 450 pptv (0.45 ppbv)""" print("replacing {}:{} in {}".format(idx0, idx1, fname)) nc = netCDF4.Dataset(fname, 'a') nc.variables['CO2_TRACER1'][:, :, idx0:idx1] = 0.45 # 450 pptv = 0...
5,334,071
def replicate_manifest_list( image: ImageName, endpoint: str, *, auth_header_dest: Dict[str, str] = None, auth_header_src: Dict[str, str] = None, ssl_context_dest: SSLContext = None, ssl_context_src: SSLContext = None, ): """ Helper function as docker-py cannot operate on manifest li...
5,334,072
def write_attribute_map_template_to_json(attribute_set, output): """Create an attribute map template file. Write a JSON file in the given file_path, storing an object mapping attributes given in the attribute_set to empty strings. This file was meant to serve as a template for matching attributes in th...
5,334,073
def paths_and_labels_to_rgb_dataset(image_paths, labels, num_classes, label_mode): """Constructs a dataset of images and labels.""" path_ds = dataset_ops.Dataset.from_tensor_slices(image_paths) img_ds = path_ds.map(lambda path: load_rgb_img_from_path(path)) label_ds = dataset_utils.labels_to_dataset(lab...
5,334,074
def main(template_initial_path, template_grown_path, step, total_steps, hydrogen_to_replace, core_atom_linker, tmpl_out_path): """ Module to modify templates, currently working in OPLS2005. This main function basically compares two templates; an initial and a grown one, extracting the atoms of the ...
5,334,075
def get_custom_headers(manifest_resource): """Generates the X-TAXII-Date-Added headers based on a manifest resource""" headers = {} times = sorted(map(lambda x: x["date_added"], manifest_resource.get("objects", []))) if len(times) > 0: headers["X-TAXII-Date-Added-First"] = times[0] head...
5,334,076
def checkCulling( errs, cullStrings ) : """ Removes all messages containing sub-strings listed in cullStrings. cullStrings can be either a string or a list of strings. If as list of strings, each string must be a sub-string in a message for the message to be culled. """ def checkCullingMatch( m...
5,334,077
def gram_matrix(x, ba, hi, wi, ch): """gram for input""" if ba is None: ba = -1 feature = K.reshape(x, [ba, int(hi * wi), ch]) gram = K.batch_dot(feature, feature, axes=1) return gram / (hi * wi * ch)
5,334,078
def read_pinout_csv(csv_file, keyname="number"): """ read a csv file and return a dict with the given keyname as the keys """ reader = csv.DictReader(open(csv_file)) lst = [] for row in reader: lst.append(row) d = {} for item in lst: d[item[keyname]] = item return d
5,334,079
async def start(hub, ctx, name, resource_group, **kwargs): """ .. versionadded:: 1.0.0 Power on (start) a virtual machine. :param name: The name of the virtual machine to start. :param resource_group: The resource group name assigned to the virtual machine. CLI Example: .. code-...
5,334,080
def Render(request, template_file, params): """Render network test pages.""" return util.Render(request, template_file, params)
5,334,081
def test_scaling_load(master_count, job_count, single_use: bool, run_delay, cpu_quota, memory_quota, work_duration, mom, external_volume: bool, ...
5,334,082
def setup_global_logger(log_filepath=None): """Setup logger for logging Args: log_filepath: log file path. If not specified, only log to console Returns: logger that can log message at different level """ logger = logging.getLogger(__name__) try: if not logger.handlers...
5,334,083
def calculate_class_recall(conf_mat: np.array) -> np.array: """ Calculates the recall for each class from a confusion matrix. """ return np.diagonal(conf_mat) / np.sum(conf_mat, axis=1)
5,334,084
def findall(element, path): """ A helper function around a :attr:`lxml.etree._Element.findall` that passes the element's namespace mapping. """ return element.findall(path, namespaces=element.nsmap)
5,334,085
def proxyFromPacFiles(pacURLs=None, URL=None, log=True): """Attempts to locate and setup a valid proxy server from pac file URLs :Parameters: - pacURLs : list List of locations (URLs) to look for a pac file. This might come from :func:`~psychopy.web.getPacFiles` or ...
5,334,086
def _check_distance_metric(model): """Simple wrapper to ensure the distance metric is valid for CoreML conversion""" is_valid = False if model.metric is 'euclidean': is_valid = True elif model.metric is 'minkowski' and model.p == 2: is_valid = True # There are a number of other dist...
5,334,087
def subplots(times,nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, gridspec_kw=None, **fig_kw): """ create figure and subplot axes with same time (x) axis Non-Market hours will not be included in the plot. Notably a custom projection is used for the time axis, and the time values ...
5,334,088
def test_env(testenv, agent, config): """ Test of a GYM environment with an agent deciding on actions based on environment state. The test is repeated for the indicated iterations. Status of environment in each step is displayed if verbose activated. Test results (frequency cou...
5,334,089
def kldivergence(p, q): """Kullback-Leibler divergence D(P || Q) for discrete distributions Parameters ---------- p, q : array-like, dtype=float, shape=n Discrete probability distributions. """ p = np.asarray(p, dtype=np.float) q = np.asarray(q, dtype=np.float) return np.sum(np.wher...
5,334,090
def read_file(file_dir: str, filename: str) -> bytes: """ Read file contents to bytes """ with open(os.path.join(file_dir, filename), "rb") as f: data = f.read() return data
5,334,091
def sortPermutations(perms, index_return=False): """ Sort perms with respect (1) to their length and (2) their lexical order @param perms: """ ans = [None] * len(perms) indices = np.ndarray(len(perms), dtype="int") ix = 0 for n in np.sort(np.unique([len(key) for key in perms])): ...
5,334,092
def get_laplacian(Dx,Dy): """ return the laplacian """ [H,W] = Dx.shape Dxx, Dyy = np.zeros((H,W)), np.zeros((H,W)) j,k = np.atleast_2d(np.arange(0,H-1)).T, np.arange(0,W-1) Dxx[j,k+1] = Dx[j,k+1] - Dx[j,k] Dyy[j+1,k] = Dy[j+1,k] - Dy[j,k] return Dxx+Dyy
5,334,093
def recipes_ending(language: StrictStr, ending: StrictStr): """ Show the recipe for a word-ending. Given an input language and an ending, present the user with the recipe that will be used to build grammatical cases for that specific ending. And this path operation will: * returns a singl...
5,334,094
def blur(grid, blurring): """ Spreads probability out on a grid using a 3x3 blurring window. The blurring parameter controls how much of a belief spills out into adjacent cells. If blurring is 0 this function will have no effect. """ height = len(grid) width = len(grid[0]) center...
5,334,095
def _row_adress(addr='1'): """returns the rown number for a column adress""" return _cell_address(''.join(['A', addr]))[1]
5,334,096
def split(x, num, axis): """ Splits a tensor into a list of tensors. :param x: [Tensor] A TensorFlow tensor object to be split. :param num: [int] Number of splits. :param axis: [int] Axis along which to be split. :return: [list] A list of TensorFlow tensor objects. ...
5,334,097
def delete_sensor_values(request): """Delete values from a sensor """ params = request.GET action = params.get('action') sensor_id = params.get('sensor') delete_where = params.get('delete_where') where_value = params.get('value') where_start_date = params.get('start_date') where_end...
5,334,098
def _parse_voc_xml(node): """ Extracted from torchvision """ voc_dict = {} children = list(node) if children: def_dic = collections.defaultdict(list) for dc in map(_parse_voc_xml, children): for ind, v in dc.items(): def_dic[ind].append(v) if n...
5,334,099