_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q267000
Conversation.handle_request
test
def handle_request(self, request: dict) -> dict: """Routes Alexa requests to appropriate handlers. Args: request: Alexa request. Returns: response: Response conforming Alexa response specification. """ request_type = request['request']['type'] req...
python
{ "resource": "" }
q267001
Conversation._act
test
def _act(self, utterance: str) -> list: """Infers DeepPavlov agent with raw user input extracted from Alexa request. Args: utterance: Raw user input extracted from Alexa request. Returns: response: DeepPavlov agent response. """ if self.stateful: ...
python
{ "resource": "" }
q267002
Conversation._generate_response
test
def _generate_response(self, response: dict, request: dict) -> dict: """Populates generated response with additional data conforming Alexa response specification. Args: response: Raw user input extracted from Alexa request. request: Alexa request. Returns: re...
python
{ "resource": "" }
q267003
Conversation._handle_intent
test
def _handle_intent(self, request: dict) -> dict: """Handles IntentRequest Alexa request. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification. """ intent_name = self.config['intent_name'] ...
python
{ "resource": "" }
q267004
Conversation._handle_launch
test
def _handle_launch(self, request: dict) -> dict: """Handles LaunchRequest Alexa request. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification. """ response = { 'response': { ...
python
{ "resource": "" }
q267005
Conversation._handle_unsupported
test
def _handle_unsupported(self, request: dict) -> dict: """Handles all unsupported types of Alexa requests. Returns standard message. Args: request: Alexa request. Returns: response: "response" part of response dict conforming Alexa specification. """ respo...
python
{ "resource": "" }
q267006
Struct._repr_pretty_
test
def _repr_pretty_(self, p, cycle): """method that defines ``Struct``'s pretty printing rules for iPython Args: p (IPython.lib.pretty.RepresentationPrinter): pretty printer object cycle (bool): is ``True`` if pretty detected a cycle """ if cycle: p.tex...
python
{ "resource": "" }
q267007
elmo_loss2ppl
test
def elmo_loss2ppl(losses: List[np.ndarray]) -> float: """ Calculates perplexity by loss Args: losses: list of numpy arrays of model losses Returns: perplexity : float """ avg_loss = np.mean(losses) return float(np.exp(avg_loss))
python
{ "resource": "" }
q267008
build_model
test
def build_model(config: Union[str, Path, dict], mode: str = 'infer', load_trained: bool = False, download: bool = False, serialized: Optional[bytes] = None) -> Chainer: """Build and return the model described in corresponding configuration file.""" config = parse_config(config) ...
python
{ "resource": "" }
q267009
interact_model
test
def interact_model(config: Union[str, Path, dict]) -> None: """Start interaction with the model described in corresponding configuration file.""" model = build_model(config) while True: args = [] for in_x in model.in_x: args.append((input('{}::'.format(in_x)),)) # ch...
python
{ "resource": "" }
q267010
predict_on_stream
test
def predict_on_stream(config: Union[str, Path, dict], batch_size: int = 1, file_path: Optional[str] = None) -> None: """Make a prediction with the component described in corresponding configuration file.""" if file_path is None or file_path == '-': if sys.stdin.isatty(): raise RuntimeError('...
python
{ "resource": "" }
q267011
read_infile
test
def read_infile(infile: Union[Path, str], from_words=False, word_column: int = WORD_COLUMN, pos_column: int = POS_COLUMN, tag_column: int = TAG_COLUMN, max_sents: int = -1, read_only_words: bool = False) -> List[Tuple[List, Union[List, None]]]: """Reads input file in ...
python
{ "resource": "" }
q267012
fn_from_str
test
def fn_from_str(name: str) -> Callable[..., Any]: """Returns a function object with the name given in string.""" try: module_name, fn_name = name.split(':') except ValueError: raise ConfigError('Expected function description in a `module.submodules:function_name` form, but got `{}`' ...
python
{ "resource": "" }
q267013
register_metric
test
def register_metric(metric_name: str) -> Callable[..., Any]: """Decorator for metric registration.""" def decorate(fn): fn_name = fn.__module__ + ':' + fn.__name__ if metric_name in _REGISTRY and _REGISTRY[metric_name] != fn_name: log.warning('"{}" is already registered as a metric n...
python
{ "resource": "" }
q267014
get_metric_by_name
test
def get_metric_by_name(name: str) -> Callable[..., Any]: """Returns a metric callable with a corresponding name.""" if name not in _REGISTRY: raise ConfigError(f'"{name}" is not registered as a metric') return fn_from_str(_REGISTRY[name])
python
{ "resource": "" }
q267015
DecayType.from_str
test
def from_str(cls, label: str) -> int: """ Convert given string label of decay type to special index Args: label: name of decay type. Set of values: `"linear"`, `"cosine"`, `"exponential"`, `"onecycle"`, `"trapezoid"`, `["polynomial", K]`, where K is ...
python
{ "resource": "" }
q267016
LRScheduledModel._get_best
test
def _get_best(values: List[float], losses: List[float], max_loss_div: float = 0.9, min_val_div: float = 10.0) -> float: """ Find the best value according to given losses Args: values: list of considered values losses: list of obtained loss values corres...
python
{ "resource": "" }
q267017
Embedder._encode
test
def _encode(self, tokens: List[str], mean: bool) -> Union[List[np.ndarray], np.ndarray]: """ Embed one text sample Args: tokens: tokenized text sample mean: whether to return mean embedding of tokens per sample Returns: list of embedded tokens or arr...
python
{ "resource": "" }
q267018
read_requirements
test
def read_requirements(): """parses requirements from requirements.txt""" reqs_path = os.path.join(__location__, 'requirements.txt') with open(reqs_path, encoding='utf8') as f: reqs = [line.strip() for line in f if not line.strip().startswith('#')] names = [] links = [] for req in reqs: ...
python
{ "resource": "" }
q267019
sk_log_loss
test
def sk_log_loss(y_true: Union[List[List[float]], List[List[int]], np.ndarray], y_predicted: Union[List[List[float]], List[List[int]], np.ndarray]) -> float: """ Calculates log loss. Args: y_true: list or array of true values y_predicted: list or array of predicted values ...
python
{ "resource": "" }
q267020
export2hub
test
def export2hub(weight_file, hub_dir, options): """Exports a TF-Hub module """ spec = make_module_spec(options, str(weight_file)) try: with tf.Graph().as_default(): module = hub.Module(spec) with tf.Session() as sess: sess.run(tf.global_variables_initial...
python
{ "resource": "" }
q267021
show_details
test
def show_details(item_data: Dict[Any, Any]) -> str: """Format catalog item output Parameters: item_data: item's attributes values Returns: [rich_message]: list of formatted rich message """ txt = "" for key, value in item_data.items(): txt += "**" + str(key) + "**" + ...
python
{ "resource": "" }
q267022
make_agent
test
def make_agent() -> EcommerceAgent: """Make an agent Returns: agent: created Ecommerce agent """ config_path = find_config('tfidf_retrieve') skill = build_model(config_path) agent = EcommerceAgent(skills=[skill]) return agent
python
{ "resource": "" }
q267023
main
test
def main(): """Parse parameters and run ms bot framework""" args = parser.parse_args() run_ms_bot_framework_server(agent_generator=make_agent, app_id=args.ms_id, app_secret=args.ms_secret, stateful=True)
python
{ "resource": "" }
q267024
download
test
def download(dest_file_path: [List[Union[str, Path]]], source_url: str, force_download=True): """Download a file from URL to one or several target locations Args: dest_file_path: path or list of paths to the file destination files (including file name) source_url: the source URL force_d...
python
{ "resource": "" }
q267025
untar
test
def untar(file_path, extract_folder=None): """Simple tar archive extractor Args: file_path: path to the tar file to be extracted extract_folder: folder to which the files will be extracted """ file_path = Path(file_path) if extract_folder is None: extract_folder = file_path...
python
{ "resource": "" }
q267026
download_decompress
test
def download_decompress(url: str, download_path: [Path, str], extract_paths=None): """Download and extract .tar.gz or .gz file to one or several target locations. The archive is deleted if extraction was successful. Args: url: URL for file downloading download_path: path to the directory wh...
python
{ "resource": "" }
q267027
update_dict_recursive
test
def update_dict_recursive(editable_dict: dict, editing_dict: dict) -> None: """Updates dict recursively You need to use this function to update dictionary if depth of editing_dict is more then 1 Args: editable_dict: dictionary, that will be edited editing_dict: dictionary, that contains ed...
python
{ "resource": "" }
q267028
path_set_md5
test
def path_set_md5(url): """Given a file URL, return a md5 query of the file Args: url: a given URL Returns: URL of the md5 file """ scheme, netloc, path, query_string, fragment = urlsplit(url) path += '.md5' return urlunsplit((scheme, netloc, path, query_string, fragment))
python
{ "resource": "" }
q267029
set_query_parameter
test
def set_query_parameter(url, param_name, param_value): """Given a URL, set or replace a query parameter and return the modified URL. Args: url: a given URL param_name: the parameter name to add param_value: the parameter value Returns: URL with the added parameter """ ...
python
{ "resource": "" }
q267030
PlainText.alexa
test
def alexa(self) -> dict: """Returns Amazon Alexa compatible state of the PlainText instance. Creating Amazon Alexa response blank with populated "outputSpeech" and "card sections. Returns: response: Amazon Alexa representation of PlainText state. """ respons...
python
{ "resource": "" }
q267031
Button.json
test
def json(self) -> dict: """Returns json compatible state of the Button instance. Returns: control_json: Json representation of Button state. """ content = {} content['name'] = self.name content['callback'] = self.callback self.control_json['content'] ...
python
{ "resource": "" }
q267032
Button.ms_bot_framework
test
def ms_bot_framework(self) -> dict: """Returns MS Bot Framework compatible state of the Button instance. Creates MS Bot Framework CardAction (button) with postBack value return. Returns: control_json: MS Bot Framework representation of Button state. """ card_action ...
python
{ "resource": "" }
q267033
ButtonsFrame.json
test
def json(self) -> dict: """Returns json compatible state of the ButtonsFrame instance. Returns json compatible state of the ButtonsFrame instance including all nested buttons. Returns: control_json: Json representation of ButtonsFrame state. """ content = {}...
python
{ "resource": "" }
q267034
ButtonsFrame.ms_bot_framework
test
def ms_bot_framework(self) -> dict: """Returns MS Bot Framework compatible state of the ButtonsFrame instance. Creating MS Bot Framework activity blank with RichCard in "attachments". RichCard is populated with CardActions corresponding buttons embedded in ButtonsFrame. Returns: ...
python
{ "resource": "" }
q267035
squad_v2_f1
test
def squad_v2_f1(y_true: List[List[str]], y_predicted: List[str]) -> float: """ Calculates F-1 score between y_true and y_predicted F-1 score uses the best matching y_true answer The same as in SQuAD-v2.0 Args: y_true: list of correct answers (correct answers are represented by list of stri...
python
{ "resource": "" }
q267036
recall_at_k
test
def recall_at_k(y_true: List[int], y_pred: List[List[np.ndarray]], k: int): """ Calculates recall at k ranking metric. Args: y_true: Labels. Not used in the calculation of the metric. y_predicted: Predictions. Each prediction contains ranking score of all ranking candidates for ...
python
{ "resource": "" }
q267037
check_gpu_existence
test
def check_gpu_existence(): r"""Return True if at least one GPU is available""" global _gpu_available if _gpu_available is None: sess_config = tf.ConfigProto() sess_config.gpu_options.allow_growth = True try: with tf.Session(config=sess_config): device_list...
python
{ "resource": "" }
q267038
_parse_config_property
test
def _parse_config_property(item: _T, variables: Dict[str, Union[str, Path, float, bool, None]]) -> _T: """Recursively apply config's variables values to its property""" if isinstance(item, str): return item.format(**variables) elif isinstance(item, list): return [_parse_config_property(item,...
python
{ "resource": "" }
q267039
parse_config
test
def parse_config(config: Union[str, Path, dict]) -> dict: """Read config's variables and apply their values to all its properties""" if isinstance(config, (str, Path)): config = read_json(find_config(config)) variables = { 'DEEPPAVLOV_PATH': os.getenv(f'DP_DEEPPAVLOV_PATH', Path(__file__).p...
python
{ "resource": "" }
q267040
expand_path
test
def expand_path(path: Union[str, Path]) -> Path: """Convert relative paths to absolute with resolving user directory.""" return Path(path).expanduser().resolve()
python
{ "resource": "" }
q267041
from_params
test
def from_params(params: Dict, mode: str = 'infer', serialized: Any = None, **kwargs) -> Component: """Builds and returns the Component from corresponding dictionary of parameters.""" # what is passed in json: config_params = {k: _resolve(v) for k, v in params.items()} # get component by reference (if a...
python
{ "resource": "" }
q267042
Bot.run
test
def run(self) -> None: """Thread run method implementation.""" while True: request = self.input_queue.get() response = self._handle_request(request) self.output_queue.put(response)
python
{ "resource": "" }
q267043
Bot._del_conversation
test
def _del_conversation(self, conversation_key: str) -> None: """Deletes Conversation instance. Args: conversation_key: Conversation key. """ if conversation_key in self.conversations.keys(): del self.conversations[conversation_key] log.info(f'Deleted c...
python
{ "resource": "" }
q267044
Bot._refresh_valid_certs
test
def _refresh_valid_certs(self) -> None: """Conducts cleanup of periodical certificates with expired validation.""" self.timer = Timer(REFRESH_VALID_CERTS_PERIOD_SECS, self._refresh_valid_certs) self.timer.start() expired_certificates = [] for valid_cert_url, valid_cert in self....
python
{ "resource": "" }
q267045
Bot._verify_request
test
def _verify_request(self, signature_chain_url: str, signature: str, request_body: bytes) -> bool: """Conducts series of Alexa request verifications against Amazon Alexa requirements. Args: signature_chain_url: Signature certificate URL from SignatureCertChainUrl HTTP header. sig...
python
{ "resource": "" }
q267046
Bot._handle_request
test
def _handle_request(self, request: dict) -> dict: """Processes Alexa requests from skill server and returns responses to Alexa. Args: request: Dict with Alexa request payload and metadata. Returns: result: Alexa formatted or error response. """ request_bo...
python
{ "resource": "" }
q267047
cls_from_str
test
def cls_from_str(name: str) -> type: """Returns a class object with the name given as a string.""" try: module_name, cls_name = name.split(':') except ValueError: raise ConfigError('Expected class description in a `module.submodules:ClassName` form, but got `{}`' .f...
python
{ "resource": "" }
q267048
register
test
def register(name: str = None) -> type: """ Register classes that could be initialized from JSON configuration file. If name is not passed, the class name is converted to snake-case. """ def decorate(model_cls: type, reg_name: str = None) -> type: model_name = reg_name or short_name(model_cl...
python
{ "resource": "" }
q267049
get_model
test
def get_model(name: str) -> type: """Returns a registered class object with the name given in the string.""" if name not in _REGISTRY: if ':' not in name: raise ConfigError("Model {} is not registered.".format(name)) return cls_from_str(name) return cls_from_str(_REGISTRY[name])
python
{ "resource": "" }
q267050
H2OGeneralizedLinearEstimator.getGLMRegularizationPath
test
def getGLMRegularizationPath(model): """ Extract full regularization path explored during lambda search from glm model. :param model: source lambda search model """ x = h2o.api("GET /3/GetGLMRegPath", data={"model": model._model_json["model_id"]["name"]}) ns = x.pop("coe...
python
{ "resource": "" }
q267051
H2OGeneralizedLinearEstimator.makeGLMModel
test
def makeGLMModel(model, coefs, threshold=.5): """ Create a custom GLM model using the given coefficients. Needs to be passed source model trained on the dataset to extract the dataset information from. :param model: source model, used for extracting dataset information :param c...
python
{ "resource": "" }
q267052
H2OCluster.from_kvs
test
def from_kvs(keyvals): """ Create H2OCluster object from a list of key-value pairs. TODO: This method should be moved into the base H2OResponse class. """ obj = H2OCluster() obj._retrieved_at = time.time() for k, v in keyvals: if k in {"__meta", "_exc...
python
{ "resource": "" }
q267053
H2OCluster.shutdown
test
def shutdown(self, prompt=False): """ Shut down the server. This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call). :param prompt: A logical value indicating whether to prompt the user before shutting down the H2O server. """ ...
python
{ "resource": "" }
q267054
H2OCluster.is_running
test
def is_running(self): """ Determine if the H2O cluster is running or not. :returns: True if the cluster is up; False otherwise """ try: if h2o.connection().local_server and not h2o.connection().local_server.is_running(): return False h2o.api("GET /") ...
python
{ "resource": "" }
q267055
H2OCluster.show_status
test
def show_status(self, detailed=False): """ Print current cluster status information. :param detailed: if True, then also print detailed information about each node. """ if self._retrieved_at + self.REFRESH_INTERVAL < time.time(): # Info is stale, need to refresh ...
python
{ "resource": "" }
q267056
H2OCluster.list_jobs
test
def list_jobs(self): """List all jobs performed by the cluster.""" res = h2o.api("GET /3/Jobs") table = [["type"], ["dest"], ["description"], ["status"]] for job in res["jobs"]: job_dest = job["dest"] table[0].append(self._translate_job_type(job_dest["type"])) ...
python
{ "resource": "" }
q267057
H2OCluster.list_timezones
test
def list_timezones(self): """Return the list of all known timezones.""" from h2o.expr import ExprNode return h2o.H2OFrame._expr(expr=ExprNode("listTimeZones"))._frame()
python
{ "resource": "" }
q267058
H2OCluster._fill_from_h2ocluster
test
def _fill_from_h2ocluster(self, other): """ Update information in this object from another H2OCluster instance. :param H2OCluster other: source of the new information for this object. """ self._props = other._props self._retrieved_at = other._retrieved_at other._...
python
{ "resource": "" }
q267059
H2OStackedEnsembleEstimator.metalearner_params
test
def metalearner_params(self): """ Parameters for metalearner algorithm Type: ``dict`` (default: ``None``). Example: metalearner_gbm_params = {'max_depth': 2, 'col_sample_rate': 0.3} """ if self._parms.get("metalearner_params") != None: metalearner_params_dic...
python
{ "resource": "" }
q267060
H2O.stabilize
test
def stabilize(self, test_func, error, timeoutSecs=10, retryDelaySecs=0.5): '''Repeatedly test a function waiting for it to return True. Arguments: test_func -- A function that will be run repeatedly error -- A function that will be run to produce an error message ...
python
{ "resource": "" }
q267061
summary
test
def summary(self, key, column="C1", timeoutSecs=10, **kwargs): ''' Return the summary for a single column for a single Frame in the h2o cluster. ''' params_dict = { # 'offset': 0, # 'len': 100 } h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'summary', True) ...
python
{ "resource": "" }
q267062
delete_frame
test
def delete_frame(self, key, ignoreMissingKey=True, timeoutSecs=60, **kwargs): ''' Delete a frame on the h2o cluster, given its key. ''' assert key is not None, '"key" parameter is null' result = self.do_json_request('/3/Frames.json/' + key, cmd='delete', timeout=timeoutSecs) # TODO: look for w...
python
{ "resource": "" }
q267063
model_builders
test
def model_builders(self, algo=None, timeoutSecs=10, **kwargs): ''' Return a model builder or all of the model builders known to the h2o cluster. The model builders are contained in a dictionary called "model_builders" at the top level of the result. The dictionary maps algorithm names to parameter...
python
{ "resource": "" }
q267064
validate_model_parameters
test
def validate_model_parameters(self, algo, training_frame, parameters, timeoutSecs=60, **kwargs): ''' Check a dictionary of model builder parameters on the h2o cluster using the given algorithm and model parameters. ''' assert algo is not None, '"algo" parameter is null' # Allow this now: assert...
python
{ "resource": "" }
q267065
compute_model_metrics
test
def compute_model_metrics(self, model, frame, timeoutSecs=60, **kwargs): ''' Score a model on the h2o cluster on the given Frame and return only the model metrics. ''' assert model is not None, '"model" parameter is null' assert frame is not None, '"frame" parameter is null' models = self.mode...
python
{ "resource": "" }
q267066
model_metrics
test
def model_metrics(self, timeoutSecs=60, **kwargs): ''' ModelMetrics list. ''' result = self.do_json_request('/3/ModelMetrics.json', cmd='get', timeout=timeoutSecs) h2o_sandbox.check_sandbox_for_errors() return result
python
{ "resource": "" }
q267067
delete_model
test
def delete_model(self, key, ignoreMissingKey=True, timeoutSecs=60, **kwargs): ''' Delete a model on the h2o cluster, given its key. ''' assert key is not None, '"key" parameter is null' result = self.do_json_request('/3/Models.json/' + key, cmd='delete', timeout=timeoutSecs) # TODO: look for w...
python
{ "resource": "" }
q267068
H2OCache._tabulate
test
def _tabulate(self, tablefmt="simple", rollups=False, rows=10): """Pretty tabulated string of all the cached data, and column names""" if not self.is_valid(): self.fill(rows=rows) # Pretty print cached data d = collections.OrderedDict() # If also printing the rollup stats, build ...
python
{ "resource": "" }
q267069
run_instances
test
def run_instances(count, ec2_config, region, waitForSSH=True, tags=None): '''Create a new reservation for count instances''' ec2params = inheritparams(ec2_config, EC2_API_RUN_INSTANCE) ec2params.setdefault('min_count', count) ec2params.setdefault('max_count', count) reservation = None conn = e...
python
{ "resource": "" }
q267070
terminate_instances
test
def terminate_instances(instances, region): '''terminate all the instances given by its ids''' if not instances: return conn = ec2_connect(region) log("Terminating instances {0}.".format(instances)) conn.terminate_instances(instances) log("Done")
python
{ "resource": "" }
q267071
stop_instances
test
def stop_instances(instances, region): '''stop all the instances given by its ids''' if not instances: return conn = ec2_connect(region) log("Stopping instances {0}.".format(instances)) conn.stop_instances(instances) log("Done")
python
{ "resource": "" }
q267072
start_instances
test
def start_instances(instances, region): '''Start all the instances given by its ids''' if not instances: return conn = ec2_connect(region) log("Starting instances {0}.".format(instances)) conn.start_instances(instances) log("Done")
python
{ "resource": "" }
q267073
reboot_instances
test
def reboot_instances(instances, region): '''Reboot all the instances given by its ids''' if not instances: return conn = ec2_connect(region) log("Rebooting instances {0}.".format(instances)) conn.reboot_instances(instances) log("Done")
python
{ "resource": "" }
q267074
wait_for_ssh
test
def wait_for_ssh(ips, port=22, skipAlive=True, requiredsuccess=3): ''' Wait for ssh service to appear on given hosts''' log('Waiting for SSH on following hosts: {0}'.format(ips)) for ip in ips: if not skipAlive or not ssh_live(ip, port): log('Waiting for SSH on instance {0}...'.format(i...
python
{ "resource": "" }
q267075
_get_method_full_name
test
def _get_method_full_name(func): """ Return fully qualified function name. This method will attempt to find "full name" of the given function object. This full name is either of the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name>" if it's a regular...
python
{ "resource": "" }
q267076
_find_function_from_code
test
def _find_function_from_code(frame, code): """ Given a frame and a compiled function code, find the corresponding function object within the frame. This function addresses the following problem: when handling a stacktrace, we receive information about which piece of code was being executed in the form ...
python
{ "resource": "" }
q267077
_get_args_str
test
def _get_args_str(func, highlight=None): """ Return function's declared arguments as a string. For example for this function it returns "func, highlight=None"; for the ``_wrap`` function it returns "text, wrap_at=120, indent=4". This should usually coincide with the function's declaration (the part ...
python
{ "resource": "" }
q267078
_wrap
test
def _wrap(text, wrap_at=120, indent=4): """ Return piece of text, wrapped around if needed. :param text: text that may be too long and then needs to be wrapped. :param wrap_at: the maximum line length. :param indent: number of spaces to prepend to all subsequent lines after the first. """ o...
python
{ "resource": "" }
q267079
H2OEstimator.join
test
def join(self): """Wait until job's completion.""" self._future = False self._job.poll() model_key = self._job.dest_key self._job = None model_json = h2o.api("GET /%d/Models/%s" % (self._rest_version, model_key))["models"][0] self._resolve_model(model_key, model_j...
python
{ "resource": "" }
q267080
H2OEstimator.train
test
def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None, weights_column=None, validation_frame=None, max_runtime_secs=None, ignored_columns=None, model_id=None, verbose=False): """ Train the H2O model. :param x: A list of column name...
python
{ "resource": "" }
q267081
H2OEstimator.fit
test
def fit(self, X, y=None, **params): """ Fit an H2O model as part of a scikit-learn pipeline or grid search. A warning will be issued if a caller other than sklearn attempts to use this method. :param H2OFrame X: An H2OFrame consisting of the predictor variables. :param H2OFrame...
python
{ "resource": "" }
q267082
H2OEstimator.get_params
test
def get_params(self, deep=True): """ Obtain parameters for this estimator. Used primarily for sklearn Pipelines and sklearn grid search. :param deep: If True, return parameters of all sub-objects that are estimators. :returns: A dict of parameters """ out = dic...
python
{ "resource": "" }
q267083
signal_handler
test
def signal_handler(signum, stackframe): """Helper function to handle caught signals.""" global g_runner global g_handling_signal if g_handling_signal: # Don't do this recursively. return g_handling_signal = True print("") print("---------------------------------------------...
python
{ "resource": "" }
q267084
wipe_output_dir
test
def wipe_output_dir(): """Clear the output directory.""" print("Wiping output directory.") try: if os.path.exists(g_output_dir): shutil.rmtree(str(g_output_dir)) except OSError as e: print("ERROR: Removing output directory %s failed: " % g_output_dir) print(" (e...
python
{ "resource": "" }
q267085
remove_sandbox
test
def remove_sandbox(parent_dir, dir_name): """ This function is written to remove sandbox directories if they exist under the parent_dir. :param parent_dir: string denoting full parent directory path :param dir_name: string denoting directory path which could be a sandbox :return: None """ ...
python
{ "resource": "" }
q267086
H2OCloudNode.scrape_port_from_stdout
test
def scrape_port_from_stdout(self): """ Look at the stdout log and figure out which port the JVM chose. If successful, port number is stored in self.port; otherwise the program is terminated. This call is blocking, and will wait for up to 30s for the server to start up. "...
python
{ "resource": "" }
q267087
H2OCloudNode.scrape_cloudsize_from_stdout
test
def scrape_cloudsize_from_stdout(self, nodes_per_cloud): """ Look at the stdout log and wait until the cluster of proper size is formed. This call is blocking. Exit if this fails. :param nodes_per_cloud: :return none """ retries = 60 while retries...
python
{ "resource": "" }
q267088
H2OCloudNode.stop
test
def stop(self): """ Normal node shutdown. Ignore failures for now. :return none """ if self.pid > 0: print("Killing JVM with PID {}".format(self.pid)) try: self.child.terminate() self.child.wait() except...
python
{ "resource": "" }
q267089
H2OCloud.stop
test
def stop(self): """ Normal cluster shutdown. :return none """ for node in self.nodes: node.stop() for node in self.client_nodes: node.stop()
python
{ "resource": "" }
q267090
H2OCloud.get_ip
test
def get_ip(self): """ Return an ip to use to talk to this cluster. """ if len(self.client_nodes) > 0: node = self.client_nodes[0] else: node = self.nodes[0] return node.get_ip()
python
{ "resource": "" }
q267091
H2OCloud.get_port
test
def get_port(self): """ Return a port to use to talk to this cluster. """ if len(self.client_nodes) > 0: node = self.client_nodes[0] else: node = self.nodes[0] return node.get_port()
python
{ "resource": "" }
q267092
H2OBinomialModel.roc
test
def roc(self, train=False, valid=False, xval=False): """ Return the coordinates of the ROC curve for a given set of data. The coordinates are two-tuples containing the false positive rates as a list and true positive rates as a list. If all are False (default), then return is the traini...
python
{ "resource": "" }
q267093
H2OWord2vecEstimator._determine_vec_size
test
def _determine_vec_size(self): """ Determines vec_size for a pre-trained model after basic model verification. """ first_column = self.pre_trained.types[self.pre_trained.columns[0]] if first_column != 'string': raise H2OValueError("First column of given pre_trained m...
python
{ "resource": "" }
q267094
h2o_mean_absolute_error
test
def h2o_mean_absolute_error(y_actual, y_predicted, weights=None): """ Mean absolute error regression loss. :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: mean absolute error loss (best is 0.0)...
python
{ "resource": "" }
q267095
h2o_mean_squared_error
test
def h2o_mean_squared_error(y_actual, y_predicted, weights=None): """ Mean squared error regression loss :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: mean squared error loss (best is 0.0). ...
python
{ "resource": "" }
q267096
h2o_median_absolute_error
test
def h2o_median_absolute_error(y_actual, y_predicted): """ Median absolute error regression loss :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :returns: median absolute error loss (best is 0.0) """ ModelBase._check_targets(y_actual, y_predi...
python
{ "resource": "" }
q267097
h2o_explained_variance_score
test
def h2o_explained_variance_score(y_actual, y_predicted, weights=None): """ Explained variance regression score function. :param y_actual: H2OFrame of actual response. :param y_predicted: H2OFrame of predicted response. :param weights: (Optional) sample weights :returns: the explained variance s...
python
{ "resource": "" }
q267098
assert_is_type
test
def assert_is_type(var, *types, **kwargs): """ Assert that the argument has the specified type. This function is used to check that the type of the argument is correct, otherwises it raises an H2OTypeError. See more details in the module's help. :param var: variable to check :param types: the ...
python
{ "resource": "" }
q267099
assert_matches
test
def assert_matches(v, regex): """ Assert that string variable matches the provided regular expression. :param v: variable to check. :param regex: regular expression to check against (can be either a string, or compiled regexp). """ m = re.match(regex, v) if m is None: vn = _retrieve...
python
{ "resource": "" }