docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Get roles associated with the given user. Args: user (string): User name. Returns: (list): List of roles that user has. Raises: requests.HTTPError on failure.
def get_user_roles(self, user): self.project_service.set_auth(self._token_project) return self.project_service.get_user_roles(user)
655,668
Add role to given user. Args: user (string): User name. role (string): Role to assign. Raises: requests.HTTPError on failure.
def add_user_role(self, user, role): self.project_service.set_auth(self._token_project) self.project_service.add_user_role(user, role)
655,669
Remove role from given user. Args: user (string): User name. role (string): Role to remove. Raises: requests.HTTPError on failure.
def delete_user_role(self, user, role): self.project_service.set_auth(self._token_project) self.project_service.delete_user_role(user, role)
655,670
Get user's data (first and last name, email, etc). Args: user (string): User name. Returns: (dictionary): User's data encoded in a dictionary. Raises: requests.HTTPError on failure.
def get_user(self, user): self.project_service.set_auth(self._token_project) return self.project_service.get_user(user)
655,671
Get user's group memberships. Args: user (string): User name. Returns: (list): User's groups. Raises: requests.HTTPError on failure.
def get_user_groups(self, user): self.project_service.set_auth(self._token_project) return self.project_service.get_user_groups(user)
655,672
Add a new user. Args: user (string): User name. first_name (optional[string]): User's first name. Defaults to None. last_name (optional[string]): User's last name. Defaults to None. email: (optional[string]): User's email address. Defaults to None. ...
def add_user( self, user, first_name=None, last_name=None, email=None, password=None ): self.project_service.set_auth(self._token_project) self.project_service.add_user( user, first_name, last_name, email, password)
655,673
Delete the given user. Args: user (string): User name. Raises: requests.HTTPError on failure.
def delete_user(self, user): self.project_service.set_auth(self._token_project) self.project_service.delete_user(user)
655,674
List all instances of the given resource type. Use the specific list_<resource>() methods instead: list_collections() list_experiments() list_channels() list_coordinate_frames() Args: resource (intern.resource.boss.BossResource): resource.nam...
def _list_resource(self, resource): self.project_service.set_auth(self._token_project) return super(BossRemote, self).list_project(resource=resource)
655,675
List all experiments that belong to a collection. Args: collection_name (string): Name of the parent collection. Returns: (list) Raises: requests.HTTPError on failure.
def list_experiments(self, collection_name): exp = ExperimentResource( name='', collection_name=collection_name, coord_frame='foo') return self._list_resource(exp)
655,676
List all channels belonging to the named experiment that is part of the named collection. Args: collection_name (string): Name of the parent collection. experiment_name (string): Name of the parent experiment. Returns: (list) Raises: req...
def list_channels(self, collection_name, experiment_name): dont_care = 'image' chan = ChannelResource( name='', collection_name=collection_name, experiment_name=experiment_name, type=dont_care) return self._list_resource(chan)
655,677
Helper that gets a fully initialized ChannelResource for an *existing* channel. Args: chan_name (str): Name of channel. coll_name (str): Name of channel's collection. exp_name (str): Name of channel's experiment. Returns: (intern.resource.boss.ChannelRes...
def get_channel(self, chan_name, coll_name, exp_name): chan = ChannelResource(chan_name, coll_name, exp_name) return self.get_project(chan)
655,678
Create the entity described by the given resource. Args: resource (intern.resource.boss.BossResource) Returns: (intern.resource.boss.BossResource): Returns resource of type requested on success. Raises: requests.HTTPError on failure.
def create_project(self, resource): self.project_service.set_auth(self._token_project) return self.project_service.create(resource)
655,679
Get attributes of the data model object named by the given resource. Args: resource (intern.resource.boss.BossResource): resource.name as well as any parents must be identified to succeed. Returns: (intern.resource.boss.BossResource): Returns resource of type ...
def get_project(self, resource): self.project_service.set_auth(self._token_project) return self.project_service.get(resource)
655,680
Deletes the entity described by the given resource. Args: resource (intern.resource.boss.BossResource) Raises: requests.HTTPError on a failure.
def delete_project(self, resource): self.project_service.set_auth(self._token_project) self.project_service.delete(resource)
655,682
List all keys associated with the given resource. Args: resource (intern.resource.boss.BossResource) Returns: (list) Raises: requests.HTTPError on a failure.
def list_metadata(self, resource): self.metadata_service.set_auth(self._token_metadata) return self.metadata_service.list(resource)
655,683
Associates new key-value pairs with the given resource. Will attempt to add all key-value pairs even if some fail. Args: resource (intern.resource.boss.BossResource) keys_vals (dictionary): Collection of key-value pairs to assign to given resource. Rais...
def create_metadata(self, resource, keys_vals): self.metadata_service.set_auth(self._token_metadata) self.metadata_service.create(resource, keys_vals)
655,684
Gets the values for given keys associated with the given resource. Args: resource (intern.resource.boss.BossResource) keys (list) Returns: (dictionary) Raises: HTTPErrorList on failure.
def get_metadata(self, resource, keys): self.metadata_service.set_auth(self._token_metadata) return self.metadata_service.get(resource, keys)
655,685
Updates key-value pairs with the given resource. Will attempt to update all key-value pairs even if some fail. Keys must already exist. Args: resource (intern.resource.boss.BossResource) keys_vals (dictionary): Collection of key-value pairs to update on ...
def update_metadata(self, resource, keys_vals): self.metadata_service.set_auth(self._token_metadata) self.metadata_service.update(resource, keys_vals)
655,686
Deletes the given key-value pairs associated with the given resource. Will attempt to delete all key-value pairs even if some fail. Args: resource (intern.resource.boss.BossResource) keys (list) Raises: HTTPErrorList on failure.
def delete_metadata(self, resource, keys): self.metadata_service.set_auth(self._token_metadata) self.metadata_service.delete(resource, keys)
655,687
Parse a bossDB URI and handle malform errors. Arguments: uri (str): URI of the form bossdb://<collection>/<experiment>/<channel> Returns: Resource
def parse_bossURI(self, uri): # type: (str) -> Resource t = uri.split("://")[1].split("/") if len(t) is 3: return self.get_channel(t[2], t[0], t[1]) raise ValueError("Cannot parse URI " + uri + ".")
655,688
Convenience method that gets experiment resource. Args: coll_name (str): Collection name exp_name (str): Experiment name Returns: (ExperimentResource)
def get_experiment(self, coll_name, exp_name): exp = ExperimentResource(exp_name, coll_name) return self.get_project(exp)
655,690
A decorator for registering a callback to a model Parameters: model: the model object whose changes the callback should respond to. Examples: .. code-block:: python from spectate import mvc items = mvc.List() @mvc.view(items) def printer(items...
def view(model: "Model", *functions: Callable) -> Optional[Callable]: if not isinstance(model, Model): raise TypeError("Expected a Model, not %r." % model) def setup(function: Callable): model._model_views.append(function) return function if functions: for f in functio...
655,696
Register a control method that reacts before the trigger method is called. Parameters: callback: The control method. If given as a callable, then that function will be used as the callback. If given as a string, then the control will look up a method ...
def before(self, callback: Union[Callable, str]) -> "Control": if isinstance(callback, Control): callback = callback._before self._before = callback return self
655,697
Register a control method that reacts after the trigger method is called. Parameters: callback: The control method. If given as a callable, then that function will be used as the callback. If given as a string, then the control will look up a method w...
def after(self, callback: Union[Callable, str]) -> "Control": if isinstance(callback, Control): callback = callback._after self._after = callback return self
655,698
Serve a directory statically Parameters: * app: Grole application object * base_url: Base URL to serve from, e.g. /static * base_path: Base path to look for files in * index: Provide simple directory indexes if True
def serve_static(app, base_url, base_path, index=False): @app.route(base_url + '/(.*)') def serve(env, req): try: base = pathlib.Path(base_path).resolve() path = (base / req.match.group(1)).resolve() except FileNotFoundError: return Response(None...
655,708
Serve API documentation extracted from request handler docstrings Parameters: * app: Grole application object * url: URL to serve at
def serve_doc(app, url): @app.route(url, doc=False) def index(env, req): ret = '' for d in env['doc']: ret += 'URL: {url}, supported methods: {methods}{doc}\n'.format(**d) return ret
655,709
Initialise object, data is the data to send Parameters: * data: Byte data to send * content_type: Value of Content-Type header, default text/plain
def __init__(self, data=b'', content_type='text/plain'): self._headers = {'Content-Length': len(data), 'Content-Type': content_type} self._data = data
655,715
Initialise object, data is the data to send Parameters: * data: Object to encode as json for sending * content_type: Value of Content-Type header, default application/json
def __init__(self, data='', content_type='application/json'): super().__init__(json.dumps(data), content_type)
655,716
Initialise object, data is the data to send Parameters: * filename: Name of file to read and send * content_type: Value of Content-Type header, default is to guess from file extension
def __init__(self, filename, content_type=None): if content_type == None: content_type = mimetypes.guess_type(filename)[0] self.filename = filename self._headers = {'Transfer-Encoding': 'chunked', 'Content-Type': content_type}
655,717
Decorator to register a handler Parameters: * path_regex: Request path regex to match against for running the handler * methods: HTTP methods to use this handler for * doc: Add to internal doc structure
def route(self, path_regex, methods=['GET'], doc=True): def register_func(func): if doc: self.env['doc'].append({'url': path_regex, 'methods': ', '.join(methods), 'doc': func.__doc__}) for method in methods: self._handlers[method].app...
655,723
Launch the server. Will run forever accepting connections until interrupted. Parameters: * host: The host to listen on * port: The port to listen on
def run(self, host='localhost', port=1234): # Setup loop loop = asyncio.get_event_loop() coro = asyncio.start_server(self._handle, host, port, loop=loop) try: server = loop.run_until_complete(coro) except Exception as e: self._logger.error('Could ...
655,725
Finds out license from list of trove classifiers. Args: trove: list of trove classifiers Returns: Fedora name of the package license or empty string, if no licensing information is found in trove classifiers.
def license_from_trove(trove): license = [] for classifier in trove: if 'License' in classifier: stripped = classifier.strip() # if taken from EGG-INFO, begins with Classifier: stripped = stripped[stripped.find('License'):] if stripped in settings.TRO...
655,769
Finds out python version from list of trove classifiers. Args: trove: list of trove classifiers Returns: python version string
def versions_from_trove(trove): versions = set() for classifier in trove: if 'Programming Language :: Python ::' in classifier: ver = classifier.split('::')[-1] major = ver.split('.')[0].strip() if major: versions.add(major) return sorted( ...
655,770
Convert spec into SCL-style spec file using `spec2scl`. Args: spec: (str) a spec file scl_options: (dict) SCL options provided Returns: A converted spec file
def convert_to_scl(spec, scl_options): scl_options['skip_functions'] = scl_options['skip_functions'].split(',') scl_options['meta_spec'] = None convertor = SclConvertor(options=scl_options) return str(convertor.convert(spec))
655,815
Converts a dependency got by pkg_resources.Requirement.parse() to RPM format. Args: dep - a dependency retrieved by pkg_resources.Requirement.parse() runtime - whether the returned dependency should be runtime (True) or build time (False) Returns: List of semi-SPECFILE depend...
def dependency_to_rpm(dep, runtime): logger.debug('Dependencies provided: {0} runtime: {1}.'.format( dep, runtime)) converted = [] if not len(dep.specs): converted.append(['Requires', dep.project_name]) else: for ver_spec in dep.specs: if ver_spec[0] == '!=': ...
655,826
Parses dependencies extracted from setup.py. Args: requires: list of dependencies as written in setup.py of the package. runtime: are the dependencies runtime (True) or build time (False)? Returns: List of semi-SPECFILE dependencies (see dependency_to_rpm for format).
def deps_from_pyp_format(requires, runtime=True): parsed = [] logger.debug("Dependencies from setup.py: {0} runtime: {1}.".format( requires, runtime)) for req in requires: try: parsed.append(Requirement.parse(req)) except ValueError: logger.warn("Unparsa...
655,827
Parses dependencies returned by pydist.json, since versions uses brackets we can't use pkg_resources to parse and we need a separate method Args: requires: list of dependencies as written in pydist.json of the package runtime: are the dependencies runtime (True) or build time (False) Ret...
def deps_from_pydit_json(requires, runtime=True): parsed = [] for req in requires: # req looks like 'some-name (>=X.Y,!=Y.X)' or 'someme-name' where # 'some-name' is the name of required package and '(>=X.Y,!=Y.X)' # are specs name, specs = None, None # len(reqs) == ...
655,828
Returns content of file from archive. If full_path is set to False and two files with given name exist, content of one is returned (it is not specified which one that is). If set to True, returns content of exactly that file. Args: name: name of the file to get content of ...
def get_content_of_file(self, name, full_path=False): if self.handle: for member in self.handle.getmembers(): if (full_path and member.name == name) or ( not full_path and os.path.basename( member.name) == name): ...
655,845
Finds out if there is a file with one of suffixes in the archive. Args: suffixes: list of suffixes or single suffix to look for Returns: True if there is at least one file with at least one given suffix in the archive, False otherwise (or archive can't be opened)
def has_file_with_suffix(self, suffixes): if not isinstance(suffixes, list): suffixes = [suffixes] if self.handle: for member in self.handle.getmembers(): if os.path.splitext(member.name)[1] in suffixes: return True el...
655,848
Properly versions the name. For example: rpm_versioned_name('python-foo', '26') will return python26-foo rpm_versioned_name('pyfoo, '3') will return python3-pyfoo If version is same as settings.DEFAULT_PYTHON_VERSION, no change is done. Args: name: name to v...
def rpm_versioned_name(cls, name, version, default_number=False): regexp = re.compile(r'^python(\d*|)-(.*)') auto_provides_regexp = re.compile(r'^python(\d*|)dist(.*)') if (not version or version == cls.get_default_py_version() and not default_number): found...
655,856
Checks if name converted using superclass rpm_name_method match name of package in the query. Searches for correct name if it doesn't. Args: name: name to convert python_version: python version for which to retrieve the name of the package ...
def rpm_name(self, name, python_version=None, pkg_name=False): if pkg_name: return super(DandifiedNameConvertor, self).rpm_name( name, python_version) original_name = name converted = super(DandifiedNameConvertor, self).rpm_name( name, python_vers...
655,865
Builds a srpm from given specfile using rpmbuild. Generated srpm is stored in directory specified by save_dir. Args: specfile: path to a specfile save_dir: path to source and build tree
def build_srpm(specfile, save_dir): logger.info('Starting rpmbuild to build: {0} SRPM.'.format(specfile)) if save_dir != get_default_save_path(): try: msg = subprocess.Popen( ['rpmbuild', '--define', '_sourcedir {0}'.format(save_dir), '-...
655,876
Creates the default brewblox_service ArgumentParser. Service-agnostic arguments are added. The parser allows calling code to add additional arguments before using it in create_app() Args: default_name (str): default value for the --name commandline argument. Returns: argpa...
def create_parser(default_name: str) -> argparse.ArgumentParser: argparser = argparse.ArgumentParser(fromfile_prefix_chars='@') argparser.add_argument('-H', '--host', help='Host to which the app binds. [%(default)s]', default='0.0.0.0') argparser.ad...
656,488
Configures Application routes, readying it for running. This function modifies routes and resources that were added by calling code, and must be called immediately prior to `run(app)`. Args: app (web.Application): The Aiohttp Application as created by `create_app()`
def furnish(app: web.Application): app_name = app['config']['name'] prefix = '/' + app_name.lstrip('/') app.router.add_routes(routes) cors_middleware.enable_cors(app) # Configure CORS and prefixes on all endpoints. known_resources = set() for route in list(app.router.routes()): ...
656,490
Runs the application in an async context. This function will block indefinitely until the application is shut down. Args: app (web.Application): The Aiohttp Application as created by `create_app()`
def run(app: web.Application): host = app['config']['host'] port = app['config']['port'] # starts app. run_app() will automatically start the async context. web.run_app(app, host=host, port=port)
656,491
--- tags: - Events summary: Subscribe to events. operationId: events.subscribe produces: - text/plain parameters: - in: body name: body description: Event message required: true schema: type: object properties: ...
async def post_subscribe(request): args = await request.json() get_listener(request.app).subscribe( args['exchange'], args['routing'] ) return web.Response()
656,538
Downloads and registers a user environment from a git repository Args: source: the source where to download the envname (expected 'github.com/user/repo[@branch]') Note: the user environment will be registered as (username/EnvName-vVersion)
def pull(self, source=''): # Checking syntax branch_parts = source.split('@') if len(branch_parts) == 2: branch = branch_parts[1] source = branch_parts[0] git_url = 'https://{}.git@{}'.format(source, branch) else: git_url = 'https:...
658,308
Format code content using Black Args: code (str): code as string Returns: str
def blacken_code(code): if black is None: raise NotImplementedError major, minor, _ = platform.python_version_tuple() pyversion = 'py{major}{minor}'.format(major=major, minor=minor) target_versions = [black.TargetVersion[pyversion.upper()]] line_length = black.DEFAULT_LINE_LENGTH ...
658,408
Compute cross-validated metrics. Trains this model on data X with labels y. Returns a list of dict with keys name, scoring_name, value. Args: X (Union[np.array, pd.DataFrame]): data y (Union[np.array, pd.DataFrame, pd.Series]): labels
def compute_metrics_cv(self, X, y, **kwargs): # compute scores results = self.cv_score_mean(X, y) return results
658,430
Compute mean score across cross validation folds. Split data and labels into cross validation folds and fit the model for each fold. Then, for each scoring type in scorings, compute the score. Finally, average the scores across folds. Returns a dictionary mapping scoring to score. ...
def cv_score_mean(self, X, y): X, y = self._format_inputs(X, y) if self.problem_type.binary_classification: kf = StratifiedKFold( shuffle=True, random_state=RANDOM_STATE + 3) elif self.problem_type.multi_classification: self.target_type_transfor...
658,433
Get contributed features for a project at project_root For a project ``foo``, walks modules within the ``foo.features.contrib`` subpackage. A single object that is an instance of ``ballet.Feature`` is imported if present in each module. The resulting ``Feature`` objects are collected. Args: ...
def get_contrib_features(project_root): # TODO Project should require ModuleType project = Project(project_root) contrib = project._resolve('.features.contrib') return _get_contrib_features(contrib)
658,443
Get contributed features from within given module Be very careful with untrusted code. The module/package will be walked, every submodule will be imported, and all the code therein will be executed. But why would you be trying to import from an untrusted package anyway? Args: contrib (modu...
def _get_contrib_features(module): if isinstance(module, types.ModuleType): # any module that has a __path__ attribute is also a package if hasattr(module, '__path__'): yield from _get_contrib_features_from_package(module) else: yield _get_contrib_feature_from_m...
658,444
Write tabular object in HDF5 or pickle format Args: obj (array or DataFrame): tabular object to write filepath (path-like): path to write to; must end in '.h5' or '.pkl'
def write_tabular(obj, filepath): _, fn, ext = splitext2(filepath) if ext == '.h5': _write_tabular_h5(obj, filepath) elif ext == '.pkl': _write_tabular_pickle(obj, filepath) else: raise NotImplementedError
658,451
Read tabular object in HDF5 or pickle format Args: filepath (path-like): path to read to; must end in '.h5' or '.pkl'
def read_tabular(filepath): _, fn, ext = splitext2(filepath) if ext == '.h5': return _read_tabular_h5(filepath) elif ext == '.pkl': return _read_tabular_pickle(filepath) else: raise NotImplementedError
658,454
Load table from table config dict Args: input_dir (path-like): directory containing input files config (dict): mapping with keys 'name', 'path', and 'pd_read_kwargs'. Returns: pd.DataFrame
def load_table_from_config(input_dir, config): path = pathlib.Path(input_dir).joinpath(config['path']) kwargs = config['pd_read_kwargs'] return pd.read_csv(path, **kwargs)
658,459
Add s into filepath before the extension Args: filepath (str, path): file path s (str): string to splice Returns: str
def spliceext(filepath, s): root, ext = os.path.splitext(safepath(filepath)) return root + s + ext
658,467
Replace any existing file extension with a new one Example:: >>> replaceext('/foo/bar.txt', 'py') '/foo/bar.py' >>> replaceext('/foo/bar.txt', '.doc') '/foo/bar.doc' Args: filepath (str, path): file path new_ext (str): new file extension; if a leading dot is no...
def replaceext(filepath, new_ext): if new_ext and new_ext[0] != '.': new_ext = '.' + new_ext root, ext = os.path.splitext(safepath(filepath)) return root + new_ext
658,468
Split filepath into root, filename, ext Args: filepath (str, path): file path Returns: str
def splitext2(filepath): root, filename = os.path.split(safepath(filepath)) filename, ext = os.path.splitext(safepath(filename)) return root, filename, ext
658,469
Determine if the file both exists and isempty Args: filepath (str, path): file path Returns: bool
def isemptyfile(filepath): exists = os.path.exists(safepath(filepath)) if exists: filesize = os.path.getsize(safepath(filepath)) return filesize == 0 else: return False
658,470
Set config variables Args: repo (git.Repo): repo variables (dict): entries of the form 'user.email': 'you@example.com'
def set_config_variables(repo, variables): with repo.config_writer() as writer: for k, value in variables.items(): section, option = k.split('.') writer.set_value(section, option, value) writer.release()
658,485
Load config at exact path Args: path (path-like): path to config file Returns: dict: config dict
def load_config_at_path(path): if path.exists() and path.is_file(): with path.open('r') as f: return yaml.load(f, Loader=yaml.SafeLoader) else: raise ConfigurationError("Couldn't find ballet.yml config file.")
658,502
Get a configuration option following a path through the config Example usage: >>> config_get(config, 'problem', 'problem_type_details', 'scorer', default='accuracy') Args: config (dict): config dict *path (list[str]): List of config sectio...
def config_get(config, *path, default=None): o = object() result = get_in(config, path, default=o) if result is not o: return result else: return default
658,503
Return a function to get configuration options for a specific project Args: conf_path (path-like): path to project's conf file (i.e. foo.conf module)
def make_config_get(conf_path): project_root = _get_project_root_from_conf_path(conf_path) config = load_config_in_dir(project_root) return partial(config_get, config)
658,504
Compute relative path of changed file to contrib dir Args: diff (git.diff.Diff): file diff project (Project): project Returns: Path
def relative_to_contrib(diff, project): path = pathlib.Path(diff.b_path) contrib_path = project.contrib_module_path return path.relative_to(contrib_path)
658,505
Return a union of transformers that apply different lags Args: lags (Collection[int]): collection of lags to apply groupby_kwargs (dict): keyword arguments to pd.DataFrame.groupby
def make_multi_lagger(lags, groupby_kwargs=None): laggers = [SingleLagger(l, groupby_kwargs=groupby_kwargs) for l in lags] feature_union = FeatureUnion([ (repr(lagger), lagger) for lagger in laggers ]) return feature_union
658,548
Start a new feature within a ballet project Renders the feature template into a temporary directory, then copies the feature files into the proper path within the contrib directory. Args: **cc_kwargs: options for the cookiecutter template Raises: ballet.exc.BalletError: the new featur...
def start_new_feature(**cc_kwargs): project = Project.from_path(pathlib.Path.cwd().resolve()) contrib_dir = project.get('contrib', 'module_path') with tempfile.TemporaryDirectory() as tempdir: # render feature template output_dir = tempdir cc_kwargs['output_dir'] = output_dir ...
658,552
Get the proposed feature The path of the proposed feature is determined by diffing the project against a comparison branch, such as master. The feature is then imported from that path and returned. Args: project (ballet.project.Project): project info Raises: ballet.exc.BalletError...
def get_proposed_feature(project): change_collector = ChangeCollector(project) collected_changes = change_collector.collect_changes() try: new_feature_info = one_or_raise(collected_changes.new_feature_info) importer, _, _ = new_feature_info except ValueError: raise BalletErr...
658,553
Collect feature info Args: candidate_feature_diffs (List[git.diff.Diff]): list of Diffs corresponding to admissible file changes compared to comparison ref Returns: List[Tuple]: list of tuple of importer, module name, and module p...
def _collect_feature_info(self, candidate_feature_diffs): project_root = self.project.path for diff in candidate_feature_diffs: path = diff.b_path modname = relpath_to_modname(path) modpath = project_root.joinpath(path) importer = partial(import_m...
658,561
Make a DataFrameMapper from a feature or list of features Args: features (Union[Feature, List[Feature]]): feature or list of features Returns: DataFrameMapper: mapper made from features
def make_mapper(features): if not features: features = Feature(input=[], transformer=NullTransformer()) if not iterable(features): features = (features, ) return DataFrameMapper( [t.as_input_transformer_tuple() for t in features], input_df=True)
658,568
Build features and target Args: X_df (DataFrame): raw variables y_df (DataFrame): raw target Returns: dict with keys X_df, features, mapper_X, X, y_df, encoder_y, y
def build(X_df=None, y_df=None): if X_df is None: X_df, _ = load_data() if y_df is None: _, y_df = load_data() features = get_contrib_features() mapper_X = ballet.feature.make_mapper(features) X = mapper_X.fit_transform(X_df) encoder_y = get_target_encoder() y = encode...
658,591
Makes a token request. If the 'token_endpoint' is not configured in the provider metadata, no request will be made. Args: authorization_code (str): authorization code issued to client after user authorization Returns: Union[AccessTokenResponse, TokenErrorResponse, None...
def token_request(self, authorization_code): if not self._client.token_endpoint: return None request = { 'grant_type': 'authorization_code', 'code': authorization_code, 'redirect_uri': self._redirect_uri } logger.debug('making to...
659,183
Summary Args: input_shape (list): The shape of the input layer targets (int): Number of targets dense_layers (list): Dense layer descriptor [fully_connected] optimizer (str or object optional): Keras optimizer as string or keras optimizer Returns: TYPE: model, b...
def DNN(input_shape, dense_layers, output_layer=[1, 'sigmoid'], optimizer='adam', loss='binary_crossentropy'): inputs = Input(shape=input_shape) dense = inputs for i, d in enumerate(dense_layers): dense = Dense(d, activation='relu')(dense) ...
660,187
waits while process starts. Args: port_num - port number timeout - specify how long, in seconds, a command can take before times out. return True if process started, return False if not
def wait_for(port_num, timeout): logger.debug("wait for {port_num}".format(**locals())) t_start = time.time() sleeps = 0.1 while time.time() - t_start < timeout: try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((_host(), port_...
661,608
kill process Args: process - Popen object for process
def kill_mprocess(process): if process and proc_alive(process): process.terminate() process.communicate() return not proc_alive(process)
661,612
remove all process's stuff Args: config_path - process's options file cfg - process's config
def cleanup_mprocess(config_path, cfg): for key in ('keyFile', 'logPath', 'dbpath'): remove_path(cfg.get(key, None)) isinstance(config_path, str) and os.path.exists(config_path) and remove_path(config_path)
661,613
write mongo*'s config file Args: params - options wich file contains config_path - path to the config_file, will create if None Return config_path where config_path - path to mongo*'s options file
def write_config(params, config_path=None): if config_path is None: config_path = tempfile.mktemp(prefix="mongo-") cfg = params.copy() if 'setParameter' in cfg: set_parameters = cfg.pop('setParameter') try: for key, value in set_parameters.items(): c...
661,615
return next opened port Args: check - check is port realy free
def port(self, check=False): if not self.__ports: # refresh ports if sequence is empty self.refresh() try: port = self.__ports.pop() if check: while not self.__check_port(port): self.release_port(port) ...
661,621
refresh ports status Args: only_closed - check status only for closed ports
def refresh(self, only_closed=False): if only_closed: opened = filter(self.__check_port, self.__closed) self.__closed = self.__closed.difference(opened) self.__ports = self.__ports.union(opened) else: ports = self.__closed.union(self.__ports) ...
661,622
create replica set according members config Args: rs_params - replica set configuration
def __init__(self, rs_params): self.server_map = {} self.auth_key = rs_params.get('auth_key', None) self.login = rs_params.get('login', '') self.auth_source = rs_params.get('authSource', 'admin') self.password = rs_params.get('password', '') self.admin_added = Fa...
661,647
create new mongod instances and add it to the replica set. Args: params - mongod params return True if operation success otherwise False
def repl_member_add(self, params): repl_config = self.config member_id = max([member['_id'] for member in repl_config['members']]) + 1 member_config = self.member_create(params, member_id) repl_config['members'].append(member_config) if not self.repl_update(repl_config):...
661,655
run command on replica set if member_id is specified command will be execute on this server if member_id is not specified command will be execute on the primary Args: command - command string arg - command argument is_eval - if True execute command as eval ...
def run_command(self, command, arg=None, is_eval=False, member_id=None): logger.debug("run_command({command}, {arg}, {is_eval}, {member_id})".format(**locals())) mode = is_eval and 'eval' or 'command' hostname = None if isinstance(member_id, int): hostname = self.mem...
661,656
start new mongod instances as part of replica set Args: params - member params member_id - member index return member config
def member_create(self, params, member_id): member_config = params.get('rsParams', {}) server_id = params.pop('server_id', None) version = params.pop('version', self._version) proc_params = {'replSet': self.repl_id} proc_params.update(params.get('procParams', {})) ...
661,658
remove member from replica set Args: member_id - member index reconfig - is need reconfig replica return True if operation success otherwise False
def member_del(self, member_id, reconfig=True): server_id = self._servers.host_to_server_id( self.member_id_to_host(member_id)) if reconfig and member_id in [member['_id'] for member in self.members()]: config = self.config config['members'].pop(member_id) ...
661,659
update member's values with reconfig replica Args: member_id - member index params - updates member params return True if operation success otherwise False
def member_update(self, member_id, params): config = self.config config['members'][member_id].update(params.get("rsParams", {})) return self.repl_update(config)
661,660
apply command (start/stop/restart) to member instance of replica set Args: member_id - member index command - string command (start/stop/restart) return True if operation success otherwise False
def member_command(self, member_id, command): server_id = self._servers.host_to_server_id( self.member_id_to_host(member_id)) return self._servers.command(server_id, command)
661,662
return MongoReplicaSetClient object if hostname specified return MongoClient object if hostname doesn't specified Args: hostname - connection uri read_preference - default PRIMARY timeout - specify how long, in seconds, a command can take before server times out.
def connection(self, hostname=None, read_preference=pymongo.ReadPreference.PRIMARY, timeout=300): logger.debug("connection({hostname}, {read_preference}, {timeout})".format(**locals())) t_start = time.time() servers = hostname or ",".join(self.server_map.values()) while True: ...
661,666
wait while all servers be reachable Args: servers - list of servers
def wait_while_reachable(self, servers, timeout=60): t_start = time.time() while True: try: for server in servers: # TODO: use state code to check if server is reachable server_info = self.connection( ho...
661,671
waiting while real state equal config state Args: timeout - specify how long, in seconds, a command can take before server times out. return True if operation success otherwise False
def waiting_config_state(self, timeout=300): t_start = time.time() while not self.check_config_state(): if time.time() - t_start > timeout: return False time.sleep(0.1) return True
661,673
create new replica set Args: rs_params - replica set configuration Return repl_id which can use to take the replica set
def create(self, rs_params): repl_id = rs_params.get('id', None) if repl_id is not None and repl_id in self: raise ReplicaSetError( "replica set with id={id} already exists".format(id=repl_id)) repl = ReplicaSet(rs_params) self[repl.repl_id] = repl ...
661,678
find and return primary hostname Args: repl_id - replica set identity
def primary(self, repl_id): repl = self[repl_id] primary = repl.primary() return repl.member_info(repl.host2id(primary))
661,679
remove replica set with kill members Args: repl_id - replica set identity return True if operation success otherwise False
def remove(self, repl_id): repl = self._storage.pop(repl_id) repl.cleanup() del(repl)
661,680
remove member from replica set (reconfig replica) Args: repl_id - replica set identity member_id - member index
def member_del(self, repl_id, member_id): repl = self[repl_id] result = repl.member_del(member_id) self[repl_id] = repl return result
661,682
create instance and add it to existing replcia Args: repl_id - replica set identity params - member params return True if operation success otherwise False
def member_add(self, repl_id, params): repl = self[repl_id] member_id = repl.repl_member_add(params) self[repl_id] = repl return member_id
661,683
apply command(start, stop, restart) to the member of replica set Args: repl_id - replica set identity member_id - member index command - command: start, stop, restart return True if operation success otherwise False
def member_command(self, repl_id, member_id, command): repl = self[repl_id] result = repl.member_command(member_id, command) self[repl_id] = repl return result
661,684
apply new params to replica set member Args: repl_id - replica set identity member_id - member index params - new member's params return True if operation success otherwise False
def member_update(self, repl_id, member_id, params): repl = self[repl_id] result = repl.member_update(member_id, params) self[repl_id] = repl return result
661,685
run command on the server Args: command - command string arg - command argument is_eval - if True execute command as eval return command's result
def run_command(self, command, arg=None, is_eval=False): mode = is_eval and 'eval' or 'command' if isinstance(arg, tuple): name, d = arg else: name, d = arg, {} result = getattr(self.connection.admin, mode)(command, name, **d) return result
661,723
remove server and data stuff Args: server_id - server identity
def remove(self, server_id): server = self._storage.pop(server_id) server.stop() server.cleanup()
661,733
run command Args: server_id - server identity command - command which apply to server
def command(self, server_id, command, *args): server = self._storage[server_id] try: if args: result = getattr(server, command)(*args) else: result = getattr(server, command)() except AttributeError: raise ValueError("C...
661,735
return dicionary object with info about server Args: server_id - server identity
def info(self, server_id): result = self._storage[server_id].info() result['id'] = server_id return result
661,736
create new ShardedCluster Args: params - dictionary with specific params for instance Return cluster_id where cluster_id - id which can use to take the cluster from servers collection
def create(self, params): sh_id = params.get('id', str(uuid4())) if sh_id in self: raise ShardedClusterError( "Sharded cluster with id %s already exists." % sh_id) params['id'] = sh_id cluster = ShardedCluster(params) self[cluster.id] = cluste...
661,758