text:
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <meta name="viewport" content="width=device-width; initial-scale=1.0;">

ATND暦

            Copyright © 2011 Hidetoshi Mori. All rights reserved.
The Application icon material available under CC 'by' license v3.0

            Programming by Hidetoshi Mori

            Icon design by Takashi Ito

            The Application is powered by ATND, Facebook, Twitter, Evernote, Webサービス by Yahoo! JAPAN, Livedoor Weather Hacks.

Acknowledgements:

            Portions of this product may utilize the following copyrighted material, the use of which is hereby acknowledged.

TapkuLibrary

tapku.com || http://github.com/devinross/tapkulibrary

            Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, ublish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

            The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

            THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
            OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

json-framework

Copyright (C) 2009 Stig Brautaset. All rights reserved.

            Redistribution and use in source and binary forms, with or without
            modification, are permitted provided that the following conditions are met:

            * Redistributions of source code must retain the above copyright notice, this
            list of conditions and the following disclaimer.

            * Redistributions in binary form must reproduce the above copyright notice,
            this list of conditions and the following disclaimer in the documentation
            and/or other materials provided with the distribution.

            * Neither the name of the author nor the names of its contributors may be used
            to endorse or promote products derived from this software without specific
            prior written permission.

            THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
            AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
            IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
            DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
            DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
            SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
            CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
            OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

RegexKitLite

            Copyright (c) 2008-2010, John Engelhart. All rights reserved.

            Redistribution and use in source and binary forms, with or without
            modification, are permitted provided that the following conditions are met:

            * Redistributions of source code must retain the above copyright
            notice, this list of conditions and the following disclaimer.

            * Redistributions in binary form must reproduce the above copyright
            notice, this list of conditions and the following disclaimer in the
            documentation and/or other materials provided with the distribution.

            * Neither the name of the Zang Industries nor the names of its
            contributors may be used to endorse or promote products derived from
            this software without specific prior written permission.

            THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
            "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
            LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
            A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
            OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
            SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
            TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
            PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
            LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
            NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
            SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Facebook

            Copyright 2010 Facebook.

            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.

Evernote

            Licensed to the Apache Software Foundation (ASF) under one
            or more contributor license agreements. See the NOTICE file
            distributed with this work for additional information
            regarding copyright ownership. The ASF licenses this file
            to you 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.


text:
#!/usr/bin/env node

'use strict';

const fs     = require('fs');
const path   = require('path');

const _    = require('lodash');

const cardinals = require('cldr-core/supplemental/plurals.json');
const ordinals  = require('cldr-core/supplemental/ordinals.json');

const version   = cardinals.supplemental.version;

const FORMS = [ 'zero', 'one', 'two', 'few', 'many', 'other' ];

////////////////////////////////////////////////////////////////////////////////
// Helpers

// Strip key prefixes to get clear names: zero / one / two / few / many / other
//
function renameKeys(rules) {
  let result = {};
  Object.keys(rules).forEach(k => {
    result[k.match(/[^-]+$/)] = rules[k];
  });
  return result;
}

// Create array of sample values for single range
// 5~16, 0.04~0.09. Both string & integer forms (when possible)
function fillRange(value) {
  let [ start, end ] = value.split('~');

  let decimals = (start.split('.')[1] || '').length;
  let mult = Math.pow(10, decimals);

  let range = Array(end * mult - start * mult + 1).fill()
    .map((v, idx) => ((idx + start * mult) / mult))
    // round errors to required decimal precision
    .map(v => v.toFixed(decimals));

  let last = range[range.length - 1];

  // Stupid self check
  if (+end !== +last) {
    throw new Error(`Range create error for ${value}: last value is ${last}`);
  }

  // Now we have array of string samples. Add integers when possible.
  let result = [];

  range.forEach(val => {
    // push test data as String
    result.push(val);
    // push test data as Number if the same
    if (String(+val) === val) { result.push(+val); }
  });

  return result;
}

// Create array of test values for @integer or @decimal
function createSamples(src) {
  let result = [];

  src
    .replace(/…/, '')
    .trim()
    .replace(/,$/, '')
    .split(',')
    .map(function (val) { return val.trim(); })
    .forEach(val => {
      if (val.indexOf('~') !== -1) {
        result = result.concat(fillRange(val));
      } else {
        // push test data as String
        result.push(val);
        // push test data as Number if the same
        if (String(+val) === val) { result.push(+val); }
      }
    });

  return result;
}

// Create equation for single form rule
function toSingleRule(str) {

  return str
    // replace modulus with shortcuts
    .replace(/([nivwfte]) % (\d+)/g, '$1$2')
    // replace ranges
    .replace(/([nivwfte]\d*) (=|\!=) (\d+[.,][.,\d]+)/g, (match, v, cond, range) => {
      // range = 5,8,9 (simple set)
      if (range.indexOf('..') < 0 && range.indexOf(',') >= 0) {
        if (cond === '=') {
          return `IN([ ${range.split(',').join(', ')} ], ${v})`;
        }
        return `!IN([ ${range.split(',').join(', ')} ], ${v})`;
      }
      // range = 0..5 or 0..5,8..20 or 0..5,8
      let conditions = range.split(',').map(interval => {
        // simple value
        if (interval.indexOf('..') < 0) return `${v} ${cond} ${interval}`;
        // range
        let [ start, end ] = interval.split('..');
        if (cond === '=') return `B(${start}, ${end}, ${v})`;

        return `!B(${start}, ${end}, ${v})`;
      });

      let joined;
      if (conditions.length > 1) {
        joined =  `(${conditions.join(cond === '=' ? ' || ' : ' && ')})`;
      } else {
        joined = conditions[0];
      }
      return joined;
    })
    .replace(/ = /g, ' === ')
    .replace(/ != /g, ' !== ')
    .replace(/ or /g, ' || ')
    .replace(/ and /g, ' && ');
}

const FN_TPL   = fs.readFileSync(path.join(__dirname, 'fn.tpl'), 'utf8');

function createLocaleFn(rules) {

  Object.keys(rules).forEach(r => {
    if (FORMS.indexOf(r) < 0) { throw new Error("Don't know this form: "); }
  });

  // Make sure existing forms are ordered
  let forms = Object.keys(rules).sort((a, b) => FORMS.indexOf(a) > FORMS.indexOf(b));

  if (forms.length === 1) return {};

  let condition = '';

  forms.forEach(function (form, idx) {
    if (form === 'other') {
      condition += idx;
      return;
    }
    let rule = rules[form].split('@')[0].trim();
    condition += `${toSingleRule(rule)} ? ${idx} : `;
  });

  let shortcuts = [ ...new Set(condition.match(/[nivwfte]\d+/g) || []) ] // unique
    .map(sh => `${sh} = ${sh[0]} % ${sh.slice(1)}`)
    .join(', ');

  let pmax = Math.max(
    ...('nivftwe'.split('').map((p, idx) => condition.indexOf(p) < 0 ? -1 : idx))
  ) + 1;

  let fn = _.template(FN_TPL)({
    params: 'nivftwe'.slice(0, pmax).split('').join(', '),
    shortcuts: shortcuts,
    condition: condition
  });

  return {
    c:   forms.map(f => FORMS.indexOf(f)),
    cFn: fn
  };
}

// Create fixtures for single locale rules
function createLocaleTest(rules) {
  let result = {};

  Object.keys(rules).forEach(form => {
    let samples = rules[form].split(/@integer|@decimal/).slice(1);

    result[form] = [];
    samples.forEach(sample => {
      result[form] = result[form].concat(createSamples(sample));
    });
  });

  return result;
}

////////////////////////////////////////////////////////////////////////////////

// Process all locales
let compiled = {};
let test = {
  cardinal: {},
  ordinal: {}
};

// Parse plural rules
Object.entries(cardinals.supplemental['plurals-type-cardinal']).forEach(([ loc, ruleset ]) => {
  let rules = renameKeys(ruleset);

  compiled[loc.toLowerCase()] = createLocaleFn(rules);
  test.cardinal[loc.toLowerCase()] = createLocaleTest(rules);
});

// Parse ordinal rules
Object.entries(ordinals.supplemental['plurals-type-ordinal']).forEach(([ loc, ruleset ]) => {
  let rules = renameKeys(ruleset);

  let res = createLocaleFn(rules);

  if (res.c) {
    compiled[loc.toLowerCase()].o = res.c;
    compiled[loc.toLowerCase()].oFn = res.cFn;
  }

  test.ordinal[loc.toLowerCase()] = createLocaleTest(rules);
});

// Collapse locales with the same rules
let reduced = {};

Object.entries(compiled).forEach(([ loc, data ]) => {
  // calculate unique key;
  let uniq = data.cFn + data.oFn;

  if (!reduced[uniq]) {
    reduced[uniq] = {
      locales: [ loc ],
      rules: data
    };
  } else {
    reduced[uniq].locales.push(loc);
  }
});

reduced = Object.values(reduced);

// Write code & fixture
const ADD_TPL   = fs.readFileSync(path.join(__dirname, 'add.tpl'), 'utf8');
const INDEX_TPL = fs.readFileSync(path.join(__dirname, 'index_tpl.js'), 'utf8');

let generated = _.template(INDEX_TPL)({ version: version })
  .replace('/*** RULES ***/', _.template(ADD_TPL)({ set: reduced }));

fs.writeFileSync(path.resolve(__dirname, '../index.js'), generated);
fs.writeFileSync(path.resolve(__dirname, '../test/test_data.json'), JSON.stringify(test, null, 2));

redpajama_set_name: RedPajamaGithub


text:
package org.snaker.designer.utils;

import java.lang.reflect.Field;

import org.apache.commons.beanutils.PropertyUtils;

/**
 * bean的工具类
 * @author yuqs
 * @version 1.0
 */
public class BeanUtil {
	/**
	 * 获得给定对象与属性名所对应的值
	 * @param bean 给定对象
	 * @param propertyName 属性名
	 * @return 返回该属性对应的值
	 */
	public static Object getPropertyValue(Object bean, String propertyName)
			throws Exception {
		try {
			return PropertyUtils.getProperty(bean, propertyName);
		} catch (Exception e) {
			throw e;
		}
	}

	/**
	 * 判断给定的bean下是否包括给定的属性名,属性名可以不限制深度.
	 * 例如给定Bean有个部门属性,名为org,org.manager.id是深度属性名
	 * @param bean 给定对象
	 * @param propertyName 属性名
	 * @return 如果存在给定的属性名则返回true,否则返回false
	 */
	public static boolean hasPropertyName(Object bean, String propertyName) {
		String[] propertyNames = StringUtils.strToStrArray(propertyName, ".");
		Class<?> clzz = bean.getClass();
		Field field = null;

		for (int i = 0; i < propertyNames.length; i++) {

			// 类型中是否有给定名称的属性
			field = hasClassField(clzz, propertyNames[i]);
			if (field == null)
				return false;

			clzz = field.getType();
		}

		return true;
	}

	public static Class<?> getProperyClass(Object bean, String propertyName) {
		try {
			return PropertyUtils.getPropertyType(bean, propertyName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 递归(直至调用的Object)判断clazz中是否有给定域名(fieldName)的域,如果有则返回对该域对应的
	 * @param clzz
	 * @param fieldName
	 * @return
	 */
	private static Field hasClassField(Class<?> clazz, String fieldName) {
		try {
			return clazz.getDeclaredField(fieldName);
		} catch (Exception e) {
			if (clazz.equals(Object.class))
				return null;
			return hasClassField(clazz.getSuperclass(), fieldName); // �ݹ鴦��,ȥ�����������
		}
	}

	/**
	 * 获得给定对象与属性名所对应的值
	 * @param bean 给定对象
	 * @param propertyName 属性名
	 * @return 返回该属性对应的值,并将该值造型为String类型
	 */
	public static String getPropertyValueToStr(Object bean, String propertyName)
			throws Exception {
		Object val = getPropertyValue(bean, propertyName);

		if (val == null)
			return null;

		return val.toString();
	}

	/**
	 * 为给定对象属性设置值
	 * @param bean 给定对象
	 * @param propertyName 属性名
	 * @param value 值
	 */
	public static void setPropertyValue(Object bean, String propertyName,
			Object value) throws Exception {
		try {
			PropertyUtils.setProperty(bean, propertyName, value);
		} catch (Exception e) {
			throw e;
		}
	}
}


text:
title:  "On Writing"
author: "Wojciech Adam Koszek"
description: >
  Man. This is really damn good book on writing by the master.
  If you need to understand how real professional writer works, this is the
  book.
address: "Menlo Park, CA"
klayout: book
tags:
- books
categories: books
read:	2015-10-21
ads:
-
spellcheck-allow:
-
---

Audiobook format of
["On writing"](http://amzn.to/2mMaaEW)
was excellent.
King read it himself.
This is what I like about audiobook: they make the form be rich and more colorful
by adding this another dimension.
This might be one of the few positions where I can *recommend* the audiobook
over a paper book.

First of all books are great.
I believe you'll have the same while reading or listening to King.

There's a great part about writing as compared to telepathy. This was my
favorite moment in a book. Another one was King's commentary on his own
accident.

King did us a big favor and published his non-fiction piece.
He explained all the inner-workings of the professional, world-class
writer.
One could compare it to Donald Knuth's books, where he explains how he
thinks about the problem.

I'm not a big horror or fiction person. In fact, I find these books hard to
swallow.
You can appreciate the storytelling and all the made up
as I'm more non-fiction hungry reader, but I really enjoyed it.
My confession: I haven't read any of King's books.

It's partially a autobiography, and partially the suggestion guide. But not
same style as [The Elements of Style](http://amzn.to/2lkwaK4), which I found
valuable, but dry and boring. Listening to "On writing" was a pure pleasure,
since it's entertaining and interesting, and the storyline interleaves the
suggestions and advises.

Second part of the book is mostly a guide for writers. Phrased King's way,
they are more memorable than "20 steps to better writing" or lists like
that.

I wish someone did similar book for non-fiction.
But even for my purposes (technical writing, essays on software) this book
will be very usable.
If you're into blog writing or writing of any kind, buy it. You won't
regret; it will help and inspire your.

**NOTE** I rarely re-listen to stuff on Audible, but I did this for King's
book.


text:
layout: default
modal-id: 5
img: safe.png
alt: image-alt
project-date: September - Current
client:  All things Swift
category: Meetup
description:

 I run and speak a monthly Swift Meetup for iOS developers in the Chicago area, some of my talks can be watched below

---


text:
'use strict';

jest.autoMockOff();

const xcode = require('xcode');
const mapHeaderSearchPaths = require('../../ios/mapHeaderSearchPaths');
const path = require('path');

const project = xcode.project(
  path.join(__dirname, '../../__fixtures__/project.pbxproj')
);

describe('ios::mapHeaderSearchPaths', () => {
  beforeEach(() => {
    project.parseSync();
  });

  /**
   * Based on the fixtures, our assumption is that this function
   * has to be executed two times.
   */
  it('should be called twice', () => {
    const callback = jest.fn();
    mapHeaderSearchPaths(project, callback);

    expect(callback.mock.calls.length).toBe(2);
  });
});


text:
#include "config.h"
#include "PageProfilerAgent.h"

#if ENABLE(INSPECTOR)

#include "JSDOMWindow.h"
#include "MainFrame.h"
#include "Page.h"

using namespace Inspector;

namespace WebCore {

PageProfilerAgent::PageProfilerAgent(InstrumentingAgents* instrumentingAgents, Page* page)
    : WebProfilerAgent(instrumentingAgents)
    , m_inspectedPage(page)
{
}

JSC::ExecState* PageProfilerAgent::profilingGlobalExecState() const
{
    return toJSDOMWindow(&m_inspectedPage->mainFrame(), debuggerWorld())->globalExec();
}

} // namespace WebCore

#endif // ENABLE(INSPECTOR)


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>${projectname}</groupId>
	<artifactId>${projectname}</artifactId>
	<version>0.1.0-SNAPSHOT</version>

	<properties>
		<jdk.version>1.6</jdk.version>
		<!-- use UTF-8 for everything -->
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
	</properties>

	<!--
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
	 -->

	<build>
	    <plugins>
	      <plugin>
	        <groupId>org.apache.maven.plugins</groupId>
	        <artifactId>maven-compiler-plugin</artifactId>
	        <configuration>
	          <source>${jdk.version}</source>
	          <target>${jdk.version}</target>
	        </configuration>
	      </plugin>
	    </plugins>
	</build>

</project>


text:
"""Abstract class for collective groups."""
from abc import ABCMeta
from abc import abstractmethod

from ray.util.collective.types import AllReduceOptions, BarrierOptions, \
    ReduceOptions, AllGatherOptions, BroadcastOptions, ReduceScatterOptions

class BaseGroup(metaclass=ABCMeta):
    def __init__(self, world_size, rank, group_name):
        """Init the process group with basic information.

        Args:
            world_size (int): The total number of processes in the group.
            rank (int): The rank of the current process.
            group_name (str): The group name.
        """
        self._world_size = world_size
        self._rank = rank
        self._group_name = group_name

    @property
    def rank(self):
        """Return the rank of the current process."""
        return self._rank

    @property
    def world_size(self):
        """Return the number of processes in this group."""
        return self._world_size

    @property
    def group_name(self):
        """Return the group name of this group."""
        return self._group_name

    def destroy_group(self):
        """GC the communicators."""
        pass

    @classmethod
    def backend(cls):
        """The backend of this collective group."""
        raise NotImplementedError()

    @abstractmethod
    def allreduce(self, tensor, allreduce_options=AllReduceOptions()):
        raise NotImplementedError()

    @abstractmethod
    def barrier(self, barrier_options=BarrierOptions()):
        raise NotImplementedError()

    @abstractmethod
    def reduce(self, tensor, reduce_options=ReduceOptions()):
        raise NotImplementedError()

    @abstractmethod
    def allgather(self,
                  tensor_list,
                  tensor,
                  allgather_options=AllGatherOptions()):
        raise NotImplementedError()

    @abstractmethod
    def broadcast(self, tensor, broadcast_options=BroadcastOptions()):
        raise NotImplementedError()

    @abstractmethod
    def reducescatter(self,
                      tensor,
                      tensor_list,
                      reducescatter_options=ReduceScatterOptions()):
        raise NotImplementedError()

    @abstractmethod
    def send(self, tensor, dst_rank):
        raise NotImplementedError()

    @abstractmethod
    def recv(self, tensor, src_rank):
        raise NotImplementedError()


text:
<?php namespace App\Http\Controllers;

use Ivacuum\Generic\Services\Telegram;

class Upload
{
    public function __invoke(Telegram $telegram)
    {
        $files = request()->file('files');

        foreach ($files as $file) {
            $filename = now()->format('Ymd-His') . '-' . $file->getClientOriginalName();

            \Storage::disk('temp')->putFileAs('', $file, $filename);

            $telegram->notifyAdmin("Загружен файл\n" . url("uploads/temp/{$filename}"));
        }

        session()->flash('message', 'Спасибо за загруженные файлы');

        return redirect('/up');
    }
}


text:
Users, Authentication, and Permissions
======================================

This is a core module found in ``kolibri/auth``.

.. toctree::
   :maxdepth: 1

   uap/concepts_and_definitions
   uap/implementation

Models
------

.. automodule:: kolibri.auth.models
    :members:


text:
"""profiler python module provides APIs to profile TensorFlow models.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=unused-import
from tensorflow.core.profiler.tfprof_log_pb2 import OpLogProto
from tensorflow.core.profiler.tfprof_output_pb2 import AdviceProto
from tensorflow.core.profiler.tfprof_output_pb2 import GraphNodeProto
from tensorflow.core.profiler.tfprof_output_pb2 import MultiGraphNodeProto

from tensorflow.python.profiler.model_analyzer import advise
from tensorflow.python.profiler.model_analyzer import profile
from tensorflow.python.profiler.model_analyzer import Profiler
from tensorflow.python.profiler.option_builder import ProfileOptionBuilder
from tensorflow.python.profiler.tfprof_logger import write_op_log

from tensorflow.python.util.tf_export import tf_export

_allowed_symbols = [
    'Profiler',
    'profile',
    'ProfileOptionBuilder',
    'advise',
    'write_op_log',
]

_allowed_symbols.extend([
    'GraphNodeProto',
    'MultiGraphNodeProto',
    'AdviceProto',
    'OpLogProto',
])

# Export protos
tf_export(v1=['profiler.GraphNodeProto'])(GraphNodeProto)
tf_export(v1=['profiler.MultiGraphNodeProto'])(MultiGraphNodeProto)
tf_export(v1=['profiler.AdviceProto'])(AdviceProto)
tf_export(v1=['profiler.OpLogProto'])(OpLogProto)


text:
require 'yaml'

configs = YAML::load(File.open(File.expand_path('../../.config', __FILE__)))

Rlocu.configure { |rlocu| rlocu.api_key = configs['API_KEY'] }


text:
/*
This is an example of a brush that is similar to the main Sculpting Grab Brush in Cinema4D.
This brush type uses the brush mode SCULPTBRUSHMODE_GRAB. When using this mode
it will select any points under the dab and keep them selected throughout the entire
brush stroke. This is different from the other brush mode where the points for each dab
are updated every time the mouse moves. This allows you to create brushes like the grab brush
where you are just moving those points around until the user lets go of them.
*/

#include "lib_sculptbrush.h"
#include "toolsculptgrabbrush.h"
#include "c4d_symbols.h"
#include "c4d.h"
#include "main.h"

#define SCULPTGRABBRUSH_SDK_EXAMPLE 1029860	//You MUST get your own ID from www.plugincafe.com

class ExampleSculptGrabBrush : public SculptBrushToolData
{
public:
	explicit ExampleSculptGrabBrush(SculptBrushParams* pParams) : SculptBrushToolData(pParams) { }
	~ExampleSculptGrabBrush() { }

	virtual Int32 GetToolPluginId();
	virtual const String GetResourceSymbol();
	virtual void PostInitDefaultSettings(BaseDocument* doc, BaseContainer& data);
	virtual Bool GetDDescription(BaseDocument* doc, BaseContainer& data, Description* description, DESCFLAGS_DESC& flags);

	static Bool MovePointsFunc(BrushDabData* dab);
};

Int32 ExampleSculptGrabBrush::GetToolPluginId()
{
	return SCULPTGRABBRUSH_SDK_EXAMPLE;
}

const String ExampleSculptGrabBrush::GetResourceSymbol()
{
	// Return the name of the .res file, in the res/description and res/strings folder, for this tool.
	return String("toolsculptgrabbrush");
}

// Set our custom values. See the toolsculptgrabbrush.res and toolsculptgrabbrush.h files for where this value is defined.
void ExampleSculptGrabBrush::PostInitDefaultSettings(BaseDocument* doc, BaseContainer& data)
{
	data.SetInt32(MDATA_TOOLSCULPTGRABBRUSH_DIRMODE, MDATA_TOOLSCULPTGRABBRUSH_DIRMODE_MOUSEDIR);
}

// The grab brush does not support the Point Radial Symmetry mode so this has to be disabled.
Bool ExampleSculptGrabBrush::GetDDescription(BaseDocument* doc, BaseContainer& data, Description* description, DESCFLAGS_DESC& flags)
{
	// Call the parent method so that the description data gets loaded in.
	if (!SculptBrushToolData::GetDDescription(doc, data, description, flags))
		return false;

	// Now find and remove the Point mode from the Radial settings.
	AutoAlloc<AtomArray> arr;
	BaseContainer*			 cycle = description->GetParameterI(DescLevel(MDATA_SCULPTBRUSH_MIRRORING_RADIAL_MODE, DTYPE_LONG, 0), arr);
	if (cycle)
	{
		BaseContainer* items = cycle->GetContainerInstance(DESC_CYCLE);
		if (items)
		{
			items->RemoveData(MDATA_SCULPTBRUSH_MIRRORING_RADIAL_MODE_POINT);	// This removes the Point radio button
		}
	}
	return true;
}

// This method does all the work for the brush. Every time the mouse moves this will be called for each brush on the surface of the model.
Bool ExampleSculptGrabBrush::MovePointsFunc(BrushDabData* dab)
{
	PolygonObject* polyObj = dab->GetPolygonObject();
	if (!polyObj)
		return false;

	Int32 a;

	// Get the world matrix for the model so that we can turn local coordinates into world coordinates.
	Matrix mat = polyObj->GetMg();

	// Get the location of the hitpoint on the model in world coordinates
	Vector hitPointWorld = mat * dab->GetHitPoint();

	// Zero out the offset since its no longer required
	mat.off = Vector(0, 0, 0);

	const BaseContainer* pData = dab->GetData();

	// Get our custom direction value that we added to our .res file.
	Int32 dirMode = pData->GetInt32(MDATA_TOOLSCULPTGRABBRUSH_DIRMODE);

	// Find the distance the mouse has moved in world coordinates by getting the world position of the mouse and subtracting the current grab brush world coordinate
	Vector moveAmnt = (dab->GetMousePos3D() - hitPointWorld);

	// Transform this distance into a vector that is in the local coordinates of the model.
	moveAmnt = ~mat * moveAmnt;

	Vector normal = dab->GetNormal();

	switch (dirMode)
	{
		case MDATA_TOOLSCULPTGRABBRUSH_DIRMODE_NORMAL:
		{
			// If we are moving the point in the direction of its normal then use the length of the distance vector to scale the normal.
			moveAmnt = normal * moveAmnt.GetLength();

			// Adjust the direction of the vector depending on if its moving above the surface or below it.
			Float dot = Dot(normal, moveAmnt);
			if (dot < 0)
				moveAmnt *= -1;
			break;
		}
		case MDATA_TOOLSCULPTGRABBRUSH_DIRMODE_MOUSEDIR:
		default:
			// Nothing to do here since moveAmnt is already correct.
			break;
	}

	// Get the original points on the surface of the object. These points are the state of the object when the
	// user first clicks on the model to do a mouse stroke. This allows you to compare where the points are during
	// a stroke, since you have moved them, when the original positions.
	const Vector32* pOriginalPoints = dab->GetOriginalPoints();

	Int32									pointCount = dab->GetPointCount();
	const Vector*					pPoints = dab->GetPoints();
	const BrushPointData* pPointData = dab->GetPointData();

	// If any of the symmetry settings have been enabled, and this is a symmetry stroke instance, then this will return true.
	Bool mirror = dab->IsMirroredDab();

	// Loop over every point on the dab and move them by the moveAmnt.
	for (a = 0; a < pointCount; ++a)
	{
		Int32 pointIndex = pPointData[a].pointIndex;

		// Get the falloff value for this point. This value will take into account the current stencil, stamp settings and the falloff curve to create this value.
		Float fallOff = dab->GetBrushFalloff(a);

		// Get the original location for this point
		Vector original = (Vector64)pOriginalPoints[pointIndex];

		// Get the vector of the point we are going to change.
		const Vector& currentPoint = pPoints[pointIndex];

		// If the user has any of the symmetry settings enabled and this is one of the symmetrical brush instance then mirror will be True.
		// We can check to see if another brush instance has already touched this point and moved it by calling the IsPointModified method.
		// If a point has been touched then that means it has already been moved by a certain vector by that brush instance.
		// This happens when the brushes overlap the same area of the model, which can easily happen if you have a large brush size and are using symmetry.
		// So we just offset it by another vector and do not worry about the original location of the point.
		if (mirror && dab->IsPointModified(pointIndex))
		{
			// Adjust the offset by the new amount.
			dab->OffsetPoint(pointIndex, moveAmnt * fallOff);
		}
		else
		{
			// If there is no symmetry or the point hasn't been touched then we can just set the position of the point normally.
			// First determine the offset vector by using the original location of the point and adding on the new point after it has been adjusted by the falloff value.
			Vector newPosOffset = original + moveAmnt * fallOff;

			// A new offset is calculated by using this new point and its current position.
			Vector offset = newPosOffset - currentPoint;

			// Offset the point to place it in the correct location.
			dab->OffsetPoint(pointIndex, offset);
		}
	}

	// Ensure that all the points for the dab are marked as dirty. This is required to ensure that they all update even if they were not directly
	// touched by this brush instance. Marking all points as dirty ensures that the normals for all points are updated. This is only required
	// for grab brushes when multiple brush instances are touching the same points.
	dab->DirtyAllPoints(SCULPTBRUSHDATATYPE_POINT);
	return true;
}

Bool RegisterSculptGrabBrush()
{
	SculptBrushParams* pParams = SculptBrushParams::Alloc();
	if (!pParams)
		return false;

	// Tell the system that its a grab brush. This means that on mouse down it will grab the selected vertices that are under the brush and
	// then during the entire mouse movement it will only affect those points.
	// If this was set to SCULPTBRUSHMODE_NORMAL then it would select new points every time the brush moves.
	pParams->SetBrushMode(SCULPTBRUSHMODE_GRAB);

	// Hide the pressure value from the HUD when the middle mouse button is pressed or ctrl+shift is held down.
	pParams->EnablePressureHUD(false);

	// This tells the system that the brush is going to be adjusting the points on the layer so it should setup the undo system for points.
	pParams->SetUndoType(SCULPTBRUSHDATATYPE_POINT);

	// Pass in the pointer to the static MovePointsFunc. This will get called for every dab.
	pParams->SetMovePointFunc(&ExampleSculptGrabBrush::MovePointsFunc);

	// Register the tool with Cinema4D.
	return RegisterToolPlugin(SCULPTGRABBRUSH_SDK_EXAMPLE, GeLoadString(IDS_SCULPTGRABBRUSH_TOOL), PLUGINFLAG_TOOL_SCULPTBRUSH | PLUGINFLAG_TOOL_NO_OBJECTOUTLINE, nullptr, GeLoadString(IDS_SCULPTGRABBRUSH_TOOL), NewObjClear(ExampleSculptGrabBrush, pParams));
}


text:
function check_for_test_param(cur_item, cur_test_param)

  nested_files = get_nested_files(cur_item)
  clean_files_list(nested_files)

  cur_regex = Regex("$(cur_test_param)\\s*:\\s*true")

  for nested_file in nested_files

    opened_file = open(nested_file)

    for cur_line in eachline(opened_file)
      stripped_line = strip(cur_line)

      if ( stripped_line == "" )
        continue
      end

      if ( !startswith(stripped_line, "#") )
        break
      end

      if ismatch(cur_regex, stripped_line)
        return true
      end
    end

    close(opened_file)

  end

  return false

end


text:
import datetime
from django.utils import timezone
from datetime import datetime, date, time, timedelta
from django.db import models
from orthg.choiceDict import *
#from lighthouse.models.lapack_routineInfo import lapack_RoutineInfo

class lapack_RoutineInfo(models.Model):
	routine = models.CharField('Routine', max_length=30)
	info = models.TextField('Information', null=True, blank=True, default='')

	def __unicode__(self):
		return self.info

	class Meta:
		app_label = 'orthg'

###---------------- for guided search ----------------###
###--- Orthogonal Problem ---###
class least(models.Model):
        thePrecision = models.CharField('precision', max_length=10, choices=PRECISION_CHOICES)
        routineName = models.CharField('routine name', max_length=30)
        standardGeneralized = models.CharField('standard/generalized', max_length=20, choices=STANDARD_CHOICES)
        complexNumber = models.CharField('complex number', max_length=10, choices=NOYES_CHOICES)
        FullStorage = models.CharField('storage and full', max_length=60, choices=FullStorageNoYes_CHOICES)
        sFullRank = models.CharField('sFullRank', max_length=225,choices=NOYES_CHOICES)
        gFullRank = models.CharField('gFullRank', max_length=225,choices=GFULLRANK_CHOICES)
        singleDouble = models.CharField('single/double', max_length=10, choices=SINGLEDOUBLE_CHOICES)
        notes = models.CharField('notes', max_length=225)
        info = models.ForeignKey(lapack_RoutineInfo)

        def __unicode__(self):
                return self.thePrecision+self.routineName

        class Meta:
                app_label = 'orthg'

'''class factorization(models.Model):
        thePrecision = models.CharField('precision', max_length=10, choices=PRECISION_CHOICES)
        routineName = models.CharField('routine name', max_length=30)
        standardGeneralized = models.CharField('standard/generalized', max_length=20, choices=STANDARD_CHOICES)
        complexNumber = models.CharField('complex number', max_length=10, choices=NOYES_CHOICES)
        StorageType = models.CharField('storage and full', max_length=60, choices=STORAGE_CHOICES) #full and packed
        MatrixType = models.CharField('matrix type', max_length=60, choices=MATRIX_CHOICES)
        sFullRank = models.CharField('sFullRank', max_length=225,choices=NOYES_CHOICES)
        generateQ = models.CharField('generate q', max_length=225,choices=NOYES_CHOICES)
        trapezoidal = models.CharField('trapezoidal matrix', max_length=225,choices=NOYES_CHOICES) #
        gFullRank = models.CharField('gFullRank', max_length=225,choices=GFULLRANK_CHOICES)#
        upperTrian = models.CharField('upper Triangular', max_length=225,choices=GFULLRANK_CHOICES)#
        lowerTrian = models.CharField('upper Triangular', max_length=225,choices=GFULLRANK_CHOICES)#
        singleDouble = models.CharField('single/double', max_length=10, choices=SINGLEDOUBLE_CHOICES)
        notes = models.CharField('notes', max_length=225)
        info = models.ForeignKey(lapack_RoutineInfo)

        def __unicode__(self):
                return self.thePrecision+self.routineName

        class Meta:
                app_label = 'orthg'
'''


text:
title: NServiceBus Host
summary: Avoid writing repeat configuration code, host your endpoints in a Windows Service, and change technologies without code.
tags:
- Hosting
- Configuration
- Logging
- Installation
- NServiceBus.Host
redirects:
 - nservicebus/the-nservicebus-host
related:
- nservicebus/operations/installers
---

To avoid re-writing the same configuration code, or to host your endpoints in a Windows Service, use `NServiceBus.Host.exe`, which can also run as a console.

The NServiceBus host streamlines service development and deployment, allows you to change technologies without code, and is administrator-friendly when setting permissions and accounts.

To use the host just create a new C# class library and reference the NServiceBus.Host NuGet package

```
install-package NServiceBus.Host
```

That's it, the package will create an example endpoint configuration and setup the NServiceBus.Host.exe to run your endpoint.

## Configuring your endpoint

The `NServiceBus.Host.exe` scans the runtime directory for assemblies containing a class that implements the `IConfigureThisEndpoint` interface. This class will contain the configuration for this endpoint. You can read more on how NServiceBus does assembly scanning [here](/nservicebus/hosting/assembly-scanning.md)

If you want to avoid the scanning process you can explicitly configure the type of your endpoint configuration by adding the following to the `NServiceBus.Host.exe.config` file. The below example show the exact syntax:

<!-- import ExplicitHostConfigType -->

## Application Domains

The `NServiceBus.Host.exe` creates a separate *service* [Application Domain](https://msdn.microsoft.com/en-us/library/2bh4z9hs.aspx) to run NServiceBus and the user code. The new domain is assigned a configuration file named after the dll that contains the class implementing `IConfigureThisEndpoint`. All the configuration should be done in that file (as opposed to `NServiceBus.Host.exe.config`). In most cases that means just adding the `app.config` file to the project and letting MSBuild take care of renaming it while moving to the `bin` folder.

NOTE: When the endpoint configuration is not specified explicitly, the host scans all the assemblies to find it and it does so in the context of the *host* application domain, not the new *service* domain. Because of that, when [reditecting assembly versions](https://msdn.microsoft.com/en-us/library/7wd6ex19.aspx), the `assemblyBinding` element needs to be present in both `NServiceBus.Host.exe.config` and `app.config`.

## Custom initialization and startup

As of NServiceBus version 5 you customize the endpoint behavior using the `IConfigureThisEndpoint.Customize` method on your endpoint configuration class. Just call the appropriate methods on the `BusConfiguration` parameter passed to the method.

<!-- import customize_nsb_host -->

#### NServiceBus version 4 and version 3

To change core settings such as assembly scanning, container, and serialization format, implement
`IWantCustomInitialization` on the endpoint configuration class (the same class that implements
`IConfigureThisEndpoint`). You must start the configuration expression `With`

```C#
Configure.With()
```

NOTE: Do not perform any startup behaviors in the `Init` method.

After the custom initialization is done the regular core `INeedInitalization` implementations found will be called in the same way as when you're self hosting.

Defer all startup behavior until all initialization has been completed. At this point, NServiceBus invokes classes that implement the `IWantToRunWhenBusStartsAndStops` (`IWantToRunWhenTheBusStarts` in version 3.x) interface. An example of behavior suitable to implement with `IWantToRunWhenBusStartsAndStops` (`IWantToRunWhenTheBusStarts` in version 3.x) is the opening of the main form in a Windows Forms application. In the back-end Windows Services, classes implementing `IWantToRunWhenBusStartsAndStops`(`IWantToRunWhenTheBusStarts` in version 3.x) should kick off things such as web crawling, data mining, and batch processes.

## Logging

As of NServiceBus version 5 logging for the host is controlled with the same API as the core. This is documented [here](/nservicebus/logging/).

You can add the logging API calls as mentioned in the above article directly in your implementation of `IConfigureThisEndoint.Customize` method.

### NServiceBus version 4 and version 3

To change the host's logging infrastructure, implement the `IWantCustomLogging` interface. In the `Init` method, configure your custom setup. To make NServiceBus use your logger, use the `NServiceBus.SetLoggingLibrary.Log4Net()` API, described in the [logging documentation](/nservicebus/logging) and shown below:

<!-- import CustomHostLogging -->

You may want to specify different logging levels (`DEBUG`, `WARN`, etc.) and possibly different targets `(CONSOLE`, `FILE`, etc.). The host provides a mechanism for changing these permutations with no code or configuration changes, via [profiles](/nservicebus/hosting/nservicebus-host/profiles.md).

## Roles - Built-in configurations

As of version 5 roles are obsoleted and should not be used. Most of the functionality of `AsA_Server`, and `AsA_Publisher` has been made defaults in the core and can be safely removed. If you still need the `AsA_Client` behavior please add the following to your configuration.

<!-- import AsAClientEquivalent -->

#### NServiceBus version 4 and version 3

The rest of the code specifying transport, subscription storage, and other technologies isn't here, because of the `AsA_Server` built-in configuration described next.

While NServiceBus allows you to pick and choose which technologies to use and how to configure each of them, the host packages these choices into three built-in options: `AsA_Client`, `AsA_Server`, and `AsA_Publisher`. All these options make use of `XmlSerializer`, `MsmqTransport`, and `UnicastBus`. The difference is in the configuration:

-   `AsA_Client` sets `MsmqTransport` as non-transactional and purges its queue of messages on startup. This means that it starts afresh every time, not remembering anything before a crash. Also, it processes messages using its own permissions, not those of the message sender.
-   `AsA_Server` sets `MsmqTransport` as transactional and does not purge messages from its queue on startup. This makes it fault-tolerant.
-   `AsA_Publisher` extends `AsA_Server` and indicates to the infrastructure to set up storage for subscription requests, described in the [profiles page](/nservicebus/hosting/nservicebus-host/profiles.md).

## Installation

When running the endpoint within the context of Visual Studio debugger, when the endpoint starts, the needed queues are created on startup to facilitate development. However, when deploying this endpoint to a server, starting the endpoint from the command prompt will not create the needed queues if the queues aren't already present. Creation of queues is a one time cost that will happen during installation only.

To install your process as a Windows Service, you need to pass `/install` on the command line to the host. By default, the name of the service is the name of your endpoint and the endpoint name is the namespace of your endpoint configuration class. To enable side-by-side operations, use the `/sideBySide` switch to add the SemVer version to the service name. Passing /install also causes the host to invoke the [installers](/nservicebus/operations/installers.md) .

To override this and specify additional details for installation:

```
NServiceBus.Host.exe [/install [/serviceName]
[/displayName]
[/description]
[/endpointConfigurationType]
[/endpointName]
[/installInfrastructure]
[/scannedAssemblies]
[/dependsOn]
[/sideBySide]
[/startManually]
[/username]
[/password]]
[/uninstall [/serviceName]
[/sidebyside]
[/instance:Instance Name ]
```

You can get to this list by running the following at the command line:

```
NServiceBus.Host.exe /?
```

To set the actual name of the Windows Services in the registry, specify `/serviceName:YourServiceName`. This is different from what you see in the Windows Service Manager.

To set the name of the Windows Service as you see it in the Windows Service Manager, specify `/displayName:YourService`.

If you do not specify `/displayName`, but do specify `/serviceName`, the display name does not become what was passed in the `/serviceName`, but rather the default described above.

To set the description shown in the Windows Service Manager, specify
`/description:DescriptionOfYourService`.

To install multiple instances of the same service by providing each a different instance name, use the 'instance' flag. For example: `/instance:Instance5`.

By default, Windows Services start automatically when the operating system starts. To change that, add
`/startManually` to the `/install` command.

To specify under which account you want your service to run, pass in the username and password of that account.

Following is an example of the `/install` command line:

```
NServiceBus.Host.exe /install /serviceName:"MyPublisher"
/displayName:"My Publisher Service"
/description:"Service for publishing event messages"
/endpointConfigurationType:"YourNameSpace.YourEndpointConfigType, YourAssembly"
/username:"corp\serviceuser"
/password:"p@ssw0rd!" NServiceBus.Production
```

NOTE: When installing the Host using a custom user account, as in the above sample, the user account is added to the `Performance Monitor Users` and is granted `run as a service` privileges. If, at a later time, the user needs to be changed it is suggested to uninstall the Host and re-install it in order to guarantee that the new user is correctly setup.

To uninstall, call

```
NServiceBus.Host.exe /uninstall
```

If you specify a service name or instance name when installing your service, you need to pass them in to the uninstall command as well:

```
NServiceBus.Host.exe [/uninstall  [/serviceName] [/instance]]
```

For example:

```
NServiceBus.Host.exe /uninstall /serviceName:YourServiceName /instance:YourInstanceName
```

To invoke the infrastructure installers, run the host with the `/installInfrastructure` switch.


text:
package com.egen.models;

import org.mongodb.morphia.annotations.Entity;
import org.mongodb.morphia.annotations.Id;

/**
 * The Entity Class Metric.
 */
@Entity("metrics")
public class Metric {

	@Id
	private long timeStamp;

	private int value;

	public Metric() {
	}

	/**
	 * Gets the time stamp.
	 *
	 * @return the time stamp
	 */
	public long getTimeStamp() {
		return timeStamp;
	}

	/**
	 * Sets the time stamp.
	 *
	 * @param timeStamp the new time stamp
	 */
	public void setTimeStamp(long timeStamp) {
		this.timeStamp = timeStamp;
	}

	/**
	 * Gets the value.
	 *
	 * @return the value
	 */
	public int getValue() {
		return value;
	}

	/**
	 * Sets the value.
	 *
	 * @param value the new value
	 */
	public void setValue(int value) {
		this.value = value;
	}

}


text:
<?xml version="1.0" encoding="utf-8"?>
<SampleMetadata>
  <ID>0fb4f1b8-217f-4dc3-a239-9744cd9c102f</ID>
  <IsFullApplication>false</IsFullApplication>
  <Level>Beginner</Level>
  <Tags>Games, iOS9</Tags>
  <LicenseRequirement>Starter</LicenseRequirement>
  <SupportedPlatforms>iOS</SupportedPlatforms>
  <Gallery>true</Gallery>
  <Brief>Demonstrates how to use the GKMinmaxStrategist class to implement a computer-controlled opponent.</Brief>
</SampleMetadata>


text:
package server_test

import (
	"context"
	"io"
	"net/http"
	"strings"
	"testing"
	"testing/iotest"

	discovery "github.com/datawire/ambassador/pkg/api/envoy/api/v2"
	"github.com/datawire/ambassador/pkg/envoy-control-plane/cache/types"
	"github.com/datawire/ambassador/pkg/envoy-control-plane/cache/v2"
	"github.com/datawire/ambassador/pkg/envoy-control-plane/resource/v2"
	rsrc "github.com/datawire/ambassador/pkg/envoy-control-plane/resource/v2"
	"github.com/datawire/ambassador/pkg/envoy-control-plane/server/v2"
)

type logger struct {
	t *testing.T
}

func (log logger) Debugf(format string, args ...interface{}) { log.t.Logf(format, args...) }
func (log logger) Infof(format string, args ...interface{})  { log.t.Logf(format, args...) }
func (log logger) Warnf(format string, args ...interface{})  { log.t.Logf(format, args...) }
func (log logger) Errorf(format string, args ...interface{}) { log.t.Logf(format, args...) }

func TestGateway(t *testing.T) {
	config := makeMockConfigWatcher()
	config.responses = map[string][]cache.RawResponse{
		resource.ClusterType: {{
			Version:   "2",
			Resources: []types.Resource{cluster},
			Request:   discovery.DiscoveryRequest{TypeUrl: rsrc.ClusterType},
		}},
		resource.RouteType: {{
			Version:   "3",
			Resources: []types.Resource{route},
			Request:   discovery.DiscoveryRequest{TypeUrl: rsrc.RouteType},
		}},
		resource.ListenerType: {{
			Version:   "4",
			Resources: []types.Resource{listener},
			Request:   discovery.DiscoveryRequest{TypeUrl: rsrc.ListenerType},
		}},
	}
	gtw := server.HTTPGateway{Log: logger{t: t}, Server: server.NewServer(context.Background(), config, nil)}

	failCases := []struct {
		path   string
		body   io.Reader
		expect int
	}{
		{
			path:   "/hello/",
			expect: http.StatusNotFound,
		},
		{
			path:   resource.FetchEndpoints,
			expect: http.StatusBadRequest,
		},
		{
			path:   resource.FetchEndpoints,
			body:   iotest.TimeoutReader(strings.NewReader("hello")),
			expect: http.StatusBadRequest,
		},
		{
			path:   resource.FetchEndpoints,
			body:   strings.NewReader("hello"),
			expect: http.StatusBadRequest,
		},
		{
			// missing response
			path:   resource.FetchEndpoints,
			body:   strings.NewReader("{\"node\": {\"id\": \"test\"}}"),
			expect: http.StatusInternalServerError,
		},
	}
	for _, cs := range failCases {
		req, err := http.NewRequest(http.MethodPost, cs.path, cs.body)
		if err != nil {
			t.Fatal(err)
		}
		resp, code, err := gtw.ServeHTTP(req)
		if resp != nil {
			t.Errorf("handler returned wrong response")
		}
		if status := code; status != cs.expect {
			t.Errorf("handler returned wrong status: %d, want %d", status, cs.expect)
		}
	}

	for _, path := range []string{resource.FetchClusters, resource.FetchRoutes, resource.FetchListeners} {
		req, err := http.NewRequest(http.MethodPost, path, strings.NewReader("{\"node\": {\"id\": \"test\"}}"))
		if err != nil {
			t.Fatal(err)
		}
		resp, code, err := gtw.ServeHTTP(req)
		if resp == nil {
			t.Errorf("handler returned wrong response")
		}
		if status := code; status != 200 {
			t.Errorf("handler returned wrong status: %d, want %d", status, 200)
		}
	}
}


text:
import chalk from "chalk"

export function printErrorAndExit(error: Error) {
  console.error(chalk.red((error.stack || error).toString()))
  process.exit(-1)
}

// you don't need to handle error in your task - it is passed only indicate status of promise
export async function executeFinally<T>(promise: Promise<T>, task: (errorOccurred: boolean) => Promise<any>): Promise<T> {
  let result: T | null = null
  try {
    result = await promise
  }
  catch (originalError) {
    try {
      await task(true)
    }
    catch (taskError) {
      throw new NestedError([originalError, taskError])
    }

    throw originalError
  }

  try {
    await task(false)
  }
  catch (taskError) {
    throw taskError
  }
  return result
}

export class NestedError extends Error {
  constructor(errors: Array<Error>, message: string = "Compound error: ") {
    let m = message
    let i = 1
    for (const error of errors) {
      const prefix = `Error #${i++} `
      m += "\n\n" + prefix + "-".repeat(80) + "\n" + error!.stack
    }
    super(m)
  }
}

export function orNullIfFileNotExist<T>(promise: Promise<T>): Promise<T | null> {
  return orIfFileNotExist(promise, null)
}

export function orIfFileNotExist<T>(promise: Promise<T>, fallbackValue: T): Promise<T> {
  return promise
    .catch(e => {
      if (e.code === "ENOENT" || e.code === "ENOTDIR") {
        return fallbackValue
      }
      throw e
    })
}


text:
(
    cd geolite2
    ./download.sh
    python setup.py sdist bdist_wheel
    twine upload dist/* -u graingert-autopypi -p "${PYPI_PASSWORD}"
)


text:
/*
 * This is a manifest file that'll be compiled into application.css, which will include all the files
 * listed below.
 *
 * Any CSS and SCSS file within this directory, lib/assets/stylesheets, vendor/assets/stylesheets,
 * or any plugin's vendor/assets/stylesheets directory can be referenced here using a relative path.
 *
 * You're free to add application-wide styles to this file and they'll appear at the bottom of the
 * compiled file so the styles you add here take precedence over styles defined in any styles
 * defined in the other CSS/SCSS files in this directory. It is generally better to create a new
 * file per style scope.
 *
 *= require_tree .
 *= require_self
 */
 .jumbotron {
   background: #532F8C;
   color: white;
   padding-bottom: 80px; }
   .jumbotron .btn-primary {
     background: #845ac7;
     border-color: #845ac7; }
     .jumbotron .btn-primary:hover {
       background: #7646c1; }
   .jumbotron p {
     color: #d9ccee;
     max-width: 75%;
     margin: 1em auto 2em; }
   .navbar + .jumbotron {
     margin-top: -20px; }
   .jumbotron .lang-logo {
     display: block;
     background: #B01302;
     border-radius: 50%;
     overflow: hidden;
     width: 100px;
     height: 100px;
     margin: auto;
     border: 2px solid white; }
     .jumbotron .lang-logo img {
       max-width: 100%; }


text:
package org.drools.workbench.screens.guided.dtable.backend.server;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import org.drools.workbench.screens.guided.dtable.model.GuidedDecisionTableEditorGraphModel;
import org.kie.soup.xstream.XStreamUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class GuidedDTGraphXMLPersistence {

    private static final Logger logger = LoggerFactory.getLogger( GuidedDTGraphXMLPersistence.class );

    private static final GuidedDTGraphXMLPersistence INSTANCE = new GuidedDTGraphXMLPersistence();

    private XStream xt;

    private GuidedDTGraphXMLPersistence() {
        xt = XStreamUtils.createTrustingXStream(new DomDriver());
        xt.alias( "graph",
                  GuidedDecisionTableEditorGraphModel.class );
        xt.alias( "entry",
                  GuidedDecisionTableEditorGraphModel.GuidedDecisionTableGraphEntry.class );
    }

    public static GuidedDTGraphXMLPersistence getInstance() {
        return INSTANCE;
    }

    public String marshal( final GuidedDecisionTableEditorGraphModel content ) {
        if ( content == null ) {
            return xt.toXML( new GuidedDecisionTableEditorGraphModel() );
        }

        try {
            return xt.toXML( content );

        } catch ( Exception e ) {
            logger.error( "Unable to marshal model. Returning a XML for empty GuidedDecisionTableEditorGraphModel.",
                          e );
        }
        return xt.toXML( new GuidedDecisionTableEditorGraphModel() );
    }

    public GuidedDecisionTableEditorGraphModel unmarshal( final String xml ) {
        if ( xml == null || xml.trim().equals( "" ) ) {
            return new GuidedDecisionTableEditorGraphModel();
        }

        try {
            final Object o = xt.fromXML( xml );
            return (GuidedDecisionTableEditorGraphModel) o;

        } catch ( Exception e ) {
            logger.error( "Unable to unmarshal content. Returning an empty GuidedDecisionTableEditorGraphModel.",
                          e );
        }
        return new GuidedDecisionTableEditorGraphModel();
    }

}


text:
#include "ipc/IpcServerProxy.h"

#include "ipc/IpcMessage.h"
#include "ipc/Ipc.h"
#include "synergy/ProtocolUtil.h"
#include "io/IStream.h"
#include "base/TMethodEventJob.h"
#include "base/Log.h"

//
// IpcServerProxy
//

IpcServerProxy::IpcServerProxy(synergy::IStream& stream, IEventQueue* events) :
	m_stream(stream),
	m_events(events)
{
	m_events->adoptHandler(m_events->forIStream().inputReady(),
		stream.getEventTarget(),
		new TMethodEventJob<IpcServerProxy>(
		this, &IpcServerProxy::handleData));
}

IpcServerProxy::~IpcServerProxy()
{
	m_events->removeHandler(m_events->forIStream().inputReady(),
		m_stream.getEventTarget());
}

void
IpcServerProxy::handleData(const Event&, void*)
{
	LOG((CLOG_DEBUG "start ipc handle data"));

	UInt8 code[4];
	UInt32 n = m_stream.read(code, 4);
	while (n != 0) {

		LOG((CLOG_DEBUG "ipc read: %c%c%c%c",
			code[0], code[1], code[2], code[3]));

		IpcMessage* m = nullptr;
		if (memcmp(code, kIpcMsgLogLine, 4) == 0) {
			m = parseLogLine();
		}
		else if (memcmp(code, kIpcMsgShutdown, 4) == 0) {
			m = new IpcShutdownMessage();
		}
		else {
			LOG((CLOG_ERR "invalid ipc message"));
			disconnect();
		}

		// don't delete with this event; the data is passed to a new event.
		Event e(m_events->forIpcServerProxy().messageReceived(), this, NULL, Event::kDontFreeData);
		e.setDataObject(m);
		m_events->addEvent(e);

		n = m_stream.read(code, 4);
	}

	LOG((CLOG_DEBUG "finished ipc handle data"));
}

void
IpcServerProxy::send(const IpcMessage& message)
{
	LOG((CLOG_DEBUG4 "ipc write: %d", message.type()));

	switch (message.type()) {
	case kIpcHello: {
		const IpcHelloMessage& hm = static_cast<const IpcHelloMessage&>(message);
		ProtocolUtil::writef(&m_stream, kIpcMsgHello, hm.clientType());
		break;
	}

	case kIpcCommand: {
		const IpcCommandMessage& cm = static_cast<const IpcCommandMessage&>(message);
		String command = cm.command();
		ProtocolUtil::writef(&m_stream, kIpcMsgCommand, &command);
		break;
	}

	default:
		LOG((CLOG_ERR "ipc message not supported: %d", message.type()));
		break;
	}
}

IpcLogLineMessage*
IpcServerProxy::parseLogLine()
{
	String logLine;
	ProtocolUtil::readf(&m_stream, kIpcMsgLogLine + 4, &logLine);

	// must be deleted by event handler.
	return new IpcLogLineMessage(logLine);
}

void
IpcServerProxy::disconnect()
{
	LOG((CLOG_DEBUG "ipc disconnect, closing stream"));
	m_stream.close();
}


text:
class Kafka < Formula
  desc "Publish-subscribe messaging rethought as a distributed commit log"
  homepage "https://kafka.apache.org"
  url "https://www.apache.org/dyn/closer.cgi?path=/kafka/0.11.0.0/kafka_2.12-0.11.0.0.tgz"
  mirror "http://mirror.nbtelecom.com.br/apache/kafka/0.11.0.0/kafka_2.12-0.11.0.0.tgz"
  sha256 "ab6310dd0d9fce1e6e8045b51b471fb35c3e197714e6e6b03bc5864898785f2d"

  bottle do
    cellar :any_skip_relocation
    sha256 "05ea7cc4ef87cae1720d83aeb9fe01efea82d22b36a2af2aecac3f848792bc6c" => :sierra
    sha256 "18286d88acbaef11b66cec0f73efddf2ea614f298e31bfa717c8fae880898887" => :el_capitan
    sha256 "18286d88acbaef11b66cec0f73efddf2ea614f298e31bfa717c8fae880898887" => :yosemite
  end

  depends_on "zookeeper"
  depends_on :java => "1.8+"

  # Related to https://issues.apache.org/jira/browse/KAFKA-2034
  # Since Kafka does not currently set the source or target compability version inside build.gradle
  # if you do not have Java 1.8 installed you cannot used the bottled version of Kafka
  pour_bottle? do
    reason "The bottle requires Java 1.8."
    satisfy { quiet_system("/usr/libexec/java_home --version 1.8 --failfast") }
  end

  def install
    data = var/"lib"
    inreplace "config/server.properties",
      "log.dirs=/tmp/kafka-logs", "log.dirs=#{data}/kafka-logs"

    inreplace "config/zookeeper.properties",
      "dataDir=/tmp/zookeeper", "dataDir=#{data}/zookeeper"

    # remove Windows scripts
    rm_rf "bin/windows"

    libexec.install "libs"

    prefix.install "bin"
    bin.env_script_all_files(libexec/"bin", Language::Java.java_home_env("1.8+"))
    Dir["#{bin}/*.sh"].each { |f| mv f, f.to_s.gsub(/.sh$/, "") }

    mv "config", "kafka"
    etc.install "kafka"
    libexec.install_symlink etc/"kafka" => "config"

    # create directory for kafka stdout+stderr output logs when run by launchd
    (var+"log/kafka").mkpath
  end

  plist_options :manual => "zookeeper-server-start #{HOMEBREW_PREFIX}/etc/kafka/zookeeper.properties & kafka-server-start #{HOMEBREW_PREFIX}/etc/kafka/server.properties"

  def plist; <<-EOS.undent
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
        <key>Label</key>
        <string>#{plist_name}</string>
        <key>WorkingDirectory</key>
        <string>#{HOMEBREW_PREFIX}</string>
        <key>ProgramArguments</key>
        <array>
            <string>#{opt_bin}/kafka-server-start</string>
            <string>#{etc}/kafka/server.properties</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>KeepAlive</key>
        <true/>
        <key>StandardErrorPath</key>
        <string>#{var}/log/kafka/kafka_output.log</string>
        <key>StandardOutPath</key>
        <string>#{var}/log/kafka/kafka_output.log</string>
    </dict>
    </plist>
    EOS
  end

  test do
    ENV["LOG_DIR"] = "#{testpath}/kafkalog"

    (testpath/"kafka").mkpath
    cp "#{etc}/kafka/zookeeper.properties", testpath/"kafka"
    cp "#{etc}/kafka/server.properties", testpath/"kafka"
    inreplace "#{testpath}/kafka/zookeeper.properties", "#{var}/lib", testpath
    inreplace "#{testpath}/kafka/server.properties", "#{var}/lib", testpath

    begin
      fork do
        exec "#{bin}/zookeeper-server-start #{testpath}/kafka/zookeeper.properties > #{testpath}/test.zookeeper-server-start.log 2>&1"
      end

      sleep 15

      fork do
        exec "#{bin}/kafka-server-start #{testpath}/kafka/server.properties > #{testpath}/test.kafka-server-start.log 2>&1"
      end

      sleep 30

      system "#{bin}/kafka-topics --zookeeper localhost:2181 --create --if-not-exists --replication-factor 1 --partitions 1 --topic test > #{testpath}/kafka/demo.out 2>/dev/null"
      pipe_output("#{bin}/kafka-console-producer --broker-list localhost:9092 --topic test 2>/dev/null", "test message")
      system "#{bin}/kafka-console-consumer --zookeeper localhost:2181 --topic test --from-beginning --max-messages 1 >> #{testpath}/kafka/demo.out 2>/dev/null"
      system "#{bin}/kafka-topics --zookeeper localhost:2181 --delete --topic test >> #{testpath}/kafka/demo.out 2>/dev/null"
    ensure
      system "#{bin}/kafka-server-stop"
      system "#{bin}/zookeeper-server-stop"
      sleep 10
    end

    assert_match /test message/, IO.read("#{testpath}/kafka/demo.out")
  end
end


text:
package com.griddynamics.jagger.monitoring.reporting;

import com.griddynamics.jagger.dbapi.entity.WorkloadData;
import com.griddynamics.jagger.reporting.AbstractMappedReportProvider;

import java.util.List;

public abstract class AbstractMonitoringReportProvider<T> extends AbstractMappedReportProvider<T> {

    public void clearCache() {
    }

    protected String parentOf(String workloadTaskId) {
        String sessionId = getSessionIdProvider().getSessionId();
        List<WorkloadData> list = (List<WorkloadData>) getHibernateTemplate().find("select wd from WorkloadData wd where wd.sessionId =? and wd.taskId =? and wd.parentId is not null", sessionId, workloadTaskId);

        if (list.size() == 1) {
            return list.get(0).getParentId();
        }

        return null;
    }
}


text:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'project/picarchive.db',
    }
}

EMAIL_HOST = ''
EMAIL_HOST_USER = DEFAULT_FROM_EMAIL = SERVER_EMAIL = 'no-reply@myhost.ru'
EMAIL_SUBJECT_PREFIX = '[PicArchive] '
EMAIL_HOST_PASSWORD = ''
EMAIL_PORT = 25
EMAIL_USE_TLS = False


text:
//-----------------------------------------------------------------------
// <copyright file="FirstPass.cs" company="Richard Smith">
//     Copyright (c) Richard Smith. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace GraphEnlargement.Sanders
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using QuickGraph;

    /// <summary>
    /// The first pass graph expansion algorith from:
    /// I. Sanders. Cooperating to buy shoes: An application of picking cycles in directed graphs.
    /// In Proceedings of the South African Institute of Computer Scientists and Information Technologists (Theme: "A Connected Society"), pages 8-16, East London, 2013.
    /// </summary>
    public class FirstPass : IGraphEnlargementAlgorithm
    {
        /// <inheritdoc/>
        public BidirectionalGraph<TVertex, Edge<TVertex>> Apply<TVertex>(BidirectionalGraph<TVertex, Edge<TVertex>> inputGraph, Func<string, TVertex, TVertex, TVertex> vertexFactory)
            where TVertex : class, IGraphEnlargementVertex
        {
            var result = inputGraph.Clone();

            var disconnected = new Stack<TVertex>(result.Vertices.Where(x => result.IsInEdgesEmpty(x) && result.IsOutEdgesEmpty(x)));
            var noInEdge = new Stack<TVertex>(result.Vertices.Where(x => result.IsInEdgesEmpty(x) && !result.IsOutEdgesEmpty(x)));
            var noOutEdge = new Stack<TVertex>(result.Vertices.Where(x => !result.IsInEdgesEmpty(x) && result.IsOutEdgesEmpty(x)));
            var use = new Queue<TVertex>(result.Vertices.Where(x => !result.IsInEdgesEmpty(x) && !result.IsOutEdgesEmpty(x)).Reverse());

            while (disconnected.Count > 0 || noInEdge.Count > 0 || noOutEdge.Count > 0)
            {
                var first = noOutEdge.Count > 0 ? noOutEdge.Pop() : null;
                var last = noInEdge.Count > 0 ? noInEdge.Pop() : null;
                var mid = disconnected.Count > 0 ? disconnected.Pop() : null;

                if (mid != null)
                {
                    if (first == null)
                    {
                        first = use.Dequeue();
                        use.Enqueue(first);
                    }

                    if (last == null)
                    {
                        last = use.Dequeue();
                        use.Enqueue(last);
                    }

                    var dummy1 = vertexFactory("Dummy 1", first, mid);
                    var dummy2 = vertexFactory("Dummy 2", mid, last);
                    result.AddVertex(dummy1);
                    result.AddVertex(dummy2);

                    result.AddEdge(new Edge<TVertex>(first, dummy1));
                    result.AddEdge(new Edge<TVertex>(dummy1, mid));
                    result.AddEdge(new Edge<TVertex>(mid, dummy2));
                    result.AddEdge(new Edge<TVertex>(dummy2, last));
                }
                else
                {
                    if (first == null)
                    {
                        first = use.Dequeue();
                        use.Enqueue(first);
                    }

                    if (last == null)
                    {
                        last = use.Dequeue();
                        use.Enqueue(last);
                    }

                    var dummy3 = vertexFactory("Dummy 3", first, last);
                    result.AddVertex(dummy3);

                    result.AddEdge(new Edge<TVertex>(first, dummy3));
                    result.AddEdge(new Edge<TVertex>(dummy3, last));
                }
            }

            return result;
        }
    }
}


text:
import os
import sys

try:
    from setuptools import setup
except ImportError:
    from distutils.core import setup

import project

if sys.argv[-1] == 'publish':
    os.system('python setup.py sdist upload')
    sys.exit()

with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as f:
    readme = f.read()

packages = [
    'project',
]

package_data = {
}

requires = [
    "Django>=1.7"
]

classifiers = [
    'Development Status :: 3 - Alpha',
    'Environment :: Web Environment',
    'Framework :: Django',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: MIT License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Programming Language :: Python :: 2.7',
    'Topic :: Internet :: WWW/HTTP :: Dynamic Content'
]

setup(
    name='project',
    version=project.__version__,
    description='Examples for jquery.django-formset',
    long_description=readme,
    packages=packages,
    package_data=package_data,
    install_requires=requires,
    author=project.__author__,
    author_email='mbertheau@gmail.com',
    url='https://github.com/mbertheau/jquery.django-formset',
    license='MIT',
    classifiers=classifiers,
)


text:
<template name="accountsLayout">
  <div class="accounts">
    {{> yield}}
  </div>
</template>


text:
import upperFirst from 'lodash/upperFirst';
import camelCase from 'lodash/camelCase';
import Blueprint from '../../lib/blueprint';

export default class ModelBlueprint extends Blueprint {

  static blueprintName = 'model';
  static description = 'Generates a blank model';

  params = [ 'name' ];

  locals({ name }) {
    return {
      name,
      className: upperFirst(camelCase(name))
    };
  }

}


text:
package com.consol.citrus.restdocs.integration;

import com.consol.citrus.annotations.CitrusXmlTest;
import com.consol.citrus.testng.spring.TestNGCitrusSpringSupport;
import org.testng.annotations.Test;

/**
 * @author Christoph Deppisch
 */
public class SoapRestDocsIT extends TestNGCitrusSpringSupport {
    @Test
    @CitrusXmlTest(name = "SoapRestDocsIT")
    public void soapRestDocsIT() {}
}


text:
FormsModule

<md-card>
  <md-card-title>
    Registration form
  </md-card-title>
  <form novalidate #f="ngForm">
    <input [ngModel]="name.first" name="first" placeholder="First name">
    <input [ngModel]="name.last" name="last" placeholder="Last name">

      Account
      <input ngModel name="username" placeholder="Username">
      <input ngModel name="password" placeholder="Password" required
      #password="ngModel">
      <input ngModel name="confirm" placeholder="Confirm password" required>

    <md-card-actions align="end">
      <button md-button>SUBMIT</button>
    </md-card-actions>
  </form>
</md-card>
<md-card>

Form: {{ f.value | json }}

Form status: {{ f.control.status }}

Account errors: {{ account.control?.errors | json  }}

</md-card>


text:
package w2.com.br.easy_game_app.ui;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

import w2.com.br.easy_game_app.ListAdapter.ListAdapterJogador;
import w2.com.br.easy_game_app.R;
import w2.com.br.easy_game_app.async.GenericAsyncTask;
import w2.com.br.easy_game_app.entity.Atualizavel;
import w2.com.br.easy_game_app.entity.Equipe;
import w2.com.br.easy_game_app.entity.Usuario;
import w2.com.br.easy_game_app.enuns.Method;
import w2.com.br.easy_game_app.enuns.TipoPosicao;

public class MapaUsuariosActivity extends FragmentActivity implements OnMapReadyCallback, Atualizavel {

    private GoogleMap mMap;
    private Marker marker;
    private Spinner sp;
    ArrayAdapter<TipoPosicao> adapter;
    private final String servicoMapa = "usuario/coordenadas/1";
    private List<Usuario> jogadores;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mapa_usuarios);

        SupportMapFragment mapaFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapa_usuarios));
        mapaFragment.getMapAsync(this);

        //spinner posição
        adapter = new ArrayAdapter<TipoPosicao>(this, android.support.design.R.layout.support_simple_spinner_dropdown_item, TipoPosicao.values());
        adapter.setDropDownViewResource(android.support.design.R.layout.support_simple_spinner_dropdown_item);

        //chamar coordenadas de jogadores
        new GenericAsyncTask(MapaUsuariosActivity.this, this, Method.GET, String.format("%s", servicoMapa)).execute();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

//        LatLng sydney = new LatLng(-25.358840, -49.214756);
//        mMap.addMarker(new MarkerOptions().position(sydney).title("(41)99221257"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));

        LatLng sydney = new LatLng(-25.358840, -49.214756);

//        mMap.addMarker(new MarkerOptions().position(sydney).title("(41)99221257"));
//        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 17));

//        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12));
//        mMap.setMapType(0);

//        customMarker(new LatLng(-25.358840, -49.214756), "Marcador 1", "title marcador 1");
//        customMarker(new LatLng(-25.358832, -49.214740), "Marcador 2", "title marcador 2");
        //EVENTS
//        mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
//            @Override
//            public void onCameraChange(CameraPosition cameraPosition) {
//                Log.i("Script", "setOnCameraChangeListner");
//                if(marker!= null){
//                    marker.remove();
//                }
//                customMarker(new LatLng(cameraPosition.target.latitude,cameraPosition.target.longitude),"1: MAracador ALterado","O markador foi reposicionado");
//
//            }
//        });

//        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
//            @Override
//            public void onMapClick(LatLng latLng) {
//                Log.i("Script", "setOnMapClickListener");
//                if (marker != null) {
//                    marker.remove();
//                }
//                customMarker(new LatLng(latLng.latitude, latLng.longitude), "2: MAracador ALterado", "O markador foi reposicionado");
//
//            }
//        });
//        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
//            @Override
//            public boolean onMarkerClick(Marker marker) {
//                Log.i("Script", "3: Marker: " + marker.getTitle());
//
//                return false;
//            }
//        });
        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {
                Log.i("Script", "4: Marker: " + marker.getTitle());
                LayoutInflater inflater = getLayoutInflater();

                final View dialoglayout = inflater.inflate(R.layout.activity_invite, null);

                sp = (Spinner) dialoglayout.findViewById(R.id.sp_posicao_invite);
                sp.setAdapter(adapter);
                Button btnSendMail = (Button) dialoglayout.findViewById(R.id.btnConvite);
                btnSendMail.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        EditText ttNome = (EditText) dialoglayout.findViewById(R.id.nome_usuario);
                        EditText ttApelido = (EditText) dialoglayout.findViewById(R.id.apelido_usuario);
                        TipoPosicao tipoPosicao = (TipoPosicao) sp.getSelectedItem();
                        Usuario usuario = new Usuario();
                        usuario.setTipoPosicao(tipoPosicao);
                        if (ttNome != null) {
                            String nome = ttNome.getText().toString();
                            usuario.setNome(nome);
                        }
                        if (ttApelido != null) {
                            String apelido = ttApelido.getText().toString();
                            usuario.setApelido(apelido);
                        }
                        if (usuario.getTipoPosicao() != null) {
                            Toast.makeText(getApplicationContext(), "Você é fodão! ", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

                AlertDialog.Builder builder = new AlertDialog.Builder(MapaUsuariosActivity.this);
                builder.setView(dialoglayout);
                builder.show();
            }
        });
    }

    public void customMarker(LatLng latLng, String title, String snippet) {
        MarkerOptions options = new MarkerOptions();
        options.position(latLng).title(title).snippet(snippet);

        //criar o marker
        marker = mMap.addMarker(options);

    }
    public void customMarkers(List<Usuario>jds) {
        LatLng sydney = new LatLng(-25.358840, -49.214756);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 12));
        mMap.setMapType(0);
        for (Usuario usuario : jds) {
            LatLng latLng = new LatLng(usuario.getLatitude(), usuario.getLongitude());
            String dados = String.format("%s %s %s", usuario.getApelido(), usuario.getTelefone(), usuario.getTipoPosicao().getDescricao());
            MarkerOptions options = new MarkerOptions();
            options.position(latLng).title(dados).snippet(dados);

            //criar o marker
            mMap.addMarker(options);
        }

    }

    @Override
    public void atualizar(JSONObject jsonObject) throws JSONException {
        jogadores = new ArrayList<>();
        JSONObject retorno = null;
        if (jsonObject.has("objeto")) {
            retorno = new JSONObject(jsonObject.getString("objeto"));
            try {
                if (retorno.has("objeto")) {
                    JSONObject objeto = retorno.getJSONObject("objeto");
                    JSONArray array = objeto.getJSONArray("coordenadas");
                    for (int i = 0; i < array.length(); i++) {
                        jogadores.add(Usuario.toCoordenadasUsuario(array.getJSONObject(i)));
                    }
                    customMarkers(jogadores);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if (jsonObject.has("erro")) {
            //TODO Toast;
            Toast.makeText(this, retorno.get("erro").toString(), Toast.LENGTH_SHORT).show();
        }
    }
}


text:
namespace autofill::autofill_metrics {

void LogVirtualCardManualFallbackBubbleShown(bool is_reshow) {
  base::UmaHistogramBoolean("Autofill.VirtualCardManualFallbackBubble.Shown",
                            is_reshow);
}

void LogVirtualCardManualFallbackBubbleResultMetric(
    VirtualCardManualFallbackBubbleResult metric,
    bool is_reshow) {
  static const char first_show[] =
      "Autofill.VirtualCardManualFallbackBubble.Result.FirstShow";
  static const char reshows[] =
      "Autofill.VirtualCardManualFallbackBubble.Result.Reshows";
  base::UmaHistogramEnumeration(is_reshow ? reshows : first_show, metric);
}

void LogVirtualCardManualFallbackBubbleFieldClicked(
    VirtualCardManualFallbackBubbleFieldClicked metric) {
  base::UmaHistogramEnumeration(
      "Autofill.VirtualCardManualFallbackBubble.FieldClicked", metric);
}

}  // namespace autofill::autofill_metrics


text:
require 'rspec-system/spec_helper'
require 'rspec-system-puppet/helpers'
require 'tempfile'

module LocalHelpers
  include RSpecSystem::Util

  def psql(psql_cmd, user = 'postgres', &block)
    psql = "psql #{psql_cmd}"
    shell("su #{shellescape(user)} -c #{shellescape(psql)}", &block)
  end
end

include RSpecSystemPuppet::Helpers

RSpec.configure do |c|
  # Project root for the firewall code
  proj_root = File.expand_path(File.join(File.dirname(__FILE__), '..'))

  # Enable colour in Jenkins
  c.tty = true

  # Include in our local helpers
  c.include ::LocalHelpers

  # Puppet helpers
  c.include RSpecSystemPuppet::Helpers
  c.extend RSpecSystemPuppet::Helpers

  # This is where we 'setup' the nodes before running our tests
  c.before :suite do
    # Install puppet
    puppet_install

    # Copy this module into the module path of the test node
    puppet_module_install(:source => proj_root, :module_name => 'postgresql')
    shell('puppet module install puppetlabs/stdlib')
    shell('puppet module install puppetlabs/firewall')
    shell('puppet module install puppetlabs/apt')
    shell('puppet module install ripienaar/concat')

    file = Tempfile.new('foo')
    begin
      file.write(<<-EOS)
---
:logger: noop
      EOS
      file.close
      rcp(:sp => file.path, :dp => '/etc/puppet/hiera.yaml')
    ensure
      file.unlink
    end
  end
end


text:
angular.module('umbraco')
.controller("Umbraco.PrevalueEditors.TreeSourceController",

	function($scope, dialogService, entityResource, $log, iconHelper){

	    if (!$scope.model) {
	        $scope.model = {};
	    }
	    if (!$scope.model.value) {
	        $scope.model.value = {
	            type: "content"
	        };
	    }

		if($scope.model.value.id && $scope.model.value.type !== "member"){
			var ent = "Document";
			if($scope.model.value.type === "media"){
				ent = "Media";
			}

			entityResource.getById($scope.model.value.id, ent).then(function(item){
				item.icon = iconHelper.convertFromLegacyIcon(item.icon);
				$scope.node = item;
			});
		}

		$scope.openContentPicker =function(){
			var d = dialogService.treePicker({
								section: $scope.model.value.type,
								treeAlias: $scope.model.value.type,
								multiPicker: false,
								callback: populate});
		};

		$scope.clear = function() {
			$scope.model.value.id = undefined;
			$scope.node = undefined;
			$scope.model.value.query = undefined;
		};

		//we always need to ensure we dont submit anything broken
	    $scope.$on("formSubmitting", function (ev, args) {
	    	if($scope.model.value.type === "member"){
	    		$scope.model.value.id = -1;
	    		$scope.model.value.query = "";
	    	}
	    });

		function populate(item){
				$scope.clear();
				item.icon = iconHelper.convertFromLegacyIcon(item.icon);
				$scope.node = item;
				$scope.model.value.id = item.id;
		}
});


text:
import getDataWrapper from "../feature/dataWrapper.js"

const wsRegex = /(\s+)/

const GenbankParser = function (config) {

    this.config = config
    this.nameFields = new Set(["gene"])

}

GenbankParser.prototype.parseFeatures = function (data) {

    var line, locusName, accession, sequence, aliases, chr

    if (!data) return null

    const dataWrapper = getDataWrapper(data)

    // Read locus
    line = dataWrapper.nextLine()
    readLocus(line)

    do {
        line = dataWrapper.nextLine()
        if (line.startsWith("ACCESSION")) {
            readAccession(line)
        } else if (line.startsWith("ALIASES")) {
            readAliases(line)
        }
    }
    while (line && !line.startsWith("FEATURES"))

    readFeatures(dataWrapper)
    readOriginSequence(dataWrapper)

    function readLocus(line) {
        const tokens = line.split(wsRegex)
        if (!tokens[0].toUpperCase() === "LOCUS") {
            // throw exception
        }
        locusName = tokens[1].trim()
    }

    function readAccession(line) {

        let tokens = line.split(wsRegex)
        if (tokens.length < 2) {
            console.log("Genbank file missing ACCESSION number.")
        } else {
            accession = tokens[1].trim()
        }
    }

    /**
     * Read the sequence aliases line  -- Note: this is an IGV extension
     * ACCESSION   K03160
     *
     * @throws IOException
     */
    function readAliases(line) {
        let tokens = line.split(wsRegex)
        if (tokens.length < 2) {
            //log.info("Genbank file missing ACCESSION number.");
        } else {
            aliases = tokens[1].split(",")
        }
    }

    /**
     * Read the origin section.   Example...
     *

     * ORIGIN
     * 1 gatcctccat atacaacggt atctccacct caggtttaga tctcaacaac ggaaccattg
     * 61 ccgacatgag acagttaggt atcgtcgaga gttacaagct aaaacgagca gtagtcagct
     * 121 ctgcatctga agccgctgaa gttctactaa gggtggataa catcatccgt gcaagaccaa
     *
     * @param reader
     */
    function readOriginSequence(dataWrapper) {

        let line

        sequence = []
        while (((line = dataWrapper.nextLine()) !== undefined) && !line.startsWith("//")) {
            line = line.trim()
            let tokens = line.split(wsRegex)
            for (let i = 1; i < tokens.length; i++) {
                let str = tokens[i]
                for (let j = 0; j < str.length; j++) {
                    sequence.push(str.charCodeAt(j))
                }
            }
        }
    }

    /**
     * FEATURES             Location/Qualifiers
     * source          1..105338
     * /organism="Homo sapiens"
     * /mol_type="genomic DNA"
     * /db_xref="taxon:9606"
     * /chromosome="10"
     * gene            1..105338
     * /gene="PTEN"
     * /note="Derived by automated computational analysis using
     * gene prediction method: BestRefseq."
     * /db_xref="GeneID:5728"
     * /db_xref="HGNC:9588"
     * /db_xref="HPRD:03431"
     * /db_xref="MIM:601728"
     *

     * CDS             join(1033..1111,30588..30672,62076..62120,67609..67652,
     * 69576..69814,88681..88822,94416..94582,97457..97681,
     * 101850..102035)
     * /gene="PTEN"
     *
     * @param reader
     * @throws IOException
     */
    function readFeatures(dataWrapper) {

        chr = accession || locusName

        //Process features until "ORIGIN"
        let features = []

        let currentLocQualifier, nextLine,
            errorCount = 0

        do {
            nextLine = dataWrapper.nextLine()

            // TODO -- first line is source (required), has total length => use to size sequence
            // TODO -- keys start at column 6,   locations and qualifiers at column 22.

            if (nextLine === "") {
                continue  // Not sure this is legal in a gbk file
            }

            if (!nextLine || nextLine.startsWith("ORIGIN")) {
                break
            }

            if (nextLine.length() < 6) {
                if (errorCount < 10) {
                    console("Unexpected line in genbank file (skipping): " + nextLine)
                }
                errorCount++
                continue
            }

            if (nextLine.charAt(5) !== ' ') {
                let featureType = nextLine.substring(5, 21).trim()
                let f = {
                    chr: chr,
                    type: featureType,
                    attributes: {}
                }

                currentLocQualifier = nextLine.substring(21)

                if (!featureType.toLowerCase().equals("source")) {
                    features.add(f)
                }

            } else {
                let tmp = nextLine.substring(21).trim()

                if (tmp.length() > 0)
                    if (tmp.charAt(0) === '/') {

                        if (currentLocQualifier.charAt(0) === '/') {

                            let tokens = currentLocQualifier.split("=", 2)

                            if (tokens.length > 1) {

                                let keyName = tokens[0].length() > 1 ? tokens[0].substring(1) : ""
                                let value = StringUtils.stripQuotes(tokens[1])

                                f.attributes[keyName] = value
                                if (nameFields.has(keyName)) {
                                    f.setName(value)
                                }
                            } else {
                                // TODO -- don't know how to interpret, log?
                            }
                        } else {

                            // location string TODO -- many forms of this to support
                            // Crude test for strand
                            let strand = currentLocQualifier.contains("complement") ? "-" : "+"
                            f.strand = strand

                            // join and complement functions irrelevant
                            let joinString = currentLocQualifier.replace("join", "")
                            joinString = joinString.replace("order", "")
                            joinString = joinString.replace("complement", "")
                            joinString = joinString.replace("(", "")
                            joinString = joinString.replace(")", "")

                            if (joinString.contains("..")) {

                                joinString = joinString.replace("<", "")
                                joinString = joinString.replace(">", "")

                                let exons = createExons(joinString, strand)

                                let firstExon = exons[0]
                                f.start = firstExon.start

                                let lastExon = exons.get[exons.length - 1]
                                f.setEnd = lastExon.end

                                if (exons.length > 1) {
                                    f.exons = exons
                                }
                            } else {
                                // TODO Single locus for now,  other forms possible
                                f.start = Number.parseInt(joinString) - 1
                                f.end = start + 1
                            }

                        }
                        currentLocQualifier = tmp
                    } else {
                        currentLocQualifier = currentLocQualifier || tmp
                    }
            }
        }
        while (true)
    }

}

/**
 * Create a list of Exon objects from the Embl join string.  Apparently exons in embl
 * format are represented by a single CDS record.
 *
 * @param joinString
 */
function createExons(joinString, strand) {

    let lociArray = joinString.split(",")

    let exons = []

    let isNegative = joinString.contains("complement")

    lociArray.forEach(function (loci) {

        let tmp = loci.split("..")

        let exonStart = 0    // - (isNegative ? 0 : 1);

        try {
            exonStart = Number.parseInt(tmp[0]) - 1

            let exonEnd = exonStart + 1
            if (tmp.length > 1) {
                exonEnd = Number.parseInt(tmp[1])
            }

            exons.add({
                chr: accession,
                start: exonStart,
                end: exonEnd,
                strand: strand
            })

        } catch (e) {
            console.error(e)
        }
    })

    exons.sort(function (a, b) {
        return a.start - b.start
    })

    return exons
}

export default GenbankParser


text:
var arrayCopy = require('../internal/arrayCopy'),
    isLength = require('../internal/isLength'),
    values = require('../object/values');

/**
 * Converts `value` to an array.
 *
 * @static
 * @memberOf _
 * @category Lang
 * @param {*} value The value to convert.
 * @returns {Array} Returns the converted array.
 * @example
 *
 * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3);
 * // => [2, 3]
 */
function toArray(value) {
  var length = value ? value.length : 0;
  if (!isLength(length)) {
    return values(value);
  }
  if (!length) {
    return [];
  }
  return arrayCopy(value);
}

module.exports = toArray;