content
stringlengths
22
815k
id
int64
0
4.91M
def get_name_convert_func(): """ Get the function to convert Caffe2 layer names to PyTorch layer names. Returns: (func): function to convert parameter name from Caffe2 format to PyTorch format. """ pairs = [ # ------------------------------------------------------------ ...
23,500
def update_workflow_modal( user_id: str, user_email: str, channel_id: str, incident_id: int, action: dict, db_session=None, slack_client=None, ): """Pushes an updated view to the run workflow modal.""" trigger_id = action["trigger_id"] incident_id = action["view"]["private_metada...
23,501
def generate_dict_entry(key, wordlist): """Generate one entry of the python dictionary""" entry = " '{}': {},\n".format(key, wordlist) return entry
23,502
def test_download_task_saves_file_for_valid_request(tmp_path: Path) -> None: """Download on valid HTTP request. Args: tmp_path (Path): see https://docs.pytest.org/en/stable/tmpdir.html """ filename = "data.zip" responses.add( responses.GET, "http://www.urltodata.ie", ...
23,503
def record_to_dict(record): """ Transform string into bovespa.Record :param record: (string) position string from bovespa. :return: parsed Record """ try: record = bovespa.Record(record) except: return None return { 'date': record.date, 'year': record.date.year, ...
23,504
def sample_product(user, **params): """Create and return a custom product""" defaults = { 'name': 'Ron Cacique', 'description': 'El ron cacique es...', 'price': 20, 'weight': '0.70', 'units': 'l', 'featured': True, } defaults.update(params) return Pro...
23,505
def _find_op_path_(block, outputs, inputs, no_grad_set): """ no_grad_set will also be changed """ input_names = set([inp.name for inp in inputs]) output_names = set([out.name for out in outputs]) relevant_op_flags = [True] * len(block.ops) # All the inputs of the block are used if inputs i...
23,506
def clean_gltf_materials(gltf): """ 未使用のglTFマテリアルを削除する :param gltf: glTFオブジェクト :return: 新しいマテリアルリスト """ return filter(lambda m: m['name'] in used_material_names(gltf), gltf['materials'])
23,507
def create_root(request): """ Returns a new traversal tree root. """ r = Root() r.add('api', api.create_root(request)) r.add('a', Annotations(request)) r.add('t', TagStreamFactory()) r.add('u', UserStreamFactory()) return r
23,508
def test_flatten_preserve_nulls(minion_opts, local_salt): """ Test the `flatten` Jinja filter. """ rendered = render_jinja_tmpl( "{{ [1, 2, [None, 3, [4]]] | flatten(preserve_nulls=True) }}", dict(opts=minion_opts, saltenv="test", salt=local_salt), ) assert rendered == "[1, 2, No...
23,509
def sort_basis_functions(basis_functions): """Sorts a set of basis functions by their distance to the function with the smallest two-norm. Args: basis_functions: The set of basis functions to sort. Expected shape is (-1, basis_function_length). Returns: sorted_basis: The so...
23,510
def to_zgrid(roms_file, z_file, src_grid=None, z_grid=None, depth=None, records=None, threads=2, reftime=None, nx=0, ny=0, weight=10, vmap=None, cdl=None, dims=2, pmap=None): """ Given an existing ROMS history or average file, create (if does not exit) a new z-grid file. Use the gi...
23,511
def info_materials_groups_get(): """ info_materials_groups_get Get **array** of information for all materials, or if an array of `type_ids` is included, information on only those materials. :rtype: List[Group] """ session = info_map.Session() mat = aliased(info_map.Material) ...
23,512
def TestFSSH(): """ molcas test 1. FSSH calculation """ pyrai2mddir = os.environ['PYRAI2MD'] testdir = '%s/fssh' % (os.getcwd()) record = { 'coord' : 'FileNotFound', 'energy' : 'FileNotFound', 'energy1' : 'FileNotFound', 'energy2' : 'FileNotFound', ...
23,513
def relu(x): """ Compute the relu of x Arguments: x -- A scalar or numpy array of any size. Return: s -- relu(x) """ s = np.maximum(0,x) return s
23,514
def _disable_flavor(flavor): """Completely disable the given `flavor` (no checks).""" _deregister_aliases(flavor) _deregister_description(flavor) _deregister_identifier(flavor) _deregister_converters(flavor) all_flavors.remove(flavor)
23,515
def validate_config(config: TrainerConfigDict) -> None: """Checks and updates the config based on settings. Rewrites rollout_fragment_length to take into account n_step truncation. """ if config["exploration_config"]["type"] == "ParameterNoise": if config["batch_mode"] != "complete_episodes": ...
23,516
def test_adjective_predicates(r): """ Test adjectives with an associated predicate """ # Accusative case (þolfall) s = r.parse_single( """ Hundurinn var viðstaddur sýninguna sem fjallaði um hann. """ ) assert "NP-PRD lo_sb_nf_sþf_et_kk NP-ADP no_et_þf_kvk" in s.tree.flat ...
23,517
def kane_frstar_alt(bodies, coordinates, speeds, kdeqs, inertial_frame, uaux=Matrix(), udep=None, Ars=None): """Form the generalized inertia force.""" t = dynamicsymbols._t N = inertial_frame # Derived inputs q = Matrix(coordinates) # q u = Matrix(speeds) # u udot = u.diff(t) qdot_u_ma...
23,518
def line(value): """ | Line which can be used to cross with functions like RSI or MACD. | Name: line\_\ **value**\ :param value: Value of the line :type value: float """ def return_function(data): column_name = f'line_{value}' if column_name not in data.columns: ...
23,519
def goodsGetSku(spuId,regionId): """ :param spuId: :param regionId: :return: """ reqUrl = req_url('goods', "/goods/getGoodsList") if reqUrl: url = reqUrl else: return "服务host匹配失败" headers = { 'Content-Type': 'application/json', 'X-Region-Id': regionI...
23,520
def build_model(config, model_dir=None, weight=None): """ Inputs: config: train_config, see train_celery.py model_dir: a trained model's output dir, None if model has not been trained yet weight: class weights """ contents = os.listdir(model_dir) print(contents) return C...
23,521
def get_scheduler(config, optimizer): """ :param config: 配置参数 :param optimizer: 优化器 :return: 学习率衰减策略 """ # 加载学习率衰减策略 if config.scheduler_name == 'StepLR': scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=config.StepLR['decay_step'], ...
23,522
def main(): """ Pairwise identity is a script which takes a protein sequence file that's full of protein sequences and calculates the percent identity of all possible pairwise combinations (basically the cartesian product) of the proteins """ sh_parse = argparse.ArgumentParser(description="Ca...
23,523
def pipeline_dict() -> dict: """Pipeline config dict. You need to update the labels!""" pipeline_dictionary = { "name": "german_business_names", "features": { "word": {"embedding_dim": 16, "lowercase_tokens": True}, "char": { "embedding_dim": 16, ...
23,524
def test_output_should_conform_to_hocr(tmp_path): """Test if an exported file conform to hOCR.""" html_path = os.path.join(tmp_path, "md.html") pdftotree.parse("tests/input/md.pdf", html_path) with Popen(["hocr-check", html_path], stderr=PIPE) as proc: assert all([line.decode("utf-8").startswith...
23,525
def _is_hangul_syllable(i): """ Function for determining if a Unicode scalar value i is within the range of Hangul syllables. :param i: Unicode scalar value to lookup :return: Boolean: True if the lookup value is within the range of Hangul syllables, otherwise False. """ if i in range(0xAC00, 0...
23,526
def shape14_4(tik_instance, input_x, res, input_shape, shape_info): """input_shape == ((32, 16, 14, 14, 16), 'float16', (1, 1), (1, 1))""" stride_w, stride_h, filter_w, filter_h, dilation_filter_w, dilation_filter_h = shape_info pad = [0, 0, 0, 0] l1_h = 14 l1_w = 14 c1_index = 0 jump_stride...
23,527
def read_json( downloader: Download, datasetinfo: Dict, **kwargs: Any ) -> Optional[Iterator[Union[List, Dict]]]: """Read data from json source allowing for JSONPath expressions Args: downloader (Download): Download object for downloading JSON datasetinfo (Dict): Dictionary of information a...
23,528
def json_dumps_safer(obj, **kwargs): """Convert obj to json, with some extra encodable types.""" return json.dumps(obj, cls=WandBJSONEncoder, **kwargs)
23,529
def load_data(filename: str): """ Load house prices dataset and preprocess data. Parameters ---------- filename: str Path to house prices dataset Returns ------- Design matrix and response vector (prices) - either as a single DataFrame or a Tuple[DataFrame, Series] """ ...
23,530
def test(runner): """Test the environment * Verify redis connectivity indepedent of moi * Verify database connectivity * Verify submission via moi Tests are performed both on the server and ipengines. """ def redis_test(**kwargs): """Put and get a key from redis""" from uui...
23,531
def reset_database(): """仅限开发阶段使用,请不要在发布阶段开启这样的危险命令 """ if app.config['ADMIN_KEY']: if request.args.get('key') == app.config['ADMIN_KEY']: if request.args.get('totp') == pyotp.TOTP(app.config['TOTP_SECRET']).now(): os.remove(app.config['SQLALCHEMY_DATABASE_PATH']) ...
23,532
def test_construct_with_node(): """This function tests constructing payload using properly formatted node data.""" control_data = get_control_data('node') payload = messages.construct_payload('This is the subject line', node={"id": "my-board"}) assert payload == control_data # nosec return
23,533
def validate_model(model): """ Validate a single data model parameter or a full data model block by recursively calling the 'validate' method on each node working from the leaf nodes up the tree. :param model: part of data model to validate :type model: :graphit:GraphAxis :return: ov...
23,534
def test_transforms_scaler(): """Tests dsutils.transforms.Scaler""" df = pd.DataFrame() df['a'] = [1, 2, 3, 4, 5] df['b'] = [1, 2, 3, 4, 5] df['c'] = [10, 20, 30, 40, 50] out = Scaler().fit_transform(df) assert isinstance(out, pd.DataFrame) assert out.shape[0] == 5 assert out.shap...
23,535
def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None. """ filename = "{0}.html".format(url.split("/").pop().lower()) filepath = abspath(join(dirna...
23,536
def ensemble_tsfresh(forecast_in, forecast_out, season, perd): """ Create rolled time series for ts feature extraction """ def tsfresh_run(forecast, season, insample=True, forecast_out=None): df_roll_prep = forecast.reset_index() if insample: df_roll_prep = df_roll_prep.drop...
23,537
def transform_svm_mat2file(filename): """ Transform the svm model in .mat to .file """ model = loadmat(filename) text_file = open(filename[:-4], "w") text_file.write("solver_type L2R_LR\n") text_file.write("nr_class %d\n" % model['svmmodel']['nr_class']) text_file.write("label 1 ...
23,538
def train_and_test(dataset, nb_epochs, random_seed, label): """ Runs DSEBM on available datasets Note: Saves summaries on tensorboard. To display them, please use cmd line tensorboard --logdir=model.training_logdir() --port=number Args: dataset (string): dataset to run the model o...
23,539
def __modules_with_root_module_path(path): """ Returns all modules beneath the root module path. This treats all directories as packages regardless of whether or not they include a __init__.py. """ modules = [] if os.path.isfile(path) and os.path.splitext(path)[1] == '.py' and os.path.basena...
23,540
def transform_from_latlon(lat, lon): """ Tranform from latitude and longitude NOTES: - credit - Shoyer https://gist.github.com/shoyer/0eb96fa8ab683ef078eb """ from affine import Affine lat = np.asarray(lat) lon = np.asarray(lon) trans = Affine.translation(lon[0], lat[0]) scale =...
23,541
def xml_to_json(xml_text: str) -> OrderedDict: """Converts xml text to json. Args: xml_text (str): xml text to be parsed Returns: OrderedDict: an ordered dict representing the xml text as json """ return xmltodict.parse(xml_text)
23,542
def get_calendar_future_events(api_service): """Se trae todos los eventos del calendario de Sysarmy. Args: api_service (googleapiclient.discovery.Resource): servicio ya autenticado para pegarle a la API de calendar. Returns: list: lista de diccionarios con los eventos futuros y...
23,543
def getWeather(city, apikey): """ 天気を取得する リクエストにAPIKeyと都市をパラメーターに入れる https://openweathermap.org/forecast5 """ payload = { 'APIKEY': APIKEY, 'q': CITY } r = requests.get( APIBASE, params=payload ) return r
23,544
def func1(xc): """Function which sets the data value""" s = .1 res = np.exp(-xc**2/(2*s**2)) return res
23,545
def GetEnabledDiskTemplates(*args): """Wrapper for L{_QaConfig.GetEnabledDiskTemplates}. """ return GetConfig().GetEnabledDiskTemplates(*args)
23,546
def test_aliases_are_dropped_on_iterating_so_jobs_arent_double_counted(proj): """ Test that aliases are dropped so that jobs aren't double counted when iterated over """ symlink = proj.basepath / "CtfFind" / "ctffind4" symlink.symlink_to(proj.basepath / "Class2D" / "job003") sym_ctffind = pr...
23,547
def is_pull_request_merged(pull_request): """Takes a github3.pulls.ShortPullRequest object""" return pull_request.merged_at is not None
23,548
def arraytoptseries(arr, crs={'epsg': '4326'}): """Convert an array of shape (2, ...) or (3, ...) to a geopandas GeoSeries containing shapely Point objects. """ if arr.shape[0] == 2: result = geopandas.GeoSeries([Point(x[0], x[1]) for x in arr.reshape(2, -1).T...
23,549
async def get_kml_network_link(): """ Return KML network link file """ logger.info('/c-haines/network-link') headers = {"Content-Type": kml_media_type, "Content-Disposition": "inline;filename=c-haines-network-link.kml"} return Response(headers=headers, media_type=kml_media_type, content=...
23,550
def splitToPyNodeList(res): # type: (str) -> List[pymel.core.general.PyNode] """ converts a whitespace-separated string of names to a list of PyNode objects Parameters ---------- res : str Returns ------- List[pymel.core.general.PyNode] """ return toPyNodeList(res.split())
23,551
def get_jira_issue(commit_message): """retrieve the jira issue referenced in the commit message >>> get_jira_issue(b"BAH-123: ") {b'BAH-123'} >>> messages = ( ... b"this is jira issue named plainly BAH-123", ... b"BAH-123 plainly at the beginning", ... b"in parens (BAH-123)", ... b"(BAH...
23,552
def wiki3(): """Generate Wikipedia markup code for statistics charts.""" ignore_dates = ('2020-02-04', '2020-02-27') data = archive.load(ignore_dates=ignore_dates) update = source = fetch_wiki_source(WIKI_SRC3) full_dates = ', '.join(x.strftime('%Y-%m-%d') for x in data.datetimes) # Cases. ...
23,553
def hello(event, context): """ This is my awesome hello world function that encrypts text! It's like my first web site, only in Lambda. Maybe I can add a hit counter later? What about <blink>? Args: event: context: Returns: """ # General run of the mill dangerous, but it ...
23,554
def _create_archive_files(msid): """Create the values.h5 and times.h5 for the lifetime of an msid :param msid: the msid that for which archive files are being created. :type msid: str :raises err: a generic `catch all` exception. """ values_files = f"{ENG_ARCHIVE}/archive/data/tlm/{msid}/value...
23,555
def test_process_e_bad_value(): """Test that we get nothing when finding a bad value.""" msg = ".E GDMM5 20210919 CS DH1948/TAIRG/DIN06/ 70/ HI/ 67" with pytest.raises(InvalidSHEFValue): process_message_e(msg, utc(2021, 9, 20))
23,556
def get_mean_std(dataloader): """Compute mean and std on the fly. Args: dataloader (Dataloader): Dataloader class from torch.utils.data. Returns: ndarray: ndarray of mean and std. """ cnt = 0 mean = 0 std = 0 for l in dataloader: # N...
23,557
def p_selection_list(p): """ selection_list : keypath_as | selection_list COMMA keypath_as """ if len(p) == 2: p[0] = { p[1].label: { "keypath": p[1].keypath, "traversal_label": p[1].traversal_label, } } elif ...
23,558
def do_retrieve(url, fname): """Retrieve given url to target filepath fname.""" folder = os.path.dirname(fname) if not os.path.exists(folder): os.makedirs(folder) print(f"{folder}{os.path.sep} created.") if not os.path.exists(fname): try: with open(fname, 'wb') as fou...
23,559
def create_random_camera(bbox, frac_space_x, frac_space_y, frac_space_z): """ Creates a new camera, sets a random position for it, for a scene inside the bbox. Given the same random_seed the pose of the camera is deterministic. Input: bbox - same rep as output from get_scene_bbos. Output: new ...
23,560
def temp2(): """ This is weird, but correct """ if True: return (1, 2) else: if True: return (2, 3) return (4, 5)
23,561
def compute_blade_representation(bitmap: int, firstIdx: int) -> Tuple[int, ...]: """ Takes a bitmap representation and converts it to the tuple blade representation """ bmp = bitmap blade = [] n = firstIdx while bmp > 0: if bmp & 1: blade.append(n) bmp = bmp >...
23,562
def are_dir_trees_equal(dir1, dir2): """ Compare two directories recursively. Files in each directory are assumed to be equal if their names and contents are equal. @param dir1: First directory path @param dir2: Second directory path @return: True if the directory trees are the same and there were no errors ...
23,563
def get_ntp_time(ntp_server_url): """ 通过ntp server获取网络时间 :param ntp_server_url: 传入的服务器的地址 :return: time.strftime()格式化后的时间和日期 """ ntp_client = ntplib.NTPClient() ntp_stats = ntp_client.request(ntp_server_url) fmt_time = time.strftime('%X', time.localtime(ntp_stats.tx_time)) fmt_date ...
23,564
def read_data(path, names, verbose=False): """ Read time-series from MATLAB .mat file. Parameters ---------- path : str Path (relative or absolute) to the time series file. names : list Names of the requested time series incl. the time array itself verbose : bool, optional ...
23,565
async def search(q: str, person_type: str = 'student') -> list: """ Search by query. :param q: `str` query to search for :param person_type: 'student', 'lecturer', 'group', 'auditorium' :return: list of results """ url = '/'.join((BASE_URL, SEARCH_INDPOINT)) params = {'term': q, ...
23,566
def stop_application(app, topwidget): """Destroy application widget and stop application.""" try: topwidget.destroy() except: pass try: del app except: pass
23,567
def format_data_hex(data): """Convert the bytes array to an hex representation.""" # Bytes are separated by spaces. return ' '.join('%02X' % byte for byte in data)
23,568
def eval_test(test_path, gt_path, test_prefix='', gt_prefix='', test_format='png', gt_format='png', exigence=2, desync=0): """ Evaluates some test results against a given ground truth :param test_path: (str) relative or absolute path to the test results images :param gt_path: (str) relati...
23,569
def get_installation_token(installation): """ Get access token for installation """ now = datetime.datetime.now().timestamp() if installation_token_expiry[installation] is None or now + 60 > installation_token_expiry[installation]: # FIXME: if .netrc file is present, Authorization header ...
23,570
def extract_data(structure, fields, exe, output, return_data, components): """ Extract data from the Abaqus .odb file. Parameters ---------- structure : obj Structure object. fields : list Data field requests. exe : str Abaqus exe path to bypass defaults. output : bo...
23,571
def disp(cog_x, cog_y, src_x, src_y): """ Compute the disp parameters Parameters ---------- cog_x: `numpy.ndarray` or float cog_y: `numpy.ndarray` or float src_x: `numpy.ndarray` or float src_y: `numpy.ndarray` or float Returns ------- (disp_dx, disp_dy, disp_norm, disp_ang...
23,572
def get_landmark_from_prob(prob, thres=0.5, mode="mean", binary_mask=False): """Compute landmark location from the model probablity maps Inputs: prob : [RO, E1], the model produced probablity map for a landmark thres : if np.max(prob)<thres, determine there is no landmark detected m...
23,573
def request( url, timeout: float, method="GET", data=None, response_encoding="utf-8", headers=None, ): """ Helper function to perform HTTP requests """ req = Request(url, data=data, method=method, headers=headers or {}) try: return urlopen(req, timeout=timeout).read()...
23,574
def get_annotation_affiliation(annotation: Any, default: Any) -> Optional[Any]: """Helper for classifying affiliation of parameter :param annotation: annotation record :returns: classified value or None """ args, alias = get_args(annotation), get_origin(annotation) # if alias and alias == list:...
23,575
def find_config_files( path=['~/.vcspull'], match=['*'], filetype=['json', 'yaml'], include_home=False ): """Return repos from a directory and match. Not recursive. Parameters ---------- path : list list of paths to search match : list list of globs to search against filetyp...
23,576
def main(): """ Benchmark your model in your local pc. """ model = MobileUNet(input_shape=(img_size, img_size, 3)) inputs = np.random.randn(batch_num, img_size, img_size, 3) time_per_batch = [] for i in range(10): start = time.time() model.predict(inputs, batch_size=batch_n...
23,577
def sort_dict(original): """Recursively sorts dictionary keys and dictionary values in alphabetical order""" if isinstance(original, dict): res = ( dict() ) # Make a new "ordered" dictionary. No need for Collections in Python 3.7+ for k, v in sorted(original.items()): ...
23,578
def playonyt(topic): """Will play video on following topic, takes about 10 to 15 seconds to load""" url = 'https://www.youtube.com/results?q=' + topic count = 0 cont = requests.get(url) data = str(cont.content) lst = data.split('"') for i in lst: count+=1 if i == 'WE...
23,579
def train_classifier(classifier, features, labels): """This function must concern itself with training the classifier on the specified data.""" return classifier.fit(features, labels)
23,580
def work_on_disk(dev, root_mb, swap_mb, image_path): """Creates partitions and write an image to the root partition.""" root_part = "%s-part1" % dev swap_part = "%s-part2" % dev if not is_block_device(dev): LOG.warn(_("parent device '%s' not found"), dev) return make_partitions(dev,...
23,581
def get_annotation_names(viewer): """Detect the names of nodes and edges layers""" layer_nodes_name = None layer_edges_name = None for layer in viewer.layers: if isinstance(layer, napari.layers.points.points.Points): layer_nodes_name = layer.name elif isinstance(layer, napar...
23,582
def remap(kx,ky,lx,ly,qomt,datai): """ remap the k-space variable back to shearing periodic frame to reflect the time dependent Eulerian wave number """ ndim = datai.ndim dim = np.array(datai.shape)# datai[nz,ny,nx] sh_data = np.empty([dim[0],dim[1],dim[2]]) tp_data = np.empty([dim[0],dim[2]]) sh...
23,583
def fips_disable(): """ Disables FIPS on RH/CentOS system. Note that you must reboot the system in order for FIPS to be disabled. This routine prepares the system to disable FIPS. CLI Example: .. code-block:: bash salt '*' ash.fips_disable """ installed_fips_pkgs = _get_install...
23,584
def get_os_platform(): """return platform name, but for Jython it uses os.name Java property""" ver = sys.platform.lower() if ver.startswith('java'): import java.lang ver = java.lang.System.getProperty("os.name").lower() print('platform: %s' % (ver)) return ver
23,585
def buy_sell_fun_mp_org(datam, S1=1.0, S2=0.8): """ 斜率指标交易策略标准分策略 """ start_t = datetime.datetime.now() print("begin-buy_sell_fun_mp:", start_t) dataR = pd.DataFrame() for code in datam.index.levels[1]: # data = price.copy() # price = datam.query("code=='%s'" % code) ...
23,586
def marshall_namedtuple(obj): """ This method takes any atomic value, list, dictionary or namedtuple, and recursively it tries translating namedtuples into dictionaries """ recurse = lambda x: map(marshall_namedtuple, x) obj_is = partial(isinstance, obj) if hasattr(obj, '_marshall'): ...
23,587
def prep_image(img, inp_dim): """ Prepare image for inputting to the neural network. Returns a Variable """ # print("prepping images") img = cv2.resize(img, (inp_dim, inp_dim)) img = img[:,:,::-1].transpose((2,0,1)).copy() img = torch.from_numpy(img).float().div(255.0) # print...
23,588
def best_broaders(supers_for_all_entities: Dict, per_candidate_links_and_supers: List[Dict], num_best: int = 5, super_counts_field: str = "broader_counts", doprint=False, representativeness_threshold=0.1): """ Returns the ...
23,589
def clump_list_sort(clump_list): """Returns a copy of clump_list, sorted by ascending minimum density. This eliminates overlap when passing to yt.visualization.plot_modification.ClumpContourCallback""" minDensity = [c['Density'].min() for c in clump_list] args = np.argsort(minDensity) list...
23,590
def _prepare_artifact( metadata_handler: metadata.Metadata, uri: Text, properties: Dict[Text, Any], custom_properties: Dict[Text, Any], reimport: bool, output_artifact_class: Type[types.Artifact], mlmd_artifact_type: Optional[metadata_store_pb2.ArtifactType] ) -> types.Artifact: """Prepares th...
23,591
def ParseCLILines(lines, skipStartLines=0, lastSkipLineRe=None, skipEndLines=0): """Delete first few and last few lines in an array""" if skipStartLines > 0: if lastSkipLineRe != None: # sanity check. Make sure last line to skip matches the given regexp if None == re.match(lastSk...
23,592
def test_screen_size(stdscr, height, width): """ Test that the current screen is larger than height x width. If its not print a warning and give the user a change to enlarge the screen wait until Y/y is provided by the user """ h, w = stdscr.getmaxyx() pair = curses.init_pair(1, curses.COLOR...
23,593
def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- weight matrix of shape (n_h, n_x) ...
23,594
def _NormalizedSource(source): """Normalize the path. But not if that gets rid of a variable, as this may expand to something larger than one directory. Arguments: source: The path to be normalize.d Returns: The normalized path. """ normalized = os.path.normpath(source) if source.count('$...
23,595
def get_df_from_sampled_trips(step_trip_list, show_service_data=False, earliest_datetime=None): """Get dataframe from sampled trip list. Parameters ---------- step_trip_list : list of lists List of trip lists occuring in the same step. show_service_data: bool Show trip pickup and dr...
23,596
def compute_v_y(transporter, particles): """ Compute values of V y on grid specified in bunch configuration :param transporter: transport function :param particles: BunchConfiguration object, specification of grid :return: matrix with columns: x, theta_x, y, theta_y, pt, V y """ return __com...
23,597
def normal_scaler(s3_bucket_input, s3_bucket_output, objects=(), dry_run=False): """ Scale the values in a dataset to fit a unit normal distribution. """ if not objects: # Allow user to specify objects, or otherwise get all objects. objects = get_all_keys(s3_bucket_input) # Calculate bounds...
23,598
def gabor_kernel_nodc(frequency, theta=0, bandwidth=1, gamma=1, n_stds=3, offset=0): """ Return complex 2D Gabor filter kernel with no DC offset. This function is a modification of the gabor_kernel function of scikit-image Gabor kernel is a Gaussian kernel modulate...
23,599