Search is not available for this dataset
text
stringlengths
75
104k
def read_temple_config(): """Reads the temple YAML configuration file in the repository""" with open(temple.constants.TEMPLE_CONFIG_FILE) as temple_config_file: return yaml.load(temple_config_file, Loader=yaml.SafeLoader)
def write_temple_config(temple_config, template, version): """Writes the temple YAML configuration""" with open(temple.constants.TEMPLE_CONFIG_FILE, 'w') as temple_config_file: versioned_config = { **temple_config, **{'_version': version, '_template': template}, } ...
def get_cookiecutter_config(template, default_config=None, version=None): """Obtains the configuration used for cookiecutter templating Args: template: Path to the template default_config (dict, optional): The default configuration version (str, optional): The git SHA or branch to use w...
def set_cmd_env_var(value): """Decorator that sets the temple command env var to value""" def func_decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): previous_cmd_env_var = os.getenv(temple.constants.TEMPLE_ENV_VAR) os.environ[temple.constants.T...
def _call_api(self, verb, url, **request_kwargs): """Perform a github API call Args: verb (str): Can be "post", "put", or "get" url (str): The base URL with a leading slash for Github API (v3) auth (str or HTTPBasicAuth): A Github API token or a HTTPBasicAuth object ...
def deploy(target): """Deploys the package and documentation. Proceeds in the following steps: 1. Ensures proper environment variables are set and checks that we are on Circle CI 2. Tags the repository with the new version 3. Creates a standard distribution and a wheel 4. Updates version.py to...
def report(func): """ Decorator for method run. This method will be execute before the execution from the method with this decorator. """ def execute(self, *args, **kwargs): try: print "[>] Executing {n} report. . . ".format(n=self.__class__.NAME) if hasattr(self, 'test'): if self.test(): return f...
def run(self): """ Finds .DS_Store files into path """ filename = ".DS_Store" command = "find {path} -type f -name \"{filename}\" ".format(path = self.path, filename = filename) cmd = CommandHelper(command) cmd.execute() files = cmd.output.split("\n") for f in files: if not f.endswith(filename): ...
def run(self): """ Method executed dynamically by framework. This method will do a http request to endpoint setted into config file with the issues and other data. """ options = {} if bool(self.config['use_proxy']): options['proxies'] = {"http": self.config['proxy'], "https": self.config['proxy']} opt...
def path(self, value): """ Setter for 'path' property Args: value (str): Absolute path to scan """ if not value.endswith('/'): self._path = '{v}/'.format(v=value) else: self._path = value
def parseConfig(cls, value): """ Parse the config values Args: value (dict): Dictionary which contains the checker config Returns: dict: The checker config with parsed values """ if 'enabled' in value: value['enabled'] = bool(value['enabled']) if 'exclude_paths' in value: value['exclude_pat...
def isInstalled(value): """ Check if a software is installed into machine. Args: value (str): Software's name Returns: bool: True if the software is installed. False else """ function = """ function is_installed { local return_=1; type $1 >/dev/null 2>&1 || { local return_=0; }; echo ...
def getOSName(self): """ Get the OS name. If OS is linux, returns the Linux distribution name Returns: str: OS name """ _system = platform.system() if _system in [self.__class__.OS_WINDOWS, self.__class__.OS_MAC, self.__class__.OS_LINUX]: if _system == self.__class__.OS_LINUX: _dist = platform.li...
def execute(self, shell = True): """ Executes the command setted into class Args: shell (boolean): Set True if command is a shell command. Default: True """ process = Popen(self.command, stdout=PIPE, stderr=PIPE, shell=shell) self.output, self.errors = process.communicate()
def _debug(message, color=None, attrs=None): """ Print a message if the class attribute 'verbose' is enabled Args: message (str): Message to print """ if attrs is None: attrs = [] if color is not None: print colored(message, color, attrs=attrs) else: if len(attrs) > 0: print colored(messa...
def setup(): """ Creates required directories and copy checkers and reports. """ # # Check if dir is writable # if not os.access(AtomShieldsScanner.HOME, os.W_OK): # AtomShieldsScanner.HOME = os.path.expanduser("~/.atomshields") # AtomShieldsScanner.CHECKERS_DIR = os.path.join(AtomShieldsScanner.HOME...
def _addConfig(instance, config, parent_section): """ Writes a section for a plugin. Args: instance (object): Class instance for plugin config (object): Object (ConfigParser) which the current config parent_section (str): Parent section for plugin. Usually 'checkers' or 'reports' """ try: section...
def getConfig(self, section = None): """ Returns a dictionary which contains the current config. If a section is setted, only will returns the section config Args: section (str): (Optional) Section name. Returns: dict: Representation of current config """ data = {} if section is None: for s i...
def _getClassInstance(path, args=None): """ Returns a class instance from a .py file. Args: path (str): Absolute path to .py file args (dict): Arguments passed via class constructor Returns: object: Class instance or None """ if not path.endswith(".py"): return None if args is None: args...
def _executeMassiveMethod(path, method, args=None, classArgs = None): """ Execute an specific method for each class instance located in path Args: path (str): Absolute path which contains the .py files method (str): Method to execute into class instance Returns: dict: Dictionary which contains the re...
def run(self): """ Run a scan in the path setted. """ self.checkProperties() self.debug("[*] Iniciando escaneo de AtomShields con las siguientes propiedades. . . ") self.showScanProperties() self.loadConfig() # Init time counter init_ts = datetime.now() # Execute plugins cwd = os.getcwd() ...
def install(): """ Install all the dependences """ cmd = CommandHelper() cmd.install("npm") cmd = CommandHelper() cmd.install("nodejs-legacy") # Install retre with npm cmd = CommandHelper() cmd.command = "npm install -g retire" cmd.execute() if cmd.errors: from termcolor import colored ...
def potential(self, value): """ Setter for 'potential' property Args: value (bool): True if a potential is required. False else """ if value: self._potential = True else: self._potential = False
def get(name, default=None, allow_default=True): """ Shortcut method for getting a setting value. :param str name: Setting key name. :param default: Default value of setting if it's not explicitly set. Defaults to `None` :param bool allow_default: If true, use the pa...
def env(key, default): """ Helper to try to get a setting from the environment, or pyconfig, or finally use a provided default. """ value = os.environ.get(key, None) if value is not None: log.info(' %s = %r', key.lower().replace('_', '.'), value) return value key = key.l...
def env_key(key, default): """ Try to get `key` from the environment. This mutates `key` to replace dots with underscores and makes it all uppercase. my.database.host => MY_DATABASE_HOST """ env = key.upper().replace('.', '_') return os.environ.get(env, default)
def set(self, name, value): """ Changes a setting value. This implements a locking mechanism to ensure some level of thread safety. :param str name: Setting key name. :param value: Setting value. """ if not self.settings.get('pyconfig.case_sensi...
def _update(self, conf_dict, base_name=None): """ Updates the current configuration with the values in `conf_dict`. :param dict conf_dict: Dictionary of key value settings. :param str base_name: Base namespace for setting keys. """ for name in conf_dict: # S...
def load(self, clear=False): """ Loads all the config plugin modules to build a working configuration. If there is a ``localconfig`` module on the python path, it will be loaded last, overriding other settings. :param bool clear: Clear out the previous settings before loading ...
def get(self, name, default, allow_default=True): """ Return a setting value. :param str name: Setting key name. :param default: Default value of setting if it's not explicitly set. :param bool allow_default: If true, use the parameter default as ...
def init(self, hosts=None, cacert=None, client_cert=None, client_key=None): """ Handle creating the new etcd client instance and other business. :param hosts: Host string or list of hosts (default: `'127.0.0.1:2379'`) :param cacert: CA cert filename (optional) :param client_cert...
def load(self, prefix=None, depth=None): """ Return a dictionary of settings loaded from etcd. """ prefix = prefix or self.prefix prefix = '/' + prefix.strip('/') + '/' if depth is None: depth = self.inherit_depth if not self.configured: ...
def get_watcher(self): """ Return a etcd watching generator which yields events as they happen. """ if not self.watching: raise StopIteration() return self.client.eternal_watch(self.prefix, recursive=True)
def start_watching(self): """ Begins watching etcd for changes. """ # Don't create a new watcher thread if we already have one running if self.watcher and self.watcher.is_alive(): return # Create a new watcher thread and start it self.watcher = Watcher() self...
def _parse_hosts(self, hosts): """ Return hosts parsed into a tuple of tuples. :param hosts: String or list of hosts """ # Default host if hosts is None: return # If it's a string, we allow comma separated strings if isinstance(hosts, six.st...
def _parse_jetconfig(self): """ Undocumented cross-compatability functionality with jetconfig (https://github.com/shakefu/jetconfig) that is very sloppy. """ conf = env('JETCONFIG_ETCD', None) if not conf: return import urlparse auth = None...
def main(): """ Main script for `pyconfig` command. """ parser = argparse.ArgumentParser(description="Helper for working with " "pyconfigs") target_group = parser.add_mutually_exclusive_group() target_group.add_argument('-f', '--filename', help="parse an individual file ...
def _handle_module(args): """ Handles the -m argument. """ module = _get_module_filename(args.module) if not module: _error("Could not load module or package: %r", args.module) elif isinstance(module, Unparseable): _error("Could not determine module source: %r", args.module) ...
def _error(msg, *args): """ Print an error message and exit. :param msg: A message to print :type msg: str """ print(msg % args, file=sys.stderr) sys.exit(1)
def _get_module_filename(module): """ Return the filename of `module` if it can be imported. If `module` is a package, its directory will be returned. If it cannot be imported ``None`` is returned. If the ``__file__`` attribute is missing, or the module or package is a compiled egg, then an :...
def _parse_and_output(filename, args): """ Parse `filename` appropriately and then output calls according to the `args` specified. :param filename: A file or directory :param args: Command arguments :type filename: str """ relpath = os.path.dirname(filename) if os.path.isfile(filen...
def _output(calls, args): """ Outputs `calls`. :param calls: List of :class:`_PyconfigCall` instances :param args: :class:`~argparse.ArgumentParser` instance :type calls: list :type args: argparse.ArgumentParser """ # Sort the keys appropriately if args.natural_sort or args.source:...
def _format_call(call, args): """ Return `call` formatted appropriately for `args`. :param call: A pyconfig call object :param args: Arguments from the command :type call: :class:`_PyconfigCall` """ out = '' if args.source: out += call.annotation() + '\n' if args.only_keys...
def _colorize(output): """ Return `output` colorized with Pygments, if available. """ if not pygments: return output # Available styles # ['monokai', 'manni', 'rrt', 'perldoc', 'borland', 'colorful', 'default', # 'murphy', 'vs', 'trac', 'tango', 'fruity', 'autumn', 'bw', 'emacs', ...
def _parse_dir(directory, relpath): """ Return a list of :class:`_PyconfigCall` from recursively parsing `directory`. :param directory: Directory to walk looking for python files :param relpath: Path to make filenames relative to :type directory: str :type relpath: str """ relpath ...
def _parse_file(filename, relpath=None): """ Return a list of :class:`_PyconfigCall` from parsing `filename`. :param filename: A file to parse :param relpath: Relative directory to strip (optional) :type filename: str :type relpath: str """ with open(filename, 'r') as source: s...
def _map_arg(arg): """ Return `arg` appropriately parsed or mapped to a usable value. """ # Grab the easy to parse values if isinstance(arg, _ast.Str): return repr(arg.s) elif isinstance(arg, _ast.Num): return arg.n elif isinstance(arg, _ast.Name): name = arg.id ...
def as_namespace(self, namespace=None): """ Return this call as if it were being assigned in a pyconfig namespace. If `namespace` is specified and matches the top level of this call's :attr:`key`, then that section of the key will be removed. """ key = self.key ...
def as_live(self): """ Return this call as if it were being assigned in a pyconfig namespace, but load the actual value currently available in pyconfig. """ key = self.get_key() default = pyconfig.get(key) if default: default = repr(default) e...
def as_call(self): """ Return this call as it is called in its source. """ default = self._default() default = ', ' + default if default else '' return "pyconfig.%s(%r%s)" % (self.method, self.get_key(), default)
def get_key(self): """ Return the call key, even if it has to be parsed from the source. """ if not isinstance(self.key, Unparseable): return self.key line = self.source[self.col_offset:] regex = re.compile('''pyconfig\.[eginst]+\(([^,]+).*?\)''') ma...
def _default_value_only(self): """ Return only the default value, if there is one. """ line = self.source[self.col_offset:] regex = re.compile('''pyconfig\.[eginst]+\(['"][^)]+?['"], ?(.*?)\)''') match = regex.match(line) if not match: return '' ...
def _default(self): """ Return the default argument, formatted nicely. """ try: # Check if it's iterable iter(self.default) except TypeError: return repr(self.default) # This is to look for unparsable values, and if we find one, we tr...
def _get_param_names(self): """ Get mappable parameters from YAML. """ template = Template(self.yaml_string) names = ['yaml_string'] # always include the template for match in re.finditer(template.pattern, template.template): name = match.group('named') or ma...
def _get_dataset(self, X, y=None): """ Construct a pylearn2 dataset. Parameters ---------- X : array_like Training examples. y : array_like, optional Labels. """ from pylearn2.datasets import DenseDesignMatrix X = np.asarr...
def _get_labels(self, y): """ Construct pylearn2 dataset labels. Parameters ---------- y : array_like, optional Labels. """ y = np.asarray(y) if y.ndim == 1: return y.reshape((y.size, 1)) assert y.ndim == 2 return y
def fit(self, X, y=None): """ Build a trainer and run main_loop. Parameters ---------- X : array_like Training examples. y : array_like, optional Labels. """ from pylearn2.config import yaml_parse from pylearn2.train import...
def _predict(self, X, method='fprop'): """ Get model predictions. See pylearn2.scripts.mlp.predict_csv and http://fastml.com/how-to-get-predictions-from-pylearn2/. Parameters ---------- X : array_like Test dataset. method : str Mo...
def _get_labels(self, y): """ Construct pylearn2 dataset labels. Parameters ---------- y : array_like, optional Labels. """ y = np.asarray(y) assert y.ndim == 1 # convert to one-hot labels = np.unique(y).tolist() oh = n...
def load(self): """ Load the dataset using pylearn2.config.yaml_parse. """ from pylearn2.config import yaml_parse from pylearn2.datasets import Dataset dataset = yaml_parse.load(self.yaml_string) assert isinstance(dataset, Dataset) data = dataset.iterator...
def fit(self): """ Fits the model with random restarts. :return: """ self.model.optimize_restarts(num_restarts=self.num_restarts, verbose=False)
def _create_kernel(self): """ creates an additive kernel """ # Check kernels kernels = self.kernel_params if not isinstance(kernels, list): raise RuntimeError('Must provide enumeration of kernels') for kernel in kernels: if sorted(list(kern...
def fit_and_score_estimator(estimator, parameters, cv, X, y=None, scoring=None, iid=True, n_jobs=1, verbose=1, pre_dispatch='2*n_jobs'): """Fit and score an estimator with cross-validation This function is basically a copy of sklearn's model_selection...
def init_subclass_by_name(baseclass, short_name, params): """ Find the subclass, `kls` of baseclass with class attribute `short_name` that matches the supplied `short_name`, and then instantiate and return that class with: return kls(**params) This function also tries its best to catch any...
def dict_merge(base, top): """Recursively merge two dictionaries, with the elements from `top` taking precedence over elements from `top`. Returns ------- out : dict A new dict, containing the merged records. """ out = dict(top) for key in base: if key in top: ...
def in_directory(path): """Context manager (with statement) that changes the current directory during the context. """ curdir = os.path.abspath(os.curdir) os.chdir(path) yield os.chdir(curdir)
def format_timedelta(td_object): """Format a timedelta object for display to users Returns ------- str """ def get_total_seconds(td): # timedelta.total_seconds not in py2.6 return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 1e6) / 1e6 seconds = i...
def _assert_all_finite(X): """Like assert_all_finite, but only for ndarray.""" X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent # false positives from overflow in sum method if (X.dt...
def _warn_if_not_finite(X): """UserWarning if array contains non-finite elements""" X = np.asanyarray(X) # First try an O(n) time, O(1) space solution for the common case that # everything is finite; fall back to O(n) space np.isfinite to prevent # false positives from overflow in sum method if ...
def num_samples(x, is_nested=False): """Return number of samples in array-like x.""" if hasattr(x, 'fit'): # Don't get num_samples from an ensembles length! raise TypeError('Expected sequence or array-like, got ' 'estimator %s' % x) if is_nested: return sum(n...
def check_arrays(*arrays, **options): """Check that all arrays have consistent first dimensions. Checks whether all objects in arrays have the same shape or length. By default lists and tuples are converted to numpy arrays. It is possible to enforce certain properties, such as dtype, continguity a...
def is_repeated_suggestion(params, history): """ Parameters ---------- params : dict Trial param set history : list of 3-tuples History of past function evaluations. Each element in history should be a tuple `(params, score, status)`, where `pa...
def suggest(self, history, searchspace): """ Suggest params to maximize an objective function based on the function evaluation history using a tree of Parzen estimators (TPE), as implemented in the hyperopt package. Use of this function requires that hyperopt be installed. ...
def _merge_defaults(self, config): """The config object loads its values from two sources, with the following precedence: 1. data/default_config.yaml 2. The config file itself, passed in to this object in the constructor as `path`. in case of conflict, th...
def fromdict(cls, config, check_fields=True): """Create a Config object from config dict directly.""" m = super(Config, cls).__new__(cls) m.path = '.' m.verbose = False m.config = m._merge_defaults(config) if check_fields: m._check_fields() return m
def get_value(self, field, default=None): """Get an entry from within a section, using a '/' delimiter""" section, key = field.split('/') return self.get_section(section).get(key, default)
def estimator(self): """Get the estimator, an instance of a (subclass of) sklearn.base.BaseEstimator It can be loaded either from a pickle, from a string using eval(), or from an entry point. e.g. estimator: # only one of the following can actually be activ...
def sha1(self): """SHA1 hash of the config file itself.""" with open(self.path, 'rb') as f: return hashlib.sha1(f.read()).hexdigest()
def get_best_candidate(self): """ Returns ---------- best_candidate : the best candidate hyper-parameters as defined by """ # TODO make this best mean response self.incumbent = self.surrogate.Y.max() # Objective function def z(x): # TO...
def plot_1(data, *args): """Plot 1. All iterations (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) return build_scatter_tooltip( x=df_all['id'], y=df_all['mean_test_score'], tt=df_params, title='All Iterations')
def plot_2(data, *args): """Plot 2. Running best score (scatter plot)""" df_all = pd.DataFrame(data) df_params = nonconstant_parameters(data) x = [df_all['id'][0]] y = [df_all['mean_test_score'][0]] params = [df_params.loc[0]] for i in range(len(df_all)): if df_all['mean_test_score']...
def plot_3(data, ss, *args): """t-SNE embedding of the parameters, colored by score """ if len(data) <= 1: warnings.warn("Only one datapoint. Could not compute t-SNE embedding.") return None scores = np.array([d['mean_test_score'] for d in data]) # maps each parameters to a vector ...
def plot_4(data, *args): """Scatter plot of score vs each param """ params = nonconstant_parameters(data) scores = np.array([d['mean_test_score'] for d in data]) order = np.argsort(scores) for key in params.keys(): if params[key].dtype == np.dtype('bool'): params[key] = para...
def add_jump(self, name, min, max, num, warp=None, var_type=float): """ An integer/float-valued enumerable with `num` items, bounded between [`min`, `max`]. Note that the right endpoint of the interval includes `max`. This is a wrapper around the add_enum. `jump` can be a float or int. ...
def add_int(self, name, min, max, warp=None): """An integer-valued dimension bounded between `min` <= x <= `max`. Note that the right endpoint of the interval includes `max`. When `warp` is None, the base measure associated with this dimension is a categorical distribution with each wei...
def add_float(self, name, min, max, warp=None): """A floating point-valued dimension bounded `min` <= x < `max` When `warp` is None, the base measure associated with this dimension is a uniform distribution on [min, max). With `warp == 'log'`, the base measure is a uniform distribution ...
def add_enum(self, name, choices): """An enumeration-valued dimension. The base measure associated with this dimension is a categorical distribution with equal weight on each element in `choices`. """ if not isinstance(choices, Iterable): raise ValueError('variable %...
def bresenham(x0, y0, x1, y1): """Yield integer coordinates on the line from (x0, y0) to (x1, y1). Input coordinates should be integers. The result will contain both the start and the end point. """ dx = x1 - x0 dy = y1 - y0 xsign = 1 if dx > 0 else -1 ysign = 1 if dy > 0 else -1 ...
def log_callback(wrapped_function): """Decorator that produces DEBUG level log messages before and after calling a parser method. If a callback raises an IgnoredMatchException the log will show 'IGNORED' instead to indicate that the parser will not create any objects from the matched string. E...
def find_match(self): """Try to find a pattern that matches the source and calll a parser method to create Python objects. A callback that raises an IgnoredMatchException indicates that the given string data is ignored by the parser and no objects are created. If none of the pa...
def add_child(self, child): """If the given object is an instance of Child add it to self and register self as a parent. """ if not isinstance(child, ChildMixin): raise TypeError( 'Requires instance of TreeElement. ' 'Got {}'.format(type(child)...
def get_ip_packet(data, client_port, server_port, is_loopback=False): """ if client_port is 0 any client_port is good """ header = _loopback if is_loopback else _ethernet try: header.unpack(data) except Exception as ex: raise ValueError('Bad header: %s' % ex) tcp_p = getattr(header...
def listening_ports(): """ Reads listening ports from /proc/net/tcp """ ports = [] if not os.path.exists(PROC_TCP): return ports with open(PROC_TCP) as fh: for line in fh: if '00000000:0000' not in line: continue parts = line.lstrip(' ').split(' ...
def report(self): """ get stats & show them """ self._output.write('\r') sort_by = 'avg' results = {} for key, latencies in self._latencies_by_method.items(): result = {} result['count'] = len(latencies) result['avg'] = sum(latencies) / len(la...
def of_structs(cls, a, b): """ Diff two thrift structs and return the result as a ThriftDiff instance """ t_diff = ThriftDiff(a, b) t_diff._do_diff() return t_diff
def of_messages(cls, msg_a, msg_b): """ Diff two thrift messages by comparing their args, raises exceptions if for some reason the messages can't be diffed. Only args of type 'struct' are compared. Returns a list of ThriftDiff results - one for each struct arg """ ...
def can_diff(msg_a, msg_b): """ Check if two thrift messages are diff ready. Returns a tuple of (boolean, reason_string), i.e. (False, reason_string) if the messages can not be diffed along with the reason and (True, None) for the opposite case """ if msg_a.metho...
def is_isomorphic_to(self, other): """ Returns true if all fields of other struct are isomorphic to this struct's fields """ return (isinstance(other, self.__class__) and len(self.fields) == len(other.fields) and all...
def is_isomorphic_to(self, other): """ Returns true if other field's meta data (everything except value) is same as this one """ return (isinstance(other, self.__class__) and self.field_type == other.field_type and self.field_id == other.field_id)
def read(cls, data, protocol=None, fallback_protocol=TBinaryProtocol, finagle_thrift=False, max_fields=MAX_FIELDS, max_list_size=MAX_LIST_SIZE, max_map_size=MAX_MAP_SIZE, max_set_size=MAX_SET_SIZE, read_values=False)...