content
stringlengths
22
815k
id
int64
0
4.91M
def parse_contact_name(row, name_cols, strict=False, type='person'): """Parses a person's name with probablepeople library Concatenates all the contact name columns into a single string and then attempts to parse it into standardized name components and return a subset of the name parts that are useful for...
11,800
def test_userkeys_to_json(): """ GIVEN a Settings model WHEN test the to_json method THEN check the id and more """ uk = UserKeysModel.by_id(1) uk_json = UserKeysModel.to_json(uk) assert uk.id == uk_json['id'] # FIXME : test that key exist, is a string and decrypt it via paramiko => ...
11,801
def write_six_img_grid_w_embedded_names( rgb_img: np.ndarray, pred: np.ndarray, label_img: np.ndarray, id_to_class_name_map: Mapping[int,str], save_fpath: str ) -> None: """ Create a 6-image tile grid with the following structure: ---------------------------------------------------------...
11,802
def build_operator_attribute_dicts(parameters, n_op, prefix="op_"): """ Extracts elements of parameters dict whose keys begin with prefix and generates a list of dicts. The values of the relevant elements of parameters must be either single values or a list of length n_op, or else an exception will be r...
11,803
def stop_spark_standalone(): """ Stop the Spark standalone cluster created from init_spark_standalone (master not specified). """ from zoo.util.spark import SparkRunner SparkRunner.stop_spark_standalone()
11,804
def write_log(title, message=''): """Write formatted log message to stderr.""" sys.stderr.write(''.join([ title.center(40).center(60, '-'), '\n', message ]))
11,805
def mock_data(rootdir, data_dir): """Build mock functional data from available atlases""" mock_dir = os.path.join(data_dir, 'mock') if not os.path.exists(mock_dir): subprocess.run("python setup_mock_data.py".split(), cwd=rootdir) return mock_dir
11,806
def showapi(): """Shows the official API available in jasyscript.py.""" from jasy.core.Inspect import generateApi Console.info(generateApi(__api__))
11,807
def get_peer_addr(ifname): """Return the peer address of given peer interface. None if address not exist or not a peer-to-peer interface. """ for addr in IP.get_addr(label=ifname): attrs = dict(addr.get('attrs', [])) if 'IFA_ADDRESS' in attrs: return attrs['IFA_ADDRESS']
11,808
def eiffel_artifact_created_event(): """Eiffel artifact created event.""" return { "meta": { "id": "7c2b6c13-8dea-4c99-a337-0490269c374d", "time": 1575981274307, "type": "EiffelArtifactCreatedEvent", "version": "3.0.0", }, "links": [], ...
11,809
def _hash(input_data, initVal=0): """ hash() -- hash a variable-length key into a 32-bit value k : the key (the unaligned variable-length array of bytes) len : the length of the key, counting by bytes level : can be any 4-byte value Returns a 32-bit value. Every bit of the key affec...
11,810
def main(): """ Main entry function. Parameters ---------- :return: - """ print("> Allergens analysis <") # ################# # initial processing # ################# load_undesirables() # initial_processing() df_open_food_facts = pd.read_csv(datasets_intermediate...
11,811
def read_config_option(key, expected_type=None, default_value=None): """Read the specified value from the configuration file. Args: key: the name of the key to read from the config file. expected_type: read the config option as the specified type (if specified) default_value: if the key...
11,812
def simple_password(request): """ Checks a password """ if request.method == "POST": form = PasswordForm(data=request.POST) if form.is_valid(): # TODO: set session with better param request.session["simple_auth"] = True return redirect(form.cleaned_dat...
11,813
def removeKeys(array: dict = None, remove: Any = None) -> dict: """ Removes keys from array by given remove value. :param array: dict[Any: Any] :param remove: Any :return: - sorted_dict - dict[Any: Any] """ if remove is None: remove = [] try: sorted_dic...
11,814
def affine2boxmesh(affines): """ :param affines: (n_parts, 6), range (0, 1) :return: """ from trimesh.path.creation import box_outline from trimesh.path.util import concatenate n_parts = len(affines) colors = [[0, 0, 255, 255], # blue [0, 255, 0, 255], # green ...
11,815
def _select_index_code(code): """ 1 - sh 0 - sz """ code = str(code) if code[0] == '3': return 0 return 1
11,816
def get_install_agent_cmd(): """Get OS specific command to install Telegraf agent.""" agent_pkg_deb = "https://packagecloud.io/install/repositories/" \ "wavefront/telegraf/script.deb.sh" agent_pkg_rpm = "https://packagecloud.io/install/repositories/" \ "wavefront/tele...
11,817
def unpack(manifests: LocalManifestLists) -> Tuple[ServerManifests, bool]: """Convert `manifests` to `ServerManifests` for internal processing. Returns `False` unless all resources in `manifests` are unique. For instance, returns False if two files define the same namespace or the same deployment. ...
11,818
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None): """Set up the switch from config.""" if DATA_KEY not in hass.data: hass.data[DATA_KEY] = {} host = config[CONF_HOST] token = config[CONF_TOKEN] name = config[CONF_NAME] model = config.get(CONF_MODEL) ...
11,819
def process_generate_metric_alarms_event(event): """Handles a new event request Placeholder copied from alert_controller implementation """ LOG.info(str(event)) return create_response(200, body="Response to HealthCheck")
11,820
def check_if_usl_forecast_exists(config, stid, run, forecast_date): """ Checks the parent USL directory to see if USL has run for specified stid and run time. This avoids the server automatically returning a "close enough" date instead of an "Error 300: multiple choices." """ run_date = (forecast_da...
11,821
def get_query_segment_info(collection_name, timeout=None, using="default"): """ Notifies Proxy to return segments information from query nodes. :param collection_name: A string representing the collection to get segments info. :param timeout: An optional duration of time in seconds to allow for the RPC...
11,822
def IoU(pred, gt, n_classes, all_iou=False): """Computes the IoU by class and returns mean-IoU""" # print("IoU") iou = [] for i in range(n_classes): if np.sum(gt == i) == 0: iou.append(np.NaN) continue TP = np.sum(np.logical_and(pred == i, gt == i)) FP = n...
11,823
def from_torchvision(vision_transform, p=1): """Takes in an arbitary torchvision tranform and wrap it such that it can be applied to a list of images of shape HxWxC Returns a callable class that takes in list of images and target as input NOTE: Due to implementation difficuities, in order ...
11,824
def is_valid(inputted): """ Essa função irá verificar o QueryDict trago pelo método POST do nosso frontend e fazer uma verificação dos campos an tes de persistir os dados no banco de dados. :param inputted: Query Dict trago pelo POST :return: Um valor booleano """ for key in inputted.keys():...
11,825
def get_ports(context, project_id=None): """Returns all ports of VMs in EOS-compatible format. :param project_id: globally unique neutron tenant identifier """ session = context.session model = db_models.AristaProvisionedVms if project_id: all_ports = (session.query(model). ...
11,826
def WriteSchemaMarkdown(fileName): """ Iterate on the global `OrderedDict` of `EoCalib` sub-classes and write description of each to a markdown file """ with open(fileName, 'w') as fout: for key, val in EO_CALIB_CLASS_DICT.items(): fout.write("## %s\n" % key) val.writeMarkdo...
11,827
def dispatcher3(request, route_table): """ return an instance of a second DispatcherActor with another name that is not launched the teardown of this fixtures terminate the actor (in case it was started and close its socket) """ dispatcher_actor = DispatcherActor( 'test_dispatcher2-', ...
11,828
def _HMAC(K, C, Mode=hashlib.sha1): """ Generate an HMAC value. The default mode is to generate an HMAC-SHA-1 value w/ the SHA-1 algorithm. :param K: shared secret between client and server. Each HOTP generator has a different and unique secret K. :type K: bytes :param C: 8-byte co...
11,829
def get_reference(planet_name): """ Return reference for a given planet's orbit fit Args: planet_name (str): name of planet. no space Returns: reference (str): Reference of orbit fit """ planet_name = planet_name.lower() if planet_name not in post_dict: raise Value...
11,830
def makedirs(name, *args, **kwargs): """Shim to transparently backport exist_ok to Python < 3.2""" if "exist_ok" in kwargs and python_lt(3, 2): if not os.path.exists(name): os.makedirs(name, *args, **kwargs) else: os.makedirs(name, *args, **kwargs)
11,831
def DefaultPortIfAvailable(): """Returns default port if available. Raises: EmulatorArgumentsError: if port is not available. Returns: int, default port """ if portpicker.is_port_free(_DEFAULT_PORT): return _DEFAULT_PORT else: raise EmulatorArgumentsError( 'Default emulator port [{...
11,832
def mock_hub(hass): """Mock hub.""" mock_integration(hass, MockModule(DOMAIN)) hub = mock.MagicMock() hub.name = "hub" hass.data[DOMAIN] = {DEFAULT_HUB: hub} return hub
11,833
def deferred_setting(name, default): """ Returns a function that calls settings with (name, default) """ return lambda: setting(name, default)
11,834
def watch_cli(optimization_id): """Watch the status of a bespoke optimization.""" pretty.install() console = rich.get_console() print_header(console) from openff.bespokefit.executor import wait_until_complete wait_until_complete(optimization_id)
11,835
def draw_donut(display, coord, box_size, color, bg_color): """Draw a donut at the given location.""" left, top = coord half = int(box_size * 0.5) quarter = int(box_size * 0.25) center = (left + half, top + half) pygame.draw.circle(display, color, center, half - 5) pygame.draw.circle(display...
11,836
def extends_dict(target, source): """ Will copy every key and value of source in target if key is not present in target """ for key, value in source.items(): if key not in target: target[key] = value elif type(target[key]) is dict: extends_dict(target[key], value) ...
11,837
def get_maps_interface_class(zep_inp): """ Takes the input of zephyrus and return the maps of interfaces to classes and viceversa """ interface_to_classes = {} class_to_interfaces = {} for i in zep_inp["components"].keys(): class_name = i.split(settings.SEPARATOR)[-1] interfaces = zep_inp["compone...
11,838
def plextv_resources_base_fixture(): """Load base payload for plex.tv resources and return it.""" return load_fixture("plex/plextv_resources_base.xml")
11,839
def _auth(machine='desi.lbl.gov'): """Get authentication credentials. """ from netrc import netrc from requests.auth import HTTPDigestAuth n = netrc() try: u,foo,p = n.authenticators(machine) except: raise ValueError('Unable to get user/pass from $HOME/.netrc for {}'.format(m...
11,840
def test_handle_html_dynmamic_with_encoding(): """Test the handler converting dynamic HTML to utf-8 encoding.""" with open(TEST_VALUE_SOURCES["html_dynamic"]) as f: test_value = f.read() test_bytes = bytes(test_value, ALT_ENCODING) with open(TEST_VALUE_SOURCES["html_dynamic_bytes"], "rb") as f: ...
11,841
def relative_date_add(date_rule: str, strict: bool = False) -> float: """Change the string in date rule format to the number of days. E.g 1d to 1, 1y to 365, 1m to 30, -1w to -7""" days = '' if re.search(DateRuleReg, date_rule) is not None: res = re.search(DateRuleReg, date_rule) date_str =...
11,842
def store_survey_elements(survey, recom, df_fri, df_frii): """Match returned recommentations ids with ObjectCatalog entries Parameters ---------- survey: zooniverse_web.models.Survey recom: acton.proto.wrappers.Recommendations df_fri: pandas.DataFrame df_frii: pandas.DataFrame """ #...
11,843
def to_frames_using_nptricks(src: np.ndarray, window_size: int, stride: int) -> np.ndarray: """ np.ndarray をフレーム分けするプリミティブな実装で,分割に`np.lib.stride_tricks.as_strided`関数を使用しており,indexingを使用する`to_frames_using_index`より高速である. Parameters ---------- src: np.ndarray splited source. window_size: i...
11,844
def global_fit( model_constructor, pdf_transform=False, default_rtol=1e-10, default_atol=1e-10, default_max_iter=int(1e7), learning_rate=1e-6, ): """ Wraps a series of functions that perform maximum likelihood fitting in the `two_phase_solver` method found in the `fax` python module....
11,845
def get_connection_string(storage_account_name): """ Checks the environment for variable named AZ_<STORAGE_ACCOUNT_NAME> and returns the corresponding connection string. Raises a ``ConnectionStringNotFound`` exception if environment variable is missing """ conn_string = os.environ.get("AZ_" + ...
11,846
def reorder_task( token: 'auth.JWT', task_id: 'typevars.ObjectID', before_id: 'Optional[typevars.ObjectID]' = None, after_id: 'Optional[typevars.ObjectID]' = None ) -> 'List[models.Task]': """Change the position of the task in the list.""" if before_id is None and after_id is None: raise uti...
11,847
def get_ldpc_code_params(ldpc_design_filename): """ Extract parameters from LDPC code design file. Parameters ---------- ldpc_design_filename : string Filename of the LDPC code design file. Returns ------- ldpc_code_params : dictionary Parameters of the LDPC code. "...
11,848
def find_collection(*, collection, name): """ Looks through the pages of a collection for a resource with the specified name. Returns it, or if not found, returns None """ if isinstance(collection, ProjectCollection): try: # try to use search if it is available # cal...
11,849
def terms_documents_matrix_ticcl_frequency(in_files): """Returns a terms document matrix and related objects of a corpus A terms document matrix contains frequencies of wordforms, with wordforms along one matrix axis (columns) and documents along the other (rows). Inputs: in_files: list of tic...
11,850
def cvt_continue_stmt(node: pytree.Base, ctx: Ctx) -> ast_cooked.Base: """continue_stmt: 'continue'""" #-# Continue assert ctx.is_REF, [node] return ast_cooked.ContinueStmt()
11,851
def nth_even(n): """Function I wrote that returns the nth even number.""" return (n * 2) - 2
11,852
def _has__of__(obj): """Check whether an object has an __of__ method for returning itself in the context of a container.""" # It is necessary to check both the type (or we get into cycles) # as well as the presence of the method (or mixins of Base pre- or # post-class-creation as done in, e.g., ...
11,853
def diff_main(args, output): """ Different stats depending on the args :param output: :return: """ f = open(os.path.join(output, "avg_methylation_60.out"), "w") all_cpg_format_file_paths = create_chr_paths_dict(args) for chr in tqdm(all_cpg_format_file_paths): v = methylation_di...
11,854
def grayscale(img): """ Applies the Grayscale transform This will return an image with only one color channel but NOTE: to see the returned image as grayscale (assuming your grayscaled image is called 'gray') you should call plt.imshow(gray, cmap='gray') """ return cv2.cvtColor(img, cv2...
11,855
def get_pageinfo(response, tracktype='recenttracks'): """Check how many pages of tracks the user have.""" xmlpage = ET.fromstring(response) totalpages = xmlpage.find(tracktype).attrib.get('totalPages') return int(totalpages)
11,856
def test_delete_not_contained_2(multi_tree): """Test that delete leaves the list intact if value not in tree.""" multi_tree.instance.delete(9999999999999) assert multi_tree.instance.size() == multi_tree.size
11,857
def _create_dispatcher_class(cls, classname, bases, dict_): """Create a :class:`._Dispatch` class corresponding to an :class:`.Events` class.""" # there's all kinds of ways to do this, # i.e. make a Dispatch class that shares the '_listen' method # of the Event class, this is the straight monkeypat...
11,858
def MIN(*args): """Return the minimum of a range or list of Number or datetime""" return _group_function(min, *args)
11,859
def GF(order, irreducible_poly=None, primitive_element=None, verify_irreducible=True, verify_primitive=True, mode="auto", target="cpu"): """ Factory function to construct a Galois field array class of type :math:`\\mathrm{GF}(p^m)`. The created class will be a subclass of :obj:`galois.FieldArray` with meta...
11,860
def remove_fields_with_value_none(fields: typing.Dict) -> typing.Dict: """ Remove keys whose value is none :param fields: the fields to clean :return: a copy of fields, without the none values """ fields = dict((key, value) for key, value in fields.items() if value is not None)...
11,861
def _register_services(hass): """Register Mixergy services.""" async def mixergy_set_charge(call): tasks = [ tank.set_target_charge(call.data) for tank in hass.data[DOMAIN].values() if isinstance(tank, Tank) ] results = await asyncio.gather(*tasks) ...
11,862
def get_repository(repository_id): """ Get the repository service address from accounts service for storing data. :param repository_id: the repository ID :return: url of the repository url :raise: HTTPError """ client = API(options.url_accounts, ssl_options=ssl_server_options()) try...
11,863
def test_all_fields_exist_in_the_json_file(): """ Sprawdź poprawność samego pliku. """ with open(SLOWO_NA_DZIS_PATH, 'r', encoding='UTF-8') as plik: slowo_na_dzis = json.load(plik) for cytat in slowo_na_dzis: pprint(cytat) assert_quote_slowo_na_dzis_json(cytat)
11,864
def make_values(params, point): #240 (line num in coconut source) """Return a dictionary with the values replaced by the values in point, where point is a list of the values corresponding to the sorted params.""" #242 (line num in coconut source) values = {} #243 (line num in coconut source) for i, k...
11,865
def elbow_method(data): """ This function will compute elbow method and generate elbow visualization :param data: 2 columns dataframe for cluster analysis :return: Plotly Figures """ distortions = [] K = range(1, 10) for k in K: elbow_kmean = model_kmeans(data, k) ...
11,866
def _configure_logging(verbose=False, debug=False): """Configure the log global, message format, and verbosity settings.""" overall_level = logging.DEBUG if debug else logging.INFO logging.basicConfig( format=('{levelname[0]}{asctime}.{msecs:03.0f} {thread} ' '{filename}:{lineno}] {m...
11,867
def sa_middleware(key: str = DEFAULT_KEY) -> 'Callable': """ SQLAlchemy asynchronous middleware factory. """ @middleware async def sa_middleware_(request: 'Request', handler: 'Callable')\ -> 'StreamResponse': if key in request: raise DuplicateRequestKeyError(key) Ses...
11,868
def load_kmeans_dataset(): """A dataset with two 'time slices' - a slice with two clear clusters along the x axis _now_ timestamp and - a slice with two clear clusters along the y axis with tomorrow's timestamp This will serve at testing if the when clause was applied correctly""" kmeans_example = ...
11,869
def _check_id_format(feature_id): """ This function check the id format. """ id_format = "^(\w+).+\S$" if not re.match(id_format, feature_id): msg = "The id field cannot contains whitespaces." raise exceptions.BadRequest({"message": msg})
11,870
def dice_loss(y_true, y_pred): """ dice_loss """ smooth = 1. intersection = K.sum(K.abs(y_true * y_pred), axis=-1) dice_coef = (2. * intersection + smooth) / (K.sum(K.square(y_true),-1) + \ K.sum(K.square(y_pred),-1) + smooth) return 1 - dice_coef
11,871
def webdriver_init(mobile): """ Initialize a mobile/desktop web driver. This initialize a web driver with a default user agent regarding the mobile demand. Default uer agents are defined by MOBILE_USER_AGENT and DESKTOP_USER_AGENT. :param mobile: The mobile flag :type conn:...
11,872
def calculate_file_hash(f, alg, buf_size): """BUF_SIZE - 64 kb need for large file""" h = hashlib.new(alg) for chunk in iter(lambda: f.read(buf_size), b""): h.update(chunk) return h.hexdigest()
11,873
def update(A, B, DA, DB, f, k, delta_t): """Apply the Gray-Scott update formula""" # compute the diffusion part of the update diff_A = DA * apply_laplacian(A) diff_B = DB * apply_laplacian(B) # Apply chemical reaction reaction = A*B**2 diff_A -= reaction diff_B += reaction # A...
11,874
def sha512(data: typing.Optional[bytes] = None): """Returns a sha512 hash object; optionally initialized with a string.""" if data is None: return hashlib.sha512() return hashlib.sha512(data)
11,875
def delete_novel( id_or_url: str, novel_service: BaseNovelService = Provide[Application.services.novel_service], path_service: BasePathService = Provide[Application.services.path_service], ): """delete all records of novel. this includes chapters, and assets""" try: novel = cli_helpers.get_n...
11,876
def combine_small_file_to_big(): """Merge multiple csv into one based on header https://stackoverflow.com/questions/44791212/concatenating-multiple-csv-files-into-a-single-csv-with-the-same-header-python/44791368 """ #import csv files from folder path = r'./' allFiles = glob.glob(path +...
11,877
def _circle_ci_pr(): """Get the current CircleCI pull request (if any). Returns: Optional[int]: The current pull request ID. """ try: return int(os.getenv(env.CIRCLE_CI_PR_NUM, '')) except ValueError: return None
11,878
def get_entropy_of_maxes(): """ Specialized code for retrieving guesses and confidence of largest model of each type from the images giving largest entropy. :return: dict containing the models predictions and confidence, as well as the correct label under "y". """ high_entropy_list = get_high_en...
11,879
def get_all_links() -> List[Dict[str, Any]]: """Returns all links as an iterator""" return get_entire_collection(LINKS_COLLECTION)
11,880
def agent(states, actions): """ creating a DNN using keras """ model = Sequential() model.add(Flatten(input_shape=(1, states))) model.add(Dense(24, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(24, activation='relu')) model.add(Dense(actions, activation=...
11,881
def search_configs(mwdb, formatter, query, limit): """ Search configs """ recent = islice(mwdb.search_configs(query), limit) formatter.print_list(recent, formatter.format_config_list)
11,882
def exercise_2(): """Get Variable Value""" price = 10 print(price)
11,883
def get_package_nvr_from_spec(spec_file): """ Return a list of the NVR required for a given spec file :param spec_file: The path to a spec file :type spec_file: str :return: list of nevra that should be built for that spec file :rtype: str """ # Get the dep name & version spec = rpm....
11,884
def rbo_ext(S, T, p): """Extrapolated RBO value as defined in equation (30). Implementation handles uneven lists but not ties. """ if len(S) > len(T): L, S = S, T else: L, S = T, S l, s = len(L), len(S) xl = overlap(L, S, l) xs = overlap(L, S, s) sum1 = sum(overlap(...
11,885
def index(request): """ View of index page """ title = _("Home") posts = Post.objects.all().order_by('-timestamp')[:5] return render(request, 'dashboard/index.html', locals())
11,886
def incremental_str_maker(str_format='{:03.f}'): """Make a function that will produce a (incrementally) new string at every call.""" i = 0 def mk_next_str(): nonlocal i i += 1 return str_format.format(i) return mk_next_str
11,887
def get_time_slider_range(highlighted=True, withinHighlighted=True, highlightedOnly=False): """Return the time range from Maya's time slider. Arguments: highlighted (bool): When True if will return a selected frame range (if there's any se...
11,888
def update_IW(hyp_D_prev, xikk, xk, Pik_old): """ Do an update of Norm-IW conjugate in an exponential form. """ suff_D = get_suff_IW_conj(xikk, xk, Pik_old) hyp_D = hyp_D_prev + suff_D Dik = get_E_IW_hyp(hyp_D) return Dik, hyp_D
11,889
def test_existing_path_FileLink(): """FileLink: Calling _repr_html_ functions as expected on existing filepath """ tf = NamedTemporaryFile() fl = display.FileLink(tf.name) actual = fl._repr_html_() expected = "<a href='files/%s' target='_blank'>%s</a><br>" % (tf.name,tf.name) nt.assert_equal...
11,890
def compute_state(observations, configuration): """ :param observations: :param configuration: :return StateTensor: """ StateTensorType = configuration.STATE_TYPE return StateTensorType([observations])
11,891
def supports_transfer_syntax(transfer_syntax: pydicom.uid.UID) -> bool: """Return ``True`` if the handler supports the `transfer_syntax`. Parameters ---------- transfer_syntax : uid.UID The Transfer Syntax UID of the *Pixel Data* that is to be used with the handler. """ return t...
11,892
def test_item_many(testapp, amount): """reStructuredText processor has to work with stream.""" stream = restructuredtext.process( testapp, [ holocron.Item( { "content": "the key is **%d**" % i, "destination": pathlib.Path("1.rs...
11,893
def enhance_user(user, json_safe=False): """ Adds computed attributes to AD user results Args: user: A dictionary of user attributes json_safe: If true, converts binary data into base64, And datetimes into human-readable strings Returns: An enhanced dictionary of user at...
11,894
def create_data(namespace_id, ocs_client): """Creates sample data for the script to use""" double_type = SdsType(id='doubleType', sdsTypeCode=SdsTypeCode.Double) datetime_type = SdsType( id='dateTimeType', sdsTypeCode=SdsTypeCode.DateTime) pressure_property = SdsTypeProperty(id='pressure', sds...
11,895
def bootstrap_aws(c): """Bootstrap AWS account for use with cdk.""" c.run("cdk bootstrap aws://$AWS_ACCOUNT/$AWS_DEFAULT_REGION")
11,896
def enhanced_feature_extractor_digit(datum): """Feature extraction playground for digits. You should return a util.Counter() of features for this datum (datum is of type samples.Datum). ## DESCRIBE YOUR ENHANCED FEATURES HERE... """ features = basic_feature_extractor_digit(datum) "*** YOU...
11,897
def train_8x8_digits(p=0.9, h=None, noise_strength=0, n_images=2, plot_cve=False): """ Built in autoencoder training and image showing. Uses mnist 8x8 digits. Change noise strength to a value between 0 and 1 to add noise to the test samples. :param p: Total Variance Explained to be used :param h: N...
11,898
def test(): """Run tests""" install() test_setup() sh("%s %s" % (PYTHON, TEST_SCRIPT))
11,899