text:
require 'command_status_apparatus/version'
require 'rails'
require 'active_record'
require 'ruby-progressbar'

module CommandStatusApparatus
  # Your code goes here...
end
require 'command_status_apparatus/command_status_interface'
require 'command_status_apparatus/command_status'
require 'command_status_apparatus/logged_runner'


text:
from xml.dom import minidom
from antlr3 import *;
from antlr3.tree import *;
import MultipathLexer
import MultipathParser
import sys
import re
import unittest
import math

class MultipathDevice:
    def __init__(self, comment, alias, wwid, additional = ''):
        self.comment = comment
        self.alias = alias
        self.wwid = wwid
        self.additional = additional

    @classmethod
    def fromASTToken(cls, elem):
        #
        additional = ''
        for e in elem.children:
            if e.toString() == '{':
                continue
            elif e.toString() == 'wwid':
                wwid = e.children[0].text
            elif e.toString() == 'alias':
                alias = e.children[0].text
            elif e.toString() == '}':
                continue
            else:
                additional += "\n"
                additional += e.toString()
                additional += " " + e.children[0].text if e.children else None
        return cls('', alias, wwid, additional)

    def getWWID(self):
    # generate WWID in Linux multipath.conf format
        return self.wwid

    def getAlias(self):
        return self.alias

    def getComment(self):
        return self.comment

    def __str__(self):
        return """multipath {
%s
wwid %s
alias %s%s
}
""" % (self.comment, self.wwid, self.alias, self.additional if self.additional else '')

    def __lt__(self, other):
        # local disks before shared ones
        if self.alias.startswith('local') and other.alias.startswith('asm'):
            return True
        if other.alias.startswith('local') and self.alias.startswith('asm'):
            return False
        return self.getAlias() < other.getAlias()
        #return self.alias < other.alias

class MultipathConf:
    def __init__(self, filename):
        self.lines = [line.rstrip('\n') for line in open(filename)]
        #
        inputStream = ANTLRFileStream(filename)
        lexer = MultipathLexer.MultipathLexer(inputStream);
        tokens = CommonTokenStream(lexer);
        parser = MultipathParser.MultipathParser(tokens);
        r = parser.multipath();
        self.tree = r.tree; # get tree from parser
        #
        self.mpathsSection = [ a for a in self.tree.children if a.token.text == 'multipaths' ] # filter tree children, find those named 'multipaths' (assuming there is only one)
        #
        self.mpathsSectionStart = tokens.get(self.mpathsSection[0].startIndex)
        self.mpathsSectionStop  = tokens.get(self.mpathsSection[0].stopIndex)
        #
        self.mpaths = []
        self.mpathsHashByWWID = {}
        self.mpathsHashByAlias = {}
        for mpath in self.mpathsSection[0].children:
            if mpath.toString() != 'multipath': # leading '{' and trailing '}' are also children of multipaths element
                continue
            device = MultipathDevice.fromASTToken(mpath)
            self.mpaths.append(device)
            self.mpathsHashByWWID[device.getWWID()] = device
            self.mpathsHashByAlias[device.getAlias()] = device
        self.mpaths.sort()

    def multipaths(self):
        return self.mpaths

    def getMultipathByWWID(self, wwid):
        return self.mpathsHashByWWID[wwid]

    def getMultipathByAlias(self, alias):
        return self.mpathsHashByAlias[alias]

    def getWWIDs(self):
        return set(map(lambda m: m.getWWID(), self.mpaths))

    def addMultipath(self, multipath):
        self.mpaths.append(multipath)
        self.mpathsHashByWWID[multipath.getWWID()] = multipath
        self.mpathsHashByAlias[multipath.getAlias()] = multipath

    def serialize(self):
        # Copy heading sections line by line, until multipaths section start
        for line in self.lines[0: self.mpathsSectionStart.line -1 ] : # antlr3 indexes lines from 1
            print line
        # Serialize current lultipaths list
        # self.mpaths.sort()
        print 'multipaths {'
        for multipath in self.mpaths:
            print(multipath)
        print '}'
        # Copy trailing line one by one - if any
        for line in self.lines[self.mpathsSectionStop.line:] :
            print line

class XmlDevice:
    def __init__(self, elem):
        #
        self.path = elem.getElementsByTagName('name')[0].getAttribute('path').strip()
        #
        self.fcLunId = elem.getElementsByTagName('fc_lun_id')[0].firstChild.nodeValue
        #
        # 50060e8007293a35 ( 5 - NNA format 5, 0060e8 - 24 bit vendor OUI, 007293a35 - 36 bit vendor sequence or serial number
        array_port_wwn = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('array_port_wwn')[0].firstChild.nodeValue
        self.serialNrHex = array_port_wwn[-9:]
        # replace last byte with zero
        self.serialNrHex = self.serialNrHex[:-2] + '00'
        #
        self.serialNrDec = elem.port  = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('serial_nr')[0].firstChild.nodeValue
        #
        self.vendorOui = array_port_wwn[1:7]
        #
        self.alpa  = elem.port  = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('alpa')[0].firstChild.nodeValue
        #
        self.lunId = elem.getElementsByTagName('lun_id')[0].firstChild.nodeValue # LUN id decimal format
        self.lunId = int(self.lunId)
        #
        self.port  = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('array_port_name')[0].firstChild.nodeValue
        #
        self.cu    = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('ldev')[0].getElementsByTagName('cu')[0].firstChild.nodeValue # decimal format
        self.cu    = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('ldev')[0].getElementsByTagName('cu')[0].firstChild.nodeValue # decimal format
        #
        self.size  = elem.getElementsByTagName('array_storage')[0].getElementsByTagName('ldev')[0].getElementsByTagName('size')[0].firstChild.nodeValue
        self.size  = int(self.size)
        #
        self.comment = "# Path: {0} \t FcLunId: {1}\t OUI: {2}\t LUN: {3:02d}\t Port: {4}\t SN: {5}/{6}\t Size: {7: 8d}"\
            .format(self.path, self.fcLunId ,self.vendorOui, self.lunId, self.port, self.serialNrHex, self.serialNrDec, self.size)

    def getWWID(self):
    # generate WWID in Linux multipath.conf format
        return '3' + '6' + self.vendorOui + self.serialNrHex + self.fcLunId;

    def getComment(self):
        return self.comment

    def __str__(self):
        return self.getComment()

    def __lt__(self, other):
        # 1st compare serial numbers
        if self.serialNrHex != other.serialNrHex:
            return self.serialNrHex < other.serialNrHex
        # 2nd compare LUN IDs
        if self.lunId != other.lunId:
            return self.lunId < other.lunId
        # 3rd should be reaches
        if self.getWWID() != other.getWWID():
            return self.getWWID() < other.getWWID()
        # 4th sort lexically by comment (path)
        return self.getComment() < other.getComment()

class XPinfo:
    def __init__(self, filename):
        xmldoc = minidom.parse(filename)
        self.itemlist = xmldoc.getElementsByTagName('device_file')
        # This list contains duplicates, one per path
        self.L = []
        for s in self.itemlist:
            self.L.append(XmlDevice(s))
        self.L.sort()
        # Put all wwids into hash map, if wwid is already present just concat comments
        self.M = {}
        for device in self.L:
            if device.getWWID() in self.M:
                d = self.M[device.getWWID()]
                d.comment += "\n" + device.comment
            else:
                self.M[device.getWWID()] = device
        # Final sorted list
        self.N = []
        for wwid in list(self.M.keys()):
            self.N.append(self.M[wwid])
        self.N.sort()

    def devices(self):
        return self.N

    def getDeviceByWWID(self, wwid):
        return self.M[wwid]

    def getWWIDs(self):
        return map(lambda m: m.getWWID(), self.N)

def nextAliasNumber(AliasList, n):
    Aliases = filter(lambda a: not re.match("^local", a) , AliasList)
    LastAlias = max(Aliases)
    aliasRe = re.compile(r'^([a-zA-Z]+)([0-9]+)')
    reSult =aliasRe.search(LastAlias);
    aliasPrefix, aliasSuffix = reSult.groups();
    # aliasNumner = 32, resp. 91, resp 450
    aliasNumber = int(aliasSuffix)
    # scale = 1, resp 1, resp 2
    scale = int(math.floor(math.log10(aliasNumber)))
    # scalePow = 10, resp 10, resp 100
    scalePow = int(math.pow(10, scale))
    # leadingDigit 3, resp 9, resp 4
    leadingDigit = int(math.floor(aliasNumber / scalePow))
    if leadingDigit == 9:
        leadingDigit = 1
        scale += 1
        scalePow = int(math.pow(10, scale))
        leadingDigit = 1
    else:
        leadingDigit += 1

    R = []
    zfilllen = max([scale+2, len(aliasSuffix)])
    for i in range(0,n):
        # alias = 40, resp 100, resp 500
        alias = aliasPrefix + str(scalePow * leadingDigit + i).zfill(zfilllen)
        R.append(alias)
    return R

if __name__ == "__main__" and len(sys.argv) >= 3:
    multipathConf = MultipathConf(str(sys.argv[1]))
    xpinfo = XPinfo(str(sys.argv[2]))
    # Get WWIDs from /etc/multipath.conf
    MPathWWIDs = multipathConf.getWWIDs()
    # Get WWIDs from xpinfo output but not in /etc/multipath.conf
    XPinfoWWIDs = xpinfo.getWWIDs()
    #
    MissingWWIDs = set(filter(lambda m: m not in MPathWWIDs, XPinfoWWIDs))
    #
    print >> sys.stderr, "mpath: " + str(len(MPathWWIDs))
    for W in MPathWWIDs:
        print >> sys.stderr, W

    print >> sys.stderr, "xpinfo: "  + str(len(XPinfoWWIDs))
    for W in XPinfoWWIDs:
        print >> sys.stderr, W

    print >> sys.stderr, "missing: " + str(len(MissingWWIDs))
    # generate alias for each missing wwid
    newAliases = nextAliasNumber(map(lambda m: m.getAlias(), multipathConf.multipaths()), len(MissingWWIDs))
    # iterate over all xpinfo wwids
    for W in XPinfoWWIDs:
        # if it is present just modify its comment
        if W in MPathWWIDs:
            multipath = multipathConf.getMultipathByWWID(W)
            xmldevive = xpinfo.getDeviceByWWID(W)
            multipath.comment = xmldevive.getComment()
        # else add a new alias
        else:
            alias = newAliases.pop(0)
            comment = xpinfo.getDeviceByWWID(W).getComment()
            print >> sys.stderr, "Adding: {0} \t {1}".format(alias, W)
            multipathConf.addMultipath(MultipathDevice(comment, alias, W))
    # serialiaze a new config file
    multipathConf.serialize()

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.chrome.testshell;

import android.content.Context;
import android.text.TextUtils;

import org.chromium.chrome.browser.TabBase;
import org.chromium.chrome.browser.infobar.AutoLoginProcessor;
import org.chromium.content.browser.ContentView;
import org.chromium.content.browser.LoadUrlParams;
import org.chromium.content.common.CleanupReference;
import org.chromium.ui.WindowAndroid;

/**
 * TestShell's implementation of a tab. This mirrors how Chrome for Android subclasses
 * and extends {@link TabBase}.
 */
public class TestShellTab extends TabBase {
    private int mNativeTestShellTab;

    private CleanupReference mCleanupReference;

    // Tab state
    private boolean mIsLoading;

    /**
     * @param context  The Context the view is running in.
     * @param url      The URL to start this tab with.
     * @param window   The WindowAndroid should represent this tab.
     */
    public TestShellTab(Context context, String url, WindowAndroid window) {
        super(false, context, window);
        initialize();
        initContentView();
        loadUrlWithSanitization(url);
    }

    @Override
    public void initialize() {
        super.initialize();

        mNativeTestShellTab = nativeInit();
        mCleanupReference = new CleanupReference(this, new DestroyRunnable(mNativeTestShellTab));
    }

    @Override
    public void destroy() {
        super.destroy();

        if (mNativeTestShellTab != 0) {
            mCleanupReference.cleanupNow();
            mNativeTestShellTab = 0;
        }
    }

    /**
     * @return Whether or not the tab is currently loading.
     */
    public boolean isLoading() {
        return mIsLoading;
    }

    /**
     * Navigates this Tab's {@link ContentView} to a sanitized version of {@code url}.
     * @param url The potentially unsanitized URL to navigate to.
     * @param postData Optional data to be sent via POST.
     */
    public void loadUrlWithSanitization(String url, byte[] postData) {
        if (url == null) return;

        // Sanitize the URL.
        url = nativeFixupUrl(mNativeTestShellTab, url);

        // Invalid URLs will just return empty.
        if (TextUtils.isEmpty(url)) return;

        ContentView contentView = getContentView();
        if (TextUtils.equals(url, contentView.getUrl())) {
            contentView.getContentViewCore().reload(true);
        } else {
            if (postData == null) {
                contentView.loadUrl(new LoadUrlParams(url));
            } else {
                contentView.loadUrl(LoadUrlParams.createLoadHttpPostParams(url, postData));
            }
        }
    }

    /**
     * Navigates this Tab's {@link ContentView} to a sanitized version of {@code url}.
     * @param url The potentially unsanitized URL to navigate to.
     */
    public void loadUrlWithSanitization(String url) {
        loadUrlWithSanitization(url, null);
    }

    @Override
    protected TabBaseChromeWebContentsDelegateAndroid createWebContentsDelegate() {
        return new TestShellTabBaseChromeWebContentsDelegateAndroid();
    }

    private static final class DestroyRunnable implements Runnable {
        private final int mNativeTestShellTab;
        private DestroyRunnable(int nativeTestShellTab) {
            mNativeTestShellTab = nativeTestShellTab;
        }
        @Override
        public void run() {
            nativeDestroy(mNativeTestShellTab);
        }
    }

    @Override
    protected AutoLoginProcessor createAutoLoginProcessor() {
       return new AutoLoginProcessor() {
           @Override
           public void processAutoLoginResult(String accountName,
                   String authToken, boolean success, String result) {
               getInfoBarContainer().processAutoLogin(accountName, authToken,
                       success, result);
           }
       };
    }

    private class TestShellTabBaseChromeWebContentsDelegateAndroid
            extends TabBaseChromeWebContentsDelegateAndroid {
        @Override
        public void onLoadStarted() {
            mIsLoading = true;
        }

        @Override
        public void onLoadStopped() {
            mIsLoading = false;
        }
    }

    private native int nativeInit();
    private static native void nativeDestroy(int nativeTestShellTab);
    private native String nativeFixupUrl(int nativeTestShellTab, String url);
}


text:
__author__ = 'Junki Ishida'

from .exceptions import FormatError
from .declarations import NotExist, Entity
from ._compat import iteritems, OrderedDict

try:
    from lxml.etree import QName
except ImportError:
    from xml.etree.ElementTree import QName

def haskey(data, key, isdict):
    if isdict:
        return key in data
    return hasattr(data, key)

def getvalue(data, key, isdict, default=None):
    if isdict:
        return data.get(key, default)
    return getattr(data, key, default)

def _to_dict(model_class, data_type, data, ordered):
    isdict = isinstance(data, dict)
    result = OrderedDict() if ordered else {}
    for k, f in iteritems(model_class._fields):
        if not haskey(data, k, isdict):
            if not f._required:
                continue
            raise FormatError('"{0}" is not found.'.format(k))
        src = getvalue(data, k, isdict)
        if not f._required and src is NotExist:
            continue
        if f._nullable and src is None:
            value = None
        else:
            if f._islist:
                value = []
                for v in src:
                    item = _to_dict(f.model_class, data_type, v, ordered) \
                        if f._islistdelegate else f._dump(v, data_type)
                    value.append(item)
            else:
                value = _to_dict(f.model_class, data_type, src, ordered) \
                    if f._isdelegate else f._dump(src, data_type)
        result[f.get_key(k)] = value
    return result

def _parse_dict(model_class, data_type, data, forcekey):
    entity = Entity()
    for k, f in model_class._fields.items():
        key = f.get_key(k)
        if not key in data:
            if not f._required:
                if forcekey:
                    entity[k] = NotExist
                continue
            raise FormatError()
        src = data[key]
        if f._nullable and src is None:
            value = None
        else:
            if f._islist:
                value = []
                if src is not None:
                    for v in src:
                        item = _parse_dict(f.model_class, data_type, v, forcekey) \
                            if f._islistdelegate else f._parse(v, data_type)
                        value.append(item)
            else:
                value = _parse_dict(f.model_class, data_type, src, forcekey) \
                    if f._isdelegate else f._parse(src, data_type)
        entity[k] = value
    return entity


text:
template< class T >
class stack_lockfree_split_reference_impl {
public:
    using _t_size = size_t;
    using _t_val = T;
    class Node;
    class NodeExternal {
    public:
	int _count_external;
	Node * _node;
	NodeExternal() : _node( nullptr ), _count_external(0) {}
    };
    class Node {
    public:
	std::atomic<int> _count_internal;
	T _val;
	NodeExternal * _next;
	Node( T val ) : _val( val ), _next( nullptr ), _count_internal(0) {}
    };
    stack_lockfree_split_reference_impl() : _head( nullptr ) {}
    size_t size() const; //not guaranteed to be consistent when threads are accessing stack
    bool put( T const & val ){ return push( val ); }
    bool get( T & val ){ return pop( val ); }
private:
    bool push( T const & val );
    bool pop( T & val );

    bool AcquireNode( NodeExternal * & );
    std::atomic< NodeExternal * > _head;
};

#include "stack_lockfree_split_reference.tpp"

template< class T >
using stack_lockfree_split_reference = IPool< T, stack_lockfree_split_reference_impl,
					      trait_pool_size::unbounded,
					      trait_pool_concurrency::lockfree,
					      trait_pool_method::partial,
					      trait_pool_fairness::lifo >;

#endif


text:
/**
 * Little helper to fetch schema.json (used by the Relayjs compiler) from indexd,
 * and dataDictionary.json from the gdc api (used by data/gqlSetup.js to customize gql queries
 * based on the active dictionary before Relay compile).
 *
 * Ex: https://dev.bionimbus.org/api/v0/submission/getschema
 *     https://dev.bionimbus.org/api/v0/submission/_dictionary/_all
 */
const https = require('https');
const http = require('http');
const fetch = require('node-fetch');
const fs = require('fs');
const {
  buildClientSchema,
  printSchema,
} = require('graphql/utilities/index');

const { gdcSubPath } = (function () {
  function addSlash(path) { return (`${path}/`).replace(/\/+$/, '/'); }

  if (process.argv.length < 3) {
    let gdcDefaultPath = 'http://localhost:5000/v0/submission/';

    if (process.env.HOSTNAME) {
      gdcDefaultPath = `https://${process.env.HOSTNAME}/api/v0/submission/`;
      if (process.env.HOSTNAME.startsWith('revproxy')) {
        gdcDefaultPath = `http://${process.env.HOSTNAME}/api/v0/submission/`;
      }
    }
    return { status: 'ok', gdcSubPath: addSlash(process.env.GDC_SUBPATH || gdcDefaultPath) };
  }
  const arg1 = process.argv[2];
  if (!arg1.match(/^https?:\/\//)) {
    console.log(`
    getSchema downloads data/schema.json and data/dictionary.json from the environment's
    gdc-api for later use configuring gql queries for the portal environment, and
    running the relayjs gql compiler.

    Use: node getSchema.js [gdcSubmissionApiPath]
        - where gdcSubmissionApiPath defaults to: process.env.GDC_SUBPATH || 'http://localhost:5000/v0/submission/'
        - example - if gdcSubmissionApiPath = https://dev.bionimbus.org/api/vo/submission/,
            then the script loads:
            * https://dev.bionimbus.org/api/v0/submission/_dictionary/_all
            * https://dev.bionimbus.org/api/v0/submission/getschema
    `);
    return { status: 'exit' };
  }
  return { status: 'ok', gdcSubPath: addSlash(arg1) };
}());

if (!gdcSubPath) {
  process.exit(1);
}

const schemaUrl = `${gdcSubPath}getschema`;
const schemaPath = `${__dirname}/schema.json`;
const dictUrl = `${gdcSubPath}_dictionary/_all`;
const dictPath = `${__dirname}/dictionary.json`;
const httpAgent = new http.Agent({
  rejectUnauthorized: false,
});
const httpsAgent = new https.Agent({
  rejectUnauthorized: false,
});

const retryBackoff = [2000, 4000, 8000, 16000];

/**
 * Wrapper around fetch - retries call on 429 status
 * up to 4 times with exponential backoff
 *
 * @param {string} urlStr
 * @param {*} opts
 */
async function fetchJsonRetry(urlStr, opts) {
  let retryCount = 0;
  let doRequest = null; // for eslint happiness

  async function doRetry(reason) {
    if (retryCount > retryBackoff.length) {
      return Promise.reject(`failed fetch ${reason}, max retries ${retryBackoff.length} exceeded for ${urlStr}`);
    }

    return new Promise(((resolve) => {
      // sleep and try again ...
      const retryIndex = Math.min(retryCount, retryBackoff.length - 1);
      const sleepMs = retryBackoff[retryIndex] + Math.floor(Math.random() * 2000);
      retryCount += 1;
      console.log(`failed fetch - ${reason}, sleeping ${sleepMs} then retry ${urlStr}`);
      setTimeout(() => {
        resolve('ok');
        console.log(`Retrying ${urlStr} after sleep - ${retryCount}`);
      }, sleepMs);
    })).then(doRequest);
  }

  doRequest = async function () {
    if (retryCount > 0) {
      console.log(`Re-fetching ${urlStr} - retry no ${retryCount}`);
    }
    return fetch(urlStr, opts,
    ).then(
      (res) => {
        if (res.status === 200) {
          return res.json().catch(
            (err) => doRetry(`failed json parse - ${err}`),
          );
        }
        return doRetry(`non-200 from server: ${res.status}`);
      },
      (err) => doRetry(err),
    );
  };

  return doRequest();
}

async function fetchJson(url) {
  console.log(`Fetching ${url}`);
  return fetchJsonRetry(url, {
    agent: url.match(/^https:/) ? httpsAgent : httpAgent,
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  });
}

const actionList = [];

actionList.push(
  // Save JSON of full schema introspection for Babel Relay Plugin to use
  fetchJson(schemaUrl).then((schema) => {
    fs.writeFileSync(schemaPath, JSON.stringify(schema, null, 2));

    // Save user readable type system shorthand of schema
    const graphQLSchema = buildClientSchema(schema.data);
    fs.writeFileSync(`${__dirname}/schema.graphql`, printSchema(graphQLSchema));
  }),
);

actionList.push(
  fetchJson(dictUrl).then(
    (dict) => {
      fs.writeFileSync(dictPath, JSON.stringify(dict, null, 2));
    },
  ),
);

Promise.all(actionList).then(
  () => {
    console.log('All done!');
    process.exit(0);
  },
  (err) => {
    console.error('Error: ', err);
    process.exit(2);
  },
);


text:
<!DOCTYPE html>

  <title>grapp-websocket-rails web component</title>

  <link href="build/grapp-websocket-rails.html" rel="import">

grapp-websocket-rails web component

A web component that displays font awesome icons

    Click here to run the tests...

    Click here to read the documentation...

    Click here to read the changelog...

Demo


text:
package com.lqtemple.android.lqbookreader.read;

import android.widget.Toast;

import com.lqtemple.android.lqbookreader.MyApplication;
import com.lqtemple.android.lqbookreader.R;

/**
 *  Toast factory
 */
public class ToastFactory {
    public static void showPageEnd() {
        Toast.makeText(MyApplication.getsContext(), R.string.book_reach_end_toast, Toast.LENGTH_SHORT).show();
    }

    public static void showPageStart() {
        Toast.makeText(MyApplication.getsContext(), R.string.book_reach_start_toast, Toast.LENGTH_SHORT).show();
    }
}


text:
import * as tf from '@tensorflow/tfjs';

/**
 * Pixel normalization.
 * @param epsilon A small positive number to avoid division by zero.
 */
class PixelNorm extends tf.layers.Layer {
  constructor(public epsilon = 1e-8, public layerConfig = {}) {
    super(layerConfig);
    this.supportsMasking = true;
  }

  /**
   * Computes output shape.
   * @param inputShape Shape of input.
   */
  computeOutputShape(inputShape: number[]) {
    return [inputShape[0], inputShape[1], inputShape[2], inputShape[3]];
  }

  /**
   * For each pixel a[i,j,k] of image in HWC format, normalize its value to
   * b[i,j,k] = a[i,j,k] / SQRT(SUM_k(a[i,j,k]^2) / C + eps).
   * @param inputs A 4D `Tensor` of NHWC format.
   * @param kwargs Only used as a pass through to call hooks.
   * @returns A 4D `Tensor` with pixel-wise normalized channels.
   */
  call(inputs: tf.Tensor4D): tf.Tensor4D {
    return tf.tidy(() => {
      let input = inputs;
      if (Array.isArray(input)) {
        input = input[0];
      }
      const mean = tf.mean(tf.square(input), [3], true);
      return tf.mul(input, tf.rsqrt(tf.add(mean, this.epsilon)));
    });
  }

  /**
   * Layers must implement "getClassName".
   */
  getClassName() {
    return 'PixelNorm';
  }
}

export function pixelNorm(epsilon = 1e-8, layerConfig = {}) {
  return new PixelNorm(epsilon, layerConfig);
}

/**
 * InitialPad.
 *
 * Padding op to allow for valid upsampling convolution,
 * of the initial convolution in the stack.
 * @param kernelH Integer, size of convolution kernel height.
 * @param kernelW Integer, size of convolution kernel height.
 */
class InitialPad extends tf.layers.Layer {
  constructor(
      public kernelH = 2, public kernelW = 16, public layerConfig = {}) {
    super(layerConfig);
    this.supportsMasking = true;
  }

  /**
   * @param inputShapes A number[] of the input `Tensor` shape.
   */
  computeOutputShape(inputShape: number[]) {
    return [
      inputShape[0], 2 * (this.kernelH - 1) + inputShape[1],
      2 * (this.kernelW - 1) + inputShape[2], inputShape[3]
    ];
  }

  /**
   * @param inputs A 4D `Tensor` of NHWC format, H=1, W=1.
   * @param kwargs Only used as a pass through to call hooks.
   * @returns A 4D `Tensor` with with padding in width and height.
   */
  call(inputs: tf.Tensor4D): tf.Tensor4D {
    let input = inputs;
    if (Array.isArray(input)) {
      input = input[0];
    }
    const padH = this.kernelH - 1;
    const padW = this.kernelW - 1;
    return tf.pad(input, [[0, 0], [padH, padH], [padW, padW], [0, 0]]);
  }

  /**
   * Layers must implement "getClassName".
   */
  getClassName() {
    return 'InitialPad';
  }
}

export function initialPad(kernelH = 2, kernelW = 16, layerConfig = {}) {
  return new InitialPad(kernelH, kernelW, layerConfig);
}

/**
 * Box (Nearest Neighbor upscaling).
 * @param scale Integer amount to upscale width and height.
 */
class BoxUpscale extends tf.layers.Layer {
  constructor(public scale = 2) {
    super({});
    this.supportsMasking = true;
  }

  /**
   * @param inputShapes Shape of the input.
   */
  computeOutputShape(inputShape: number[]) {
    return [
      inputShape[0], this.scale * inputShape[1], this.scale * inputShape[2],
      inputShape[3]
    ];
  }

  /**
   * @param inputs A 4D `Tensor` of NHWC format.
   * @param kwargs Only used as a pass through to call hooks.
   * @returns A 4D `Tensor` of `images` up scaled by a factor `scale`.
   */
  call(inputs: tf.Tensor4D): tf.Tensor4D {
    return tf.tidy(() => {
      let input = inputs;
      if (Array.isArray(input)) {
        input = input[0];
      }
      const tiledInput = tf.tile(input, [this.scale ** 2, 1, 1, 1]);
      return tf.batchToSpaceND(
          tiledInput, [this.scale, this.scale], [[0, 0], [0, 0]]);
    });
  }

  /**
   * Layers must implement "getClassName".
   */
  getClassName() {
    return 'BoxUpscale';
  }
}

export function boxUpscale(scale = 2) {
  return new BoxUpscale(scale);
}


text:
using extensions::api::manifest_types::ChromeUIOverrides;

namespace extensions {

// The manifest permission implementation supports a permission for overriding
// the bookmark UI.
class UIOverridesHandler::ManifestPermissionImpl : public ManifestPermission {
 public:
  explicit ManifestPermissionImpl(bool override_bookmarks_ui_permission)
      : override_bookmarks_ui_permission_(override_bookmarks_ui_permission) {}

  // extensions::ManifestPermission overrides.
  virtual std::string name() const OVERRIDE {
    return manifest_keys::kUIOverride;
  }

  virtual std::string id() const OVERRIDE {
    return name();
  }

  virtual bool HasMessages() const OVERRIDE {
    return override_bookmarks_ui_permission_;
  }

  virtual PermissionMessages GetMessages() const OVERRIDE {
    PermissionMessages result;
    if (override_bookmarks_ui_permission_) {
      result.push_back(PermissionMessage(
          PermissionMessage::kOverrideBookmarksUI,
          l10n_util::GetStringUTF16(
              IDS_EXTENSION_PROMPT_WARNING_OVERRIDE_BOOKMARKS_UI)));
    }
    return result;
  }

  virtual bool FromValue(const base::Value* value) OVERRIDE {
    return value && value->GetAsBoolean(&override_bookmarks_ui_permission_);
  }

  virtual scoped_ptr<base::Value> ToValue() const OVERRIDE {
    return scoped_ptr<base::Value>(
        new base::FundamentalValue(override_bookmarks_ui_permission_)).Pass();
  }

  virtual ManifestPermission* Clone() const OVERRIDE {
    return scoped_ptr<ManifestPermissionImpl>(
        new ManifestPermissionImpl(
            override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Diff(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ &&
        !other->override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Union(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ ||
        other->override_bookmarks_ui_permission_)).release();
  }

  virtual ManifestPermission* Intersect(const ManifestPermission* rhs) const
      OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return scoped_ptr<ManifestPermissionImpl>(new ManifestPermissionImpl(
        override_bookmarks_ui_permission_ &&
        other->override_bookmarks_ui_permission_)).release();
  }

  virtual bool Contains(const ManifestPermission* rhs) const OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return !other->override_bookmarks_ui_permission_ ||
        override_bookmarks_ui_permission_;
  }

  virtual bool Equal(const ManifestPermission* rhs) const OVERRIDE {
    const ManifestPermissionImpl* other =
        static_cast<const ManifestPermissionImpl*>(rhs);

    return override_bookmarks_ui_permission_ ==
        other->override_bookmarks_ui_permission_;
  }

  virtual void Write(IPC::Message* m) const OVERRIDE {
    IPC::WriteParam(m, override_bookmarks_ui_permission_);
  }

  virtual bool Read(const IPC::Message* m, PickleIterator* iter) OVERRIDE {
    return IPC::ReadParam(m, iter, &override_bookmarks_ui_permission_);
  }

  virtual void Log(std::string* log) const OVERRIDE {
    IPC::LogParam(override_bookmarks_ui_permission_, log);
  }

 private:
  bool override_bookmarks_ui_permission_;
};

UIOverrides::UIOverrides() {}

UIOverrides::~UIOverrides() {}

const UIOverrides* UIOverrides::Get(const Extension* extension) {
  return static_cast<UIOverrides*>(
      extension->GetManifestData(manifest_keys::kUIOverride));
}

bool UIOverrides::RemovesBookmarkButton(const UIOverrides& ui_overrides) {
  return ui_overrides.bookmarks_ui &&
      ui_overrides.bookmarks_ui->remove_button &&
      *ui_overrides.bookmarks_ui->remove_button;
}

bool UIOverrides::RemovesBookmarkShortcut(const UIOverrides& ui_overrides) {
  return ui_overrides.bookmarks_ui &&
      ui_overrides.bookmarks_ui->remove_bookmark_shortcut &&
      *ui_overrides.bookmarks_ui->remove_bookmark_shortcut;
}

UIOverridesHandler::UIOverridesHandler() {}

UIOverridesHandler::~UIOverridesHandler() {}

bool UIOverridesHandler::Parse(Extension* extension, base::string16* error) {
  const base::Value* dict = NULL;
  CHECK(extension->manifest()->Get(manifest_keys::kUIOverride, &dict));
  scoped_ptr<ChromeUIOverrides> overrides(
      ChromeUIOverrides::FromValue(*dict, error));
  if (!overrides)
    return false;

  scoped_ptr<UIOverrides> info(new UIOverrides);
  info->bookmarks_ui.swap(overrides->bookmarks_ui);
  if (!info->bookmarks_ui) {
    *error = ErrorUtils::FormatErrorMessageUTF16(
        manifest_errors::kInvalidEmptyDictionary,
        manifest_keys::kUIOverride);
    return false;
  }
  info->manifest_permission.reset(new ManifestPermissionImpl(
      UIOverrides::RemovesBookmarkButton(*info)));
  extension->SetManifestData(manifest_keys::kUIOverride, info.release());
  return true;
}

bool UIOverridesHandler::Validate(const Extension* extension,
                                  std::string* error,
                                  std::vector<InstallWarning>* warnings) const {
  const UIOverrides* ui_overrides = UIOverrides::Get(extension);

  if (ui_overrides && ui_overrides->bookmarks_ui) {
    if (!FeatureSwitch::enable_override_bookmarks_ui()->IsEnabled()) {
      warnings->push_back(InstallWarning(
          ErrorUtils::FormatErrorMessage(
              manifest_errors::kUnrecognizedManifestKey,
              manifest_keys::kBookmarkUI)));
    }
  }

  return true;
}

ManifestPermission* UIOverridesHandler::CreatePermission() {
  return new ManifestPermissionImpl(false);
}

ManifestPermission* UIOverridesHandler::CreateInitialRequiredPermission(
    const Extension* extension) {
  const UIOverrides* data = UIOverrides::Get(extension);
  if (data)
    return data->manifest_permission->Clone();
  return NULL;
}
const std::vector<std::string> UIOverridesHandler::Keys() const {
  return SingleKey(manifest_keys::kUIOverride);
}

}  // namespace extensions


text:
/*
 * $Id: AVT.java 469221 2006-10-30 18:26:44Z minchau $
 */
package org.apache.xalan.templates;

import java.util.StringTokenizer;
import java.util.Vector;

import javax.xml.transform.TransformerException;

import org.apache.xalan.processor.StylesheetHandler;
import org.apache.xalan.res.XSLMessages;
import org.apache.xalan.res.XSLTErrorResources;
import org.apache.xml.utils.FastStringBuffer;
import org.apache.xml.utils.StringBufferPool;
import org.apache.xpath.XPath;
import org.apache.xpath.XPathContext;

/**
 * Class to hold an Attribute Value Template.
 * @xsl.usage advanced
 */
public class AVT implements java.io.Serializable, XSLTVisitable
{
    static final long serialVersionUID = 5167607155517042691L;

  /**
    *We are not going to use the object pool if USE_OBJECT_POOL == false.
  */
  private final static boolean USE_OBJECT_POOL = false;

  /**
    * INIT_BUFFER_CHUNK_BITS is used to set initial size of
    * of the char m_array in FastStringBuffer if USE_OBJECT_POOL == false.
    * size = 2^ INIT_BUFFER_CHUNK_BITS, INIT_BUFFER_CHUNK_BITS = 7
    * corresponds size = 256.
  */
  private final static int INIT_BUFFER_CHUNK_BITS = 8;

  /**
   * If the AVT is not complex, just hold the simple string.
   * @serial
   */
  private String m_simpleString = null;

  /**
   * If the AVT is complex, hold a Vector of AVTParts.
   * @serial
   */
  private Vector m_parts = null;

  /**
   * The name of the attribute.
   * @serial
   */
  private String m_rawName;

  /**
   * Get the raw name of the attribute, with the prefix unprocessed.
   *
   * @return non-null reference to prefixed name.
   */
  public String getRawName()
  {
    return m_rawName;
  }

  /**
   * Get the raw name of the attribute, with the prefix unprocessed.
   *
   * @param rawName non-null reference to prefixed name.
   */
  public void setRawName(String rawName)
  {
    m_rawName = rawName;
  }

  /**
   * The name of the attribute.
   * @serial
   */
  private String m_name;

  /**
   * Get the local name of the attribute.
   *
   * @return non-null reference to name string.
   */
  public String getName()
  {
    return m_name;
  }

  /**
   * Set the local name of the attribute.
   *
   * @param name non-null reference to name string.
   */
  public void setName(String name)
  {
    m_name = name;
  }

  /**
   * The namespace URI of the owning attribute.
   * @serial
   */
  private String m_uri;

  /**
   * Get the namespace URI of the attribute.
   *
   * @return non-null reference to URI, "" if null namespace.
   */
  public String getURI()
  {
    return m_uri;
  }

  /**
   * Get the namespace URI of the attribute.
   *
   * @param uri non-null reference to URI, "" if null namespace.
   */
  public void setURI(String uri)
  {
    m_uri = uri;
  }

  /**
   * Construct an AVT by parsing the string, and either
   * constructing a vector of AVTParts, or simply hold
   * on to the string if the AVT is simple.
   *
   * @param handler non-null reference to StylesheetHandler that is constructing.
   * @param uri non-null reference to URI, "" if null namespace.
   * @param name  non-null reference to name string.
   * @param rawName prefixed name.
   * @param stringedValue non-null raw string value.
   *
   * @throws javax.xml.transform.TransformerException
   */
  public AVT(StylesheetHandler handler, String uri, String name,
             String rawName, String stringedValue,
             ElemTemplateElement owner)
          throws javax.xml.transform.TransformerException
  {

    m_uri = uri;
    m_name = name;
    m_rawName = rawName;

    StringTokenizer tokenizer = new StringTokenizer(stringedValue, "{}\"\'",
                                  true);
    int nTokens = tokenizer.countTokens();

    if (nTokens < 2)
    {
      m_simpleString = stringedValue;  // then do the simple thing
    }
    else
    {
      FastStringBuffer buffer = null;
      FastStringBuffer exprBuffer = null;
      if(USE_OBJECT_POOL){
        buffer = StringBufferPool.get();
        exprBuffer = StringBufferPool.get();
      }else{
        buffer = new FastStringBuffer(6);
        exprBuffer = new FastStringBuffer(6);
      }
      try
      {
        m_parts = new Vector(nTokens + 1);

        String t = null;  // base token
        String lookahead = null;  // next token
        String error = null;  // if non-null, break from loop

        while (tokenizer.hasMoreTokens())
        {
          if (lookahead != null)
          {
            t = lookahead;
            lookahead = null;
          }
          else
            t = tokenizer.nextToken();

          if (t.length() == 1)
          {
            switch (t.charAt(0))
            {
            case ('\"') :
            case ('\'') :
            {

              // just keep on going, since we're not in an attribute template
              buffer.append(t);

              break;
            }
            case ('{') :
            {

              try
              {
                // Attribute Value Template start
                lookahead = tokenizer.nextToken();

                if (lookahead.equals("{"))
                {

                  // Double curlys mean escape to show curly
                  buffer.append(lookahead);

                  lookahead = null;

                  break;  // from switch
                }

                /*
                else if(lookahead.equals("\"") || lookahead.equals("\'"))
                {
                // Error. Expressions can not begin with quotes.
                error = "Expressions can not begin with quotes.";
                break; // from switch
                }
                */
                else
                {
                  if (buffer.length() > 0)
                  {
                    m_parts.addElement(new AVTPartSimple(buffer.toString()));
                    buffer.setLength(0);
                  }

                  exprBuffer.setLength(0);

                  while (null != lookahead)
                  {
                    if (lookahead.length() == 1)
                    {
                      switch (lookahead.charAt(0))
                      {
                      case '\'' :
                      case '\"' :
                        {

                          // String start
                          exprBuffer.append(lookahead);

                          String quote = lookahead;

                          // Consume stuff 'till next quote
                          lookahead = tokenizer.nextToken();

                          while (!lookahead.equals(quote))
                          {
                            exprBuffer.append(lookahead);

                            lookahead = tokenizer.nextToken();
                          }

                          exprBuffer.append(lookahead);

                          lookahead = tokenizer.nextToken();

                          break;
                        }
                      case '{' :
                        {

                          // What's another curly doing here?
                          error = XSLMessages.createMessage(
                                                            XSLTErrorResources.ER_NO_CURLYBRACE, null);  //"Error: Can not have \"{\" within expression.";

                          lookahead = null;  // breaks out of inner while loop

                          break;
                        }
                      case '}' :
                        {

                          // Proper close of attribute template.
                          // Evaluate the expression.
                          buffer.setLength(0);

                          XPath xpath =
                                       handler.createXPath(exprBuffer.toString(), owner);

                          m_parts.addElement(new AVTPartXPath(xpath));

                          lookahead = null;  // breaks out of inner while loop

                          break;
                        }
                      default :
                        {

                          // part of the template stuff, just add it.
                          exprBuffer.append(lookahead);

                          lookahead = tokenizer.nextToken();
                        }
                      }  // end inner switch
                    }  // end if lookahead length == 1
                    else
                    {

                      // part of the template stuff, just add it.
                      exprBuffer.append(lookahead);

                      lookahead = tokenizer.nextToken();
                    }
                  }  // end while(!lookahead.equals("}"))

                  if (error != null)
                  {
                    break;  // from inner while loop
                  }
                }

                break;
              }
              catch (java.util.NoSuchElementException ex)
              {
                error = XSLMessages.createMessage(XSLTErrorResources.ER_ILLEGAL_ATTRIBUTE_VALUE, new Object[]{ name, stringedValue });
                break;
              }
            }
            case ('}') :
            {
              lookahead = tokenizer.nextToken();

              if (lookahead.equals("}"))
              {

                // Double curlys mean escape to show curly
                buffer.append(lookahead);

                lookahead = null;  // swallow
              }
              else
              {

                // Illegal, I think...
                try
                {
                  handler.warn(XSLTErrorResources.WG_FOUND_CURLYBRACE, null);  //"Found \"}\" but no attribute template open!");
                }
                catch (org.xml.sax.SAXException se)
                {
                  throw new TransformerException(se);
                }

                buffer.append("}");

                // leave the lookahead to be processed by the next round.
              }

              break;
            }
            default :
            {

              // Anything else just add to string.
              buffer.append(t);
            }
            }  // end switch t
          }  // end if length == 1
          else
          {

            // Anything else just add to string.
            buffer.append(t);
          }

          if (null != error)
          {
            try
            {
              handler.warn(XSLTErrorResources.WG_ATTR_TEMPLATE,
                           new Object[]{ error });  //"Attr Template, "+error);
            }
            catch (org.xml.sax.SAXException se)
            {
              throw new TransformerException(se);
            }

            break;
          }
        }  // end while(tokenizer.hasMoreTokens())

        if (buffer.length() > 0)
        {
          m_parts.addElement(new AVTPartSimple(buffer.toString()));
          buffer.setLength(0);
        }
      }
      finally
      {
        if(USE_OBJECT_POOL){
             StringBufferPool.free(buffer);
             StringBufferPool.free(exprBuffer);
         }else{
            buffer = null;
            exprBuffer = null;
         };
      }
    }  // end else nTokens > 1

    if (null == m_parts && (null == m_simpleString))
    {

      // Error?
      m_simpleString = "";
    }
  }

  /**
   * Get the AVT as the original string.
   *
   * @return The AVT as the original string
   */
  public String getSimpleString()
  {

    if (null != m_simpleString){
      return m_simpleString;
    }
    else if (null != m_parts){
     final FastStringBuffer buf = getBuffer();
     String out = null;

    int n = m_parts.size();
    try{
      for (int i = 0; i < n; i++){
        AVTPart part = (AVTPart) m_parts.elementAt(i);
        buf.append(part.getSimpleString());
      }
      out = buf.toString();
    }finally{
      if(USE_OBJECT_POOL){
         StringBufferPool.free(buf);
     }else{
        buf.setLength(0);
     };
    }
    return out;
  }else{
      return "";
  }
}

  /**
   * Evaluate the AVT and return a String.
   *
   * @param xctxt Te XPathContext to use to evaluate this.
   * @param context The current source tree context.
   * @param nsNode The current namespace context (stylesheet tree context).
   *
   * @return The AVT evaluated as a string
   *
   * @throws javax.xml.transform.TransformerException
   */
  public String evaluate(
          XPathContext xctxt, int context, org.apache.xml.utils.PrefixResolver nsNode)
            throws javax.xml.transform.TransformerException
  {
    if (null != m_simpleString){
        return m_simpleString;
    }else if (null != m_parts){
      final FastStringBuffer buf =getBuffer();
      String out = null;
      int n = m_parts.size();
      try{
        for (int i = 0; i < n; i++){
          AVTPart part = (AVTPart) m_parts.elementAt(i);
          part.evaluate(xctxt, buf, context, nsNode);
        }
       out = buf.toString();
      }finally{
          if(USE_OBJECT_POOL){
             StringBufferPool.free(buf);
         }else{
           buf.setLength(0);
         }
      }
     return out;
    }else{
      return "";
    }
  }

  /**
   * Test whether the AVT is insensitive to the context in which
   *  it is being evaluated. This is intended to facilitate
   *  compilation of templates, by allowing simple AVTs to be
   *  converted back into strings.
   *
   *  Currently the only case we recognize is simple strings.
   * ADDED 9/5/2000 to support compilation experiment
   *
   * @return True if the m_simpleString member of this AVT is not null
   */
  public boolean isContextInsensitive()
  {
    return null != m_simpleString;
  }

  /**
   * Tell if this expression or it's subexpressions can traverse outside
   * the current subtree.
   *
   * @return true if traversal outside the context node's subtree can occur.
   */
  public boolean canTraverseOutsideSubtree()
  {

    if (null != m_parts)
    {
      int n = m_parts.size();

      for (int i = 0; i < n; i++)
      {
        AVTPart part = (AVTPart) m_parts.elementAt(i);

        if (part.canTraverseOutsideSubtree())
          return true;
      }
    }

    return false;
  }

  /**
   * This function is used to fixup variables from QNames to stack frame
   * indexes at stylesheet build time.
   * @param vars List of QNames that correspond to variables.  This list
   * should be searched backwards for the first qualified name that
   * corresponds to the variable reference qname.  The position of the
   * QName in the vector from the start of the vector will be its position
   * in the stack frame (but variables above the globalsTop value will need
   * to be offset to the current stack frame).
   */
  public void fixupVariables(java.util.Vector vars, int globalsSize)
  {
    if (null != m_parts)
    {
      int n = m_parts.size();

      for (int i = 0; i < n; i++)
      {
        AVTPart part = (AVTPart) m_parts.elementAt(i);

        part.fixupVariables(vars, globalsSize);
      }
    }
  }

  /**
   * @see XSLTVisitable#callVisitors(XSLTVisitor)
   */
  public void callVisitors(XSLTVisitor visitor)
  {
  	if(visitor.visitAVT(this) && (null != m_parts))
  	{
      int n = m_parts.size();

      for (int i = 0; i < n; i++)
      {
        AVTPart part = (AVTPart) m_parts.elementAt(i);

        part.callVisitors(visitor);
      }
  	}
  }

  /**
   * Returns true if this AVT is simple
   */
  public boolean isSimple() {
  	return m_simpleString != null;
  }

  private final FastStringBuffer getBuffer(){
    if(USE_OBJECT_POOL){
      return StringBufferPool.get();
    }else{
      return new FastStringBuffer(INIT_BUFFER_CHUNK_BITS);
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Class Hierarchy</title>
<meta name="date" content="2014-08-03">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For All Packages

Package Hierarchies:

j3dio,

j3dio.obj,

j3dio.ply,

j3dio.raw,

j3dio.stl

Class Hierarchy

java.lang.Object

j3dio.ply.Element

j3dio.ply.ElementInstance

j3dio.stl.FaceT (implements j3dio.Byteable)

j3dio.obj.MtlMaterial (implements j3dio.Exportable)

j3dio.obj.ObjModel (implements j3dio.Exportable, j3dio.GLRenderable)

j3dio.ply.PlyModel (implements j3dio.Exportable)

j3dio.Point3f (implements j3dio.Byteable)

j3dio.obj.MtlPoint3f

j3dio.raw.RawFace

j3dio.obj.ObjFace

j3dio.raw.RawModel (implements j3dio.Exportable, j3dio.GLRenderable)

j3dio.stl.StlModel (implements j3dio.Byteable, j3dio.Exportable, j3dio.GLRenderable)

Interface Hierarchy

j3dio.Byteable

j3dio.Exportable

j3dio.GLRenderable

Enum Hierarchy

java.lang.Object

java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)

j3dio.ply.PlyModel.Format

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView
    android:id="@android:id/text1"
    style="@style/labelText"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:paddingLeft="15dp"
    tools:text="@string/dummy.short"/>


text:
package com.xfhy.daily.presenter;

import com.xfhy.androidbasiclibs.basekit.presenter.BasePresenter;
import com.xfhy.androidbasiclibs.basekit.view.BaseView;
import com.xfhy.daily.model.bean.ColumnDailyDetailsBean;

import java.util.List;

/**
 * @author xfhy
 *         create at 2017/11/26 12:36
 *         description:知乎通用list的规范
 */
public interface ZHSectionDetailsContract {

    interface Presenter extends BasePresenter<View> {

        /**
         * 从网络请求主题列表
         */
        void reqDataFromNet(String sectionId);

        /**
         * 获取专栏详情列表数据
         */
        List<ColumnDailyDetailsBean.StoriesBean> getData();

        /**
         * 刷新数据
         */
        void refreshData(String sectionId);

        /**
         * 获取点击item位置的文章id
         */
        int getDailyId(int position);

    }

    interface View extends BaseView {
        /**
         * 请求专栏列表数据成功
         */
        void loadSuccess(List<ColumnDailyDetailsBean.StoriesBean> dataBeans);

        /**
         * 获取当前专栏id
         */
        String getSectionId();

    }

}


text:
- The transformation matrix can now be computed independent of applying
  the matrix, allowing caching for better performance.

### [0.0.1](https://github.com/jmeas/two-rotations.js/releases/tag/v0.0.1)

- The first release!


text:
type Record = { name: string };
type State = {
  byId_straight: { [id: string]: Record },
  byId_maybe: { [id: string]: ?Record }, // could be null or undefined
  byId_void: { [id: string]: Record | void } // cound by undefined
}

const state: State = {
  byId_straight: {},
  byId_maybe: {},
  byId_void: {},
}

const s = state.byId_straight['a'];
const m = state.byId_maybe['a'];
const v = state.byId_void['a'];

s.name;
m.name;
v.name;


text:
/**
 * AppController
 * @namespace telepati.controllers
 */
(function () {
    'use strict';
    angular.module('telepati').controller('AppController', AppController);
    AppController.$inject = ['$location', '$scope', '$interval', 'AppService'];
    /**
     * @namespace AppController
     */
    function AppController($location, $scope, $interval, AppService) {
      var vm = this;
      vm.init = init;
      vm.users = Array();
      vm.profile = String();
      vm.showChatWindow = false;
      vm.loadUserChat = loadUserChat;
      vm.sendChatMessage = sendChatMessage;
      vm.setProfile = setProfile;
      vm.profilePing = profilePing;

      /**
      * @name getProfile
      * @desc get profile
      * @memberOf telepati.controllers.AppController
      */
      function getProfile(){
        AppService.getProfile()
          .success(function(data){
            if(data.response){
              vm.profile = data.data.message;
            }
          });
      }

      /**
      * @name getUserProfiles
      * @desc get user list
      * @memberOf telepati.controllers.AppController
      */
      function getUserProfiles(){
        AppService.getUsers()
          .success(function(data){
            vm.users = data.usersList;
          });
      }

      /**
      * @name getUserChats
      * @desc get current user chats
      * @memberOf telepati.controllers.AppController
      */
      function getUserChats(){
        if((vm.user==undefined) || (vm.user.name.length < 1))
          return;

        AppService.getChatMessages(vm.user)
          .success(function(data){
            vm.chats = data.messagesList;
            console.log(vm.chats);
          });
      }

      /**
      * @name init
      * @desc startup script
      * @memberOf telepati.controllers.AppController
      */
      function init() {
        getProfile();
        getUserProfiles();
      }

      /**
      * @name loadUserChat
      * @desc get chat conversation between user
      * @memberOf telepati.controllers.AppController
      */
      function loadUserChat(index) {
        vm.showChatWindow = true;
        vm.user = vm.users[index];
        getUserChats();
      }

      /**
      * @name sendChatMessage
      * @desc send message to chat
      * @memberOf telepati.controllers.AppController
      */
      function sendChatMessage() {
        if((vm.user==undefined) || (vm.user.name.length < 1))
          return;
        if((vm.newMessage==undefined) || (vm.newMessage.length < 1))
          return;

        var msg = {
          name: vm.profile,
          public_key: "public_key",
          message: vm.newMessage,
          recipient: vm.user.name,
        }
        AppService.getChatMessages(msg)
          .success(function(data){
            vm.chats = data.messagesList;
            console.log(vm.chats);
          });

        vm.newMessage = "";
      }

      /**
      * @name setProfile
      * @desc set profile name
      * @memberOf telepati.controllers.AppController
      */
      function setProfile() {
        if((vm.profile==undefined) || (vm.profile.length < 1))
          return;

        var msg = {
          name: vm.profile,
        }
        AppService.setProfileName(msg)
          .success(function(data){
            if(data.response){
              getProfile();
              $('#myModal').modal('toggle');
            }
          });
      }

      /**
      * @name profilePing
      * @desc send profile info to air
      * @memberOf telepati.controllers.AppController
      */
      function profilePing() {
        if((vm.profile==undefined) || (vm.profile.length < 1))
          return;

        var msg = {
          name: vm.profile,
          public_key: "public_key",
        }
        AppService.profilePing(msg)
          .success(function(data){
            if(data.response){
              console.log("Ping Successful ...");
            }
          });
      }

      // $interval(getUserProfiles, 2000);
      // $interval(getUserChats, 2000);
      // $interval(profilePing, 2000);

    }
})();


text:
namespace Poco {
namespace Net {

class Net_API MailRecipient
	/// The recipient of an e-mail message.
	///
	/// A recipient has a type (primary recipient,
	/// carbon-copy recipient, blind-carbon-copy
	/// recipient), an e-mail address and an optional
	/// real name.
{
public:
	enum RecipientType
	{
		PRIMARY_RECIPIENT,
		CC_RECIPIENT,
		BCC_RECIPIENT
	};

	MailRecipient();
		/// Creates an empty MailRecipient.

	MailRecipient(const MailRecipient& recipient);
		/// Creates a MailRecipient by copying another one.

	MailRecipient(RecipientType type, const std::string& address);
		/// Creates a MailRecipient of the given type.

	MailRecipient(RecipientType type, const std::string& address, const std::string& realName);
		/// Creates a MailRecipient of the given type.

	~MailRecipient();
		/// Destroys the MailRecipient.

	MailRecipient& operator = (const MailRecipient& recipient);
		/// Assigns another recipient.

	void swap(MailRecipient& recipient);
		/// Exchanges the content of two recipients.

	RecipientType getType() const;
		/// Returns the type of the recipient.

	void setType(RecipientType type);
		/// Sets the type of the recipient.

	const std::string& getAddress() const;
		/// Returns the address of the recipient.

	void setAddress(const std::string& address);
		/// Sets the address of the recipient.

	const std::string& getRealName() const;
		/// Returns the real name of the recipient.

	void setRealName(const std::string& realName);
		/// Sets the real name of the recipient.

private:
	std::string   _address;
	std::string   _realName;
	RecipientType _type;
};

//
// inlines
//
inline MailRecipient::RecipientType MailRecipient::getType() const
{
	return _type;
}

inline const std::string& MailRecipient::getAddress() const
{
	return _address;
}

inline const std::string& MailRecipient::getRealName() const
{
	return _realName;
}

inline void swap(MailRecipient& r1, MailRecipient& r2)
{
	r1.swap(r2);
}

} } // namespace Poco::Net

#endif // Net_MailRecipient_INCLUDED


text:
import re

import requests
from six import iteritems

# project
from datadog_checks.base import AgentCheck

EVENT_TYPE = SOURCE_TYPE_NAME = 'squid'

METRIC_PREFIX = "squid.cachemgr"
SERVICE_CHECK = "squid.can_connect"
SQUID_COUNTERS = [
    "client_http.requests",
    "client_http.hits",
    "client_http.errors",
    "client_http.kbytes_in",
    "client_http.kbytes_out",
    "client_http.hit_kbytes_out",
    "server.all.requests",
    "server.all.errors",
    "server.all.kbytes_in",
    "server.all.kbytes_out",
    "server.http.requests",
    "server.http.errors",
    "server.http.kbytes_in",
    "server.http.kbytes_out",
    "server.ftp.requests",
    "server.ftp.errors",
    "server.ftp.kbytes_in",
    "server.ftp.kbytes_out",
    "server.other.requests",
    "server.other.errors",
    "server.other.kbytes_in",
    "server.other.kbytes_out",
    "icp.pkts_sent",
    "icp.pkts_recv",
    "icp.queries_sent",
    "icp.replies_sent",
    "icp.queries_recv",
    "icp.replies_recv",
    "icp.query_timeouts",
    "icp.replies_queued",
    "icp.kbytes_sent",
    "icp.kbytes_recv",
    "icp.q_kbytes_sent",
    "icp.r_kbytes_sent",
    "icp.q_kbytes_recv",
    "icp.r_kbytes_recv",
    "icp.times_used",
    "cd.times_used",
    "cd.msgs_sent",
    "cd.msgs_recv",
    "cd.memory",
    "cd.local_memory",
    "cd.kbytes_sent",
    "cd.kbytes_recv",
    "unlink.requests",
    "page_faults",
    "select_loops",
    "cpu_time",
    "swap.outs",
    "swap.ins",
    "swap.files_cleaned",
    "aborted_requests",
]

# Regular SEMVER pattern but the "patch" part is optional.
SQUID_VERSION_PATTERN = re.compile(
    r"""
    (?P<major>0|[1-9]\d*)
    \.
    (?P<minor>0|[1-9]\d*)
    (?:\.(?P<patch>0|[1-9]\d*))?
    (?:-(?P<release>
        (?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)
        (?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*
    ))?
    (?:\+(?P<build>
        [0-9a-zA-Z-]+
        (?:\.[0-9a-zA-Z-]+)*
    ))?
    """,
    re.VERBOSE,
)

class SquidCheck(AgentCheck):
    HTTP_CONFIG_REMAPPER = {'cachemgr_username': {'name': 'username'}, 'cachemgr_password': {'name': 'password'}}

    def check(self, instance):

        name, host, port, custom_tags = self.parse_instance(instance)
        tags = ["name:%s" % name]
        # Get the squid counters values
        counters = self.get_counters(host, port, tags + custom_tags)

        # Send these values as rate
        for counter, value in iteritems(counters):
            self.rate(counter, value, tags=tags + custom_tags)

    def get_counters(self, host, port, tags):
        if not (host.startswith('http://') or host.startswith('https://')):
            host = 'http://%s' % host
        url = "%s:%s/squid-internal-mgr/counters" % (host, port)
        try:
            res = self.http.get(url)
            res.raise_for_status()
            self.service_check(SERVICE_CHECK, AgentCheck.OK, tags=tags)
            headers = res.headers
            self.submit_version(headers)

        except requests.exceptions.RequestException as e:
            self.service_check(SERVICE_CHECK, AgentCheck.CRITICAL, tags=tags)
            self.log.error('There was an error connecting to squid at %s: %s', url, e)
            raise

        # Each line is a counter in the form 'counter_name = value'
        raw_counters = res.text.strip().split("\n")
        counters = {}
        for line in raw_counters:
            counter, value = self.parse_counter(line)
            if counter in SQUID_COUNTERS:
                counters["%s.%s" % (METRIC_PREFIX, counter)] = float(value)
        return counters

    def parse_instance(self, instance):
        name = instance.get("name")
        if not name:
            raise Exception("Each instance in squid.yaml must have a name")
        host = instance.get("host", "localhost")
        port = instance.get("port", 3128)
        custom_tags = instance.get("tags", [])
        return name, host, port, custom_tags

    def parse_counter(self, line):
        # Squid returns a plain text page with one counter per line:
        # ...
        # client_http.errors = 0
        # client_http.kbytes_in = 0
        # client_http.kbytes_out = 2
        # ...
        try:
            counter, value = line.strip().split("=")
            counter = counter.strip()
            value = value.strip()
        except ValueError as e:
            self.log.error('Error parsing counter with line %s: %s', line, e)
            return None, None

        return counter, value

    @AgentCheck.metadata_entrypoint
    def submit_version(self, headers):
        version_header = headers.get("Server", "")
        if "/" not in version_header:
            self.log.debug("Squid version %s not valid version", version_header)
            return

        squid_version = version_header.split('/')[1]
        self.set_metadata(
            'version', squid_version, scheme='regex', final_scheme='semver', pattern=SQUID_VERSION_PATTERN
        )
        self.log.debug("Squid version %s metadata submitted")


text:
import IDocumentWriter from '../../documentWriter/IDocumentWriter';
import { AttributeNodePointer } from '../../domClone/Pointer';
import { ConcreteNode, NODE_TYPES } from '../../domFacade/ConcreteNode';
import DomFacade from '../../domFacade/DomFacade';
import INodesFactory from '../../nodesFactory/INodesFactory';
import QName from '../dataTypes/valueTypes/QName';
import {
	deletePu,
	insertAfter,
	insertAttributes,
	insertBefore,
	insertInto,
	insertIntoAsFirst,
	insertIntoAsLast,
	rename,
	replaceElementContent,
	replaceNode,
	replaceValue,
} from './applyPulPrimitives';
import { IPendingUpdate } from './IPendingUpdate';
import { DeletePendingUpdate } from './pendingUpdates/DeletePendingUpdate';
import { InsertAfterPendingUpdate } from './pendingUpdates/InsertAfterPendingUpdate';
import { InsertAttributesPendingUpdate } from './pendingUpdates/InsertAttributesPendingUpdate';
import { InsertBeforePendingUpdate } from './pendingUpdates/InsertBeforePendingUpdate';
import { InsertIntoAsFirstPendingUpdate } from './pendingUpdates/InsertIntoAsFirstPendingUpdate';
import { InsertIntoAsLastPendingUpdate } from './pendingUpdates/InsertIntoAsLastPendingUpdate';
import { InsertIntoPendingUpdate } from './pendingUpdates/InsertIntoPendingUpdate';
import { RenamePendingUpdate } from './pendingUpdates/RenamePendingUpdate';
import { ReplaceElementContentPendingUpdate } from './pendingUpdates/ReplaceElementContentPendingUpdate';
import { ReplaceNodePendingUpdate } from './pendingUpdates/ReplaceNodePendingUpdate';
import { ReplaceValuePendingUpdate } from './pendingUpdates/ReplaceValuePendingUpdate';
import { errXUDY0015, errXUDY0016, errXUDY0017, errXUDY0024 } from './XQueryUpdateFacilityErrors';

export const applyUpdates = (
	pul: IPendingUpdate[],
	_revalidationModule: any,
	_inheritNamespaces: any,
	domFacade: DomFacade,
	nodesFactory: INodesFactory,
	documentWriter: IDocumentWriter
) => {
	// 1. Checks the update primitives on $pul for compatibility using upd:compatibilityCheck.
	compatibilityCheck(pul, domFacade);

	// 2. The semantics of all update primitives on $pul, other than upd:put primitives, are made effective in the following order:
	// a. First, all upd:insertInto, upd:insertAttributes, upd:replaceValue, and upd:rename primitives are applied.
	pul.filter(
		(pu) => ['insertInto', 'insertAttributes', 'replaceValue', 'rename'].indexOf(pu.type) !== -1
	).forEach((pu) => {
		switch (pu.type) {
			case 'insertInto':
				const insertPu = pu as InsertIntoPendingUpdate;
				insertInto(insertPu.target, insertPu.content, documentWriter);
				break;
			case 'insertAttributes':
				const insertAttributesPu = pu as InsertAttributesPendingUpdate;
				insertAttributes(
					insertAttributesPu.target,
					insertAttributesPu.content,
					domFacade,
					documentWriter
				);
				break;
			case 'rename':
				const renamePu = pu as RenamePendingUpdate;
				rename(renamePu.target, renamePu.newName, domFacade, nodesFactory, documentWriter);
				break;
			case 'replaceValue':
				const replaceValuePu = pu as ReplaceValuePendingUpdate;
				replaceValue(
					replaceValuePu.target,
					replaceValuePu.stringValue,
					domFacade,
					documentWriter
				);
				break;
		}
	});

	// b. Next, all upd:insertBefore, upd:insertAfter, upd:insertIntoAsFirst, and upd:insertIntoAsLast primitives are applied.
	pul.filter(
		(pu) =>
			['insertBefore', 'insertAfter', 'insertIntoAsFirst', 'insertIntoAsLast'].indexOf(
				pu.type
			) !== -1
	).forEach((pu) => {
		switch (pu.type) {
			case 'insertAfter':
				const insertAfterPu = pu as InsertAfterPendingUpdate;
				insertAfter(insertAfterPu.target, insertAfterPu.content, domFacade, documentWriter);
				break;
			case 'insertBefore':
				const insertBeforePu = pu as InsertBeforePendingUpdate;
				insertBefore(
					insertBeforePu.target,
					insertBeforePu.content,
					domFacade,
					documentWriter
				);
				break;
			case 'insertIntoAsFirst':
				const insertAsFirstPu = pu as InsertIntoAsFirstPendingUpdate;
				insertIntoAsFirst(
					insertAsFirstPu.target,
					insertAsFirstPu.content,
					domFacade,
					documentWriter
				);
				break;
			case 'insertIntoAsLast':
				const insertAsLastPu = pu as InsertIntoAsLastPendingUpdate;
				insertIntoAsLast(insertAsLastPu.target, insertAsLastPu.content, documentWriter);
				break;
		}
	});

	// c. Next, all upd:replaceNode primitives are applied.
	pul.filter((pu) => pu.type === 'replaceNode').forEach((pu) => {
		const replacePu = pu as ReplaceNodePendingUpdate;
		replaceNode(replacePu.target, replacePu.replacement, domFacade, documentWriter);
	});

	// d. Next, all upd:replaceElementContent primitives are applied.
	pul.filter((pu) => pu.type === 'replaceElementContent').forEach((pu) => {
		const replacePu = pu as ReplaceElementContentPendingUpdate;
		replaceElementContent(replacePu.target, replacePu.text, domFacade, documentWriter);
	});

	// e. Next, all upd:delete primitives are applied.
	pul.filter((pu) => pu.type === 'delete').forEach((pu) => {
		const deletePendingUpdate = pu as DeletePendingUpdate;
		deletePu(deletePendingUpdate.target, domFacade, documentWriter);
	});

	// Point 3. to 7. are either not necessary or should be done by the caller.

	// 8. As the final step, all upd:put primitives on $pul are applied.
	if (pul.some((pu) => pu.type === 'put')) {
		throw new Error(
			'Not implemented: the execution for pendingUpdate "put" is not yet implemented.'
		);
	}
};

const compatibilityCheck = (pul: IPendingUpdate[], domFacade: DomFacade) => {
	function findDuplicateTargets(type: string, onFoundDuplicate: (node: ConcreteNode) => void) {
		const targets = new Set();
		pul.filter((pu) => pu.type === type)
			.map((pu) => pu.target)
			.forEach((target) => {
				const targetNode = target ? target.node : null;
				if (targets.has(targetNode)) {
					onFoundDuplicate(targetNode);
				}
				targets.add(targetNode);
			});
	}

	// A dynamic error if any of the following conditions are detected:

	// 1. Two or more upd:rename primitives in $pul have the same target node [err:XUDY0015].
	findDuplicateTargets('rename', (target) => {
		throw errXUDY0015(target);
	});

	// 2. Two or more upd:replaceNode primitives in $pul have the same target node [err:XUDY0016].
	findDuplicateTargets('replaceNode', (target) => {
		throw errXUDY0016(target);
	});

	// 3. Two or more upd:replaceValue primitives in $pul have the same target node [err:XUDY0017].
	findDuplicateTargets('replaceValue', (target) => {
		throw errXUDY0017(target);
	});

	// 4. Two or more upd:replaceElementContent primitives in $pul have the same target node [err:XUDY0017].
	findDuplicateTargets('replaceElementContent', (target) => {
		throw errXUDY0017(target);
	});

	// 5. Two or more upd:put primitives in $pul have the same $uri operand [err:XUDY0031].

	// 6. Two or more primitives in $pul create conflicting namespace bindings for the same element node [err:XUDY0024].
	// The following kinds of primitives create namespace bindings:
	const newQNamesByElement = new Map();
	const getAttributeName = (attribute: AttributeNodePointer) =>
		new QName(
			domFacade.getPrefix(attribute),
			domFacade.getNamespaceURI(attribute),
			domFacade.getLocalName(attribute)
		);
	// a. upd:insertAttributes creates one namespace binding on the $target element corresponding to
	//    the implied namespace binding of the name of each attribute node in $content.
	// b. upd:replaceNode creates one namespace binding on the $target element corresponding to the
	//    implied namespace binding of the name of each attribute node in $replacement.
	pul.filter(
		(pu) =>
			pu.type === 'replaceNode' &&
			domFacade.getNodeType(pu.target) === NODE_TYPES.ATTRIBUTE_NODE
	).forEach((pu: ReplaceNodePendingUpdate) => {
		const elementPointer = domFacade.getParentNodePointer(pu.target);
		const element = elementPointer ? elementPointer.node : null;
		const qNames = newQNamesByElement.get(element);
		if (qNames) {
			qNames.push(...pu.replacement.map(getAttributeName));
		} else {
			newQNamesByElement.set(element, pu.replacement.map(getAttributeName));
		}
	});
	// c. upd:rename creates a namespace binding on $target, or on the parent (if any) of $target if
	//    $target is an attribute node, corresponding to the implied namespace binding of $newName.
	pul.filter(
		(pu) =>
			pu.type === 'rename' && domFacade.getNodeType(pu.target) === NODE_TYPES.ATTRIBUTE_NODE
	).forEach((pu: RenamePendingUpdate) => {
		const elementPointer = domFacade.getParentNodePointer(pu.target);
		if (!elementPointer) {
			return;
		}
		const element = elementPointer.node;
		const qNames = newQNamesByElement.get(element);
		if (qNames) {
			qNames.push(pu.newName);
		} else {
			newQNamesByElement.set(element, [pu.newName]);
		}
	});

	newQNamesByElement.forEach((qNames, _element) => {
		const prefixes: { [prefix: string]: string } = {};
		qNames.forEach((qName: QName) => {
			if (!prefixes[qName.prefix]) {
				prefixes[qName.prefix] = qName.namespaceURI;
			}
			if (prefixes[qName.prefix] !== qName.namespaceURI) {
				throw errXUDY0024(qName.namespaceURI);
			}
		});
	});
};

export const mergeUpdates = (pul1: IPendingUpdate[], ...puls: IPendingUpdate[][]) => {
	return pul1.concat(...puls.filter(Boolean));
};