content
stringlengths
22
815k
id
int64
0
4.91M
def XMLToPython (pattern): """Convert the given pattern to the format required for Python regular expressions. @param pattern: A Unicode string defining a pattern consistent with U{XML regular expressions<http://www.w3.org/TR/xmlschema-2/index.html#regexs>}. @return: A Unicode string specifyin...
22,500
def test_bad_color_array(): """Test adding shapes to InfiniteLineList.""" np.random.seed(0) data = np.random.random(1) vert = VerticalLine(data) line_list = InfiniteLineList() line_list.add(vert) # test setting color with a color array of the wrong shape bad_color_array = np.array([[0, ...
22,501
def write_deterministic_to_file(configuration, nowcast_data, filename=None, metadata=None): """Write deterministic output in ODIM HDF5 format.. Input: configuration -- Object containing configuration parameters nowcast_data -- generated deterministic nowcast filename -- filename for out...
22,502
def __termios(fd): """Try to discover terminal width with fcntl, struct and termios.""" #noinspection PyBroadException try: import fcntl import termios import struct cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) except Ex...
22,503
def encode(numbers, GCE=GCE): """ do extended encoding on a list of numbers for the google chart api >>> encode([1690, 90,1000]) 'chd=e:aaBaPo' """ encoded = [] for number in numbers: if number > 4095: raise ValueError('too large') first, second = divmod(number, len(GCE)) ...
22,504
def compute_f_mat(mat_rat,user_count,movie_count): """ compute the f matrix :param mat_rat: user`s rating matrix([user number,movie number]) where 1 means user likes the index movie. :param user_count: statistics of moive numbers that user have watch. :param movie_count: statistics of user numbers t...
22,505
def main(device, transfer_json, test_mode): """ Main """ release_josn = f"metadata/release-{device}.json" if test_mode: log.warn("Test mode is active") mount_point = "test/" else: mount_point = MOUNT_POINT define_tag_from_json(release_josn) copy_metadata_files()...
22,506
def metadata(path="xdress/metadata.json"): """Build a metadata file.""" md = {} md.update(INFO) # FIXME: Add the contents of CMakeCache.txt to the metadata dictionary # write the metadata file with open(path, 'w') as f: json.dump(md, f, indent=2) return md
22,507
def query_assemblies(organism, output, quiet=False): """from a taxid or a organism name, download all refseq assemblies """ logger = logging.getLogger(__name__) assemblies = [] genomes = Entrez.read(Entrez.esearch( "assembly", term=f"{organism}[Organism]", retmax=10000))["I...
22,508
def setup_autoscale(): """Setup AWS autoscale""" my_id = 'wedding_plattform' kwargs = { "ami_id": 'ami-3fec7956', # Official Ubuntu 12.04.1 LTS US-EAST-1 "instance_type": "t1.micro", "key_name": my_id, "security_groups": [my_id], "availability_zones": ["us-east-1a",...
22,509
def main(params): """Loads the file containing the collation results from Wdiff. Then, identifies various kinds of differences that can be observed. Assembles this information for each difference between the two texts.""" print("\n== coleto: running text_analyze. ==") difftext = get_difftext(params[...
22,510
def test__get_title_failure(_root_errors, _ns): """ GIVEN a XML root Element of an METS/XML file with missing title values and a dictionary with the mets namespace WHEN calling the method _get_title() THEN check that the returned string is correct """ expected = "" actual...
22,511
def test_stacking(): """Assert that the stacking method creates a Stack model.""" atom = ATOMClassifier(X_bin, y_bin, experiment="test", random_state=1) pytest.raises(NotFittedError, atom.stacking) atom.run(["LR", "LGB"]) atom.stacking() assert hasattr(atom, "stack") assert "Stack" in atom.m...
22,512
def matrix_horizontal_stack(matrices: list, _deepcopy: bool = True): """ stack matrices horizontally. :param matrices: (list of Matrix) :param _deepcopy: (bool) :return: (Matrix) """ assert matrices for _i in range(1, len(matrices)): assert matrices[_i].basic_data_type() == matri...
22,513
def inds_to_invmap_as_array(inds: np.ndarray): """ Returns a mapping that maps global indices to local ones as an array. Parameters ---------- inds : numpy.ndarray An array of global indices. Returns ------- numpy.ndarray Mapping from global to local. """ re...
22,514
def install_plugin_urls(): """ urlpatterns - bCTF original urlpatterns """ urls = [] for plugin in list_plugins(): urls.append(path('{0}/'.format(plugin), include('plugins.{0}.urls'.format(plugin)))) return urls
22,515
def ident_keys(item, cfg): """Returns the list of keys in item which gives its identity :param item: dict with type information :param cfg: config options :returns: a list of fields for item that give it its identity :rtype: list """ try: return content.ident_keys(item) except E...
22,516
def playlists_by_date(formatter, albums): """Returns a single playlist of favorite tracks from albums sorted by decreasing review date. """ sorted_tracks = [] sorted_albums = sorted(albums, key=lambda x: x["date"], reverse=True) for album in sorted_albums: if album["picks"] is None: ...
22,517
def cryptdisks_start(target, context=None): """ Execute :man:`cryptdisks_start` or emulate its functionality. :param target: The mapped device name (a string). :param context: See :func:`.coerce_context()` for details. :raises: :exc:`~executor.ExternalCommandFailed` when a command fails, ...
22,518
def attach_ipv6_raguard_policy_to_interface(device, interface, policy_name): """ Attach IPv6 RA Guard Policy to an interface Args: device (`obj`): Device object interface (`str`): Interface to attach policy policy_name (`str`): Policy name to be attached to interface ...
22,519
def merge_two_sorted_array(l1, l2): """ Time Complexity: O(n+m) Space Complexity: O(n+m) :param l1: List[int] :param l2: List[int] :return: List[int] """ if not l1: return l2 if not l2: return l1 merge_list = [] i1 = 0 i2 = 0 l1_len = len(l1) - 1 ...
22,520
def regression_metrics(y_true,y_pred): """ param1: pandas.Series/pandas.DataFrame/numpy.darray param2: pandas.Series/pandas.DataFrame/numpy.darray return: dictionary Function accept actual prediction labels from the dataset and predicted values from the model and utilizes this two values/data...
22,521
def test_auto_id(): """Tests auto_id option.""" acc = mm.MOTAccumulator(auto_id=True) acc.update([1, 2, 3, 4], [], []) acc.update([1, 2, 3, 4], [], []) assert acc.events.index.levels[0][-1] == 1 acc.update([1, 2, 3, 4], [], []) assert acc.events.index.levels[0][-1] == 2 with pytest.rais...
22,522
def convert_from_quint8(arr): """ Dequantize a quint8 NumPy ndarray into a float one. :param arr: Input ndarray. """ assert isinstance(arr, np.ndarray) assert ( "mgb_dtype" in arr.dtype.metadata and arr.dtype.metadata["mgb_dtype"]["name"] == "Quantized8Asymm" ), "arr should ...
22,523
def _process_payment_id(state: State, tsx_data: MoneroTransactionData): """ Writes payment id to the `extra` field under the TX_EXTRA_NONCE = 0x02 tag. The second tag describes if the payment id is encrypted or not. If the payment id is 8 bytes long it implies encryption and therefore the TX_EXTRA_...
22,524
def classpartial(*args, **kwargs): """Bind arguments to a class's __init__.""" cls, args = args[0], args[1:] class Partial(cls): __doc__ = cls.__doc__ def __new__(self): return cls(*args, **kwargs) Partial.__name__ = cls.__name__ return Partial
22,525
def load_xml(xml_path): """ Загружает xml в etree.ElementTree """ if os.path.exists(xml_path): xml_io = open(xml_path, 'rb') else: raise ValueError(xml_path) xml = objectify.parse(xml_io) xml_io.close() return xml
22,526
def alphabetize_concat(input_list): """ Takes a python list. List can contain arbitrary objects with .__str__() method (so string, int, float are all ok.) Sorts them alphanumerically. Returns a single string with result joined by underscores. """ array = np.array(input_list, dtype=st...
22,527
def kick(state, ai, ac, af, cosmology=cosmo, dtype=np.float32, name="Kick", **kwargs): """Kick the particles given the state Parameters ---------- state: tensor Input state tensor of shape (3, batch_size, npart, 3) ai, ac, af: float """ with tf.name_scope(name): state = tf.convert_to_te...
22,528
def check_similarity(var1, var2, error): """ Check the simulatiry between two numbers, considering a error margin. Parameters: ----------- var1: float var2: float error: float Returns: ----------- similarity: boolean """ if((var1 <= (var2 + error)) and (v...
22,529
def model_type_by_code(algorithm_code): """ Method which return algorithm type by algorithm code. algorithm_code MUST contain any 'intable' type :param algorithm_code: code of algorithm :return: algorithm type name by algorithm code or None """ # invalid algorithm code case if algorith...
22,530
def getCasing(word): """ Returns the casing of a word""" if len(word) == 0: return 'other' elif word.isdigit(): #Is a digit return 'numeric' elif word.islower(): #All lower case return 'allLower' elif word.isupper(): #All upper case return 'allUpper' elif word[0...
22,531
def normalize_angle(deg): """ Take an angle in degrees and return it as a value between 0 and 360 :param deg: float or int :return: float or int, value between 0 and 360 """ angle = deg while angle > 360: angle -= 360 while angle < 360: angle += 360 return angle
22,532
def test_staging_different_volumes_with_the_same_staging_target_path(): """Staging different volumes with the same staging_target_path."""
22,533
def current_global_irradiance(site_properties, solar_properties, timestamp): """Calculate the clear-sky POA (plane of array) irradiance for a specific time (seconds timestamp).""" dt = datetime.datetime.fromtimestamp(timestamp=timestamp, tz=tz.gettz(site_properties.tz)) n = dt.timetuple().tm_yday sigma...
22,534
def agglomeration_energy_gather(bundle_activities, nonbundle_activities, n_bundles, agglomeration_energy): """ Accumulate the energy binding a new feature to an existing bundle.. This formulation takes advantage of loops and the sparsity of the data. The original arithme...
22,535
def add_glider(i, j, grid): """adds a glider with top left cell at (i, j)""" glider = np.array([[0, 0, 255], [255, 0, 255], [0, 255, 255]]) grid[i:i+3, j:j+3] = glider
22,536
def date_formatting(format_date, date_selected): """Date formatting management. Arguments: format_date {str} -- Date date_selected {str} -- Date user input Returns: str -- formatted date """ if len(date_selected) == 19: date_selected = datetime.strptime( ...
22,537
def update_validationsets_sources(validation_dict, date_acquired=False): """Adds or replaces metadata dictionary of validation reference dataset to the validation sets sources file :param validation_dict: dictionary of validation metadata :param date_acquired: """ if not date_acquired: ...
22,538
def test_search(runner): """ Test search """ res = runner.invoke(search, ["author=wangonya"]) assert res.exit_code == 0 assert "Status code: 200" in res.output res = runner.invoke(search, ["auonya"]) assert res.exit_code == 0 assert "Status code: 400" in res.output
22,539
def parse_activity_from_metadata(metadata): """Parse activity name from metadata Args: metadata: List of metadata from log file Returns Activity name from metadata""" return _parse_type_metadata(metadata)[1]
22,540
def mask_data_by_FeatureMask(eopatch, data_da, mask): """ Creates a copy of array and insert 0 where data is masked. :param data_da: dataarray :type data_da: xarray.DataArray :return: dataaray :rtype: xarray.DataArray """ mask = eopatch[FeatureType.MASK][mask] if len(data_da...
22,541
def makeFields(prefix, n): """Generate a list of field names with this prefix up to n""" return [prefix+str(n) for n in range(1,n+1)]
22,542
def process_input_dir(input_dir): """ Find all image file paths in subdirs, convert to str and extract labels from subdir names :param input_dir Path object for parent directory e.g. train :returns: list of file paths as str, list of image labels as str """ file_paths = list(input_dir.rglob('*....
22,543
def test_kappa_RTA_aln_with_sigma(aln_lda): """Test RTA with smearing method by AlN.""" aln_lda.sigmas = [ 0.1, ] aln_lda.sigma_cutoff = 3 kappa_P_RTA, kappa_C = _get_kappa_RTA(aln_lda, [7, 7, 5]) np.testing.assert_allclose(aln_lda_kappa_P_RTA_with_sigmas, kappa_P_RTA, atol=0.5) np.t...
22,544
def plot_2d_projection_many_mp(ax, mp): """ Plot many motion primitives projected onto the x-y axis, independent of original dimension. """ n_dim = mp[0]['p0'].shape[0] for m in mp: if m['is_valid']: st, sj, sa, sv, sp = min_time_bvp.uniformly_sample( m['p0']...
22,545
def main(): """ Entry of module :return: """ setup_logger() config = None try: config = create_config(FLAGS.config_source, FLAGS.json_file) _LOGGER.info('Begin to compile model, config: %s', config) except Exception as error: # pylint:disable=broad-except _LOGGE...
22,546
def fak(n): """ Berechnet die Fakultaet der ganzen Zahl n. """ erg = 1 for i in range(2, n+1): erg *= i return erg
22,547
def save(data, destination_path, **kwargs): """Generate a csv file from a datastructure. :param data: Currently data must be a list of dicts. :type data: list of dict :param destination_path: Path of the resulting CSV file. :type destination_path: str :raises ValueError: If the format of data c...
22,548
def create_sequences_sonnets(sonnets): """ This creates sequences as done in Homework 6, by mapping each word to an integer in order to create a series of sequences. This function specifically makes entire sonnets into individual sequences and returns the list of processed sonnets back to be used in...
22,549
def detect_venv_command(command_name: str) -> pathlib.Path: """Detect a command in the same venv as the current utility.""" venv_path = pathlib.Path(sys.argv[0]).parent.absolute() expected_command_path = venv_path / command_name if expected_command_path.is_file(): result = expected_command_path...
22,550
def l_to_rgb(img_l): """ Convert a numpy array (l channel) into an rgb image :param img_l: :return: """ lab = np.squeeze(255 * (img_l + 1) / 2) return color.gray2rgb(lab) / 255
22,551
def plotLogsInteract(d2, d3, rho1, rho2, rho3, v1, v2, v3, usingT=False): """ interactive wrapper of plotLogs """ d = np.array((0., d2, d3), dtype=float) rho = np.array((rho1, rho2, rho3), dtype=float) v = np.array((v1, v2, v3), dtype=float) plotLogs(d, rho, v, usingT)
22,552
def blockchain_assert_absolute_time_exceeds(condition: ConditionWithArgs, timestamp): """ Checks if current time in millis exceeds the time specified in condition """ try: expected_mili_time = int_from_bytes(condition.vars[0]) except ValueError: return Err.INVALID_CONDITION curr...
22,553
def test_check_phi(): """Tests the _check_phi function""" numeaf = 175 def set_phi(f): tm.phi = f # First check that None is properly converted tm._phi = None assert_is(tm.phi, None) tm.phi = np.ones(numeaf) assert_array_equal(tm.phi, np.ones(numeaf)) # Check that incorrect n...
22,554
def show_aip(mets_file): """Show a METS file""" mets_instance = METS.query.filter_by(metsfile='%s' % (mets_file)).first() level = mets_instance.level original_files = mets_instance.metslist dcmetadata = mets_instance.dcmetadata divs = mets_instance.divs filecount = mets_instance.originalfile...
22,555
def testCartesianEpehemeris( ephemeris_actual, ephemeris_desired, position_tol=1*u.m, velocity_tol=(1*u.mm/u.s), magnitude=True, raise_error=True ): """ Tests that the two sets of cartesian ephemeris are within the desired absolute tolerances of each other...
22,556
def test_fuse_circuit_two_qubit_gates(backend): """Check circuit fusion in circuit with two-qubit gates only.""" c = Circuit(2) c.add(gates.CNOT(0, 1)) c.add(gates.RX(0, theta=0.1234).controlled_by(1)) c.add(gates.SWAP(0, 1)) c.add(gates.fSim(1, 0, theta=0.1234, phi=0.324)) c.add(gates.RY(1,...
22,557
def mixin_post_create(cls, sender, instance, created, *args, **kwargs): """ Create or update services without indetifiers """ if not created: return user = instance service_classes = tuple( c for c in SERVICES if not getattr(c, 'IDENTIFIER_FIELD', None) ) for service_cl...
22,558
def get_longitude_latitude(city_info, station): """ 利用高德地图查询对应的地铁站经纬度信息,下面的key需要自己去高德官网申请 https://lbs.amap.com/api/webservice/guide/api/georegeo :param city_info: 具体城市的地铁,如:广州市地铁 :param station: 具体的地铁站名称,如:珠江新城站 :return: 经纬度 """ addr = city_info + station print('*要查找的地点:' + addr) ...
22,559
def make_resource_object(resource_type, credentials_path): """Creates and configures the service object for operating on resources. Args: resource_type: [string] The Google API resource type to operate on. credentials_path: [string] Path to credentials file, or none for default. """ try: api_name, ...
22,560
def AreBenchmarkResultsDifferent(result_dict_1, result_dict_2, test=MANN, significance_level=0.05): """Runs the given test on the results of each metric in the benchmarks. Checks if the dicts have been created from the same benchmark, i.e. if metric names match (e.g. first_non_em...
22,561
def _load_pascal_annotation(image_index): """ Load image and bounding boxes info from XML file in the PASCAL VOC format. """ #image_index = _load_image_set_index() classes = ('__background__', # always index 0 'aeroplane', 'bicycle', 'bird', 'boat', ...
22,562
def virsh_memtune_conf(params, env): """ """ pass
22,563
def create_global_var(shape, value, dtype, persistable=False, force_cpu=False, name=None): """ This function creates a new tensor variable with value in the global block(block 0). Parameters: ...
22,564
def select(population, fitness_val): """ 选择操作,用轮盘赌法进行选择 :param population: 种群基因型 :param fitness_val: 种群适应度 :return selected_pop: 选择后的种群 """ f_sum = sum(fitness_val) cumulative = [] for i in range(1, len(fitness_val)+1): cumulative.append(sum(fitness_val[:i]) / f_sum) ...
22,565
def _nan_helper(y, nan=False, inf=False, undef=None): """ Helper to handle indices and logical indices of NaNs, Infs or undefs. Definition ---------- def _nan_helper(y, nan=False, inf=False, undef=None): Input ----- y 1d numpy array with possible missing values Optional ...
22,566
def unpacking(block_dets, *, repeat=False, **_kwargs): """ Identify name unpacking e.g. x, y = coord """ unpacked_els = block_dets.element.xpath(ASSIGN_UNPACKING_XPATH) if not unpacked_els: return None title = layout("""\ ### Name unpacking """) summary_bits = [] for unp...
22,567
def load_training_data(): """Loads the Fashion-MNIST dataset. Returns: Tuple of Numpy arrays: `(x_train, y_train)`. License: The copyright for Fashion-MNIST is held by Zalando SE. Fashion-MNIST is licensed under the [MIT license]( https://github.com/zalandoresearch/fashion-...
22,568
def set_difference(tree, context, attribs): """A meta-feature that will produce the set difference of two boolean features (will have keys set to 1 only for those features that occur in the first set but not in the second). @rtype: dict @return: dictionary with keys for key occurring with the first...
22,569
def _output_to_new(parsed_file: parse.PyTestGenParsedFile, output_dir: str, include: List[str] = []) -> None: """Output the tests in 'parsed_file' to an output directory, optionally only including a whitelist of functions to output tests for. Args: parsed_file:...
22,570
def create_STATES(us_states_location): """ Create shapely files of states. Args: us_states_location (str): Directory location of states shapefiles. Returns: States data as cartopy feature for plotting. """ proj = ccrs.LambertConformal(central_latitude = 25, ...
22,571
def get_name_by_url(url): """Returns the name of a stock from the instrument url. Should be located at ``https://api.robinhood.com/instruments/<id>`` where <id> is the id of the stock. :param url: The url of the stock as a string. :type url: str :returns: Returns the simple name of the stock. If th...
22,572
def reducer(event, context): """Combine results from workers into a single result.""" format_reducer_fn = FORMAT_HANDLERS[event["format"]]["reducer"] format_reducer_fn(event["request_id"]) increment_state_field(event["request_id"], "CompletedReducerExecutions", 1) record_timing_event(event["request...
22,573
def recursively_replace(original, replacements, include_original_keys=False): """Clones an iterable and recursively replaces specific values.""" # If this function would be called recursively, the parameters 'replacements' and 'include_original_keys' would have to be # passed each time. Therefore, a h...
22,574
def test_indexLengthCheck(wkwdataset): """Test whether the dataset length matches the length of train, validation and test datasets""" indexStrings = getIndsPropString(wkwdataset) indexList = getIndices(wkwdataset, indexStrings) lengthSeparate = [len(index) for index in indexList] assert sum(lengthS...
22,575
def set_default_node_as(as_num): """ Set the default node BGP AS Number. :param as_num: The default AS number :return: None. """ client.set_default_node_as(as_num)
22,576
def destructure(hint: t.Any) -> t.Tuple[t.Any, t.Tuple[t.Any, ...]]: """Return type hint origin and args.""" return get_origin(hint), get_args(hint)
22,577
def f_x_pbe(x, kappa=0.804, mu=0.2195149727645171): """Evaluates PBE exchange enhancement factor. 10.1103/PhysRevLett.77.3865 Eq. 14. F_X(x) = 1 + kappa ( 1 - 1 / (1 + mu s^2)/kappa ) kappa, mu = 0.804, 0.2195149727645171 (PBE values) s = c x, c = 1 / (2 (3pi^2)^(1/3) ) Args: x: Float numpy array with...
22,578
def index(): """ if no browser and no platform: it's a CLI request. """ if g.client['browser'] is None or g.client['platform'] is None: string = "hello from API {} -- in CLI Mode" msg = {'message': string.format(versions[0]), 'status': 'OK', 'mode': 200} ...
22,579
def getKeyWait(opCode): """ A key press is awaited, and then stored in VX. (Blocking Operation. All instruction halted until next key event) OPCODE: FX0A Parameters: opCode: (16 bit hexadecimal number) """ global PC, register press = False ...
22,580
def prompt_yes_no(question, default=None): """Asks a yes/no question and returns either True or False.""" prompt = (default is True and 'Y/n') or (default is False and 'y/N') or 'y/n' valid = {'yes': True, 'ye': True, 'y': True, 'no': False, 'n': False} while True: choice = input(question + prompt + ': ')....
22,581
def attention_resnet20(**kwargs): """Constructs a ResNet-20 model. """ model = CifarAttentionResNet(CifarAttentionBasicBlock, 3, **kwargs) return model
22,582
def download_data(download_path: str) -> None: """ Downloads data from kaggle. Requires kaggle API key to be set up. Args: download_path : str Download destination """ system( "kaggle competitions download " + "-c tpu-getting-started " + f...
22,583
def get_basename(name): """ [pm/cmds] オブジェクト名からベースネームを取得する """ fullpath = get_fullpath(name) return re(r"^.*\|", "", fullpath)
22,584
def get_live_token(resource_uri: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetLiveTokenResult: """ The response to a live token query. :param str resource_uri: The identifier of the resource. """ __args__ = dict() __args__['resourceUri'] ...
22,585
def load_subspace_vectors(embd, subspace_words): """Loads all word vectors for the particular subspace in the list of words as a matrix Arguments embd : Dictonary of word-to-embedding for all words subspace_words : List of words representing a particular subspace Returns subspace_e...
22,586
def _safe_filename(filename): """ Generates a safe filename that is unlikely to collide with existing objects in Google Cloud Storage. ``filename.ext`` is transformed into ``filename-YYYY-MM-DD-HHMMSS.ext`` """ filename = secure_filename(filename) date = datetime.datetime.utcnow().strftime("...
22,587
def get_raw(contents: List[str]) -> Tuple[sections.Raw, List[str]]: """Parse the \\*RAW section""" raw_dict, rest = get_section(contents, "raw") remarks = raw_dict[REMARKS] if REMARKS in raw_dict else "" raw_info = sections.Raw( remarks=remarks, raw=raw_dict, ) return raw_info, r...
22,588
async def add(ctx): """Country Name Add a player to the game as country""" command, country, player = ctx.message.content.split(" ") if country in Country.__members__: member = discord.utils.find(lambda m: m.name == player, ctx.message.channel.server.members) if member != None: ...
22,589
def requireIsExisting( path ): """ Throws an AssertionError if 'path' does not exist. """ requireIsTextNonEmpty( path ) requireMsg( isExisting( path ), path + ": No such file or directory" )
22,590
def transfers_from_stops( stops, stop_times, transfer_type=2, trips=False, links_from_stop_times_kwargs={'max_shortcut': False, 'stop_id': 'stop_id'}, euclidean_kwargs={'latitude': 'stop_lat', 'longitude': 'stop_lon'}, seek_traffic_redundant_paths=True, seek_transfer_redundant_paths=True...
22,591
def export_retinanet(args: argparse.Namespace) -> None: """ Loads, converts and export retinanet as tf serving model. """ weights_path = args.weights version = args.version num_classes = args.num_classes export_path = args.output_path backbone_name = args.backbone_name anchors_file = args.an...
22,592
def PySequence_ITEM(space, w_obj, i): """Return the ith element of o or NULL on failure. Macro form of PySequence_GetItem() but without checking that PySequence_Check(o)() is true and without adjustment for negative indices. This function used an int type for i. This might require changes in yo...
22,593
def run_model_pipeline(process_number, uuid_list): """ Run the modeling stage of the pipeline. """ for uuid in uuid_list: if uuid is None: continue try: run_model_pipeline_for_user(uuid) except Exception as e: print "dang flabbit failed on error %s" % e
22,594
def decode_hex(data): """Decodes a hex encoded string into raw bytes.""" try: return codecs.decode(data, 'hex_codec') except binascii.Error: raise TypeError()
22,595
def network(ipaddress, info_type): """Show IP (IPv4) BGP network""" command = 'sudo vtysh -c "show ip bgp' if ipaddress is not None: if '/' in ipaddress: # For network prefixes then this all info_type(s) are available pass else: # For an ipaddress then check...
22,596
def crop_bbox_by_coords(bbox, crop_coords, crop_height, crop_width, rows, cols): """Crop a bounding box using the provided coordinates of bottom-left and top-right corners in pixels and the required height and width of the crop. """ bbox = denormalize_bbox(bbox, rows, cols) x_min, y_min, x_max, y_ma...
22,597
def computeDateGranularity(ldf): """ Given a ldf, inspects temporal column and finds out the granularity of dates. Example ---------- ['2018-01-01', '2019-01-02', '2018-01-03'] -> "day" ['2018-01-01', '2019-02-01', '2018-03-01'] -> "month" ['2018-01-01', '2019-01-01', '2020-01-01'] -> "year" Parameters -----...
22,598
def next_pending_location(user_id: int, current_coords: Optional[Tuple[int, int]] = None) -> Optional[Tuple[int, int]]: """ Retrieves the next pending stone's coordinates. If current_coords is not specified (or is not pending), retrieves the longest-pending stone's coordinates. The order for determining whi...
22,599