function
stringlengths
11
56k
repo_name
stringlengths
5
60
features
list
def name(self): # The name of the section on a proxy is read-only. return self._name
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, msg=''): self.message = msg Exception.__init__(self, msg)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, section): Error.__init__(self, 'No section: %r' % (section,)) self.section = section self.args = (section, )
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, section, source=None, lineno=None): msg = [repr(section), " already exists"] if source is not None: message = ["While reading from ", repr(source)] if lineno is not None: message.append(" [line {0:2d}]".format(lineno)) message.append(": section ") message.extend(msg) msg = message else: msg.insert(0, "Section ") Error.__init__(self, "".join(msg)) self.section = section self.source = source self.lineno = lineno self.args = (section, source, lineno)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, section, option, source=None, lineno=None): msg = [repr(option), " in section ", repr(section), " already exists"] if source is not None: message = ["While reading from ", repr(source)] if lineno is not None: message.append(" [line {0:2d}]".format(lineno)) message.append(": option ") message.extend(msg) msg = message else: msg.insert(0, "Option ") Error.__init__(self, "".join(msg)) self.section = section self.option = option self.source = source self.lineno = lineno self.args = (section, option, source, lineno)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, option, section): Error.__init__(self, "No option %r in section: %r" % (option, section)) self.option = option self.section = section self.args = (option, section)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, option, section, msg): Error.__init__(self, msg) self.option = option self.section = section self.args = (option, section, msg)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, option, section, rawval, reference): msg = ("Bad value substitution:\n" "\tsection: [%s]\n" "\toption : %s\n" "\tkey : %s\n" "\trawval : %s\n" % (section, option, reference, rawval)) InterpolationError.__init__(self, option, section, msg) self.reference = reference self.args = (option, section, rawval, reference)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, option, section, rawval): msg = ("Value interpolation too deeply recursive:\n" "\tsection: [%s]\n" "\toption : %s\n" "\trawval : %s\n" % (section, option, rawval)) InterpolationError.__init__(self, option, section, msg) self.args = (option, section, rawval)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, source=None, filename=None): # Exactly one of `source'/`filename' arguments has to be given. # `filename' kept for compatibility. if filename and source: raise ValueError("Cannot specify both `filename' and `source'. " "Use `source'.") elif not filename and not source: raise ValueError("Required argument `source' not given.") elif filename: source = filename Error.__init__(self, 'Source contains parsing errors: %r' % source) self.source = source self.errors = [] self.args = (source, )
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def filename(self): """Deprecated, use `source'.""" warnings.warn( "The 'filename' attribute will be removed in future versions. " "Use 'source' instead.", DeprecationWarning, stacklevel=2 ) return self.source
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def filename(self, value): """Deprecated, user `source'.""" warnings.warn( "The 'filename' attribute will be removed in future versions. " "Use 'source' instead.", DeprecationWarning, stacklevel=2 ) self.source = value
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, filename, lineno, line): Error.__init__( self, 'File contains no section headers.\nfile: %r, line: %d\n%r' % (filename, lineno, line)) self.source = filename self.lineno = lineno self.line = line self.args = (filename, lineno, line)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def before_get(self, parser, section, option, value, defaults): return value
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def before_read(self, parser, section, option, value): return value
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def before_get(self, parser, section, option, value, defaults): L = [] self._interpolate_some(parser, option, L, value, section, defaults, 1) return ''.join(L)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _interpolate_some(self, parser, option, accum, rest, section, map, depth): if depth > MAX_INTERPOLATION_DEPTH: raise InterpolationDepthError(option, section, rest) while rest: p = rest.find("%") if p < 0: accum.append(rest) return if p > 0: accum.append(rest[:p]) rest = rest[p:] # p is no longer used c = rest[1:2] if c == "%": accum.append("%") rest = rest[2:] elif c == "(": m = self._KEYCRE.match(rest) if m is None: raise InterpolationSyntaxError(option, section, "bad interpolation variable reference %r" % rest) var = parser.optionxform(m.group(1)) rest = rest[m.end():] try: v = map[var] except KeyError: raise InterpolationMissingOptionError( option, section, rest, var) if "%" in v: self._interpolate_some(parser, option, accum, v, section, map, depth + 1) else: accum.append(v) else: raise InterpolationSyntaxError( option, section, "'%%' must be followed by '%%' or '(', " "found: %r" % (rest,))
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def before_get(self, parser, section, option, value, defaults): L = [] self._interpolate_some(parser, option, L, value, section, defaults, 1) return ''.join(L)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _interpolate_some(self, parser, option, accum, rest, section, map, depth): if depth > MAX_INTERPOLATION_DEPTH: raise InterpolationDepthError(option, section, rest) while rest: p = rest.find("$") if p < 0: accum.append(rest) return if p > 0: accum.append(rest[:p]) rest = rest[p:] # p is no longer used c = rest[1:2] if c == "$": accum.append("$") rest = rest[2:] elif c == "{": m = self._KEYCRE.match(rest) if m is None: raise InterpolationSyntaxError(option, section, "bad interpolation variable reference %r" % rest) path = m.group(1).split(':') rest = rest[m.end():] sect = section opt = option try: if len(path) == 1: opt = parser.optionxform(path[0]) v = map[opt] elif len(path) == 2: sect = path[0] opt = parser.optionxform(path[1]) v = parser.get(sect, opt, raw=True) else: raise InterpolationSyntaxError( option, section, "More than one ':' found: %r" % (rest,)) except (KeyError, NoSectionError, NoOptionError): raise InterpolationMissingOptionError( option, section, rest, ":".join(path)) if "$" in v: self._interpolate_some(parser, opt, accum, v, sect, dict(parser.items(sect, raw=True)), depth + 1) else: accum.append(v) else: raise InterpolationSyntaxError( option, section, "'$' must be followed by '$' or '{', " "found: %r" % (rest,))
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def before_get(self, parser, section, option, value, vars): rawval = value depth = MAX_INTERPOLATION_DEPTH while depth: # Loop through this until it's done depth -= 1 if value and "%(" in value: replace = functools.partial(self._interpolation_replace, parser=parser) value = self._KEYCRE.sub(replace, value) try: value = value % vars except KeyError as e: raise InterpolationMissingOptionError( option, section, rawval, e.args[0]) else: break if value and "%(" in value: raise InterpolationDepthError(option, section, rawval) return value
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _interpolation_replace(match, parser): s = match.group(1) if s is None: return match.group() else: return "%%(%s)s" % parser.optionxform(s)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, defaults=None, dict_type=_default_dict, allow_no_value=False, *, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section=DEFAULTSECT, interpolation=_UNSET): self._dict = dict_type self._sections = self._dict() self._defaults = self._dict() self._proxies = self._dict() self._proxies[default_section] = SectionProxy(self, default_section) if defaults: for key, value in defaults.items(): self._defaults[self.optionxform(key)] = value self._delimiters = tuple(delimiters) if delimiters == ('=', ':'): self._optcre = self.OPTCRE_NV if allow_no_value else self.OPTCRE else: d = "|".join(re.escape(d) for d in delimiters) if allow_no_value: self._optcre = re.compile(self._OPT_NV_TMPL.format(delim=d), re.VERBOSE) else: self._optcre = re.compile(self._OPT_TMPL.format(delim=d), re.VERBOSE) self._comment_prefixes = tuple(comment_prefixes or ()) self._inline_comment_prefixes = tuple(inline_comment_prefixes or ()) self._strict = strict self._allow_no_value = allow_no_value self._empty_lines_in_values = empty_lines_in_values self.default_section=default_section self._interpolation = interpolation if self._interpolation is _UNSET: self._interpolation = self._DEFAULT_INTERPOLATION if self._interpolation is None: self._interpolation = Interpolation()
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def sections(self): """Return a list of section names, excluding [DEFAULT]""" # self._sections will never have [DEFAULT] in it return list(self._sections.keys())
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def has_section(self, section): """Indicate whether the named section is present in the configuration. The DEFAULT section is not acknowledged. """ return section in self._sections
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def read(self, filenames, encoding=None): """Read and parse a filename or a list of filenames. Files that cannot be opened are silently ignored; this is designed so that you can specify a list of potential configuration file locations (e.g. current directory, user's home directory, systemwide directory), and all existing configuration files in the list will be read. A single filename may also be given. Return list of successfully read files. """ if isinstance(filenames, str): filenames = [filenames] read_ok = [] for filename in filenames: try: with open(filename, encoding=encoding) as fp: self._read(fp, filename) except OSError: continue read_ok.append(filename) return read_ok
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def read_string(self, string, source='<string>'): """Read configuration from a given string.""" sfile = io.StringIO(string) self.read_file(sfile, source)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def readfp(self, fp, filename=None): """Deprecated, use read_file instead.""" warnings.warn( "This method will be removed in future versions. " "Use 'parser.read_file()' instead.", DeprecationWarning, stacklevel=2 ) self.read_file(fp, source=filename)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _get(self, section, conv, option, **kwargs): return conv(self.get(section, option, **kwargs))
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def getfloat(self, section, option, *, raw=False, vars=None, fallback=_UNSET): try: return self._get(section, float, option, raw=raw, vars=vars) except (NoSectionError, NoOptionError): if fallback is _UNSET: raise else: return fallback
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def items(self, section=_UNSET, raw=False, vars=None): """Return a list of (name, value) tuples for each option in a section. All % interpolations are expanded in the return values, based on the defaults passed into the constructor, unless the optional argument `raw' is true. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents overrides any pre-existing defaults. The section DEFAULT is special. """ if section is _UNSET: return super().items() d = self._defaults.copy() try: d.update(self._sections[section]) except KeyError: if section != self.default_section: raise NoSectionError(section) # Update with the entry specific variables if vars: for key, value in vars.items(): d[self.optionxform(key)] = value value_getter = lambda option: self._interpolation.before_get(self, section, option, d[option], d) if raw: value_getter = lambda option: d[option] return [(option, value_getter(option)) for option in d.keys()]
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def optionxform(self, optionstr): return optionstr.lower()
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def set(self, section, option, value=None): """Set an option.""" if value: value = self._interpolation.before_set(self, section, option, value) if not section or section == self.default_section: sectdict = self._defaults else: try: sectdict = self._sections[section] except KeyError: raise NoSectionError(section) sectdict[self.optionxform(option)] = value
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _write_section(self, fp, section_name, section_items, delimiter): """Write a single section to the specified `fp'.""" fp.write("[{}]\n".format(section_name)) for key, value in section_items: value = self._interpolation.before_write(self, section_name, key, value) if value is not None or not self._allow_no_value: value = delimiter + str(value).replace('\n', '\n\t') else: value = "" fp.write("{}{}\n".format(key, value)) fp.write("\n")
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def remove_section(self, section): """Remove a file section.""" existed = section in self._sections if existed: del self._sections[section] del self._proxies[section] return existed
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __setitem__(self, key, value): # To conform with the mapping protocol, overwrites existing values in # the section. # XXX this is not atomic if read_dict fails at any point. Then again, # no update method in configparser is atomic in this implementation. if key == self.default_section: self._defaults.clear() elif key in self._sections: self._sections[key].clear() self.read_dict({key: value})
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __contains__(self, key): return key == self.default_section or self.has_section(key)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __iter__(self): # XXX does it break when underlying container state changed? return itertools.chain((self.default_section,), self._sections.keys())
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _join_multiline_values(self): defaults = self.default_section, self._defaults all_sections = itertools.chain((defaults,), self._sections.items()) for section, options in all_sections: for name, val in options.items(): if isinstance(val, list): val = '\n'.join(val).rstrip() options[name] = self._interpolation.before_read(self, section, name, val)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _unify_values(self, section, vars): """Create a sequence of lookups with 'vars' taking priority over the 'section' which takes priority over the DEFAULTSECT. """ sectiondict = {} try: sectiondict = self._sections[section] except KeyError: if section != self.default_section: raise NoSectionError(section) # Update with the entry specific variables vardict = {} if vars: for key, value in vars.items(): if value is not None: value = str(value) vardict[self.optionxform(key)] = value return _ChainMap(vardict, sectiondict, self._defaults)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _validate_value_types(self, *, section="", option="", value=""): """Raises a TypeError for non-string values. The only legal non-string value if we allow valueless options is None, so we need to check if the value is a string if: - we do not allow valueless options, or - we allow valueless options but the value is not None For compatibility reasons this method is not used in classic set() for RawConfigParsers. It is invoked in every case for mapping protocol access and in ConfigParser.set(). """ if not isinstance(section, str): raise TypeError("section names must be strings") if not isinstance(option, str): raise TypeError("option keys must be strings") if not self._allow_no_value or value: if not isinstance(value, str): raise TypeError("option values must be strings")
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def set(self, section, option, value=None): """Set an option. Extends RawConfigParser.set by validating type and interpolation syntax on the value.""" self._validate_value_types(option=option, value=value) super().set(section, option, value)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) warnings.warn( "The SafeConfigParser class has been renamed to ConfigParser " "in Python 3.2. This alias will be removed in future versions." " Use ConfigParser directly instead.", DeprecationWarning, stacklevel=2 )
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, parser, name): """Creates a view on a section of the specified `name` in `parser`.""" self._parser = parser self._name = name
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __getitem__(self, key): if not self._parser.has_option(self._name, key): raise KeyError(key) return self._parser.get(self._name, key)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __delitem__(self, key): if not (self._parser.has_option(self._name, key) and self._parser.remove_option(self._name, key)): raise KeyError(key)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __len__(self): return len(self._options())
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def _options(self): if self._name != self._parser.default_section: return self._parser.options(self._name) else: return self._parser.defaults()
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def getint(self, option, fallback=None, *, raw=False, vars=None): return self._parser.getint(self._name, option, raw=raw, vars=vars, fallback=fallback)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def getboolean(self, option, fallback=None, *, raw=False, vars=None): return self._parser.getboolean(self._name, option, raw=raw, vars=vars, fallback=fallback)
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def parser(self): # The parser object of the proxy is read-only. return self._parser
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def name(self): # The name of the section on a proxy is read-only. return self._name
ArcherSys/ArcherSys
[ 3, 2, 3, 16, 1412356452 ]
def __init__(self, config): self.printer = config.get_printer() self.reactor = self.printer.get_reactor() self.name = config.get_name().split()[1] self.gcode = self.printer.lookup_object('gcode') gcode_macro = self.printer.load_object(config, 'gcode_macro') self.timer_gcode = gcode_macro.load_template(config, 'gcode') self.duration = config.getfloat('initial_duration', 0., minval=0.) self.timer_handler = None self.inside_timer = self.repeat = False self.printer.register_event_handler("klippy:ready", self._handle_ready) self.gcode.register_mux_command( "UPDATE_DELAYED_GCODE", "ID", self.name, self.cmd_UPDATE_DELAYED_GCODE, desc=self.cmd_UPDATE_DELAYED_GCODE_help)
KevinOConnor/klipper
[ 6307, 4329, 6307, 57, 1464190926 ]
def _gcode_timer_event(self, eventtime): self.inside_timer = True try: self.gcode.run_script(self.timer_gcode.render()) except Exception: logging.exception("Script running error") nextwake = self.reactor.NEVER if self.repeat: nextwake = eventtime + self.duration self.inside_timer = self.repeat = False return nextwake
KevinOConnor/klipper
[ 6307, 4329, 6307, 57, 1464190926 ]
def cmd_UPDATE_DELAYED_GCODE(self, gcmd): self.duration = gcmd.get_float('DURATION', minval=0.) if self.inside_timer: self.repeat = (self.duration != 0.) else: waketime = self.reactor.NEVER if self.duration: waketime = self.reactor.monotonic() + self.duration self.reactor.update_timer(self.timer_handler, waketime)
KevinOConnor/klipper
[ 6307, 4329, 6307, 57, 1464190926 ]
def __init__(self, default, values=None, type=None, on_change=None, doc=None): self.default = default self.values = values self.type = type self.on_change = on_change self.doc = doc self.__doc__ = self._docstring()
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def _docstring(self): default = "``default={}``".format(repr(self.default)) values = ( ", ``values={}``".format(repr(self.values)) if self.values is not None else "" ) on_change = ( ", ``on_change={}``".format(self.on_change.__name__) if self.on_change is not None else "" ) return "{}{}{}\n{}".format(default, values, on_change, self.doc or "")
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def __set__(self, obj, value): self._validate(value) obj._values[self.name] = value self._callback(obj)
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def _callback(self, obj): """Trigger any callbacks.""" if self.on_change is not None: self.on_change(obj)
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def __init__(self): self._values = {} self._loaded_files = [] # Set the default value of each ``Option`` for name, opt in self.options().items(): opt._validate(opt.default) self._values[name] = opt.default # Call hooks for each Option # (This must happen *after* all default values are set so that # logging can be properly configured. for opt in self.options().values(): opt._callback(self)
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def __setattr__(self, name, value): if name.startswith("_") or name in self.options().keys(): super().__setattr__(name, value) else: raise ValueError("{} is not a valid config option".format(name))
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def options(cls): """Return a dictionary of the ``Option`` objects for this config.""" return {k: v for k, v in cls.__dict__.items() if isinstance(v, Option)}
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def load_dict(self, dct): """Load a dictionary of configuration values.""" for k, v in dct.items(): setattr(self, k, v)
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def snapshot(self): """Return a snapshot of the current values of this configuration.""" return copy(self._values)
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def __init__(self, conf, **new_values): self.conf = conf self.new_values = new_values self.initial_values = conf.snapshot()
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def __exit__(self, *exc): """Reset config to initial values; reraise any exceptions.""" self.conf.load_dict(self.initial_values) return False
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def configure_joblib(conf): constants.joblib_memory = joblib.Memory( location=conf.FS_CACHE_DIRECTORY, verbose=conf.FS_CACHE_VERBOSITY )
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def always_zero(a, b): return 0
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def single_node_partitions(mechanism, purview, node_labels=None): for element in mechanism: element = tuple([element]) others = tuple(sorted(set(mechanism) - set(element))) part1 = Part(mechanism=element, purview=()) part2 = Part(mechanism=others, purview=purview) yield KPartition(part1, part2, node_labels=node_labels)
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def log(self): """Log current settings.""" log.info("PyPhi v%s", __about__.__version__) if self._loaded_files: log.info("Loaded configuration from %s", self._loaded_files) else: log.info("Using default configuration (no configuration file " "provided)") log.info("Current PyPhi configuration:\n %s", str(self))
wmayner/pyphi
[ 320, 79, 320, 8, 1396935070 ]
def setUp(self): self.oFile = vhdlFile.vhdlFile(lFile) self.assertIsNone(eError)
jeremiah-c-leary/vhdl-style-guide
[ 129, 31, 129, 57, 1499106283 ]
def test_rule_500_upper(self): oRule = ieee.rule_500() oRule.case = 'upper' self.assertTrue(oRule) self.assertEqual(oRule.name, 'ieee') self.assertEqual(oRule.identifier, '500') lExpected = [] lExpected.extend(range(5, 10)) lExpected.extend([12, 13, 15, 16, 17, 18]) lExpected.extend(range(26, 28)) lExpected.extend([30]) lExpected.extend(range(32, 34)) lExpected.extend(range(39, 44)) lExpected.extend([46, 47, 49, 50, 51, 52]) oRule.analyze(self.oFile) self.assertEqual(utils.extract_violation_lines_from_violation_object(oRule.violations), lExpected)
jeremiah-c-leary/vhdl-style-guide
[ 129, 31, 129, 57, 1499106283 ]
def test_lva(db_session, client): lva = clubs.lva(owner=users.john()) add_fixtures(db_session, lva) res = client.get("/clubs/{id}".format(id=lva.id)) assert res.status_code == 200 assert res.json == { "id": lva.id, "name": "LV Aachen", "timeCreated": "2015-12-24T12:34:56+00:00", "website": "http://www.lv-aachen.de", "isWritable": False, "owner": {"id": lva.owner.id, "name": lva.owner.name}, }
skylines-project/skylines
[ 367, 102, 367, 81, 1324989203 ]
def test_writable(db_session, client): lva = clubs.lva() john = users.john(club=lva) add_fixtures(db_session, lva, john) res = client.get("/clubs/{id}".format(id=lva.id), headers=auth_for(john)) assert res.status_code == 200 assert res.json == { "id": lva.id, "name": "LV Aachen", "timeCreated": "2015-12-24T12:34:56+00:00", "website": "http://www.lv-aachen.de", "isWritable": True, "owner": None, }
skylines-project/skylines
[ 367, 102, 367, 81, 1324989203 ]
def copy_file(source, destination): """ :param source: The source of the folder for copying :param destination: The destination folder for the file :return: """ destination_folder = os.path.join(settings.BASE_DIR, os.path.dirname(destination)) if not os.path.exists(destination_folder): os.mkdir(destination_folder) print("Copying {0}".format(source)) shutil.copy(os.path.join(settings.BASE_DIR, source), os.path.join(settings.BASE_DIR, destination))
BirkbeckCTP/janeway
[ 143, 55, 143, 533, 1499695733 ]
def mycb(so_far, total): print('{0} kb transferred out of {1}'.format(so_far / 1024, total / 1024))
BirkbeckCTP/janeway
[ 143, 55, 143, 533, 1499695733 ]
def handle_directory(tmp_path, start_time): print("Copying to backup dir") file_name = '{0}.zip'.format(start_time) copy_file('files/temp/{0}'.format(file_name), settings.BACKUP_DIR)
BirkbeckCTP/janeway
[ 143, 55, 143, 533, 1499695733 ]
def send_email(start_time, e, success=False): admins = models.Account.objects.filter(is_superuser=True) message = '' if not success: message = 'There was an error during the backup process.\n\n ' send_mail( 'Backup', '{0}{1}.'.format(message, e), 'backup@janeway', [user.email for user in admins], fail_silently=False, )
BirkbeckCTP/janeway
[ 143, 55, 143, 533, 1499695733 ]
def setUpClass(cls): super().setUpClass() cls.account_obj = cls.env["account.account"] cls.model_obj = cls.env["ir.model"] cls.field_obj = cls.env["ir.model.fields"] cls.invoice = cls.env["account.move"].create( {"journal_id": cls.journal.id, "partner_id": cls.partner.id} ) # Mock data for testing model dimension, by_sequence with fitered vals = { "name": "A", "line_ids": [ # use sequence as record identifier (0, 0, {"value": "percent", "sequence": 1001}), (0, 0, {"value": "balance", "sequence": 1002}), ], } cls.payterm_a = cls.env["account.payment.term"].create(vals)
OCA/account-analytic
[ 78, 321, 78, 47, 1402916118 ]
def test_invoice_line_dimension_by_sequence(self): """If dimension is by sequence, I expect, - No duplicated sequence - Selection allowed by sequence, i.e., Concept then Type """ invoice_line_obj = self.env["account.move.line"] # Test no dimension with any sequence values = { "name": "test no sequence", "price_unit": 1, "account_id": self.account.id, "move_id": self.invoice.id, "analytic_account_id": self.analytic_account.id, } line = invoice_line_obj.create(values) res = line._compute_analytic_tags_domain() self.assertFalse(res["domain"]["analytic_tag_ids"]) # Now, user will see tags in sequence 1) Type 2) Concept self.dimension_1.write({"required": False, "by_sequence": True, "sequence": 1}) with self.assertRaises(ValidationError): self.dimension_2.write( {"required": False, "by_sequence": True, "sequence": 1} ) self.dimension_2.write({"required": False, "by_sequence": True, "sequence": 2}) # Now, user will see tags in sequence 1) Type 2) Concept values = { "name": "test sequence", "price_unit": 1, "account_id": self.account.id, "move_id": self.invoice.id, "analytic_account_id": self.analytic_account.id, } line = invoice_line_obj.create(values) # First selection, dimension 1 tag shouldn't be in the domain res = line._compute_analytic_tags_domain() tag_ids = res["domain"]["analytic_tag_ids"][0][2] self.assertNotIn(self.analytic_tag_2a.id, tag_ids) # Select a dimension 1 tag line.analytic_tag_ids += self.analytic_tag_1a res = line._compute_analytic_tags_domain() tag_ids = res["domain"]["analytic_tag_ids"][0][2] # Test that all dimension 1 tags are not in list type_tag_ids = [self.analytic_tag_1a.id, self.analytic_tag_1b.id] for type_tag_id in type_tag_ids: self.assertNotIn(type_tag_id, tag_ids)
OCA/account-analytic
[ 78, 321, 78, 47, 1402916118 ]
def setUpClass(cls): super().setUpClass()
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def tearDownClass(cls): super().tearDownClass()
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def tearDown(self): super().tearDown()
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def test_create_sftp_input_without_name(self): (sample_input, sample_files) = self._get_sample_sftp_input() sample_input.name = None input_resource_response = self.bitmovin.inputs.SFTP.create(sample_input) self.assertIsNotNone(input_resource_response) self.assertIsNotNone(input_resource_response.resource) self.assertIsNotNone(input_resource_response.resource.id) self._compare_sftp_inputs(sample_input, input_resource_response.resource)
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def test_retrieve_sftp_input(self): (sample_input, sample_files) = self._get_sample_sftp_input() created_input_response = self.bitmovin.inputs.SFTP.create(sample_input) self.assertIsNotNone(created_input_response) self.assertIsNotNone(created_input_response.resource) self.assertIsNotNone(created_input_response.resource.id) self._compare_sftp_inputs(sample_input, created_input_response.resource) retrieved_input_response = self.bitmovin.inputs.SFTP.retrieve(created_input_response.resource.id) self.assertIsNotNone(retrieved_input_response) self.assertIsNotNone(retrieved_input_response.resource) self._compare_sftp_inputs(created_input_response.resource, retrieved_input_response.resource)
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def test_list_sftp_inputs(self): (sample_input, sample_files) = self._get_sample_sftp_input() created_input_response = self.bitmovin.inputs.SFTP.create(sample_input) self.assertIsNotNone(created_input_response) self.assertIsNotNone(created_input_response.resource) self.assertIsNotNone(created_input_response.resource.id) self._compare_sftp_inputs(sample_input, created_input_response.resource) inputs = self.bitmovin.inputs.SFTP.list() self.assertIsNotNone(inputs) self.assertIsNotNone(inputs.resource) self.assertIsNotNone(inputs.response) self.assertIsInstance(inputs.resource, list) self.assertIsInstance(inputs.response, Response) self.assertGreater(inputs.resource.__sizeof__(), 1)
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def _compare_sftp_inputs(self, first: SFTPInput, second: SFTPInput): """ :param first: SFTPInput :param second: SFTPInput :return: bool """ self.assertEqual(first.host, second.host) self.assertEqual(first.name, second.name) self.assertEqual(first.description, second.description) #self.assertEqual(first.username, second.username) # issue 574
bitmovin/bitmovin-python
[ 40, 21, 40, 3, 1478271716 ]
def __virtual__(): """ Only works on Windows systems with PyWin32 """ if not salt.utils.platform.is_windows(): return False, "WUA: Only available on Windows systems" if not HAS_PYWIN32: return False, "WUA: Requires PyWin32 libraries" if not salt.utils.win_update.HAS_PYWIN32: return False, "WUA: Missing Libraries required by salt.utils.win_update" if salt.utils.win_service.info("wuauserv")["StartType"] == "Disabled": return ( False, "WUA: The Windows Update service (wuauserv) must not be disabled", ) if salt.utils.win_service.info("msiserver")["StartType"] == "Disabled": return ( False, "WUA: The Windows Installer service (msiserver) must not be disabled", ) if salt.utils.win_service.info("BITS")["StartType"] == "Disabled": return ( False, "WUA: The Background Intelligent Transfer service (bits) must not " "be disabled", ) if not salt.utils.win_service.info("CryptSvc")["StartType"] == "Auto": return ( False, "WUA: The Cryptographic Services service (CryptSvc) must not be disabled", ) if salt.utils.win_service.info("TrustedInstaller")["StartType"] == "Disabled": return ( False, "WUA: The Windows Module Installer service (TrustedInstaller) must " "not be disabled", ) return True
saltstack/salt
[ 13089, 5388, 13089, 3074, 1298233016 ]
def get(name, download=False, install=False, online=True): """ .. versionadded:: 2017.7.0 Returns details for the named update Args: name (str): The name of the update you're searching for. This can be the GUID, a KB number, or any part of the name of the update. GUIDs and KBs are preferred. Run ``list`` to get the GUID for the update you're looking for. download (bool): Download the update returned by this function. Run this function first to see if the update exists, then set ``download=True`` to download the update. install (bool): Install the update returned by this function. Run this function first to see if the update exists, then set ``install=True`` to install the update. online (bool): Tells the Windows Update Agent go online to update its local update database. ``True`` will go online. ``False`` will use the local update database as is. Default is ``True`` .. versionadded:: 3001 Returns: dict: Returns a dict containing a list of updates that match the name if download and install are both set to False. Should usually be a single update, but can return multiple if a partial name is given. If download or install is set to true it will return the results of the operation. .. code-block:: cfg Dict of Updates: {'<GUID>': { 'Title': <title>, 'KB': <KB>, 'GUID': <the globally unique identifier for the update>, 'Description': <description>, 'Downloaded': <has the update been downloaded>, 'Installed': <has the update been installed>, 'Mandatory': <is the update mandatory>, 'UserInput': <is user input required>, 'EULAAccepted': <has the EULA been accepted>, 'Severity': <update severity>, 'NeedsReboot': <is the update installed and awaiting reboot>, 'RebootBehavior': <will the update require a reboot>, 'Categories': [ '<category 1>', '<category 2>', ... ] }} CLI Examples: .. code-block:: bash # Recommended Usage using GUID without braces # Use this to find the status of a specific update salt '*' win_wua.get 12345678-abcd-1234-abcd-1234567890ab # Use the following if you don't know the GUID: # Using a KB number # Not all updates have an associated KB salt '*' win_wua.get KB3030298 # Using part or all of the name of the update # Could possibly return multiple results # Not all updates have an associated KB salt '*' win_wua.get 'Microsoft Camera Codec Pack' """ # Create a Windows Update Agent instance wua = salt.utils.win_update.WindowsUpdateAgent(online=online) # Search for Update updates = wua.search(name) ret = {} # Download if download or install: ret["Download"] = wua.download(updates) # Install if install: ret["Install"] = wua.install(updates) return ret if ret else updates.list()
saltstack/salt
[ 13089, 5388, 13089, 3074, 1298233016 ]
def installed(summary=False, kbs_only=False): """ .. versionadded:: 3001 Get a list of all updates that are currently installed on the system. .. note:: This list may not necessarily match the Update History on the machine. This will only show the updates that apply to the current build of Windows. So, for example, the system may have shipped with Windows 10 Build 1607. That machine received updates to the 1607 build. Later the machine was upgraded to a newer feature release, 1803 for example. Then more updates were applied. This will only return the updates applied to the 1803 build and not those applied when the system was at the 1607 build. Args: summary (bool): Return a summary instead of a detailed list of updates. ``True`` will return a Summary, ``False`` will return a detailed list of installed updates. Default is ``False`` kbs_only (bool): Only return a list of KBs installed on the system. If this parameter is passed, the ``summary`` parameter will be ignored. Default is ``False`` Returns: dict: Returns a dictionary of either a Summary or a detailed list of updates installed on the system when ``kbs_only=False`` list: Returns a list of KBs installed on the system when ``kbs_only=True`` CLI Examples: .. code-block:: bash # Get a detailed list of all applicable updates installed on the system salt '*' win_wua.installed # Get a summary of all applicable updates installed on the system salt '*' win_wua.installed summary=True # Get a simple list of KBs installed on the system salt '*' win_wua.installed kbs_only=True """ # Create a Windows Update Agent instance. Since we're only listing installed # updates, there's no need to go online to update the Windows Update db wua = salt.utils.win_update.WindowsUpdateAgent(online=False) updates = wua.installed() # Get installed Updates objects results = updates.list() # Convert to list if kbs_only: list_kbs = set() for item in results: list_kbs.update(results[item]["KBs"]) return sorted(list_kbs) return updates.summary() if summary else results
saltstack/salt
[ 13089, 5388, 13089, 3074, 1298233016 ]
def install(names): """ .. versionadded:: 2017.7.0 Installs updates that match the list of identifiers. It may be easier to use the list_updates function and set ``install=True``. Args: names (str, list): A single update or a list of updates to install. This can be any combination of GUIDs, KB numbers, or names. GUIDs or KBs are preferred. .. note:: An error will be raised if there are more results than there are items in the names parameter Returns: dict: A dictionary containing the details about the installed updates CLI Examples: .. code-block:: bash # Normal Usage salt '*' win_wua.install KB12323211 """ # Create a Windows Update Agent instance wua = salt.utils.win_update.WindowsUpdateAgent() # Search for Updates updates = wua.search(names) if updates.count() == 0: raise CommandExecutionError("No updates found") # Make sure it's a list so count comparison is correct if isinstance(names, str): names = [names] if isinstance(names, int): names = [str(names)] if updates.count() > len(names): raise CommandExecutionError( "Multiple updates found, names need to be more specific" ) return wua.install(updates)
saltstack/salt
[ 13089, 5388, 13089, 3074, 1298233016 ]
def set_wu_settings( level=None, recommended=None, featured=None, elevated=None, msupdate=None, day=None, time=None,
saltstack/salt
[ 13089, 5388, 13089, 3074, 1298233016 ]
def get_wu_settings(): """ Get current Windows Update settings. Returns: dict: A dictionary of Windows Update settings: Featured Updates: Boolean value that indicates whether to display notifications for featured updates. Group Policy Required (Read-only): Boolean value that indicates whether Group Policy requires the Automatic Updates service. Microsoft Update: Boolean value that indicates whether to turn on Microsoft Update for other Microsoft Products Needs Reboot: Boolean value that indicates whether the machine is in a reboot pending state. Non Admins Elevated: Boolean value that indicates whether non-administrators can perform some update-related actions without administrator approval. Notification Level: Number 1 to 4 indicating the update level: 1. Never check for updates 2. Check for updates but let me choose whether to download and install them 3. Download updates but let me choose whether to install them 4. Install updates automatically Read Only (Read-only): Boolean value that indicates whether the Automatic Update settings are read-only. Recommended Updates: Boolean value that indicates whether to include optional or recommended updates when a search for updates and installation of updates is performed. Scheduled Day: Days of the week on which Automatic Updates installs or uninstalls updates. Scheduled Time: Time at which Automatic Updates installs or uninstalls updates. CLI Examples: .. code-block:: bash salt '*' win_wua.get_wu_settings """ ret = {} day = [ "Every Day", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ] # Initialize the PyCom system with salt.utils.winapi.Com(): # Create an AutoUpdate object obj_au = win32com.client.Dispatch("Microsoft.Update.AutoUpdate") # Create an AutoUpdate Settings Object obj_au_settings = obj_au.Settings # Populate the return dictionary ret["Featured Updates"] = obj_au_settings.FeaturedUpdatesEnabled ret["Group Policy Required"] = obj_au_settings.Required ret["Microsoft Update"] = _get_msupdate_status() ret["Needs Reboot"] = get_needs_reboot() ret["Non Admins Elevated"] = obj_au_settings.NonAdministratorsElevated ret["Notification Level"] = obj_au_settings.NotificationLevel ret["Read Only"] = obj_au_settings.ReadOnly ret["Recommended Updates"] = obj_au_settings.IncludeRecommendedUpdates ret["Scheduled Day"] = day[obj_au_settings.ScheduledInstallationDay] # Scheduled Installation Time requires special handling to return the time # in the right format if obj_au_settings.ScheduledInstallationTime < 10: ret["Scheduled Time"] = "0{}:00".format( obj_au_settings.ScheduledInstallationTime ) else: ret["Scheduled Time"] = "{}:00".format( obj_au_settings.ScheduledInstallationTime ) return ret
saltstack/salt
[ 13089, 5388, 13089, 3074, 1298233016 ]
def get_allowed_auths(self, username): return "publickey,password"
yaybu/touchdown
[ 11, 4, 11, 17, 1410353271 ]
def check_auth_publickey(self, username, key): return paramiko.AUTH_SUCCESSFUL
yaybu/touchdown
[ 11, 4, 11, 17, 1410353271 ]
def check_channel_exec_request(self, channel, command): return True
yaybu/touchdown
[ 11, 4, 11, 17, 1410353271 ]
def check_channel_pty_request( self, channel, term, width, height, pixelwidth, pixelheight, modes
yaybu/touchdown
[ 11, 4, 11, 17, 1410353271 ]
def __enter__(self): self.listen_socket = socket.socket() self.listen_socket.bind(("0.0.0.0", 0)) self.listen_socket.listen(1) self.address, self.port = self.listen_socket.getsockname() self.fixtures.push(lambda *exc_info: self.listen_socket.close()) self.event = threading.Event() self.ssh_connection = self.workspace.add_ssh_connection( name="test-ssh-connection", hostname=self.address, port=self.port ) self.listen_thread = threading.Thread(target=self.server_thread) self.listen_thread.daemon = True self.listen_thread.start() return self
yaybu/touchdown
[ 11, 4, 11, 17, 1410353271 ]
def update(self, prediction_probs, eviction_mask, oracle_scores): """Updates the value of the metric based on a batch of data. Args: prediction_probs (torch.FloatTensor): batch of probability distributions over cache lines of shape (batch_size, num_cache_lines), each corresponding to a cache access. In each distribution, the lines are ordered from top-1 to top-num_cache_lines. eviction_mask (torch.ByteTensor): of shape (batch_size), where eviction_mask[i] = True if the i-th cache access results in an eviction. The metric value is tracked for two populations: (i) all cache accesses and (ii) for evictions. oracle_scores (list[list[float]]): the oracle scores of the cache lines, of shape (batch_size, num_cache_lines). """ raise NotImplementedError()
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def write_to_tensorboard(self, tb_writer, tb_tag, step): """Writes the value of the tracked metric(s) to tensorboard. Args: tb_writer (tf.Writer): tensorboard writer to write to. tb_tag (str): metrics are written to tb_tag/metric_name(s). step (int): the step to use when writing to tensorboard. """ raise NotImplementedError()
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]
def __init__(self, k): """Sets the value of k to track up to. Args: k (int): metric tracks top-1 to top-k. """ self._k = k self._num_top_i_successes = {"total": [0] * k, "eviction": [0] * k} self._num_accesses = {"total": 0, "eviction": 0}
google-research/google-research
[ 27788, 6881, 27788, 944, 1538678568 ]