content
stringlengths
22
815k
id
int64
0
4.91M
def resnet101(pretrained=False, num_groups=None, weight_std=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], num_groups=num_groups, weight_std=weight_std, **kwargs) ...
1,000
def cron(cronline, venusian_category='irc3.plugins.cron'): """main decorator""" def wrapper(func): def callback(context, name, ob): obj = context.context crons = obj.get_plugin(Crons) if info.scope == 'class': callback = getattr( ob...
1,001
def test_all_pr(): """ Tests that all_pr matches a hand-obtained solution. """ pos_scores = [-1., 0., 2.] neg_scores = [-2., 0., 1.] # scores: [2., 1., 0., 0., -1., -2.] # labels: [1, 0, 1, 0, 1, 0 ] precision = [1., 1., .5, .5, .6, 3. / 6.] recall = [0., 1. / 3., 1. / 3., 2...
1,002
def merge( _0: pandas.core.frame.DataFrame, _1: pandas.core.frame.DataFrame, /, *, how: Literal["inner"], shuffle: Literal["disk"], ): """ usage.dask: 1 """ ...
1,003
def oauth_type(): """Check if Slack or another OAuth has been configured""" if "OAUTH_TYPE" in current_app.config: return current_app.config["OAUTH_TYPE"].lower() else: return None
1,004
def _get_scenarios(rule_dir, scripts, scenarios_regex, benchmark_cpes): """ Returns only valid scenario files, rest is ignored (is not meant to be executed directly. """ if scenarios_regex is not None: scenarios_pattern = re.compile(scenarios_regex) scenarios = [] for script in scripts...
1,005
def create_categories(): """Create a group of random strings for each column in the table.""" return [ [ ''.join(random.choices(string.ascii_lowercase, k=random.randint(STR_MIN, STR_MAX))) for _i in range(CAT_COUNT) ] for _j in range(COL_COUNT) ]
1,006
def get_asp_output_folder(project_name): """ :type project_name: string """ loc = PROJECT_RESULTS_LOC + project_name + '/' + PROJECT_ASP_OUTPUT_FOLDER mkdir_p(loc) return os.path.abspath(loc)
1,007
def _compute_comm_classes( A: Union[np.ndarray, spmatrix] ) -> Tuple[List[List[Any]], bool]: """Compute communication classes for a graph given by A.""" di_graph = ( nx.from_scipy_sparse_matrix(A, create_using=nx.DiGraph) if issparse(A) else nx.from_numpy_array(A, create_using=nx.Di...
1,008
def parse_lines(lines: typing.List[str], units: Units, use_na: bool = True) -> typing.List[typing.Dict[str, typing.Any]]: """ Returns a list of parsed line dictionaries """ parsed_lines = [] prob = '' while lines: raw_line = lines[0].strip() line =...
1,009
def rand_cutout(np_img, pcts=(0.05, 0.4), depth=(1., 0.), max_k=1): """Cut out from image, and edges of rectangles are smooth. Returns: applied image, cut mask """ cut = np.ones(np_img.shape[:2]) k = random.randint(1, max_k) for _ in range(k): d = random.random() * depth[0] + de...
1,010
def create_content_list(contents: List[str]) -> str: """Format list of string into markdown list Args: contents: (List[string]), list of string to be formatted Returns: String """ return '\n'.join( [template.LIST_TEMPLATE.format( level='', content=item ) for item in c...
1,011
def publish_agent(ctx: Context): """Publish an agent.""" try_to_load_agent_config(ctx) check_is_author_logged_in(ctx.agent_config.author) name = ctx.agent_config.agent_name config_file_source_path = os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE) output_tar = os.path.join(ctx.cwd, "{}.tar.gz".fo...
1,012
def test_sample_clobber_config(tmpdir): """Verify --sample won't clobber config if it already exists.""" with tmpdir.as_cwd(), pytest.raises(sh.ErrorReturnCode_1) as error: Path("mailmerge_server.conf").touch() sh.mailmerge("--sample") stdout = error.value.stdout.decode("utf-8") stderr =...
1,013
def determine_degree_of_endstopping(model, model_folder, block_managers, blocks_to_look_at=None): """ For a list of blocks: Determines the degree of end-stopping and saves these values to the '[folder]/meta.json' file and saves the activations to an npy file: '[folder]/[prefix]-deg_of_es_activation...
1,014
def autolabel(ax: plt.Axes, rects: List[plt.Rectangle], y_range: Tuple[float, float], bottom: bool = False, color: str = 'black') -> None: """ Attach a text label above each bar displaying its height """ for rect in rects: height = rect.get_height() ...
1,015
def convert(key: str, content: str, output_format: OWLFormat=OWLFormat.func) -> Optional[str]: """ Convert content into output_format :param key: Key of content for error reporting :param content: OWL representation :param output_format: target format :return: Converted information if successful...
1,016
def _post_single_image(client: Imgur, image_path, title, description=None): """ Limit to 1250 POST requests per hour and 12500 per day """ image = client.image_upload(image_path, title, description) # album_id = client.album_get('Family Photos')['response']['data']['id'] # client.album_add(album...
1,017
def load_data(path, start=0, end=99999, step=1, returnNames = False): """Load images into a list #Arguments paths: List of strings representing paths to folders containing images that must be named as numbers start,end,step: Refers to the number of name of images. Only loads ...
1,018
async def test_patch_self_relative(api_client): """ Проверяем что жителю можно указать себя родственником. Напоминает фильм Патруль времени, не так ли? """ dataset = [ generate_citizen( citizen_id=1, name='Джейн', gender='male', birth_date='13.09.1945', town='Нью-Йорк...
1,019
def test_list_nmtoken_max_length_nistxml_sv_iv_list_nmtoken_max_length_1_3(mode, save_output, output_format): """ Type list/NMTOKEN is restricted by facet maxLength with value 5. """ assert_bindings( schema="nistData/list/NMTOKEN/Schema+Instance/NISTSchema-SV-IV-list-NMTOKEN-maxLength-1.xsd", ...
1,020
def run_build_commands_with(msg, cmds): """Run general build commands""" window, view, file_shown_in_view = get_haskell_command_window_view_file_project() if not file_shown_in_view: return syntax_file_for_view = view.settings().get('syntax').lower() if 'haskell' not in syntax_file_for_view: ...
1,021
def test_app_creation_failed_no_message_to_has_defects(subtests): """Test exception raised when Mailgun Domain is undefined.""" for to_header, defects_listing in [ ('a', '- addr-spec local part with no domain'), ('a, <b@c', ('- addr-spec local part with no domain\n' "- missi...
1,022
def animated_1d_plot(probe_data_dnf: np.ndarray, probe_data_input1: np.ndarray, probe_data_input2: np.ndarray, interval: ty.Optional[int] = 30) -> None: """Generates an animated plot for examples in the DNF regimes tutorial. Parameters --------...
1,023
def main(): """ Main entry point for module execution :returns: the result form module invocation """ required_if = [ ("state", "merged", ("config",)), ("state", "replaced", ("config",)), ("state", "rendered", ("config",)), ("state", "overridden", ("config",)), ...
1,024
def create_tendencies(params, return_inner_products=False, return_qgtensor=False): """Function to handle the inner products and tendencies tensors construction. Returns the tendencies function :math:`\\boldsymbol{f}` determining the model's ordinary differential equations: .. math:: \dot{\\boldsymbol{x...
1,025
def git_get_keywords(versionfile_abs): """Extract version information from the given file.""" # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from...
1,026
def combined_city_hexes(gpkg_inputs, gpkg_output_hex, cities): """ Create a combined layer of all city hexes to facilitate later grouped analyses and plotting. This is ordered by Continent, Country, City, and hex index. Parameters ---------- gpkg_inputs: list list of sampl...
1,027
def script(text, interpreter="sh"): """Execute a shell script. The script is passed to the interpreter via stdin and the return code of the interpreter is returned.""" process = Popen(interpreter, stdin=PIPE) process.communicate(input=text) process.wait() return process.returncode
1,028
def add_login_arguments_group(parser, full=False): """Adds login arguments to the passed parser :param parser: The parser to add the login option group to :type parser: ArgumentParser. :param full: Flag to include seldom used options :type full: bool """ group = parser.add_argument_...
1,029
def _xml_create_tag_with_parents(xmltree, xpath, node): """ Create a tag at the given xpath together with it's parents if they are missing xml_create_tag cannot create subtags, but since we know that we have simple xpaths we can do it here No tag order is enforced here, since we are in intermediate...
1,030
def copy_ncbi(corpus_path, directory_path): """Divides files from the corpus directory into different directories :param corpus_path: corpus path :param directory_path: new corpus path """ os.system('rm -rf ' + directory_path + '/* || true') for (dir_path, dir_names, file_names) in os.walk(cor...
1,031
def generateImage(boardfilename, outputfilename, dpi, pcbdrawArgs, back): """ Generate board image for the diagram. Returns bounding box (top let, bottom right) active areas of the images in KiCAD native units. """ # For now, use PcbDraw as a process until we rewrite the tool so it can be # used...
1,032
def mask_to_image( mask: _T_input, batch_first: bool = False, color: Optional[str] = None, origin: str = 'lower' ) -> np.ndarray: """ Creates an image from a mask `Tensor` or `ndarray`. For more details of the output shape, see the tensorboardx docs Note: Clips mask to ...
1,033
def lerp(x0, x1, t): """ Linear interpolation """ return (1.0 - t) * x0 + t * x1
1,034
def read_uint4(f): """ >>> import io >>> read_uint4(io.BytesIO(b'\\xff\\x00\\x00\\x00')) 255 >>> read_uint4(io.BytesIO(b'\\x00\\x00\\x00\\x80')) == 2**31 True """ data = f.read(4) if len(data) == 4: return _unpack('<I', data)[0] raise ValueError('not enough data in stream...
1,035
def bound_contribution(w, g, G, nmax, squeeze=True): # TODO docstring # This method assumes g, if it is multidimensional varies along the first axis while w varies along the zeroth axis. """ """ # helper methods def f1(g): return np.sqrt(g).astype(int) # * L(w + (1 / ell - ell / g) ...
1,036
def configure_typogrify(pelicanobj, mathjax_settings): """Instructs Typogrify to ignore math tags - which allows Typogfrify to play nicely with math related content""" # If Typogrify is not being used, then just exit if not pelicanobj.settings.get('TYPOGRIFY', False): return try: i...
1,037
def karatsuba_256x256(ab, a, b, t0, t1, t2, t3, t4): """assumes a and b are two ymm registers""" z0, z2 = ab a0, a1 = a, t0 b0, b1 = b, t1 z1 = t2 p("vextracti128 $1, %ymm{}, %xmm{}".format(a, a1)) p("vextracti128 $1, %ymm{}, %xmm{}".format(b, b1)) mult_128x128(z2, a1, b1, t3, t4) p...
1,038
def get_onto_class_by_node_type(ont: owlready2.namespace.Ontology, node_label: str): """Get an object corresponding to an ontology class given the node label. `owlready2` doesn't make it easy to dynamically retrieve ontology classes. This uses some (relatively unsafe) string manipulation to hack together a...
1,039
def validate_dtype_freq(dtype, freq): """ If both a dtype and a freq are available, ensure they match. If only dtype is available, extract the implied freq. Parameters ---------- dtype : dtype freq : DateOffset or None Returns ------- freq : DateOffset Raises ------ ...
1,040
def extract_filtered_series(data_frame, column_list): """ Returns a filtered Panda Series one-dimensional ndarray from a targeted column. Duplicate values and NaN or blank values are dropped from the result set which is returned sorted (ascending). :param data_frame: Pandas DataFrame :param column_list: list of c...
1,041
def event_rheader(r): """ Resource headers for component views """ rheader = None if r.representation == "html": if r.name == "event": # Event Controller tabs = [(T("Event Details"), None)] #if settings.has_module("req"): # tabs.append((T("Reques...
1,042
def parse_args(): """Read arguments from config file and command line args.""" options_default = { 'permissions': True, 'checksum': True, 'interval': 60, 'pidfile': '~/.dropboxhandler.pid', 'daemon': False, 'umask': 0o077, } parser = argparse.ArgumentPars...
1,043
def backend_is_up(backend): """Returns whether a server is receiving traffic in HAProxy. :param backend: backend dict, like one of those returned by smartstack_tools.get_multiple_backends. :returns is_up: Whether the backend is in a state that receives traffic. """ return str(backend['status']).st...
1,044
def get_bot_files_glob(**kwargs): """Returns a `list` with the matching file names using the format string for BOT data """ outdict = {} kwcopy = kwargs.copy() test_name = kwcopy.pop('testName').lower() nfiles = kwcopy.get('nfiles', None) rafts = get_raft_names_dc(kwcopy['run'], kwcopy.get('test...
1,045
def plot_univariate_categorical_columns(categorical_cols: Sequence[str], dataframe: pd.DataFrame, **kwargs) -> None: """plots categorical variable bars Args: categorical_cols (Sequence[str]): categorical columns dataframe (pd.DataFrame): DataFrame """ for c in categorical_cols: ...
1,046
def _submit_drmaa(args, unknown_args): """ Submit multiple 'pisces run' jobs to the cluster using libdrmaa """ if args.local: submit_local(args.metadata, args.config, args.max_memory, args.runtime, unknown_args, args.dry_run, args.debug, args.workdir) else: submit_drmaa(args.metadata, args....
1,047
def minutiae_selection(minutiae): """ Selects the subset of most reliable minutiae. """ M = np.array([(m['x'], m['y'], m['direction'], m['reliability']) for m in minutiae]) M[:,2] = np.round(np.rad2deg(nbis_idx2angle(M[:,2], N=16))) M[:,3] = np.round(M[:,3] * 100.0) M = M.astype(int) M = M[M[:,3] > np.percentile...
1,048
def test_imshowhs_grid_1(): """ Show DEM draped over the shaded topographic relief """ # %% mg = landlab.RasterModelGrid((4, 5)) _ = mg.add_zeros("topographic__elevation", at="node") _ = landlab.plot.imshowhs_grid( mg, "topographic__elevation", var_name="Topo", ...
1,049
def alt_blend_value(data, i, j, k): """Computes the average value of the three vertices of a triangle in the simplex triangulation, where two of the vertices are on the upper horizontal.""" keys = alt_triangle_coordinates(i, j, k) return blend_value(data, i, j, k, keys=keys)
1,050
async def test_set_licensing_info_put_mhlm(test_server): """Test to check endpoint : "/set_licensing_info" Test which sends HTTP PUT request with MHLM licensing information. Args: test_server (aiohttp_client): A aiohttp_client server to send HTTP GET request. """ data = { "type": "...
1,051
def _BinaryCrossEntropy(): """Returns a layer that computes prediction-target cross entropies.""" def f(model_output, target_category): # pylint: disable=invalid-name shapes.assert_same_shape(model_output, target_category) batch_size = model_output.shape[0] j = jnp.dot(jnp.transpose(target_category), j...
1,052
def compile_exe(): """ Creates a standalone EXE file. """ print('\nRunning compile using distutils and py2exe:\n') from distutils.core import setup import py2exe # required for proper inclusion typelibs = [] com_server = [] dll_excludes = ['w9xpopen.exe'] sys.argv[1] = 'py2exe'...
1,053
def normalize(subs, strict): """ Normalises subtitles. :param subs: :py:class:`Subtitle` objects :param bool strict: Whether to enable strict mode, see :py:func:`Subtitle.to_srt` for more information :returns: A single SRT formatted string, with each input ...
1,054
def update_weights(model, weights): """ Package up a trained/finetuned model as a new bioimageio model """ from bioimageio.core.build_spec import build_model # create a subfolder to store the files for the new model model_root = Path("./sample_data") model_root.mkdir(exist_ok=True) # c...
1,055
def Stern_Brocot(n): """ Another way to iterate over rationals References: https://stackoverflow.com/questions/24997970/iterating-over-parts-of-the-stern-brocot-tree-in-python """ states = [(0, 1, 1, 1)] result = [] while len(states) != 0: a, b, c, d = states.pop() i...
1,056
def compare_elements(prev_hash_dict, current_hash_dict): """Compare elements that have changed between prev_hash_dict and current_hash_dict. Check if any elements have been added, removed or modified. """ changed = {} for key in prev_hash_dict: elem = current_hash_dict.get(key, '') ...
1,057
def test_list(script_collection): """Ensure the method returns the expected value on success""" x_resp = script_collection._client.http_get.return_value x_resp.status_code = 200 result = script_collection.list() assert result == x_resp.json.return_value
1,058
def test_interp_time( time: types_time_like, time_ref: types_timestamp_like, systems: List[str], csm_has_time_ref: bool, num_abs_systems: int, ): """Test the ``interp_time`` method. Parameters ---------- time : The value passed to the functions as ``time`` parameter time...
1,059
def add_to_mongo(data): """ 入库 :param data: :return: """ connection = pymongo.MongoClient() tdb = connection.Spider db = tdb.ip_pool if isinstance(data, list): db.insert_many(data) else: db.insert(data)
1,060
def generator_string(lang_uses: str = 'all', char_count: int = 1, char_size: str = 'lower') -> str: """Generator string :param lang_uses: набор символов :type lang_uses: str :param char_count: сколько символов отдать :type char_count: int :param char_size: размер символов ...
1,061
def create_cvmfs_persistent_volume_claim(cvmfs_volume): """Create CVMFS persistent volume claim.""" from kubernetes.client.rest import ApiException from reana_commons.k8s.api_client import current_k8s_corev1_api_client try: current_k8s_corev1_api_client.create_namespaced_persistent_volume_claim...
1,062
def SLC_copy(SLC_in, SLC_par_in, SLC_out, SLC_par_out, fcase='-', sc='-', roff='-', nr='-', loff='-', nl='-', swap='-', header_lines='-', logpath=None, outdir=None, shellscript=None): """ | Copy SLC with options for data format conversion, segment extraction, and byte swapping | Copyright 2015,...
1,063
def get_host_ips(version=4, exclude=None): """ Gets all IP addresses assigned to this host. Ignores Loopback Addresses This function is fail-safe and will return an empty array instead of raising any exceptions. :param version: Desired IP address version. Can be 4 or 6. defaults to 4 :par...
1,064
def rate_string(rate, work_unit, computer_prefix=False): """Return a human-friendly string representing a rate. 'rate' is given in 'work_unit's per second. If the rate is less than 0.1 then the inverse is shown. Examples: >>> rate_string(200000, "B", True) '195KB/s' >>> rate_string(0.01, ...
1,065
def get_queue_arn(sqs_client, queue_url: str) -> str: """Encapsulates SQS::get_queue_attributes with special attribute QueueArn. :param sqs_client: The Boto3 AWS SQS client object. :param queue_url: URL of the queue :return: The Amazon Resource Name (ARN) of the queue. """ try: respons...
1,066
def any_flexloggers_running() -> bool: """Returns whether any FlexLogger.exe processes are running.""" for proc in psutil.process_iter(["pid", "name"]): if proc.info["name"].lower() == "flexlogger.exe": return True return False
1,067
def _get_non_white_runs(mask): """Returns those runs that are delimeted by white cells.""" res = [] in_a_block = False last_idx = len(mask) - 1 for idx, cell in enumerate(mask): if cell != WHITE and not in_a_block: in_a_block = True start = idx if cell == WHI...
1,068
def createMask(input=None, static_sig=4.0, group=None, editpars=False, configObj=None, **inputDict): """ The user can input a list of images if they like to create static masks as well as optional values for static_sig and inputDict. The configObj.cfg file will set the defaults and then override th...
1,069
def cov(x, y, w): """Calculates weighted covariance""" return np.sum( w * (x - np.average(x, axis=0, weights=w)) * (y - np.average(y, axis=0, weights=w)) ) / np.sum(w)
1,070
def eval_metrics_all( y: List[np.ndarray], y_hat: List[np.ndarray] ) -> Dict[str, float]: """Calculates combined accuracy, f1, precision, recall and AUC scores for multiple arrays. The arrays are shorted to the minimum length of the corresponding partner and stacked on top of each other to calculate...
1,071
def test_multiple_primary(): """test prevention of multiple primary keys""" with pytest.raises(MultiplePrimaryKeysError): class Test(Model): # pylint: disable=unused-variable """bad model with multiple primary keys""" id = Field(default=0, is_primary=True) idd = Fie...
1,072
def cli(): """ Tools for user manipulation """
1,073
def fake_dataset_no_label(path, range1, batch_size=32, shuffle=False): """ Create fake dataset with no label Args: path (str) : provide the data settings range1 (tuple) : range of generated images batch_size (int): number of samples contained in each generated batch shuffle ...
1,074
def output_influx(customer, show_hourly=False): """Print data using influxDB format.""" _params = {"name": "InfluxDB", "bucket" : "HydroQuebec", #"batch_size" : 100, } db = InfluxDB(_params) db.write_data_to_db(customer, show_hourly=show_hourly) print("Sent this to InfluxDB") ...
1,075
def number_of_songs_match(folder, songs): """ Checks if the number of music files in folder matches the number of tracks listed in songs. Arguments: - folder: path to folder where music files are found - songs: list of track numbers Returns: True / False """ file...
1,076
def spaces_to_pluses(q, city, state): """ """ if city and state: return split_text(q), split_text(city), split_text(state) else: return split_text(q), 'Nationwide', ' '
1,077
def add_date(start, unit, addend): """ Find the date so many days/months/years into the future from the given date """ start = _parse_date(start) if unit == 'days': print(start.replace(days=addend)) elif unit == 'months': print(start.replace(months=addend)) elif unit == 'ye...
1,078
def add_parent_path(plevel=1): """ Solve "Parent module '' not loaded, cannot perform relative import" Issue :param plevel: :return: """ from minghu6.etc.path import get_pre_path import os path = get_pre_path(__file__, plevel) os.path.join(path)
1,079
def _check_str_input(var, input_name: str, valid_options: Optional[List[str]] = None) -> str: """ _check_str_input Convenience function to check if an input is a string. If argument valid_options is given, this function will also check that var is a valid option from the valid_options specified. P...
1,080
def os_compress(filename, ctype, remove_original=False): """ compress a file to any of the formats: ['.Z', '.gz', '.tar.gz', '.zip'] If the instance is already compressed (to any format), no operation will be performed. If it is uncompressed: 1) then the file will be compressed 3) if remove...
1,081
def run_U_fixed_dynamics(**kwargs): """ Run simulation for a given set of parameter values and generate relevant plots """ # Steady state checks #print('============================== U fixed, U='+str(kwargs['U'])) a = mpde(**kwargs) #lib.disp_params(a) # display non-array paramete...
1,082
def removeDuplicates(bookmarks, newBookmarks): """Creates and returns a new list of bookmarks without any duplicates""" nodup = [] for bmNew in newBookmarks: foundDup = False for bm in bookmarks: if (bm.linkURL == bmNew.linkURL): foundDup = True break if (not foundDup): nodup.ap...
1,083
def TNaming_Naming_GetID(*args): """ * following code from TDesignStd ============================== :rtype: Standard_GUID """ return _TNaming.TNaming_Naming_GetID(*args)
1,084
def assigned_user_add(request, location_id, destination): """ Assigned user add is a POST function where it will ADD a user to a project/task/opportunity/requirement. :param request: :param location_id: :param destination: :return: """ # Load the template t = loader.get_template('Nea...
1,085
def test_MeshAdaptRestart_adaptiveTime_BackwardEuler_baseline_withRDMC(verbose=0): """Get baseline data""" currentPath = os.path.dirname(os.path.abspath(__file__)) runCommand = "cd "+currentPath+"; parun -C \"gen_mesh=False usePUMI=True adapt=0 fixedTimeStep=False\" -D \"baseline\" dambreak_Colagrossi_so.py...
1,086
def _parse_challenge(header): # type: (str) -> Dict[str, str] """Parse challenge header into service and scope""" ret = {} if header.startswith(BEARER): challenge_params = header[len(BEARER) + 1 :] matches = re.split(AUTHENTICATION_CHALLENGE_PARAMS_PATTERN, challenge_params) _cl...
1,087
def test_get_batch(source): """ Creates an input/target pair for evaluation """ seq_len = len(source) - 1 data = source[:seq_len] target = source[1:1+seq_len].view(-1) return data, target
1,088
def ShowChance(chance): """show how many chances are left""" print("{:^40s}".format("you have {} more chance".format(chance)))
1,089
def getReceptorResidues(filename=None, data=None): """Accepts a PDB(TQ) file and returns a nested dictionary of: chain:residue:atoms """ if filename: lines = getLines(filename) else: lines = data structure = {} for l in lines: if l.startswith(...
1,090
def extract_first_compute_cell(text): """ INPUT: a block of wiki-like marked up text OUTPUT: - ``meta`` - meta information about the cell (as a dictionary) - ``input`` - string, the input text - ``output`` - string, the output text - ``end`` - integer, first position after }}} in...
1,091
def test_matrix2dict(): """ Test Utils: matrix 2 dict """ m = [[0, 1, 3], [1, 0, 2], [3, 2, 0]] d = matrix2dict(m) assert (d == {0: {0: 0, 1: 1, 2:3}, 1: {0: 1, 1: 0, 2:2}, 2: {0: 3, 1:2, 2:0}} )
1,092
def setup_env_with_project_ini_self_destruct(): """Set up the environment base structure""" setup_env = EnvSetUp(p_make_project_ini=True) yield setup_env rm_tree(setup_env.anchor_dir, p_crash=False)
1,093
def check_schema(loader_impl: LoaderImpl) -> LoaderImpl: """Wrapper method to check column names and types.""" @wraps(loader_impl) def wrapped_loader(fp: Union[str, IO], extra_fields: Dict[str, str] = None) -> DataFrame: name = fp if isinstance(fp, str) else fp.name data = loader_impl(fp, e...
1,094
def fail_quality(name, message): """ Fail the specified quality check by generating the JUnit XML results file and raising a ``BuildFailure``. """ write_junit_xml(name, message) raise BuildFailure(message)
1,095
def get_album_photos(album, offset, vk_session): """Retrieves list of photos within given album from VK.com :param album: :type album: str :param offset: :type offset: int or None :param vk_session: instance of :class:`vk_api.VkApi` :type vk_session: :class:`vk_api.VkApi` :return: "...
1,096
def get_view_cursor(**kwargs) -> 'XTextViewCursor': """ Gets current view cursor which is a XTextViewCursor Keyword Args: o_doc (object, optional): current document (xModel) Returns: object: View Cursor """ o_doc = kwargs.get('o_doc', None) if o_doc is None: o_doc =...
1,097
def get_common_metrics(test_values, predicted): """ Return some common classifier metrics :param test_values: values to test with :param predicted: predicted values :return: accuracy, precision and recall value """ accuracy = metrics.accuracy_score(test_values, predicted) precision = met...
1,098
def update_maintenance_window_target(WindowId=None, WindowTargetId=None, Targets=None, OwnerInformation=None, Name=None, Description=None, Replace=None): """ Modifies the target of an existing maintenance window. You can change the following: See also: AWS API Documentation Exceptions :exa...
1,099