text:
/* @flow */

import { genHandlers } from './events'
import baseDirectives from '../directives/index'
import { camelize, no, extend } from 'shared/util'
import { baseWarn, pluckModuleFunction } from '../helpers'

type TransformFunction = (el: ASTElement, code: string) => string;
type DataGenFunction = (el: ASTElement) => string;
type DirectiveFunction = (el: ASTElement, dir: ASTDirective, warn: Function) => boolean;

export class CodegenState {
  options: CompilerOptions;
  warn: Function;
  transforms: Array<TransformFunction>;
  dataGenFns: Array<DataGenFunction>;
  directives: { [key: string]: DirectiveFunction };
  maybeComponent: (el: ASTElement) => boolean;
  onceId: number;
  staticRenderFns: Array<string>;

  constructor (options: CompilerOptions) {
    this.options = options
    this.warn = options.warn || baseWarn

    // web 平台下实例的属性 transforms 是空数组
    this.transforms = pluckModuleFunction(options.modules, 'transformCode')

    // 获取 动态绑定/静态 的 class/style 的值并拼接成字串
    this.dataGenFns = pluckModuleFunction(options.modules, 'genData')

    // baseDirectives 包括 on(v-on), bind(v-bind), cloak(v-cloak) 三个指令
    // options.directives 至少包括 model(v-model), html(v-html), text(v-text) 三个指令
    this.directives = extend(extend({}, baseDirectives), options.directives)

    const isReservedTag = options.isReservedTag || no
    this.maybeComponent = (el: ASTElement) => !isReservedTag(el.tag)

    this.onceId = 0
    this.staticRenderFns = []
  }
}

export type CodegenResult = {
  render: string,
  staticRenderFns: Array<string>
};

// 生成 render 字符串
export function generate (
  ast: ASTElement | void,
  options: CompilerOptions
): CodegenResult {
  const state = new CodegenState(options)
  const code = ast ? genElement(ast, state) : '_c("div")' // 若没有 ast 就创建一个空的div
  return {
    render: `with(this){return ${code}}`,
    staticRenderFns: state.staticRenderFns // 数组,用于存放渲染静态节点的函数
  }
}

export function genElement (el: ASTElement, state: CodegenState): string {
  if (el.staticRoot && !el.staticProcessed) {
    // 静态根节点
    return genStatic(el, state)
  } else if (el.once && !el.onceProcessed) {
    // v-once
    return genOnce(el, state)
  } else if (el.for && !el.forProcessed) {
    // v-for,el 上会多出属性 for/alias/iterator1/iterator2
    return genFor(el, state)
  } else if (el.if && !el.ifProcessed) {
    // v-if,会有 el.ifConditions 属性
    return genIf(el, state)
  } else if (el.tag === 'template' && !el.slotTarget) {
    return genChildren(el, state) || 'void 0'
  } else if (el.tag === 'slot') {
    return genSlot(el, state)
  } else {
    // component or element
    let code
    if (el.component) {
      // 处理动态组件(含 v-bind:is)的情况
      code = genComponent(el.component, el, state)
    } else {
      // 如果 el.plain 是 true,说明该结点没有属性
      const data = el.plain ? undefined : genData(el, state)
      // 不是内联模板的情况,会深度遍历子节点生成各元素节点的对应字串
      const children = el.inlineTemplate ? null : genChildren(el, state, true)
      // _c 即 createElement
      code = `_c('${el.tag}'${ // 元素标签名
        data ? `,${data}` : '' // data 元素上添加的属性,针对没有 data 的情况在 createElement 中会进行参数修正
      }${
        children ? `,${children}` : '' // children 子元素数组 + 子元素数组进行归一化处理的级别
      })`
    }
    // module transforms
    for (let i = 0; i < state.transforms.length; i++) {
      code = state.transforms[i](el, code)
    }
    return code
  }
}

// hoist static sub-trees out
// 生成静态节点的渲染字符串,因为静态节点不会发生变化,这部分提出来单独处理的
function genStatic (el: ASTElement, state: CodegenState): string {
  el.staticProcessed = true
  state.staticRenderFns.push(`with(this){return ${genElement(el, state)}}`)
  // _m 即 renderStatic
  return `_m(${
    state.staticRenderFns.length - 1 // staticRenderFns 中的索引,用于定位对应的渲染函数
  }${
    el.staticInFor ? ',true' : '' // 标记是否在 v-for 中
  })`
}

// v-once
function genOnce (el: ASTElement, state: CodegenState): string {
  el.onceProcessed = true
  if (el.if && !el.ifProcessed) {
    return genIf(el, state)
  } else if (el.staticInFor) {
    let key = ''
    let parent = el.parent
    while (parent) {
      if (parent.for) {
        key = parent.key
        break
      }
      parent = parent.parent
    }
    if (!key) {
      process.env.NODE_ENV !== 'production' && state.warn(
        `v-once can only be used inside v-for that is keyed. `
      )
      return genElement(el, state)
    }
    return `_o(${genElement(el, state)},${state.onceId++},${key})`
  } else {
    return genStatic(el, state)
  }
}

export function genIf (
  el: any,
  state: CodegenState,
  altGen?: Function,
  altEmpty?: string
): string {
  // 处理过的标志
  el.ifProcessed = true // avoid recursion
  return genIfConditions(el.ifConditions.slice(), state, altGen, altEmpty)
}

function genIfConditions (
  conditions: ASTIfConditions,
  state: CodegenState,
  altGen?: Function,
  altEmpty?: string
): string {
  // 没有表达式的(表达式数组都 pop 完了),返回空节点
  if (!conditions.length) {
    // _e 即 createEmptyVNode 创建一个空的 vnode 节点
    return altEmpty || '_e()'
  }
  // condition 含有属性 exp(表达式)/block(对应元素)
  const condition = conditions.shift()
  if (condition.exp) {
    return `(${condition.exp})?${
      // 表达式为真就开始生成元素了
      genTernaryExp(condition.block)
    }:${
      // 表达式为假就接着迭代判断剩下的表达式(即处理 v-else/v-else-if 时收集的表达式)
      genIfConditions(conditions, state, altGen, altEmpty)
    }`
  } else {
    return `${genTernaryExp(condition.block)}`
  }

  // v-if with v-once should generate code like (a)?_m(0):_m(1)
  function genTernaryExp (el) {
    return altGen
      ? altGen(el, state) // 有传入参数 altGen 的就用 altGen
      : el.once
        ? genOnce(el, state) // 有 v-once 的使用 genOnce
        : genElement(el, state) // 其它情形使用 genElement
  }
}

export function genFor (
  el: any,
  state: CodegenState,
  altGen?: Function,
  altHelper?: string
): string {
  const exp = el.for
  const alias = el.alias
  const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
  const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''

  if (process.env.NODE_ENV !== 'production' &&
    state.maybeComponent(el) &&
    el.tag !== 'slot' &&
    el.tag !== 'template' &&
    !el.key
  ) {
    state.warn(
      `<${el.tag} v-for="${alias} in ${exp}">: component lists rendered with ` +
      `v-for should have explicit keys. ` +
      `See https://vuejs.org/guide/list.html#key for more info.`,
      true /* tip */
    )
  }

  el.forProcessed = true // avoid recursion
  return `${altHelper || '_l'}((${exp}),` +
    `function(${alias}${iterator1}${iterator2}){` +
      `return ${(altGen || genElement)(el, state)}` +
    '})'
}

export function genData (el: ASTElement, state: CodegenState): string {
  let data = '{'

  // directives first.
  // directives may mutate the el's other properties before they are generated.
  // 指令可能会改变元素 el 的其它属性,因此优先处理指令
  const dirs = genDirectives(el, state)
  if (dirs) data += dirs + ','

  // key
  if (el.key) {
    data += `key:${el.key},`
  }
  // ref
  if (el.ref) {
    data += `ref:${el.ref},`
  }
  if (el.refInFor) {
    data += `refInFor:true,`
  }
  // pre
  if (el.pre) {
    data += `pre:true,`
  }
  // record original tag name for components using "is" attribute
  if (el.component) {
    data += `tag:"${el.tag}",`
  }
  // module data generation functions
  // class/style 相关的
  for (let i = 0; i < state.dataGenFns.length; i++) {
    data += state.dataGenFns[i](el)
  }
  // attributes
  if (el.attrs) {
    data += `attrs:{${genProps(el.attrs)}},`
  }
  // DOM props
  if (el.props) {
    data += `domProps:{${genProps(el.props)}},`
  }
  // event handlers
  if (el.events) {
    data += `${genHandlers(el.events, false, state.warn)},`
  }
  if (el.nativeEvents) {
    data += `${genHandlers(el.nativeEvents, true, state.warn)},`
  }
  // slot target
  // only for non-scoped slots
  if (el.slotTarget && !el.slotScope) {
    data += `slot:${el.slotTarget},`
  }
  // scoped slots
  if (el.scopedSlots) {
    data += `${genScopedSlots(el.scopedSlots, state)},`
  }
  // component v-model
  if (el.model) {
    data += `model:{value:${
      el.model.value
    },callback:${
      el.model.callback
    },expression:${
      el.model.expression
    }},`
  }
  // inline-template
  if (el.inlineTemplate) {
    const inlineTemplate = genInlineTemplate(el, state)
    if (inlineTemplate) {
      data += `${inlineTemplate},`
    }
  }
  data = data.replace(/,$/, '') + '}'
  // v-bind data wrap
  if (el.wrapData) {
    data = el.wrapData(data)
  }
  // v-on data wrap
  if (el.wrapListeners) {
    data = el.wrapListeners(data)
  }
  return data
}

function genDirectives (el: ASTElement, state: CodegenState): string | void {
  const dirs = el.directives
  if (!dirs) return
  let res = 'directives:['
  let hasRuntime = false
  let i, l, dir, needRuntime
  for (i = 0, l = dirs.length; i < l; i++) {
    dir = dirs[i]
    needRuntime = true
    const gen: DirectiveFunction = state.directives[dir.name]
    if (gen) {
      // compile-time directive that manipulates AST.
      // returns true if it also needs a runtime counterpart.
      needRuntime = !!gen(el, dir, state.warn)
    }
    if (needRuntime) {
      hasRuntime = true
      res += `{name:"${dir.name}",rawName:"${dir.rawName}"${
        dir.value ? `,value:(${dir.value}),expression:${JSON.stringify(dir.value)}` : ''
      }${
        dir.arg ? `,arg:"${dir.arg}"` : ''
      }${
        dir.modifiers ? `,modifiers:${JSON.stringify(dir.modifiers)}` : ''
      }},`
    }
  }
  if (hasRuntime) {
    // 去掉最后一个无用的 ',' 后包上 ']'
    return res.slice(0, -1) + ']'
  }
}

function genInlineTemplate (el: ASTElement, state: CodegenState): ?string {
  const ast = el.children[0]
  if (process.env.NODE_ENV !== 'production' && (
    el.children.length !== 1 || ast.type !== 1
  )) {
    state.warn('Inline-template components must have exactly one child element.')
  }
  if (ast.type === 1) {
    const inlineRenderFns = generate(ast, state.options)
    return `inlineTemplate:{render:function(){${
      inlineRenderFns.render
    }},staticRenderFns:[${
      inlineRenderFns.staticRenderFns.map(code => `function(){${code}}`).join(',')
    }]}`
  }
}

function genScopedSlots (
  slots: { [key: string]: ASTElement },
  state: CodegenState
): string {
  return `scopedSlots:_u([${
    Object.keys(slots).map(key => {
      return genScopedSlot(key, slots[key], state)
    }).join(',')
  }])`
}

function genScopedSlot (
  key: string,
  el: ASTElement,
  state: CodegenState
): string {
  if (el.for && !el.forProcessed) {
    return genForScopedSlot(key, el, state)
  }
  const fn = `function(${String(el.slotScope)}){` +
    `return ${el.tag === 'template'
      ? el.if
        ? `${el.if}?${genChildren(el, state) || 'undefined'}:undefined`
        : genChildren(el, state) || 'undefined'
      : genElement(el, state)
    }}`
  return `{key:${key},fn:${fn}}`
}

function genForScopedSlot (
  key: string,
  el: any,
  state: CodegenState
): string {
  const exp = el.for
  const alias = el.alias
  const iterator1 = el.iterator1 ? `,${el.iterator1}` : ''
  const iterator2 = el.iterator2 ? `,${el.iterator2}` : ''
  el.forProcessed = true // avoid recursion
  return `_l((${exp}),` +
    `function(${alias}${iterator1}${iterator2}){` +
      `return ${genScopedSlot(key, el, state)}` +
    '})'
}

export function genChildren (
  el: ASTElement,
  state: CodegenState,
  checkSkip?: boolean,
  altGenElement?: Function,
  altGenNode?: Function
): string | void {
  const children = el.children
  if (children.length) {
    // el 取当前第一个子元素
    const el: any = children[0]
    // optimize single v-for
    // 优化一波某元素的唯一子元素上使用了 v-for 指令的情况
    if (children.length === 1 && // 只有一个子元素
      el.for && // 且该子元素含有 v-for 指令
      el.tag !== 'template' && // 且该子元素不是 template 标签
      el.tag !== 'slot' // 且该子元素也不是 template 标签
    ) {
      return (altGenElement || genElement)(el, state)
    }
    const normalizationType = checkSkip
      ? getNormalizationType(children, state.maybeComponent)
      : 0
    const gen = altGenNode || genNode
    // 遍历子元素数组,执行 gen 方法,并拼接结果
    return `[${children.map(c => gen(c, state)).join(',')}]${
    // 传入子元素数组进行归一化处理的级别
      normalizationType ? `,${normalizationType}` : ''
    }`
  }
}

// determine the normalization needed for the children array.
// 0: no normalization needed 不需要归一化的处理
// 1: simple normalization needed (possible 1-level deep nested array) 简单归一化处理
// 2: full normalization needed 深度归一化处理
function getNormalizationType (
  children: Array<ASTNode>,
  maybeComponent: (el: ASTElement) => boolean
): number {
  let res = 0
  for (let i = 0; i < children.length; i++) {
    const el: ASTNode = children[i]
    if (el.type !== 1) {
      continue
    }
    if (needsNormalization(el) ||
        (el.ifConditions && el.ifConditions.some(c => needsNormalization(c.block)))) {
      res = 2
      break
    }
    if (maybeComponent(el) ||
        (el.ifConditions && el.ifConditions.some(c => maybeComponent(c.block)))) {
      res = 1
    }
  }
  return res
}

function needsNormalization (el: ASTElement): boolean {
  return el.for !== undefined || el.tag === 'template' || el.tag === 'slot'
}

function genNode (node: ASTNode, state: CodegenState): string {
  if (node.type === 1) {
    // 元素节点
    return genElement(node, state)
  } if (node.type === 3 && node.isComment) {
    // 文本节点,且判断出是注释
    return genComment(node)
  } else {
    // 文本节点,其内再区分是否含有表达式
    return genText(node)
  }
}

export function genText (text: ASTText | ASTExpression): string {
  return `_v(${text.type === 2
    // 含有表达式的节点
    ? text.expression // no need for () because already wrapped in _s()
    // 文本节点
    : transformSpecialNewlines(JSON.stringify(text.text))
  })`
}

export function genComment (comment: ASTText): string {
  return `_e(${JSON.stringify(comment.text)})`
}

function genSlot (el: ASTElement, state: CodegenState): string {
  const slotName = el.slotName || '"default"'
  const children = genChildren(el, state)
  let res = `_t(${slotName}${children ? `,${children}` : ''}`
  const attrs = el.attrs && `{${el.attrs.map(a => `${camelize(a.name)}:${a.value}`).join(',')}}`
  const bind = el.attrsMap['v-bind']
  if ((attrs || bind) && !children) {
    res += `,null`
  }
  if (attrs) {
    res += `,${attrs}`
  }
  if (bind) {
    res += `${attrs ? '' : ',null'},${bind}`
  }
  return res + ')'
}

// componentName is el.component, take it as argument to shun flow's pessimistic refinement
function genComponent (
  componentName: string,
  el: ASTElement,
  state: CodegenState
): string {
  const children = el.inlineTemplate ? null : genChildren(el, state, true)
  return `_c(${componentName},${genData(el, state)}${
    children ? `,${children}` : ''
  })`
}

// 把属性连接成字符串
function genProps (props: Array<{ name: string, value: any }>): string {
  let res = ''
  for (let i = 0; i < props.length; i++) {
    const prop = props[i]
    /* istanbul ignore if */
    if (__WEEX__) {
      res += `"${prop.name}":${generateValue(prop.value)},`
    } else {
      res += `"${prop.name}":${transformSpecialNewlines(prop.value)},`
    }
  }
  // 去掉最后一个无用的 ','
  return res.slice(0, -1)
}

/* istanbul ignore next */
function generateValue (value) {
  if (typeof value === 'string') {
    return transformSpecialNewlines(value)
  }
  return JSON.stringify(value)
}

// #3895, #4268
function transformSpecialNewlines (text: string): string {
  return text
    .replace(/\u2028/g, '\\u2028')
    .replace(/\u2029/g, '\\u2029')
}


text:
import unittest

from davies.survey_math import *

class MathTestCase(unittest.TestCase):

    def assertSequenceAlmostEqual(self, first, second, places=None, msg=None, delta=None):
        """Fail if the contents of two sequences are not "almost equal"."""
        if first == second:
            return True
        self.assertEqual(len(first), len(second))
        for one, two in zip(first, second):
            self.assertAlmostEqual(one, two, places, msg, delta)

class HorizontalDistanceTest(unittest.TestCase):

    def test1(self):
        self.assertAlmostEqual(hd(0, 100), 100, msg='horizontal distance of a horizontal shot should be 100%')

    def test2(self):
        self.assertAlmostEqual(hd(90, 100), 0, msg='horizontal distance of a plumb-up should be zero')

    def test3(self):
        self.assertAlmostEqual(hd(-90, 100), 0, msg='horizontal distance of a plumb-down should be zero')

class VerticalDistanceTest(unittest.TestCase):

    def test1(self):
        self.assertAlmostEqual(vd(90, 100), 100, msg='vertical distance of a plumb-up should be 100%')

    def test2(self):
        self.assertAlmostEqual(vd(0, 100), 0, msg='vertical distance of a horizontal shot should be zero')

    def test3(self):
        # TODO: or should it be NEGATIVE?!
        self.assertAlmostEqual(vd(-90, 100), 100, msg='vertical distance of a plumb-down should be 100%')

class AngleDeltaTest(unittest.TestCase):

    def test1(self):
        self.assertEqual(angle_delta(359, 0), 1)
        self.assertEqual(angle_delta(0, 359), 1)

    def test2(self):
        self.assertEqual(angle_delta(90, 270), 180)
        self.assertEqual(angle_delta(270, 90), 180)

class CartesianOffsetTest(MathTestCase):
    leg = (100**2/2)**0.5  # pythagorean theorem: leg of 45-deg triangle with hypotenuse of len 100

    def test1(self):
        self.assertSequenceAlmostEqual(cartesian_offset(0, 0, 100), (0, 100), msg='horizontal north')

    def test2(self):
        self.assertSequenceAlmostEqual(cartesian_offset(90, 0, 100), (100, 0), msg='horizontal east')

    def test3(self):
        self.assertSequenceAlmostEqual(cartesian_offset(180, 0, 100), (0, -100), msg='horizontal south')

    def test4(self):
        self.assertSequenceAlmostEqual(cartesian_offset(270, 0, 100), (-100, 0), msg='horizontal west')

    def test5(self):
        self.assertSequenceAlmostEqual(cartesian_offset(0, 90, 100), (0, 0), msg='plumb up')

    def test6(self):
        self.assertSequenceAlmostEqual(cartesian_offset(0, -90, 100), (0, 0), msg='plumb down')

    def test7(self):
        self.assertSequenceAlmostEqual(cartesian_offset(45, 0, 100), (self.leg, self.leg), msg='horizontal at 45azm')

    def test8(self):
        self.assertSequenceAlmostEqual(cartesian_offset(180+45, 0, 100), (-self.leg, -self.leg), msg='horizontal at 125azm')

    def test9(self):
        self.assertSequenceAlmostEqual(cartesian_offset(0, 45, 100), (0, self.leg), msg='high angle north')

class UnitConversionTest(MathTestCase):

    def test_m2ft(self):
        self.assertEqual(m2ft(100), 328.084)

    def test_ft2m(self):
        self.assertEqual(ft2m(100), 30.48)

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var helpers = require('yeoman-generator').test;
var assert = _.extend({}, require('yeoman-generator').assert);

var run = function(components, done) {
  helpers.run(path.join( __dirname, '../app'))
    .inDir(path.join( __dirname, './tmp'))
    .withOptions({ 'skip-install': true })
    .withPrompt({ name: 'caribou-app' })
    .withPrompt({ components: components })
    .onEnd(done);
};

var projectFiles = [
  '.bowerrc',
  '.jshintrc',
  '.gitignore',
  'bower.json',
  'package.json',
  'gulpfile.js',
  'karma.conf.js'
];

var appFiles = [
  'app/media/caribou.png',
  'app/scripts/application.js',
  'app/scripts/vendor.json',
  'app/styles/application.scss',
  'app/styles/caribou.scss',
  'app/styles/vendor.scss',
  'app/index.html',
  'test/app_helper.js',
  'test/app/test.js',
  'test/fixtures/example.json'
];

var serverFiles = [
  'server/config/env/base.js',
  'server/config/env/development.js',
  'server/config/env/production.js',
  'server/config/env/staging.js',
  'server/config/index.js',
  'server/application.js',
  'test/server_helper.js',
  'test/server/test.js'
];

assert.fileMatches = function(file, fixture) {
  assert.textEqual(
    fs.readFileSync(file, 'utf8'),
    fs.readFileSync(fixture, 'utf8'));
};

describe('caribou', function() {
  describe('full-stack', function() {
    before(function(done) { run(['jquery', 'bootstrap', 'ember', 'server'], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles, serverFiles));
      assert.noFile([]);
    });

    it('creates expected gulpfile.js', function() {
      assert.fileMatches('gulpfile.js', path.join(__dirname,
        'expected/gulpfile.full-stack.js'));
    });

    it('includes jquery', function() {
      assert.fileContent('bower.json', /jquery/);
      assert.fileContent('app/scripts/vendor.json', /jquery/);
    });

    it('includes bootstrap', function() {
      assert.fileContent('bower.json', /bootstrap/);
      assert.fileContent('app/scripts/vendor.json', /bootstrap/);
      assert.fileContent('app/styles/vendor.scss', /bootstrap/);
    });

    it('includes ember', function() {
      assert.fileContent('bower.json', /ember/);
      assert.fileContent('app/scripts/vendor.json', /ember/);
      assert.fileContent('test/app_helper.js', /ember/);
    });
  });

  describe('minimal', function() {
    before(function(done) { run([], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles));
      assert.noFile([].concat(serverFiles));
    });

    it('does not include jquery', function() {
      assert.noFileContent('bower.json', /jquery/);
      assert.noFileContent('app/scripts/vendor.json', /jquery/);
    });

    it('does not include bootstrap', function() {
      assert.noFileContent('bower.json', /bootstrap/);
      assert.noFileContent('app/scripts/vendor.json', /bootstrap/);
      assert.noFileContent('app/styles/vendor.scss', /bootstrap/);
    });

    it('does not include ember', function() {
      assert.noFileContent('bower.json', /ember/);
      assert.noFileContent('app/scripts/vendor.json', /ember/);
    });

    it('does not include server', function() {
      assert.noFileContent('gulpfile.js', /server/);
    });
  });

  describe('ember-only', function() {
    before(function(done) { run(['jquery', 'ember'], done); });

    it('creates expected files', function() {
      assert.file([].concat(projectFiles, appFiles));
      assert.noFile([].concat(serverFiles));
    });

    it('does not include bootstrap', function() {
      assert.noFileContent('bower.json', /bootstrap/);
      assert.noFileContent('app/scripts/vendor.json', /bootstrap/);
    });

    it('includes jquery', function() {
      assert.fileContent('bower.json', /jquery/);
      assert.fileContent('app/scripts/vendor.json', /jquery/);
    });

    it('includes ember', function() {
      assert.fileContent('bower.json', /ember/);
      assert.fileContent('app/scripts/vendor.json', /ember/);
    });
  });
});


text:
/*
    Calimero - A library for KNX network access
    Copyright (C) 2006-2008 B. Malinowsky

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or at your option any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

    Linking this library statically or dynamically with other modules is
    making a combined work based on this library. Thus, the terms and
    conditions of the GNU General Public License cover the whole
    combination.

    As a special exception, the copyright holders of this library give you
    permission to link this library with independent modules to produce an
    executable, regardless of the license terms of these independent
    modules, and to copy and distribute the resulting executable under terms
    of your choice, provided that you also meet, for each linked independent
    module, the terms and conditions of the license of that module. An
    independent module is a module which is not derived from or based on
    this library. If you modify this library, you may extend this exception
    to your version of the library, but you are not obligated to do so. If
    you do not wish to do so, delete this exception statement from your
    version.
*/

package tuwien.auto.calimero;

import java.util.EventListener;

/**
 * The base listener interface to receive events of the communication with a KNX
 * network.
 *

 */
public interface KNXListener extends EventListener
{
	/**
	 * Arrival of a new KNX message frame.
	 *

	 *
	 * @param e frame event object
	 */
	void frameReceived(FrameEvent e);

	/**
	 * The connection has been closed.
	 *

	 *
	 * @param e connection close event object
	 */
	void connectionClosed(CloseEvent e);
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
       bean-discovery-mode="all">
<!--    -->
<!--    <interceptors>-->
<!--       <class>org.nemanjamarjanovic.rekomendator.bussines.log.control.MethodLog</class>-->
<!--   </interceptors>-->
</beans>


text:
Home

Contact

Newsletter


text:
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Route.css';

import Icon from '../../components/Material/Icon'
import Slider from '../../components/Material/Slider'
const title = 'React Starter Kit';

function Route({}, context) {
  context.setTitle(title);
  return (

 Sliders

                A slider should be discreet, and may contain a label to describe
                what it's manipulating and another label to describe the value. Label
                Text should be centered against the control.

                There should be two modes. One in which the slider control moves only to
                the ends of the segments, and one where the slider control may move anywhere
                along each segement (infinite).

                Slider control should be customizable in size, and have a component above
                or below the the control itself that acts as the control. this control should
                be customizable by the user.

            <Slider/>

  );
}

Route.propTypes = {
};
Route.contextTypes = { setTitle: PropTypes.func.isRequired };

export default withStyles(s)(Route);


text:
<html>
<head>
<title>
Pizza Applet
</title>
</head>
<body bgcolor="green">
<applet code=PizzaApplet.class width=300 height=250>
</applet>
</body>
</html>


text:
using GRA.SRP.DAL;
using SRPApp.Classes;
using System;

namespace GRA.SRP {
    public partial class NotFound : BaseSRPPage {
        protected void Page_Load(object sender, EventArgs e) {
            if(!IsPostBack) {
                TranslateStrings(this);

                try {
                    string contactEmail = SRPSettings.GetSettingValue("ContactEmail");
                    if(!string.IsNullOrEmpty(contactEmail)) {
                        AlternateContact.Text = string.Format("If you continue to have issues, you can send an email to {0}.",
                                                              contactEmail);
                    }
                } catch(Exception ex) {
                    try {
                        this.Log().Error("An error occurred showing the not found page: {0}",
                                         ex.Message);
                    } catch(Exception) {

                    }
                }
            }
        }
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
  <meta name="content-language" content="en-AU" />
  <title>Adjax demonstration</title>
  <link rel="stylesheet" type="text/css" href="{{ MEDIA_URL }}/css/screen.css" media="screen" />

Adjax

{% block content %}
{% endblock %}

Hardy Software

  {% block javascript %}
  {% endblock %}


text:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="DEBUG"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="[%-5p] %d [%t] %c - %m%n"/>
        </layout>
    </appender>

    <logger name="esride.opendatabridge">
        <level value="DEBUG"/>
    </logger>

    <!-- Just for HTTP Logging  -->
    <logger name="org.apache.http">
        <level value="DEBUG"/>
    </logger>

    <root>
        <level value="WARN"/>
        <appender-ref ref="CONSOLE"/>
    </root>
</log4j:configuration>


text:
#pragma once

#include <string>
#include <sstream>
#include <stdarg.h>

#include <vector>
#include <map>
#include <queue>

#include "vendor/json/json.h"

#include "ScriptingManager.hpp"

#include "RenderTypes.hpp"

namespace Engine {
    namespace Platform {
        ENGINE_CLASS(Mutex);
    }

    typedef EventMagic (*EventTargetFunc)(Json::Value e, void* userPointer);

    ENGINE_CLASS(EventTarget);

    class EventTarget {
    public:
        enum class Type {
            Invalid,
            CPlusPlus,
            Javascript
        };

        virtual ~EventTarget() {}

        virtual EventMagic Run(Json::Value& e) = 0;

        virtual bool IsScript() { return true; }
        virtual Type GetType() { return Type::Invalid; }
    };

    struct Event {
        std::string Label;
        EventTarget* Target = NULL;
        bool Active = false;

        Event() : Label(""), Active(false) {}
        Event(std::string Label, EventTarget* target) : Label(Label), Target(target), Active(true) { }
        };

    struct EventClassSecurity {
        bool NoScript = false;

        std::string ToString() {
            std::stringstream ss;
            ss << "NoScript=" << this->NoScript;
            return ss.str();
        }
    };

    ENGINE_CLASS(EventClass);

    class EventClass {
    public:
        size_t GetDeferedMessageCount();
        void LogEvents(std::string logName);
        EventMagic Emit(Json::Value args, int jsArgC, v8::Handle<v8::Value> jsArgV[]);
        EventMagic Emit(Json::Value args);
        EventMagic Emit();

        EventClassPtr AddListener(size_t priority, std::string name, EventTarget* target);
        EventClassPtr AddListener(std::string name, EventTargetPtr target);

        void Clear(std::string eventID);
        EventClassPtr SetDefered(bool defered);
        EventClassPtr SetNoScript(bool noScript);
        void PollDeferedMessages();
        void AddDeferedMessage(Json::Value e);

        int ListenerCount();

        std::string TargetName;
        EventClassSecurity Security;
    private:
        bool _alwaysDefered = false;
        std::multimap<size_t, Event> _events;
        std::queue<Json::Value> _deferedMessages;
    };

    typedef EventClass*& EventClassPtrRef;

    ENGINE_CLASS(EventEmitter);

    class EventEmitter {
    public:
        EventEmitter();

        EventClassPtrRef GetEvent(std::string eventName);

        void Clear(std::string eventID);

        void PollDeferedMessages();
        void PollDeferedMessages(std::string eventName);
        void EmitThread(std::string threadID, std::string evnt, Json::Value e);

        static EventTargetPtr MakeTarget(EventTargetFunc target);
        static EventTargetPtr MakeTarget(EventTargetFunc target, void* userPointer);
        static EventTargetPtr MakeTarget(v8::Handle<v8::Function> target);

    private:
        static EventMagic _debug(Json::Value args, void* userPointer);

        Platform::MutexPtr _eventMutex;
        std::unordered_map<std::string, EventClassPtr> _events;

        int lastEventID = 0;
    };

    EventEmitterPtr GetEventsSingilton();
}


text:
struct Collection: public std::vector<std::shared_ptr<Item>> {

    using ItemMap = std::map<std::string, std::shared_ptr<Item>>;

    Collection(const std::vector<std::string> &);

    size_type currentIndex() const;
    Item & current();

    void previous();
    void next();

private:

    void addItem(const std::string &);

    ItemMap topLevelItems_;
    size_type currentIdx_;

};


text:
#include "animatedtext.h"
#include "map.h"
#include "game.h"
#include <framework/core/clock.h>
#include <framework/core/eventdispatcher.h>
#include <framework/graphics/graphics.h>

AnimatedText::AnimatedText()
{
    m_cachedText.setFont(g_fonts.getFont("verdana-11px-rounded"));
    m_cachedText.setAlign(Fw::AlignLeft);
}

void AnimatedText::drawText(const Point& dest, const Rect& visibleRect)
{
    static float tf = Otc::ANIMATED_TEXT_DURATION;
    static float tftf = Otc::ANIMATED_TEXT_DURATION * Otc::ANIMATED_TEXT_DURATION;

    Point p = dest;
    Size textSize = m_cachedText.getTextSize();
    float t = m_animationTimer.ticksElapsed();
    p.x += (24 - textSize.width() / 2);

    if(g_game.getFeature(Otc::GameDiagonalAnimatedText)) {
        p.x -= (4 * t / tf) + (8 * t * t / tftf);
    }

    p.y += 8 + (-48 * t) / tf;
    p += m_offset;
    Rect rect(p, textSize);

    if(visibleRect.contains(rect)) {
        //TODO: cache into a framebuffer
        float t0 = tf / 1.2;
        if(t > t0) {
            Color color = m_color;
            color.setAlpha((float)(1 - (t - t0) / (tf - t0)));
            g_painter->setColor(color);
        }
        else
            g_painter->setColor(m_color);
        m_cachedText.draw(rect);
    }
}

void AnimatedText::onAppear()
{
    m_animationTimer.restart();

    // schedule removal
    auto self = asAnimatedText();
    g_dispatcher.scheduleEvent([self]() { g_map.removeThing(self); }, Otc::ANIMATED_TEXT_DURATION);
}

void AnimatedText::setColor(int color)
{
    m_color = Color::from8bit(color);
}

void AnimatedText::setText(const std::string& text)
{
    m_cachedText.setText(text);
}

bool AnimatedText::merge(const AnimatedTextPtr& other)
{
    if(other->getColor() != m_color)
        return false;

    if(other->getCachedText().getFont() != m_cachedText.getFont())
        return false;

    if(m_animationTimer.ticksElapsed() > Otc::ANIMATED_TEXT_DURATION / 2.5)
        return false;

    try {
        int number = stdext::safe_cast<int>(m_cachedText.getText());
        int otherNumber = stdext::safe_cast<int>(other->getCachedText().getText());

        std::string text = stdext::format("%d", number + otherNumber);
        m_cachedText.setText(text);
        return true;
    }
    catch(...) {
        return false;
    }
}


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

<TITLE>
Indirect (POI API Documentation)
</TITLE>

<META NAME="keywords" CONTENT="org.apache.poi.hssf.record.formula.functions.Indirect class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

org.apache.poi.hssf.record.formula.functions

Class Indirect

java.lang.Object
  org.apache.poi.hssf.record.formula.functions.Indirect

All Implemented Interfaces:
FreeRefFunction

public final class Indirect
extends java.lang.Object
implements FreeRefFunction

Implementation for Excel function INDIRECT

 INDIRECT() returns the cell or area reference denoted by the text argument.

 Syntax:

 INDIRECT(ref_text,isA1Style)

 ref_text a string representation of the desired reference as it would normally be written
 in a cell formula.

 isA1Style (default TRUE) specifies whether the ref_text should be interpreted as A1-style
 or R1C1-style.

Author:

Josh Micich

Constructor Summary

Indirect()

Method Summary

 ValueEval
evaluate(Eval[] args,
         int srcCellRow,
         short srcCellCol,
         HSSFWorkbook workbook,
         HSSFSheet sheet)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

Indirect

public Indirect()

Method Detail

evaluate

public ValueEval evaluate(Eval[] args,
                          int srcCellRow,
                          short srcCellCol,
                          HSSFWorkbook workbook,
                          HSSFSheet sheet)

Specified by:
evaluate in interface FreeRefFunction

Parameters:
args - the pre-evaluated arguments for this function. args is never null,
                  nor are any of its elements.
srcCellRow - zero based row index of the cell containing the currently evaluating formula
srcCellCol - zero based column index of the cell containing the currently evaluating formula
workbook - is the workbook containing the formula/cell being evaluated
sheet - is the sheet containing the formula/cell being evaluated

Returns:
never null. Possibly an instance of <tt>ErrorEval</tt> in the case of
 a specified Excel error (Exceptions are never thrown to represent Excel errors).

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

        Copyright 2008 The Apache Software Foundation or
        its licensors, as applicable.


text:
package com.liubo.demo.redis.service;

import com.liubo.demo.redis.model.User;

/**
 * Created by Administrator on 2016/5/13.
 */

public interface UserService {

    /**
     *查询用户信息
     * @param userId
     * @return
     */
    public User getUserById(String userId);

    /**
     * 更新用户信息
     * @param user
     * @return
     */
    public  boolean modifyUser(User user);

}


text:
package com.matthewmitchell.nubitsj.testing;

import com.google.common.base.*;
import com.google.common.util.concurrent.*;
import com.matthewmitchell.nubitsj.core.*;
import com.matthewmitchell.nubitsj.net.*;
import com.matthewmitchell.nubitsj.store.*;
import com.matthewmitchell.nubitsj.utils.*;

import java.net.*;
import java.util.concurrent.*;

import static com.google.common.base.Preconditions.*;

/**
 * You can derive from this class and call peerGroup.start() in your tests to get a functional PeerGroup that can be
 * used with loopback peers created using connectPeer. This involves real TCP connections so is a pretty accurate
 * mock, but means unit tests cannot be run simultaneously.
 */
public class TestWithPeerGroup extends TestWithNetworkConnections {
    protected PeerGroup peerGroup;

    protected VersionMessage remoteVersionMessage;
    private final ClientType clientType;

    public TestWithPeerGroup(ClientType clientType) {
        super(clientType);
        if (clientType != ClientType.NIO_CLIENT_MANAGER && clientType != ClientType.BLOCKING_CLIENT_MANAGER)
            throw new RuntimeException();
        this.clientType = clientType;
    }

    @Override
    public void setUp() throws Exception {
        setUp(new MemoryBlockStore(params));
    }

    @Override
    public void setUp(BlockStore blockStore) throws Exception {
        super.setUp(blockStore);

        remoteVersionMessage = new VersionMessage(params, 1);
        remoteVersionMessage.localServices = VersionMessage.NODE_NETWORK;
        remoteVersionMessage.clientVersion = NotFoundMessage.MIN_PROTOCOL_VERSION;
        blockJobs = false;
        initPeerGroup();
    }

    @Override
    public void tearDown() {
        try {
            super.tearDown();
            blockJobs = false;
            Utils.finishMockSleep();
            if (peerGroup.isRunning())
                peerGroup.stopAsync();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    protected void initPeerGroup() {
        if (clientType == ClientType.NIO_CLIENT_MANAGER)
            peerGroup = createPeerGroup(new NioClientManager());
        else
            peerGroup = createPeerGroup(new BlockingClientManager());
        peerGroup.setPingIntervalMsec(0);  // Disable the pings as they just get in the way of most tests.
        peerGroup.addWallet(wallet);
        peerGroup.setUseLocalhostPeerWhenPossible(false); // Prevents from connecting to nubits nodes on localhost.
    }

    protected boolean blockJobs = false;
    protected final Semaphore jobBlocks = new Semaphore(0);

    private PeerGroup createPeerGroup(final ClientConnectionManager manager) {
        return new PeerGroup(params, blockChain, manager) {
            @Override
            protected ListeningScheduledExecutorService createPrivateExecutor() {
                return MoreExecutors.listeningDecorator(new ScheduledThreadPoolExecutor(1, new ContextPropagatingThreadFactory("PeerGroup test thread")) {
                    @Override
                    public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) {
                        if (!blockJobs)
                            return super.schedule(command, delay, unit);
                        return super.schedule(new Runnable() {
                            @Override
                            public void run() {
                                Utils.rollMockClockMillis(unit.toMillis(delay));
                                command.run();
                                jobBlocks.acquireUninterruptibly();
                            }
                        }, 0 /* immediate */, unit);
                    }
                });
            }
        };
    }

    protected InboundMessageQueuer connectPeerWithoutVersionExchange(int id) throws Exception {
        Preconditions.checkArgument(id < PEER_SERVERS);
        InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", 2000 + id);
        Peer peer = peerGroup.connectTo(remoteAddress).getConnectionOpenFuture().get();
        InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take();
        writeTarget.peer = peer;
        return writeTarget;
    }

    protected InboundMessageQueuer connectPeer(int id) throws Exception {
        return connectPeer(id, remoteVersionMessage);
    }

    protected InboundMessageQueuer connectPeer(int id, VersionMessage versionMessage) throws Exception {
        checkArgument(versionMessage.hasBlockChain());
        InboundMessageQueuer writeTarget = connectPeerWithoutVersionExchange(id);
        // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter
        writeTarget.sendMessage(versionMessage);
        writeTarget.sendMessage(new VersionAck());
        stepThroughInit(versionMessage, writeTarget);
        return writeTarget;
    }

    // handle peer discovered by PeerGroup
    protected InboundMessageQueuer handleConnectToPeer(int id) throws Exception {
        return handleConnectToPeer(id, remoteVersionMessage);
    }

    // handle peer discovered by PeerGroup
    protected InboundMessageQueuer handleConnectToPeer(int id, VersionMessage versionMessage) throws Exception {
        InboundMessageQueuer writeTarget = newPeerWriteTargetQueue.take();
        checkArgument(versionMessage.hasBlockChain());
        // Complete handshake with the peer - send/receive version(ack)s, receive bloom filter
        writeTarget.sendMessage(versionMessage);
        writeTarget.sendMessage(new VersionAck());
        stepThroughInit(versionMessage, writeTarget);
        return writeTarget;
    }

    private void stepThroughInit(VersionMessage versionMessage, InboundMessageQueuer writeTarget) throws InterruptedException {
        checkState(writeTarget.nextMessageBlocking() instanceof VersionMessage);
        checkState(writeTarget.nextMessageBlocking() instanceof VersionAck);
        if (versionMessage.isBloomFilteringSupported()) {
            checkState(writeTarget.nextMessageBlocking() instanceof BloomFilter);
            checkState(writeTarget.nextMessageBlocking() instanceof MemoryPoolMessage);
        }
    }
}


text:
set -e

# provider specific
export PROVIDER="kvm"

"$PORTAL_APP_REPO_FOLDER/cloud_portal/shared/deploy.sh"


text:
"""

Copyright (c) 2015 Civic Knowledge. This file is licensed under the terms of the
Revised BSD License, included in this distribution as LICENSE.txt
"""

from  .__meta__ import __version__, __author__

from .fetch import get_source, import_source, download, extract_file_from_zip
from .sources.spec import ColumnSpec, SourceSpec
from .mpf import MPRowsFile
from .sources import RowProxy

import logging

# FORMAT = '%(asctime)-15s %(clientip)s %(user)-8s %(message)s'
logging.basicConfig()

if __name__ == "__main__":
    from .cli import main
    main()

# Some utilities

def head(iterable, n ):
    """Return a list of the first N rows from the iterable"""
    from itertools import islice
    return list(islice(iterable, n))

def tail(iterable, n):
    import collections
    "Return an iterator over the last n items"
    # tail(3, 'ABCDEFG') --> E F G
    return list(iter(collections.deque(iterable, maxlen=n)))


text:
<?php
/**
 * Класс формы для сообщения об ошибке
 *
 * @category YupeFormModel
 * @package  yupe.modules.yupe.models
 * @author   AKulikov <tuxuls@gmail.com>
 * @license  BSD http://ru.wikipedia.org/wiki/%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F_BSD
 * @version  0.5.3
 * @link     http://yupe.ru
 *
 **/
namespace yupe\models;

use Yii;

class BugForm extends YFormModel
{
    const OTHER_MODULE = 0;

    public $module;
    public $subject;
    public $message;
    public $sendTo;

    /**
     * Правила валидации:
     *
     * @return array of validation rules
     **/
    public function rules()
    {
        return array(
            array('module, subject, message, sendTo', 'required'),
            array('sendTo','email'),
            array('subject', 'length', 'min' => 6, 'max' => 256),
            array('message', 'length', 'min' => 20),
        );
    }

    /**
     * Получаем атрибуты полей
     *
     * @return array of attributes labels
     */
    public function attributeLabels()
    {
        return array(
            'module'  => Yii::t('YupeModule.yupe', 'Module'),
            'subject' => Yii::t('YupeModule.yupe', 'Theme'),
            'message' => Yii::t('YupeModule.yupe', 'Error description'),
            'sendTo'  => Yii::t('YupeModule.yupe', 'Send to'),
        );
    }

    /**
     * Получаем описания полей
     *
     * @return array of attributes description
     */
    public function attributeDescriptions()
    {
        return array(
            'module'  => Yii::t('YupeModule.yupe', 'You must select module in which error was found. If error located not in module you must choose "other" and specify component name in topic/description'),
            'subject' => Yii::t('YupeModule.yupe', 'Please type in short form information about error. In which module/component/widget/etc. it was found.'),
            'message' => Yii::t('YupeModule.yupe', 'Please type detailed information about error. How we can reproduce it? In which platform or software version you found it? Other information what can help us. Also you can propose decision of this problem.'),
            'sendTo'  => Yii::t('YupeModule.yupe', 'Please select receiver for this error report'),
        );
    }

    /**
     * Список модулей
     *
     * @return array listing modules
     **/
    public function getModuleList()
    {
        $modulesList = array(
            self::OTHER_MODULE => Yii::t('YupeModule.yupe','Other'),
        );

        foreach (Yii::app()->modules as $key => $value) {
            $key = strtolower($key);

            if (!Yii::app()->hasModule($key) || ($module = Yii::app()->getModule($key)) === null) {
                continue;
            }

            $modulesList[$key] = $module->name . ' (' . $module->version . ')';
        }

        return $modulesList;
    }

    /**
     * Список получателей
     *
     * @return array listing recipients
     **/
    public function getSendToList()
    {
        return array(
            'team@yupe.ru' => Yii::t('YupeModule.yupe', 'Yupe development team!'),
        );
    }
}


text:
#ifdef USE_TI_UITAB

#import "TiProxy.h"
#import "TiUITabProxy.h"
#import "TiUIViewProxy.h"
#import "TiWindowProxy.h"
#import "TiUITabController.h"
#import "TiUITabGroupProxy.h"
#import "TiUtils.h"
#import "ImageLoader.h"
#import "TiApp.h"

//NOTE: this proxy is a little different than normal Proxy/View pattern
//since it's not really backed by a view in the normal way.  It's given
//a root level window proxy (and view) that are passed as the root controller
//to the Nav Controller.  So, we do a few things that you'd normally not
//have to do in a Proxy/View pattern.

@interface TiUITabProxy ()
-(void)openOnUIThread:(NSArray*)args;
@end

@implementation TiUITabProxy

-(void)_destroy
{
    RELEASE_TO_NIL(closingWindows);
    RELEASE_TO_NIL(controllerStack);
	RELEASE_TO_NIL(rootController);
    RELEASE_TO_NIL(controller);
	RELEASE_TO_NIL(current);
	[super _destroy];
}

-(NSMutableDictionary*)langConversionTable
{
    return [NSMutableDictionary dictionaryWithObject:@"title" forKey:@"titleid"];
}

-(void)_configure
{
	// since we're special proxy type instead of normal, we force in values
	[self replaceValue:nil forKey:@"title" notification:NO];
	[self replaceValue:nil forKey:@"icon" notification:NO];
	[self replaceValue:nil forKey:@"badge" notification:NO];
	[super _configure];
}

-(TiUITabController *)rootController
{
	if (rootController == nil)
	{
		TiWindowProxy *window = [self valueForKey:@"window"];
		[window setParentOrientationController:self];
		rootController = [[TiUITabController alloc] initWithProxy:window tab:self];
	}
	return rootController;
}

-(UINavigationController*)controller
{
	if (controller==nil)
	{
		controller = [[UINavigationController alloc] initWithRootViewController:[self rootController]];
		controller.delegate = self;
		[self setTitle:[self valueForKey:@"title"]];
		[self setIcon:[self valueForKey:@"icon"]];
		[self setBadge:[self valueForKey:@"badge"]];
	}
	return controller;
}

-(void)setTabGroup:(TiUITabGroupProxy*)proxy
{
	if (proxy == tabGroup)
	{
		return;
	}
	for (TiViewController * thisController in [controller viewControllers])
	{
		if (![thisController isKindOfClass:[TiViewController class]])
		{
			continue;
		}
		[(TiWindowProxy *)[thisController proxy] _associateTab:nil navBar:nil tab:nil];
	}
	tabGroup = proxy;
}

-(void) cleanNavStack:(BOOL)removeTab
{
    TiThreadPerformOnMainThread(^{
        [controller setDelegate:nil];
        if ([[controller viewControllers] count] > 1) {
            NSMutableArray* doomedVcs = [[NSMutableArray arrayWithArray:[controller viewControllers]] retain];
            [doomedVcs removeObject:rootController];
            [controller setViewControllers:[NSArray arrayWithObject:rootController]];
            if (current != nil) {
                RELEASE_TO_NIL(current);
                current = [rootController retain];
            }
            for (TiUITabController* doomedVc in doomedVcs) {
                [self closeWindow:(TiWindowProxy *)[doomedVc proxy] animated:NO];
            }
            RELEASE_TO_NIL(doomedVcs);
        }
        if (removeTab) {
            [self closeWindow:[rootController window] animated:NO];
            RELEASE_TO_NIL(rootController);
            RELEASE_TO_NIL(controller);
            RELEASE_TO_NIL(current);
        }
        else {
            [controller setDelegate:self];
        }
    },YES);
}

-(void)removeFromTabGroup
{
    [self setActive:NUMBOOL(NO)];
    [self cleanNavStack:YES];
}

- (void)handleWillShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	BOOL safeToTransition = YES;
	if (current!=nil)
	{
		TiWindowProxy *currentWindow = [current window];

		[currentWindow _tabBeforeBlur];
		[[currentWindow retain] autorelease];

		// close the window if it's not our root window
		// check to make sure that we're not actually push a window on the stack
		if (opening==NO && [rootController window]!=currentWindow && [TiUtils boolValue:currentWindow.opened] && currentWindow.closing==NO && [controllerStack containsObject:viewController])
		{
			RELEASE_TO_NIL(closingWindows);
            closingWindows = [[NSMutableArray alloc] init];
            // Travel down the stack until the new viewController is reached; these are the windows
            // which must be closed.
            NSEnumerator* enumerator = [controllerStack reverseObjectEnumerator];
            for (UIViewController* windowController in enumerator) {
                if (windowController != viewController && [windowController isKindOfClass:[TiUITabController class]]) {
                    TiWindowProxy* window = [(TiUITabController*)windowController window];
                    if (window == nil)
                    {
                        continue;
                    }
                    [closingWindows addObject:window];
                    safeToTransition = safeToTransition && ![window restoreFullScreen];

                    [window windowWillClose];
                }
                else {
                    break;
                }
            }
		}

		[currentWindow _tabBlur];
		RELEASE_TO_NIL(current);
	}

	current = (TiUITabController*)[viewController retain];

	TiWindowProxy *newWindow = [current window];

	[newWindow _tabBeforeFocus];

	if (opening || [TiUtils boolValue:newWindow.opened]==NO)
	{
		[newWindow open:nil];
	}

	[newWindow _tabFocus];
	WARN_IF_BACKGROUND_THREAD_OBJ;
	if (safeToTransition) {
		[self childOrientationControllerChangedFlags:newWindow];
	}

	opening = NO;
}

- (void)handleDidShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	if (closingWindows!=nil)
	{
        for (TiWindowProxy* closingWindow in closingWindows) {
            NSArray* args = [NSArray arrayWithObjects:closingWindow,[NSDictionary dictionaryWithObject:NUMBOOL(animated) forKey:@"animated"], nil];
            [self close:args];
        }
	}
    RELEASE_TO_NIL(closingWindows);
    RELEASE_TO_NIL(controllerStack);
    controllerStack = [[[rootController navigationController] viewControllers] copy];
    [self childOrientationControllerChangedFlags:[current window]];
}

#pragma mark Delegates

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
	transitionIsAnimating = YES;
	if (current==viewController)
	{
		return;
	}
	[self handleWillShowViewController:viewController animated:animated];
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    id activeTab = [tabGroup valueForKey:@"activeTab"];
    if (activeTab == nil || activeTab == [NSNull null]) {
        //Make sure that the activeTab property is set
        [self setActive:[NSNumber numberWithBool:YES]];
    }
	transitionIsAnimating = NO;
	[self handleDidShowViewController:viewController animated:animated];
}

- (void)handleWillBlur
{
	TiWindowProxy *currentWindow = [current window];
	[currentWindow _tabBeforeBlur];
}

- (void)handleDidBlur:(NSDictionary *)event
{
	if ([self _hasListeners:@"blur"])
	{
		[self fireEvent:@"blur" withObject:event propagate:NO];
	}
	TiWindowProxy *currentWindow = [current window];
	[currentWindow _tabBlur];
}

- (void)handleWillFocus
{
	TiWindowProxy *currentWindow = [current window];
	[currentWindow _tabBeforeFocus];
}

- (void)handleDidFocus:(NSDictionary *)event
{
	if ([self _hasListeners:@"focus"])
	{
		[self fireEvent:@"focus" withObject:event propagate:NO];
	}
	TiWindowProxy *currentWindow = [current window];
	[currentWindow _tabFocus];
}

#pragma mark Public APIs

-(TiProxy*)tabGroup
{
	return tabGroup;
}

-(void)open:(NSArray*)args
{
	TiWindowProxy *window = [args objectAtIndex:0];
	ENSURE_TYPE(window,TiWindowProxy);
	// since the didShow notification above happens on both a push and pop, i need to keep a flag
	// to let me know which state i'm in so i only close the current window on a pop
	opening = YES;
	// Because the window may be going out of scope soon, and that rememberself is a bit, not a counter, we can safely protect here.
	[window rememberSelf];
	[window setParentOrientationController:self];
	// TODO: Slap patch.  Views, when opening/added, should check parent visibility (and parent/parent visibility, if possible)
	[window parentWillShow];
	[[[TiApp app] controller] dismissKeyboard];
	TiThreadPerformOnMainThread(^{
		[self openOnUIThread:args];
	}, YES);
}

-(void)openOnUIThread:(NSArray*)args
{
	if (transitionIsAnimating)
	{
		[self performSelector:_cmd withObject:args afterDelay:0.1];
		return;
	}
	TiWindowProxy *window = [args objectAtIndex:0];
	BOOL animated = args!=nil && [args count] > 1 ? [TiUtils boolValue:@"animated" properties:[args objectAtIndex:1] def:YES] : YES;
	TiUITabController *root = [[TiUITabController alloc] initWithProxy:window tab:self];

	[self controller];
	[[rootController navigationController] pushViewController:root animated:animated];
	[root release];
}

-(void)close:(id)args
{
	ENSURE_UI_THREAD(close,args);

	// Don't use ENSURE_SINGLE_ARG because it will overwrite the original 'args' value if we
	// ARE passing more than one arg
	TiWindowProxy* window = nil;
	if ([args isKindOfClass:[NSArray class]]) {
		window = [args objectAtIndex:0];
	}
	else {
		window = args;
	}
	if (![window isKindOfClass:[TiWindowProxy class]]) {
		[self throwException:TiExceptionInvalidType
				   subreason:[NSString stringWithFormat:@"expected: %@, was: %@",[TiWindowProxy class],[window class]]
					location:CODELOCATION];
	}

	NSDictionary* properties = (([args isKindOfClass:[NSArray class]]) &&
								([args count] > 1) &&
								([[args objectAtIndex:1] isKindOfClass:[NSDictionary class]])) ? [args objectAtIndex:1] : nil;

	BOOL animated = [TiUtils boolValue:@"animated" properties:properties def:NO];

    if (window == [rootController window]) {
        NSLog(@"[WARN] Can not close root window of a tab. Use TabGroup.removeTab instead");
        return;
    }
    if (window == [current window]) {
        [[rootController navigationController] popViewControllerAnimated:animated];
        return;
    }
    [self closeWindow:window animated:animated];
}

- (void)closeWindow:(TiWindowProxy *)window animated:(BOOL)animated
{
    [window retain];
    UIViewController *windowController = [[window controller] retain];
    if ([windowController isKindOfClass:[TiUITabController class]]) {
        [(TiWindowProxy *)[(TiUITabController*)windowController proxy] _associateTab:nil navBar:nil tab:nil];
    }

	// Manage the navigation controller stack
	UINavigationController* navController = [rootController navigationController];
	NSMutableArray* newControllerStack = [NSMutableArray arrayWithArray:[navController viewControllers]];
	[newControllerStack removeObject:windowController];
	[navController setViewControllers:newControllerStack animated:animated];
    RELEASE_TO_NIL(controllerStack);
    controllerStack = [newControllerStack retain];
	[window _tabBlur];
	[window setParentOrientationController:nil];

	// for this to work right, we need to sure that we always have the tab close the window
	// and not let the window simply close by itself. this will ensure that we tell the
	// tab that we're doing that
	[window close:[NSArray arrayWithObjects:[NSDictionary dictionaryWithObject:NUMBOOL(YES) forKey:@"closeByTab"],nil]];
    RELEASE_TO_NIL_AUTORELEASE(window);
    RELEASE_TO_NIL(windowController);
}

-(void)windowClosing:(TiWindowProxy*)window animated:(BOOL)animated
{
	if (current!=nil && [current window]==window)
	{
		[[rootController navigationController] popViewControllerAnimated:animated];
	}
}

-(void)setActive:(id)active
{
	[self replaceValue:active forKey:@"active" notification:NO];

	id activeTab = [tabGroup valueForKey:@"activeTab"];

	if ([TiUtils boolValue:active])
	{
		if (activeTab!=self)
		{
			[tabGroup replaceValue:self forKey:@"activeTab" notification:YES];
		}
	}
	else
	{
		if (activeTab==self)
		{
			[tabGroup replaceValue:nil forKey:@"activeTab" notification:YES];
		}
	}
}

-(void)updateTabBarItem
{
	if (rootController == nil)
	{
		return;
	}
	ENSURE_UI_THREAD_0_ARGS;

	id badgeValue = [TiUtils stringValue:[self valueForKey:@"badge"]];
	id icon = [self valueForKey:@"icon"];

	if ([icon isKindOfClass:[NSNumber class]])
	{
		int value = [TiUtils intValue:icon];
		UITabBarItem *newItem = [[UITabBarItem alloc] initWithTabBarSystemItem:value tag:value];
		[newItem setBadgeValue:badgeValue];
		[rootController setTabBarItem:newItem];
		[newItem release];
		systemTab = YES;
		return;
	}

	NSString * title = [TiUtils stringValue:[self valueForKey:@"title"]];

	UIImage *image;
	if (icon == nil)
	{
		image = nil;
	}
	else
	{
		// we might be inside a different context than our tab group and if so, he takes precendence in
		// url resolution
		TiProxy* currentWindow = [self.executionContext preloadForKey:@"currentWindow" name:@"UI"];
		if (currentWindow==nil)
		{
			// check our current window's context that we are owned by
			currentWindow = [self.pageContext preloadForKey:@"currentWindow" name:@"UI"];
		}
		if (currentWindow==nil)
		{
			currentWindow = self;
		}
		image = [[ImageLoader sharedLoader] loadImmediateImage:[TiUtils toURL:icon proxy:currentWindow]];
	}

	[rootController setTitle:title];
	UITabBarItem *ourItem = nil;

	if (!systemTab)
	{
		ourItem = [rootController tabBarItem];
		[ourItem setTitle:title];
		[ourItem setImage:image];
	}

	if(ourItem == nil)
	{
		systemTab = NO;
		ourItem = [[[UITabBarItem alloc] initWithTitle:title image:image tag:0] autorelease];
		[rootController setTabBarItem:ourItem];
	}

	[ourItem setBadgeValue:badgeValue];
}

-(void)setTitle:(id)title
{
	[self replaceValue:title forKey:@"title" notification:NO];
	[self updateTabBarItem];
}

-(void)setIcon:(id)icon
{
	if([icon isKindOfClass:[NSString class]])
	{
		// we might be inside a different context than our tab group and if so, he takes precendence in
		// url resolution
		TiProxy* currentWindow = [self.executionContext preloadForKey:@"currentWindow" name:@"UI"];
		if (currentWindow==nil)
		{
			// check our current window's context that we are owned by
			currentWindow = [self.pageContext preloadForKey:@"currentWindow" name:@"UI"];
		}
		if (currentWindow==nil)
		{
			currentWindow = self;
		}

		icon = [[TiUtils toURL:icon proxy:currentWindow] absoluteString];
	}

	[self replaceValue:icon forKey:@"icon" notification:NO];

	[self updateTabBarItem];
}

-(void)setBadge:(id)badge
{
	[self replaceValue:badge forKey:@"badge" notification:NO];
	[self updateTabBarItem];
}

-(void)willChangeSize
{
	[super willChangeSize];

	//TODO: Shouldn't this be not through UI? Shouldn't we retain the windows ourselves?
	for (UIViewController * thisController in [controller viewControllers])
	{
		if ([thisController isKindOfClass:[TiViewController class]])
		{
			TiViewProxy * thisProxy = [(TiViewController *)thisController proxy];
			[thisProxy willChangeSize];
		}
	}
}

@synthesize parentOrientationController;

-(TiOrientationFlags)orientationFlags
{
	UIViewController * modalController = [controller modalViewController];
	if ([modalController conformsToProtocol:@protocol(TiOrientationController)])
	{
		return [(id<TiOrientationController>)modalController orientationFlags];
	}

	for (id thisController in [[controller viewControllers] reverseObjectEnumerator])
	{
		if (![thisController isKindOfClass:[TiViewController class]])
		{
			continue;
		}
		TiWindowProxy * thisProxy = (TiWindowProxy *)[(TiViewController *)thisController proxy];
		if ([thisProxy conformsToProtocol:@protocol(TiOrientationController)])
		{
			TiOrientationFlags result = [thisProxy orientationFlags];
			if (result != TiOrientationNone)
			{
				return result;
			}
		}
	}
	return TiOrientationNone;
}

-(void)childOrientationControllerChangedFlags:(id<TiOrientationController>) orientationController
{
	WARN_IF_BACKGROUND_THREAD_OBJ;
	[parentOrientationController childOrientationControllerChangedFlags:self];
}

@end

#endif


text:
layout: post
title: Isolated Storage ... not that isolated?
comments: true
tags: [C#, Development, Storage, Windows Phone]
categories: [Development]
---
A few weeks ago when I was at the //publish event in London I had some trouble getting my code to work properly. You know, because the day you need to hack something together quickly is the day the computer goes "I know what you want to do, but you're missing something, and I can't tell you what".

One of my biggest issues that day was that I was reading some data off of IsolatedStorage, and then doing some manipulation so the ViewModel could work it's magic, and that somehow managed to modify the data which I thought was safely stored in IsolatedStorage.

```csharp
object o = StorageUtility.ReadSetting(Utilities.PLAN_LOG);
var log = o as PlanLog;
var lastNWorkouts = log.Workouts.OrderByDescending(w > w.Date)
                                .Where(w => w.Exercises.Any(e => e.ExerciseName.Equals(config.TargetExercise)))
                                .Take(config.ConsecutiveFailCount);
var lastWorkout = lastNWorkouts.First().Exercises.First(e => e.ExerciseName.Equals(config.TargetExercise));
```

This is part of my Workout Tracking library that I'm using in my Stronglifts app and trying to extend into something (hopefully) quite useful. So, the first bit is quite simple. I have a little utility class I'm using to read and write to IS which I won't bother you with right now. I get the data and set a couple of LINQ queries to get the bits that I need.

```csharp
CurrentWorkout.ExerciseList.FirstOrDefault(e => e.Name.Equals(config.TargetExercise)).Sets = new List(lastWorkout.Sets)
```

My idea was that I had this data, fresh out of IS, and I wanted to copy it to my Model, which the ViewModel would then access to do it's thing. So rhat this bit of code was supposed to do was create a new List of Set, copying the elements from what I read from Isolated Storage. What was in fact happening is that I was creating a new list but the Set instances were referencing the original data. So when I then modified the data on my new list, the data in Isolated Storage would also get those changes (without me explicitly writing to it).

Now, as I side note, that code was in the published app and I swear I didn't notice anything misbehaving, but when debugging my app to show it off at the //publish event, any changes to the Sets list would affect the serialized data in IS. My suspicion is that since that Set class was a reference type, the CLR kept that "connection" alive, allowing changes to propagate to IsolatedStorage. So it's not as "isolated" as I believed.

In the end I had to modify that one line of code to ensure that I was created new instances of every item:

```csharp
for (int i = 0; i < lastWorkout.Sets.Count; i++)
{
    CurrentWorkout.ExerciseList.FirstOrDefault(e => e.Name.Equals(config.TargetExercise)).Sets[i] = new Set()
    {
        NumberOfReps = lastWorkout.Sets[i].NumberOfReps,
        SetType = lastWorkout.Sets[i].SetType,
        Unit = lastWorkout.Sets[i].Unit,
        Weight = lastWorkout.Sets[i].Weight
    };
}
```

... Yeah, I don't like that either. If you have a better idea I'm all ears.

That's all for now.


text:
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.
// ----------------------------------------------------------------------------------

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.Azure.Commands.Dns.Models;
using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters;
using Microsoft.Azure.Management.Dns.Models;
using Microsoft.Azure.Management.Internal.Network.Common;
using ProjectResources = Microsoft.Azure.Commands.Dns.Properties.Resources;

namespace Microsoft.Azure.Commands.Dns
{
    /// <summary>
    /// Creates a new zone.
    /// </summary>
    [Cmdlet("New", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "DnsZone", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium, DefaultParameterSetName = IdsParameterSetName), OutputType(typeof(DnsZone))]
    public class NewAzureDnsZone : DnsBaseCmdlet
    {
        private const string IdsParameterSetName = "Ids";
        private const string ObjectsParameterSetName = "Objects";

        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The full name of the zone (without a terminating dot).")]
        [ValidateNotNullOrEmpty]
        public string Name { get; set; }

        [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group in which to create the zone.")]
        [ResourceGroupCompleter]
        [ValidateNotNullOrEmpty]
        public string ResourceGroupName { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The type of the zone, Public or Private. This property cannot be changed for a zone.")]
        [ValidateNotNullOrEmpty]
        [ValidateSet("Public", "Private")]
        public ZoneType? ZoneType { get; set; }

        [Alias("Tags")]
        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "A hash table which represents resource tags.")]
        public Hashtable Tag { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = IdsParameterSetName, HelpMessage = "The list of virtual network ids that will register virtual machine hostnames records in this DNS zone, only available for private zones.")]
        [ValidateNotNull]
        public List<string> RegistrationVirtualNetworkId { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = IdsParameterSetName, HelpMessage = "The list of virtual network ids able to resolve records in this DNS zone, only available for private zones.")]
        [ValidateNotNull]
        public List<string> ResolutionVirtualNetworkId { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ObjectsParameterSetName, HelpMessage = "The list of virtual networks that will register virtual machine hostnames records in this DNS zone, only available for private zones.")]
        [ValidateNotNull]
        public List<IResourceReference> RegistrationVirtualNetwork { get; set; }

        [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ObjectsParameterSetName, HelpMessage = "The list of virtual networks able to resolve records in this DNS zone, only available for private zones.")]
        [ValidateNotNull]
        public List<IResourceReference> ResolutionVirtualNetwork { get; set; }

        public override void ExecuteCmdlet()
        {
            WriteWarning("The output object type of this cmdlet will be modified in a future release.");

            if (this.Name.EndsWith("."))
            {
                this.Name = this.Name.TrimEnd('.');
                this.WriteWarning(string.Format("Modifying zone name to remove terminating '.'.  Zone name used is \"{0}\".", this.Name));
            }

            ConfirmAction(
                ProjectResources.Progress_CreatingNewZone,
                this.Name,
                () =>
                {
                    ZoneType zoneType = this.ZoneType != null ? this.ZoneType.Value : Management.Dns.Models.ZoneType.Public;

                    List<string> registrationVirtualNetworkIds = this.RegistrationVirtualNetworkId;
                    List<string> resolutionVirtualNetworkIds = this.ResolutionVirtualNetworkId;
                    if (this.ParameterSetName == ObjectsParameterSetName)
                    {
                        registrationVirtualNetworkIds = this.RegistrationVirtualNetwork?.Select(virtualNetwork => virtualNetwork.Id).ToList();
                        resolutionVirtualNetworkIds = this.ResolutionVirtualNetwork?.Select(virtualNetwork => virtualNetwork.Id).ToList();
                    }

                    DnsZone result = this.DnsClient.CreateDnsZone(
                        this.Name,
                        this.ResourceGroupName,
                        this.Tag,
                        zoneType,
                        registrationVirtualNetworkIds,
                        resolutionVirtualNetworkIds);
                    this.WriteVerbose(ProjectResources.Success);
                    this.WriteVerbose(zoneType == Management.Dns.Models.ZoneType.Private
                        ? string.Format(ProjectResources.Success_NewPrivateZone, this.Name, this.ResourceGroupName)
                        : string.Format(ProjectResources.Success_NewZone, this.Name, this.ResourceGroupName));
                    this.WriteObject(result);
                });
        }
    }
}


text:
package pdufield

import (
	"io"
	"strconv"
)

// Name is the name of a PDU field.
type Name string

// Supported PDU field names.
const (
	AddrNPI              Name = "addr_npi"
	AddrTON              Name = "addr_ton"
	AddressRange         Name = "address_range"
	DataCoding           Name = "data_coding"
	DestAddrNPI          Name = "dest_addr_npi"
	DestAddrTON          Name = "dest_addr_ton"
	DestinationAddr      Name = "destination_addr"
	ESMClass             Name = "esm_class"
	ErrorCode            Name = "error_code"
	FinalDate            Name = "final_date"
	InterfaceVersion     Name = "interface_version"
	MessageID            Name = "message_id"
	MessageState         Name = "message_state"
	Password             Name = "password"
	PriorityFlag         Name = "priority_flag"
	ProtocolID           Name = "protocol_id"
	RegisteredDelivery   Name = "registered_delivery"
	ReplaceIfPresentFlag Name = "replace_if_present_flag"
	SMDefaultMsgID       Name = "sm_default_msg_id"
	SMLength             Name = "sm_length"
	ScheduleDeliveryTime Name = "schedule_delivery_time"
	ServiceType          Name = "service_type"
	ShortMessage         Name = "short_message"
	SourceAddr           Name = "source_addr"
	SourceAddrNPI        Name = "source_addr_npi"
	SourceAddrTON        Name = "source_addr_ton"
	SystemID             Name = "system_id"
	SystemType           Name = "system_type"
	ValidityPeriod       Name = "validity_period"
)

// Fixed is a PDU of fixed length.
type Fixed struct {
	Data uint8
}

// Len implements the Data interface.
func (f *Fixed) Len() int {
	return 1
}

// Raw implements the Data interface.
func (f *Fixed) Raw() interface{} {
	return f.Data
}

// String implements the Data interface.
func (f *Fixed) String() string {
	return strconv.Itoa(int(f.Data))
}

// Bytes implements the Data interface.
func (f *Fixed) Bytes() []byte {
	return []byte{f.Data}
}

// SerializeTo implements the Data interface.
func (f *Fixed) SerializeTo(w io.Writer) error {
	_, err := w.Write(f.Bytes())
	return err
}

// Variable is a PDU field of variable length.
type Variable struct {
	Data []byte
}

// Len implements the Data interface.
func (v *Variable) Len() int {
	return len(v.Bytes())
}

// Raw implements the Data interface.
func (v *Variable) Raw() interface{} {
	return v.Data
}

// String implements the Data interface.
func (v *Variable) String() string {
	if l := len(v.Data); l > 0 && v.Data[l-1] == 0x00 {
		return string(v.Data[:l-1])
	}
	return string(v.Data)
}

// Bytes implements the Data interface.
func (v *Variable) Bytes() []byte {
	if len(v.Data) > 0 && v.Data[len(v.Data)-1] == 0x00 {
		return v.Data
	}
	return append(v.Data, 0x00)
}

// SerializeTo implements the Data interface.
func (v *Variable) SerializeTo(w io.Writer) error {
	_, err := w.Write(v.Bytes())
	return err
}

// SM is a PDU field used for Short Messages.
type SM struct {
	Data []byte
}

// Len implements the Data interface.
func (sm *SM) Len() int {
	return len(sm.Data)
}

// Raw implements the Data interface.
func (sm *SM) Raw() interface{} {
	return sm.Data
}

// String implements the Data interface.
func (sm *SM) String() string {
	return string(sm.Data)
}

// Bytes implements the Data interface.
func (sm *SM) Bytes() []byte {
	return sm.Data
}

// SerializeTo implements the Data interface.
func (sm *SM) SerializeTo(w io.Writer) error {
	_, err := w.Write(sm.Bytes())
	return err
}


text:
package gov.samhsa.c2s.c2suiapi.service.mapping.customconverter;

import gov.samhsa.c2s.c2suiapi.infrastructure.dto.UmsAddressDto;
import gov.samhsa.c2s.c2suiapi.infrastructure.dto.UmsUserDto;
import gov.samhsa.c2s.c2suiapi.service.mapping.Use;
import org.modelmapper.AbstractConverter;
import org.springframework.stereotype.Component;

@Component
public class UmsAddressesToHomeAddressConverter extends AbstractConverter<UmsUserDto, UmsAddressDto> {
    @Override
    protected UmsAddressDto convert(UmsUserDto source) {
        return source.getAddresses().stream()
                .filter(umsAddressDto -> umsAddressDto.getUse().equalsIgnoreCase(Use.HOME.toString()))
                .findFirst()
                .orElse(null);
    }
}


text:
1) buf_modify - Create Buffer and change it's data.
Run ```node buf_modify.js```

2) buf2json - Create Data in buffer and change it to json.
Run ```node buf2json.js```

3) cmd_readline - Custom console which is reading lines.
Run ```node cmd_readline.js```

4) cmd_utils - Small cmd uitl for coping file data to a new one.
Run ```node cmd_utils -s <soruce file> -f <destination file>```

5) custom_repl - Custom NodeJS REPL.
Run

```
npm install request
npm install underscore

node custom_repl.js
```

6) format_options - Different output styles
Run ```node format_options.js```

7) array_conversion - convert array [2, 4, 6, 8, 9, 15] to ['4', '16', '64']
Run ```node array_conversion.js```

8) calc_cumulative - Calculate cumulative TTL of request.
Run ```node calc_cumulative.js```

9) analyze_polygons - Read csv file with polygons and show which geometric figures are undefined
Run

```
npm install csv-parse
npm install async

node analyze_polygons.js
```

10) get_console - Create and run a script in console.
Run ```node get_console.js```

11) get_permissions - Get permissions of get_console.js
Run

```
npm install stat-mode
node get_permissions.js
```

12) read_by_grep - Run ls and grep commands
Run ```node read_by_grep.js```

13) read_dirs - Read directory
Run ```node read_dirs.js```

14) read_file - Read a file
Run ```node read_file.js```


text:
package com.raltamirano.fsm;

import java.util.ArrayList;
import java.util.List;

import com.raltamirano.fsm.exceptions.FSMException;

public final class Transition {
	private final State sourceState;
	private final Condition condition;
	private final State targetState;
	private final List<Action> actions;

	public Transition(State sourceState, Condition condition, State targetState) {
		if (sourceState == null) {
			throw new FSMException("'sourceState' can not be null!");
		}
		if (condition == null) {
			throw new FSMException("'condition' can not be null!");
		}
		if (targetState == null) {
			throw new FSMException("'targetState' can not be null!");
		}

		this.sourceState = sourceState;
		this.condition = condition;
		this.targetState = targetState;
		this.actions = new ArrayList<Action>();
	}

	public Transition(State sourceState, Condition condition, State targetState, Action action) {
		this(sourceState, condition, targetState);

		if (action == null) {
			throw new FSMException("'action' can not be null!");
		}

		this.actions.add(action);
	}

	public State getSourceState() {
		return this.sourceState;
	}

	public Condition getCondition() {
		return this.condition;
	}

	public State getTargetState() {
		return this.targetState;
	}

	public List<Action> getActions() {
		return this.actions;
	}
}


text:
package org.jabref.logic.integrity;

import java.util.Collections;
import java.util.List;

import org.jabref.model.database.BibDatabase;
import org.jabref.model.entry.BibEntry;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;

public class EntryLinkCheckerTest {

    private BibDatabase database;
    private EntryLinkChecker checker;
    private BibEntry entry;

    @BeforeEach
    public void setUp() {
        database = new BibDatabase();
        checker = new EntryLinkChecker(database);
        entry = new BibEntry();
        database.insertEntry(entry);
    }

    @Test
    public void testEntryLinkChecker() {
        assertThrows(NullPointerException.class, () -> new EntryLinkChecker(null));
    }

    @Test
    public void testCheckNoFields() {
        assertEquals(Collections.emptyList(), checker.check(entry));
    }

    @Test
    public void testCheckNonRelatedFieldsOnly() {
        entry.setField("year", "2016");
        assertEquals(Collections.emptyList(), checker.check(entry));
    }

    @Test
    public void testCheckNonExistingCrossref() {
        entry.setField("crossref", "banana");

        List<IntegrityMessage> message = checker.check(entry);
        assertFalse(message.toString(), message.isEmpty());
    }

    @Test
    public void testCheckExistingCrossref() {
        entry.setField("crossref", "banana");

        BibEntry entry2 = new BibEntry();
        entry2.setCiteKey("banana");
        database.insertEntry(entry2);

        List<IntegrityMessage> message = checker.check(entry);
        assertEquals(Collections.emptyList(), message);
    }

    @Test
    public void testCheckExistingRelated() {
        entry.setField("related", "banana,pineapple");

        BibEntry entry2 = new BibEntry();
        entry2.setCiteKey("banana");
        database.insertEntry(entry2);

        BibEntry entry3 = new BibEntry();
        entry3.setCiteKey("pineapple");
        database.insertEntry(entry3);

        List<IntegrityMessage> message = checker.check(entry);
        assertEquals(Collections.emptyList(), message);
    }

    @Test
    public void testCheckNonExistingRelated() {
        BibEntry entry1 = new BibEntry();
        entry1.setField("related", "banana,pineapple,strawberry");
        database.insertEntry(entry1);

        BibEntry entry2 = new BibEntry();
        entry2.setCiteKey("banana");
        database.insertEntry(entry2);

        BibEntry entry3 = new BibEntry();
        entry3.setCiteKey("pineapple");
        database.insertEntry(entry3);

        List<IntegrityMessage> message = checker.check(entry1);
        assertFalse(message.toString(), message.isEmpty());
    }
}


text:
'use strict';

describe('tracker.standings module', function() {

  beforeEach(module('tracker.standings'));

  describe('standings controller', function(){

    it('should ....', inject(function($controller) {
      //spec body
      var standingsCtrl = $controller('StandingsCtrl');
      expect(standingsCtrl).toBeDefined();
    }));

  });
});


text:
[![travis-ci status](https://travis-ci.org/cloudwu/pbc.svg?branch=master)](https://travis-ci.org/cloudwu/pbc)

PBC is a google protocol buffers library for C without code generation.

## Quick Example

    package tutorial;

    message Person {
      required string name = 1;
      required int32 id = 2;        // Unique ID number for this person.
      optional string email = 3;

      enum PhoneType {
        MOBILE = 0;
        HOME = 1;
        WORK = 2;
      }

      message PhoneNumber {
        required string number = 1;
        optional PhoneType type = 2 [default = HOME];
      }

      repeated PhoneNumber phone = 4;
    }

```C
struct pbc_rmessage * m = pbc_rmessage_new(env, "tutorial.Person", slice);
printf("name = %s\n", pbc_rmessage_string(m , "name" , 0 , NULL));
printf("id = %d\n", pbc_rmessage_integer(m , "id" , 0 , NULL));
printf("email = %s\n", pbc_rmessage_string(m , "email" , 0 , NULL));

int phone_n = pbc_rmessage_size(m, "phone");
int i;

for (i=0;i<phone_n;i++) {
	struct pbc_rmessage * p = pbc_rmessage_message(m , "phone", i);
	printf("\tnumber[%d] = %s\n",i,pbc_rmessage_string(p , "number", i ,NULL));
	printf("\ttype[%d] = %s\n",i,pbc_rmessage_string(p, "type", i, NULL));
}

pbc_rmessage_delete(m);
```

## Message API

You can use *wmessage* for encoding , and *rmessage* for decoding.

See test/addressbook.c for details.

## Pattern API

If you need better performance , you can use pbc_pattern_xxx api .

See test/pattern.c for details.

Pattern api is faster and less memory used because it can access data in native C struct.

## Extension

PBC support extension in a very simple way . PBC add a specific prefix to every extension field name.

## Service

Not supported

## Enum

With message API , you can use both string and integer as enum type . They must be integer in Pattern API.

## Lua bindings

cd bindings/lua && make

See https://github.com/cloudwu/pbc/tree/master/binding/lua/README.md

## Build with cmake
### Build for native library
```bash
cd REPO
mkdir build
cd build
cmake ..
# You may also add -G "Visual Studio 15 2017 Win64" for Visual Studio 2017 and win64 or -G "MSYS Makefils" for MinGW
# Or add -DCMAKE_INSTALL_PREFIX=<install dir> to specify where to install when run make install

# Then build
make -j4 # Using gcc/clang and make
MSBuild pbc.sln /verbosity:minimal /target:ALL_BUILD /p:Configuration=RelWithDebInfo /p:Platform=x64 # Using Visual Studio, usually in C:\Program Files (x86)\MSBuild\15.0 or C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\

# At last, install it
make install # Using gcc/clang and make
MSBuild pbc.sln /verbosity:minimal /target:INSTALL /p:Configuration=RelWithDebInfo /p:Platform=x64 # Using Visual Studio
```

### Build lua-binding
Just add lua include directory and library directory to cmake standard search directory. If we can find available lua, we will build lua binding for the right version.

### Cross-Compile for iOS
Just run build_ios.sh in macOS

**CMAKE_INSTALL_PREFIX** can not be set here

```bash
mkdir -p build && cd build && ./build_ios.sh -r ..

# add LUA_INCLUDE_DIR and LUA_VERSION_STRING for build lua binding
mkdir -p build && cd build && ./build_ios.sh -r .. -- -DLUA_INCLUDE_DIR=<where has lua.h> -DLUA_VERSION_STRING=<5.1 or 5.3>
```

All prebuilt static library files and lua file will be generated at $PWD/prebuilt

### Cross-Compile for Android
Just run build_android.sh in Unix like system. We do not support MSYS or MinGW shell now.

**CMAKE_INSTALL_PREFIX** can not be set here

You must at least specify NDK_ROOT
```bash
mkdir -p build && cd build && ./build_android.sh -r .. -n <ndk_root>

# add -i and -u options to build lua binding
mkdir -p build && cd build && ./build_android.sh -r .. -n <ndk_root> -i <where has lua.h or ARCHITECTURE/lua.h> -u <where ARCHITECTURE/[library pattern] in it>

# for example, if we install NDK in /home/prebuilt/android/ndk/android-ndk-r13b, and lua.h in /home/prebuilt/lua/luajit/include/luajit-2.0/ and armeabi-v7a/libluajit-5.1.[a|so] x86/libluajit-5.1.[a|so] x86_64/libluajit-5.1.[a|so] arm64-v8a/libluajit-5.1.[a|so] .. in /home/prebuilt/lua/luajit/include/lib, we can use the command below
mkdir -p build && cd build && ./build_android.sh -r .. -n /home/prebuilt/android/ndk/android-ndk-r13b -i /home/prebuilt/lua/luajit/include/luajit-2.0 -u /home/prebuilt/lua/luajit/include/lib
```

All prebuilt library files and lua file will be generated at $PWD/prebuilt. And library in difference architecture will be placed in $PWD/prebuilt/ARCHITECTURE

## Question ?

* Send me email : http://www.codingnow.com/2000/gmail.gif
* My Blog : http://blog.codingnow.com
* Design : http://blog.codingnow.com/2011/12/protocol_buffers_for_c.html (in Chinese)
* Build for Visual Studio 2012 : https://github.com/miaodadao/pbc


text:
import os
from bottle import route, run, template, static_file, post, request

@route("/static/<filepath:path>")
def server_static(filepath):
    return static_file(filepath, root='static')

@route("/")
def index():
    return template("index")

if __name__ == '__main__':
    if os.getenv("HEROKU")==None:
        run(host="localhost", port=(os.environ.get("PORT",5200)), debug=True, reloader=True)
    else:
        run(host="0.0.0.0", port=(os.environ.get("PORT",5200)), debug=True, reloader=True)


text:
package org.seasar.doma.internal.expr.node;

import static org.seasar.doma.internal.util.AssertionUtil.*;

/**
 * @author taedium
 *
 */
public class OrOperatorNode implements LogicalBinaryOperatorNode {

    protected static final int PRIORITY = 10;

    protected final ExpressionLocation location;

    protected final String expression;

    protected ExpressionNode leftNode;

    protected ExpressionNode rightNode;

    public OrOperatorNode(ExpressionLocation location, String expression) {
        assertNotNull(location, expression);
        this.location = location;
        this.expression = expression;
    }

    @Override
    public ExpressionNode getLeftNode() {
        return leftNode;
    }

    public void setLeftNode(ExpressionNode leftNode) {
        this.leftNode = leftNode;
    }

    @Override
    public ExpressionNode getRightNode() {
        return rightNode;
    }

    public void setRightNode(ExpressionNode rightNode) {
        this.rightNode = rightNode;
    }

    @Override
    public int getPriority() {
        return PRIORITY;
    }

    @Override
    public <R, P> R accept(ExpressionNodeVisitor<R, P> visitor, P p) {
        return visitor.visitOrOperatorNode(this, p);
    }

    @Override
    public ExpressionLocation getLocation() {
        return location;
    }

    @Override
    public String getExpression() {
        return expression;
    }

    @Override
    public String toString() {
        return String.format("%s %s %s", leftNode, expression, rightNode);
    }

}


text:
<link href="<?php echo site_url()?>css/pricelist.css" rel="stylesheet"/>

Print Types/Price List <?php if(!$default):?>for <?php echo $gallery_name;?><?php endif;?>

<?php if($default):?>Set the default sizes/print types here.<?php endif;?> Examples of request types include 8" x 10", 4" x 6", or 'Add to Slideshow,' etc...

<form>

Size Name
Price
No Input

<?php

foreach($print_sizes as $size){
	echo "
Remove	";
	echo "<input type='text' class ='size_val' value='".$size['size_val']."'>	";
	echo "$<input type= 'text' class='price' value='".$size['price']."'>	";
	if($size['no_input']){
		echo "<input type='checkbox' class='no_input' checked=true>
";
	}else{
		echo "<input type='checkbox' class='no_input'>
";

	}

}
?>

</form>
New size

Select 'No Input' for requests such as 'Add to disk/slideshow' or 'Email me', for which the users have no need to specify a number they want.

<?php if(!$default):?>

Important: Altering print types or changing prices will reset any user's requests on this gallery.
<?php endif;?>


text:
package com.consol.citrus.camel.actions;

import com.consol.citrus.context.TestContext;
import com.consol.citrus.exceptions.CitrusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Christoph Deppisch
 * @since 2.4
 */
public class StartCamelRouteAction extends AbstractCamelRouteAction {

    /** Logger */
    private static Logger log = LoggerFactory.getLogger(StartCamelRouteAction.class);

    /**
     * Default constructor.
     */
    public StartCamelRouteAction() {
        setName("start-routes");
    }

    @Override
    public void doExecute(TestContext context) {
        try {
            for (String routeId : routeIds) {
                camelContext.startRoute(routeId);
                log.info(String.format("Started Camel route '%s' on context '%s'", routeId, camelContext.getName()));
            }
        } catch (Exception e) {
            throw new CitrusRuntimeException("Failed to start Camel routes", e);
        }
    }
}


text:
class BookFinder::CLI

  def call
    greeting
    create_books
    main_menu
  end

  def greeting
    puts "    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++".blue
    puts "    +    Welcome To The Top 100 Novels of All Time          +".yellow
    puts "    +    To List Times Magazine's Top 100 Novels => Enter 1 +".green
    puts "    +    To Exit Application => Enter 2                     +".red
    puts "    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++".blue
  end

  def create_books
    novels_array = BookFinder::Scraper.top_100_novels
    BookFinder::Book.create_from_collection(novels_array)
  end

  def main_menu
    input = gets.strip

    case input
    when "1"
      puts ""
      BookFinder::Book.list_books
      all_books = BookFinder::Book.all

      puts ""
      puts "    +++++++++++++++++++++++++++++++++++++++++++++++++++++++".yellow
      puts "    +   Choose a Book Number To Receive a Description     +".red
      puts "    +   Or Type Any Letter To Return To The Main Menu     +".green
      puts "    +++++++++++++++++++++++++++++++++++++++++++++++++++++++".blue
      description_menu

    when "2"
      puts ""
      puts "Goodbye!".bold.red
    else
      puts ""
      puts "   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++".blue
      puts "   +               Invalid Entry                           +".green
      puts "   + To List Times Magazine's Top 100 Novels => Enter 1    +".yellow
      puts "   +         To Exit Application => Enter 2                +".red
      puts "   +++++++++++++++++++++++++++++++++++++++++++++++++++++++++".blue
      main_menu
    end
  end

  def description_menu
    input = gets.strip.to_i

    if input.between?(1, 100)
      book = BookFinder::Book.all[input - 1]
      puts ""
      puts "+++ A brief description of '#{book.title}' by #{book.author} +++".yellow
      puts ""
      puts BookFinder::Scraper.book_description(book.book_link)
      puts ""
      puts "For more information on this book, please visit:".yellow
      puts "#{book.book_link}".green
      puts ""
      greeting
      main_menu
    else
      greeting
      main_menu
    end
  end
end


text:
{% extends "admin/base_site.html" %}
{% load i18n static %}

{% block extrastyle %}{{ block.super }}<link rel="stylesheet" type="text/css" href="{% static 'admin/css/dashboard.css' %}" />{% endblock %}

{% block coltype %}colMS{% endblock %}

{% block bodyclass %}{{ block.super }} dashboard{% endblock %}

{% block breadcrumbs %}{% endblock %}

{% block content %}

Guides

How to add a ring

Do a quick background check: run a wide scope search for rings with
        the properties of the ring you want to add. If you don't notice anything that looks like your ring, proceeed
        to the next steps.

Make a record for your ring

On the admin home page, click the "add" option in the row for Ring (or Commutative ring, if
                    applicable. A commutative ring can be created in either place.)

Fill in as much information for the ring as you can (use the keyword selector and ignore kwd.)

Hopefully you had some key properties of the ring in mind. You ought to add
                    properties to the ring via the following steps.

The bottom of the form has a few rows to associate properties with the ring.

Select a property you are interested in from the drop-down in the row.

In "has property," put a 1 if the ring HAS the property, and a 0 if it does NOT have the property.

Use the "reason" field if the reason is something very straightforward. Use the "source"
                            field to include a citation if you can. Please use at least one of these fields!

Hit "save." Your ring is now in the database, and is associated with the properties you entered.

On the admin home page, click the "processor" link. Select your ring from the dropdown, then hit "process."
        The processor will draw all conclusions that it possibly can with current data. Running the processor twice in
            a row will not add anything, but if you manually add new properties to the ring, then processing again may
            add new entries.

You will probably get a "success" message, but if instead you get an error message, get in contact with me.

Tips:

If the form demands content in one of the text fields, you can skirt it by submitting whitespace.

Remember that you don't have to supply all properties you know about the ring, just "the best" ones.

How to modify properties on an existing ring

Click the "change" link in the Ring row (or Commutative ring row, if you want to modify its commutative
            properties.)

The form for the ring will appear, and at the bottom will be the currently associated properties, along with
        a few empty rows for you to add items. You can remove currently existing items (if you have permissions to do
        so.

Once done modifying the associations, you hit the save button.

How to add a citation

Click the "add" link in the Citations row on the admin homepage. (In the Theorem adder, you can also click
        the square next to the citation dropdown field to reach this form. It will soon be the same for the ring adder.)

Select the publication from the dropdown, or if your publication is not in the dropdown already, use
            the square next to the dropdown as a shortcut to the publication adder.

Include the page number and other descriptors as appropriate into the location field. (For example "Theorem 10.9")

Hit save, and your citation will now be in the database.

How to add a publication

Click the "add" link in the Citations row on the admin homepage. (You may also have gotten here from the square
        next to the publication dropdown in the citation adder.)

Enter the publication title, author(s) and date, using January 1 as a default, if necessary.

Anything else about the publication (like edition, volume, publisher) goes into the details field.

Click "save" and the publication will now appear in the database.

{% endblock %}