content
stringlengths
22
815k
id
int64
0
4.91M
def test_thresholds(numba_conditional): """Test automatic threshold calculations.""" # within subjects rng = np.random.RandomState(0) X = rng.randn(10, 1, 1) + 0.08 want_thresh = -stats.t.ppf(0.025, len(X) - 1) assert 0.03 < stats.ttest_1samp(X[:, 0, 0], 0)[1] < 0.05 my_fun = partial(ttest_1...
5,327,700
def upper_bounds_max_ppr_target(adj, alpha, fragile, local_budget, target): """ Computes the upper bound for x_target for any teleport vector. Parameters ---------- adj : sp.spmatrix, shape [n, n] Sparse adjacency matrix. alpha : float (1-alpha) teleport[v] is the probability to...
5,327,701
def import_layer_data(node, path): """Import ngLayerData from JSON file. Args: node (str): Name of the mesh. Used to find the JSON file. path (str): The parent folder where the file is saved. Returns: str: The raw ngLayer data (somehow, this is a string!) """ nice_name = no...
5,327,702
def cramers_corrected_stat(contingency_table): """ Computes corrected Cramer's V statistic for categorial-categorial association """ try: chi2 = chi2_contingency(contingency_table)[0] except ValueError: return np.NaN n = contingency_table.sum().sum() phi2 = chi2...
5,327,703
def p_domain_def(p): """domain_def : LPAREN DOMAIN_KEY NAME RPAREN""" p[0] = p[3]
5,327,704
def test_utils_return_htmldir_pathname_htmldir_name_not_given(tmp_path): """Raises exception if HTML directory name is deliberately omitted.""" rd = tmp_path dd = Path(tmp_path).joinpath("a") dd.mkdir() os.chdir(dd) with pytest.raises(SystemExit): get_htmldir_path(rootdir=rd, htmldir=Non...
5,327,705
def frame_comps_from_set(frame_set): """ A `set` of all component names every defined within any frame class in this `TransformGraph`. Broken out of the class so this can be called on a temporary frame set to validate new additions to the transform graph before actually adding them. """ res...
5,327,706
def generate_keyframe_chunks(animated_rotations, animated_locations, animated_scales, num_frames, chunksize): """ This function has a very high bug potential... """ # These lines create lists of length num_frames with None for frames with no data rotations = populate_frames(num_frames, animated_rota...
5,327,707
def collection_tail(path_string): """Walk the path, return the tail collection""" # pylint: disable=consider-using-enumerate coll = None parts = extract_path(path_string) if parts: try: last_i = len(parts) - 1 coll = bpy.data.collections[parts[0]] f...
5,327,708
def create_raw(df_dev, most_likely_values=None): """ return df: | time | dev_1 | .... | dev_n | -------------------------------- | ts1 | 1 | .... | 0 | """ df_dev = df_dev.copy() df = df_dev.pivot(index=TIME, columns=DEVICE, values=VAL) df = df.reset_i...
5,327,709
def p1_marker_loc(p1_input, board_list, player1): """Take the location of the marker for Player 1.""" # verify if the input is not in range or in range but in a already taken spot while p1_input not in range(1, 10) or ( p1_input in range(1, 10) and board_list[p1_input] != " " ): try: ...
5,327,710
def send_welcome_ephemeral_message_to_participant( participant_email: str, incident_id: int, db_session: SessionLocal ): """Sends an ephemeral message to the participant.""" # we load the incident instance incident = incident_service.get(db_session=db_session, incident_id=incident_id) # we send the...
5,327,711
def validateEpirr(jsonObj): """Ensure that IHEC Data Hub metadata matches with EpiRR record.""" print() datasets = jsonObj['datasets'] samples = jsonObj['samples'] for dataset_name in datasets: dataset = datasets[dataset_name] exp_attr = dataset['experiment_attributes'] ex...
5,327,712
def chord(tones, dur, phrasing="", articulation="", ornamentation="", dynamics="", markup="", markdown="", prefix="", suffix=""): """ Returns a list containing a single Point that prints as a chord with the specified tones and duration. """ tones = flatten([tonify(tones)]) return [Point(tones, dur, phrasing...
5,327,713
def build_gem_graph(): """Builds a gem graph, F4,1. Ref: http://mathworld.wolfram.com/GemGraph.html""" graph = build_5_cycle_graph() graph.new_edge(1, 3) graph.new_edge(1, 4) return graph
5,327,714
async def get_forecasts_by_user_year_epic( user_id, epic_id, year, month, session: Session = Depends(get_session) ): """Get forecast by user, epic, year, month""" statement = ( select(Forecast.id, Forecast.month, Forecast.year, Forecast.days) .where(Forecast.user_id == user_id) .wher...
5,327,715
def face_xyz_to_uv(face, p): """(face, XYZ) to UV see :cpp:func:`S2::FaceXYZtoUV` """ if face < 3: if p[face] <= 0: return False, 0, 0 else: if p[face - 3] >= 0: return False, 0, 0 u, v = valid_face_xyz_to_uv(face, p) return True, u, v
5,327,716
def cleanupString(string, replacewith="_", regex="([^A-Za-z0-9])"): """Remove all non-numeric or alphanumeric characters""" # Please don't use the logging system here. The logging system # needs this method, using the logging system here would # introduce a circular dependency. Be careful not to call ot...
5,327,717
def send_message(data, header_size=8): """Send data over socket.""" @_retry() def _connect(socket_path): """Connect socket.""" sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(socket_path) sock.settimeout(SOCKET_TIMEOUT) return sock def _che...
5,327,718
def _get_mapping_keys_in_condition( condition: Expression, column_name: str ) -> Optional[Set[str]]: """ Finds the top level conditions that include filter based on the arrayJoin. This is meant to be used to find the keys the query is filtering the arrayJoin on. We can only apply the arrayFilter...
5,327,719
def make_request(method, url, **kwargs): """Make HTTP request, raising an exception if it fails. """ request_func = getattr(requests, method) response = request_func(url, **kwargs) # raise an exception if request is not successful if not response.status_code == requests.codes.ok: respons...
5,327,720
def hold(source): """Place the active call on the source phone on hold""" print("Holding call on {0}".format(source.Name)) return operation(source,'Hold')
5,327,721
def make_grid(batch, grid_height=None, zoom=1, old_buffer=None, border_size=1): """Creates a grid out an image batch. Args: batch: numpy array of shape [batch_size, height, width, n_channels]. The data can either be float in [0, 1] or int in [0, 255]. If the data has only 1 channel it will be conve...
5,327,722
def _get_patterns_map(resolver, default_args=None): """ Cribbed from http://www.djangosnippets.org/snippets/1153/ Recursively generates a map of (pattern name or path to view function) -> (view function, default args) """ patterns_map = {} if default_args is None: default_args = {...
5,327,723
def encoder_package_to_options(encoder_package, post_url=None, extra_numerics=None, extra_categoricals=None, omitted_fields=None): """ :param encoder_package: one hot encoder package :param post_url: url to send for...
5,327,724
def parse_files(fnames): """Parses all given files for seiscomp xml""" j = 0 out = Catalog() for i, fname in enumerate(fnames): print('read ' + fname) out += readSeisComPEventXML0_6(fname) if (i + 1) % 100 == 0 or i == len(fnames) - 1: out_fname = str(...
5,327,725
def train(model, network_input, network_output): """ Train the Neural Network """ filepath = "weights_"+name+"/weights-{epoch:02d}-{loss:.4f}.hdf5" checkpoint = ModelCheckpoint( filepath, monitor='loss', verbose=0, save_best_only=True, mode='min' ) c...
5,327,726
def get_subset_values(request, pk): """Return the numerical values of a subset as a formatted list.""" values = models.NumericalValue.objects.filter( datapoint__subset__pk=pk).select_related( 'error').select_related('upperbound').order_by( 'qualifier', 'datapoint__pk') to...
5,327,727
def timestamp(format_key: str) -> str: """ 格式化时间 :Args: - format_key: 转化格式方式, STR TYPE. :Usage: timestamp('format_day') """ format_time = { 'default': { 'format_day': '%Y-%m-%d', 'format_now': '%Y-%m-%d-%H_%M_%S', ...
5,327,728
def _save_conn_form( request: HttpRequest, form: SQLConnectionForm, template_name: str, ) -> JsonResponse: """Save the connection provided in the form. :param request: HTTP request :param form: form object with the collected information :param template_name: To render the response :r...
5,327,729
def client() -> GivEnergyClient: """Supply a client with a mocked modbus client.""" # side_effects = [{1: 2, 3: 4}, {5: 6, 7: 8}, {9: 10, 11: 12}, {13: 14, 15: 16}, {17: 18, 19: 20}] return GivEnergyClient(host='foo')
5,327,730
def test_bus(test_system): """Create the test system.""" test_system.run_load_flow() return test_system.buses["bus3"]
5,327,731
def add_exptime(inlist, exptime, exptkey='exptime', hext=0, verbose=True): """ Given a list of fits files, adds to each one an EXPTIME header keyword with a value based on the passed exptime parameter. ** NOTE ** The exptime parameter can either be a numerical value, in which case it is interprete...
5,327,732
def mask_target(y_true, bbox_true, mask_true, mask_regress, proposal, assign = cls_assign, sampling_count = 256, positive_ratio = 0.25, mean = [0., 0., 0., 0.], std = [0.1, 0.1, 0.2, 0.2], method = "bilinear"): """ y_true = label #(padded_num_true, 1 or num_class) bbox_true = [[x1, y1, x2, y2], ...] #(padde...
5,327,733
def display_context(doc): """Create a Jinja context for display""" from rowgenerators.exceptions import DownloadError # Make a naive dictionary conversion context = {s.name.lower(): s.as_dict() for s in doc if s.name.lower() != 'schema'} mandatory_sections = ['documentation', 'contacts'] # Re...
5,327,734
def _get_triplet_mask(labels: torch.Tensor) -> torch.BoolTensor: """Return a 3D mask where mask[a, p, n] is True if the triplet (a, p, n) is valid. A triplet (i, j, k) is valid if: - i, j, k are distinct - labels[i] == labels[j] and labels[i] != labels[k] Args: labels (torch.Te...
5,327,735
def test_function_words_removal(): """Test function words are properly deleted from title strings""" key_formatter = KeyFormatter({}) # a list of function words as defined by JabRef # (cf. https://docs.jabref.org/setup/bibtexkeypatterns) function_words_list = [ "a", "an", "the", "above", "a...
5,327,736
def analyse_registration_output(output_string): """Parse the registration command output and return appropriate error""" parse_error="ERROR:Unable to parse error message:" + output_string success=0 fail=1 status_regex = re.compile("Status\s*:\s*(?P<status>[A-Z]+).*") try: status = stat...
5,327,737
def randomrandrange(x, y=None): """Method randomRandrange. return a randomly selected element from range(start, stop). This is equivalent to choice(range(start, stop)), but doesnt actually build a range object. """ if isinstance(y, NoneType): return random.randrange(x) # nosec ...
5,327,738
def difficulties(prefix="data"): """ Helper function that returns a list of template files. """ print("Loading difficulties ...") difficulties = [ ] os.path.walk(os.path.join(prefix, "templ_difficulties/"), processor, difficulties) if (len(difficulties) == 0): die("FATAL: No difficulties to use!") return ...
5,327,739
def int_domains(ecoords: np.ndarray, qpos: np.ndarray, qweight: np.ndarray, dshpfnc: Callable): """ Returns the measure (length, area or volume in 1d, 2d and 3d) of several domains. """ nE = ecoords.shape[0] res = np.zeros(nE, dtype=ecoords.dtype) nG = len(qweight) for i...
5,327,740
def pg_conn(postgresql): """Runs the sqitch plan and loads seed data before returning db connection. """ with postgresql: # Loads data from blogdb fixture data with postgresql.cursor() as cur: cur.execute( """ create table users ( ...
5,327,741
def test_list_unsigned_long_min_length_2_nistxml_sv_iv_list_unsigned_long_min_length_3_5(mode, save_output, output_format): """ Type list/unsignedLong is restricted by facet minLength with value 7. """ assert_bindings( schema="nistData/list/unsignedLong/Schema+Instance/NISTSchema-SV-IV-list-unsi...
5,327,742
def check_ocsp_response_status(single_response_map, ocsp_response): """ Checks the OCSP response status """ ret = [] for hkey, data in single_response_map.items(): if data['status'] == 'good': ret.append(_process_good_status( hkey, data, ocsp_response)) el...
5,327,743
def checkParameter(): """ function: check parameter for different action input: NA output: NA """ # check mpprc file path g_opts.mpprcFile = DefaultValue.getMpprcFile() # the value of "-t" can not be "" if g_opts.action == "": GaussLog.exitWithError(ErrorCode.GAUSS_500["GAUSS...
5,327,744
def partial_with_hound_context(hound, func, *args, **kwargs): """ Retuns a partially bound function Propagates the currently active hound reason (if any) Useful for capturing the current contextual hound reason when queueing a background action """ if hound is not None: reason = hound.ge...
5,327,745
def rssfeed_edit(request, feed, ret_path): """ Eigenschaften des RSS-Feeds aendern """ def save_values(feed, old, new): """ geaenderte Werte des RSS-Feeds speichern """ has_changed = False key = 'title' if old[key] != new[key]: feed.title = encode_html(new[key]) has_changed = True k...
5,327,746
def disassemble_pretty(self, addr=None, insns=1, arch=None, mode=None): """ Wrapper around disassemble to return disassembled instructions as string. """ ret = "" disas = self.disassemble(addr, insns, arch, mode) for i in disas: ret += "0x%x:\t%s\t%s\n" % (i.addr...
5,327,747
def detect(net, meta, image, thresh=.5, hier_thresh=.5, nms=.45, debug=False): """ Performs the detection """ custom_image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) custom_image = cv2.resize(custom_image, (lib.network_width( net), lib.network_height(net)), interpolation=cv2.INTER_LINEAR) ...
5,327,748
def overlay_boxes(image, predictions): """ Adds the predicted boxes on top of the image Arguments: image (np.ndarray): an image as returned by OpenCV predictions (BoxList): the result of the computation by the model. It should contain the field `labels`. """ labels = pred...
5,327,749
async def mux_data(dut): """It should multiplex between two data channels""" # Reset dut.reset.value = 1 dut.io_in1_req.value = 0 dut.io_in2_req.value = 0 dut.io_sel_req.value = 0 dut.io_in1_data.value = 42 dut.io_in2_data.value = 84 dut.io_sel_data.value = 0 dut.io_out_ack.value...
5,327,750
def convert_tilt_convention(iconfig, old_convention, new_convention): """ convert the tilt angles from an old convention to a new convention This should work for both configs with statuses and without """ if new_convention == old_convention: return def _get_...
5,327,751
def setAllPorts(descriptor, delayed): """ setAllPorts(descriptor: ModuleDescriptor) -> None Traverse descriptor and all of its children/grand-children to add all ports """ addPorts(descriptor.module, delayed) for child in descriptor.children: setAllPorts(child, delayed)
5,327,752
def _type_of_plot(orientation, n_var, i, j): """internal helper function for determining plot type in a corner plot Parameters ---------- orientation : str the orientation options: 'lower left', 'lower right', 'upper left', 'upper right' i, j : int the row, column index ...
5,327,753
def main(gene_files, pos_files, neg_files): """Analize repeat data for genes. Main method that runs the repeat analysis. Parameters ---------- gene_files : List List of file names containing gene information for a given chromosome in JSON format. pos_files : List ...
5,327,754
def t2_function(t, M_0, T2, p): """Calculate stretched or un-stretched (p=1) exponential T2 curve .. math:: f(t) = M_{0} e^{(-2(t/T_{2})^{p}} Args: t (array): time series M_{0} (float): see equation T_{2} (float): T2 value p (float): see equation Returns: ...
5,327,755
def ry(phi): """Returns the rotational matrix for an angle phi around the y-axis """ if type(phi) == np.ndarray: m11 = np.cos(phi) m12 = np.full(len(phi), 0) m13 = np.sin(phi) m22 = np.full(len(phi), 1) m1 = np.stack((m11, m12, m13), axis=0) m2 = np...
5,327,756
def hashed_embedding_lookup_sparse(params, sparse_values, dimension, combiner="mean", default_value=None, name=None): """Looks up embeddings of...
5,327,757
def DelfFeaturePostProcessing(boxes, descriptors, use_pca, pca_parameters=None): """Extract DELF features from input image. Args: boxes: [N, 4] float array which denotes the selected receptive box. N is the number of final feature points which pass through keypoint selection and NMS steps. ...
5,327,758
def render_field(field, **kwargs): """Render a field to a Bootstrap layout.""" renderer_cls = get_field_renderer(**kwargs) return renderer_cls(field, **kwargs).render()
5,327,759
def bisection(a, b, poly, tolerance): """ Assume that poly(a) <= 0 and poly(b) >= 0. Modify a and b so that abs(b-a) < tolerance and poly(b) >= 0 and poly(a) <= 0. Return (a+b)/2 :param a: poly(a) <= 0 :param b: poly(b) >= 0 :param poly: polynomial coefficients, low order first :param to...
5,327,760
def decrypt_message(key, message): """ returns the decrypted message """ return translate_message(key, message, 'decrypt')
5,327,761
def IOU(a_wh, b_wh): """ Intersection over Union Args: a_wh: (width, height) of box A b_wh: (width, height) of box B Returns float. """ aw, ah = a_wh bw, bh = b_wh I = min(aw, bw) * min(ah, bh) area_a = aw * ah area_b = bw * bh U = area_a + area_b - I ...
5,327,762
def decode_image(img_b64): """Decode image from base64. https://jdhao.github.io/2020/03/17/base64_opencv_pil_image_conversion/ """ img_bytes = base64.b64decode(img_b64) im_arr = np.frombuffer(img_bytes, dtype=np.uint8) img = cv2.imdecode(im_arr, flags=cv2.IMREAD_COLOR) img = cv2.cvtColor(img...
5,327,763
def test_to_yaml_bugfix_419(): """Ensure that GH#419 is fixed""" # pylint: disable=no-self-use class CheckedSchemaModel(pandera.SchemaModel): """Schema with a global check""" a: pat.Series[pat.Int64] b: pat.Series[pat.Int64] @pandera.dataframe_check() def unregiste...
5,327,764
def date_from_string(date_str, format_str): """ returns a date object by a string """ return datetime.strptime(date_str, format_str).date()
5,327,765
def fix_sensor_name(name): """Cleanup sensor name, returns str.""" name = re.sub(r'^(\w+)-(\w+)-(\w+)', r'\1 (\2 \3)', name, re.IGNORECASE) name = name.title() name = name.replace('Acpi', 'ACPI') name = name.replace('ACPItz', 'ACPI TZ') name = name.replace('Coretemp', 'CoreTemp') name = name.replace('Cpu'...
5,327,766
def handle_request_text(message): """ Obtenha a segunda mensagem, altere o estado do usuário para 2. Retorne a música completa do usuário. """ if get_user_state(message.chat.id) == 1: get_user_state(message.chat.id) bot.send_message( message.chat.id, "Escreva o nome da ...
5,327,767
def get_relevant_coordinates(): """Returns a numpy ndarray specifying the pixel a lidar ray hits when shot through the near plane.""" coords_and_angles = np.genfromtxt('coords_and_angles.csv', delimiter=',') return np.hsplit(coords_and_angles,2)
5,327,768
def smart_split(text): """ Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped ...
5,327,769
def load_helpers(): """Try to import ``helpers.py`` from each app in INSTALLED_APPS.""" # We want to wait as long as possible to load helpers so there aren't any # weird circular imports with jingo. global _helpers_loaded if _helpers_loaded: return _helpers_loaded = True from jingo ...
5,327,770
def _expand_host_port_user(lst): """ Input: list containing hostnames, (host, port)-tuples or (host, port, user)-tuples. Output: list of (host, port, user)-tuples. """ def expand(v): if isinstance(v, basestring): return (v, None, None) elif len(v) == 1: return...
5,327,771
def noise(line, wl=11): """ Return the noise after smoothing. """ signal = smooth_and_trim(line, window_len=wl) noise = np.sqrt((line - signal) ** 2) return noise
5,327,772
def _evaluate( limit_batches: Optional[int], train_pipeline: TrainPipelineSparseDist, iterator: Iterator[Batch], next_iterator: Iterator[Batch], stage: str, ) -> Tuple[float, float]: """ Evaluates model. Computes and prints metrics including AUROC and Accuracy. Helper function for train_...
5,327,773
def superimpose(fname, params): """ function to add wavefronts """ ### TODO: FIX HARDCODING OF FILENAMES ETC. memMap = readMap(params['global'] + params['train'], shape = params['train_shape']) wfr = Wavefront() wfr.load_hdf5(params['indir'] + fname) ...
5,327,774
def check_pre_release(tag_name): """ Check the given tag to determine if it is a release tag, that is, whether it is of the form rX.Y.Z. Tags that do not match (e.g., because they are suffixed with someting like -beta# or -rc#) are considered pre-release tags. Note that this assumes that the tag na...
5,327,775
def _get_target_connection_details(target_connection_string): """ Returns a tuple with the raw connection details for the target machine extracted from the connection string provided in the application arguments. It is a specialized parser of that string. :param target_connection_string: the connection...
5,327,776
def download_audio(cache_audio_dir, cache_text_file): """ This method takes the sentences from the text file generated using generate_cache_text() and performs TTS inference on mimic2-api. The wav files and phonemes are stored in 'cache_audio_dir' Args: cache_audio_dir (path): path to st...
5,327,777
def async_setup_platform(hass, config, async_add_devices, discovery_info=None): """Set up an Arlo IP sensor.""" arlo = hass.data.get(DATA_ARLO) if not arlo: return False sensors = [] for sensor_type in config.get(CONF_MONITORED_CONDITIONS): if sensor_type == 'total_cameras': ...
5,327,778
def tfr_array_multitaper(epoch_data, sfreq, freqs, n_cycles=7.0, zero_mean=True, time_bandwidth=None, use_fft=True, decim=1, output='complex', n_jobs=1, verbose=None): """Compute Time-Frequency Representation (TFR) using DPSS tapers. Sa...
5,327,779
def card(id: int): """ Show the selected card data (by id). """ for card in cards["cards"]: if card["id"] == id: logging.info("card") return card logging.info("card") return "Card not found."
5,327,780
def build_norm_layer(cfg, num_features, postfix=""): """ Build normalization layer Args: cfg (dict): cfg should contain: type (str): identify norm layer type. layer args: args needed to instantiate a norm layer. requires_grad (bool): [optional] whether stop gradient u...
5,327,781
def _add_response_tree ( tree , *args ) : """Specific action to ROOT.TChain """ import ostap.trees.trees from ostap.core.core import Ostap, ROOTCWD from ostap.io.root_file import REOPEN tdir = tree.GetDirectory() with ROOTCWD () , REOPEN ( tdir ) as tfile : ...
5,327,782
def data_collection(dataframe): """ Return statistical data of sentences with label, which is 0 for negative and 1 for positive. """ sentences = dataframe['question_text'].values # punctuations punc = dict((key, []) for key in PUNCT_DICT.keys()) # punc_count = dict((key, 0) for key in PUNCT_DICT.keys()) pos = ...
5,327,783
def scalarProd(v,w): """ A sum of 2 vectors in n-space. Params: A 2 tuple point (V) another 2 tuple point (W) returns: Distance of (V,W) """ v = x[0] + x[1] w = y[0] + y[1] return np.array(v*w)
5,327,784
def rename_genbank(file: str, out: str, new_locus_tag_prefix: str, old_locus_tag_prefix: str = None, validate: bool = False): """ Change the locus tags in a GenBank file :param file: input file :param out: output file :param new_locus_tag_prefix: desired locus tag :param old_locus_tag_prefix: l...
5,327,785
def sample_summary(df, extra_values=None, params=SummaryParams()): """ Returns table showing statistical summary from the sample parameters: mean, std, mode, hpdi. Parameters ------------ df : Panda's dataframe Contains parameter sample values: each column is a parameter. extra_v...
5,327,786
def classFactory(iface): # pylint: disable=invalid-name """Load GNAT class from file GNAT. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # from .gnat import GNAT return GNAT(iface)
5,327,787
def get_quicksetup_password(ctx, param, value): # pylint: disable=unused-argument """Determine the password to be used as default for the Postgres connection in `verdi quicksetup` If a value is explicitly passed, that value is returned. If there is no value, the current username in the context will be sca...
5,327,788
def convert(day_input: List[str]) -> List[List[str]]: """Breaks down the input into a list of directions for each tile""" def dirs(line: str) -> List[str]: dirs, last_c = [], '' for c in line: if c in ['e', 'w']: dirs.append(last_c + c) last_c = '' ...
5,327,789
def assert_allclose( actual: Tuple[numpy.uint8, numpy.uint8, numpy.uint8, numpy.uint8, numpy.uint8], desired: List[numpy.uint8], ): """ usage.matplotlib: 1 """ ...
5,327,790
def read(filepath): """Read file content from provided filepath.""" with codecs.open(filepath, encoding='utf-8') as f: return f.read()
5,327,791
def trend_indicator(trend, style): """Get the trend indicator and corresponding color.""" if trend == 0.00042 or np.isnan(trend): return '?', (0, 0, 0, 0) arrows = ('→', '↗', '↑', '↓', '↘') trend = min(max(trend, -1), 1) # limit the trend trend_color = (1, 0, 0, trend * trend) if (trend > ...
5,327,792
async def wait_all_tasks_blocked() -> None: """Wait until all other tasks are waiting for something.""" await _get_asynclib().wait_all_tasks_blocked()
5,327,793
def then_cfb_t(result: dict, note: str): """ check the relative error of the ros """ check_metric('CFB_t', result['fuel_type'], result['python'].cfb_t, result['expected']['cfb'], acceptable_margin_of_error, note)
5,327,794
def space(fn: Callable[[State], T], verbose: bool=False) -> Iterable[T]: """ Return an iterable that generates values from ``fn`` fully exhausting the state space. During iteration, the function ``fn`` is called repeatedly with a :class:`~exhaust.State` instance as only argument. :param fn: Th...
5,327,795
def get_menu_as_json(menu): """Build Tree-like JSON structure from the top menu. From the top menu items, its children and its grandchildren. """ top_items = menu.items.filter(parent=None) menu_data = [] for item in top_items: top_item_data = get_menu_item_as_dict(item) top_item...
5,327,796
def vortex_contribution_normal(panels): """ Builds the vortex contribution matrix for the normal velocity. Parameters ---------- panels: 1D array of Panel objects List of panels. Returns ------- A: 2D Numpy array of floats Vortex contribution matrix. """ ...
5,327,797
def find_template(raw, name): """Return Template node with given name or None if there is no such template""" e=Expander('', wikidb=DictDB()) todo = [parse(raw, replace_tags=e.replace_tags)] while todo: n = todo.pop() if isinstance(n, basestring): continue if isi...
5,327,798
def Doxygenate(text): """Change commenting style to the one recognized by Doxygen.""" # /* -> /** text = re.sub(r'(/\*)([ \t\n]) ?', r'/**\2', text) # // -> /// text = re.sub(r'(//)([ \t\n]) ?', r'///\2', text) # // Author:-> /** \author */ text = re.sub(r'(//[ ]+Author:?[ ]*)([^\n]+)', r'/** \\author \...
5,327,799