text:
from service.cmd import vsctl, ofctl, run_cmd, daemon_start
from urllib.parse import urlparse
import socket
import logging
import docker
import os
import netifaces

logger = logging.getLogger()

A_SW_DEF = {'name': 'aswitch', 'dp_id': '00:00:00:00:00:00:00:00', 'status': 'active'}
A_SW_NAME = A_SW_DEF['name']

NETWORK_LAB_NAME = os.environ.get("NETWORK_LAB_NAME")
NETWORK_LAB_IFACE = None
if NETWORK_LAB_NAME is not None:
    docker_client = docker.from_env()
    self_container = docker_client.containers.get(os.environ.get('HOSTNAME'))
    network_lab_iface_mac = self_container.attrs['NetworkSettings']['Networks'][NETWORK_LAB_NAME]['MacAddress']
    for iface in netifaces.interfaces():
        ifaddr = netifaces.ifaddresses(iface)
        if ifaddr[netifaces.AF_LINK][0]['addr'] == network_lab_iface_mac:
            NETWORK_LAB_IFACE = iface

def pname(sw, port):
    return '{}-{}'.format(sw, port)

def resolve_host(uri):
    parts = uri.split(":", 3)
    assert len(parts) == 3, "Controller uri '%s' is incorrect" % uri

    try:
        ip = socket.gethostbyname(parts[1])
    except socket.gaierror as e:
        raise Exception("Couldn't resolve host '%s', seems like Floodlight is down" % parts[1]) from e  # noqa
    return parts[0] + ":" + ip + ":" + parts[2]

class Switch:
    def __init__(self, name, of_ver, controller=None):
        self.name = name
        self.of_ver = of_ver
        self.vscmd = []
        self.controller = controller

    def get_and_flush_batch_cmd(self):
        cmd = " -- ".join(self.vscmd)
        self.vscmd = []
        return cmd

    @classmethod
    def create(cls, sw_def):
        # force OF 1.3
        of_ver = 'OpenFlow13'
        name = sw_def['name']
        controller = None
        if 'controller' in sw_def:
            controller = " ".join([resolve_host(cnt) for cnt in sw_def['controller'].split(" ")])
        switch = cls(name, of_ver, controller)

        cmd = [
            '--if-exists del-br %s' % name,
            'add-br %s' % name,
            'set bridge {} other-config:datapath-id={}'.format(name, sw_def['dp_id'].replace(':', '')),
            'set bridge %s fail_mode=secure' % name,
            'set bridge {} protocols={}'.format(name, of_ver)
        ]

        switch.vscmd.extend(cmd)
        return switch

    @classmethod
    def create_with_ports(cls, sw_def):
        sw = Switch.create(sw_def)
        sw.define_ports(range(1, sw_def['max_port'] + 1))
        sw.define_server42_port(sw_def)
        return sw

    def destroy(self):
        self.vscmd.extend((['del-br {}'.format(self.name)]))

    def define_ports(self, ports):
        cmd = []
        for pnum in ports:
            cmd.append('add-port {} {}'.format(self.name, pname(self.name, str(pnum))))
        self.vscmd.extend(cmd)

    def setup_port(self, p_name, p_num, bandwidth=None):
        cmd = [
            'set interface {} ofport_request={}'.format(p_name, p_num),
        ]
        if bandwidth:
            cmd.append('set interface {} ingress_policing_rate={}'.format(p_name, bandwidth))
        self.vscmd.extend(cmd)

    def define_server42_port(self, sw_def):
        prop = sw_def.get('prop', None)
        if prop is not None and prop.get('server42_flow_rtt', False) \
                and NETWORK_LAB_IFACE is not None:
            prop = sw_def['prop']
            port = prop['server42_port']
            vlan = prop['server42_vlan']
            self.vscmd.extend(
                ['add-port {} {}.{}'.format(self.name, NETWORK_LAB_IFACE, vlan),
                 'set interface {}.{} ofport={}'.format(NETWORK_LAB_IFACE, vlan, port)])
            run_cmd(f'ip link add link {NETWORK_LAB_IFACE} name {NETWORK_LAB_IFACE}.{vlan} type vlan id {vlan}')
            run_cmd(f'ip link set up {NETWORK_LAB_IFACE}.{vlan}')

    def dump_flows(self):
        return ofctl(["dump-flows {sw} -O {of_ver}".format(sw=self.name, of_ver=self.of_ver)])[0]

    def mod_port_state(self, ports, port_state):
        if ports and port_state:
            ofctl(["mod-port {sw} -O {of_ver} {port} {port_state}"
                  .format(sw=self.name, of_ver=self.of_ver, port=str(port), port_state=port_state) for port in ports])

    def force_update_controller_host(self, controller, batch=True):
        cmd = [
            'set-controller {} {}'.format(self.name, controller),
            'set bridge {} other-config:disable-in-band=true'.format(self.name)
        ]
        self.vscmd.extend(cmd) if batch else vsctl(cmd)

    def add_controller(self, batch=True):
        if self.controller:
            cmd = [
                'set-controller {} {}'.format(self.name, self.controller),
                'set bridge {} other-config:disable-in-band=true'.format(self.name)
            ]
            self.vscmd.extend(cmd) if batch else vsctl(cmd)

    def set_controller(self, controller):
        cnt = " ".join([resolve_host(controller) for controller in controller.split(" ")])
        cmd = ['set-controller {} {}'.format(self.name, cnt)]
        vsctl(cmd)

    def update_burst_size_and_rate(self, meter_id, burst_size, rate):
        cmd = '-O {of_ver} mod-meter {sw} meter={meter_id},pktps,burst,stats,bands=type=drop,' \
              'rate={rate},burst_size={burst_size}'.format(sw=self.name, of_ver=self.of_ver, meter_id=meter_id,
                                                           burst_size=burst_size, rate=rate)
        ofctl([cmd])

class ASwitch(Switch):
    def add_route_flows(self, mappings):
        if mappings:
            ofctl(['add-flow {sw} -O {of_ver} in_port={in_port},actions=output={out_port}'
                  .format(sw=self.name, of_ver=self.of_ver, **flow) for flow in mappings])

    def del_route_flows(self, mappings):
        if mappings:
            ofctl(['del-flows {sw} -O {of_ver} in_port={in_port}'
                  .format(sw=self.name, of_ver=self.of_ver, **flow) for flow in mappings])

class Link:
    def __init__(self, src, src_port, dst, dst_port, bandwidth, is_isl):
        self.src = src
        self.src_port = src_port
        self.dst = dst
        self.dst_port = dst_port
        self.bandwidth = bandwidth
        self.is_isl = is_isl

    def src_name(self):
        return pname(self.src, self.src_port)

    def dst_name(self):
        return pname(self.dst, self.dst_port)

    @classmethod
    def create(cls, src, src_port, dst, dst_port, bandwidth=None, is_isl=True):
        link = cls(src, src_port, dst, dst_port, bandwidth, is_isl)

        run_cmd('ip link add {} type veth peer name {}'.format(link.src_name(), link.dst_name()))
        run_cmd('ip link set up {}'.format(link.src_name()))
        run_cmd('ip link set up {}'.format(link.dst_name()))

        return link

    def destroy(self):
        run_cmd('ip link delete {}'.format(self.src_name()))

    def setup_switch_ports(self, switches):
        switches[self.src].setup_port(self.src_name(), self.src_port, self.bandwidth)
        if self.is_isl:
            switches[self.dst].setup_port(self.dst_name(), self.dst_port, self.bandwidth)

class Traffgen:
    proc = None

    def __init__(self, tgen_def):
        self.name = tgen_def['name']
        self.iface = tgen_def['iface_name']
        self.sw = tgen_def['switch_connected']
        self.sw_port = tgen_def['switch_port']
        ctrl_url = urlparse(tgen_def['control_endpoint'])

        # listen rest on all interfaces
        self.endpoint = '%s:%s' % ('0.0.0.0', str(ctrl_url.port))

    def make_link(self):
        return Link.create(self.sw, self.sw_port, self.name, self.iface, is_isl=False)

    def run(self):
        self.proc = daemon_start(
            ['kilda-traffexam', pname(self.name, str(self.iface)), self.endpoint],
            self.name)

    def destroy(self):
        if self.proc:
            self.proc.terminate()

class Topology:
    def __init__(self, switches, links, traffgens):
        self.switches = switches
        self.links = links
        self.traffgens = traffgens

    @classmethod
    def create(cls, topo_def):
        switches = {}
        links = []
        traffgens = []
        a_mappings = []
        a_ports = set()

        for isl_def in topo_def['isls']:
            src = isl_def['src_switch']
            src_port = isl_def['src_port']
            dst = isl_def.get('dst_switch', None)
            dst_port = isl_def.get('dst_port', None)
            bandwidth = isl_def.get('max_bandwidth', None)
            a_def = isl_def.get('aswitch', None)

            if a_def:
                if a_def.get('in_port', None):
                    a_ports.add(a_def['in_port'])
                if a_def.get('out_port', None):
                    a_ports.add(a_def['out_port'])

                links.append(Link.create(src, src_port, A_SW_NAME, a_def['in_port'], bandwidth))
                if dst and dst_port:
                    links.append(Link.create(A_SW_NAME, a_def['out_port'], dst, dst_port, bandwidth))
                    a_mappings.append(
                        {'in_port': a_def['in_port'], 'out_port': a_def['out_port']})
                    a_mappings.append(
                        {'in_port': a_def['out_port'], 'out_port': a_def['in_port']})
            else:
                links.append(Link.create(src, src_port, dst, dst_port, bandwidth))

        for tgen_def in [active_tgen for active_tgen in topo_def.get('traff_gens', [])
                         if active_tgen['status'].lower() == "active"]:
            tg = Traffgen(tgen_def)
            traffgens.append(tg)
            links.append(tg.make_link())

        switches[A_SW_NAME] = ASwitch.create(A_SW_DEF)
        switches[A_SW_NAME].define_ports(a_ports)
        for sw_def in topo_def['switches']:
            sw = Switch.create_with_ports(sw_def)
            switches[sw.name] = sw

        for link in links:
            link.setup_switch_ports(switches)

        vsctl(['set Open_vSwitch . other_config:vlan-limit=0'])
        cls.batch_switch_cmd(switches)
        run_cmd('ovs-appctl revalidator/purge')

        switches[A_SW_NAME].add_route_flows(a_mappings)
        return cls(switches, links, traffgens)

    # This should be ~ 'getconf ARG_MAX' / 8
    # Empirical constant copied from Mininet
    ARG_MAX = 128000

    @classmethod
    def batch_switch_cmd(cls, switches):
        vsctl_len = len('ovs-vsctl')
        cmds = []
        cmds_len = 0
        for sw in switches.values():
            cmd = sw.get_and_flush_batch_cmd()
            # Don't exceed ARG_MAX
            if len(cmd) + cmds_len + vsctl_len >= cls.ARG_MAX:
                vsctl(cmds)
                cmds = []
                cmds_len = 0
            cmds.append(cmd)
            cmds_len += len(cmd)
        if cmds:
            vsctl(cmds)

    def run(self):
        for sw in self.switches.values():
            sw.add_controller()
        Topology.batch_switch_cmd(self.switches)

        for tgen in self.traffgens:
            tgen.run()

    def destroy(self):
        for tgen in self.traffgens:
            tgen.destroy()

        for sw in self.switches.values():
            sw.destroy()
        Topology.batch_switch_cmd(self.switches)

        for link in self.links:
            link.destroy()


text:
"use babel";

import OutputStore, {
  reduceOutputs,
  isSingeLine
} from "../../lib/store/output";

// Adapted from https://github.com/nteract/nteract/blob/master/test/renderer/reducers/document-spec.js#L33
describe("reduceOutputs", () => {
  it("puts new outputs at the end by default", () => {
    const outputs = [
      { output_type: "stream", name: "stdout", text: "Woo" },
      { output_type: "error", ename: "well", evalue: "actually", traceback: [] }
    ];
    const newOutputs = reduceOutputs(outputs, {
      output_type: "display_data",
      data: {},
      metadata: {}
    });

    expect(newOutputs).toEqual([
      { output_type: "stream", name: "stdout", text: "Woo" },
      {
        output_type: "error",
        ename: "well",
        evalue: "actually",
        traceback: []
      },
      {
        output_type: "display_data",
        data: {},
        metadata: {}
      }
    ]);
  });

  it("handles the case of a single stream output", () => {
    const outputs = [{ name: "stdout", text: "hello", output_type: "stream" }];
    const newOutputs = reduceOutputs(outputs, {
      name: "stdout",
      text: " world",
      output_type: "stream"
    });

    expect(newOutputs).toEqual([
      {
        name: "stdout",
        text: "hello world",
        output_type: "stream"
      }
    ]);
  });

  it("merges streams of text", () => {
    let outputs = [];

    outputs = reduceOutputs(outputs, {
      name: "stdout",
      text: "hello",
      output_type: "stream"
    });
    expect(outputs).toEqual([
      { output_type: "stream", name: "stdout", text: "hello" }
    ]);

    outputs = reduceOutputs(outputs, {
      name: "stdout",
      text: " world",
      output_type: "stream"
    });
    expect(outputs).toEqual([
      {
        output_type: "stream",
        name: "stdout",
        text: "hello world"
      }
    ]);
  });

  it("keeps respective streams together", () => {
    const outputs = [
      { name: "stdout", text: "hello", output_type: "stream" },
      { name: "stderr", text: "errors are", output_type: "stream" }
    ];
    const newOutputs = reduceOutputs(outputs, {
      name: "stdout",
      text: " world",
      output_type: "stream"
    });

    expect(newOutputs).toEqual([
      {
        name: "stdout",
        text: "hello world",
        output_type: "stream"
      },
      {
        name: "stderr",
        text: "errors are",
        output_type: "stream"
      }
    ]);

    const evenNewerOutputs = reduceOutputs(newOutputs, {
      name: "stderr",
      text: " informative",
      output_type: "stream"
    });
    expect(evenNewerOutputs).toEqual([
      {
        name: "stdout",
        text: "hello world",
        output_type: "stream"
      },
      {
        name: "stderr",
        text: "errors are informative",
        output_type: "stream"
      }
    ]);
  });
});

describe("isSingeLine", () => {
  it("checks for single line output", () => {
    const textSingle = "hello world";
    expect(isSingeLine(textSingle, textSingle.length + 1)).toEqual(true);
    expect(isSingeLine(textSingle, textSingle.length)).toEqual(false);
  });
  it("checks for multiple line output", () => {
    const textMultiple = "hello \n world";
    expect(isSingeLine(textMultiple, textMultiple.length + 1)).toEqual(false);
    expect(isSingeLine(textMultiple, textMultiple.length)).toEqual(false);
  });
  it("checks for single line output with line break at the end ", () => {
    const textEndlinebreak = "hello world \n";
    expect(isSingeLine(textEndlinebreak, textEndlinebreak.length + 1)).toEqual(
      true
    );
    expect(isSingeLine(textEndlinebreak, textEndlinebreak.length)).toEqual(
      false
    );
  });
});

describe("OutputStore", () => {
  let store;
  beforeEach(() => {
    store = new OutputStore();
  });
  describe("updatePosition", () => {
    it("checks if output lineHeight position gets updated", () => {
      store.updatePosition({ lineHeight: 10 });
      expect(store.position).toEqual({
        lineHeight: 10,
        lineLength: 0,
        editorWidth: 0,
        charWidth: 0
      });
    });
    it("checks if output lineLength position gets updated", () => {
      store.updatePosition({ lineLength: 10 });
      expect(store.position).toEqual({
        lineHeight: 0,
        lineLength: 10,
        editorWidth: 0,
        charWidth: 0
      });
    });
    it("checks if output editorWidth position gets updated", () => {
      store.updatePosition({ editorWidth: 10 });
      expect(store.position).toEqual({
        lineHeight: 0,
        lineLength: 0,
        editorWidth: 10,
        charWidth: 0
      });
    });
    it("checks if all output positions get updated", () => {
      store.updatePosition({
        lineHeight: 10,
        lineLength: 10,
        editorWidth: 10,
        charWidth: 12
      });
      expect(store.position).toEqual({
        lineHeight: 10,
        lineLength: 10,
        editorWidth: 10,
        charWidth: 12
      });
    });
  });
  describe("setIndex", () => {
    it("checks if index is set up right ", () => {
      store.outputs = [1, 2];
      store.setIndex(0);
      expect(store.index).toEqual(0);
      store.setIndex(1);
      expect(store.index).toEqual(1);
      store.setIndex(2);
      expect(store.index).toEqual(1);
      store.setIndex(-2);
      expect(store.index).toEqual(0);
    });
  });
  describe("incrementIndex", () => {
    it("checks if index incrementing works ", () => {
      store.outputs = [1, 2];
      store.setIndex(0);
      store.incrementIndex();
      expect(store.index).toEqual(1);
    });
  });
  describe("decrementIndex", () => {
    it("checks if index decrementing works ", () => {
      store.outputs = [1, 2];
      store.setIndex(1);
      store.decrementIndex();
      //index is now at 0
      expect(0).toEqual(store.index);
      store.decrementIndex();
      //index is now at -1
      expect(0).toEqual(store.index);
    });
    describe("clear", () => {
      it("checks if output clearing works ", () => {
        store.outputs.push("foo");
        expect(store.outputs.length).toEqual(1);
        store.setIndex(0);
        expect(store.index).toEqual(0);
        store.clear();
        expect(store.outputs.length).toEqual(0);
        expect(store.index).toEqual(-1);
      });
    });
  });
});

redpajama_set_name: RedPajamaGithub


text:
var ColumnCompiler, MysqlSchemaCompiler, SchemaCompiler, _, tools;

_ = require('lodash');

tools = require('../../tools');

SchemaCompiler = require('../../schema/SchemaCompiler');

ColumnCompiler = require('./ColumnCompiler');

module.exports = MysqlSchemaCompiler = (function() {
  class MysqlSchemaCompiler extends SchemaCompiler {
    // https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
    // ALTER [IGNORE] TABLE tbl_name
    //   DROP [COLUMN] col_name
    dropColumn(tableName, column, options) {
      var LF, escapeId, indent, words;
      ({words, escapeId, indent, LF} = this);
      return words.alter_table + ' ' + escapeId(tableName) + LF + indent + words.drop_column + ' ' + escapeId(column);
    }

    diffType(tableName, column, oldColumnSpec, newColumnSpec) {
      var LF, altersql, args, columnCompiler, columnId, escapeId, indent, newModifier, newTypeString, oldModifier, oldTypeString, options, tablesql, words;
      options = _.defaults({}, options, this.options);
      ({words, escapeId, columnCompiler, args, indent, LF} = this);
      args.table = tableName;
      args.column = column;
      columnId = escapeId(column);
      // ALTER TABLE [ IF EXISTS ] name
      tablesql = [words.alter_table, ' '];
      if (options.if_exists) {
        tablesql.push(words.if_exists);
        tablesql.push(' ');
      }
      tablesql.push.apply(tablesql, [escapeId(tableName), LF]);
      altersql = [];
      oldTypeString = columnCompiler.getTypeString(oldColumnSpec);
      newTypeString = columnCompiler.getTypeString(newColumnSpec);
      oldModifier = columnCompiler.getColumnModifier(oldColumnSpec);
      newModifier = columnCompiler.getColumnModifier(newColumnSpec);
      if (oldTypeString !== newTypeString) {
        if (oldColumnSpec.type === 'enum' && newColumnSpec.type === 'enum') {
          return;
        }
        // CHANGE [COLUMN] old_col_name new_col_name column_definition
        // TODO: find a way to compare enum
        tablesql.push.apply(tablesql, [indent, words.change_column, ' ', columnId, ' ', columnId, ' ', newTypeString, ' ', newModifier]);
      } else if (oldModifier !== newModifier) {
        return;
      } else {
        return;
      }
      // TODO: more tests to be able to do a proper default value comparaison
      // console.log oldModifier, newModifier
      return tablesql.join('');
    }

    // Rename primary key does not exist in MySQL 5.7
    // we may drop the old one and create a new one,
    // but it will probably cause mess with foreign keys
    renamePrimaryKey() {}

    // https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
    // ALTER [IGNORE] TABLE tbl_name
    //   DROP PRIMARY KEY
    dropPrimaryKey(tableName, oldName, options) {
      var LF, escapeId, indent, words;
      options = _.defaults({}, options, this.options);
      ({words, escapeId, indent, LF} = this);
      return words.alter_table + ' ' + escapeId(tableName) + LF + indent + words.drop_primary_key;
    }

    // Rename foreign key does not exist in MySQL 5.7
    // drop the old one and create a new one
    renameForeignKey(newTableModel, oldName, newKey, oldTableModel, options) {
      return this.dropForeignKey(oldTableModel, oldName, options) + ';\n' + this.addForeignKey(newTableModel, newKey, options);
    }

    // https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
    // ALTER [IGNORE] TABLE tbl_name
    //   DROP FOREIGN KEY fk_symbol
    dropForeignKey(oldTableModel, oldName, options) {
      var LF, escapeId, indent, ref, ref1, sql, words;
      options = _.defaults({}, options, this.options);
      ({words, escapeId, indent, LF} = this);
      sql = words.alter_table + ' ' + escapeId(oldTableModel.name) + LF + indent + words.drop_foreign_key + ' ' + escapeId(oldName);
      // MySQL also drops the index with the same name
      if ((ref = oldTableModel.indexes) != null ? ref.hasOwnProperty(oldName) : void 0) {
        delete oldTableModel.indexes[oldName];
      }
      if ((ref1 = oldTableModel.constraints.UNIQUE) != null ? ref1.hasOwnProperty(oldName) : void 0) {
        delete oldTableModel.constraints.UNIQUE[oldName];
      }
      return sql;
    }

    // https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
    // ALTER [IGNORE] TABLE tbl_name
    //   RENAME {INDEX|KEY} old_index_name TO new_index_name
    renameIndex(tableName, oldName, newName, options) {
      var LF, escapeId, indent, words;
      ({words, escapeId, indent, LF} = this);
      return words.alter_table + ' ' + escapeId(tableName) + LF + indent + words.rename_index + ' ' + escapeId(oldName) + ' ' + words.to + ' ' + escapeId(newName);
    }

    // https://dev.mysql.com/doc/refman/5.7/en/alter-table.html
    // ALTER [IGNORE] TABLE tbl_name
    //   DROP {INDEX|KEY} index_name
    dropIndex(tableName, indexName, options = {}) {
      var LF, escapeId, indent, words;
      options = _.defaults({}, options, this.options);
      ({words, escapeId, indent, LF} = this);
      return words.alter_table + ' ' + escapeId(tableName) + LF + indent + words.drop_index + ' ' + escapeId(indexName);
    }

  };

  MysqlSchemaCompiler.prototype.ColumnCompiler = ColumnCompiler;

  // https://dev.mysql.com/doc/refman/5.7/en/create-table-foreign-keys.html
  MysqlSchemaCompiler.prototype.validUpdateActions = ['no_action', 'restrict', 'cascade', 'set_null'];

  return MysqlSchemaCompiler;

}).call(this);

MysqlSchemaCompiler.prototype.renameUniqueIndex = MysqlSchemaCompiler.prototype.renameIndex;

MysqlSchemaCompiler.prototype.dropUniqueIndex = MysqlSchemaCompiler.prototype.dropIndex;


text:
/* this file has been autogenerated by vtkNodeJsWrap */
/* editing this might proof futile */

#ifndef NATIVE_EXTENSION_VTK_VTKLODPROP3DWRAP_H
#define NATIVE_EXTENSION_VTK_VTKLODPROP3DWRAP_H

#include <nan.h>

#include <vtkSmartPointer.h>
#include <vtkLODProp3D.h>

#include "vtkProp3DWrap.h"
#include "../../plus/plus.h"

class VtkLODProp3DWrap : public VtkProp3DWrap
{
	public:
		using Nan::ObjectWrap::Wrap;
		static void Init(v8::Local<v8::Object> exports);
		static void InitPtpl();
		static void ConstructorGetter(
			v8::Local<v8::String> property,
			const Nan::PropertyCallbackInfo<v8::Value>& info);

		VtkLODProp3DWrap(vtkSmartPointer<vtkLODProp3D>);
		VtkLODProp3DWrap();
		~VtkLODProp3DWrap( );
		static Nan::Persistent<v8::FunctionTemplate> ptpl;

	private:
		static void New(const Nan::FunctionCallbackInfo<v8::Value>& info);

		static void AddEstimatedRenderTime(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void AddLOD(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void AutomaticLODSelectionOff(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void AutomaticLODSelectionOn(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void AutomaticPickLODSelectionOff(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void AutomaticPickLODSelectionOn(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void DisableLOD(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void EnableLOD(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetActors(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetAutomaticLODSelection(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetAutomaticLODSelectionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetAutomaticLODSelectionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetAutomaticPickLODSelection(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetAutomaticPickLODSelectionMaxValue(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetAutomaticPickLODSelectionMinValue(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetBounds(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetCurrentIndex(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetLODEstimatedRenderTime(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetLODIndexEstimatedRenderTime(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetLODIndexLevel(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetLODLevel(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetLODMapper(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetLastRenderedLODID(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetNumberOfLODs(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetPickLODID(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetSelectedLODID(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetSelectedPickLODID(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void GetVolumes(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void HasTranslucentPolygonalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsA(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void IsLODEnabled(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ReleaseGraphicsResources(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void RemoveLOD(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void RenderOpaqueGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void RenderTranslucentPolygonalGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void RenderVolumetricGeometry(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void RestoreEstimatedRenderTime(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetAllocatedRenderTime(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetAutomaticLODSelection(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetAutomaticPickLODSelection(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetLODBackfaceProperty(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetLODLevel(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetLODMapper(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetLODProperty(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetLODTexture(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetSelectedLODID(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void SetSelectedPickLODID(const Nan::FunctionCallbackInfo<v8::Value>& info);
		static void ShallowCopy(const Nan::FunctionCallbackInfo<v8::Value>& info);

#ifdef VTK_NODE_PLUS_VTKLODPROP3DWRAP_CLASSDEF
		VTK_NODE_PLUS_VTKLODPROP3DWRAP_CLASSDEF
#endif
};

#endif


text:
***********
Performance
***********

.. note:: XXX: This section is not yet written.

.. automodule:: numpy.doc.performance


text:
// 5 april 2015
// based on wintooltipsubclasstest.c 31 march-2 april 2015
#define UNICODE
#define _UNICODE
#define STRICT
#define STRICT_TYPED_ITEMIDS
#define CINTERFACE
// get Windows version right; right now Windows XP
#define WINVER 0x0501
#define _WIN32_WINNT 0x0501
#define _WIN32_WINDOWS 0x0501		/* according to Microsoft's winperf.h */
#define _WIN32_IE 0x0600			/* according to Microsoft's sdkddkver.h */
#define NTDDI_VERSION 0x05010000	/* according to Microsoft's sdkddkver.h */
#include <windows.h>
#include <commctrl.h>
#include <windowsx.h>
#include <stdio.h>
#include <stdlib.h>

void die(char *why)
{
	fprintf(stderr, "error %s: %I32u\n", why, GetLastError());
	abort();
}

HWND tooltip = NULL;
HINSTANCE hInstance;

void makeTooltip(HWND hwnd)
{
	TOOLINFOW ti;

	tooltip = CreateWindowExW(WS_EX_TOOLWINDOW,
		TOOLTIPS_CLASSW, L"",
		WS_POPUP | TTS_NOPREFIX,
		0, 0,
		0, 0,
		hwnd, NULL, hInstance, NULL);
	if (tooltip == NULL)
		die("creating tooltip");

	ZeroMemory(&ti, sizeof (TOOLINFOW));
	ti.cbSize = TTTOOLINFOW_V2_SIZE;
	ti.uFlags = TTF_IDISHWND | TTF_SUBCLASS | TTF_TRANSPARENT;
	ti.hwnd = hwnd;
	ti.uId = (UINT_PTR) hwnd;
	ti.hinst = hInstance;
	ti.lpszText = L"this is a tooltip! wow!";
	if (SendMessageW(tooltip, TTM_ADDTOOL, 0, (LPARAM) (&ti)) == FALSE)
		die("setting up tooltip");
}

LPARAM last = 0;

LRESULT CALLBACK wndproc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
	switch (uMsg) {
	case WM_CLOSE:
		PostQuitMessage(0);
		break;
	case WM_MOUSEMOVE:
		// cheap way of testing for hovers
		if (lParam != last)
			SetTimer(hwnd, 1, GetDoubleClickTime(), NULL);
		last = lParam;
		break;
	case WM_TIMER:
		if (wParam != 1)
			break;
		KillTimer(hwnd, 1);
		makeTooltip(hwnd);
		SendMessage(tooltip, TTM_POPUP, 0, 0);
		return 0;
	}
	return DefWindowProc(hwnd, uMsg, wParam, lParam);
}

void initCommonControls(BOOL);

int main(int argc, char *argv[])
{
	BOOL comctl5;
	WNDCLASSW wc;
	HWND mainwin;
	MSG msg;

	hInstance = GetModuleHandle(NULL);

	comctl5 = FALSE;
	if (argc > 1)
		comctl5 = strcmp(argv[1], "comctl5") == 0;
	initCommonControls(comctl5);

	ZeroMemory(&wc, sizeof (WNDCLASSW));
	wc.lpszClassName = L"mainwin";
	wc.lpfnWndProc = wndproc;
	wc.hIcon = LoadIconW(NULL, IDI_APPLICATION);
	wc.hCursor = LoadCursorW(NULL, IDC_ARROW);
	wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1);
	wc.hInstance = GetModuleHandle(NULL);
	if (RegisterClassW(&wc) == 0)
		die("registering main window class");

	mainwin = CreateWindowExW(0,
		L"mainwin", L"Main Window",
		WS_OVERLAPPEDWINDOW,
		CW_USEDEFAULT, CW_USEDEFAULT,
		CW_USEDEFAULT, CW_USEDEFAULT,
		NULL, NULL, GetModuleHandle(NULL), NULL);
	if (mainwin == NULL)
		die("creating main window");

	ShowWindow(mainwin, SW_SHOWDEFAULT);
	UpdateWindow(mainwin);

	while (GetMessage(&msg, NULL, 0, 0) > 0) {
		TranslateMessage(&msg);
		DispatchMessage(&msg);
	}
	return 0;
}

// MSDN doesn't list a constant that only includes tooltips but says this and a few others do
#define wantedICCClasses (ICC_BAR_CLASSES)

static ULONG_PTR comctlManifestCookie;
static HMODULE comctl32;

// note that this is an 8-bit character string we're writing; see the encoding clause
static const char manifest[] = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n<assemblyIdentity\n    version=\"1.0.0.0\"\n    processorArchitecture=\"*\"\n    name=\"CompanyName.ProductName.YourApplication\"\n    type=\"win32\"\n/>\n<description>Your application description here.</description>\n<dependency>\n    <dependentAssembly>\n        <assemblyIdentity\n            type=\"win32\"\n            name=\"Microsoft.Windows.Common-Controls\"\n            version=\"6.0.0.0\"\n            processorArchitecture=\"*\"\n            publicKeyToken=\"6595b64144ccf1df\"\n            language=\"*\"\n        />\n    </dependentAssembly>\n</dependency>\n</assembly>\n";

void initCommonControls(BOOL comctl5)
{
	WCHAR temppath[MAX_PATH + 1];
	WCHAR filename[MAX_PATH + 1];
	HANDLE file;
	DWORD nExpected, nGot;
	ACTCTX actctx;
	HANDLE ac;
	INITCOMMONCONTROLSEX icc;
	FARPROC f;
	// this is listed as WINAPI in both Microsoft's and MinGW's headers, but not on MSDN for some reason
	BOOL (*WINAPI ficc)(const LPINITCOMMONCONTROLSEX);

	if (!comctl5) {
		if (GetTempPathW(MAX_PATH + 1, temppath) == 0)
			die("getting temporary path for writing manifest file");
		if (GetTempFileNameW(temppath, L"manifest", 0, filename) == 0)
			die("getting temporary filename for writing manifest file");
		file = CreateFileW(filename, GENERIC_WRITE,
			0,			// don't share while writing
			NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
		if (file == NULL)
			die("creating manifest file");
		nExpected = (sizeof manifest / sizeof manifest[0]) - 1;		// - 1 to omit the terminating null character)
		if (WriteFile(file, manifest, nExpected, &nGot, NULL) == 0)
			die("writing manifest file");
		if (nGot != nExpected)
			die("short write to manifest file");
		if (CloseHandle(file) == 0)
			die("closing manifest file (this IS an error here because not doing so will prevent Windows from being able to use the manifest file in an activation context)");

		ZeroMemory(&actctx, sizeof (ACTCTX));
		actctx.cbSize = sizeof (ACTCTX);
		actctx.dwFlags = ACTCTX_FLAG_SET_PROCESS_DEFAULT;
		actctx.lpSource = filename;
		ac = CreateActCtx(&actctx);
		if (ac == INVALID_HANDLE_VALUE)
			die("creating activation context for synthesized manifest file");
		if (ActivateActCtx(ac, &comctlManifestCookie) == FALSE)
			die("activating activation context for synthesized manifest file");
	}

	ZeroMemory(&icc, sizeof (INITCOMMONCONTROLSEX));
	icc.dwSize = sizeof (INITCOMMONCONTROLSEX);
	icc.dwICC = wantedICCClasses;

	comctl32 = LoadLibraryW(L"comctl32.dll");
	if (comctl32 == NULL)
		die("loading comctl32.dll");
	f = GetProcAddress(comctl32, "InitCommonControlsEx");
	if (f == NULL)
		die("loading InitCommonControlsEx()");
	ficc = (BOOL (*WINAPI)(const LPINITCOMMONCONTROLSEX)) f;
	if ((*ficc)(&icc) == FALSE)
		die("initializing Common Controls (comctl32.dll)");
}


text:
#ifndef MAIN_H
#define MAIN_H

#include "point.h"

struct point *input_point(char label);
double input_double(char *prompt);

#endif /* MAIN_H */


text:
module.exports = {
  name: 'setting reactive param',
  init: function(){
    var router = basis.require('basis.router');
    var type = basis.require('basis.type');
    var catchWarnings = basis.require('./helpers/common.js').catchWarnings;
  },
  test: [
    {
      name: 'simple case',
      test: function(){
        var route = router.route('page(/:str)', {
          params: {
            str: type.string
          }
        });

        router.navigate('page');

        route.params.str.set('someother');

        assert.async(function(){
          assert(location.hash === '#page/someother');

          route.destroy();
        });
      }
    },
    {
      name: 'setting already modified route',
      test: function(){
        var route = router.route(':first(/:second)(/:third)', {
          params: {
            first: type.string,
            second: type.string,
            third: type.string
          }
        });

        router.navigate('foo/bar/baz');

        route.params.first.set('spam');

        assert.async(function(){
          assert(location.hash === '#spam/bar/baz');

          route.destroy();
        });
      }
    },
    {
      name: 'it should fire only one location change on multiple params update',
      test: function(){
        var route = router.route(':first(/:second)(/:third)', {
          params: {
            first: type.string,
            second: type.string,
            third: type.string
          }
        });

        router.navigate('foo/bar/baz');

        var counter = 0;
        var handler = function(first, second, third){
          counter++;
        };
        route.add(handler);

        assert.async(function(){
          assert(counter === 1);

          route.params.first.set('first');
          route.params.second.set('second');
          route.params.third.set('third');

          assert.async(function(){
            assert(location.hash === '#first/second/third');

            route.destroy();
          });
        });
      }
    },
    {
      name: 'transforms params passing previous value',
      test: function(){
        var route = router.route('page/:str', {
          params: {
            str: type.string
          }
        });

        router.navigate('page/some');

        catchWarnings(function(){
          route.params.str.set(true);
        });

        assert(route.params.str.value === 'some');
        assert(location.hash === '#page/some');

        route.destroy();
      }
    },
    {
      name: 'setting params when not matched - warning and ignore',
      test: function(){
        var route = router.route('page/:str', {
          params: {
            str: type.string
          }
        });

        router.navigate('something-different');

        assert(route.params.str.value === '');

        var warned = catchWarnings(function(){
          route.params.str.set('str');
        });

        assert.async(function(){
          assert(warned);
          assert(route.params.str.value === '');
          assert(location.hash === '#something-different');

          route.destroy();
        });
      }
    },
    {
      name: 'setting params on going route away',
      test: function(){
        var route = router.route('num/:num', {
          params: {
            num: type.number.nullable
          }
        });

        router.navigate('num/42');

        route.params.num.link(null, function(num){
          if (!num) {
            route.params.num.set(1);
          }
        });

        catchWarnings(function(){
          router.navigate('different-route/');
        });

        assert.async(function(){
          assert(location.hash === '#different-route/');
        });
      }
    }
  ]
};


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppBaseTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme" parent="AppBaseTheme">
    </style>

    <!--DailyHeadLineStyle-->
    <style name="HeadLineStyle">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_gravity">center_vertical</item>
        <item name="android:gravity">center_vertical</item>
        <item name="android:paddingLeft">20dp</item>
        <item name="android:textColor">@color/normalTextColor</item>
        <item name="android:textSize">12sp</item>
    </style>

    <!-- expandedTitleTextAppearance Title -->
    <style name="expandedTitle">
        <item name="android:textColor">@color/black</item>
        <item name="android:textSize">15sp</item>
    </style>

    <!--TabLayout-->
    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textSize">12sp</item>
    </style>

    <!-- toolbar标题样式 -->
    <style name="ToolbarTitle" parent="@style/TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">4sp</item>
        <item name="android:textColor">#ffffffff</item>
    </style>

    <!--侧滑菜单最下面两个按钮-->
    <style name="DrawlayoutTextview">
        <item name="android:layout_width">0dp</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:layout_weight">1</item>
        <item name="android:gravity">center</item>
        <item name="android:textColor">@color/BlackWhiteColor</item>
    </style>

</resources>


text:
[![Build Status](https://travis-ci.org/abbeycode/UnrarKit.svg?branch=master)](https://travis-ci.org/abbeycode/UnrarKit)
[![Documentation Coverage](https://img.shields.io/cocoapods/metrics/doc-percent/UnrarKit.svg)](http://cocoadocs.org/docsets/UnrarKit)

# About

UnrarKit is here to enable Mac and iOS apps to easily work with RAR files for read-only operations. It is currently based on version 5.2.1 of the [UnRAR library](http://www.rarlab.com/rar/unrarsrc-5.2.1.tar.gz).

There is a main project, with unit tests, and a basic iOS example project, which demonstrates how to use the library. To see all of these, open the main workspace file.

I'm always open to improvements, so please submit your pull requests, or [create issues](https://github.com/abbeycode/UnrarKit/issues) for someone else to implement.

# Installation

UnrarKit supports both [CocoaPods](https://cocoapods.org/) and [Carthage](https://github.com/Carthage/Carthage). CocoaPods does not support dynamic framework targets (as of v0.39.0), so in that case, please use Carthage.

Cartfile:

    github "abbeycode/UnrarKit"

Podfile:

    pod "UnrarKit"

# Example Usage

```Objective-C
NSError *archiveError = nil;
URKArchive *archive = [[URKArchive alloc] initWithPath:@"An Archive.rar" error:&archiveError];
NSError *error = nil;
```

## Listing the file names in an archive
```Objective-C
NSArray<String*> *filesInArchive = [archive listFilenames:&error];
for (NSString *name in filesInArchive) {
    NSLog(@"Archived file: %@", name);
}
```

## Listing the file details in an archive
```Objective-C
NSArray<URKFileInfo*> *fileInfosInArchive = [archive listFileInfo:&error];
for (URKFileInfo *info in fileInfosInArchive) {
    NSLog(@"Archive name: %@ | File name: %@ | Size: %lld", info.archiveName, info.filename, info.uncompressedSize);
}
```

## Working with passwords
```Objective-C
NSArray<URKFileInfo*> *fileInfosInArchive = [archive listFileInfo:&error];
if (archive.isPasswordProtected) {
    NSString *givenPassword = // prompt user
    archive.password = givenPassword
}

// You can now extract the files
```

## Extracting files to a directory
```Objective-C
BOOL extractFilesSuccessful = [archive extractFilesTo:@"some/directory"
                                            overWrite:NO
                                             progress:
    ^(URKFileInfo *currentFile, CGFloat percentArchiveDecompressed) {
        NSLog(@"Extracting %@: %f%% complete", currentFile.filename, percentArchiveDecompressed);
    }
                                                error:&error];
```

## Extracting a file into memory
```Objective-C
NSData *extractedData = [archive extractDataFromFile:@"a file in the archive.jpg"
                                            progress:^(CGFloat percentDecompressed) {
                                                         NSLog(@"Extracting, %f%% complete", percentDecompressed);
                                            }
                                               error:&error];
```

## Streaming a file

For large files, you may not want the whole contents in memory at once. You can handle it one "chunk" at a time, like so:

```Objective-C
BOOL success = [archive extractBufferedDataFromFile:@"a file in the archive.jpg"
                                              error:&error
                                             action:
                ^(NSData *dataChunk, CGFloat percentDecompressed) {
                    NSLog(@"Decompressed: %f%%", percentDecompressed);
                    // Do something with the NSData chunk
                }];
```

# Progress Reporting

The following methods support `NSProgress` and `NSProgressReporting`:

* `extractFilesTo:overwrite:error:`
* `extractData:error:`
* `extractDataFromFile:error:`
* `performOnFilesInArchive:error:`
* `performOnDataInArchive:error:`
* `extractBufferedDataFromFile:error:action:`

## Using implicit `NSProgress` hierarchy

You can create your own instance of `NSProgress` and observe its `fractionCompleted` property with KVO to monitor progress like so:

```Objective-C
    static void *ExtractDataContext = &ExtractDataContext;

    URKArchive *archive = [[URKArchive alloc] initWithURL:aFileURL error:nil];

    NSProgress *extractDataProgress = [NSProgress progressWithTotalUnitCount:1];
    [extractDataProgress becomeCurrentWithPendingUnitCount:1];

    NSString *observedSelector = NSStringFromSelector(@selector(fractionCompleted));

    [extractDataProgress addObserver:self
                          forKeyPath:observedSelector
                             options:NSKeyValueObservingOptionInitial
                             context:ExtractDataContext];

    NSError *extractError = nil;
    NSData *data = [archive extractDataFromFile:firstFile error:&extractError];

    [extractDataProgress resignCurrent];
    [extractDataProgress removeObserver:self forKeyPath:observedSelector];
```

## Using your own explicit `NSProgress` instance

If you don't have a hierarchy of `NSProgress` instances, or if you want to observe more details during progress updates in `extractFilesTo:overwrite:error:`, you can create your own instance of `NSProgress` and set the `URKArchive` instance's `progress` property, like so:

```Objective-C
    static void *ExtractFilesContext = &ExtractFilesContext;

    URKArchive *archive = [[URKArchive alloc] initWithURL:aFileURL error:nil];

    NSProgress *extractFilesProgress = [NSProgress progressWithTotalUnitCount:1];
    archive.progress = extractFilesProgress;

    NSString *observedSelector = NSStringFromSelector(@selector(localizedDescription));

    [self.descriptionsReported removeAllObjects];
    [extractFilesProgress addObserver:self
                           forKeyPath:observedSelector
                              options:NSKeyValueObservingOptionInitial
                              context:ExtractFilesContext];

    NSError *extractError = nil;
    BOOL success = [archive extractFilesTo:extractURL.path
                                 overwrite:NO
                                     error:&extractError];

    [extractFilesProgress removeObserver:self forKeyPath:observedSelector];
```

## Cancellation with `NSProgress`

Using either method above, you can call `[progress cancel]` to stop the operation in progress. It will cause the operation to fail, returning `nil` or `NO` (depending on the return type, and give an error with error code `URKErrorCodeUserCancelled`.

# Notes

To open in Xcode, use the [UnrarKit.xcworkspace](UnrarKit.xcworkspace) file, which includes the other projects.

# Documentation

Full documentation for the project is available on [CocoaDocs](http://cocoadocs.org/docsets/UnrarKit).

# Logging

For all OS versions from 2016 onward (macOS 10.12, iOS 10, tvOS 10, watchOS 3), UnzipKit uses the new [Unified Logging framework](https://developer.apple.com/documentation/os/logging) for logging and Activity Tracing. You can view messages at the Info or Debug level to view more details of how UnzipKit is working, and use Activity Tracing to help pinpoint the code path that's causing a particular error.

As a fallback, regular `NSLog` is used on older OSes, with all messages logged at the same level.

When debugging your own code, if you'd like to decrease the verbosity of the UnrarKit framework, you can run the following command:

    sudo log config --mode "level:default" --subsystem com.abbey-code.UnrarKit

The available levels, in order of increasing verbosity, are `default`, `info`, `debug`, with `debug` being the default.

## Logging guidelines

These are the general rules governing the particulars of how activities and log messages are classified and written. They were written after the initial round of log messages were, so there may be some inconsistencies (such as an incorrect log level). If you think you spot one, open an issue or a pull request!

### Logging

Log messages should follow these conventions.

1. Log messages don't have final punctuation (like these list items)
1. Messages that note a C function is about to be called, rather than a higher level UnrarKit or Cocoa method, end with "...", since it's not expected for them to log any details of their own

#### Default log level

There should be no messages at this level, so that it's possible for a consumer of the API to turn off _all_ diagnostic logging from it, as detailed above. It's only possible to `log config --mode "level:off"` for a process, not a subsystem.

#### Info log level

Info level log statements serve the following specific purposes.

1. Major action is taken, such as initializing an archive object, or deleting a file from an archive
1. Noting each public method has been called, and the arguments with which it was called
1. Signposting the major actions a public method takes
1. Notifying that an atypical condition has occurred (such as an action causing an early stop in a block or a NO return value)
1. Noting that a loop is about to occur, which will contain debug-level messages for each iteration

#### Debug log level

Most messages fall into this category, making it extremely verbose. All non-error messages that don't fall into either of the other two categories should be debug-level, with some examples of specific cases below.

1. Any log message in a private method
1. Noting variable and argument values in a method
1. Indicating that everything is working as expected
1. Indicating what happens during each iteration of a loop (or documenting that an iteration has happened at all)

#### Error log level

1. Every `NSError` generated should get logged with the same detail message as the `NSError` object itself
1. `NSError` log messages should contain the string of the error code's enumeration value (e.g. `"URKErrorCodeArchiveNotFound"`) when it is known at design time
1. Errors should reported everywhere they're encountered, making it easier to trace their flows through the call stack
1. Early exits that result in desired work not being performed

#### Fault log level

So far, there is only one case that gets logged at Fault-level: when a Cocoa framework methods that come back with an error

### Activities
1. Public methods have an English activity names with spaces, and are title-case
1. Private methods each have an activity with the method's name
1. Sub-activities are created for significant scope changes, such as when inside an action block, but not if no significant work is done before entering that action
1. Top-level activities within a method have variables named `activity`, with more specific labels given to sub-activities
1. If a method is strictly an overload that calls out to another overload without doing anything else, it should not define its own activity

# Pushing a new CocoaPods version

New tagged builds (in any branch) get pushed to CocoaPods automatically, provided they meet the following criteria:

1. All builds and tests succeed
2. The library builds successfully for CocoaPods and for Carthage
3. The build is tagged with something resembling a version number (`#.#.#(-beta#)`, e.g. **2.9** or **2.9-beta5**)
4. `pod spec lint` passes, making sure the CocoaPod is 100% valid

Before pushing a build, you must:

1. Add the release notes to the [CHANGELOG.md](CHANGELOG.md), and commit
2. Run [set-version](Scripts/set-version.sh), like so:

    `./Scripts/set-version.sh <version number>`

    This does the following:

    1. Updates the [UnrarKit-Info.plist](Resources/UnrarKit-Info.plist) file to indicate the new version number, and commits it

    2. Makes an annotated tag whose message contains the release notes entered in Step 1

Once that's done, you can call `git push --follow-tags` [1](#f1), and let [Travis CI](https://travis-ci.org/abbeycode/UnrarKit/builds) take care of the rest.

# Credits

* Dov Frankel (dov@abbey-code.com)
* Rogerio Pereira Araujo (rogerio.araujo@gmail.com)
* Vicent Scott (vkan388@gmail.com)

1: Or set `followTags = true` in your git config to always get this behavior:

    git config --global push.followTags true

[↩](#a1)


text:
package vg.civcraft.mc.prisonpearl.command.commands;

import java.util.LinkedList;
import java.util.List;

import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;

import vg.civcraft.mc.civmodcore.command.PlayerCommand;
import vg.civcraft.mc.prisonpearl.PrisonPearl;
import vg.civcraft.mc.prisonpearl.PrisonPearlPlugin;
import vg.civcraft.mc.prisonpearl.Summon;
import vg.civcraft.mc.prisonpearl.managers.MercuryManager;
import vg.civcraft.mc.prisonpearl.managers.PrisonPearlManager;
import vg.civcraft.mc.prisonpearl.managers.SummonManager;

public class ToggleDamage extends PlayerCommand{
	public ToggleDamage(String name) {
		super(name);
		setIdentifier("pptoggledamage");
		setDescription("Toggles whether the player imprisoned in the pearl you are holding is allowed to deal damage to other players");
		setUsage("/pptd [true|false]");
		setArguments(0, 1);
	}

	public boolean execute(CommandSender sender, String[] args) {
		if (!(sender instanceof Player)) {
			sender.sendMessage(ChatColor.RED
					+ "This command can only be used as a player");
			return true;
		}
		Player p = (Player) sender;
		PrisonPearlManager manager = PrisonPearlPlugin.getPrisonPearlManager();
		SummonManager summonManager = PrisonPearlPlugin.getSummonManager();
		ItemStack is = p.getInventory().getItemInMainHand();
		PrisonPearl pearl = null;
		if (is != null) {
			pearl = manager.getPearlByItemStack(is);
		}
		if (pearl == null) {
			p.sendMessage(ChatColor.RED
					+ "You are not holding a valid ender pearl");
			return true;
		}
		Player imprisoned = pearl.getImprisonedPlayer();
		if (imprisoned == null) {
			p.sendMessage(ChatColor.RED
					+ "The player held in this pearl is not online");
			return true;
		}
		Summon summon = summonManager.getSummon(pearl);
		if (summon == null) {
			p.sendMessage(ChatColor.RED + "This player is not summoned");
			return true;
		}
		if (args.length > 0) {
			if (args[0].equalsIgnoreCase("true")
					|| args[0].equalsIgnoreCase("false")) {
				boolean toggle = Boolean.getBoolean(args[0]);
				if (summon.getCanDamage() == toggle) {
					p.sendMessage(ChatColor.RED
							+ "Dealing damage is already set to "
							+ String.valueOf(toggle) + " for "
							+ pearl.getImprisonedName());
					return true;
				}
				summon.setCanDamage(toggle);
				p.sendMessage(ChatColor.GREEN + "Damaging players was set to "
						+ String.valueOf(toggle) + " for "
						+ pearl.getImprisonedName());
				return true;
			} else {
				p.sendMessage(ChatColor.RED
						+ "You may only specify true or false as arguments for this commands");
				return true;
			}
		}
		boolean currentState = summon.getCanDamage();
		summon.setCanDamage(!currentState);
		MercuryManager.updateSummonToggleDamage(summon);
		p.sendMessage(ChatColor.GREEN + "Damaging players was set to "
				+ String.valueOf(!currentState) + " for "
				+ pearl.getImprisonedName());
		return true;
	}

	public List<String> tabComplete(CommandSender sender, String[] args) {
		return new LinkedList<String>(); // empty list
	}
}


text:
/* ###
 * IP: GHIDRA
 * REVIEWED: YES
 *
 * 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 help.validator;

import java.io.IOException;
import java.nio.file.Path;
import java.util.LinkedHashMap;

public abstract class TagProcessor {

	enum TagProcessingState {
		LOOKING_FOR_NEXT_ATTR, READING_ATTR, LOOKING_FOR_VALUE, READING_VALUE;
	}

	TagProcessor() {
	}

	abstract void processTag(String tagType, LinkedHashMap<String, String> tagAttributes,
			Path file, int lineNum) throws IOException;

	public void startOfFile(Path htmlFile) {
		// stub
	}

	public void endOfFile() {
		// stub
	}

	public String processText(String text) {
		return text;
	}

	public boolean isTagSupported(String tagType) {
		return true;
	}

	public int getErrorCount() {
		return 0;
	}
}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>colour.colorimetry.illuminants — Colour 0.3.6 documentation</title>

    <link rel="stylesheet" href="../../../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/bootswatch-3.1.0/colour/bootstrap.min.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/bootstrap-sphinx.css" type="text/css" />
    <link rel="stylesheet" href="../../../_static/styles.css" type="text/css" />

    <link rel="top" title="Colour 0.3.6 documentation" href="../../../index.html" />
    <link rel="up" title="colour.colorimetry" href="../colorimetry.html" />
<meta charset='utf-8'>
<meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'>
<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1'>
<meta name="apple-mobile-web-app-capable" content="yes">

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".nav-collapse">

        </button>

          Colour 0.3

colour-science.org

                   Documentation

                           API Reference

                           IPython Notebooks

                           Features

                           Contributing

<form class="navbar-form navbar-right" action="../../../search.html" method="get">

  <input type="text" name="q" class="form-control" placeholder="Search" />

  <input type="hidden" name="check_keywords" value="yes" />
  <input type="hidden" name="area" value="default" />
</form>

Source code for colour.colorimetry.illuminants

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Illuminants
===========

Defines *CIE* illuminants computation related objects.

See Also
--------
`Illuminants IPython Notebook
<http://nbviewer.ipython.org/github/colour-science/colour-ipython/blob/master/notebooks/colorimetry/illuminants.ipynb>`_  # noqa
colour.colorimetry.dataset.illuminants.d_illuminants_s_spds,
colour.colorimetry.spectrum.SpectralPowerDistribution
"""

from __future__ import division, unicode_literals

from colour.colorimetry import (
    D_ILLUMINANTS_S_SPDS,
    SpectralPowerDistribution)

__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013 - 2015 - Colour Developers'
__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'

__all__ = ['D_illuminant_relative_spd']

[docs]def D_illuminant_relative_spd(xy):
    """
    Returns the relative spectral power distribution of given
    *CIE Standard Illuminant D Series* using given *xy* chromaticity
    coordinates.

    References
    ----------
    .. [1]  Wyszecki, G., & Stiles, W. S. (2000). CIE Method of Calculating
            D-Illuminants. In Color Science: Concepts and Methods,
            Quantitative Data and Formulae (pp. 145–146). Wiley.
            ISBN:978-0471399186
    .. [2]  Lindbloom, B. (2007). Spectral Power Distribution of a
            CIE D-Illuminant. Retrieved April 05, 2014, from
            http://www.brucelindbloom.com/Eqn_DIlluminant.html

    Parameters
    ----------
    xy : array_like
        *xy* chromaticity coordinates.

    Returns
    -------
    SpectralPowerDistribution
        *CIE Standard Illuminant D Series* relative spectral power
        distribution.

    Examples
    --------
    >>> import numpy as np
    >>> xy = np.array([0.34567, 0.35850])
    >>> D_illuminant_relative_spd(xy)  # doctest: +ELLIPSIS
    <colour.colorimetry.spectrum.SpectralPowerDistribution object at 0x...>
    """

    M = 0.0241 + 0.2562 * xy[0] - 0.7341 * xy[1]
    M1 = (-1.3515 - 1.7703 * xy[0] + 5.9114 * xy[1]) / M
    M2 = (0.0300 - 31.4424 * xy[0] + 30.0717 * xy[1]) / M

    distribution = {}
    for i in D_ILLUMINANTS_S_SPDS.get('S0').shape:
        S0 = D_ILLUMINANTS_S_SPDS.get('S0').get(i)
        S1 = D_ILLUMINANTS_S_SPDS.get('S1').get(i)
        S2 = D_ILLUMINANTS_S_SPDS.get('S2').get(i)
        distribution[i] = S0 + M1 * S1 + M2 * S2

    return SpectralPowerDistribution('CIE Standard Illuminant D Series',
                                     distribution)

      Back to top

        © Copyright 2013 - 2015, Colour Developers.

      Created using Sphinx 1.2.2.


text:
using UnityEngine;
using System.Collections;

public class FlyingController : MonoBehaviour {
	protected Animator anim;

	public FlyerController FlyerControllerReference;

	// Use this for initialization
	void Start () {
		anim = GetComponent<Animator>();
	}

	// Update is called once per frame
	void Update () {
		if (Input.GetKeyDown("space") || PostureController.IsStartFlying ) {
			Debug.Log("Set start flying");
			anim.SetBool("StartFlying", true);
//			this.transform.parent.GetComponent<ControllerServer>().StartServer();
		}
	}

	//Mecanim AnimationEvent called when ReadyForFly animation done.
	void OnReadyForFlying(int value){
		Debug.Log("Triggered On Ready for Flying animation");
		if (FlyerControllerReference) {
			Debug.Log("Set is flying to true");
			FlyerControllerReference.IsFlying = true;
		}
	}
}


text:
package za.org.grassroot.webapp.model.rest.wrappers;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Getter;
import org.springframework.http.HttpStatus;
import za.org.grassroot.core.domain.Permission;
import za.org.grassroot.webapp.enums.RestStatus;

/**
 * Created by paballo on 2016/03/07.
 */
@Getter
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PermissionLackingWrapper implements ResponseWrapper {

    protected final String status;
    protected final int code;
    protected final String message;

    public PermissionLackingWrapper(HttpStatus code, Permission permission, RestStatus status) {
        this.code = code.value();
        this.message = permission.getName();
        this.status = String.valueOf(status);
    }

    @Override
    public String toString() {
        return "PermissionLacking{" +
                "status='" + status + '\'' +
                ", code=" + code +
                ", message='" + message + '\'' +
                '}';
    }
}