Implementation of NAPALM method compare_config.
173128
def compare_config(self):
        """"""
        if self.config_session is None:
            return ''
        else:
            commands = ['show session-config named %s diffs' % self.config_session]
            result = self.device.run_commands(commands, encoding='text')[0]['output']

            result = '\n'.join(result.splitlines()[2:])

            return result.strip()
1194018
def compare(self):  # pylint: disable=no-self-use
        
        # becuase we emulate the configuration history
        # the difference is between the last committed config and the running-config
        running_config = self._download_running_config()
        running_config_lines = running_config.splitlines()
        last_committed_config = self._last_working_config
        last_committed_config_lines = last_committed_config.splitlines()
        difference = difflib.unified_diff(running_config_lines, last_committed_config_lines, n=0)
        return '\n'.join(difference)
857369
function inspector(files, options) {
    var spec = files[0],
        comparison = files[1],
        object;

    config = options || {};
    response = {
        passed: [],
        failed: [],
        pending: []
    };
    searchAndCompare(spec, comparison, [], config);
    return response;
}
1075379
def diff(ctx, files, metrics, all, detail):
    """"""
    config = ctx.obj["CONFIG"]

    if not exists(config):
        handle_no_cache(ctx)

    if not metrics:
        metrics = get_default_metrics(config)
        logger.info(f"Using default metrics {metrics}")
    else:
        metrics = metrics.split(",")
        logger.info(f"Using specified metrics {metrics}")

    from wily.commands.diff import diff

    logger.debug(f"Running diff on {files} for metric {metrics}")
    diff(
        config=config, files=files, metrics=metrics, changes_only=not all, detail=detail
    )
1258526
def main(global_config, **settings):
    """"""
    engine = engine_from_config(settings, "sqlalchemy.")

    DBSession.configure(bind=engine)

    Base.metadata.bind = engine

    config = Configurator(settings=settings)

    config.include("pyramid_jinja2")

    config.include("pyramid_debugtoolbar")

    config.add_route("home", "/")

    config.add_route("data", "/data")

    config.add_route("data_advanced", "/data_advanced")

    config.add_route("data_yadcf", "/data_yadcf")

    config.add_route("dt_110x", "/dt_110x")

    config.add_route("dt_110x_custom_column", "/dt_110x_custom_column")

    config.add_route("dt_110x_basic_column_search",
                     "/dt_110x_basic_column_search")

    config.add_route("dt_110x_advanced_column_search",
                     "/dt_110x_advanced_column_search")

    config.add_route("dt_110x_yadcf", "/dt_110x_yadcf")

    config.scan()

    json_renderer = JSON()

    json_renderer.add_adapter(date, date_adapter)

    config.add_renderer("json_with_dates", json_renderer)

    config.add_jinja2_renderer('.html')

    return config.make_wsgi_app()
1234288
function compare(specValue, comparisonValue, currentDescription) {

    var lengthIndex = currentDescription.length - 1,
        suite = currentDescription.slice(0, (lengthIndex)).join(" "),
        spec = currentDescription[lengthIndex],
        object = {};

    if (suite === "") {
        object[spec] = specValue;
    } else {
        object[suite] = {};
        object[suite][spec] = specValue;
    }

    if (typeof(specValue) !== 'undefined' && typeof(comparisonValue) !== 'undefined') {
        if (comparisonValue === "PASSED") {
            response.passed.push(object);
        } else {
            response.failed.push(object);
        }
    } else {
        if (config.hint) {
            console.log(("ShouldIt? is running in " + config.hint + " hint mode.\n").green);
            console.log("One of your features has not been implelented.");
            console.log((object[suite][spec] + '\n').grey);
            console.log("The recommended test for you to implement is below:\n");
            console.log(templates(config.hint, suite, spec).yellow);
            console.log("\n");
            throw "end";
        }
        response.pending.push(object);
    }

}
485194
def _comparison_functions(cls, partial=False):
        

        def prerelease_cmp(a, b):
            """Compare prerelease components.

            Special rule: a version without prerelease component has higher
            precedence than one with a prerelease component.
            """
            if a and b:
                return identifier_list_cmp(a, b)
            elif a:
                # Versions with prerelease field have lower precedence
                return -1
            elif b:
                return 1
            else:
                return 0

        def build_cmp(a, b):
            """Compare build metadata.

            Special rule: there is no ordering on build metadata.
            """
            if a == b:
                return 0
            else:
                return NotImplemented

        def make_optional(orig_cmp_fun):
            """Convert a cmp-like function to consider 'None == *'."""
            @functools.wraps(orig_cmp_fun)
            def alt_cmp_fun(a, b):
                if a is None or b is None:
                    return 0
                return orig_cmp_fun(a, b)

            return alt_cmp_fun

        if partial:
            return [
                base_cmp,  # Major is still mandatory
                make_optional(base_cmp),
                make_optional(base_cmp),
                make_optional(prerelease_cmp),
                make_optional(build_cmp),
            ]
        else:
            return [
                base_cmp,
                base_cmp,
                base_cmp,
                prerelease_cmp,
                build_cmp,
            ]
1097776
def config(client, event, channel, nick, rest):
	""
	pattern = re.compile(r'(?P<key>\w+)\s*(?P<op>[+-]?=)\s*(?P<value>.*)$')
	match = pattern.match(rest)
	if not match:
		return "Command not recognized"
	res = match.groupdict()
	key = res['key']
	op = res['op']
	value = yaml.safe_load(res['value'])
	if op in ('+=', '-='):
		# list operation
		op_name = {'+=': 'append', '-=': 'remove'}[op]
		op_name
		if key not in pmxbot.config:
			msg = "{key} not found in config. Can't {op_name}."
			return msg.format(**locals())
		if not isinstance(pmxbot.config[key], (list, tuple)):
			msg = "{key} is not list or tuple. Can't {op_name}."
			return msg.format(**locals())
		op = getattr(pmxbot.config[key], op_name)
		op(value)
	else:  # op is '='
		pmxbot.config[key] = value
78548
def _compare(cur_cmp, cur_struct):
    '''
    
    '''
    if isinstance(cur_cmp, dict) and isinstance(cur_struct, dict):
        log.debug('Comparing dict to dict')
        for cmp_key, cmp_value in six.iteritems(cur_cmp):
            if cmp_key == '*':
                # matches any key from the source dictionary
                if isinstance(cmp_value, dict):
                    found = False
                    for _, cur_struct_val in six.iteritems(cur_struct):
                        found |= _compare(cmp_value, cur_struct_val)
                    return found
                else:
                    found = False
                    if isinstance(cur_struct, (list, tuple)):
                        for cur_ele in cur_struct:
                            found |= _compare(cmp_value, cur_ele)
                    elif isinstance(cur_struct, dict):
                        for _, cur_ele in six.iteritems(cur_struct):
                            found |= _compare(cmp_value, cur_ele)
                    return found
            else:
                if isinstance(cmp_value, dict):
                    if cmp_key not in cur_struct:
                        return False
                    return _compare(cmp_value, cur_struct[cmp_key])
                if isinstance(cmp_value, list):
                    found = False
                    for _, cur_struct_val in six.iteritems(cur_struct):
                        found |= _compare(cmp_value, cur_struct_val)
                    return found
                else:
                    return _compare(cmp_value, cur_struct[cmp_key])
    elif isinstance(cur_cmp, (list, tuple)) and isinstance(cur_struct, (list, tuple)):
        log.debug('Comparing list to list')
        found = False
        for cur_cmp_ele in cur_cmp:
            for cur_struct_ele in cur_struct:
                found |= _compare(cur_cmp_ele, cur_struct_ele)
        return found
    elif isinstance(cur_cmp, dict) and isinstance(cur_struct, (list, tuple)):
        log.debug('Comparing dict to list (of dicts?)')
        found = False
        for cur_struct_ele in cur_struct:
            found |= _compare(cur_cmp, cur_struct_ele)
        return found
    elif isinstance(cur_cmp, bool) and isinstance(cur_struct, bool):
        log.debug('Comparing booleans: %s ? %s', cur_cmp, cur_struct)
        return cur_cmp == cur_struct
    elif isinstance(cur_cmp, (six.string_types, six.text_type)) and \
         isinstance(cur_struct, (six.string_types, six.text_type)):
        log.debug('Comparing strings (and regex?): %s ? %s', cur_cmp, cur_struct)
        # Trying literal match
        matched = re.match(cur_cmp, cur_struct, re.I)
        if matched:
            return True
        return False
    elif isinstance(cur_cmp, (six.integer_types, float)) and \
         isinstance(cur_struct, (six.integer_types, float)):
        log.debug('Comparing numeric values: %d ? %d', cur_cmp, cur_struct)
        # numeric compare
        return cur_cmp == cur_struct
    elif isinstance(cur_struct, (six.integer_types, float)) and \
         isinstance(cur_cmp, (six.string_types, six.text_type)):
        # Comapring the numerical value agains a presumably mathematical value
        log.debug('Comparing a numeric value (%d) with a string (%s)', cur_struct, cur_cmp)
        numeric_compare = _numeric_regex.match(cur_cmp)
        # determine if the value to compare agains is a mathematical operand
        if numeric_compare:
            compare_value = numeric_compare.group(2)
            return getattr(float(cur_struct), _numeric_operand[numeric_compare.group(1)])(float(compare_value))
        return False
    return False
125053
def compare(node1, node2):
    """"""
    if not os.path.isdir("a"):
        print("error: comparison feature not initialized", file=sys.stderr)
        sys.exit(4)

    print("=" * 80)
    print("WERKZEUG INTERNAL BENCHMARK -- COMPARE MODE".center(80))
    print("-" * 80)

    def _hg_update(repo, node):
        def hg(*x):
            return subprocess.call(
                ["hg"] + list(x), cwd=repo, stdout=null_out, stderr=null_out
            )

        hg("revert", "-a", "--no-backup")
        client = subprocess.Popen(
            ["hg", "status", "--unknown", "-n", "-0"], stdout=subprocess.PIPE, cwd=repo
        )
        unknown = client.communicate()[0]
        if unknown:
            client = subprocess.Popen(
                ["xargs", "-0", "rm", "-f"],
                cwd=repo,
                stdout=null_out,
                stdin=subprocess.PIPE,
            )
            client.communicate(unknown)
        hg("pull", "../..")
        hg("update", node)
        if node == "tip":
            diff = subprocess.Popen(
                ["hg", "diff"], cwd="..", stdout=subprocess.PIPE
            ).communicate()[0]
            if diff:
                client = subprocess.Popen(
                    ["hg", "import", "--no-commit", "-"],
                    cwd=repo,
                    stdout=null_out,
                    stdin=subprocess.PIPE,
                )
                client.communicate(diff)

    _hg_update("a", node1)
    _hg_update("b", node2)
    d1 = run("a", no_header=True)
    d2 = run("b", no_header=True)

    print("DIRECT COMPARISON".center(80))
    print("-" * 80)
    for key in sorted(d1):
        delta = d1[key] - d2[key]
        if abs(1 - d1[key] / d2[key]) < TOLERANCE or abs(delta) < MIN_RESOLUTION:
            delta = "=="
        else:
            delta = "%+.4f (%+d%%)" % (delta, round(d2[key] / d1[key] * 100 - 100))
        print("%36s   %.4f    %.4f    %s" % (format_func(key), d1[key], d2[key], delta))
    print("-" * 80)
1080477
@Override
    public int compareTo(Vulnerability v) {
        return new CompareToBuilder()
                .append(this.name, v.name)
                .toComparison();
    }
1323302
def _compare_by_version(path1, path2):
    
    if path1.source == path2.source:
        if path1.source_version_num > path2.source_version_num:
            return path1
        else:
            return path2
    return None
1187961
private static CompareOp reverseCompareOp(CompareOp compareOp) {
    switch (compareOp) {
    case EQUAL:
    case NOT_EQUAL:
    case NO_OP:
      return compareOp;
    case LESS:
      return CompareOp.GREATER;
    case LESS_OR_EQUAL:
      return CompareOp.GREATER_OR_EQUAL;
    case GREATER:
      return CompareOp.LESS;
    case GREATER_OR_EQUAL:
      return CompareOp.LESS_OR_EQUAL;
    default:
      return CompareOp.NO_OP;
    }
  }
40906
def beacon(config):
    '''
    
    '''
    log.debug('Executing napalm beacon with config:')
    log.debug(config)
    ret = []
    for mod in config:
        if not mod:
            continue
        event = {}
        fun = mod.keys()[0]
        fun_cfg = mod.values()[0]
        args = fun_cfg.pop('_args', [])
        kwargs = fun_cfg.pop('_kwargs', {})
        log.debug('Executing %s with %s and %s', fun, args, kwargs)
        fun_ret = __salt__[fun](*args, **kwargs)
        log.debug('Got the reply from the minion:')
        log.debug(fun_ret)
        if not fun_ret.get('result', False):
            log.error('Error whilst executing %s', fun)
            log.error(fun_ret)
            continue
        fun_ret_out = fun_ret['out']
        log.debug('Comparing to:')
        log.debug(fun_cfg)
        try:
            fun_cmp_result = _compare(fun_cfg, fun_ret_out)
        except Exception as err:
            log.error(err, exc_info=True)
            # catch any exception and continue
            # to not jeopardise the execution of the next function in the list
            continue
        log.debug('Result of comparison: %s', fun_cmp_result)
        if fun_cmp_result:
            log.info('Matched %s with %s', fun, fun_cfg)
            event['tag'] = '{os}/{fun}'.format(os=__grains__['os'], fun=fun)
            event['fun'] = fun
            event['args'] = args
            event['kwargs'] = kwargs
            event['data'] = fun_ret
            event['match'] = fun_cfg
            log.debug('Queueing event:')
            log.debug(event)
            ret.append(event)
    log.debug('NAPALM beacon generated the events:')
    log.debug(ret)
    return ret
215965
def set_comparison(self):
        
        self.comp1 = self.zvals[0]
        self.comp2 = self.zvals[1]
        return
300587
def compare_version(self, version_string, op):
        """"""
        from pkg_resources import parse_version
        from monty.operator import operator_from_str
        op = operator_from_str(op)
        return op(parse_version(self.version), parse_version(version_string))
1359738
function compareComponents(a, b) {
  const [aNormalized, bNormalized] = normalizeVersions(a, b);

  for (let i = 0; i < bNormalized.length; i++) {
    const result = compareNumeric(aNormalized[i], bNormalized[i]);
    if (result) {
      return result;
    }
  }

  return 0;
}