content
stringlengths
22
815k
id
int64
0
4.91M
def start_replica_cmd(builddir, replica_id): """ Return a command that starts an skvbc replica when passed to subprocess.Popen. Note each arguments is an element in a list. """ statusTimerMilli = "500" viewChangeTimeoutMilli = "10000" path = os.path.join(builddir, "tests", "simpleKVBC",...
43,600
def _pip_check(): """Ensures none of the instrumentations have dependency conflicts. Clean check reported as: 'No broken requirements found.' Dependency conflicts are reported as: 'opentelemetry-instrumentation-flask 1.0.1 has requirement opentelemetry-sdk<2.0,>=1.0, but you have opentelemetry-sdk 0...
43,601
def convolve_images(images_with_headers): """ Convolves all of the images to a common resolution using a simple gaussian kernel. Parameters ---------- images_with_headers: zipped list structure A structure containing headers and image data for all FITS input images. """ ...
43,602
def execute_until_false(method, interval_s): """Executes a method forever until the method returns a false value. Args: method: The callable to execute. interval_s: The number of seconds to start the execution after each method finishes. Returns: An Interval object. """ interval = Interval...
43,603
def vecnorm(a): """Return a/|a|""" return a / mdamath.norm(a)
43,604
def continue_job_later(job, message): """Notify CodePipeline of a continuing job This will cause CodePipeline to invoke the function again with the supplied continuation token. Args: job: The JobID message: A message to be logged relating to the job status continuation...
43,605
def count_qubits(operator): """Compute the minimum number of qubits on which operator acts. Args: operator: FermionOperator, QubitOperator, DiagonalCoulombHamiltonian, or PolynomialTensor. Returns: num_qubits (int): The minimum number of qubits on which operator acts. Rais...
43,606
def datenum_to_date(date_num): """Transform date_num to datetime object. Returns pd.NaT on invalid input""" try: total_seconds = round(dt.timedelta(days=date_num - 366).total_seconds()) return dt.datetime(1, 1, 1) + dt.timedelta(seconds=total_seconds) - dt.timedelta(days=1) except Overf...
43,607
def save_ground_truth_part(name, tuple_path, mean, sem, std, sestd): """Saves a ground truth part to strings. This is meant to be called with outputs of `nest.flatten_with_tuple_paths(ground_truth_mean)`. Args: name: Python `str`. Name of the sample transformation. tuple_path: Tuple path of the part o...
43,608
def resnet_block(x, filters, kernel_size=3, stride=1, conv_shortcut=True, name=None): """A residual block. # Arguments x: input tensor. filters: integer, filters of the bottleneck layer. kernel_size: default 3, kernel size of the bottleneck layer. stride: defa...
43,609
def plot_npt_prod_data_with_t0(job): """Generate plots for production data with t0 as a vertical line.""" import pandas as pd from reproducibility_project.src.analysis.equilibration import ( plot_job_property_with_t0, ) ensemble = "npt" # plot t0 df = pd.read_csv(job.fn("log-npt.t...
43,610
def parse_cpe(cpe): """ Split the given CPE name into its components. :param cpe: CPE name. :type cpe: str :returns: CPE components. :rtype: list(str) """ ver = get_cpe_version(cpe) if ver == "2.2": parsed = [cpe22_unquote(x.strip()) for x in cpe[5:].split(":")] if ...
43,611
def draw_points(xs, ys, covs, M): """ Resample a set of points M times, adding noise according to their covariance matrices. Returns ------- x_samples, y_samples : np.array Every column j, is x[j] redrawn M times. Has M rows, and every row is a realization of xs or ys. """ #...
43,612
def k_folds_split(raw_indexes, n_splits, labels=default_pars.validation_pars_labels, shuffle=default_pars.validation_pars_shuffle, random_state=default_pars.random_state, return_original_indexes=default_pars.validation_pars_return_original_indexes): """Splits a raw set of indexes...
43,613
def save_result(save_path, result, args='', values=''): """This function is used to save result generated in `nei()`. It saves all the results in '.pkl' file first, then save image files for the sinogram-like rho_t arrays. If reconstructions are contained in the result object, save these as images as...
43,614
def element_wise_entropy(px): """ Returns a numpy array with element wise entropy calculated as -p_i*log_2(p_i). Params ------ px (np.array) Array of individual probabilities, i.e. a probability vector or distribution. Returns ------- entropy (np.array) Array of element...
43,615
def score_page(preds, truth): """ Scores a single page. Args: preds: prediction string of labels and center points. truth: ground truth string of labels and bounding boxes. Returns: True/false positive and false negative counts for the page """ tp = 0 fp = 0 fn = ...
43,616
def _validate_eida_token(token): """ Just a basic check if the string contains something that looks like a PGP message """ if re.search(pattern='BEGIN PGP MESSAGE', string=token, flags=re.IGNORECASE): return True return False
43,617
def test_interactive_auth_new_transaction(client, acc1_usd_deposit_transaction_factory): """ Tests that requests by previously authenticated accounts are denied if they were not authenticated for the specified transaction. """ deposit = acc1_usd_deposit_transaction_factory() # So that form_for_t...
43,618
def dn_histogram_mode_5(y, y_min, y_max): """ Mode of z-scored distribution (5-bin histogram) """ return histogram_mode(y, y_min, y_max, 5)
43,619
def _make_element(spec, parent, attributes=None): """Helper function to generate the right kind of Element given a spec.""" if (spec.name == constants.WORLDBODY or (spec.name == constants.SITE and (parent.tag == constants.BODY or parent.tag == constants.WORLDBODY))): return _Attac...
43,620
def create_hook_mock() -> TmTcHookBase: """Create simple minimal hook mock using the MagicMock facilities by unittest :return: """ tmtc_hook_base = TmTcHookBase() tmtc_hook_base.add_globals_pre_args_parsing = MagicMock(return_value=0) tmtc_hook_base.add_globals_post_args_parsing = MagicMock(retu...
43,621
def read_sounding(timestamp, index_col=0, caching=True, **kws): """read wyoming sounding with optional caching (default)""" if caching: if in_cache(timestamp, **kws): data = cache_read(timestamp, **kws) # TODO: index col swapping return data skiprows = (0,1,2,3,4,...
43,622
def tsv_to_txt(tsv_file, txt_file): """ """ # Open tsv and txt files(open txt file in write mode) tsv_file = open(tsv_file) txt_file = open(txt_file, "w") # Read tsv file and use delimiter as \t. csv.reader # function retruns a iterator # which is stored in read_csv read_tsv = c...
43,623
def nlf_css(parser, token): """Newsletter friendly CSS""" args = token.split_contents() css = {} css_order = [] for item in args[1:]: tag, value = item.split("=") tag, value = tag.strip('"'), value.strip('"') css[tag] = value css_order.append(tag) nodelist = parse...
43,624
def data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_peak_information_rate_put(uuid, tapi_common_capacity_value=None): # noqa: E501 """data_context_connectivity_context_connectivity_serviceuuid_requested_capacity_bandwidth_profile_peak_information_rate_put create...
43,625
def _get_default_dataset_statistics( statistics: statistics_pb2.DatasetFeatureStatisticsList ) -> statistics_pb2.DatasetFeatureStatistics: """Gets the DatasetFeatureStatistics to use for validation. If there is a single DatasetFeatureStatistics, this function returns that. If there are multiple DatasetFeatur...
43,626
def foldr(_folder: Callable[[A, B], B], _init: B, _linked_list: LinkedList[A]) -> B: """ foldr """ if _linked_list.content is None: return _init else: head = _linked_list.content[0] tail = _linked_list.content[1] return _folder(head, foldr(_folder, _init, tail))
43,627
def get_per_lane_sample_dist_plot(sample_data: pd.DataFrame) -> dict: """ A function for returing sample distribution plots :params sample_data: A Pandas DataFrame containing sample data :returns: A dictionary containing sample distribution plots """ try: lane_plots = dict() for...
43,628
def run_in_main_thread(func, *args, **kwargs): """在主事件循环中执行,不等待调用结果""" loop = AsyncThreads.get_main_loop() loop.call_soon_threadsafe(_proxy_to_async_call, func, *args, **kwargs)
43,629
def __write_samples(samples, io, target_data_folder, check_rule): """ check_rule: func (sample_index, part_size, part_index) """ assert(callable(check_rule)) parts_to_split = io.CVCount prefix = u"part_{}.txt" # CV mode random.Random(1).shuffle(samples) print "Separate sam...
43,630
def mark_volatile(obj): """DEPRECATED(Jiayuan Mao): mark_volatile has been deprecated and will be removed by 10/23/2018; please use torch.no_grad instead.""" return stmap(_mark_volatile, obj)
43,631
def list_keys(bucket): """ Lists all the keys in a bucket. :param bucket: (string) A bucket name. :return: (string list) Keys in the bucket. """ _check_bucket(bucket) bucket_path = _bucket_path(bucket) keys = [] for key_path in bucket_path.iterdir(): keys.append(key_path.name...
43,632
def get_plugin_path() -> str: """Get 3D plugin path Returns: str: path """
43,633
def h6(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", translate...
43,634
def extractUniversesWithMeaning(item): """ """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol) or 'preview' in item['title'].lower(): return None if 'Angel of Death' in item['title']: return buildReleaseMessageWithType(item, 'Angel of Death', vol, chp, frag=frag, ...
43,635
def fma(x, y, z): """ See https://docs.nvidia.com/cuda/libdevice-users-guide/__nv_fma.html :param x: Argument. :type x: float64 :param y: Argument. :type y: float64 :param z: Argument. :type z: float64 :rtype: float64 """
43,636
def get_provenance(message): """Given a message with results, find the source of the edges""" prov = defaultdict(lambda: defaultdict(int)) # {qedge->{source->count}} results = message['message']['results'] kg = message['message']['knowledge_graph']['edges'] edge_bindings = [ r['edge_bindings'] for r...
43,637
def bricklinkColorToLEGO(colornum): """ Get the LEGO equivalent to a bricklink color number if it exists :param colornum: :return: """ default = {"name": "Unknown", "Lego": colornum, "BrickLink": colornum} if colornum < 0: return default for color in color_data: if colo...
43,638
def compare_structures(args): """ Compare structures in files for similarity using structure matcher. Args: args (dict): Args from argparse. """ filenames = args.filenames if len(filenames) < 2: print("You need more than one structure to compare!") sys.exit(-1) try: ...
43,639
def _helper_assert_get_alias_dict( contents_of_alias_dict_file, target_alias_dict, config_obj, alias_file_path, alias_file_path_is_file, mock_is_file, mock_get_alias_file_path, mock_get_contents, ): """ contents_of_alias_dict_file: the string contents of the file storing the ...
43,640
def lambda_handler(sns_event, context): """ AWS LAMBDA function that is run when the SNS topic to which it is subscribed -- 'video-transcoded-notification' -- receives a message. This extracts metadata from the just-trancoded video into a JSON file; then uploads it to s3. The AWS Lambda Handler fiel...
43,641
def bounds(gdf): """Calculates the bounding coordinates (left, bottom, right, top) in the given GeoDataFrame. Args: gdf: A GeoDataFrame containing the input points. Returns: An array [minx, miny, maxx, maxy] denoting the spatial extent. """ bounds = gdf.to...
43,642
def controls_receptor(): """Control for receptor network. TODO: remain to be added to manuscript """ config = FullConfig() config.data_dir = './datasets/proto/standard' config.max_epoch = 100 config.train_pn2kc = False config.receptor_layer = True config.or2orn_normalization = Tru...
43,643
def exec_file(path, globals=None, locals=None): """ :param str path: :param dict globals: :param dict locals: """ if globals is None: globals = sys._getframe(1).f_globals if locals is None: locals = sys._getframe(1).f_locals with open(path, 'r') as file_obj: exec...
43,644
def powerport_get_row_boot_strap (port_id, raw = False): """ Get boot strapping setting """ result = powerport_get_port_status (port_id + 24, "pdu", raw) state = result.pop ("Port State", None) if (state): result["Boot Strap"] = "Normal" if (state == "Off") else "Network" ...
43,645
def feedback_patch(transaction): """ PATCH /feedbacks/1 :param transaction: :return: """ with stash['app'].app_context(): feedback = FeedbackFactory() db.session.add(feedback) db.session.commit()
43,646
def inv_ltri(ltri, det): """Lower triangular inverse""" inv_ltri = np.array((ltri[2], -ltri[1], ltri[0]), dtype=ltri.dtype) / det return inv_ltri
43,647
def create_dummy_review(user, title='Review 1'): """Simple function for creating reviews of a user""" review = Review.objects.create( reviewer=user, title=title, rating=5, summary='This is my first review!!!', ip='190.190.190.1', ...
43,648
def checkOneFile(path): """Process one file and return analysis result as element object""" # Create output elementtree object if config.inputRecursiveFlag or config.inputWrapperFlag: # Name space already declared in results element, so no need to do it # here root = ET.Element('jp...
43,649
def check_user(update): """verify that a user has signed up""" user = update.message.from_user if db.tel_get_user(user.id) is not None: return True else: return False
43,650
def acmg(): """Calculate an ACMG classification from submitted criteria.""" criteria = request.args.getlist("criterion") classification = get_acmg(criteria) return jsonify(dict(classification=classification))
43,651
def test_response_custom_header(client: Eve, sample_schema: dict): """Test to ensure headers can be overridden on a response :param Eve client: Mockerena app instance :param dict sample_schema: Sample schema data :raises: AssertionError """ sample_schema["responses"] = [{"headers": {"Last-Modi...
43,652
def import_bin(filename, **kwargs): """ Read a .bin file generated by the IRIS Instruments Syscal Pro System and return a curated dataframe for further processing. This dataframe contains only information currently deemed important. Use the function reda.importers.iris_syscal_pro_binary._import_bin...
43,653
def get_messages(receive_address, send_address, offset, count): """ return most recent messages from offset to count from both communicators """ conn = connect_db() cur = conn.cursor() cur.execute( "(SELECT * FROM message WHERE (recvAddress=%s AND sendAddress=%s) ORDER by id DESC LIMIT %s OFFSET...
43,654
def get_test_node(context, **kw): """Return a Node object with appropriate attributes. NOTE: The object leaves the attributes marked as changed, such that a create() could be used to commit it to the DB. """ db_node = db_utils.get_test_node(**kw) # Let DB generate ID if it isn't specified expli...
43,655
def GlobalAttributes(ds, var): """ Creates the global attributes for the netcdf file that is being written these attributes come from : https://www.unidata.ucar.edu/software/thredds/current/netcdf-java/metadata/DataDiscoveryAttConvention.html args: runinfo Table containing all the details of the individual runs...
43,656
async def test_initial_api_error( hass, mock_config_entry, mock_modules, ): """Test an API error on initial call.""" # Load the entry mock_config_entry.add_to_hass(hass) with patch( "homeassistant.components.home_plus_control.api.HomePlusControlAsyncApi.async_get_modules", re...
43,657
def extend_path(path: List[Tuple[MerkleTree, hash.HashTriple]], tree: MerkleTree, ) -> List[List[Tuple[MerkleTree, hash.HashTriple]]]: """Extend path if possible.""" paths = [] for t in (tree.left, tree.right): if t is not None: path_ = path + [(t, get_has...
43,658
def main(argv): """Cleans the generated Amplitude binary assets. Returns: Returns 0 on success. """ projectPath = common.get_o3de_project_path() try: common.clean_flatbuffer_binaries( common.get_conversion_data(os.path.join( projectPath, "sounds", "amplit...
43,659
def calculate_debt(runsdim, runstot, low_bound, high_bound): """ calculates tech debt and bugs """ debt_indexes = np.random.uniform(low_bound, high_bound, runstot) debt_indexes = runsdim * debt_indexes debt_indexes = np.rint(debt_indexes) return np.int64(debt_indexes)
43,660
def test_fst_disconnect_1_of_2_stas_from_non_fst_ap(dev, apdev, test_params): """FST disconnect 1 of 2 STAs from non-FST AP""" fst_ap1, fst_ap2, sta1, sta2 = fst_module_aux.start_two_ap_sta_pairs(apdev) with HWSimRadio() as (radio, iface): non_fst_ap = hostapd.add_ap(iface, { "ssid": "non_fst_11g" }...
43,661
def load_dictionary(loc): """ Load a dictionary """ with open(loc, 'r') as f: worddict = pkl.load(f) return worddict
43,662
def get_specific_post(post_id): """Get specific post""" value = posts.get(post_id) if not value: return json.dumps({"error": "Post Not Found"}), 404 return json.dumps(value), 200
43,663
def first_half(dayinput): """ first half solver: """ houses = { (0,0): 1 } coords = [0, 0] for h in dayinput: coords = change_coords(h, coords) home = (coords[0], coords[1]) if houses.get(home, None): houses[home] += 1 else: houses[home] = ...
43,664
def compute_cluster_metrics(neighbor_mat, max_k=10, included_fovs=None, fov_col='SampleID'): """Produce k-means clustering metrics to help identify optimal number of clusters Args: neighbor_mat (pandas.DataFrame): a neighborhood matrix, created from create_neighb...
43,665
def map_flat_line(x, y, data, linestyles='--', colors='k', ax=None, **kwargs): """Plot a flat line across every axis in a FacetGrid. For use with seaborn's map_dataframe, this will plot a horizontal or vertical line across all axes in a FacetGrid. Parameters ---------- x, y : str, float, or li...
43,666
def validate_api_version(): """ A decorator that validates the requested API version on a route """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): req_api_version = kwargs.get("api_version", 1) if req_api_version > api_version or req_api_version ...
43,667
def plot_2D_interpolation_result( scan2D_result: Scan2DResult, fig: Optional[matplotlib.figure.Figure] = None, ax: Optional[matplotlib.axes.Axes] = None, **plot_kwargs, ) -> None: """Function to plot a Scan2DResult from 2D interpolation. Args: scan2d_result: Scan result to be plotted. ...
43,668
def build_dictionary(sentences, size): """ Create dictionary containing most frequent words in the sentences :param sentences: sequence of sentence that contains words Caution: the sequence might be exhausted after calling this function! :param size: size of dictionary you want :return: dict...
43,669
def simplestr(text): """convert a string into a scrubbed lower snakecase. Intended use is converting human typed field names deterministically into a string that can be used for a key lookup. :param text: type str text to be converted """ text = text.strip() text = text.replace(' ', '_') ...
43,670
def lti_launch(request): """ This method is here to build the LTI_LAUNCH dictionary containing all the LTI parameters and place it into the session. This is nessesary as we need to access these parameters throughout the application and they are only available the first time the application loads. ...
43,671
def compress_file(filename): """ Compresses file with gzip :param filename: path to file to be compressed :type filename: str :rtype: str or None """ if not os.path.isfile(filename): msg = "File not found or cannot be accessed: '{f}'".format(f=filename) _log.critical(msg) ...
43,672
def cartesian_to_altaz(x): """ Converts local Cartesian coordinates to Alt-az, inverting altaz_to_cartesian """ x, y, z = x return np.arcsin(z), np.arctan2(-y, x)
43,673
def main(): """Main function.""" argv = sys.argv assert len(argv) == 4, 'Invalid arguments' global kernel_path global install_path global arch kernel_path = argv[1] install_path = argv[2] arch = argv[3] # avoid the conflic with the 'new' operator in C++ patch_rule_append(...
43,674
def discount_opex(opex, global_parameters, country_parameters): """ Discount opex based on return period. Parameters ---------- cost : float Financial cost. global_parameters : dict All global model parameters. country_parameters : dict All country specific parameter...
43,675
def load_dataset_from_path(path): """ Build a dataset in the form of a pandas dataframe where the schema is: <LYRIC_PATH, EMOTION> """ rows = list() # Traverse the dataset directory for root, dirs, files in os.walk(path): for f in files: fields = f.split('_') if len(fields) <= 0: ...
43,676
def permute(x, perm): """Permutes the last three dimensions of the input Tensor or Array. Args: x (Tensor or Array): Input to be permuted. perm (tuple or list): Permutation. Note: If the input has fewer than three dimensions a copy is returned. """ if is_tensor(x): ...
43,677
def is_hr_between(time: int, time_range: tuple) -> bool: """ Calculate if hour is within a range of hours Example: is_hr_between(4, (24, 5)) will match hours from 24:00:00 to 04:59:59 """ if time_range[1] < time_range[0]: return time >= time_range[0] or time <= time_range[1] return time_...
43,678
def schedule_pull(graph, pull_nodes, message_func, reduce_func, apply_func, inplace, outframe=None): """Get pull schedule Parameters ---------- graph: GraphAdaptor Graph pull_nodes : ...
43,679
def run(): """Run the agent for a finite number of trials.""" # Set up environment and agent e = Environment() # create environment (also adds some dummy traffic) a = e.create_agent(LearningAgent) # create agent e.set_primary_agent(a, enforce_deadline=True) # specify agent to track # NOTE: Y...
43,680
def calc_Topt(sur,obs,Tvals,objfunc='nse'): """ Function to calibrate the T parameter using a brute-force method Args: sur (pandas.Series): pandas series of the surface soil moisture obs (pandas.Series): pandas series of the soil moisture at layer x to calibrate Tvals (list,tuple,set...
43,681
def build_release(): """ Build release with docker """ print(yellow('==> building local release with docker...')) print(red('(!) FLAVOR => %s' % env.flavor)) local('docker build -f %s -t twined/%s_%s .' % (env.dockerfile, env.project_name, env.flavor))
43,682
def share_file(service, file_id): """Make files public For a given file-id, sets role 'reader' to 'anyone'. Returns public link to file. :param: file_id (string) :return: (string) url to shared file """ permission = { 'type': "anyone", 'role': "reader", ...
43,683
def getlocal(): """Get the path to the local directory where OCRopus data is installed. Checks OCROPUS_DATA in the environment first, otherwise defaults to /usr/local/share/ocropus.""" local = os.getenv("OCROPUS_DATA") or modeldir return local
43,684
def load_cereals(context: SolidExecutionContext, date: str): """Docstring for load_cereals. Args: context: SolidExecutionContext Yields: List[Dict[str, str]]: Cereals """ dataset_path = os.path.join(os.path.dirname(__file__), 'cereal.csv') with open(dataset_path, 'r') as fd: ...
43,685
def convert_image_for_visualization(image_data, mean_subtracted=True): """ Convert image data from tensorflow to displayable format """ import data image = image_data if mean_subtracted: image = image + np.asarray(data.IMAGE_BGR_MEAN, np.float32) if FLAGS.image_channel_order == 'BGR': image = ima...
43,686
def mld(returns_array, scale=252): """ Maximum Loss Duration Maximum number of time steps when the returns were below 0 :param returns_array: array of investment returns :param scale: number of days required for normalization. By default in a year there are 252 trading days. :return: MLD """...
43,687
def json2geodf( content: Union[List[Dict[str, Any]], Dict[str, Any]], in_crs: str = DEF_CRS, crs: str = DEF_CRS, ) -> gpd.GeoDataFrame: """Create GeoDataFrame from (Geo)JSON. Parameters ---------- content : dict or list of dict A (Geo)JSON dictionary e.g., r.json() or a list of them...
43,688
def build_block_specs( block_specs: Optional[List[Tuple[Any, ...]]] = None) -> List[BlockSpec]: """Builds the list of BlockSpec objects for SpineNet.""" if not block_specs: block_specs = SPINENET_BLOCK_SPECS logging.info('Building SpineNet block specs: %s', block_specs) return [BlockSpec(*b) for b in bl...
43,689
def est_agb(dbh_mat, sp_list): """ Estimate above ground biomass using the allometric equation in Ishihara et al. 2015. """ # wood density wd_list = [ dict_sp[sp]["wood_density"] if sp in dict_sp and dict_sp[sp]["wood_density"] else None for sp in sp_list ] #...
43,690
def update_pair_statistics(pair, changed, stats, indices): """Minimally update the indices and frequency of symbol pairs if we merge a pair of symbols, only pairs that overlap with occurrences of this pair are affected, and need to be updated. """ stats[pair] = 0 # 已经全部合并 indices[pair] = defau...
43,691
def parse_json_and_match_key(line: str) -> Optional[LogType]: """Parse a line as JSON string and check if it a valid log.""" log = parse_json(line) if log: key = "logbook_type" if key not in log or log[key] != "config": log = None return log
43,692
def nearDistance(img, centers): """ Get the blob nearest to the image center, which is probably the blob for cells, using euclidian distance. Parameters: img, image with labels defined; centers, list of label' centers of mass. Returns: nearestLabel, label nearest to the image center. ...
43,693
def create_app(config_object=ProdConfig): """This function is an application factory. As explained here: http://flask.pocoo.org/docs/patterns/appfactories/. :param config_object: The configuration object to use. """ app = Flask(__name__.split('.')[0]) app.config.from_object(config_object) ...
43,694
def inject(html): """ Inject HTML into a notebook cell """ if not is_notebook(): return from IPython.display import display,HTML display(HTML(html))
43,695
def get_f1_dist1(y_true, y_pred, smooth=default_smooth): """Helper to turn the F1 score into a loss""" return 1 - get_f1_score1(y_true, y_pred, smooth)
43,696
def get_date_info_for_pids_tables(project_id, client): """ Loop through tables within all datasets and determine if the table has an end_date date or a date field. Filtering out the person table and keeping only tables with PID and an upload or start/end date associated. :param project_id: bq name of p...
43,697
def migrate(name=None, fake=False): """makemigrate :param name: 迁移文件名称 :param fake: fake=True, 如果你的数据库已经有了数据, 且不想删除它 """ router = Router(db, ignore='basemodel') names = [mm.name for mm in router.model.select().order_by(router.model.id)] if name: router.run(name, fake) else: ...
43,698
def default_worker_init_fn() -> None: """ """ worker_seed = torch.initial_seed() torch.random.seed(worker_seed) random.seed(worker_seed) numpy.random.seed(worker_seed)
43,699