content
stringlengths
22
815k
id
int64
0
4.91M
def dir_size(path): """ Get the size of the directory represented by path recursively. :param path: Path to the dir whose size needs to be calculated :return: size in bytes of the dir """ # Closure for recursiveness def get_dir_size(path): size = 0 for entry in os.scandir(pat...
73,000
async def _get_username_password(registry_name: str) -> UsernamePassword: """ Gets the UsernamePassword for logging into the meadowrun-managed Azure container registry. Can be passed to functions in docker_controller.py """ # https://github.com/Azure/azure-cli/blob/284d6131679cecc26f928c78f1e4c29e2...
73,001
def rep(data): """Checks if all labels are represented in the dataset `data`.""" labels = [0, 1] # Iteratively check if all labels are represented for i in range(len(data) - 1): row = data[i] label = row["label"] contains = label in labels if contains and labels: ...
73,002
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ # support logging in python3 logging.config.fileConfig( settings['logging.config'], disable_existing_loggers=False ) config = Configurator(settings=settings) config.set_root_facto...
73,003
def test_observation_node__constructor(parent): """Tests initiation of observation nodes""" n = ObservationNode(parent) assert parent == n.parent other_node = ActionNode("garbage statistic", ObservationNode()) assert other_node != n.parent
73,004
def run_program(program, args=None, **subprocess_kwargs): """ Run program in a separate process. NOTE: returns the process object created by `subprocess.Popen()`. This can be used with `proc.communicate()` for example. If 'shell' appears in the kwargs, it must be False, otherwise ...
73,005
def quota_size(value): """ Covnert a human readable quota size into a number of bytes. """ _UNITS_RE = re.compile('^\s*(?P<value>\d+(\.(\d*)?)?)\s*(?P<scale>[kMGTP]i?)?B?$') _UNITS_SCALES = {None: 1, 'k' : 1000, 'ki': 1024, 'M' : 1000**2, 'Mi': 1024*...
73,006
def register_project(): """Register a project at Conductor service if not done already. The function checks all projects in the users config file and if a project does not have an id already it will try register it at the specified Conductor Service. """ registration_id = request.json["id"] ...
73,007
def snow_and_ndsi_locations(src_info, no_data_value): """Generate Landsat snow locations and NDSI nodata locations Args: src_info <SourceInfo>: Information about the source data no_data_value <int>: No data (fill) value to use Returns: list(<int>): Locations where we decided snow e...
73,008
def compute_cov(tensor, tensor_right=None, normalizer=None): """Compute the empirical second moment of the rows of a 2D Tensor. This function is meant to be applied to random matrices for which the true row mean is zero, so that the true second moment equals the true covariance. Args: tensor: A 2D Tensor....
73,009
def gen_blockMeshDict(x_cord, y_cord): """ Create a `blockMeshDict` file for the geometry """ scale = 1 z = 0.05 x_orig = 0 y_orig = 0 x_max = 3 y_max = 1 x_cord = x_cord y_cord = y_cord x_cell = int(x_cord * 50) y_cell = int(y_cord * 50) # Open file f = op...
73,010
def parametrize_filebased(abspath: Optional[str], filename: str, relpath: Optional[str]) -> Any: """ Converts a target json file as a source of parameters for pytest. :param abspath: Absolute path of the json file :param filename: Name of the json file :param relpath: Relative path to the json file ...
73,011
def hexbin_viz( df: pd.DataFrame, x: str, y: str, plot_width: int, plot_height: int, tile_size: Optional[float] = None, ) -> Panel: """ Render a hexbin plot """ # pylint: disable=too-many-arguments,too-many-locals xmin, xmax = df[x].min(), df[x].max() ymin, ymax = df[y].m...
73,012
def _func_if(args, is_differentscenario, line, pos): """args[0]がTrueであればargs[1]を、そうでなければargs[2]を返す。""" _chk_argscount(args, 3, "IF", line, pos) a = args[0] _chk_boolean(a, "IF", 0) t = args[1] f = args[2] return t if a.value else f
73,013
def profiler(output_file=None, sort_by='cumulative', lines_to_print=None, strip_dirs=False): """ A time profiler decorator :param str output_file: Path of the output file. If only name of the file is given, it's saved in the current directory. If it's None, the name ...
73,014
def find_overlapping_annotations(m, annotations): """Takes a markup object and a df of annotations from the same report""" def overlaps(m_span, a_span): m_span = [int(n) for n in m_span] a_span = [int(n) for n in a_span] #print(m_span, a_span) overlap = ((a_span[0] <= m_span[0] <...
73,015
def _merge_prefix(deque, size): """Replace the first entries in a deque of strings with a single string of up to size bytes. >>> d = collections.deque(['abc', 'de', 'fghi', 'j']) >>> _merge_prefix(d, 5); print(d) deque(['abcde', 'fghi', 'j']) Strings will be split as necessary to reach the des...
73,016
def _is_prime_bruteforce(prime): """Check if a number is prime using brute force and some caching. Our brute force method is a little smarter than the standard method, as we rule some factors out due to the following principles: 1) We already have a list of cached primes. If our supposed prime is c...
73,017
def encode(data: Union[bytes, dict, int, list]) -> bytes: """Convert the given Python object to a bencoded string. Raises: ValueError: If the provided object type is not supported Returns: A bencoded string """ if isinstance(data, bytes): return _encode_bytes(data) if ...
73,018
def match_grasp_view_and_label(end_points): """ Slice grasp labels according to predicted views. """ top_view_inds = end_points['grasp_top_view_inds'] # (B, Ns) template_views_rot = end_points['batch_grasp_view_rot'] # (B, Ns, V, 3, 3) grasp_labels = end_points['batch_grasp_label'] # (B, Ns, V, A, D) ...
73,019
def test_projwfc_no_retrieved_temporary(generate_calc_job_node, fixture_localhost, generate_parser): """Test ``ProjwfcParser`` fails when the retrieved temporary folder is missing.""" node = generate_calc_job_node( entry_point_name='quantumespresso.projwfc', computer=fixture_localhost, t...
73,020
def execute_blueprint(cli, blueprint, repo_info, logger=None): """ Execute a blueprint """ if logger is None: logger = j.logger.logging errors = [] logger.info('Executing blueprint [{}]'.format(blueprint)) try: res, ok = check_status_code(cli.executeBlueprint(data={}, bluep...
73,021
def test_cli_09_launch_bottleneck_2trucks2links( runner, bottleneck_2trucks2links ): """Run: ensemble launch -s path/bottleneck_1truck.xml""" result = runner.invoke(cli.main, ["launch", "-s", bottleneck_2trucks2links]) f"Input File: {bottleneck_1truck} Found\n" in result.output
73,022
def convert_meshio( mesh, ignore_unknown=False, import_dim=(1, 2, 3), element_id_name="element_id", material_id_name="material_id", ): """ Convert points and cells from meshio to ogs format. Parameters ---------- mesh : meshio mesh class The given mesh by meshio igno...
73,023
def send_email(json_data, to): """Prepares a mail Message to be sent as a background task with Flask-Mail :param to: list[str] the list of recipients :param dict json_data: The dictionary that has info for the mail """ if not isinstance(to, list): to = [to] msg = Message(subject=MAIL_SU...
73,024
def get_data(path_imgs,path_masks,axis=0, batch=50,buffer_size=300, size_crop=160,random_crop=False, augmentation=False,repeat=1, pixels=0,cache=True, ): """ Returns dataset already preprocessed """ data = tf.data.Dataset.from_generator(gener...
73,025
def torch_item(x): """ Like ``x.item()`` for a :class:`~torch.Tensor`, but also works with numbers. """ return x if isinstance(x, numbers.Number) else x.item()
73,026
def small_world_random(G): """ Compute the average clustering coefficient and average shortest path length of a random network with the same number of nodes and edges as G Parameters ---------- G: Network X undirected graph Returns ------- C: float the random network cluste...
73,027
def count(grid, c): """ Count the occurrences of an object "c" in the 2D list "grid". """ acc = 0 for row in grid: for elem in row: acc += c == elem return acc
73,028
def fatorial(a, show = False): """ -> Lê o fatorial a = Número que irá ver o fator show = Mostrar o calculo ou não """ f = 1 for c in range(a, 0, -1): f *= c if show == True: print(f'{c}', end=' ') if c > 1: print('x', end=' ')...
73,029
def test_ll_error(): """Tests that the log-likelihood function correctly raises an error when an incorrect string is passed as a parameter.""" y_true = np.array([1., 2., 3.]) y_pred = np.array([3., 4., 5.]) assert_raises(ValueError, log_likelihood_glm, 'error', ...
73,030
def setup(fips_dir, proj_dir) : """setup the Android SDK and NDK""" log.colored(log.YELLOW, '=== setup Android SDK/NDK :') # first make sure that java is present, otherwise the Android # SDK setup will finish without errors, but is not actually usable if not java.check_exists(fips_dir) : lo...
73,031
def strictly_upper_triangle(m): """ Returns a matrix containing the strictly upper triangle of m and zeros elsewhere. """ l = _np.shape(m)[0] out = m.copy() for i in range(0, l): for j in range(0, i + 1): out[i, j] = 0 return out
73,032
def config_retry_strategy(retry): """Generate retry strategy.""" if not isinstance(retry, int): raise ValueError("Parameter retry should be a number") return {"limit": retry, "retryPolicy": "Always"}
73,033
def isomap_transform(data_scaled, labels) : """Compute the Isomap transform from a scaled data. Parameters ---------- data_scaled : numpy.ndarray A matrix with the scaled data to transform labels : numpy.ndarray Labels to assign to the transformed data (0 for real and 1 for sy...
73,034
def call_solver(matvec, matvec_args, hI, params, x0, tol): """ Code used by both solve_for_RH and solve_for_LH to call the sparse solver. Solves matvec(*matvec_args, x) = hI for x. PARAMETERS ---------- matvec (jax.tree_util.Partial): A function implementing the linear ...
73,035
def vertex_score(timeseries): """ A timeseries is anomalous if vertex score in hypergraph is greater than average score of observed anomalous vertex. :return: True or False """ if vertex_centers.shape[0] <= 1: update_vertex_param() timeseries = np.array(timeseries) test_data = timese...
73,036
def setenv(variable: str, value: str) -> None: """ set system Environment Variable example: envset('TESTVARIABLE', 'TESTVALUE') """ if variable and type(variable) == str and type(value) == str: os.system(f'setx \"{variable}\" \"{value}\" > nul') os.environ[variable]=value else: ...
73,037
def emergency_contact_list(request): """ Renders emergency contact info page """ brothers = Brother.objects.exclude(brother_status='2').order_by("last_name") context = { 'brothers': brothers, } return render(request, 'emergency-contact-list.html', context)
73,038
async def test_encoding_subscribable_topics( hass, mqtt_mock_entry_with_yaml_config, caplog, topic, value, attribute, attribute_value, ): """Test handling of incoming encoded payload.""" await help_test_encoding_subscribable_topics( hass, mqtt_mock_entry_with_yaml_con...
73,039
def deprecation_warning(msg): """Raise a deprecation warning.""" warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
73,040
def get_backup_path(p: Path) -> Optional[Path]: """Gets the backup path for a given path. If the path we come up with already exists (highly unlikely), returns ``None``. """ basename = p.name # e.g. "2020-10-17T18_21_41" # Colons aren't allowed in Windows paths, so we can't quite use ISO 86...
73,041
def usage(): """ Usage: python3 -h | -help python3 ConfigInstance.py -U user [-T config_type] [-P cluster_static_config] [-C "PARAMETER=VALUE" [...]] [-D "PARAMETER=VALUE" [...]] [-L log] target file: pg_config, gs_config, all """ print(usage.__doc__)
73,042
def create_user_records_bp(app): """Create user records blueprint.""" ext = app.extensions["invenio-rdm-records"] return ext.user_records_resource.as_blueprint( "bibliographic_user_records_resource" )
73,043
def make_create_dataframe( col_names: Any, K: RuntimeTypeDescriptor = None ) -> Transformation: """Make a Transformation that constructs a dataframe from a Vec<Vec<String>>. :param col_names: Column names for each record entry. :type col_names: Any :param K: categorical/hashable data type o...
73,044
def chop(surface, rect): """ chop(Surface, rect) -> Surface gets a copy of an image with an interior area removed """ raise NotImplementedError
73,045
def init_tensorboard_logger() -> pl.loggers.TensorBoardLogger: """TODO""" return None
73,046
def conda_prefix(user=None): """ Get the conda prefix for a particular user (~/anaconda) If user is None it defaults to /opt/anaconda """ if user == 'root': return __salt__['grains.get']('conda:prefix', default='/opt/anaconda') else: if user is None: user = __salt__['...
73,047
def filter_entropy(np_img, neighborhood=9, threshold=5, output_type="uint8"): """ Filter image based on entropy (complexity). Args: np_img: Image as a NumPy array. neighborhood: Neighborhood size (defines height and width of 2D array of 1's). threshold: Threshold value. output_type:...
73,048
def ProxyInfoFromEnvironmentVar(proxy_env_var): """Reads proxy info from the environment and converts to httplib2.ProxyInfo. Args: proxy_env_var: Environment variable string to read, such as http_proxy or https_proxy. Returns: httplib2.ProxyInfo constructed from the environment string. """ pr...
73,049
def getTechniqueData(technique=None): """ Returns injection data for technique specified """ return kb.injection.data.get(technique)
73,050
def _deserialize_video(json_text): """ Parses JSON and deserializes it into a list of YouTubeResult objects. """ results = [] parsed_json = json.loads(json_text) items = parsed_json["items"] for item in items: result = YouTubeResult() snippet = item["snippet"] content...
73,051
def virtualip_list(ctx, filter, **ids): """List all virtual IP associated to a vport, a redirection target""" """or a subnet""" id_type, id = check_id(**ids) request = "%ss/%s/virtualips" % (id_type, id) result = ctx.obj['nc'].get(request, filter=filter) table = PrettyTable(['ID', ...
73,052
def interval(lower_, upper_): """Build an interval.""" if lower_ <= upper_: return lower_, upper_ return None
73,053
async def apiDiscordCommandsDelete(cls:"WebIndex", WebRequest:Request) -> Response: """ Default url: /api/discord/commands/delete """ Data:WebRequestContent = WebRequestContent(WebRequest) await Data.load() # get required vars guild_id:str = Data.getStr("guild_id", "", must_be_digit=True) command_id:str = Dat...
73,054
def _parse_amiga_props(amiga_props, offset_x): """Convert AmigaFont properties into yaff properties.""" if amiga_props.tf_Style & _FSF_COLORFONT: raise ValueError('Amiga ColorFont not supported') props = {} # preserve tags stored in name field after \0 name, *tags = amiga_props.dfh_Name.deco...
73,055
def flow_to_trafo_PnP(*args, **kwargs): """ input: real_br: torch.tensor torch.Size([2]) real_tl: torch.tensor torch.Size([2]) ren_br: torch.tensor torch.Size([2]) ren_tl: torch.tensor torch.Size([2]) flow_mask: torch.Size([480, 640]) u_map: torch.Size([480, 640]) v_map...
73,056
def Ha_plot(ax): """Plot the Ha line and bandpass.""" ax.axvspan(Ha - 0.678, Ha + 0.678, color='tab:blue', alpha=.5) ax.axvspan(6545.495, 6556.245, color='tab:blue', alpha=.5) ax.axvspan(6575.934, 6584.684, color='tab:blue', alpha=.5) ax.axvline(Ha, color='red', ls='dashed') ax.set_xlim(6544.49...
73,057
def ikev2scan(ip, **kwargs): """Send a IKEv2 SA to an IP and wait for answers.""" return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8), exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs)
73,058
def usb_get_strings(*args): """ usb_get_strings(context, device) -> (return_code, manufacturer, description, serial) Return device ID strings from the usb device. The parameters manufacturer, description and serial may be NULL or pointer to buffers to store the fetched strings. Use this fun...
73,059
def set_avatar_url(): """ 设置用户头像信息 1. 获取参数,avatar, user_id,request.filter.get('avatar') 2. 检验参数存在 3. 读取图片数据,data= avatar.read() 4. 调用七牛云接口,上传用户头像 5. 保存用户头像信息到数据库 6. 拼接用户头像图片的完整路径,七牛云外链域名+图片文件名 7. 返回结果 :return: """ # 获取参数 user_id = g.user_id avatar = request.files...
73,060
def showSegmentation( segmentation, voxelsize_mm=np.ones([3, 1]), degrad=4, label=1, smoothing=True, vtk_file=None, qt_app=None, show=True, resize_mm=None ): """ Funkce vrací trojrozměrné porobné jako data['segmentation'] v data...
73,061
def fetch_links(html): """ Fetch all links on a given page and return their hrefs in a list """ elements = html.cssselect('a') return [e.get('href') for e in elements if e.get('href') is not None]
73,062
def isolines_style(value=RANGE_LABEL_KEY, top=11, cat=None, palette='pinkyl', size=None, opacity=0.8, stroke_color='rgba(150,150,150,0.4)', stroke_width=None): """Helper function for quickly creating an isolines style. Based on the color category style. Args: value (str, optional...
73,063
def generate_html(html_name: str = "default_name"): """ format html_string and output html file :param html_name: save html file name :return: html_string """ if len(test_record_instance.test_record_list) == 0 and len(test_record_instance.error_record_list) == 0: raise HTMLException(html...
73,064
def write_dataset(dataset, filename): """ Writes a specific dataset (list of bee image files) to a txt file in the specified file :param dataset: the bee dataset to store :param filename: the file where the dataset will be written :return: nothing """ with open(filename, 'w') as file: ...
73,065
def nlp_answer(question: str = "人工智能") -> str: """ 智能问答 https://ownthink.com/robot.html :param question: word in chinese :type question: str :return: indicator data :rtype: list or dict or pandas.DataFrame """ url = 'https://api.ownthink.com/bot' params = { 'spoken': ques...
73,066
def load_eia861_state_total_sales( pudl_out: pudl.output.pudltabl.PudlTabl ) -> pd.DataFrame: """ Read and format EIA 861 sales by state and year. Args: pudl_out: Used to access :meth:`pudl.output.pudltabl.PudlTabl.sales_eia861`. Returns: Dataframe with columns `state_id_...
73,067
def echo_handler(ex, *args, **kwargs): """ Example error handler which echoes the exception and the arguments. """ argstring = ','.join(['%s' % arg for arg in args]) return '%s/%s/%s' % (ex.message, argstring, kwargs)
73,068
def test_load_duplicate_course( mock_upsert_tasks, course_exists, course_id_is_duplicate, duplicate_course_exists ): """Test that load_course loads the course""" course = CourseFactory.create(runs=None) if course_exists else CourseFactory.build() duplicate_course = ( CourseFactory.create(runs=N...
73,069
def p(k, x): """Iterative optimal binary pebbler generating {f^i(x)}_{i=0}^{n-1} in reverse, n=2^k.""" # initial stage z = [] y = x for h in range(2**k, 1, -1): if h & (h-1) == 0: # h is power of 2 z.insert(0, y) y = f(y) yield # output stage y...
73,070
def get_onnx2ncnn_path() -> str: """Get onnx2ncnn path. Returns: str: A path of onnx2ncnn tool. """ wildcard = os.path.abspath( os.path.join( os.path.dirname(__file__), '../../../build/bin/onnx2ncnn')) paths = glob.glob(wildcard) lib_path = paths[0] if len(paths) > ...
73,071
def find_media(args, src_api, dest_api, dest_project): """ Finds existing media in destination project. Returns media that need to be created and ID mapping between source and destination medias. """ media = [] media_mapping = {} if args.skip_media: logger.info(f"Skipping media due t...
73,072
def list_host_deployment_info(package_name, environment, version=None, revision=None, apptypes=None): """Give all deployment information for a given package deployed to hosts for given (or all) application types and in given environment """ dep_info = (Session.qu...
73,073
def test__config__get(): """Test FluffConfig.get method.""" cfg = FluffConfig(config_b) assert cfg.get("rules") == "L007" assert cfg.get("rulez") is None assert cfg.get("rulez", section="core", default=123) == 123 assert ( cfg.get("operator_new_lines", section=["rules", "L007"], default...
73,074
def main(): """Main""" # Init ## Terminal size size = x_size, y_size = os.get_terminal_size() player = player_x, player_y = 2.4, 2.7 map_ = [ # 0: Vide, 1: Mur [1,1,1,1,1,1,1,1], [1,0,1,0,1,0,1,1], [1,0,0,0,1,0,0,1], [1,1,0,1,1,1,0,1], ...
73,075
def _predict(group, model): """internal use """ # generate arrays and interpolate components onto the unknown x array xdat, ydat = get_arrays(group, model.arrayname) if xdat is None or ydat is None: raise ValueError("cannot get arrays for arrayname='%s'" % arrayname) spectra = interp(xdat, ...
73,076
def test_runtime_config_attributes(): """Check the attributes existence for a class RuntimeConfig.""" config = RuntimeConfig() assert config is not None assert hasattr(config, "_config")
73,077
def computer_quals(predictions, n_alleles): """Computes GQ and QUAL values from a set of prediction probabilities.""" ## GQ is prob(GQ) / prob(all genotypes) ## GQ is rounded to the nearest integer to comply with the VCF spec index, gt = get_max_index(predictions, n_alleles) gq = int(np.around(ptrue...
73,078
def get_documentation_version_output(documentation_version: Optional[pulumi.Input[str]] = None, rest_api_id: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetDocumentationVersionResult]: """...
73,079
def parse_surveyvars_spss(spss_file, lgr=logger): """Extracts dat metadata from CDC YRBS SPSS files Extracts the survey questions and responses from the CDC YRBS SPSS file. Args: spss_file: SPSS file path Returns: survey_vars: an OrderedDict with survey variables The resu...
73,080
def false_only(t: Type) -> ProperType: """ Restricted version of t with only False-ish values """ t = get_proper_type(t) if not t.can_be_false: if state.strict_optional: # All values of t are True-ish, so there are no false values in it return UninhabitedType(line=t....
73,081
def make_timevect(num, step, start=0.0, dtype=None): """ Return a linearly spaced time vector. Remark: using this method is preferable to ``numpy.arange(start, start + num * step, step`` which may yield an incorrect number of samples due to numerical inaccuracy. Parameters ---------- num :...
73,082
def repr_tree(tree, viz, current_node, rec_depth, color_map, parameters): """ Represent a subtree on the GraphViz object Parameters ----------- tree Current subtree viz GraphViz object current_node Father node of the current subtree rec_depth Reached recu...
73,083
def get_object_versions(object_id: int) -> typing.List[Object]: """ Returns all versions of an object, sorted from oldest to newest. :param object_id: the ID of the existing object :return: the object versions :raise errors.ObjectDoesNotExistError: when no object with the given object ID ex...
73,084
def _transform_xml(xml, xslt_path): """ Converts the xml document from one metadata schema to another """ xslt_file = open('{0}/../misc/tools/{1}'.format(ROOT_PATH, xslt_path)) xslt_root = etree.parse(xslt_file) transform = etree.XSLT(xslt_root) return transform(xml)
73,085
def load_parser(d): """ For loadclass = 'POINTLOAD', 'LINELOAD' or 'AREALOAD' LINELOAD "B2141" "5F" TYPE "POINTF" DIR "GRAV" LC "LL_0.5" FVAL 15 RDIST 0.4 LINELOAD "B2109" "6F" TYPE "UNIFF" DIR "GRAV" LC "DL" FVAL 0.7 LINELOAD "C7" "GF" TYPE "TEMP" LC "THN" T -10 AREALO...
73,086
def neuron_create(num_inputs, activation, bias, layer_id, neuron_id): """ Create a neuron. :param num_inputs: input dimension :param activation: activation function. :param bias: bias for this activation. :param layer_id: :param neuron_id: :return: """ return {'weights'...
73,087
def load_config(config_name): """ Loads a json config file and returns a config dictionary. :param config_name: the path to the config json """ with open(config_name) as config_file: config = json.load(config_file) return config
73,088
def lowres_initial_dem_splines_fit( lowres_dsm_from_matches: xr.Dataset, lowres_initial_dem: xr.Dataset, origin: np.ndarray, time_direction_vector: np.ndarray, ext: int = 3, order: int = 3, ): """ This function takes 2 datasets containing DSM and models the difference between the two...
73,089
def main(): """ Execute action :return: None """ community_obj = NetAppONTAPClusterPeer() community_obj.apply()
73,090
def find_plugins(plugin_dir): """Finds all python files in the specified path and imports them. This is needed, if we want to detect automatically, which datastore and parser we can apply :param plugin_dir: path to the plugin directory""" plugin_files = [x[:-3] for x in os.listdir(plugin_dir) if x....
73,091
def test_bitext(input_path1, input_path2, output_path1, output_path2): """ Test the reconstruction of a bilingual corpus passing it through Tokenizer/Multitext pipeline. Example: text.test_bitext('data/en-fr/test.en-fr.en', 'data/en-fr/test.en-fr.fr', 'data/en-fr/test.en-fr.en-bi', 'data/en...
73,092
def conformer_sampling(zma, spc_info, thy_info, cnf_run_fs, cnf_save_fs, rid, script_str, overwrite, nsamp_par=(False, 3, 3, 1, 50, 50), tors_names=(), zrxn=None, two_stage=False, re...
73,093
def apply_pca(X, n_pc): """ Applying PCA """ U, S, V = pca(X) Z = project_data(X, U, n_pc) # attempt to recover the original structure (and later render it again): X_recovered = recover_data(Z, U, n_pc) return X_recovered
73,094
def wordform_output(IGC_folder, prop_names): """ Iterates over the input corpus and returns the word forms not found in the BIN, ordered by frequency. Can be altered for other gagnagrunnar or malheildir. """ dim = SQLDatabase(db_name='gagnagrunnar/bin_lemmur_ordmyndir.db') filters = SQLDa...
73,095
def collect_errors(source): """ :return list(Error) """ from robot.parsing.builders import get_model # TODO: Check if we should provide a curdir. model = get_model(source, curdir=None) errors_visitor = ErrorsVisitor() errors_visitor.visit(model) return errors_visitor.errors
73,096
def get_wordlist(): """Returns default HarSanitizer wordlist.""" hs = HarSanitizer() try: if WORDLIST_PATH[:4] == "http": wordlist_json = json.loads(urllib3.urlopen(WORDLIST_PATH).read()) wordlist = hs.load_wordlist(wordlist=wordlist_json) else: wordlist = hs.load_wordlist(wordlist_path...
73,097
def stop_build(build, request=None): """ Stop a specific build, by moving it into "ABORTING" state and then waiting for the worker to figure out how to kill it. """ if build is None or not build.is_stoppable(): return else: build.status = ABORTING projects = Project.objec...
73,098
def load_fraud(n_rows=None, verbose=True): """Load credit card fraud dataset. The fraud dataset can be used for binary classification problems. Arguments: n_rows (int): Number of rows from the dataset to return verbose (bool): Whether to print information about features and labels ...
73,099