content
stringlengths
22
815k
id
int64
0
4.91M
def run() -> None: """Run the sync command.""" if not util.jotter_project_exists(): print("Unable to sync, the current folder is not a jotter project.") raise SystemExit(1) repo = git.Repo(path=".") if "origin" not in repo.remotes: print("Unable to sync, repo did not have remote...
40,100
def get_classifier_bb(defences=None): """ Standard BlackBox classifier for unit testing :return: BlackBoxClassifier """ from art.classifiers import BlackBoxClassifier from art.utils import to_categorical # define blackbox classifier def predict(x): with open(os.path.join(os.pat...
40,101
def tracks(track): """ Check if the submitted RGTs are valid Arguments --------- track: ICESat-2 reference ground track (RGT) """ #-- string length of RGTs in granules track_length = 4 #-- total number of ICESat-2 satellite RGTs is 1387 all_tracks = [str(tr + 1).zfill(track_leng...
40,102
def submit_spark_job(project_id, region, cluster_name, job_id_output_path, main_jar_file_uri=None, main_class=None, args=[], spark_job={}, job={}, wait_interval=30): """Submits a Cloud Dataproc job for running Apache Spark applications on YARN. Args: project_id (str): Required. The ID of t...
40,103
def run(): """Main entry point to execute this program.""" sleep_enabled = _sleep_enabled() try: File.logger().info('%s - Awake: %s', clock.timestamp(), machine.wake_reason()) rainfall = False next_wake = config.RTC_ALARM battery_volts = _battery_vo...
40,104
def scan_2(contexts=["HElib_Fp","SEAL"]): """ set levels set to 4, see where we go wrong """ for gate in ["ADD","SUBTRACT","MULTIPLY","SELECT","NEGATE"]: for input_type in ["bool","uint8_t","int8_t","uint16_t","int16_t","uint32_t","int32_t"]: for d in range(1,9): for ...
40,105
def load_pickle(f): """load pickle file and generate dictionary :param f: absolute filepath to CSC library pickle files :return: dictionary object (Pandas) """ with open(f, 'rb') as infile: pickle_dataframe = pl.load(infile,encoding='latin1') try: pickle_dictionary = p...
40,106
def get_filter_ids(id_query): """Parses the `id` filter paramter from the url query. """ if id_query is None: return None filter_ids = id_query.split(',') for filter_id in filter_ids: validate_id(filter_id) return filter_ids
40,107
def random_sampling(predictions, number): """ This method will return us the next values that we need to labelise for our training with a random prioritisation Args: predictions : A matrix of probabilities with all the predictions for the unlabelled da...
40,108
def natsort_key_icase(s: str) -> str: """Split string to numeric and non-numeric fragments.""" return natsort_key(s.lower())
40,109
def write_empty_datastore(datastore_json): """ Generate an empty datastore JSON if required by the tool contract interface but we have no sub-reports to save. """ if datastore_json is not None: datastore = DataStore([]) datastore.write_json(datastore_json) log.info("Wrote emp...
40,110
def model_fn_builder(bert_config, init_checkpoint, learning_rate, num_train_steps, num_warmup_steps, use_tpu, use_one_hot_embeddings): """Returns `model_fn` closure for TPUEstimator.""" def model_fn(features, labels, mode, params): # pylint: disable=unused-argument ""...
40,111
def test_peek_on_deque(): """Test peek on deque.""" test_deque = Deque(TEST_DEQUE_DATA) peek_tail_data = test_deque.peek() assert peek_tail_data == test_deque.dll.tail.data
40,112
def datetime_to_gps_format(t): """ Converts from a datetime to week number and time of week format. NOTE: This does NOT convert between utc and gps time. The result will still be in gps time (so will be off by some number of leap seconds). Parameters ---------- t : np.datetime64, pd.Ti...
40,113
def view(jinja_environment: Environment, name: str, *args, **kwargs): """ Returns a Response object with HTML obtained from synchronous rendering. Use this when `enable_async` is set to False when calling `use_templates`. """ return get_response( render_template( jinja_environme...
40,114
def create_preprocess_fn( vocab: List[str], num_oov_buckets: int, client_batch_size: int, client_epochs_per_round: int, max_sequence_length: int, max_elements_per_client: int, max_shuffle_buffer_size: int = 10000) -> tff.Computation: """Creates a preprocessing functions for Stack Overflow ...
40,115
def SetPlayerSecret(request, callback, customData = None, extraHeaders = None): """ Sets or resets the player's secret. Player secrets are used to sign API requests. https://docs.microsoft.com/rest/api/playfab/admin/authentication/setplayersecret """ if not PlayFabSettings.DeveloperSecretKey: ...
40,116
def get_slope_aspect(dem, get_aspect=True): """ Return the instantaneous slope and aspect (if get_aspect) for dem. Both values derived using NumPy's gradient method by methods from: Ritter, Paul. "A vector-based slope and aspect generation algorithm." Photogrammetric Engineering and Remote Sensing...
40,117
def get_element_parts( original_list: list, splitter_character: str, split_index: int ) -> list: """ Split all elements of the passed list on the passed splitter_character. Return the element at the passed index. Parameters ---------- original_list : list List of strings to be spli...
40,118
def download(tickers: list, start: Union[str, int] = None, end: Union[str, int] = None, interval: str = "1d") -> dict: """ Download historical data for tickers in the list. Parameters ---------- tickers: list Tickers for which to download historical information. start: str or int ...
40,119
def logsumexp_masked(a, mask): """Returns row-wise masked log sum exp of a. Uses the following trick for numeric stability: log(sum(exp(x))) == log(sum(exp(x - max(x)))) + max(x) Args: a: 2D tensor. mask: 2D tensor. """ mask = tf.cast(mask, a.dtype) a_max = tf.math.reduce_max(a * mask, axis=1, k...
40,120
def test_tag_release(uni_repo): """Make sure we can tag a test release and a real release.""" commit_repo() retval, _stdout, _stderr = run_in_sandbox('python .multipackage/scripts/tag_release.py my_package -t -y -f -n') assert retval == 0 retval, _stdout, _stderr = run_in_sandbox('python .multipa...
40,121
def mutaprop_class(display_name, gui_id=None, gui_major_version=0, gui_minor_version=0): """ Class-level decorator. It is required for classes whose instances should be visible for the Mutaprop UI manager. :param display_name: Class name/description to be accessible by the UI API. ...
40,122
def preprocess2(data: list, max_length: int, test_data: bool): """ 입력을 받아서 딥러닝 모델이 학습 가능한 포맷으로 변경하는 함수입니다. 기본 제공 알고리즘은 char2vec이며, 기본 모델이 MLP이기 때문에, 입력 값의 크기를 모두 고정한 벡터를 리턴합니다. 문자열의 길이가 고정값보다 길면 긴 부분을 제거하고, 짧으면 0으로 채웁니다. :param data: 문자열 리스트 ([문자열1, 문자열2, ...]) :param max_length: 문자열의 최대 길이 ...
40,123
def create_inference_metadata(object_type, boundary_image, boundary_world): """ Create a metadata of **each** detected object :param object_type: Type of the object | int :param boundary: Boundary of the object in GCS - shape: 2(x, y) x points | np.array :return: JSON object of each detected object ...
40,124
def add_nodetype_operation(name, node_type, aten=True): """ Add a graph operation to a specific NodeType. |br| Adding all possible ONNX/ATen graph operations to our list is not feasible, and thus we test our algorithms only with the models in this library. If you get the following error, whilst generat...
40,125
def ex5(): """Values coming in from users will be strings, ensure that you convert them to numbers before doing the math Keep the inputs/outputs separate from doing the calculations Generate a single output statement with appropriate line breaks""" SimpleMath(lambda prompt: int(input(prompt))).repo...
40,126
def noauth_filter_factory(global_conf, forged_roles): """Create a NoAuth paste deploy filter :param forged_roles: A space seperated list for roles to forge on requests """ forged_roles = forged_roles.split() def filter(app): return NoAuthFilter(app, forged_roles) return filter
40,127
def parse_line_protocol_stat_key(key: str) -> Tuple[str, Dict[str, str]]: """Parseline protocolish key to stat prefix and key. Examples: SNMP_WORKER;hostname=abc.com,worker=snmp-mti will become: ("SNMP_WORKER", {"hostname": "abc.com", "worker": "snmp-mti"}) """ try: pr...
40,128
def test_add_prefix_validation(): """ Task 'add_prefix' options should be correctly validated """ container = TaskMaster() with pytest.raises(TaskValidationError) as excinfo: validate_task_options( "add_prefix", container.task_add_prefix.required, ) asse...
40,129
def negative_log_partial_likelihood(censor, risk): """Return the negative log-partial likelihood of the prediction y_true contains the survival time risk is the risk output from the neural network censor is the vector of inputs that are censored regularization is the regularization constant (not use...
40,130
def approx_equal(x, y, tol=1e-12, rel=1e-7): """approx_equal(x, y [, tol [, rel]]) => True|False Return True if numbers x and y are approximately equal, to within some margin of error, otherwise return False. Numbers which compare equal will also compare approximately equal. x is approximately equ...
40,131
def get_deleted_filename(absolute): """ Returns the name of the deleted file referenced by the AUFS whiteout file at the given path or None if the file path does not reference a whiteout file. """ filename = os.path.basename(absolute) if not filename.startswith(AUFS_WHITEOUT): return Non...
40,132
def add_strategy(name, implementation): """Add a workflow strategy Used by different hosting environments to add new workflows """ log.info('Adding %s fixer strategy', name) workflow_strategies[name] = implementation
40,133
def process_placement_opt(request_json, policies, osdf_config): """Perform the work for placement optimization (e.g. call SDC artifact and make conductor request) NOTE: there is scope to make the requests to policy asynchronous to speed up overall performance :param request_json: json content from original...
40,134
def parallelize_parameter(func, iterable, respective=False, **kwargs): """Decrease your output size of your function""" import multiprocessing maxx = multiprocessing.cpu_count() n_jobs = maxx - 2 batch_size = [5, 10, 25, 50, 100] iterable2 = [] for i, j in enumerate(iterable): iter...
40,135
def get_latest_enabled_scripts(): """The ``/scripts/latest/enabled`` endpoint requires authentication. It is used to get latest enabled scripts for all services submitted by all teams including master/organizer where the team id will be Null. The JSON response is: { "scripts" : [L...
40,136
def hanning(shape, dtype=np.float, device=backend.cpu_device): """Create multi-dimensional hanning window. Args: shape (tuple of ints): Output shape. dtype (Dtype): Output data-type. device (Device): Output device. Returns: array: hanning filter. """ device = backe...
40,137
def get_playblast_compressions(playblast_format): """ Returns a list of supported compressions for DCC playblast :param playblast_format: str :return: list(str) """ raise NotImplementedError()
40,138
def bitwise_and(x1: Union[ivy.Array, ivy.NativeArray], x2: Union[ivy.Array, ivy.NativeArray]) -> ivy.Array: """ Computes the bitwise AND of the underlying binary representation of each element x1_i of the input array x1 with the respective element x2_i of the input array x2. :param x1: first input arra...
40,139
def view_intro_home_menu(): """ Displays an introduction to the home menu. """ print("\n ### Menu Principal ### \n" "\n" "-- Que souhaitez vous réaliser ? --\n")
40,140
def init_database(use_mysql=False, dbname="sbs"): """ initialize database if use_mysql is true, use environment variables to set it up otherwise default to sqlite """ #engine = create_engine('sqlite:///:memory:', echo=False) # "mysql+mysqldb://{user}:{password}@{host}:{port}/{dbname}" if...
40,141
def test_forward_Alexnet(): """Alexnet""" data = np.random.randint(0, 256, size=(1, 3, 227, 227)).astype(np.float32) _test_alexnet(data)
40,142
def add_without_punctuation(line, punctuation): """Returns the line cleaned of punctuation. Param: line (unicode) Returns: False if there are not any punctuation Corrected line """ cleaned_line = line.translate(str.maketrans('', '', punctuation)) if line != cleaned_line...
40,143
def find_word_helper(xy: tuple, xy_lst: list, boggle_dic: dict, word: str, word_lst: list, dictionary: list): """ This function will find all possible arrangements of the word using recursion algorithm. """ # Chose the next coordinate (present in x and y axis). for i in range(-1, 2, 1): for j in range(-1, 2, 1):...
40,144
def test_subtitle_upload_serializer(): """ Test for the VideoSubtitleUploadSerializer """ input_data = { "video": "9734262d30144b8cbedb94a872158581", "language": "en", "filename": "foo.vtt", } serializer = serializers.VideoSubtitleUploadSerializer(data=input_data) assert ser...
40,145
def there_is_zero( f: Callable[[float], float], head: float, tail: float, subint: int ) -> bool: """ Checks if the function has a zero in [head, tail], looking at subint subintervals """ length = tail - head step = length / subint t = head a = f(head) for i in range(1, subint + 1...
40,146
def target_distribution_gen(name, parameter1, parameter2): """ parameter1 is usually a parameter of distribution (not always relevant). parameter2 is usually noise.""" if name=="Fritz-visibility": """ parameter2 is the visibility""" ids = np.zeros((4,4,4)).astype(str) p = np.zeros((4,4,...
40,147
def module_code( sexpr, name: str = "<unknown>", filename: str = "<unknown>", lineno: int = 1, doc: str = "", ): """Create a module's code object from given metadata and s-expression. """ module_builder = Builder( ScopeSolver.outermost(), [], SharedState(doc, lineno, filename) ...
40,148
def acknowledgements(): """Provides acknowlegements for the JRO instruments and experiments Returns ------- ackn : str String providing acknowledgement text for studies using JRO data """ ackn = ' '.join(["The Jicamarca Radio Observatory is a facility of the", "Ins...
40,149
def list_vmachines(vdc): """ Returns: list: vmachines info """ return vdc.to_dict()["vmachines"]
40,150
def reflection_matrix(v): """ The reflection transformation about a plane with normal vector `v`. """ n = len(v) v = np.array(v)[np.newaxis] return np.eye(n) - 2 * np.dot(v.T, v)
40,151
def log_level(level): """ Setup the root logger for the script """ return { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, }.get(level, logging.INFO)
40,152
def no_overwrite(env_var, env_val): """ Do not overwrite ENV VAR if it exists """ check_for = os.environ.get(env_var) if check_for: # print("%s already set" % env_var) return else: # Not set os.environ.setdefault(env_var, env_val) # print("%s set to %s" % (env_var...
40,153
def __pauli_prep_gates(circuit, qreg, op): """ Add state preparation gates to a circuit. """ bas, proj = op if bas not in ['X', 'Y', 'Z']: raise QISKitError("There's no X, Y or Z basis for this Pauli " "preparation") if bas == "X": if proj == 1: ...
40,154
def gradient_fill(ax, data, color): """ Gradient fill :param ax: Axis :param data: pandas Series :param color: color """ line, = ax.plot(data, linewidth=0.7, color=color) # From https://stackoverflow.com/questions/29321835/is-it-possible-to-get-color-gradients- # under-cu...
40,155
def validate_data_empty(_dict_: dict, strict: bool, suppress_warning: bool) -> None: """ Raises exception or warning if _dict_ is not empty. """ if len(_dict_) != 0: if strict: raise ValueError( 'Extra keys unused \'{}\' '.format(_dict_) ) elif suppress_wa...
40,156
def is_valid_furl_or_file(furl_or_file): """Validate a FURL or a FURL file. If ``furl_or_file`` looks like a file, we simply make sure its directory exists and that it has a ``.furl`` file extension. We don't try to see if the FURL file exists or to read its contents. This is useful for cases wher...
40,157
def string(_instance: Any, attribute: Attribute, value: str) -> None: # type: ignore """attrs validator to ensure that a string is non-empty.""" # Annoyingly, due to some quirk in the CattrConverter, we end up with "None" rather than None for strings set to JSON null # As a result, we need to prevent "None...
40,158
def stride(input_data, input_labels): """ Takes an input waterfall visibility with labels and strides across frequency, producing (Nchan - 64)/S new waterfalls to be folded. """ spw_hw = 32 # spectral window half width nchans = 1024 fold = nchans / (2 * spw_hw) sample_spws = random.samp...
40,159
def test_histograms(): """Test `pyabc.visualization.plot_histogram_1d/2d/matrix`""" # 1d pyabc.visualization.plot_histogram_1d( histories[0], 'p0', bins=20, xmin=limits['p0'][0], xmax=limits['p0'][1], size=(5, 5), refval=p_true, ) # 2d pyab...
40,160
def abspaths(paths): """ an wrapper function of os.path.abspath to process mutliple paths. """ return [os.path.abspath(p) for p in paths]
40,161
def chiF_sparseAD(model, k): """ Compute chi_F using the DominantSparseSymeig primitive, where the matrix to be diagonalized is "sparse" and represented as a function. """ import DominantSparseEigenAD.Lanczos as lanczos lanczos.setDominantSparseSymeig(model.H, model.Hadjoint_to_gadjoint) ...
40,162
def sum_digits(y): """Sum all the digits of y. >>> sum_digits(10) # 1 + 0 = 1 1 >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12 12 >>> sum_digits(1234567890) 45 >>> a = sum_digits(123) # make sure that you are using return rather than print >>> a 6 """ "*** YOUR CODE HERE ***"...
40,163
def leastsq(error_func, x0, *args, **options): """Find the parameters that yield the best fit for the data. `x0` can be a sequence, array, Series, or Params Positional arguments are passed along to `error_func`. Keyword arguments are passed to `scipy.optimize.leastsq` error_func: function that c...
40,164
def atomic_token_partition(value): """Partition given value on a token that appears resolvable(contains no sub tokens). Returns in a tuple: (before_token, token, after_token). Returned token includes token syntax. If no tokens are found, returned tuple contains None in all values. :param value: tex...
40,165
def send_message_from(message, filename): """send a text message with """ from telegram import Bot, ParseMode host = socket.gethostname() message = f'*{message}*' + f'\n_{host}:{filename}_' bot = Bot(token=get_bot_token()) bot.send_message(chat_id=get_chat_id(), text=message, parse_mode=ParseM...
40,166
def add_color_bar(img, space, cv): """ args: img: (ndarray) in [img_rows, img_cols, channels], dtype as unit8 space: (int) pixels of space cv: (int) color value in [0, 255] return: tmp_img: (ndarray) processed img """ assert len(img.shape) == 3, "img should be 3D" ...
40,167
def get_cli_body_ssh(command, response, module): """Get response for when transport=cli. This is kind of a hack and mainly needed because these modules were originally written for NX-API. And not every command supports "| json" when using cli/ssh. As such, we assume if | json returns an XML string, i...
40,168
def zero_at(pos, size=8): """ Create a size-bit int which only has one '0' bit at specific position. :param int pos: Position of '0' bit. :param int size: Length of value by bit. :rtype: int """ assert 0 <= pos < size return 2**size - 2**(size - pos - 1) - 1
40,169
def get_authz_token(request, user=None, access_token=None): """Construct AuthzToken instance from session; refresh token if needed.""" if access_token is not None: return _create_authz_token(request, user=user, access_token=access_token) elif is_request_access_token(request): return _create_...
40,170
def get_bert_model(): """ Load uncased HuggingFace model. """ bert_model = torch.hub.load('huggingface/pytorch-transformers', 'model', 'bert-base-uncased') return bert_model
40,171
def delete_repo_cli(api_client, repo_id, path): """ Deletes the repo. """ id_from_param_or_path = (repo_id if repo_id is not None else ReposApi(api_client).get_repo_id(path)) content = ReposApi(api_client).delete(id_from_param_or_path) click.echo(pretty_format(conten...
40,172
def get_bitseq_estimates( config, isoform_strategy, bitseq_id_field='transcript_id', strings_to_remove=['.cds-only', '.merged']): """ Load the bitseq abundance estimates into a single long data frame. Parameters ---------- config: dict-like The configuration for ...
40,173
def retrieve_folder(local_path, dropbox_path, OAuth_token): """ downloads files from a given dropbox's folder to a given local path :param local_path: str path to be saved the files :param dropbox_path: str dropbox path :param OAuth_token: str authentication token needed to establish a remote connec...
40,174
def na_layout(na_layout_path: Path) -> ParadigmLayout: """ Returns the parsed NA layout. """ with na_layout_path.open(encoding="UTF-8") as layout_file: return ParadigmLayout.load(layout_file)
40,175
def mean_allcnnc(): """The all convolution layer implementation of torch.mean().""" # TODO implement pre forward hook to adapt to arbitary image size for other data sets than cifar100 return nn.Sequential( nn.AvgPool2d(kernel_size=(6, 6)), flatten() )
40,176
def load_atomic_data_for_training(in_file, categories, tokenizer, max_input_length, max_output_length): """ Loads an ATOMIC dataset file and :param in_file: CSV ATOMIC file :param categories: ATOMIC category list :param tokenizer: LM tokenizer :return: a list of tuples """ examples = loa...
40,177
def test_lock_inplace_false(): """Creating a locked and unlocked copies.""" flex = FlexDict(DATA) flex_locked = flex.lock(inplace=False) flex_unlocked = flex_locked.unlock(inplace=False) assert flex.locked is False assert flex_locked.locked is True assert flex_unlocked.locked is False
40,178
def md5s_loaded(func): """Decorator which automatically calls load_md5s.""" def newfunc(self, *args, **kwargs): if self.md5_map == None: self.load_md5s() return func(self, *args, **kwargs) return newfunc
40,179
def is_dap_message(message: str) -> bool: """Checks if a message contains information about some neighbour DAP.""" if "DAP" in message: return True return False
40,180
def PhotoMetricDistortion( img, brightness_delta=32, contrast_range=(0.5, 1.5), saturation_range=(0.5, 1.5), hue_delta=18): """Apply photometric distortion to image sequentially, every dictprocessation is applied with a probability of 0.5. The position of random contrast ...
40,181
def delete_files(filenames): """Delete files in a list if they exists.""" for f in filenames: if os.path.isfile(f): os.remove(f) print('FILE DELETED: ', f) else: print('FILE NOT FOUND: ', f)
40,182
def sharded_adafactor( learning_rate_fn: optax.Schedule, weight_decay: Optional[float] = None, layerwise_adaptation: bool = False, decay_method: str = '', decay_adam: float = 0., decay_pow: float = 0., beta1: float = 0., clipping_threshold: float = 1., factored: bool = True, epsi...
40,183
def main(sat_fold, coords_file, out_fold, inbands, slstr_res, sat_platform): """Sentinel-3 band extraction. Extract a specified list of bands for all images contained in a specified folder at given coordinates, specified in a csv file. Note, the images have to be unzipped raw S3 OLCI images. For each ...
40,184
def make_game(): """Builds and returns an Apprehend game.""" return ascii_art.ascii_art_to_game( GAME_ART, what_lies_beneath=' ', sprites={'P': PlayerSprite, 'b': BallSprite}, update_schedule=['b', 'P'],nb_action=2)
40,185
def get_system_memory(): """Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes. """ # Try to accurately figure out the memory limit if we are in a docker # container. Note that this file is not specific to Docker and its value is # oft...
40,186
def process_makefile( data: Any, specification: Any, path: Tuple[str, ...] = (), apply_defaults: bool = True, ) -> Any: """Validates a makefile and applies defaults to missing keys. Note that that default values are deep-copied before being set. """ if isinstance(specification, WithoutD...
40,187
def load_fashion(n_data=70000): """Fetches the fashion MNIST dataset and returns its desired subset. Args: n_data (int, optional): The size of the wanted subset. Defaults to 70000. Returns: tuple: The dataset, the labels of elements, the names of categories and the name of the dataset. ...
40,188
def matplotlib_scraper_multi(block, block_vars, gallery_conf, **kwargs): """Scrape Matplotlib images, but with both high and low-def... Parameters ---------- block : tuple A tuple containing the (label, content, line_number) of the block. block_vars : dict Dict of block variables. ...
40,189
def add_countdown_ago(date, event, events_dates_per_event): """ Given a date and an even, compute the number of days since the previous occurence of this events within events_dates_per_event """ countdown = [] for special_date in events_dates_per_event[event]: date_count_down = (special_...
40,190
def get_groups_from_json(json_definitions): """Return a dict of tango.Group objects matching the JSON definitions. Extracts the definitions of groups of devices and builds up matching tango.Group objects. Some minimal validation is done - if the definition contains nothing then None is returned, other...
40,191
def _get_indexed_role(dep): """Return the function (governor/dependent) and role based on the dependency relation type.""" gram_relation = dep['@type'][0:5] if gram_relation in ["conj", "conj_"]: return (-1, 'conj') (function, role) = _relation_map[gram_relation] return (_iminus_one...
40,192
def to_file(encoded_data, filename): """Write encoded data to the binary file. Args: encoded_data: A list of two-element tuples of int and str. filename: Name of the destination file. """ required_bytes = math.ceil( len(bin(max([i[0] for i in encoded_data]))[2:]) / 8) bytes_...
40,193
def write(file, segments, image_path=None): """ write the segments (belonging to image_path) to the file in JSON format segments can be one of a number of things: 1) a simple list of pts 2) a list of 2-element tuples (label, pts) 3) a list of 3-element tuples (lab...
40,194
def aug_op_mul_col(aug_input: Tensor, mul: float) -> Tensor: """ multiply each pixel :param aug_input: the tensor to augment :param mul: the multiplication factor :return: the augmented tensor """ input_tensor = aug_input * mul input_tensor = aug_op_clip(input_tensor, clip=(0, 1)) re...
40,195
def example3(path: str): """Planetary orbit""" print(f"\n{Col.TITL}{' Example 3 ':-^79}{Col.RES}\n") if not path: path = "qr_data/ex3.txt" file = open(path, "r") ls = file.readlines() # Read input data from `file` m = int(ls[0].replace("\n", "")) data = np.zeros((m, 2)) for ...
40,196
def drones_byDroneId_patch(droneId): """ Update the information on a specific drone It is handler for PATCH /drones/<droneId> """ return handlers.drones_byDroneId_patchHandler(droneId)
40,197
def main(): """Print the length of the longest common substing of two stings""" s1 = input().strip() s2 = input().strip() print(lcs(s1, s2))
40,198
def load_drop_columns(df, targets, file): """ Loads a dataframe with only a subset of the columns TODO: we probably need to delete this because this exists: df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields) #https://stackoverflow.com/questions/26063231/read-specific-columns-with-pa...
40,199