content
stringlengths
22
815k
id
int64
0
4.91M
def create(): """Create new event.""" form = CreateEventForm(request.form, csrf_enabled=False) print ("form received") if form.validate_on_submit(): print ("valid") RecEvent.create(title=form.title.data, date=form.date.data, time=form.time.data, location=form.loca...
72,500
def get_version(): """ Obtain the version of the ITU-R P.1853 recommendation currently being used. Returns ------- version: int Version currently being used. """ global __model return __model.__version__
72,501
def read_version(version_file_name): """ Reads the package version from the supplied file """ version_file = open(os.path.join(version_file_name)).read() return re.search("__version__ = ['\"]([^'\"]+)['\"]", version_file).group(1)
72,502
def find_ue_ip(imsi: str): """ Finds the UE IP address corresponding to the IMSI """ cmd = ["mobility_cli.py", "get_subscriber_table"] output = subprocess.check_output(cmd) output_str = str(output, "utf-8").strip() pattern = "IMSI.*?" + imsi + ".*?([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1...
72,503
def print_mathml(expr): """ Print's a pretty representation of the MathML code for expr >>> from sympy import * >>> from sympy.printing.mathml import print_mathml >>> x = Symbol('x') >>> print_mathml(x+1) #doctest: +NORMALIZE_WHITESPACE <apply> <plus/> <cn> 1...
72,504
def get_args(): """Gets parsed command-line arguments. Returns: Parsed command-line arguments. """ parser = argparse.ArgumentParser(description="plays Ms. Pac-Man") parser.add_argument("--no-learn", default=False, action="store_true", help="play without training") ...
72,505
def _random_bernoulli(shape, probs, dtype=tf.int32, seed=None, name=None): """Returns samples from a Bernoulli distribution.""" with tf.name_scope(name, "random_bernoulli", [shape, probs]): probs = tf.convert_to_tensor(probs) random_uniform = tf.random_uniform(shape, dtype=probs.dtype, seed=seed) return...
72,506
def tokenize(text): """Return tokenized form of text Parameters ---------- text : str string to be tokenized Returns ------- list tokens of string text """ # Normalize and remove punctuations and extra chars such as (, # text = re.sub(r'[^a-zA-Z0-9]'...
72,507
def ReadData(name): """ Reads data from several files. """ f = open('%s-n.txt' % name,'rt') n = string.atoi(f.readline()) f.close() gammas = [] f = open('%s-gammas.csv' % name,'rt') for row in csv.reader(f,quoting=csv.QUOTE_NONNUMERIC): gammas.extend(row) f....
72,508
def split_and_strip_without( string: str, exclude, separator_regexp: Optional[str] = None ) -> List[str]: """Split a string into items, and trim any excess spaces Any items in exclude are not in the returned list >>> split_and_strip_without('fred, was, here ', ['was']) ['fred', 'here'] """ ...
72,509
def _current_season(): """Return the current NHL season""" endpoint = "seasons/current" data = _api_request(endpoint) if data: season = data['seasons'][0]['seasonId'] return season else: raise JockBotNHLException('Unable to retrieve current NHL season')
72,510
def validity_checks(): """ Ensures the input values chosen are valid and can perform a simulation. """ if L <= 0: raise RuntimeWarning("The channel length must be a positive number.") if A <= 0: raise RuntimeWarning("The attenuation loss must be a positive number.") if ...
72,511
def test_bot_unknown_mode(mockbot, ircfactory): """Ensure modes not in PREFIX or CHANMODES trigger a WHO.""" irc = ircfactory(mockbot) irc.bot._isupport = isupport.ISupport(chanmodes=("b", "", "", "mnt", tuple())) irc.bot.modeparser.chanmodes = irc.bot.isupport.CHANMODES irc.channel_joined("#test", ...
72,512
def load_file(path: str) -> Tuple[TestCase, ...]: """Load test cases from a file. Parameters ---------- path : str File path. Returns ------- Tuple[TestCase, ...] Test cases. """ with open(path, "r") as file: return tuple( load_case(case) ...
72,513
def get_interfaces(): """ Returns a list of your computer's IP configuration: ['lo0', 'gif0', 'stf0', 'XHC20', 'en0', 'p2p0', 'awdl0', 'en1', 'bridge0', 'utun0'] """ interfaces = netifaces.interfaces() return interfaces
72,514
def clean_python_name(s): """Method to convert string to Python 2 object name. Inteded for use in dataframe column names such : i) it complies to python 2.x object name standard: (letter|'_')(letter|digit|'_') ii) my preference to use lowercase and adhere to practice ...
72,515
def broadcast_object(obj: object, src: int = 0, comm: Optional[B.BaguaSingleCommunicatorPy] = None) -> object: """Serializes and broadcasts an object from root rank to all other processes. Typical usage is to broadcast the ``optimizer.state_dict()``, for example: >>> state_dict = broadcast_object(optim...
72,516
def open_pickle_jar(directory, filename): """loads .pkl file""" return pickle.load(open(os.path.join(directory, filename), 'rb'))
72,517
def mktemp_dump(data): """Create a temporary file under the current plugin tmp directory and write data to the file. """ ftmp = tempfile.mktemp(dir=HotSOSConfig.PLUGIN_TMP_DIR) with open(ftmp, 'w') as fd: fd.write(data) return ftmp
72,518
def get_leagues_by_team(team_ids): """ https://developer.riotgames.com/api/methods#!/985/3352 Args: team_ids (str | list<str>): the team ID(s) to get leagues for Returns: dict<str, list<League>>: the team(s)' leagues """ # Can only have 10 teams max if it's a list if isinst...
72,519
def generate_asset_name (asset_id, block_index): """Create asset_name from asset_id.""" if asset_id == 0: return config.BTC elif asset_id == 1: return config.XCP if asset_id < 26**3: raise exceptions.AssetIDError('too low') if enabled('numeric_asset_names'): # Protocol change. if ...
72,520
def parse_object(tokens: Deque[Token]) -> JSONObject: """Parses an object out of JSON tokens""" obj: JSONObject = {} # special case: if tokens[0].type == 'right_brace': tokens.popleft() return obj while tokens: token = tokens.popleft() if not token.type == 'string'...
72,521
def calc_Asym_vs_emin_energies(det_df, dict_index_to_det, singles_hist_e_n, e_bin_edges_sh, bhp_nn_e, e_bin_edges, emins, emax, angle_bin_edges, plot_flag=True, show_flag = False, save_flag=True): """ Calculate Asym for variable emi...
72,522
def get_best_of_n_avg(seq, n=3): """compute the average of first n numbers in the list ``seq`` sorted in ascending order """ return sum(sorted(seq)[:n])/n
72,523
def _prep_cosim(args, **sigs): """ prepare the cosimulation environment """ # compile the verilog files with the verilog simulator files = ['../myhdl/mm_maths1.v', '../bsv/mb_maths1.v', '../bsv/mkMaths1.v', '../chisel/generated/mc_maths1.v', './tb_math...
72,524
def main(): """ Main function """ # Hyperparamters embedding_dim = 5 num_layers = 2 output_dim = 10 batch_size = 3 encoder_seq_length = 4 decoder_seq_length = 6 # Model Definition model = RNN(embedding_dim, num_layers, output_dim) # Inputs encoder_output = torch.randn(...
72,525
def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: import __builtin__ all = __builtin__.__dict__.copy() all.update(globals()) objlst = sorted(conf.layers, key=lambda x:x.__name__) for o in objlst: print "%-10s : ...
72,526
def update_optional_data(): """每天8点更新自选基金历史净值""" yesterday = dt.yesterday() records = FundHistoryNetWorth.objects.aggregate( {'$match': {'is_delete': 0}}, {"$group": {"_id": "$code", 'date': {'$max': '$date'}}} ) for rec in records: code = rec['_id'] last_day = rec...
72,527
def write_contents_to_file(changelog_obj, dir_changes_set, cli_args, output_file_path): """ Taking in a changelog object (a dict that contains a list of objects) and a set, we format and parse out the contents to a written file. Does not return anything. """ jinja_env = jinja2.Environment( ...
72,528
def py2_earth_hours_left(start_date=BITE_CREATED_DT): """Return how many hours, rounded to 2 decimals, Python 2 has left on Planet Earth (calculated from start_date)""" return round((PY2_DEATH_DT - start_date) / timedelta(hours=1), 2)
72,529
def test_basic(): """ Run a test of the fnnls implementation on the example from the Fast Nonnegative Least Squares paper by Bro and Jung """ epsilon = 0.00001 Z = np.asarray([ [73, 71, 52], [87, 74, 46], [72, 2, 7], ...
72,530
def merge_model_results(results: Dict[str, Dict[Tuple[str, int], pd.DataFrame]]) -> pd.DataFrame: """ Combine the results of running :func:`util.analyze_model` across a corpus into a single dataframe. :param results: Mapping from model name to dictionary of dataframes, one dataframe per docume...
72,531
def _float_feature(value): """Wrapper for inserting float features into Example proto.""" return tf.train.Feature(float_list=tf.train.FloatList(value=value))
72,532
def valid_bytes_128_after(valid_bytes_48_after): """ Fixture that yields a :class:`~bytes` that is 128 bits and is ordered "greater than" the result of the :func:`~valid_bytes_128_after` fixture. """ return valid_bytes_48_after + b'\0' * 10
72,533
def const_coeffs(s=0.0, py=0.0, pz=0.0, px=0.0): """ Creates coefficients for seperated tunnelling to each orbital. The energies are set to zero. """ cc = np.array([s, py, pz, px]) != 0.0 coeffs = np.empty((sum(cc),4),) ene = np.zeros(sum(cc)) if s != 0.0: coeffs[sum(cc[:1])-1] ...
72,534
def print_board(game_state): """Prints the tic tac toe board.""" for i in range(len(game_state)): row = game_state[i] print(row[0] + "|" + row[1] + "|" + row[2]) if i < 2: print("-----")
72,535
def calcIntraElectroHydrophobic(pdb, interface, depthDistances): """ Calculated possible electro interactions, excluding 1-2 and 1-3 interactions (already included in angle and bond interactions """ HYDROPHOBIC_CHARGED_CUTOFF_DISTANCE = 6 # we could have 6? Hbonds = getHbonds(pdb, pdb.nam...
72,536
def positional_encoding(position: int, d_model: int) -> tf.Tensor: """Returns the positional encoding for a given position and timestamp""" angle_rads = get_angles(np.arange(position)[:, np.newaxis], np.arange(d_model)[np.newaxis, :], d_model) #...
72,537
def add_multiple_of_row_of_square_matrix(matrix: List[List], source_row: int, k: int, target_row: int): """ add k * source_row to target_row of matrix m """ n = len(matrix) row_operator = make_identity(n) row_operator[target_row][source_row] = k return multiply_matrices(row_operator, matrix)
72,538
def shadow_mapping(cam_results, light_results, rays, ppc, light_ppc, image_shape, batch_size, fine_sampling): """ cam_result: result dictionary with `depth_*`, `opacity_*` light_result: result dictionary with `depth_*`, `opacity_*` rays: generated rays ppc: [Batch_size] Camera Poses: instance of th...
72,539
def get_panelists(): """Retrieve a list of panelists and their corresponding information""" return panelists.get_panelists(database_connection)
72,540
def count_distinct_col(curs, table_name, col='y'): """Queries to find number of distinct values of col column in table in database. Args: curs (sqlite3.Cursor): cursor to database table_name (str): name of table to query col (str): name of column to find number of distinct values fo...
72,541
def get_info(timeout_seconds=None) -> bool: """ Gets information from twitch and hands it over to parsers. Also manages any PING's sent by twitch, automatically replying with a PONG. Args: timeout_seconds: How long you'd like to wait for a response before disconnecting....
72,542
def test_calculate_distance(): """ This function will test calculate_distance and ensure that it is doing what I expect. """ #define two points r1= np.array([0,0,0]) r2= np.array([0,1,0]) #define expected value expected= 1 calculated_distance= molecool.calculate_distance...
72,543
def test_is_own_subscription_permission( mocker, logged_in_username, req_body_username, url_kwarg_username, expected ): """ Test that IsOwnSubscriptionOrAdminPermission returns True if the user is adding/deleting their own resource """ view = mocker.Mock(kwargs={"subscriber_name": url_kwarg_user...
72,544
def does_file_exist(file_path: Path) -> bool: """Check for file existence.""" print(f"... Checking if file [{file_path}] exists") if os.path.isfile(file_path): print("...... File exists...") return True else: return False
72,545
def reduce_dataset_by_column_value(df, colname, values): """Returns the passed dataframe, with only the passed column values""" col_ids = df[colname].unique() nvals = len(col_ids) # Reduce dataset reduced = df.loc[df['locus_tag'].isin(values)] # create indices and values for probes new_ids...
72,546
def limitsSql(pageToken=0, pageSize=None): """ Takes parsed pagination data, spits out equivalent SQL 'limit' statement. :param pageToken: starting row position, can be an int or string containing an int :param pageSize: number of records requested for this transaciton, can be an int or...
72,547
def maybe_download_sbs(): """Download the SBS dataset to its expected location if necessary""" files = [] for channel in 1, 2: idx = 1 for row in "ABCDEFGH": for col in range(1, 13): files.append("Channel%d-%02d-%s-%02d.tif" % (channel, idx, row, col)) ...
72,548
def test_login_view_invalid_credentials(hass, cloud_client): """Test logging in with invalid credentials.""" with patch.object(cloud_api, 'async_login', MagicMock(side_effect=cloud_api.Unauthenticated)): req = yield from cloud_client.post('/api/cloud/login', json={ 'use...
72,549
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode): """ Train the GAN :param epoch_count: Number of epochs :param batch_size: Batch Size :param z_dim: Z dimension :param learning_rate: Learning Rate :param beta1: The exponential decay ra...
72,550
def test_valid_application(db_parameters): """Valid application name.""" application = 'Special_Client' cnx = snowflake.connector.connect( user=db_parameters['user'], password=db_parameters['password'], host=db_parameters['host'], port=db_parameters['port'], account=d...
72,551
def split(df): """ Splits the given dataframe into a 8/2 split for training and testing :param df:the dataframe you want to split :return: """ training, test = train_test_split(df, test_size=0.2, random_state=42) train, val = train_test_split(training, test_size=0.2, random_state=42) re...
72,552
def test_wait_within_timeout(): """Test that we can wait for a job terminating before timeout. """ i = 0 def cond(): nonlocal i j = i i += 1 return j job = InstrJob(cond, 0) assert job.wait_for_completion(refresh_time=0.01) assert i == 2
72,553
def get_lm_corpus(datadir: str, dataset: str, use_bpe=False, max_size=None, valid_custom=None) -> Corpus: """Factory method for Corpus. Arguments: max_size: . use_bpe: OpenAI's BPE encoding datadir: Where does the data live? dataset: eg 'wt103' which tells the Corpus how to pars...
72,554
def test_env_var_is_set(run_and_terminate_server): """Test the AIIDA_PROFILE env var is set The issue with this test, is that the set "AIIDA_PROFILE" environment variable in the click command cannot be retrieved from the test functions' `os.environ`. Hence, we test it by making sure the current AiiDA p...
72,555
def user_prompt(question, default = "yes"): """Asks the user a yes/no question Args: question (str): Question for the user """ prompt = '[Y/n] ' valid = {"yes": True, "y": True, "no": False, "n": False} while True: sys.stdout.write(question + " " + prompt) choice = inpu...
72,556
def test_plo_single(tree): """No children.""" k = K() k.insert(1) assert plo(k) == '1'
72,557
def scrape_answers( contentfile, delay_min=1, delay_max=3, start=0, end=10000, folder=None ): """ Given a manually saved Quora content page (see "answers_from_quora_html()" for details), convert them all to markdown in the current folder using auto-generated names based on the question names. ...
72,558
def main(params): """ main entry point :param dict params: """ # swap according dataset type if params['type'] == 'synth': experiments_synthetic() elif params['type'] == 'real': experiments_real() # plt.show()
72,559
def download_data(force_download=False): """Downloads the data :param bool force_download: If true, overwrites a previously cached file :rtype: str """ if os.path.exists(DATA_PATH) and not force_download: log.info('using cached data at %s', DATA_PATH) else: log.info('downloading...
72,560
def module_method(fn): """Decorates a function as a module method. The `module_method` allows modules to have multiple methods that make use of the modules parameters. Example:: class MyLinearModule(nn.Module): def apply(self, x, features, kernel_init): kernel = self.param('kernel', (x.shap...
72,561
def sa_middleware(key: str = SA_DEFAULT_KEY) -> THandler: """SQLAlchemy asynchronous middleware factory. :param key: key of SQLAlchemy binding. Has default. """ @middleware async def sa_middleware_( request: Request, handler: THandler, ) -> StreamResponse: if key in req...
72,562
def unset_key( dotenv_path: Union[str, _PathLike], key_to_unset: str, quote_mode: str = "always", encoding: Optional[str] = "utf-8", ) -> Tuple[Optional[bool], str]: """ Removes a given key from the given .env If the .env path given doesn't exist, fails If the given key doesn't exist in...
72,563
def update_bot_max_safety_orders( thebot, org_base_order, org_safety_order, new_max_safety_orders ): """Update bot with new max safety orders and old bo/so values.""" bot_name = thebot["name"] base_order_volume = float(thebot["base_order_volume"]) safety_order_volume = float(thebot["safety_order_vo...
72,564
def generate_working_dir(working_dir_base): """ Creates a unique working directory to combat job multitenancy :param working_dir_base: base working directory :return: a unique subfolder in working_dir_base with a uuid """ working_dir = os.path.join(working_dir_base, str(uuid.uuid4())) try: ...
72,565
def save_pickle(X, path): """ Save a pickle object in the location given by path. Parameters ---------- X : pickle object Object to be saved. path : str Path to pickle file. """ with open(path, 'wb') as f: pickle.dump(X, f)
72,566
def manage(command, args=''): """Dev only - a convenience""" local('{}/manage.py {} {}'.format(BASE_DIR, command, args))
72,567
def report_to_fields(report, fields=None): """ Take a single report and convert the KEY: value lines into a dict of key-value pairs. Ignore any lines that don't have a colon in them. :param report: A list of text lines. :param fields: If not None, then update an existing dict. :return: ...
72,568
def add_http_if_no_scheme(url): """Add http as the default scheme if it is missing from the url.""" match = re.match(r"^\w+://", url, flags=re.I) if not match: parts = urlparse(url) scheme = "http:" if parts.netloc else "http://" url = scheme + url return url
72,569
def _check_half_window(half_window, allow_zero=False): """ Ensures the half-window is an integer and has an appropriate value. Parameters ---------- half_window : int, optional The half-window used for the smoothing functions. Used to pad the left and right edges of the data to redu...
72,570
def deliver_dap(survey_dict: dict): """deliver a survey submission intended for DAP""" logger.info("Sending DAP submission") deliver(survey_dict, DAP)
72,571
def _create_engine_kwargs(): """Create the kwargs for the database engine. Returns: (Dict): "Engine arguments" (String): "Certificate file path" """ kwargs = { "client_encoding": "utf8", "pool_size": Config.SQLALCHEMY_POOL_SIZE, } cert_file = "/etc/ssl/certs/ser...
72,572
def register_contract_contractType(config, model): """Register a contract contractType. :param config: The pyramid configuration object that will be populated. :param model: The contract model class """ contract_type = model.contractType.default or 'common' config.registry.contra...
72,573
async def get_run_controller( runId: str, task_runner: TaskRunner = Depends(get_task_runner), engine_store: EngineStore = Depends(get_engine_store), run_store: RunStore = Depends(get_run_store), ) -> RunController: """Get a RunController for the current run. This ensures that a run exists and i...
72,574
def get_pixel_ratio(img, img_path): """ Tries to read file metadata from dm file. If normal .tif images are provided instead, prompts user for the nm/pixel ratio, which can be found using the measurement tool in ImageJ or similar. For example, a scale bar of 100nm corresponds to a nm/pixel ratio of ...
72,575
def test_logout(client, admin_headers): """Test logout view""" resp = client.get('/dashboard/logout', headers=admin_headers) assert resp.status_code == 302
72,576
def gauss_kern(size, sizey=None): # smooth test """ Returns a normalized 2D gauss kernel array for convolutions """ size = int(size) if not sizey: sizey = size else: sizey = int(sizey) x, y = np.mgrid[-size:size+1, -sizey:sizey+1] g = np.exp(-(x**2/float(size)+y**2/float(sizey))...
72,577
def full_clean(string_in): """Call of my string cleaning functions in order""" #print('string_in = %s' % string_in) if string_in is None: return string_in elif type(string_in) == unicode: string_in = string_in.encode('UTF-8') elif type(string_in) not in [str, unicode]: return...
72,578
def partitioned_variable_assign(partitioned_var, new_value): """Assign op for partitioned variables. Args: partitioned_var: A partitioned tensorflow variable new_value: Value to be assigned to the variable var Returns: A tensorflow op that groups the assign ops for each of the variable slice...
72,579
def iter_ligands() -> Iterable[Ligand]: """Cp ligands in SMILES format""" if idxs is None: cp_replacements = [Ligand(func_smiles, "ModifiedLigand")] elif direction is not None and len(idxs) == 4: cp_replacements = [ Ligand( func_smiles, "ModifiedLi...
72,580
def process_df( df: pd.DataFrame, version: Optional[str] = None, skip_databases: Optional[Set[str]] = None, ) -> DGIProcessor: """Get a processor that extracted INDRA Statements from DGI content based on the given dataframe. Parameters ---------- df : pd.DataFrame A pandas DataF...
72,581
def coerce_levels(image_numpy, levels=255, method="divide", reference_image = [], reference_norm_range = [.075, 1], mask_value=0, coerce_positive=True): """ In volumes with huge outliers, the divide method will likely result in many zero values. This happens in practice quite often. TO-DO: find a b...
72,582
def merge_and_count(ll: List[int], lr: List[int]) -> (int, List[int]): """ :param ll: :param lr: :return: >>> merge_and_count([1, 2, 4], [3, 5]) (1, [1, 2, 3, 4, 5]) >>> merge_and_count([1, 2, 6], [3, 5]) (2, [1, 2, 3, 5, 6]) """ result = [] count = 0 l_ll = len(ll) ...
72,583
def get_ap_bboxes(img, model, dataset_name, verbose=False): """ Detect appearance based foreground bounding boxes on a frame by a pre-trained object detector. Args: img (ndarray): The frame to be detected. model (nn.Module): The loaded detector. dataset_name (str): The name of datase...
72,584
def syscmd(cmd: typing.Union[str, list], encoding: str=''): """ Runs a command on the system, waits for the command to finish, and then returns the text output of the command. If the command produces no text output, the command's return code will be returned instead. Optionally decode output bytestring....
72,585
def delete_user_entitlement(user, organization=None, detect=None): """Remove user from an organization. :param user: Email ID or ID of the user. :type user: str """ organization = resolve_instance(detect=detect, organization=organization) if '@' in user: user = resolve_identity_as_id(use...
72,586
def encode_string(input_string): """Encode the string value in binary using utf-8 as well as its length (valuable info when decoding later on). Length will be encoded as an unsigned short (max 65535). """ input_string_encoded = input_string.encode("utf-8") length = len(input_string_encoded)...
72,587
def resnet152(block, layers, pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(block, layers, **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet...
72,588
def preview_orig_button(): """ original preview """ # global file_in_path try: magick.display_image(file_in_path.get(), GM_or_IM) except: log.write_log("No orig picture to preview", "W")
72,589
def delete_project(project_type, project_id): """ Delete an existing project (including all configuration, data and metadata) GET: - project_type: "link" or "normalize" - project_id """ _check_project_type(project_type) # TODO: replace by _init_project if project_ty...
72,590
def task19(): """ Function that take sentence with words and numbers and calculate the number upper case and lower case letters Input: sentence Output: dictionary (e.g. {"UPPER": 3, "LOWER":65}) """ pass
72,591
def download_file(url, filename, sourceiss3bucket=None): """ Download the file from `url` and save it locally under `filename`. :rtype : bool :param url: :param filename: :param sourceiss3bucket: """ conn = None if sourceiss3bucket: bucket_name = url.split('/')[3] key_na...
72,592
def handle_args(): """Parse out arguments""" parser = argparse.ArgumentParser(description="Autogenerates a script to mock the output of a command", epilog="Example: cmdmock sensors -u") #parser.add_argument('-i', '--interactive', action='store_true', # ...
72,593
def main(): """ TODO: blur the image. """ old_img = SimpleImage("images/smiley-face.png") old_img.show() blurred_img = blur(old_img) for i in range(5): blurred_img = blur(blurred_img) blurred_img.show()
72,594
def do_start_station(): """ Retrieve initialization files and base (package) directory """ basedir= os.getcwd() sys.path.append(os.path.abspath(os.path.join(basedir, 'source'))) # print(basedir) ignorelist = [] ignorelist = ['00_dataviewer_shell.py'] i = 1 filelist = get...
72,595
def parse_vmin_vmax(container, field, vmin, vmax): """ Parse and return vmin and vmax parameters. """ field_dict = container.fields[field] if vmin is None: if 'valid_min' in field_dict: vmin = field_dict['valid_min'] else: vmin = -6 # default value if vmax is No...
72,596
def to_dict(url: str) -> dict: """Method to convert and return as dictionary.""" return json.loads(fetch_data(url))
72,597
def test_correct_comprehension( parse_tokens, assert_errors, default_options, code, mode, ): """Ensures that correct consistency does not raise a warning.""" file_tokens = parse_tokens(mode(code)) visitor = InconsistentComprehensionVisitor(default_options, file_tokens) visitor.run()...
72,598
def polygon_iou(poly1, poly2): """Compute the IoU of polygons.""" return polygon_geo_cpu.polygon_iou(poly1, poly2)
72,599