text:
package edu.stanford.math.plex4.graph.random;

import java.util.Random;

import cern.jet.random.AbstractDistribution;
import cern.jet.random.Distributions;
import cern.jet.random.Uniform;
import cern.jet.random.engine.RandomEngine;
import edu.stanford.math.plex4.graph.AbstractUndirectedGraph;
import gnu.trove.TIntArrayList;

/**
 * This class creates a random graph generated from the forest fire model. This
 * is described on page 50 of "Community Structure in Large Networks", by
 * Mahoney, et al. See http://arxiv.org/abs/0810.1355
 *
 * @author Andrew Tausz
 * @date February 7, 2009
 */
public class ForestFireGraph extends GraphInstanceGenerator {

	private static final long serialVersionUID = -872184123268309649L;
	protected double forwardBurningProbability;
	protected double backwardBurningProbability;
	protected RandomEngine randomEngine = AbstractDistribution
			.makeDefaultGenerator();
	protected Uniform uniformGenerator = new Uniform(this.randomEngine);
	protected int nodeCount;

	public ForestFireGraph(int n, double forwardBurningProbability,
			double backwardBurningProbability) {
		this.nodeCount = n;
		this.forwardBurningProbability = forwardBurningProbability;
		this.backwardBurningProbability = backwardBurningProbability;
	}

	@Override
	public AbstractUndirectedGraph generate() {
		AbstractUndirectedGraph graph = this.initializeGraph(this.nodeCount);

		boolean[] nodeAdded = new boolean[this.nodeCount];
		int currentNode = 0;

		for (int t = 0; t < this.nodeCount; t++) {
			// select a node not in the graph
			while (nodeAdded[currentNode] == true) {
				currentNode++;
			}
			// if we are in the first step, just go to the next iteration
			if (t == 0) {
				nodeAdded[currentNode] = true;
				continue;
			}
			// add a connection between the new node and a random node in the
			// existing graph
			int v = currentNode;
			int w = uniformGenerator.nextIntFromTo(0, t - 1);
			graph.addEdge(v, w);
			nodeAdded[currentNode] = true;
			graph = this.burnNodes(v, w, t, graph);
		}

		return graph;
	}

	private AbstractUndirectedGraph burnNodes(int v, int w, int t, AbstractUndirectedGraph graph) {
		double px = this.forwardBurningProbability
				/ (1 - this.forwardBurningProbability);
		double py = this.backwardBurningProbability
				/ (1 - this.backwardBurningProbability);
		int x = Distributions.nextGeometric(px, this.randomEngine);
		int y = Distributions.nextGeometric(py, this.randomEngine);
		x = Math.min(x, graph.getDegree(w));
		y = Math.min(y, graph.getDegree(w));
		int[] neighborsSet = graph.getNeighbors(w);
		TIntArrayList neighbors = new TIntArrayList();
		neighbors.add(neighborsSet);

		int count = 0;
		neighbors.shuffle(new Random());
		int neighbor;

		for (int neighborIndex = 0; neighborIndex < neighbors.size(); neighborIndex++) {
			neighbor = neighbors.get(neighborIndex);

			if (!graph.containsEdge(v, neighbor) && (neighbor != v)) {
				graph.addEdge(v, neighbor);
				// this.BurnNodes(v, neighbor, t);
			}
			count++;
			if (count >= x) break;
		}
		return graph;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "ForestFire(" + this.nodeCount + ","
				+ this.forwardBurningProbability + ","
				+ this.backwardBurningProbability + ")";
	}

}


text:
from . import move_strategies
from . import move_schemes
from .spring_shooting import SpringShootingMover

redpajama_set_name: RedPajamaGithub


text:
import gevent
import json
import copy
import xmltodict
import redis
import datetime
import sys
from opserver_util import OpServerUtils
import re
from gevent.coros import BoundedSemaphore
from pysandesh.util import UTCTimestampUsec
from pysandesh.connection_info import ConnectionState
from sandesh.viz.constants import UVE_MAP
from pysandesh.gen_py.process_info.ttypes import ConnectionType,\
     ConnectionStatus
import traceback

class UVEServer(object):

    def __init__(self, redis_uve_server, logger, redis_password=None, \
            uvedbcache=None, usecache=False):
        self._local_redis_uve = redis_uve_server
        self._redis_uve_map = {}
        self._logger = logger
        self._redis = None
        self._uvedbcache = uvedbcache
        self._usecache = usecache
        self._redis_password = redis_password
        self._uve_reverse_map = {}
        for h,m in UVE_MAP.iteritems():
            self._uve_reverse_map[m] = h

    #end __init__
    def redis_instances(self):
        return set(self._redis_uve_map.keys())

    def update_redis_uve_list(self, redis_uve_list):
        newlist = set(redis_uve_list)
        chg = False
        # if some redis instances are gone, remove them from our map
        for test_elem in self._redis_uve_map.keys():
            if test_elem not in newlist:
                chg = True
                r_ip = test_elem[0]
                r_port = test_elem[1]
                del self._redis_uve_map[test_elem]
                ConnectionState.delete(ConnectionType.REDIS_UVE,\
                    r_ip+":"+str(r_port))

        # new redis instances need to be inserted into the map
        for test_elem in newlist:
            if test_elem not in self._redis_uve_map:
                chg = True
                r_ip = test_elem[0]
                r_port = test_elem[1]
                self._redis_uve_map[test_elem] = None
                ConnectionState.update(ConnectionType.REDIS_UVE,\
                    r_ip+":"+str(r_port), ConnectionStatus.INIT)
        if chg:
            self._logger.error("updated redis_uve_list %s" % str(self._redis_uve_map))

        # Exercise redis connections to update health
        if len(newlist):
            self.get_uve("ObjectCollectorInfo:__NONE__", False, None)

    # end update_redis_uve_list

    def fill_redis_uve_info(self, redis_uve_info):
        redis_uve_info.ip = self._local_redis_uve[0]
        redis_uve_info.port = self._local_redis_uve[1]
        redish =  redis.StrictRedis(self._local_redis_uve[0],
                                    self._local_redis_uve[1],
                                    password=self._redis_password,
                                    db=1)
        try:
            redish.ping()
        except redis.exceptions.ConnectionError:
            redis_uve_info.status = 'DisConnected'
        else:
            redis_uve_info.status = 'Connected'
    #end fill_redis_uve_info

    @staticmethod
    def merge_previous(state, key, typ, attr, prevdict):
        print "%s New    val is %s" % (attr, prevdict)
        nstate = copy.deepcopy(state)
        if UVEServer._is_agg_item(prevdict):
            count = int(state[key][typ][attr]['previous']['#text'])
            count += int(prevdict['#text'])
            nstate[key][typ][attr]['previous']['#text'] = str(count)

        if UVEServer._is_agg_list(prevdict):
            sname = ParallelAggregator.get_list_name(
                state[key][typ][attr]['previous'])
            count = len(prevdict['list'][sname]) + \
                len(state[key][typ][attr]['previous']['list'][sname])
            nstate[key][typ][attr]['previous']['list'][sname].extend(
                prevdict['list'][sname])
            nstate[key][typ][attr]['previous']['list']['@size'] = \
                str(count)

            tstate = {}
            tstate[typ] = {}
            tstate[typ][attr] = copy.deepcopy(
                nstate[key][typ][attr]['previous'])
            nstate[key][typ][attr]['previous'] =\
                ParallelAggregator.consolidate_list(tstate, typ, attr)

        print "%s Merged val is %s"\
            % (attr, nstate[key][typ][attr]['previous'])
        return nstate

    def run(self):
	ConnectionState.update(conn_type = ConnectionType.REDIS_UVE,
            name = 'LOCAL', status = ConnectionStatus.INIT)
        while True:
            if self._redis:
                redish = self._redis
            else:

                redish =  redis.StrictRedis(self._local_redis_uve[0],
                                            self._local_redis_uve[1],
                                            password=self._redis_password,
                                            db=1)
            try:
                if not self._redis:
                    value = ""
                    redish.ping()
                else:
                    k, value = redish.brpop("DELETED")
                    self._logger.debug("%s del received for " % value)
                    # value is of the format:
                    # DEL:<key>:<src>:<node-type>:<module>:<instance-id>:<message-type>:<seqno>
                    redish.delete(value)
            except gevent.GreenletExit:
                self._logger.error('UVEServer Exiting on gevent-kill')
                break
            except:
                if self._redis:
                    #send redis connection down msg. Coule be bcos of authentication
                    ConnectionState.update(conn_type = ConnectionType.REDIS_UVE,
                        name = 'LOCAL', status = ConnectionStatus.DOWN)
                    self._redis = None
                gevent.sleep(5)
            else:
                self._logger.debug("Deleted %s" % value)
                if not self._redis:
                    self._redis = redish
                    ConnectionState.update(conn_type = ConnectionType.REDIS_UVE,
                        name = 'LOCAL', status = ConnectionStatus.UP)

    @staticmethod
    def _is_agg_item(attr):
        if attr['@type'] in ['i8', 'i16', 'i32', 'i64', 'byte',
                             'u8', 'u16', 'u32', 'u64']:
            if '@aggtype' in attr:
                if attr['@aggtype'] == "counter":
                    return True
        return False

    @staticmethod
    def _is_agg_list(attr):
        if attr['@type'] in ['list']:
            if '@aggtype' in attr:
                if attr['@aggtype'] == "append":
                    return True
        return False

    def get_part(self, part, r_inst):
        # Get UVE and Type contents of given partition on given
        # collector/redis instance.
        uves = {}
        try:
            r_ip = r_inst[0]
            r_port = r_inst[1]
            redish = self._redis_inst_get(r_inst)
            gen_uves = {}
            for elems in redish.smembers("PART2KEY:" + str(part)):
                info = elems.split(":", 5)
                gen = info[0] + ":" + info[1] + ":" + info[2] + ":" + info[3]
                typ = info[4]
                key = info[5]
                if not gen in gen_uves:
                     gen_uves[gen] = {}
                if not key in gen_uves[gen]:
                     gen_uves[gen][key] = {}
                gen_uves[gen][key][typ] = {}
        except Exception as e:
            self._logger.error("get_part failed %s for : %s:%d tb %s" \
                               % (str(e), r_ip, r_port, traceback.format_exc()))
            self._redis_inst_down(r_inst)
        else:
            self._redis_inst_up(r_inst, redish)
        return r_ip + ":" + str(r_port) , gen_uves

    def _redis_inst_get(self, r_inst):
        r_ip = r_inst[0]
        r_port = r_inst[1]
	if not self._redis_uve_map[r_inst]:
	    return redis.StrictRedis(
		    host=r_ip, port=r_port,
		    password=self._redis_password, db=1, socket_timeout=90)
	else:
	    return self._redis_uve_map[r_inst]

    def _redis_inst_up(self, r_inst, redish):
	if not self._redis_uve_map[r_inst]:
            r_ip = r_inst[0]
            r_port = r_inst[1]
	    self._redis_uve_map[r_inst] = redish
	    ConnectionState.update(ConnectionType.REDIS_UVE,
		r_ip + ":" + str(r_port), ConnectionStatus.UP)

    def _redis_inst_down(self, r_inst):
	if self._redis_uve_map[r_inst]:
            r_ip = r_inst[0]
            r_port = r_inst[1]
	    self._redis_uve_map[r_inst] = None
	    ConnectionState.update(ConnectionType.REDIS_UVE,
		r_ip + ":" + str(r_port), ConnectionStatus.DOWN)

    def get_tables(self):
        tables = set()
        for r_inst in self._redis_uve_map.keys():
            try:
                redish = self._redis_inst_get(r_inst)
                tbs = [elem.split(":",1)[1] for elem in redish.keys("TABLE:*")]
                tables.update(set(tbs))
            except Exception as e:
                self._logger.error("get_tables failed %s for : %s tb %s" \
                               % (str(e), str(r_inst), traceback.format_exc()))
                self._redis_inst_down(r_inst)
            else:
                self._redis_inst_up(r_inst, redish)

        return tables

    def get_uve(self, key, flat, filters=None, base_url=None):

        filters = filters or {}
        sfilter = filters.get('sfilt')
        mfilter = filters.get('mfilt')
        tfilter = filters.get('cfilt')
        ackfilter = filters.get('ackfilt')

        if flat and not sfilter and not mfilter and self._usecache:
            return self._uvedbcache.get_uve(key, filters)

        is_alarm = False
        if tfilter == "UVEAlarms":
            is_alarm = True

        state = {}
        state[key] = {}
        rsp = {}
        failures = False

        tab = key.split(":",1)[0]

        for r_inst in self._redis_uve_map.keys():
            try:
                redish = self._redis_inst_get(r_inst)
                qmap = {}

                ppe = redish.pipeline()
                ppe.smembers("ALARM_ORIGINS:" + key)
                if not is_alarm:
                    ppe.smembers("ORIGINS:" + key)
                pperes = ppe.execute()
                origins = set()
                for origset in pperes:
                    for smt in origset:
                        tt = smt.rsplit(":",1)[1]
                        sm = smt.rsplit(":",1)[0]
                        source = sm.split(":", 1)[0]
                        mdule = sm.split(":", 1)[1]
                        if tfilter is not None:
                            if tt not in tfilter:
                                continue
                        if sfilter is not None:
                            if sfilter != source:
                                continue
                        if mfilter is not None:
                            if mfilter != mdule:
                                continue
                        origins.add(smt)

                ppeval = redish.pipeline()
                for origs in origins:
                    ppeval.hgetall("VALUES:" + key + ":" + origs)
                odictlist = ppeval.execute()

                idx = 0
                for origs in origins:

                    odict = odictlist[idx]
                    idx = idx + 1

                    info = origs.rsplit(":", 1)
                    dsource = info[0]
                    typ = info[1]

                    afilter_list = set()
                    if tfilter is not None:
                        afilter_list = tfilter[typ]

                    for attr, value in odict.iteritems():
                        if len(afilter_list):
                            if attr not in afilter_list:
                                continue

                        if value[0] == '<':
                            snhdict = xmltodict.parse(value)
                            # TODO: This is a hack for separating external
                            # bgp routers from control-nodes
                            if snhdict[attr]['@type'] == 'map':
                                if typ == 'ContrailConfig' and \
                                        tab == 'ObjectBgpRouter' and \
                                        attr == 'elements':
                                    try:
                                        elem = OpServerUtils.uve_attr_flatten(\
                                            snhdict[attr])
                                        vendor = json.loads(\
                                            elem['bgp_router_parameters'])["vendor"]
                                        if vendor != "contrail":
                                            continue
                                    except:
                                        pass
                            elif snhdict[attr]['@type'] == 'list':
                                sname = ParallelAggregator.get_list_name(
                                        snhdict[attr])
                                if snhdict[attr]['list']['@size'] == '0':
                                    continue
                                elif snhdict[attr]['list']['@size'] == '1':
                                    if not isinstance(
                                        snhdict[attr]['list'][sname], list):
                                        snhdict[attr]['list'][sname] = [
                                            snhdict[attr]['list'][sname]]
                                if typ == 'UVEAlarms' and attr == 'alarms' and \
                                        ackfilter is not None:
                                    alarms = []
                                    for alarm in snhdict[attr]['list'][sname]:
                                        ack_attr = alarm.get('ack')
                                        if ack_attr:
                                            ack = ack_attr['#text']
                                        else:
                                            ack = 'false'
                                        if ack == ackfilter:
                                            alarms.append(alarm)
                                    if not len(alarms):
                                        continue
                                    snhdict[attr]['list'][sname] = alarms
                                    snhdict[attr]['list']['@size'] = \
                                        str(len(alarms))
                        else:
                            continue

                        # print "Attr %s Value %s" % (attr, snhdict)
                        if typ not in state[key]:
                            state[key][typ] = {}
                        if attr not in state[key][typ]:
                            state[key][typ][attr] = {}
                        if dsource in state[key][typ][attr]:
                            print "Found Dup %s:%s:%s:%s:%s = %s" % \
                                (key, typ, attr, source, mdule, state[
                                key][typ][attr][dsource])
                        state[key][typ][attr][dsource] = snhdict[attr]

                pa = ParallelAggregator(state, self._uve_reverse_map)
                rsp = pa.aggregate(key, flat, base_url)
            except Exception as e:
                self._logger.error("redis-uve failed %s for : %s tb %s" \
                               % (str(e), str(r_inst), traceback.format_exc()))
                self._redis_inst_down(r_inst)
                failures = True
            else:
                self._redis_inst_up(r_inst, redish)
                self._logger.debug("Computed %s as %s" % (key,rsp.keys()))

        return failures, rsp
    # end get_uve

    def get_uve_regex(self, key):
        regex = ''
        if key[0] != '*':
            regex += '^'
        regex += key.replace('*', '.*?')
        if key[-1] != '*':
            regex += '$'
        return re.compile(regex)
    # end get_uve_regex

    def get_alarms(self, filters):
        tables = filters.get('tablefilt')
        kfilter = filters.get('kfilt')
        patterns = None
        if kfilter is not None:
            patterns = set()
            for filt in kfilter:
                patterns.add(self.get_uve_regex(filt))

        rsp = self._uvedbcache.get_uve_list(tables, filters, patterns, False)
        return rsp
    # end get_alarms

    def multi_uve_get(self, table, flat, filters=None, base_url=None):
        sfilter = filters.get('sfilt')
        mfilter = filters.get('mfilt')
        kfilter = filters.get('kfilt')

        patterns = None
        if kfilter is not None:
            patterns = set()
            for filt in kfilter:
                patterns.add(self.get_uve_regex(filt))

        if not sfilter and not mfilter and self._usecache:
            rsp = self._uvedbcache.get_uve_list([table], filters, patterns, True)
            if table in rsp:
                uve_list = rsp[table]
            else:
                uve_list = set()
        else:
            # get_uve_list cannot handle attribute names very efficiently,
            # so we don't pass them here
            uve_list = self.get_uve_list(table, filters, False)

        for uve_name in uve_list:
            _,uve_val = self.get_uve(
                table + ':' + uve_name, flat, filters,  base_url)
            if uve_val == {}:
                continue
            else:
                uve = {'name': uve_name, 'value': uve_val}
                yield uve

    # end multi_uve_get

    def get_uve_list(self, table, filters=None, parse_afilter=False):
        is_alarm = False
        filters = filters or {}
        tfilter = filters.get('cfilt')
        if tfilter == "UVEAlarms":
            is_alarm = True
        uve_list = set()
        kfilter = filters.get('kfilt')
        sfilter = filters.get('sfilt')
        mfilter = filters.get('mfilt')

        patterns = None
        if kfilter is not None:
            patterns = set()
            for filt in kfilter:
                patterns.add(self.get_uve_regex(filt))

        if not sfilter and not mfilter and self._usecache:
            rsp = self._uvedbcache.get_uve_list([table], filters, patterns)
            if table in rsp:
                uve_list = rsp[table]
            return uve_list

        for r_inst in self._redis_uve_map.keys():
            try:
                redish = self._redis_inst_get(r_inst)

                # For UVE queries, we wanna read both UVE and Alarm table
                entries = redish.smembers('ALARM_TABLE:' + table)
                if not is_alarm:
                    entries = entries.union(redish.smembers('TABLE:' + table))
                for entry in entries:
                    info = (entry.split(':', 1)[1]).rsplit(':', 5)
                    uve_key = info[0]
                    if kfilter is not None:
                        kfilter_match = False
                        for pattern in patterns:
                            if pattern.match(uve_key):
                                kfilter_match = True
                                break
                        if not kfilter_match:
                            continue
                    src = info[1]
                    if sfilter is not None:
                        if sfilter != src:
                            continue
                    module = info[2]+':'+info[3]+':'+info[4]
                    if mfilter is not None:
                        if mfilter != module:
                            continue
                    typ = info[5]
                    if tfilter is not None:
                        if typ not in tfilter:
                            continue
                    if parse_afilter:
                        if tfilter is not None and len(tfilter[typ]):
                            valkey = "VALUES:" + table + ":" + uve_key + \
                                ":" + src + ":" + module + ":" + typ
                            for afilter in tfilter[typ]:
                                attrval = redish.hget(valkey, afilter)
                                if attrval is not None:
                                    break
                            if attrval is None:
                                continue
                    uve_list.add(uve_key)
            except Exception as e:
                self._logger.error("get_uve_list failed %s for : %s tb %s" \
                               % (str(e), str(r_inst), traceback.format_exc()))
                self._redis_inst_down(r_inst)
            else:
                self._redis_inst_up(r_inst, redish)
        return uve_list
    # end get_uve_list

# end UVEServer

class ParallelAggregator:

    def __init__(self, state, rev_map = {}):
        self._state = state
        self._rev_map = rev_map

    def _default_agg(self, oattr):
        itemset = set()
        result = []
        for source in oattr.keys():
            elem = oattr[source]
            hdelem = json.dumps(elem)
            if hdelem not in itemset:
                itemset.add(hdelem)
                result.append([elem, source])
            else:
                for items in result:
                    if elem in items:
                        items.append(source)
        return result

    def _is_sum(self, oattr):
        akey = oattr.keys()[0]
        if '@aggtype' not in oattr[akey]:
            return False
        if oattr[akey]['@aggtype'] in ["sum"]:
            return True
        if oattr[akey]['@type'] in ['i8', 'i16', 'i32', 'i64',
                                    'byte', 'u8', 'u16', 'u32', 'u64']:
            if oattr[akey]['@aggtype'] in ["counter"]:
                return True
        return False

    def _is_union(self, oattr):
        akey = oattr.keys()[0]
        if not oattr[akey]['@type'] in ["list"]:
            return False
        if '@aggtype' not in oattr[akey]:
            return False
        if oattr[akey]['@aggtype'] in ["union"]:
            return True
        else:
            return False

    def _is_append(self, oattr):
        akey = oattr.keys()[0]
        if not oattr[akey]['@type'] in ["list"]:
            return False
        if '@aggtype' not in oattr[akey]:
            return False
        if oattr[akey]['@aggtype'] in ["append"]:
            return True
        else:
            return False

    @staticmethod
    def get_list_name(attr):
        sname = ""
        for sattr in attr['list'].keys():
            if sattr[0] not in ['@']:
                sname = sattr
        return sname

    @staticmethod
    def _get_list_key(elem):
        skey = ""
        for sattr in elem.keys():
            if '@aggtype' in elem[sattr]:
                if elem[sattr]['@aggtype'] in ["listkey"]:
                    skey = sattr
        return skey

    def _sum_agg(self, oattr):
        akey = oattr.keys()[0]
        result = copy.deepcopy(oattr[akey])
        count = 0
        for source in oattr.keys():
            count += int(oattr[source]['#text'])
        result['#text'] = str(count)
        return result

    def _union_agg(self, oattr):
        akey = oattr.keys()[0]
        result = copy.deepcopy(oattr[akey])
        itemset = set()
        sname = ParallelAggregator.get_list_name(oattr[akey])
        result['list'][sname] = []

        siz = 0
        for source in oattr.keys():
            if isinstance(oattr[source]['list'][sname], basestring):
                oattr[source]['list'][sname] = [oattr[source]['list'][sname]]
            for elem in oattr[source]['list'][sname]:
                hdelem = json.dumps(elem)
                if hdelem not in itemset:
                    itemset.add(hdelem)
                    result['list'][sname].append(elem)
                    siz += 1
        result['list']['@size'] = str(siz)

        return result

    def _append_agg(self, oattr):
        akey = oattr.keys()[0]
        result = copy.deepcopy(oattr[akey])
        sname = ParallelAggregator.get_list_name(oattr[akey])
        result['list'][sname] = []
        siz = 0
        for source in oattr.keys():
            if not isinstance(oattr[source]['list'][sname], list):
                oattr[source]['list'][sname] = [oattr[source]['list'][sname]]
            for elem in oattr[source]['list'][sname]:
                result['list'][sname].append(elem)
                siz += 1
        result['list']['@size'] = str(siz)
        return result

    @staticmethod
    def _list_agg_attrs(item):
        for ctrs in item.keys():
            if '@aggtype'in item[ctrs]:
                if item[ctrs]['@aggtype'] in ["listkey"]:
                    continue
            if item[ctrs]['@type'] in ['i8', 'i16', 'i32', 'i64',
                                       'byte', 'u8', 'u16', 'u32', 'u64']:
                yield ctrs

    @staticmethod
    def consolidate_list(result, typ, objattr):
        applist = ParallelAggregator.get_list_name(
            result[typ][objattr])
        appkey = ParallelAggregator._get_list_key(
            result[typ][objattr]['list'][applist][0])

        # There is no listkey ; no consolidation is possible
        if len(appkey) == 0:
            return result

        # If the list's underlying struct has a listkey present,
        # we need to further aggregate entries that have the
        # same listkey
        mod_result = copy.deepcopy(result[typ][objattr])
        mod_result['list'][applist] = []
        res_size = 0
        mod_result['list']['@size'] = int(res_size)

        # Add up stats
        for items in result[typ][objattr]['list'][applist]:
            matched = False
            for res_items in mod_result['list'][applist]:
                if items[appkey]['#text'] in [res_items[appkey]['#text']]:
                    for ctrs in ParallelAggregator._list_agg_attrs(items):
                        res_items[ctrs]['#text'] += int(items[ctrs]['#text'])
                    matched = True
            if not matched:
                newitem = copy.deepcopy(items)
                for ctrs in ParallelAggregator._list_agg_attrs(items):
                    newitem[ctrs]['#text'] = int(items[ctrs]['#text'])
                mod_result['list'][applist].append(newitem)
                res_size += 1

        # Convert results back into strings
        for res_items in mod_result['list'][applist]:
            for ctrs in ParallelAggregator._list_agg_attrs(res_items):
                res_items[ctrs]['#text'] = str(res_items[ctrs]['#text'])
        mod_result['list']['@size'] = str(res_size)
        return mod_result

    def aggregate(self, key, flat, base_url = None):
        '''
        This function does parallel aggregation of this UVE's state.
        It aggregates across all sources and return the global state of the UVE
        '''
        result = {}
        try:
            for typ in self._state[key].keys():
                result[typ] = {}
                for objattr in self._state[key][typ].keys():
                    if self._is_sum(self._state[key][typ][objattr]):
                        sum_res = self._sum_agg(self._state[key][typ][objattr])
                        if flat:
                            result[typ][objattr] = \
                                OpServerUtils.uve_attr_flatten(sum_res)
                        else:
                            result[typ][objattr] = sum_res
                    elif self._is_union(self._state[key][typ][objattr]):
                        union_res = self._union_agg(
                            self._state[key][typ][objattr])
                        conv_res = None
                        if union_res.has_key('@ulink') and base_url and \
                                union_res['list']['@type'] == 'string':
                            uterms = union_res['@ulink'].split(":",1)

                            # This is the linked UVE's table name
                            m_table = uterms[0]

                            if self._rev_map.has_key(m_table):
                                h_table = self._rev_map[m_table]
                                conv_res = []
                                sname = ParallelAggregator.get_list_name(union_res)
                                for el in union_res['list'][sname]:
                                    lobj = {}
                                    lobj['name'] = el
                                    lobj['href'] = base_url + '/analytics/uves/' + \
                                        h_table + '/' + el
                                    if len(uterms) == 2:
                                        lobj['href'] = lobj['href'] + '?cfilt=' + uterms[1]
                                    else:
                                        lobj['href'] = lobj['href'] + '?flat'
                                    conv_res.append(lobj)
                        if flat:
                            if not conv_res:
                                result[typ][objattr] = \
                                        OpServerUtils.uve_attr_flatten(union_res)
                            else:
                                result[typ][objattr] = conv_res
                        else:
                            result[typ][objattr] = union_res
                    elif self._is_append(self._state[key][typ][objattr]):
                        result[typ][objattr] = self._append_agg(
                            self._state[key][typ][objattr])
                        append_res = ParallelAggregator.consolidate_list(
                            result, typ, objattr)

                        if flat:
                            result[typ][objattr] =\
                                OpServerUtils.uve_attr_flatten(append_res)
                        else:
                            result[typ][objattr] = append_res

                    else:
                        default_res = self._default_agg(
                            self._state[key][typ][objattr])
                        if flat:
                            if (len(default_res) == 1):
                                result[typ][objattr] =\
                                    OpServerUtils.uve_attr_flatten(
                                        default_res[0][0])
                            else:
                                nres = []
                                for idx in range(len(default_res)):
                                    nres.append(default_res[idx])
                                    nres[idx][0] =\
                                        OpServerUtils.uve_attr_flatten(
                                            default_res[idx][0])
                                result[typ][objattr] = nres
                        else:
                            result[typ][objattr] = default_res
        except KeyError:
            pass
        return result

if __name__ == '__main__':
    uveserver = UVEServer(None, 0, None, None)
    gevent.spawn(uveserver.run())
    _, uve_state = json.loads(uveserver.get_uve("abc-corp:vn02", False))
    print json.dumps(uve_state, indent=4, sort_keys=True)


text:
<?php
$assets_location = base_url()."assets/";
?>

<!DOCTYPE html>

<meta charset="UTF-8">
<title>Free Leoshop Website Template | Register :: w3layouts</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="<?php echo $assets_location;?>css/style.css" rel="stylesheet" type="text/css" media="all" />
<link href='<?php echo $assets_location;?>http://fonts.googleapis.com/css?family=Exo+2' rel='stylesheet' type='text/css'>

<link href="<?php echo $assets_location;?>css/megamenu.css" rel="stylesheet" type="text/css" media="all" />

<a href="<?php echo base_url();?>/index.php/Form">Register
 |

<a href="<?php echo base_url();?>index.php/login_user">Log In
 |

					<a href="<?php echo $assets_location;?>index.html">

<a href="<?php echo base_url();?>/index.php/MyController/">Home

<a class="color4" href="<?php echo base_url();?>/index.php/MyController/makanan">Makanan

<a class="color5" href="<?php echo base_url();?>/index.php/MyController/minuman">Minuman

Register

    		   <form method="post" action="<?php echo base_url();?>index.php/form/submit">

<input type="text" name="name" placeholder="name">

<input type="text" name="username" placeholder="username">

<input type="password" name="password" placeholder="password">

<input type="text" name="address" placeholder="address">

<input type="text" name="country" placeholder="Country">

<input type="text" name="city" placeholder="City">

<input type="text" name="phone_number" placeholder="phone_number">

					   <button type="submit" name="Submit" value="submit">Submit</button>

		    </form>

Free Shipping on orders over

087752806361

Information

Menu makanan lengkap

Menu lengkap penyetan

Aneka minuman dan Jus

Menu lengkap sego njamoer

Jajanan ringan

Batagor dan bakso

Contact us

087752806361

Phone:(031) 222 666 444

Email: segersumyah.com


text:
module YARD
  module CodeObjects
    # This module controls registration and accessing of namespace separators
    # for {Registry} lookup.
    #
    # @since 0.9.1
    module NamespaceMapper
      # @!group Registering a Separator for a Namespace

      # Registers a separator with an optional set of valid types that
      # must follow the separator lexically.
      #
      # Calls all callbacks defined by {NamespaceMapper.on_invalidate} after
      # the separator is registered.
      #
      # @param sep [String] the separator string for the namespace
      # @param valid_types [Array<Symbol>] a list of object types that
      #   must follow the separator. If the list is empty, any type can
      #   follow the separator.
      # @example Registering separators for a method object
      #   # Anything after a "#" denotes a method object
      #   register_separator "#", :method
      #   # Anything after a "." denotes a method object
      #   register_separator ".", :method
      # @see .on_invalidate
      def register_separator(sep, *valid_types)
        NamespaceMapper.invalidate

        valid_types.each do |t|
          NamespaceMapper.rev_map[t] ||= []
          NamespaceMapper.rev_map[t] << sep
        end

        NamespaceMapper.map[sep] ||= []
        NamespaceMapper.map[sep] += valid_types
      end

      # Unregisters a separator by a type.
      #
      # @param type [Symbol] the type to unregister
      # @see #register_separator
      def unregister_separator_by_type(type)
        seps = NamespaceMapper.rev_map[type]
        return unless seps

        seps.each {|s| NamespaceMapper.map.delete(s) }
        NamespaceMapper.rev_map.delete(type)
        NamespaceMapper.invalidate
      end

      # Clears the map of separators.
      #
      # @return [void]
      def clear_separators
        NamespaceMapper.invalidate
        NamespaceMapper.map = {}
        NamespaceMapper.rev_map = {}
      end

      # Gets or sets the default separator value to use when no
      # separator for the namespace can be determined.
      #
      # @param value [String, nil] the default separator, or nil to return the
      #   value
      # @example
      #   default_separator "::"
      def default_separator(value = nil)
        if value
          NamespaceMapper.invalidate
          NamespaceMapper.default_separator = Regexp.quote value
        else
          NamespaceMapper.default_separator
        end
      end

      # @!group Separator and Type Lookup Helpers

      # @return [Array<String>] all of the registered separators
      def separators
        NamespaceMapper.map.keys
      end

      # @return [Regexp] the regexp match of all separators
      def separators_match
        NamespaceMapper.map_match
      end

      # @param sep [String] the separator to return types for
      # @return [Array<Symbol>] a list of types registered to a separator
      def types_for_separator(sep)
        NamespaceMapper.map[sep] || []
      end

      # @param type [String] the type to return separators for
      # @return [Array<Symbol>] a list of separators registered to a type
      def separators_for_type(type)
        NamespaceMapper.rev_map[type] || []
      end

      # Internal methods to act as a singleton registry
      class << self
        # @!group Invalidation callbacks

        # Adds a callback that triggers when a new separator is registered or
        # the cache is cleared by invalidation.
        def on_invalidate(&block)
          (@invalidation_callbacks ||= []).push(block)
        end

        # @!visibility private

        # @return [Hash] a mapping of types to separators
        def map
          @map ||= {}
        end

        # @return [Hash] a reverse mapping of separators to types
        def rev_map
          @rev_map ||= {}
        end

        # Invalidates all separators
        # @return [void]
        def invalidate
          @map_match = nil
          (@invalidation_callbacks || []).each(&:call)
        end

        # @return [Regexp] the full list of separators as a regexp match
        def map_match
          @map_match ||= map.keys.map {|k| Regexp.quote k }.join('|')
        end

        # @return [String] the default separator when no separator can begin
        #   determined.
        attr_accessor :default_separator
      end
    end
  end
end


text:
using System.Collections.Generic;
using System.Drawing;
using System.Linq;

using Blade;
using Blade.Collections;
using System;

namespace Maui.Data.Recognition.Html
{
    /// <summary>
    /// Specifies a path inside a HTML document from the root to a HTML element.
    /// </summary>
    public class HtmlPath
    {
        private const char PathSeparator = '/';

        /// <summary/>
        public HtmlPath()
        {
            Elements = new List<HtmlPathElement>();
        }

        /// <summary/>
        public HtmlPath( IEnumerable<HtmlPathElement> elements )
        {
            Elements = elements.ToList();
        }

        /// <summary/>
        public IList<HtmlPathElement> Elements { get; private set; }

        /// <summary/>
        public HtmlPathElement Last
        {
            get
            {
                if ( Elements.Count == 0 )
                {
                    return null;
                }
                return Elements[ Elements.Count - 1 ];
            }
        }

        /// <summary/>
        public bool PointsToTable
        {
            get { return Last.IsTableOrTBody; }
        }

        /// <summary/>
        public bool PointsToTableCell
        {
            get { return Last.TagName == "TD"; }
        }

        /// <summary>
        /// Returns the position of the table cell in the cell the
        /// path is pointing to.
        /// If the path does not point into a table or the position could
        /// not be calculated an empty point is returned.
        /// </summary>
        public Point GetTableCellPosition()
        {
            if ( !PointsToTableCell )
            {
                return Point.Empty;
            }

            Point p = new Point();
            p.X = Last.Position;

            foreach ( HtmlPathElement tr in Elements.Reverse() )
            {
                if ( tr.IsTableOrTBody )
                {
                    // then this is a currupt path
                    return Point.Empty;
                }

                if ( tr.TagName == "TR" )
                {
                    p.Y = tr.Position;
                    return p;
                }
            }

            // no TR found -> path corrupt
            return Point.Empty;
        }

        /// <summary/>
        public override string ToString()
        {
            return PathSeparator + Elements.Join( PathSeparator );
        }

        /// <summary/>
        public static HtmlPath Parse( string pathStr )
        {
            if ( string.IsNullOrEmpty( pathStr ) )
            {
                throw new ArgumentException( "value is null or empty string", "pathStr" );
            }

            var pathElements = pathStr.Split( PathSeparator )
                .Where( token => !token.IsNullOrTrimmedEmpty() )
                .Select( token => HtmlPathElement.Parse( token ) );

            return new HtmlPath( pathElements );
        }
    }
}


text:
require 'rails_helper'

RSpec.describe Course::Discussion::Post::Vote do
  it { is_expected.to belong_to(:post).inverse_of(:votes) }

  let(:instance) { Instance.default }
  with_tenant(:instance) do
    let(:user) { create(:user) }
    let(:post) { create(:course_discussion_post) }

    describe '.upvotes' do
      let!(:vote) { post.votes.create(vote_flag: true, creator: user) }
      it 'retrieves all upvotes' do
        expect(post.votes.upvotes).not_to be_empty
        expect(post.votes.upvotes.all?(&:vote_flag)).to be(true)
      end
    end

    describe '.downvotes' do
      let!(:vote) { post.votes.create(vote_flag: false, creator: user) }
      it 'retrieves all upvotes' do
        expect(post.votes.downvotes).not_to be_empty
        expect(post.votes.downvotes.any?(&:vote_flag)).to be(false)
      end
    end
  end
end


text:
namespace seqan {

// ============================================================================
// Forwards
// ============================================================================

// ============================================================================
// Tags, Classes, Enums
// ============================================================================

// The documentation of the Dependent specialization is in string_set_tight.h
// since Tight is the default specialization of Dependent.

// StringSet with individual sequences in a string of string pointers
template <typename TString>
class StringSet<TString, Dependent<Generous> >
{
public:
    typedef String<TString *>                           TStrings;
    typedef typename Size<StringSet>::Type              TSize;
    typedef typename StringSetLimits<StringSet>::Type   TLimits;
    typedef typename Concatenator<StringSet>::Type      TConcatenator;

    TStrings        strings;
    TLimits         limits;
    bool            limitsValid;        // is true if limits contains the cumulative sum of the sequence lengths
    TConcatenator   concat;

    StringSet()
        : limitsValid(true)
    {
        SEQAN_CHECKPOINT;
        appendValue(limits, 0);
    }

    template <typename TDefault>
    StringSet(StringSet<TString, Owner<TDefault> > const& _other)
        : limitsValid(true)
    {
        SEQAN_CHECKPOINT;
        appendValue(limits, 0);
        for (unsigned int i = 0; i < length(_other); ++i)
            appendValue(*this, _other[i]);
    }

    // ----------------------------------------------------------------------
    // Subscription operators; have to be defined in class def.
    // ----------------------------------------------------------------------

    template <typename TPos>
    inline typename Reference<StringSet>::Type
    operator[] (TPos pos)
    {
        return value(*this, pos);
    }

    template <typename TPos>
    inline typename Reference<StringSet const>::Type
    operator[] (TPos pos) const
    {
        return value(*this, pos);
    }
};

// ============================================================================
// Metafunctions
// ============================================================================

// ============================================================================
// Functions
// ============================================================================

// --------------------------------------------------------------------------
// Function appendValue()
// --------------------------------------------------------------------------

template <typename TString, typename TExpand >
inline void appendValue(
    StringSet<TString, Dependent<Generous> > & me,
    TString const & obj,
    Tag<TExpand> const & tag)
{
    SEQAN_CHECKPOINT;
    appendValue(me.limits, lengthSum(me) + length(obj), tag);
    appendValue(me.strings, const_cast<TString*>(&obj), tag);
}

// --------------------------------------------------------------------------
// Function clear()
// --------------------------------------------------------------------------

template <typename TString >
inline void clear(StringSet<TString, Dependent<Generous> > & me)
{
    SEQAN_CHECKPOINT;
    clear(me.strings);
    resize(me.limits, 1, Exact());
    me.limitsValid = true;
}

// --------------------------------------------------------------------------
// Function value()
// --------------------------------------------------------------------------

template <typename TString, typename TPos >
inline typename Reference<StringSet<TString, Dependent<Generous> > >::Type
value(StringSet<TString, Dependent<Generous> >& me, TPos pos)
{
    SEQAN_CHECKPOINT;
    unsigned i = _findIthNonZeroValue(me.strings, pos);
    if (i <length(me.strings))
        return *me.strings[i];
    static TString tmp = "";
    return tmp;
}

template <typename TString, typename TPos >
inline typename Reference<StringSet<TString, Dependent<Generous> > const >::Type
value(StringSet<TString, Dependent<Generous> > const & me, TPos pos)
{
    SEQAN_CHECKPOINT;
    unsigned i = _findIthNonZeroValue(me.strings, pos);
    if (i < length(me.strings))
        return *me.strings[i];
    static TString tmp = "";
    return tmp;
}

// --------------------------------------------------------------------------
// Function getValueById()
// --------------------------------------------------------------------------

template <typename TString, typename TId>
inline typename Reference<StringSet<TString, Dependent<Generous> > >::Type
getValueById(StringSet<TString, Dependent<Generous> >& me,
            TId const id)
{
    SEQAN_CHECKPOINT;
    if (me.strings[id])
        return *me.strings[id];
    static TString tmp = "";
    return tmp;
}

// --------------------------------------------------------------------------
// Function assignValueById()
// --------------------------------------------------------------------------

template<typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
assignValueById(StringSet<TString, Dependent<Generous> >& me,
                TString& obj,
                TId id)
{
    SEQAN_CHECKPOINT;
    SEQAN_ASSERT(length(stringSetLimits(me)) == length(me) + 1);
    if (id >= (TId) length(me.strings)) resize(me.strings, id+1, (TString*) 0);
    if ((TString*) me.strings[id] == (TString*) 0)
        resize(me.limits, length(me.limits) + 1, Generous());
    me.strings[id] = &obj;
    me.limitsValid = false;
    SEQAN_ASSERT(length(stringSetLimits(me)) == length(me) + 1);
    return id;
}

// --------------------------------------------------------------------------
// Function removeValueById()
// --------------------------------------------------------------------------

template<typename TString, typename TId>
inline void
removeValueById(StringSet<TString, Dependent<Generous> >& me, TId const id)
{
    SEQAN_CHECKPOINT;
    if (me.strings[id] != (TString*) 0)
    {
        resize(me.limits, length(me.limits) - 1, Generous());
        me.limitsValid = empty(me);
    }
    me.strings[id] = 0;
    while (!empty(me.strings) && !me.strings[length(me.strings) - 1])
        resize(me.strings, length(me.strings) - 1, Generous());
}

// --------------------------------------------------------------------------
// Function positionToId()
// --------------------------------------------------------------------------

template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
positionToId(StringSet<TString, Dependent<Generous> >& me,
        TPos const pos)
{
    SEQAN_CHECKPOINT;
    return _findIthNonZeroValue(me.strings,pos);
}

template <typename TString, typename TPos>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
positionToId(StringSet<TString, Dependent<Generous> > const& me,
            TPos const pos)
{
    SEQAN_CHECKPOINT;
    return _findIthNonZeroValue(me.strings,pos);
}

// --------------------------------------------------------------------------
// Function idToPosition()
// --------------------------------------------------------------------------

template <typename TString, typename TId>
inline typename Id<StringSet<TString, Dependent<Generous> > >::Type
idToPosition(StringSet<TString, Dependent<Generous> > const& me,
            TId const id)
{
    SEQAN_CHECKPOINT;
    return _countNonZeroValues(me.strings,id);
}

}  // namespace seqan

#endif  // #ifndef SEQAN_SEQUENCE_STRING_SET_DEPENDENT_GENEROUSH_


text:
package client

import (
	"crypto/tls"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"net/url"

	"github.com/gorilla/websocket"
	"github.com/hyperhq/hyper-api/types/events"
	signutil "github.com/hyperhq/websocket-client/go/util"
	"golang.org/x/net/context"
)

// Events returns a stream of events in the daemon. It's up to the caller to close the stream
// by cancelling the context. Once the stream has been completely read an io.EOF error will
// be sent over the error channel. If an error is sent all processing will be stopped. It's up
// to the caller to reopen the stream in the event of an error by reinvoking this method.
func (cli *DockerCli) Events(ctx context.Context) (<-chan events.Message, <-chan error) {
	messages := make(chan events.Message)
	errs := make(chan error, 1)

	go func() {
		hostUrl, err := url.Parse(cli.host)
		if err != nil {
			errs <- err
			return
		}

		cloudConfig, existed := cli.configFile.CloudConfig[cli.host]
		if !existed {
			errs <- errors.New("Please specify 'accessKey' and 'secretKey'!")
			return
		}

		// TODO: add filter when we have other type event.
		var u = url.URL{Scheme: "wss", Host: hostUrl.Host, Path: "/events/ws"}

		// add sign to header
		req, err := http.NewRequest("GET", u.String(), nil)
		if err != nil {
			errs <- err
			return
		}

		req.URL = &u
		req = signutil.Sign4(cloudConfig.AccessKey, cloudConfig.SecretKey, req)

		// connect to websocket server
		config := &tls.Config{
			InsecureSkipVerify: true,
		}
		dialer := websocket.Dialer{
			TLSClientConfig: config,
		}

		ws, resp, err := dialer.Dial(u.String(), req.Header)
		if err != nil {
			errs <- err
			return
		}
		defer ws.Close()

		if resp.ContentLength > 0 {
			defer resp.Body.Close()
			ioutil.ReadAll(resp.Body)
		}

		// process websocket message
		for {
			_, message, err := ws.ReadMessage()
			if err != nil {
				errs <- err
				return
			}

			select {
			case <-ctx.Done():
				errs <- ctx.Err()
				return
			default:
				var event events.Message
				err := json.Unmarshal([]byte(message), &event)
				if err != nil {
					errs <- err
					return
				}

				select {
				case messages <- event:
				case <-ctx.Done():
					errs <- ctx.Err()
					return
				}
			}
		}
	}()

	return messages, errs
}


text:
package ruolan.com.myhearts.ui.fragment.home;

import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.convert.StringConvert;
import com.lzy.okrx.RxAdapter;

import java.lang.reflect.Type;

import ruolan.com.myhearts.R;
import ruolan.com.myhearts.contant.HttpUrlPaths;
import ruolan.com.myhearts.entity.NewTitleBean;
import ruolan.com.myhearts.ui.base.BaseActivity;
import ruolan.com.myhearts.utils.TranslucentUtils;
import rx.android.schedulers.AndroidSchedulers;

public class NewsActivity extends BaseActivity {

    @Override
    protected int getResultId() {
        return R.layout.activity_news;
    }

    @Override
    public void initData() {
        super.initData();
        requestTitleData();

        //requestWebViewUrl();

    }

    private void requestWebViewUrl(String url) {
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                view.loadUrl(url);
                return true;
            }

        });

        //在这里可以设置加载进度条
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
               // mProgressBar.setProgress(newProgress);
                if (newProgress>=100){
                   // mProgressBar.setVisibility(View.GONE);
                }
            }
        });

        mWebView.loadUrl(url);
    }

    private void requestTitleData() {
        OkGo.post(HttpUrlPaths.NEWS_USER_DETAIL)
                .params("id", id)
                .params("userid", userid)
                .getCall(StringConvert.create(), RxAdapter.<String>create())
                .doOnSubscribe(() -> {

                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(s -> {
                    Type type = new TypeToken<NewTitleBean>() {
                    }.getType();
                    NewTitleBean bean = new Gson().fromJson(s, type);
                    if (bean.getErrorCode() == 0 && bean.getErrorStr().equals("success")
                            && bean.getResultCount() > 0) {

                        mTvCategory.setText(bean.getResults().getCatg());
                        mTvViewCount.setText(bean.getResults().getViewCnt());
//                        Glide.with(NewsActivity.this)
//                                .load(bean.getResults().getIcon())
//                                .asBitmap()
//                                .error(R.mipmap.login_bg)
//                                .placeholder(R.mipmap.login_bg)
//                                .into(mImgBg);

                        mTvTitle.setText(bean.getResults().getTitle());
                        url = HttpUrlPaths.NEWS_DETAIL + "?id=" + bean.getResults().getId();
                        requestWebViewUrl(url);
                    }
                }, throwable -> {
                });
    }

    @Override
    protected void initListener() {

        mToolbar.setNavigationOnClickListener(v -> {
            onBackPressed();
        });
    }

    String id;
    String userid;
    String url;

    @Override
    public void initView() {

        TranslucentUtils.setColor(this, getResources().getColor(R.color.colorPrimary), 1);
        id = getIntent().getStringExtra("id");
        userid = getIntent().getStringExtra("userid");

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle(getResources().getString(R.string.news_detail));
        mTvTitle = (TextView) findViewById(R.id.tv_title);
        mTvCategory = (TextView) findViewById(R.id.tv_category);
        mTvViewCount = (TextView) findViewById(R.id.tv_view_count);
        mCollapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
        mWebView = (WebView) findViewById(R.id.web_view);
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        mImgBg = (ImageView) findViewById(R.id.img_bg);
        setSupportActionBar(mToolbar);

        //        设置返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mProgressBar = (ProgressBar) findViewById(R.id.index_progressBar);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    ImageView mImgBg;
    Toolbar mToolbar;
    TextView mTvTitle;
    TextView mTvCategory;
    TextView mTvViewCount;
    CollapsingToolbarLayout mCollapsingToolbar;
    WebView mWebView;
    ProgressBar mProgressBar;
}


text:
//package org.jasig.cas.authentication.handler.support;

//import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
//import org.springframework.util.StringUtils;

/**
 * Simple test implementation of a AuthenticationHandler that returns true if
 * the username and password match. This class should never be enabled in a
 * production environment and is only designed to facilitate unit testing and
 * load testing.
 *
 * @author Scott Battaglia
 * @version $Revision$ $Date$
 * @since 3.0
 */

using NCAS.jasig.authentication.principal;
using NCAS.jasig.web.MOCK2JAVA;

namespace NCAS.jasig.authentication.handler.support
{
    public class SimpleTestUsernamePasswordAuthenticationHandler :
        AbstractUsernamePasswordAuthenticationHandler
    {

        public SimpleTestUsernamePasswordAuthenticationHandler()
        {
            //log
            //    .warn(this.getClass().getName()
            //        + " is only to be used in a testing environment.  NEVER enable this in a production environment.");
        }

        protected override bool authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials)
        {
            string username = credentials.getUsername();
            string password = credentials.getPassword();

            if (StringUtils.hasText(username) && StringUtils.hasText(password)
                && username.Equals(this.getPasswordEncoder().encode(password)))
            {
                //log
                //    .debug("User [" + username
                //        + "] was successfully authenticated.");
                return true;
            }

            //log.debug("User [" + username + "] failed authentication");

            return false;
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project-private xmlns="http://www.netbeans.org/ns/project-private/1">
    <editor-bookmarks xmlns="http://www.netbeans.org/ns/editor-bookmarks/2" lastBookmarkId="0"/>
    <open-files xmlns="http://www.netbeans.org/ns/projectui-open-files/2">
        <group>
            <file>file:/E:/Netbeans_Projects/First_Swing_App/src/first_swing_app/Absolute_Positioning.java</file>
            <file>file:/E:/Netbeans_Projects/First_Swing_App/src/first_swing_app/Disable_That_Button.java</file>
        </group>
    </open-files>
</project-private>


text:
import warnings
from bottery.exceptions import BotteryDeprecationWarning

warnings.warn('Module `bottery.platform.telegram` is deprecated, '
             'use `bottery.telegram` instead',
             BotteryDeprecationWarning, stacklevel=2)

from bottery.telegram import *


text:
require File.expand_path('../../test_helper', __FILE__)

class CommonViewsTest < ActionController::IntegrationTest
  fixtures :projects,
           :users,
           :roles,
           :members,
           :member_roles,
           :issues,
           :issue_statuses,
           :versions,
           :trackers,
           :projects_trackers,
           :issue_categories,
           :enabled_modules,
           :enumerations,
           :attachments,
           :workflows,
           :custom_fields,
           :custom_values,
           :custom_fields_projects,
           :custom_fields_trackers,
           :time_entries,
           :journals,
           :journal_details,
           :queries

  ActiveRecord::Fixtures.create_fixtures(Redmine::Plugin.find(:redmine_contacts).directory + '/test/fixtures/',
                                         [:contacts,
                                          :contacts_projects,
                                          :contacts_issues,
                                          :deals,
                                          :notes,
                                          :tags,
                                          :taggings,
                                          :contacts_queries])

  ActiveRecord::Fixtures.create_fixtures(Redmine::Plugin.find(:redmine_contacts_helpdesk).directory + '/test/fixtures/',
                                         [:journal_messages,
                                          :canned_responses,
                                          :helpdesk_tickets])

  def setup
    RedmineHelpdesk::TestCase.prepare

    @request    = ActionController::TestRequest.new
    @response   = ActionController::TestResponse.new
    @request.env['HTTP_REFERER'] = '/'
  end

  test "View project settings" do
    log_user("admin", "admin")
    get "/projects/ecookbook/settings"
    assert_response :success
  end

  test "View helpdesk plugin settings" do
    log_user("admin", "admin")
    get "/settings/plugin/redmine_contacts_helpdesk"
    assert_response :success
  end

end


text:
action :set do
  execute "set nice" do
    command "renice #{new_resource.priority} #{findpid(new_resource.pid)}"
  end
end


text: Hosted on GitHub Pages using the Dinky theme


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using SteamToolkit;
using SteamToolkit.Community;
using SteamToolkit.Web;

namespace SteamWebChat
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class FriendsListWindow
    {
        private static Account _account;

        public static List<PlayerSummary> FriendSummaries = new List<PlayerSummary>();
        public static PlayerSummary MySummary { get; private set; }

        public static SteamChatHandler ChatHandler { get; private set; }
        public static SteamUserHandler SteamUserHandler { get; private set; }
        public static ChatEventsManager ChatEventsManager { get; private set; }

        public static ChatWindow ChatWindow { get; private set; }

        public event LoadingFinished OnLoadingFinished;

        public delegate void LoadingFinished(object sender, EventArgs e);

        public FriendsListWindow(Account account, string apiKey)
        {
            _account = account;

            #region activate apis
            ChatHandler = new SteamChatHandler(_account);
            SteamUserHandler = new SteamUserHandler(apiKey);
            #endregion

            InitializeComponent();
        }

        public void LoginAndGoOnline()
        {
            PopulateLists();

            GoOnline();

            ChatEventsManager = new ChatEventsManager(ChatHandler, TimeSpan.FromSeconds(2), 10);
            ChatEventsManager.ChatMessageReceived += OnMessage;

            Loaded += FriendsListWindow_Loaded;
            Closed += FriendsListWindow_Closed;
            OnLoadingFinished?.Invoke(this, new EventArgs());
        }

        static void PopulateLists()
        {
            MySummary = SteamUserHandler.GetPlayerSummariesV2(new List<ulong> { _account.SteamId }).FirstOrDefault();
            if (MySummary == null) throw new Exception("Unable to get my own player summary, please try again.");
        }

        static void GoOnline()
        {
            PollResponse response;
            Message responseMessage = null;
            do
            {
                response = ChatHandler.Poll(10);
                if (response.Messages == null) continue;
                responseMessage = response.Messages.FirstOrDefault(x => x.AccountIdFrom == IdConversions.UlongToAccountId(_account.SteamId));
                Thread.Sleep(TimeSpan.FromSeconds(2));
            } while ((response.Error != "OK" || responseMessage?.PersonaState == 0));
        }

        private void FriendsListWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(() => { PopulateFriendList(); });
        }

        private void PopulateFriendList()
        {
            List<Friend> friends = SteamUserHandler.GetFriendList(_account.SteamId, "friend");

            foreach (
                PlayerSummary friendSummary in
                    friends.Select(
                        friend =>
                            SteamUserHandler.GetPlayerSummariesV2(new List<ulong> { friend.SteamId }).FirstOrDefault())
                        .Where(friendSummary => friendSummary != null))
            {
                FriendSummaries.Add(friendSummary);

                FriendStateResponse state =
                    ChatHandler.FriendState(IdConversions.UlongToAccountId(friendSummary.SteamId));
                friendsStackPanel.Dispatcher.Invoke(() =>
                {
                    var control = new FriendControl(new ChatUser { State = state, Summary = friendSummary });
                    control.MouseDoubleClick += FriendItem_Clicked;
                    friendsStackPanel.Children.Add(control);
                });
            }

            friendsStackPanel.Dispatcher.Invoke(() =>
            {
                //sort
                List<FriendControl> controls =
                    friendsStackPanel.Children.Cast<FriendControl>().OrderBy(x => x.Friend.Summary.PersonaName).ToList();

                friendsStackPanel.Children.Clear();

                foreach (FriendControl friendControl in controls)
                {
                    friendsStackPanel.Children.Add(friendControl);
                }
            });
        }

        static void FriendsListWindow_Closed(object sender, EventArgs e)
        {
            ChatWindow?.Close();
            ChatEventsManager.EndMessageLoop();
            ChatHandler.Logoff();
        }

        static void ChatWindow_Closed(object sender, EventArgs e)
        {
            var window = sender as ChatWindow;
            if (window == null) return;
            ChatWindow = null;
        }

        void FriendItem_Clicked(object sender, MouseButtonEventArgs e)
        {
            var control = sender as FriendControl;
            if (control == null) return;

            CheckCreateChatWindow();

            PlayerSummary summary = FriendSummaries.FirstOrDefault(x => x.PersonaName == control.personaName.Text);
            if (summary != null)
                ChatWindow.AddChatWindow(control.Friend, string.Empty);
        }

        void OnMessage(object sender, ChatMessageArgs e)
        {
            CheckCreateChatWindow();

            PlayerSummary summary =
                FriendSummaries.FirstOrDefault(
                    x => x.SteamId == IdConversions.AccountIdToUlong(e.ChatMessage.AccountIdFrom));

            if (summary == null)
            {
                MessageBox.Show("I was lazy and I don't poll for new friends. They attempted to send you a message.");
                return;
            }

            List<FriendControl> friendControls = new List<FriendControl>();
            ChatUser friend = null;

            friendsStackPanel.Dispatcher.Invoke(() =>
            {
                friendControls = friendsStackPanel.Children.Cast<FriendControl>().ToList();
            });

            foreach (FriendControl control in friendControls)
            {
                ulong steamId = 0;
                control.Dispatcher.Invoke(() => { steamId = control.Friend.Summary.SteamId; });
                if (steamId != summary.SteamId) continue;
                control.Dispatcher.Invoke(() => { friend = control.Friend; });
                break;
            }

            if (friend == null) throw new Exception("Could not locate friend, please report this!");

            ChatWindow.AddChatWindow(friend, e.ChatMessage.Text);
        }

        void CheckCreateChatWindow()
        {
            if (ChatWindow != null) return;

            if (!Dispatcher.CheckAccess())
            {
                Dispatcher.Invoke(() =>
                {
                    ChatWindow = new ChatWindow(ChatEventsManager, ChatHandler, SteamUserHandler);
                    ChatWindow.Closed += ChatWindow_Closed;
                    ChatWindow.Show();
                });
            }
            else
            {
                ChatWindow = new ChatWindow(ChatEventsManager, ChatHandler, SteamUserHandler);
                ChatWindow.Closed += ChatWindow_Closed;
                ChatWindow.Show();
            }
        }
    }
}


text:
echo makensis -DSHAKEY_VERSION=$VERSION support/nsis/app.nsi
makensis -DSHAKEY_VERSION=$VERSION support/nsis/app.nsi
echo makensis -DSHAKEY_VERSION=$VERSION support/nsis/install.nsi
makensis -DSHAKEY_VERSION=$VERSION support/nsis/install.nsi


text:
package org.springframework.social.greenhouse.api.impl;

import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.social.greenhouse.api.EventOperations;
import org.springframework.social.greenhouse.api.Greenhouse;
import org.springframework.social.greenhouse.api.SessionOperations;
import org.springframework.social.greenhouse.api.TweetOperations;
import org.springframework.social.greenhouse.api.UserOperations;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;

/**
 * This is the central class for interacting with Greenhouse.
 * @author Roy Clarkson
 */
public class GreenhouseTemplate extends AbstractOAuth2ApiBinding implements Greenhouse {

	private final String apiUrlBase;

	private UserOperations userOperations;

	private EventOperations eventOperations;

	private SessionOperations sessionOperations;

	private TweetOperations tweetOperations;

	/**
	 * Create a new instance of GreenhouseTemplate.
	 * @param accessToken an access token acquired through OAuth 2 authentication with Greenhouse
	 */
	public GreenhouseTemplate(String accessToken, String apiUrlBase) {
		super(accessToken);
		this.apiUrlBase = apiUrlBase;
		registerGreenhouseJsonModule();
		getRestTemplate().setErrorHandler(new GreenhouseErrorHandler());
		initSubApis();
	}

	public UserOperations userOperations() {
		return userOperations;
	}

	public EventOperations eventOperations() {
		return eventOperations;
	}

	public SessionOperations sessionOperations() {
		return sessionOperations;
	}

	public TweetOperations tweetOperations() {
		return tweetOperations;
	}

	// private helper

	private void registerGreenhouseJsonModule() {
		List<HttpMessageConverter<?>> converters = getRestTemplate().getMessageConverters();
		for (HttpMessageConverter<?> converter : converters) {
			if(converter instanceof MappingJacksonHttpMessageConverter) {
				MappingJacksonHttpMessageConverter jsonConverter = (MappingJacksonHttpMessageConverter) converter;
				ObjectMapper objectMapper = new ObjectMapper();
				objectMapper.registerModule(new GreenhouseModule());
				jsonConverter.setObjectMapper(objectMapper);
			}
		}
	}

	private String getApiUrlBase() {
		return apiUrlBase;
	}

	private void initSubApis() {
		this.userOperations = new UserTemplate(getRestTemplate(), isAuthorized(), getApiUrlBase());
		this.eventOperations = new EventTemplate(getRestTemplate(), isAuthorized(), getApiUrlBase());
		this.sessionOperations = new SessionTemplate(getRestTemplate(), isAuthorized(), getApiUrlBase());
		this.tweetOperations = new TweetTemplate(getRestTemplate(), isAuthorized(), getApiUrlBase());
	}

}


text:
package org.jboss.narayana.txframework.functional.ws.ba.participantCompletion;

import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Cancel;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Close;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Compensate;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Completes;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.ConfirmCompleted;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Error;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Status;
import org.jboss.narayana.txframework.api.annotation.lifecycle.ba.Unknown;
import org.jboss.narayana.txframework.api.annotation.service.ServiceRequest;
import org.jboss.narayana.txframework.api.annotation.transaction.Compensatable;
import org.jboss.narayana.txframework.api.configuration.transaction.CompletionType;
import org.jboss.narayana.txframework.api.management.TXDataMap;
import org.jboss.narayana.txframework.api.management.WSBATxControl;
import org.jboss.narayana.txframework.functional.common.EventLog;
import org.jboss.narayana.txframework.functional.common.ServiceCommand;
import org.jboss.narayana.txframework.functional.common.SomeApplicationException;

import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;
import java.lang.annotation.Annotation;

import static org.jboss.narayana.txframework.functional.common.ServiceCommand.*;

/**
 * @author Paul Robinson (paul.robinson@redhat.com)
 */
@Stateless
@WebService(serviceName = "BAParticipantCompletionService", portName = "BAParticipantCompletionService",
        name = "BAParticipantCompletion", targetNamespace = "http://www.jboss.com/functional/ba/participantcompletion/")
@SOAPBinding(style = SOAPBinding.Style.RPC)
@Compensatable(completionType = CompletionType.PARTICIPANT)
public class BAParticipantCompletionService implements BAParticipantCompletion {

    @Inject
    private WSBATxControl txControl;
    @Inject
    private EventLog eventLog = new EventLog();
    @Inject
    private TXDataMap<String, String> txDataMap;

    @WebMethod
    @ServiceRequest
    @Completes
    public void saveDataAutoComplete(ServiceCommand... serviceCommands) throws SomeApplicationException {

        saveData(serviceCommands);
    }

    @WebMethod
    @ServiceRequest
    public void saveDataManualComplete(ServiceCommand... serviceCommands) throws SomeApplicationException {

        saveData(serviceCommands);
    }

    private void saveData(ServiceCommand[] serviceCommands) throws SomeApplicationException {

        txDataMap.put("data", "data");
        if (present(THROW_APPLICATION_EXCEPTION, serviceCommands)) {
            throw new SomeApplicationException("Intentionally thrown Exception");
        }

        if (present(CANNOT_COMPLETE, serviceCommands)) {
            txControl.cannotComplete();
            return;
        }

        if (present(COMPLETE, serviceCommands)) {
            txControl.completed();
        }
    }

    @WebMethod
    public EventLog getEventLog() {

        return eventLog;
    }

    @WebMethod
    public void clearEventLog() {

        eventLog.clear();
    }

    @Compensate
    @WebMethod(exclude = true)
    public void compensate() {

        logEvent(Compensate.class);
    }

    @ConfirmCompleted
    @WebMethod(exclude = true)
    public void confirmCompleted(Boolean success) {

        logEvent(ConfirmCompleted.class);
    }

    @Cancel
    @WebMethod(exclude = true)
    public void cancel() {

        logEvent(Cancel.class);
    }

    @Close
    @WebMethod(exclude = true)
    public void close() {

        logEvent(Close.class);
    }

    @ConfirmCompleted
    @WebMethod(exclude = true)
    public void confirmCompleted(boolean success) {

        logEvent(ConfirmCompleted.class);
    }

    @Error
    @WebMethod(exclude = true)
    public void error() {

        logEvent(Error.class);
    }

    @Status
    @WebMethod(exclude = true)
    public String status() {

        logEvent(Status.class);
        return null;
    }

    @Unknown
    @WebMethod(exclude = true)
    public void unknown() {

        logEvent(Unknown.class);
    }

    private boolean present(ServiceCommand expectedServiceCommand, ServiceCommand... serviceCommands) {

        for (ServiceCommand foundServiceCommand : serviceCommands) {
            if (foundServiceCommand == expectedServiceCommand) {
                return true;
            }
        }
        return false;
    }

    private void logEvent(Class<? extends Annotation> event) {
        //Check data is available
        if (txDataMap.get("data") == null) {
            eventLog.addDataUnavailable(event);
        }

        eventLog.addEvent(event);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jdbi.v3.core.argument.internal;

import java.lang.reflect.Type;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

import org.jdbi.v3.core.annotation.internal.JdbiAnnotations;
import org.jdbi.v3.core.argument.NamedArgumentFinder;
import org.jdbi.v3.core.config.ConfigRegistry;
import org.jdbi.v3.core.mapper.reflect.internal.PojoProperties;
import org.jdbi.v3.core.mapper.reflect.internal.PojoProperties.PojoProperty;
import org.jdbi.v3.core.mapper.reflect.internal.PojoTypes;
import org.jdbi.v3.core.statement.StatementContext;
import org.jdbi.v3.core.statement.UnableToCreateStatementException;

/**
 * This class hosts the logic from BeanPropertyArguments.
 * When we can remove that class from public API, this class will easily replace it.
 */
public class PojoPropertyArguments extends ObjectPropertyNamedArgumentFinder {
    protected final PojoProperties<?> properties;
    protected final ConfigRegistry config;
    private final Set<String> names;

    public PojoPropertyArguments(String prefix, Object obj, Type type, ConfigRegistry config) {
        this(prefix,
                obj,
                config.get(PojoTypes.class).findFor(type)
                    .orElseThrow(() -> new UnableToCreateStatementException("Couldn't find pojo type of " + obj.getClass())),
                config);
    }

    protected PojoPropertyArguments(String prefix, Object obj, PojoProperties<?> properties, ConfigRegistry config) {
        super(prefix, obj);
        this.properties = properties;
        this.config = config;
        names = properties.getProperties()
                .entrySet()
                .stream()
                .filter(e -> JdbiAnnotations.isBound(e.getValue()))
                .map(Entry::getKey)
                .collect(Collectors.toSet());
    }

    @Override
    protected Optional<TypedValue> getValue(String name, StatementContext ctx) {
        return Optional.ofNullable(properties.getProperties().get(name))
                .map(PojoProperty.class::cast)
                .filter(JdbiAnnotations::isBound)
                .map(p -> new TypedValue(p.getQualifiedType(), p.get(obj)));
    }

    @Override
    public Collection<String> getNames() {
        return names;
    }

    @Override
    protected NamedArgumentFinder getNestedArgumentFinder(TypedValue value) {
        return new PojoPropertyArguments(null, value.getValue(), value.getType().getType(), config);
    }

    @Override
    public String toString() {
        return "{lazy bean property arguments \"" + obj + "\"}";
    }
}