content
stringlengths
22
815k
id
int64
0
4.91M
def main(): """ Run some tests with a dummy file, overriding chromosome lengths locally for sake of testing. """ tl = TwoLocus(in_path='/csbiodata/public/www.csbio.unc.edu/htdocs/sgreens/pairwise_origins/') # tl = TwoLocus() # tl.preprocess(glob.glob('OR_ss_origins/*.hap')) print len(tl.list_ava...
5,301,300
def dice(a, b): """ "Entity-based" measure in CoNLL; #4 in CEAF paper """ if a and b: return (2 * len(a & b)) / (len(a) + len(b)) return 0.
5,301,301
def traverseFilter(node,filterCallback): """Traverse every node and return a list of the nodes that matched the given expression For example: expr='a+3+map("test",f())' ast=SeExprPy.AST(expr) allCalls=SeExprPy.traverseFilter(ast.root(),lambda node,children: node.type==SeExprPy.ASTType.C...
5,301,302
def int2bin(n,digits=8): """ integer to binary string""" return "".join([str((n >> y) & 1) for y in range(digits-1, -1, -1)])
5,301,303
def infer_locations(data: InferenceHint) -> pd.DataFrame: """Infer the locations for the given input.""" return infer_concat(get_location_model(), data, columns=LOCATION_COLUMNS)
5,301,304
def replace_digits(p, digits): """If p contains more than one of the same digit, replace them will all other possible digits.""" if 0 in digits: other_digits = [str(d) for d in list(range(1, 10)) if str(d) != str(p)[digits[0]]] else: other_digits = [str(d)...
5,301,305
def flattendataitem(dataitem): """ This could easily be more elegant, but """ # If it's a dataitem for the multiplex stream we don't flatten it if not isnormaldataitem(dataitem): return dataitem # Nice normalized dataitems get to be flattened of course flattened = dict() ...
5,301,306
def active_piece(piece): """ Validate piece as active. """ return piece & 1 and piece & 0xE
5,301,307
def ProjectEdgeSubmesh( submesh_and_edge = [None] ): """ Description: Projects orthogonally an edge sub-mesh on another. Arguments: # submesh_and_edge Description: The source submesh and the target sub-edge. Type: List of1 Edge + 1 Sub-mesh GUI selection: yes Selection by na...
5,301,308
def get_db_connection(config_filename): """ Create a database connection to the mysql database associated with slurm. :param config_filename: path to slurmdbd.conf :return: database connection """ config = Config(config_filename) port = None if config.port: port = int(config.port...
5,301,309
def _create_gradient_clipper(cfg): """ Creates gradient clipping closure to clip by value or by norm, according to the provided config. """ cfg = cfg.clone() def clip_grad_norm(p: _GradientClipperInput): torch.nn.utils.clip_grad_norm_(p, cfg.CLIP_VALUE, cfg.NORM_TYPE) def clip_grad...
5,301,310
def readwav(filename): """ read in audio data from a wav file. Return d, sr """ # Read in wav file sr, wavd = wav.read(filename) # normalize short ints to floats of -1 / 1 data = np.asfarray(wavd) / 32768.0 return data, sr
5,301,311
def main(): """Main.""" conf = { "/": { 'request.dispatch': cherrypy.dispatch.MethodDispatcher() } } cherrypy.quickstart(TuxyCaptcha(), "/", conf)
5,301,312
def jacobian(x0, system, weight=False): """Compute the Jacobians of a steady state nonlinear state-space model Jacobians of a nonlinear state-space model x(t+1) = A x(t) + B u(t) + E zeta(x(t),u(t)) y(t) = C x(t) + D u(t) + F eta(x(t),u(t)) i.e. the partial derivatives of the modeled ou...
5,301,313
def parse_args(argv=None): """Return the parsed args to use in main().""" if argv is None: argv = sys.argv prog = argv[0] if prog == __file__: prog = '{} -m ptvsd'.format(os.path.basename(sys.executable)) else: prog = argv[0] argv = argv[1:] su...
5,301,314
def delete_neighbor_v4(obj_ids): """Delete NeighborV4.""" for obj_id in obj_ids: try: obj_to_delete = get_neighbor_v4_by_id(obj_id) obj_to_delete.delete_v4() except NeighborV4DoesNotExistException as e: raise ObjectDoesNotExistException(str(e)) except...
5,301,315
def bay_bridge_example(render=None, use_inflows=False, use_traffic_lights=False): """ Perform a simulation of vehicles on the Oakland-San Francisco Bay Bridge. Parameters ---------- render: bool, optional specifies whether to use the gui during ...
5,301,316
def load_training_dataset(data_path,datafile,normalize_by='by_subject',scaling=True,padding=True,input_shape=(79, 95, 69)): """ Loads the training dataset from datset.pickle file and returns the train, test and val dataset data_path: str full path of the data datafile: pickle file which contains the inf...
5,301,317
def keepClosestMarkupRelationships(markup): """Initially modifiers may be applied to multiple targets. This function computes the text difference between the modifier and each modified target and keeps only the minimum distance relationship Finally, we make sure that there are no self modifying modifie...
5,301,318
def dsfdP(P): """ Derivative of Specific entropy [kJ m^3 / kg K kJ] of saturated liquid w.r.t. pressure""" T = satT(P) return region1.dsdP(P, T) + region1.dsdT(P, T) * dTsdP(P)
5,301,319
def cleanup_images(path: str, image: Optional[str] = None) -> None: """ Clean up image storage directory. Only supose to delete .gif, .mp4, and .jpg files """ if image is not None: try: os.remove(path + image) except Exception as err: _LOGGER.error("Error at...
5,301,320
def calcDeDt(stars,tau): """ Calculates the change in binary orbital eccentricity over time at each radial bin due to the torque/mass from the surrounding CB disk. Parameters ---------- stars: pynbody stars object (sim units) tau: torque/mass on binary due to CB disk during a given snapshot...
5,301,321
def register_procedure(entry_point: "ProcedureHarness") -> None: """ Register a new ProcedureHarness with QCEngine """ name = entry_point.name if name.lower() in procedures.keys(): raise ValueError("{} is already a registered procedure.".format(name)) procedures[name.lower()] = entry_p...
5,301,322
def zamid_to_name(zamid): """"Finds and returns the name of the nuclide""" dic = d.nuc_name_dic if len(zamid) == 5: nz = int(zamid[0:1]) na = int(zamid[1:4]) state = int(zamid[4]) if len(zamid) == 6: nz = int(zamid[0:2]) na = int(zamid[2:5]) state = int(zamid[5]) if len(zamid) == 7: nz = int(zamid[0...
5,301,323
def rk4_solve_parallel(y, t, w): """ Runge-Kutta solver for systems of 1st order ODEs (should call function rk4_step_parallel) Args: f: name of right-hand side function that gives rate of change of y y: numpy array of dependent variable output (fist entry should be initial conditions) ...
5,301,324
def add_json(item): """Download all packages described by a json file""" with open(item) as sync_file: sync = json.load(sync_file) for package in sync['packages']: add_package(package, sync['servers'])
5,301,325
def r_enumerate(seq): """Enumerate a sequence in reverse order.""" # Note that we don't use reversed() since Python 2.3 doesn't have it num = len(seq) - 1 while num >= 0: yield num, seq[num] num -= 1
5,301,326
def purchase_reserved_db_instances_offering(ReservedDBInstancesOfferingId=None, ReservedDBInstanceId=None, DBInstanceCount=None, Tags=None): """ Purchases a reserved DB instance offering. See also: AWS API Documentation Examples This example purchases a reserved DB instance offering that matche...
5,301,327
def test_rectangular_dos_unit(D, gamma): """Integral over the whole DOS should be 1.""" dos = partial(gt.lattice.rectangular.dos, half_bandwidth=D, scale=gamma) singularity = D * (gamma - 1) / (gamma + 1) assert fp.quad(dos, [-D, -singularity, singularity, D]) == pytest.approx(1.)
5,301,328
def get_hist(data, bins=None, range=None, dx=None, wts=None): """ return hist, bins, var after binning data This is just a wrapper for numpy.histogram, with optional weights for each element and proper computing of variances. Note: there are no overflow / underflow bins. Available binning methods...
5,301,329
def get_all_source_files(arr=None, prefix="."): """Return source files.""" if arr is None: arr = [] if not os.path.isdir(prefix): # assume a file arr.append(prefix) return arr for fx in os.listdir(prefix): # pylint: disable=too-many-boolean-expressions i...
5,301,330
def test_add_frequencies(future_shapes, gain_data): """Test adding frequencies between two UVCal objects""" # don't test on delays because there's no freq axis for the delay array calobj = gain_data if future_shapes: calobj.use_future_array_shapes() calobj2 = calobj.copy() calobj_full...
5,301,331
def count_all_questions_yes(group_input: str) -> int: """count questions all group members answered with yes""" list_of_sets = [set(line.strip()) for line in group_input.split("\n")] return len(set.intersection(*list_of_sets))
5,301,332
def parseIncludeReferenceStatementsByDir(dir_path): """ Resolves `include` and `$ref` statements for all the JSON files inside a given directory. Args: dir_path (str): directory to parse. Returns: dict|list """ data = [] for root, dirs, files in os.walk(dir_path): ...
5,301,333
def writeNetworkMetadata(f, network): """ Write the metadata for the `network` to the given file object `f`. """ if network.title != '' and network.title != 'Untitled': f.write('title = "{0}"\n'.format(network.title)) if network.description != '': f.write('description = \\\n') ...
5,301,334
def test_appendleft_child_to_empty_deque(): """Testing a value added to the front of a empty deque.""" test_deque = Deque() test_deque.appendleft_child([1, 2, 3, 5]) assert test_deque.dll.head.data == ([1, 2, 3, 5])
5,301,335
def db_heal(args, api_args): """Creates missing entries in DB's for all inconsistencies.""" vnc_cgitb.enable(format='text') db_healer = DatabaseHealer(args, api_args) # Obj UUID cassandra inconsistencies db_healer.heal_fq_name_index() db_healer.heal_back_ref_index() db_healer.heal_children_...
5,301,336
def check_service_status(service): """ queries systemd through dbus to see if the service is running """ service_running = False bus = SystemBus() systemd = bus.get_object("org.freedesktop.systemd1", "/org/freedesktop/systemd1") manager = Interface(systemd, dbus_interface="org.freedesktop.systemd1.M...
5,301,337
def get_job_results(job_id): """ A ndb helper method that manipulates the _scraper object. """ return ndb.root._spiders.lists[job_id].results
5,301,338
def filter_valid_classification_data_sources_items(items: Iterable[ScalarDataSource], file_to_path_mapping: Optional[Dict[str, Path]], max_sequence_position_value: Optional[int] = None, ...
5,301,339
def z_coord(cube): """Heuristic way to return the dimensionless vertical coordinate.""" try: z = cube.coord(axis='Z') except CoordinateNotFoundError: z = cube.coords(axis='Z') for coord in cube.coords(axis='Z'): if coord.ndim == 1: z = coord return z
5,301,340
def visualize_spharagram(sphara_trans_eegdata,time_axis=None,eegdata=None,ysel=None,dt=None): """ param: ysel number of basis functions for transformation param: sphara_trans_eegdata [timesteps, N_bases] """ if dt and not time_axis: time_axis = np.arange(0,len(sphara_trans_eegdata)*dt,dt) ...
5,301,341
def pool_drivers(): """ Return a list of EntryPoints names """ return [ep.name for ep in pkg_resources.iter_entry_points(STORAGE_ENTRY_POINT)]
5,301,342
def to_bagua_process_group( process_group: Union[TorchProcessGroup, BaguaProcessGroup, None] = None ): """Convert a PyTorch process group to a Bagua process group. Args: process_group (Union[TorchProcessGroup, BaguaProcessGroup, None], optional): PyTorch process group or Bagua process g...
5,301,343
def operate_favorite(bvid: str = None, aid: int = None, add_media_ids: list = None, del_media_ids: list = None, verify: utils.Verify = None): """ 操作音频收藏夹 :param aid: :param bvid: :param add_media_ids: :param del_media_ids: :param verify: :return: """ if not (...
5,301,344
def test_domain(value, fails, allow_empty, allow_ips): """Test the domain validator.""" if not fails: validated = validators.domain(value, allow_empty = allow_empty, allow_ips = allow_ips) if value: assert is...
5,301,345
def Mounted(obj): """ Returns true if the specified mobile is mounted. :param obj: An entity serial in integer or hex format, or an alias string such as "self". """ pass
5,301,346
def test_get_device_detects_none(hass, mock_openzwave): """Test device returns none.""" node = MockNode() value = MockValue(data=0, node=node) values = MockEntityValues(primary=value, node=node) device = zwave.get_device(hass=hass, node=node, values=values, node_config...
5,301,347
def client_code(abstraction: OperationSystem) -> str: """ За исключением этапа инициализации, когда объект Абстракции связывается с определённым объектом Реализации, клиентский код должен зависеть только от класса Абстракции. Таким образом, клиентский код может поддерживать любую комбинацию абстракц...
5,301,348
def consistent_langevin_dynamics(rng, model, sigmas, init, epsilon, T, denoise=True, infi...
5,301,349
def _random_colour_masks(image): """ Generates a random color mask. :param image: Image to generate the mask. :return: Coloured mask. """ r = np.zeros_like(image).astype(np.uint8) g = np.zeros_like(image).astype(np.uint8) b = np.zeros_like(image).astype(np.uint8) r[image == 0], g[ima...
5,301,350
def get_cell_numbers(contained): """Retrieve non-overlapping cell numbers from the output of `get_overlapping`. None may appear at the ends of the output, indicating that the corresponding target cells are not overlapping with any source cells. These should be ignored when regridding. Cell numbers...
5,301,351
def test_fill(): """Test filling labels with different brush sizes.""" np.random.seed(0) data = np.random.randint(20, size=(10, 15)) data[:10, :10] = 2 data[:5, :5] = 1 layer = Labels(data) assert np.unique(layer.data[:5, :5]) == 1 assert np.unique(layer.data[5:10, 5:10]) == 2 layer...
5,301,352
def describe_period_project_users(clinic_acct_username, clinic_acct_password): """ Answer some basic questions about the users involved in the project. """ tp_api = TidepoolAPI(clinic_acct_username, clinic_acct_password) tp_api.login() pending_invitations_json = tp_api.get_pending_observer_inv...
5,301,353
def get_mos(da, da_peak_times): """ Takes an xarray DataArray containing veg_index values and calculates the vegetation values (time not available) at middle of season (mos) for each timeseries per-pixel. The middle of season is the mean vege value and time (day of year) in the timeseries at 80% t...
5,301,354
def alternate_remove_duplicates(qdb: dt.QueriesTextParser): """Different commands, same result""" _dup_list = [] for topic, q_vars in qdb.query_vars.items(): _dup_list.extend(qdb.queries_df.loc[qdb.queries_df['qid'].isin(q_vars)].duplicated('text')) return qdb.queries_df[~qdb.queries_df['qid'].i...
5,301,355
def to_hash_bucket_deterministic(batch, num_buckets, seed=None): """Buckets input examples, roughly uniformly and deterministically. Args: batch: a tensor of rank >= 1, containing the input examples (batch axis = 0). num_buckets: an integer, number of buckets. seed: (optional) this seed will be u...
5,301,356
def reduce_infectivity(model: Model, modelList=None): """Reduce the values of the effective contact rates of a model. This is an optional function to be executed before or after each iteration. To use it, add it to the after_funcs or before_funcs parameters. It traverses the model aand reduces the valu...
5,301,357
def random_training_set(chunks, revmap, volatile=False, start=0, batch_size=util.BATCH_SIZE): """Generate a training set from the randomized set of chunks (sequences), returning them in descending order by size (per Torch's variable length sequence RNN support). If `volatile` is True, the variables wil...
5,301,358
def test_iaverage_output_shape(axis): """Test output shape""" source = [np.random.random((16, 12, 5)) for _ in range(10)] stack = np.stack(source, axis=-1) from_numpy = np.average(stack, axis=axis) out = last(iaverage(source, axis=axis)) assert from_numpy.shape == out.shape assert np.allclo...
5,301,359
def verify_password(username, password): """Verify that user exists and that password is correct.""" user = models.User.query.get(username) if user and verify_password_argon2id(user.password, password): return user return None
5,301,360
def check_half_links(ln): """ Scan line for SE half-links where '[https://...]' appears. SE half-links support specifying only the URL and SE goes out to get the current name for the URL. This only works in SE though, not in G-H Pages. From: https://meta.stackexchange.com/help/forma...
5,301,361
def RandomUniform(inp, low=-1.0, high=1.0): """ Random uniformly distributed initialization. """ return np.random.uniform(size=inp, low=low, high=high)
5,301,362
def device_activity(dev): """Indicate device LED activity """ if dev: dev.DeviceActivity()
5,301,363
def uiCheckboxSetText(checkbox, text): """ Sets the text of the checkbox. :param checkbox: uiCheckbox :param text: string :return: None """ clibui.uiCheckboxSetText(checkbox, bytes(text, 'utf-8'))
5,301,364
def twdb_texuni(dataframe, drop_dcp_metadata=True, dual_well=False): """Parser for twdb texuni dataloggers. Data is transmitted every 12 hours and each message contains 12 water level measurements on the hour for the previous 12 hours format examples: '"\r\n+0.000,-245.3,\r\n+0.000,-245.3,\r\n+0.00...
5,301,365
def FromMol( mol: Chem.Mol, useGroups: Optional[bool] = True, useFilters: Optional[bool] = True ) -> str: """Convert RDKit Mol to AMSR :param mol: RDKit Mol :param useGroups: use group symbols/abbreviations :param useFilters: apply filters to exclude unstable or synthetically inaccessible molecules...
5,301,366
def _similar_names(owner, attrname, distance_threshold, max_choices): """Given an owner and a name, try to find similar names. The similar names are searched given a distance metric and only a given number of choices will be returned. """ possible_names = [] names = _node_names(owner) for ...
5,301,367
def list_remote_pipelines() -> List[str]: """List all the repositories in the pangeo-forge organization.""" r = requests.get(f"{BASE}/orgs/pangeo-forge/repos", headers=HEADERS) r.raise_for_status() repos = r.json() repos = [repo["name"] for repo in repos if "-pipeline" in repo["name"]] return re...
5,301,368
def get_amended_desc(drev, ctx, folded): """similar to ``getdescfromdrev``, but supports a folded series of commits This is used when determining if an individual commit needs to have its message amended after posting it for review. The determination is made for each individual commit, even when they ...
5,301,369
def todays_artist_spotlight(): """ If there is an artist spotlight for today, return that artist object """ today = datetime.date.today() # get today's artist spotlight, if there is one try: spotlight = ArtistSpotlight.objects.get(date=today) except ArtistSpotlight.DoesNotExist as e...
5,301,370
def _get_angle(a, b, c): """ Get angle between vector ba and bc """ ba = a - b bc = c - b cosine_angle = np.dot(ba, bc) / (np.linalg.norm(ba) * np.linalg.norm(bc)) angle = np.arccos(cosine_angle) return np.degrees(angle)
5,301,371
def _wx(item: str) -> dict: """ Parses remaining weather elements """ ret = {'wx': []} items = item.split() for item in items: if len(item) < 3: ret['wx'].append(item) elif item.startswith('FV'): _, ret['flight_visibility'] = core.get_visibility([item[2:]]...
5,301,372
def _setup_render_size_from_intrinsics(scene, intrinsics): """Set the render output size from camera intrinsics. Args: scene (bpy.types.Scene): scene to operate in intrinsics (np.array): intrinsics in order fx, fy, cx, cy """ fx, fy, cx, cy = intrinsics[0], intrinsics[1], intrinsics[2],...
5,301,373
def test_that_code_is_up_to_date(): """Test that running the codegen updates what we expect, but does not introduce changes.""" # Obtain mtime of all files mtimes = {} for root, dirs, files in os.walk(lib_dir): if "__pycache__" in root: continue for fname in files: ...
5,301,374
def zeroSR1(fcnGrad, h, prox, options): """ ZEROSR1 Solves smooth + nonsmooth/constrained optimization problems xk,nit, stepSizes = zeroSR1(fcnGrad, h, prox_h, opts) This uses the zero-memory SR1 method (quasi-Newton) to solve: min_x f(x) + h(x) where 'fcnGrad' calculates f(x) and its gradient at x, and h(x...
5,301,375
def del_link(hist,appli): """"Fonction qui est appelée lors de la commande Choix du p dans lequel supprimer le lien""" p_I="" #On initialise p_I pour éviter un problème dans la fonction remplir_listbox root=Tk() root.title("Supprimer un lien") Label(root,text="Veuillez indiquer dans quel paragra...
5,301,376
def tag_validate(tags, case_ids, plan_id): """Tests tag checking func""" error_msg = None tag_id = re.findall('ID_\d+|id_\d+', str(tags)) if not tag_id: error_msg = "Wrong Tag Format:\ \nPls add tag 'ID_case_id' to this case." elif int(tag_id[0][3:]) not in case_ids: ...
5,301,377
def assert_equal( actual: Tuple[numpy.int32, numpy.int32, numpy.int32], desired: Tuple[int, int, int] ): """ usage.scipy: 1 """ ...
5,301,378
def generate_tree_html(tree): """ Given a tree representing HTML file paths, return an HTML table plotting those paths. """ items = [] for node, subtree in sorted(compat_items(tree)): if 'entry' in subtree: html = u'<li><a href="{}">{}</a></li>'.format(subtree['entry']['relpa...
5,301,379
def test_query_set_fields_exception(cbcsdk_mock): """Testing raising ApiError in Query.set_fields().""" api = cbcsdk_mock.api event = api.select(Event) assert event._fields == ["*"] event.set_fields(["event_type"]) assert event._get_query_parameters()["fields"] == ["event_type"] event.set_fi...
5,301,380
def return_valid_table_names() -> Tuple[str, ...]: """Get a tuple of valid table names.""" return tuple(_TABLE_COLUMN_PATTERNS.keys())
5,301,381
def safety(c): # type: (Context) -> None """Run safety.""" _run( c, "poetry export --dev --format=requirements.txt --without-hashes | " "poetry run safety check --stdin --full-report", )
5,301,382
def _text_match(vobject_item, filter_, child_name, ns, attrib_name=None): """Check whether the ``item`` matches the text-match ``filter_``. See rfc4791-9.7.5. """ # TODO: collations are not supported, but the default ones needed # for DAV servers are actually pretty useless. Texts are lowered to ...
5,301,383
def test_add_job_input_type_major(monkeypatch, dates, forces, job_len): """ Check that only input lists are accepted. Checked by counting jobs added to police.jobs dataframe. """ # This will give police.available from fixtures monkeypatch.setattr(PoliceAPI, "_basic_request_to_df", mock_request_t...
5,301,384
def cached_dataset(f, url=None, version=None, paths=None): """Test decorator providing a clone of `url` from cache If config datalad.tests.cache is not set, delivers a clone in a temporary location of the original `url`. Otherwise that clone is in fact a clone of a cached dataset (origin being the cach...
5,301,385
async def db_add_column(ctx, column_name, data_type): """Add a column to the table""" txt = HD.add_column(column_name, data_type) await ctx.send(txt)
5,301,386
def rest_target_reset(args): """ :param argparse.Namespace args: object containing the processed command line arguments; need args.target :raises: IndexError if target not found """ for target in args.target: rtb, rt = _rest_target_find_by_id(target) rtb.rest_tb_target_reset(rt...
5,301,387
def _concat_nested_arrays(arrs, cells_as_numpy=False): """ Helper function to nest tabular arrays from nested list of arrays. Parameters ---------- arrs : list of numpy arrays Arrays must have the same number of rows, but can have varying number of columns. cells_as_numpy : boo...
5,301,388
def submit_to_remote(name, value, **options): """ A submit button that submits via an XMLHttpRequest call Returns a button input tag that will submit form using XMLHttpRequest in the background instead of regular reloading POST arrangement. Keyword args are the same as in ``form_remote_tag``....
5,301,389
def commutative_similarity(node, target, tolerance=0, *args, **kwargs): """Apply :func:`monosaccharide_similarity` to ``node`` and ``target`` for both ``node --> target`` and ``target --> node``, returning whether either comparison passes the tolerance threshold. Parameters ---------- node: :cl...
5,301,390
def dataloader_subset(dl, batches=1): """Like torch's dataset Subset but for dataloaders. This lets us easily do things like fit on a single batch (or small number of batches) by essentially copying an existing dataloader's options but using a smaller dataset. A few limitations: custom samplers and batc...
5,301,391
def RunOsUpgradeBuild(args, output_filter, instance_uri, release_track): """Run a OS Upgrade on Google Cloud Builder. Args: args: an argparse namespace. All the arguments that were provided to this command invocation. output_filter: A list of strings indicating what lines from the log should be...
5,301,392
def FormatFieldType(type_context, field): """Format a FieldDescriptorProto type description. Args: type_context: contextual information for message/enum/field. field: FieldDescriptor proto. Returns: Formatted proto field type as string. """ label = 'repeated ' if field.label == field.LABEL_REPEA...
5,301,393
def get_ip(): """ 获取本地ip """ my_ip = "" try: my_ip = urllib.request.urlopen('http://api.ipify.org').read() except Exception: my_ip = urllib.request.urlopen('http://icanhazip.com').read() return bytes.decode(my_ip).strip()
5,301,394
def get_ict_dataset(use_titles=True, query_in_block_prob=1): """Get a dataset which uses block samples mappings to get ICT/block indexing data (via get_block()) rather than for training, since it is only built with a single epoch sample mapping. """ args = get_args() block_dataset = get_indexed_data...
5,301,395
def build_geojson(): """ Converts json structure into geojson for Mapbox: - 'Point' geometry for STILL (resting) datapoints - 'LineString' geometry for IN_VEHICLE, ON_FOOT, WALKING datapoints """ if STILL_JSON.is_file() is False: print(">>> Individual jsons not found, categorizing m...
5,301,396
def test_parallel_pickling(): """ Check that pmap captures the errors when it is passed an object that cannot be pickled. """ def g(x): return x ** 2 try: # pickling a local function always fail but the exception # raised is a PickleError for python <= 3.4 and AttributeE...
5,301,397
def pair_assemble(t, on_left=None, on_right=None): """ Combine a pair of records into a single record This is mindful to shared columns as well as missing records Parameters ---------- t : Join The join to combine. on_left : list of column indicies, optional The column indicies...
5,301,398
def create_OrdinalEncoderTransformer_test_df(): """Create DataFrame to use OrdinalEncoderTransformer tests that correct values are DataFrame column a is the response, the other columns are categorical columns of types; object, category, int, float, bool. """ df = pd.DataFrame( { ...
5,301,399