text:
package it.prisma.presentationlayer.webui.core.paas;

import it.prisma.domain.dsl.accounting.AuthTokenRepresentation;
import it.prisma.domain.dsl.paas.services.emailaas.Credential;
import it.prisma.domain.dsl.paas.services.emailaas.EmailDomains;
import it.prisma.domain.dsl.paas.services.emailaas.EmailInfoRepresentation;
import it.prisma.domain.dsl.paas.services.emailaas.history.RowEmail;
import it.prisma.domain.dsl.prisma.prismaprotocol.restwsrequests.RestWSParamsContainer;
import it.prisma.presentationlayer.webui.security.userdetails.PrismaUserDetails;
import it.prisma.presentationlayer.webui.vos.paas.appaas.BootstrapTable;
import it.prisma.utils.web.ws.rest.apiclients.prisma.AbstractPrismaAPIClient.PrismaMetaData;
import it.prisma.utils.web.ws.rest.apiclients.prisma.bizlayer.PrismaBizAPIClient;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class EMAILManagementService {

	@Autowired
	private PrismaBizAPIClient prismaBizAPIClient;

	public boolean isEmailAccountExists(String email) throws Exception {

		AuthTokenRepresentation authToken = ( (PrismaUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() ).getUserToken();

		return prismaBizAPIClient.emailIsEmailAccountExists(email, authToken.getTokenId());
	}

	public BootstrapTable<RowEmail> getEmailAccountList(Long userPrismaId, RestWSParamsContainer params) throws Exception {

		PrismaMetaData meta = prismaBizAPIClient.new PrismaMetaData();
		BootstrapTable<RowEmail> table = new BootstrapTable<RowEmail>();

		AuthTokenRepresentation authToken = ( (PrismaUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() ).getUserToken();

		table.setEnvironments(prismaBizAPIClient.emailGetEmailAccountList(userPrismaId, params, meta, authToken.getTokenId()));
		table.setTotal(meta.getMeta().getPagination().getTotalCount());
		return table;
	}

	public List<EmailDomains> getEmailDomainList() throws Exception {

		AuthTokenRepresentation authToken = ( (PrismaUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() ).getUserToken();

		return prismaBizAPIClient.emailGetEmailDomainList(authToken.getTokenId());
	}

	public boolean updatePassword(Credential credential)
			throws Exception {

		AuthTokenRepresentation authToken = ( (PrismaUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() ).getUserToken();

		return prismaBizAPIClient.emailUpdatePassword(credential, authToken.getTokenId());
	}

	public boolean deleteEmailAccount(String email, String password) throws Exception {

		AuthTokenRepresentation authToken = ( (PrismaUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() ).getUserToken();

		return prismaBizAPIClient.emailDeleteEmailAccount(email, password, authToken.getTokenId());
	}

	public boolean createEmailAccount(Long userPrismaId, EmailInfoRepresentation request) throws Exception {

		AuthTokenRepresentation authToken = ( (PrismaUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal() ).getUserToken();

		return prismaBizAPIClient.emailCreateEmailAccount(userPrismaId, request, authToken.getTokenId());
	}
}


text:
"""Coverage plugin for pytest."""

import pytest

import cov_core

def pytest_addoption(parser):
    """Add options to control coverage."""

    group = parser.getgroup('coverage reporting with distributed testing '
                            'support')
    group.addoption('--cov', action='append', default=[], metavar='path',
                    dest='cov_source',
                    help='measure coverage for filesystem path '
                    '(multi-allowed)')
    group.addoption('--cov-report', action='append', default=[],
                    metavar='type', dest='cov_report',
                    choices=['term', 'term-missing', 'annotate', 'html',
                             'xml'],
                    help='type of report to generate: term, term-missing, '
                    'annotate, html, xml (multi-allowed)')
    group.addoption('--cov-config', action='store', default='.coveragerc',
                    metavar='path', dest='cov_config',
                    help='config file for coverage, default: .coveragerc')
    group.addoption('--no-cov-on-fail', action='store_true', default=False,
                    dest='no_cov_on_fail',
                    help='do not report coverage if test run fails, '
                         'default: False')

@pytest.mark.try_last
def pytest_load_initial_conftests(early_config, parser, args):
    ns = parser.parse_known_args(args)
    if ns.cov_source:
        plugin = CovPlugin(ns, early_config.pluginmanager)
        early_config.pluginmanager.register(plugin, '_cov')

def pytest_configure(config):
    """Activate coverage plugin if appropriate."""
    if config.getvalue('cov_source'):
        if not config.pluginmanager.hasplugin('_cov'):
            plugin = CovPlugin(config.option, config.pluginmanager,
                               start=False)
            config.pluginmanager.register(plugin, '_cov')

class CovPlugin(object):
    """Use coverage package to produce code coverage reports.

    Delegates all work to a particular implementation based on whether
    this test process is centralised, a distributed master or a
    distributed slave.
    """

    def __init__(self, options, pluginmanager, start=True):
        """Creates a coverage pytest plugin.

        We read the rc file that coverage uses to get the data file
        name.  This is needed since we give coverage through it's API
        the data file name.
        """

        # Our implementation is unknown at this time.
        self.cov_controller = None
        self.failed = False
        self.options = options

        is_dist = (getattr(options, 'numprocesses', False) or
                   getattr(options, 'distload', False) or
                   getattr(options, 'dist', 'no') != 'no')
        if is_dist and start:
            self.start(cov_core.DistMaster)
        elif start:
            self.start(cov_core.Central)

        # slave is started in pytest hook

    def start(self, controller_cls, config=None, nodeid=None):
        if config is None:
            # fake config option for cov_core
            class Config(object):
                option = self.options

            config = Config()

        self.cov_controller = controller_cls(
            self.options.cov_source,
            self.options.cov_report or ['term'],
            self.options.cov_config,
            config,
            nodeid
        )
        self.cov_controller.start()

    def pytest_sessionstart(self, session):
        """At session start determine our implementation and delegate to it."""
        is_slave = hasattr(session.config, 'slaveinput')
        if is_slave:
            nodeid = session.config.slaveinput.get('slaveid',
                                                   getattr(session, 'nodeid'))
            self.start(cov_core.DistSlave, session.config, nodeid)

    def pytest_configure_node(self, node):
        """Delegate to our implementation.

        Mark this hook as optional in case xdist is not installed.
        """
        self.cov_controller.configure_node(node)
    pytest_configure_node.optionalhook = True

    def pytest_testnodedown(self, node, error):
        """Delegate to our implementation.

        Mark this hook as optional in case xdist is not installed.
        """
        self.cov_controller.testnodedown(node, error)
    pytest_testnodedown.optionalhook = True

    def pytest_sessionfinish(self, session, exitstatus):
        """Delegate to our implementation."""
        self.failed = exitstatus != 0
        self.cov_controller.finish()

    def pytest_terminal_summary(self, terminalreporter):
        """Delegate to our implementation."""
        if not (self.failed and self.options.no_cov_on_fail):
            self.cov_controller.summary(terminalreporter._tw)

def pytest_funcarg__cov(request):
    """A pytest funcarg that provides access to the underlying coverage
    object.
    """

    # Check with hasplugin to avoid getplugin exception in older pytest.
    if request.config.pluginmanager.hasplugin('_cov'):
        plugin = request.config.pluginmanager.getplugin('_cov')
        if plugin.cov_controller:
            return plugin.cov_controller.cov
    return None

redpajama_set_name: RedPajamaGithub


text:
define([
	'knockout',
	'underscore',
	'storage',
	'constants',
	'localization'
], function (ko, _, storage, constants, localization) {
	'use strict';

	return function (params) {
		return {
			exception: params,
			hasError: !!params
		};
	};
});


text:
module Mastermind
  class Player
    attr_accessor :code
    attr_reader :name, :guess_log

    def initialize(name)
      @name = name
      @guess_log = []
    end

    def make_code
      puts "Choose your secret code."
      @code = get_code
    end

    def get_code
      loop do
        code = gets.chomp
        if wrong_size?(code)
          puts 'You can only use 4-digit code. Try again.'
        elsif outside_range?(code)
          puts 'You can only use numbers from 1 to 8. Try again.'
        else
          return code
        end
      end
    end

    def log(code, feedback)
      guess_log << [code, feedback]
    end

    private

    def wrong_size?(code)
      code.size != 4
    end

    def outside_range?(code)
      code.split('').any? { |e| !e.to_i.between?(1, 8) }
    end
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">

  <title>Audio Calling Implemented in Toxic | Tox Development blog</title>
  <meta name="viewport" content="width=device-width">
  <meta name="description" content="Last night, a non-gui client was given audio support: Toxic!
What does this mean? Well for starters toxic is the CLI client, meaning it's all done in console, so not that many people will be using it.">
<meta property="og:type" content="article">
<meta property="og:title" content="Audio Calling Implemented in Toxic">
<meta property="og:url" content="https://blog.tox.im/2014/03/11/audio/">
<meta property="og:site_name" content="Tox Development blog">
<meta property="og:description" content="Last night, a non-gui client was given audio support: Toxic!
What does this mean? Well for starters toxic is the CLI client, meaning it's all done in console, so not that many people will be using it.">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Audio Calling Implemented in Toxic">
<meta name="twitter:description" content="Last night, a non-gui client was given audio support: Toxic!
What does this mean? Well for starters toxic is the CLI client, meaning it's all done in console, so not that many people will be using it.">

    <link rel="alternative" href="/atom.xml" title="Tox Development blog" type="application/atom+xml">

    <link rel="icon" href="/favicon.png">

  <link rel="stylesheet" href="/css/style.css" type="text/css">

		Tox Development blog

Home

Archives

		<form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" results="0" class="search-form-input" placeholder="Search"><input type="submit" value="" class="search-form-submit"><input type="hidden" name="q" value="site:https://blog.tox.im"></form>

  <time datetime="2014-03-11T18:55:02.000Z" itemprop="datePublished">Mar 11 2014</time>

		Tox Foundation

      Audio Calling Implemented in Toxic

Last night, a non-gui client was given audio support: Toxic!

What does this mean? Well for starters toxic is the CLI client, meaning it's all done in console, so not that many people will be using it. That said, it's the first real implementation of the audio/video features worked on by mannol and Martijnvdc, with mannol putting audio functionality inside of Toxic as well.

It took a while for one client to do it, but after this we expect more clients to add support, with an example to go off of. Be warned though, Toxic is buggy right now, and is subject to crashing. This goes along with a daily reminder that Tox is still pre-alpha, but making strides!

    Toxic

      Newer

          Antox 0.5 Released

      Older

          Antox 0.4 Released

  <form action="//google.com/search" method="get" accept-charset="utf-8">
    <input type="search" name="q" results="0" placeholder="Search">
    <input type="hidden" name="q" value="site:blog.tox.im">
  </form>

		Tox Development blog

		© 2015 Tox Foundation

		Modify from Apollo theme, designed by SANOGRAPHIX.NET

		Powered by Hexo

<link rel="stylesheet" href="/fancybox/jquery.fancybox.css" media="screen" type="text/css">


text:
$(function () {
  // Toggle visibility
  $('.toggle-button button').click(function (e) {
    e.preventDefault();

    var self = $(this);

    if (self.is('.active')) {
      return;
    }

    var attribute = self.data('attribute');
    var value = self.text();

    $.ajax({
      url: '/api/v1/user/' + $('#server').data('username') + '/',
      type: 'POST',
      data: {
        csrfmiddlewaretoken: $('body').data('csrf'),
        attribute: attribute,
        value: value,
      },
      success: function () {
        self.addClass('active');
        self.siblings().removeClass('active');

        var label = self.parents('.field').find('label').text();
        Pontoon.endLoader(`${label} visibility set to ${value}.`);
      },
      error: function (request) {
        if (request.responseText === 'error') {
          Pontoon.endLoader('Oops, something went wrong.', 'error');
        } else {
          Pontoon.endLoader(request.responseText, 'error');
        }
      },
    });
  });

  // Toggle user profile attribute
  $('.check-box').click(function () {
    var self = $(this);

    $.ajax({
      url: '/api/v1/user/' + $('#server').data('username') + '/',
      type: 'POST',
      data: {
        csrfmiddlewaretoken: $('body').data('csrf'),
        attribute: self.data('attribute'),
        value: !self.is('.enabled'),
      },
      success: function () {
        self.toggleClass('enabled');
        var is_enabled = self.is('.enabled');
        var status = is_enabled ? 'enabled' : 'disabled';

        Pontoon.endLoader(self.text() + ' ' + status + '.');
      },
      error: function (request) {
        if (request.responseText === 'error') {
          Pontoon.endLoader('Oops, something went wrong.', 'error');
        } else {
          Pontoon.endLoader(request.responseText, 'error');
        }
      },
    });
  });

  // Save custom homepage
  $('#homepage .locale .menu li:not(".no-match")').click(function () {
    var custom_homepage = $(this).find('.language').data('code');

    $.ajax({
      url: '/save-custom-homepage/',
      type: 'POST',
      data: {
        csrfmiddlewaretoken: $('body').data('csrf'),
        custom_homepage: custom_homepage,
      },
      success: function (data) {
        if (data === 'ok') {
          Pontoon.endLoader('Custom homepage saved.');
        }
      },
      error: function (request) {
        if (request.responseText === 'error') {
          Pontoon.endLoader('Oops, something went wrong.', 'error');
        } else {
          Pontoon.endLoader(request.responseText, 'error');
        }
      },
    });
  });

  // Save preferred source locale
  $('#preferred-locale .locale .menu li:not(".no-match")').click(function () {
    var preferred_source_locale = $(this).find('.language').data('code');

    $.ajax({
      url: '/save-preferred-source-locale/',
      type: 'POST',
      data: {
        csrfmiddlewaretoken: $('body').data('csrf'),
        preferred_source_locale: preferred_source_locale,
      },
      success: function (data) {
        if (data === 'ok') {
          Pontoon.endLoader('Preferred source locale saved.');
        }
      },
      error: function (request) {
        if (request.responseText === 'error') {
          Pontoon.endLoader('Oops, something went wrong.', 'error');
        } else {
          Pontoon.endLoader(request.responseText, 'error');
        }
      },
    });
  });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jiangbin.coolweather" >
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name = "jiangbin.coolweather.activity.ChooseAreaActivity"
            android:label = "@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="jiangbin.coolweather.activity.WeatherActivity"></activity>
    </application>

</manifest>


text:
/*
 * net.js: Wrapper around node.js core `net` module for observing relevant events
 *
 * (C) 2011 Nodejitsu Inc.
 *
 */

var net = require('net'),
    semver = require('semver'),
    carapace = require('../carapace');

//
// ### function override (version)
// Helper function which overrides with the correct `net` module
// override for current node version.
//
module.exports = function (carapace) {
  carapace.net = function (argv, next) {
    var version = process.version,
        methods = Object.keys(module.exports),
        method;

    for (var i = 0; i < methods.length; i++) {
      method = module.exports[methods[i]];
      if (method.nodeVersion && semver.satisfies(version, method.nodeVersion)) {
        method();
        return next();
      }
    }
    throw new Error('No appropiate net override for node version ' + version);
  };
};

//
// ### function toPort(x)
// #### @x {Number|String} Object to convert to a port number.
// Helper function from Node code to parse port arguments
// passed to net.prototype.Server.listen
//
function toPort(x) {
  return (x = Number(x)) >= 0 ? x : false;
}

//
// ### function nextPort (port)
// #### @port {Number} Port to increment from.
// Gets the next port in sequence from the
// specified `port`.
//
function nextPort(port) {
  if (!port) {
    return 8000;
  }

  //
  // Find the next port that we are not supposed to ignore or cause errors on
  //
  var unavailable = carapace.ports.ignore.concat(carapace.ports.throw);
  do {
    port = port + 1;
  } while (unavailable.indexOf(port) !== -1);

  return port;
}

//
// ### functon reservedPort
// #### @desired {Number} Desired port to bind to.
// Helper function which will emit an error if the
// server (the `this` argument) is in `carapace.ports.throw`
//
function reservedPort(desired) {
  if (carapace.ports.throw.indexOf(desired) !== -1) {
    this.close();
    //
    // Build fake error
    //
    var err = new Error('EADDRINUSE, Address already in use');
    err.code = 'EADDRINUSE';
    err.syscall = 'bind';
    err.errno = 100;
    this.emit('error', err);
    return true;
  }

  return false;
}

//
// ### function _listen2 ()
// Override for `node@0.[5-8].x`
//
module.exports._listen2 = function overrideNet() {
  var _listen2 = net.Server.prototype._listen2;

  net.Server.prototype._listen2 = function ourListen(address, port, addressType, desired) {
    var self = this;

    address = '0.0.0.0';
    port = toPort(port);
    desired || (desired = port);

    //
    // Always throw if our desired port was one that should always throw
    //
    if (reservedPort.call(this, port)) {
      return;
    }

    //
    // Since desired is not on a throwing port
    // we want to skip ports in both throw and ignore
    //
    port || (port = 0);

    //
    // We rely on `error` event to check if address it taken/available, however
    // user may want to hook up to `error` in his application as well (and
    // usually exit when it's emitted). This messes things up. Here we store
    // `error` event listeners and remove them. They will be restored after we
    // start listening or get an error which is not `EADDRINUSE`.
    //
    var errorListeners = self.listeners('error').slice(0);
    self.removeAllListeners('error');

    function restoreErrorListeners() {
      errorListeners.forEach(function (listener) {
        self.on('error', listener);
      });
    }

    //
    // Problem with `listening` events is a bit different. We want to ensure
    // that we first emit `carapace::port` and *then* the proper `listening`
    // event (which can be consumed by user's app).
    //
    // (Also, not doing so breaks `net/net-multiple-servers-test` test.)
    //
    var listeningListeners = self.listeners('listening').slice(0);
    self.removeAllListeners('listening');

    function restoreListeningListeners() {
      listeningListeners.forEach(function (listener) {
        self.on('listening', listener);
      });
    }

    function onListen() {
      //
      // Yay, we made it! Lets restore `error` listeners and tell the world
      // that we totally owned this port.
      //

      self.removeListener('error', onError);

      restoreErrorListeners();
      restoreListeningListeners();

      //
      // Store the server that has listened on the `desired` port
      // on the carapace itself, indexed by port.
      //
      carapace.servers[desired] = self;

      carapace.emit('port', {
        id: carapace.id,
        addr: address,
        port: self.address().port,
        desired: desired
      });

      process.nextTick(function () {
        self.emit('listening');
      });
    }

    function onError(err) {
      //
      // We failed to listen. Unless it's not EADDRINUSE lets try doing the
      // same thing, just with next port.
      //

      self.removeListener('listening', onListen);

      //
      // We can safely restore these listeners here. We're going to call
      // `ourFunction`, so they will be removed again anyway.
      //
      restoreErrorListeners();
      restoreListeningListeners();

      if (err.code !== 'EADDRINUSE' && err.code !== 'EACCES') {
        try { self.close() }
        catch (ex) { }

        self.emit('error', err);
      }
      else {
        ourListen.call(self, '0.0.0.0', nextPort(port), addressType, desired);
      }
    }

    self.once('listening', onListen);
    self.once('error', onError);

    //
    // Call original _listen2 function.
    //
    process.nextTick(function () {
      _listen2.call(self, address, port, addressType);
    });
  };
};

//
// Setup the valid `nodeVersion` for all of the
// monkey patches to `require('net')`.
//
module.exports._listen2.nodeVersion = '0.5.x || 0.6.x || 0.7.x || 0.8.x || 0.9.x || 0.10.x';


text:
<?php

namespace Blocktrail\SDK;

use BitWasp\Bitcoin\Mnemonic\Bip39\Bip39SeedGenerator;

class WalletV1Sweeper extends WalletSweeper {

    /**
     * @param string              $primaryMnemonic
     * @param string              $primaryPassphrase
     * @param string              $backupMnemonic
     * @param array               $blocktrailPublicKeys
     * @param UnspentOutputFinder $unspentOutputFinder
     * @param string              $network
     * @param bool                $testnet
     */
    public function __construct($primaryMnemonic, $primaryPassphrase, $backupMnemonic, array $blocktrailPublicKeys, UnspentOutputFinder $unspentOutputFinder, $network = 'btc', $testnet = false) {
        // cleanup copy paste errors from mnemonics
        $primaryMnemonic = str_replace("  ", " ", str_replace("\r\n", " ", str_replace("\n", " ", trim($primaryMnemonic))));
        $backupMnemonic = str_replace("  ", " ", str_replace("\r\n", " ", str_replace("\n", " ", trim($backupMnemonic))));

        // convert the primary and backup mnemonics to seeds (using BIP39), then create private keys (using BIP32)
        $primarySeed = (new Bip39SeedGenerator())->getSeed($primaryMnemonic, $primaryPassphrase);
        $backupSeed = (new Bip39SeedGenerator())->getSeed($backupMnemonic, "");

        parent::__construct($primarySeed, $backupSeed, $blocktrailPublicKeys, $unspentOutputFinder, $network, $testnet);
    }
}


text:
package flux

import (
	"os"

	"github.com/istoican/flux/consistent"
	"github.com/istoican/flux/consistent/hash"
	"github.com/istoican/flux/storage"
	"github.com/istoican/flux/storage/memory"
	"github.com/istoican/flux/transport"
	"github.com/istoican/flux/transport/http/peer"
)

// Config :
type Config struct {
	Addr    string
	Store   storage.Store
	OnJoin  func(id string)
	OnLeave func(id string)
	PeerFn  func(string) transport.Peer
	HashFn  consistent.HashFn
}

// DefaultConfig :
func DefaultConfig() Config {
	hostname, _ := os.Hostname()

	return Config{
		Addr:   hostname,
		Store:  memory.NewStore(),
		HashFn: hash.CRC32,
		PeerFn: peer.New,
	}
}


text:
var ventana2 = Ti.UI.currentWindow;
ventana2.backgroundColor = '#00000'
var webView = Titanium.UI.createWebView({
	url:'http://www.upiicsa.ipn.mx/',
	top:'30dp',
});

ventana2.add(webView);


text:
require 'rails_helper'
require 'shoulda/matchers'

describe Contact do

	it "should have valid factory" do
   	   expect(FactoryGirl.create(:contact)).to be_valid
 	end

 	it "should be invalid without name" do
 	   expect(FactoryGirl.build(:contact, name: nil)).not_to be_valid
	end

	it "should be invalid without surname" do
 	   expect(FactoryGirl.build(:contact, surname: nil)).not_to be_valid
	end

	it "should be invalid without telephone" do
 	   expect(FactoryGirl.build(:contact, telephone: nil)).not_to be_valid
	end

	it "should be invalid without email" do
 	   expect(FactoryGirl.build(:contact, email: nil)).not_to be_valid
	end

	it { should have_and_belong_to_many(:locations) }

end


text:
<?php

namespace Laravel\Tinker\Console;

use Psy\Shell;
use Psy\Configuration;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;

class TinkerCommand extends Command
{
    /**
     * Artisan commands to include in the tinker shell.
     *
     * @var array
     */
    protected $commandWhitelist = [
        'clear-compiled', 'down', 'env', 'inspire', 'migrate', 'optimize', 'up',
    ];

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'tinker';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Interact with your application';

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
        $this->getApplication()->setCatchExceptions(false);

        $config = new Configuration([
            'updateCheck' => 'never'
        ]);

        $config->getPresenter()->addCasters(
            $this->getCasters()
        );

        $shell = new Shell($config);
        $shell->addCommands($this->getCommands());
        $shell->setIncludes($this->argument('include'));

        $shell->run();
    }

    /**
     * Get artisan commands to pass through to PsySH.
     *
     * @return array
     */
    protected function getCommands()
    {
        $commands = [];

        foreach ($this->getApplication()->all() as $name => $command) {
            if (in_array($name, $this->commandWhitelist)) {
                $commands[] = $command;
            }
        }

        return $commands;
    }

    /**
     * Get an array of Laravel tailored casters.
     *
     * @return array
     */
    protected function getCasters()
    {
        $casters = [
            'Illuminate\Support\Collection' => 'Laravel\Tinker\TinkerCaster::castCollection',
        ];

        if (class_exists('Illuminate\Database\Eloquent\Model')) {
            $casters['Illuminate\Database\Eloquent\Model'] = 'Laravel\Tinker\TinkerCaster::castModel';
        }

        if (class_exists('Illuminate\Foundation\Application')) {
            $casters['Illuminate\Foundation\Application'] = 'Laravel\Tinker\TinkerCaster::castApplication';
        }

        return $casters;
    }

    /**
     * Get the console command arguments.
     *
     * @return array
     */
    protected function getArguments()
    {
        return [
            ['include', InputArgument::IS_ARRAY, 'Include file(s) before starting tinker'],
        ];
    }
}


text:
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Microsoft.Ddue.Tools.CommandLine {

    public sealed class ParseArgumentsResult {

        internal Dictionary < string, ParseResult > errors = new Dictionary < string, ParseResult >();

        internal List < string > nonoptions = new List < string >();

        // data

        internal OptionCollection options;

        internal ParseArgumentsResult() { }

        // accessors

        public OptionCollection Options {
            get {
                return (options);
            }
        }

        public bool Success {
            get {
                if (errors.Count == 0) {
                    return (true);
                } else {
                    return (false);
                }
            }
        }

        public ReadOnlyCollection < string > UnusedArguments {

            get {
                return (new ReadOnlyCollection < string >(nonoptions));
            }
        }

        public void WriteParseErrors(TextWriter writer) {

            if (writer == null) throw new ArgumentNullException("writer");
            foreach (KeyValuePair < string, ParseResult > error in errors) {
                writer.WriteLine("{0}: {1}", error.Value, error.Key);

            }

        }

    }

}


text:
package com.thoughtworks.go.config;

import com.thoughtworks.go.domain.config.ConfigurationKey;
import com.thoughtworks.go.domain.config.ConfigurationProperty;
import com.thoughtworks.go.domain.config.ConfigurationValue;
import com.thoughtworks.go.domain.config.EncryptedConfigurationValue;
import com.thoughtworks.go.plugin.access.authorization.AuthorizationMetadataStore;
import com.thoughtworks.go.plugin.api.info.PluginDescriptor;
import com.thoughtworks.go.plugin.domain.authorization.AuthorizationPluginInfo;
import com.thoughtworks.go.plugin.domain.common.Metadata;
import com.thoughtworks.go.plugin.domain.common.PluggableInstanceSettings;
import com.thoughtworks.go.plugin.domain.common.PluginConfiguration;
import org.junit.After;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;

import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;

public class SecurityAuthConfigTest {
    private AuthorizationMetadataStore store = AuthorizationMetadataStore.instance();

    @After
    public void tearDown() throws Exception {
        store.clear();
    }

    @Test
    public void addConfigurations_shouldAddConfigurationsWithValue() throws Exception {
        ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("some_name"));

        SecurityAuthConfig authConfig = new SecurityAuthConfig("id", "plugin_id");
        authConfig.addConfigurations(Arrays.asList(property));

        assertThat(authConfig.size(), is(1));
        assertThat(authConfig, contains(new ConfigurationProperty(new ConfigurationKey("username"), new ConfigurationValue("some_name"))));
    }

    @Test
    public void addConfigurations_shouldAddConfigurationsWithEncryptedValue() throws Exception {
        ConfigurationProperty property = new ConfigurationProperty(new ConfigurationKey("username"), new EncryptedConfigurationValue("some_name"));

        SecurityAuthConfig authConfig = new SecurityAuthConfig("id", "plugin_id");
        authConfig.addConfigurations(Arrays.asList(property));

        assertThat(authConfig.size(), is(1));
        assertThat(authConfig, contains(new ConfigurationProperty(new ConfigurationKey("username"), new EncryptedConfigurationValue("some_name"))));
    }

    @Test
    public void addConfiguration_shouldEncryptASecureVariable() throws Exception {
        PluggableInstanceSettings profileSettings = new PluggableInstanceSettings(Arrays.asList(new PluginConfiguration("password", new Metadata(true, true))));
        AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(pluginDescriptor("plugin_id"), profileSettings, null, null, null);

        store.setPluginInfo(pluginInfo);
        SecurityAuthConfig authConfig = new SecurityAuthConfig("id", "plugin_id");
        authConfig.addConfigurations(Arrays.asList(new ConfigurationProperty(new ConfigurationKey("password"), new ConfigurationValue("pass"))));

        assertThat(authConfig.size(), is(1));
        assertTrue(authConfig.first().isSecure());
    }

    @Test
    public void addConfiguration_shouldIgnoreEncryptionInAbsenceOfCorrespondingConfigurationInStore() throws Exception {
        AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(pluginDescriptor("plugin_id"), new PluggableInstanceSettings(new ArrayList<>()), null, null, null);

        store.setPluginInfo(pluginInfo);
        SecurityAuthConfig authConfig = new SecurityAuthConfig("id", "plugin_id");
        authConfig.addConfigurations(Arrays.asList(new ConfigurationProperty(new ConfigurationKey("password"), new ConfigurationValue("pass"))));

        assertThat(authConfig.size(), is(1));
        assertFalse(authConfig.first().isSecure());
        assertThat(authConfig, contains(new ConfigurationProperty(new ConfigurationKey("password"), new ConfigurationValue("pass"))));
    }

    @Test
    public void postConstruct_shouldEncryptSecureConfigurations() throws Exception {
        PluggableInstanceSettings profileSettings = new PluggableInstanceSettings(Arrays.asList(new PluginConfiguration("password", new Metadata(true, true))));
        AuthorizationPluginInfo pluginInfo = new AuthorizationPluginInfo(pluginDescriptor("plugin_id"), profileSettings, null, null, null);

        store.setPluginInfo(pluginInfo);
        SecurityAuthConfig authConfig = new SecurityAuthConfig("id", "plugin_id", new ConfigurationProperty(new ConfigurationKey("password"), new ConfigurationValue("pass")));

        authConfig.encryptSecureConfigurations();

        assertThat(authConfig.size(), is(1));
        assertTrue(authConfig.first().isSecure());
    }

    @Test
    public void postConstruct_shouldIgnoreEncryptionIfPluginInfoIsNotDefined() throws Exception {
        SecurityAuthConfig authConfig = new SecurityAuthConfig("id", "plugin_id", new ConfigurationProperty(new ConfigurationKey("password"), new ConfigurationValue("pass")));

        authConfig.encryptSecureConfigurations();

        assertThat(authConfig.size(), is(1));
        assertFalse(authConfig.first().isSecure());
    }

    private PluginDescriptor pluginDescriptor(String pluginId) {
        return new PluginDescriptor() {
            @Override
            public String id() {
                return pluginId;
            }

            @Override
            public String version() {
                return null;
            }

            @Override
            public About about() {
                return null;
            }
        };
    }
}


text:
*   Status: Superseded
*   Version: N/A
*   Implementation Owner: @verb

The Troubleshooting Running Pods proposal has moved to the
[Ephemeral Containers KEP](https://git.k8s.io/enhancements/keps/sig-node/20190212-ephemeral-containers.md).


text:
package com.dtflys.forest.annotation;

import com.dtflys.forest.lifecycles.MethodAnnotationLifeCycle;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 该注解用于为方法级别的自定义注解指定生命周期类
 * @author gongjun [dt_flys@hotmail.com]
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface MethodLifeCycle {

    /**
     * 注解所绑定的生命周期类(方法级别)
     */
    Class<? extends MethodAnnotationLifeCycle> value();
}


text:
package ca.cs.ualberta.localpost.view;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import ca.cs.ualberta.localpost.controller.CommentListAdapter;
import ca.cs.ualberta.localpost.controller.ConnectivityCheck;
import ca.cs.ualberta.localpost.controller.ElasticSearchOperations;
import ca.cs.ualberta.localpost.controller.Serialize;
import ca.cs.ualberta.localpost.controller.SortLatestComments;
import ca.cs.ualberta.localpost.model.CommentModel;

import com.google.gson.Gson;

/**
 * Displays and order comments that were sorted by date (Most Recent dates will
 * be first)
 *
 * @author Team 01
 *
 */
public class LastestTabView extends Fragment {
	public int isPictures;
	private ListView listView;
	ArrayList<CommentModel> model;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		// Inflates the view with a list view. Also populates listview
		View rootView = inflater.inflate(R.layout.tab, container, false);
		listView = (ListView) rootView.findViewById(R.id.commentList);
		return rootView;
	}

	/**
	 * Overrides onResume. Sorts comments with Lastest Alg.(Most recent First)
	 * This will update the listView with the sorted data
	 */
	@Override
	public void onResume() {
		super.onResume();
		new Handler().postDelayed(new Runnable() {
			public void run() {
				ConnectivityCheck conn = new ConnectivityCheck(getActivity());
				if (conn.isConnectingToInternet()) {
					try {
						model = new ElasticSearchOperations().execute(3, null,
								null, null).get();
						Serialize.check_if_exist("cachedrootcomment.json",getActivity());
						for (CommentModel c : model) {
							Serialize.SaveComment(c, getActivity(), null);
							Serialize.update(c, getActivity(),"favoritecomment.json");
							Serialize.update(c, getActivity(),"historycomment.json");
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					model = Serialize.loadFromFile("cachedrootcomment.json",getActivity());
				}

				SortLatestComments sort = new SortLatestComments();
				model = sort.sortComments(model);
				CommentListAdapter adapter = new CommentListAdapter(getActivity(), R.id.custom_adapter, model);
				listView.setAdapter(adapter);
				registerForContextMenu(listView);

				listView.setOnItemClickListener(new OnItemClickListener() {
					public void onItemClick(AdapterView<?> parent, View view,
							int position, long id) {
						Gson gson = new Gson();
						String modelString = gson.toJson(model.get(position));
						Intent myIntent = new Intent(getActivity(),ThreadView.class);
						myIntent.putExtra("CommentModel", modelString);
						startActivity(myIntent);
					}
				});
			}
		}, 500);
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, Menu.FIRST, 0, "UpRad");
		menu.add(0, Menu.FIRST + 1, 0, "DownRad");
		menu.add(0, Menu.FIRST + 2, 0, "Favorite");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		ConnectivityCheck conn = new ConnectivityCheck(getActivity());
		// Get item list index
		ElasticSearchOperations es = new ElasticSearchOperations();
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();
		int index = (int) info.id;
		switch (item.getItemId()) {
		case Menu.FIRST:
			if (conn.isConnectingToInternet()) {
				Toast.makeText(getActivity(), "UpRad", Toast.LENGTH_SHORT)
						.show();
				model.get(index).incRadish();
				es.execute(1, model.get(index).getPostId(), model.get(index),
						null);
				return true;
			} else {
				Toast.makeText(getActivity(),
						"You require connectivity to Uprad", Toast.LENGTH_SHORT)
						.show();
				return true;
			}
		case Menu.FIRST + 1:
			if (conn.isConnectingToInternet()) {
				Toast.makeText(getActivity(), "DownRad", Toast.LENGTH_SHORT)
						.show();
				model.get(index).decRadish();
				es.execute(1, model.get(index).getPostId(), model.get(index),
						null);
				return true;
			} else {
				Toast.makeText(getActivity(),
						"You require connectivity to Downrad",
						Toast.LENGTH_SHORT).show();
				return true;
			}
		case Menu.FIRST + 2:
			Serialize.SaveComment(model.get(index), getActivity(), "favourite");
			Toast.makeText(getActivity(), "Comment has been Favorited",
					Toast.LENGTH_SHORT).show();
			Serialize.update(model.get(index), getActivity(),
					"favoritecomment.json");
			return true;
		}
		return super.onContextItemSelected(item);
	}
}


text:
package org.elasticsearch.index.mapper.core;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.Terms;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.NumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.NumericUtils;
import org.elasticsearch.ElasticsearchIllegalArgumentException;
import org.elasticsearch.action.fieldstats.FieldStats;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Numbers;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.analysis.NumericLongAnalyzer;
import org.elasticsearch.index.fielddata.FieldDataType;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MergeContext;
import org.elasticsearch.index.mapper.MergeMappingException;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.search.NumericRangeFieldDataFilter;
import org.elasticsearch.index.similarity.SimilarityProvider;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeLongValue;
import static org.elasticsearch.index.mapper.MapperBuilders.longField;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField;

/**
 *
 */
public class LongFieldMapper extends NumberFieldMapper<Long> {

    public static final String CONTENT_TYPE = "long";

    public static class Defaults extends NumberFieldMapper.Defaults {
        public static final FieldType FIELD_TYPE = new FieldType(NumberFieldMapper.Defaults.FIELD_TYPE);

        static {
            FIELD_TYPE.freeze();
        }

        public static final Long NULL_VALUE = null;
    }

    public static class Builder extends NumberFieldMapper.Builder<Builder, LongFieldMapper> {

        protected Long nullValue = Defaults.NULL_VALUE;

        public Builder(String name) {
            super(name, new FieldType(Defaults.FIELD_TYPE), Defaults.PRECISION_STEP_64_BIT);
            builder = this;
        }

        public Builder nullValue(long nullValue) {
            this.nullValue = nullValue;
            return this;
        }

        @Override
        public LongFieldMapper build(BuilderContext context) {
            fieldType.setOmitNorms(fieldType.omitNorms() && boost == 1.0f);
            LongFieldMapper fieldMapper = new LongFieldMapper(buildNames(context), fieldType.numericPrecisionStep(), boost, fieldType, docValues, nullValue,
                    ignoreMalformed(context), coerce(context), similarity, normsLoading,
                    fieldDataSettings, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
            fieldMapper.includeInAll(includeInAll);
            return fieldMapper;
        }
    }

    public static class TypeParser implements Mapper.TypeParser {
        @Override
        public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
            LongFieldMapper.Builder builder = longField(name);
            parseNumberField(builder, name, node, parserContext);
            for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry<String, Object> entry = iterator.next();
                String propName = Strings.toUnderscoreCase(entry.getKey());
                Object propNode = entry.getValue();
                if (propName.equals("null_value")) {
                    if (propNode == null) {
                        throw new MapperParsingException("Property [null_value] cannot be null.");
                    }
                    builder.nullValue(nodeLongValue(propNode));
                    iterator.remove();
                }
            }
            return builder;
        }
    }

    private Long nullValue;

    private String nullValueAsString;

    protected LongFieldMapper(Names names, int precisionStep, float boost, FieldType fieldType, Boolean docValues,
                              Long nullValue, Explicit<Boolean> ignoreMalformed, Explicit<Boolean> coerce,
                              SimilarityProvider similarity, Loading normsLoading, @Nullable Settings fieldDataSettings,
                              Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
        super(names, precisionStep, boost, fieldType, docValues, ignoreMalformed, coerce,
                NumericLongAnalyzer.buildNamedAnalyzer(precisionStep), NumericLongAnalyzer.buildNamedAnalyzer(Integer.MAX_VALUE),
                similarity, normsLoading, fieldDataSettings, indexSettings, multiFields, copyTo);
        this.nullValue = nullValue;
        this.nullValueAsString = nullValue == null ? null : nullValue.toString();
    }

    @Override
    public FieldType defaultFieldType() {
        return Defaults.FIELD_TYPE;
    }

    @Override
    public FieldDataType defaultFieldDataType() {
        return new FieldDataType("long");
    }

    @Override
    protected int maxPrecisionStep() {
        return 64;
    }

    @Override
    public Long value(Object value) {
        if (value == null) {
            return null;
        }
        if (value instanceof Number) {
            return ((Number) value).longValue();
        }
        if (value instanceof BytesRef) {
            return Numbers.bytesToLong((BytesRef) value);
        }
        return java.lang.Long.parseLong(value.toString());
    }

    @Override
    public BytesRef indexedValueForSearch(Object value) {
        BytesRefBuilder bytesRef = new BytesRefBuilder();
        NumericUtils.longToPrefixCoded(parseLongValue(value), 0, bytesRef);  // 0 because of exact match
        return bytesRef.get();
    }

    @Override
    public Query fuzzyQuery(String value, Fuzziness fuzziness, int prefixLength, int maxExpansions, boolean transpositions) {
        long iValue = java.lang.Long.parseLong(value);
        final long iSim = fuzziness.asLong();
        return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                iValue - iSim,
                iValue + iSim,
                true, true);
    }

    @Override
    public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
        return NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                lowerTerm == null ? null : parseLongValue(lowerTerm),
                upperTerm == null ? null : parseLongValue(upperTerm),
                includeLower, includeUpper);
    }

    @Override
    public Filter rangeFilter(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
        return Queries.wrap(NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                lowerTerm == null ? null : parseLongValue(lowerTerm),
                upperTerm == null ? null : parseLongValue(upperTerm),
                includeLower, includeUpper));
    }

    @Override
    public Filter rangeFilter(QueryParseContext parseContext, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable QueryParseContext context) {
        return NumericRangeFieldDataFilter.newLongRange((IndexNumericFieldData) parseContext.getForField(this),
                lowerTerm == null ? null : parseLongValue(lowerTerm),
                upperTerm == null ? null : parseLongValue(upperTerm),
                includeLower, includeUpper);
    }

    @Override
    public Filter nullValueFilter() {
        if (nullValue == null) {
            return null;
        }
        return Queries.wrap(NumericRangeQuery.newLongRange(names.indexName(), precisionStep,
                nullValue,
                nullValue,
                true, true));
    }

    @Override
    protected boolean customBoost() {
        return true;
    }

    @Override
    protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
        long value;
        float boost = this.boost;
        if (context.externalValueSet()) {
            Object externalValue = context.externalValue();
            if (externalValue == null) {
                if (nullValue == null) {
                    return;
                }
                value = nullValue;
            } else if (externalValue instanceof String) {
                String sExternalValue = (String) externalValue;
                if (sExternalValue.length() == 0) {
                    if (nullValue == null) {
                        return;
                    }
                    value = nullValue;
                } else {
                    value = java.lang.Long.parseLong(sExternalValue);
                }
            } else {
                value = ((Number) externalValue).longValue();
            }
            if (context.includeInAll(includeInAll, this)) {
                context.allEntries().addText(names.fullName(), java.lang.Long.toString(value), boost);
            }
        } else {
            XContentParser parser = context.parser();
            if (parser.currentToken() == XContentParser.Token.VALUE_NULL ||
                    (parser.currentToken() == XContentParser.Token.VALUE_STRING && parser.textLength() == 0)) {
                if (nullValue == null) {
                    return;
                }
                value = nullValue;
                if (nullValueAsString != null && (context.includeInAll(includeInAll, this))) {
                    context.allEntries().addText(names.fullName(), nullValueAsString, boost);
                }
            } else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
                XContentParser.Token token;
                String currentFieldName = null;
                Long objValue = nullValue;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else {
                        if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
                            if (parser.currentToken() != XContentParser.Token.VALUE_NULL) {
                                objValue = parser.longValue(coerce.value());
                            }
                        } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
                            boost = parser.floatValue();
                        } else {
                            throw new ElasticsearchIllegalArgumentException("unknown property [" + currentFieldName + "]");
                        }
                    }
                }
                if (objValue == null) {
                    // no value
                    return;
                }
                value = objValue;
            } else {
                value = parser.longValue(coerce.value());
                if (context.includeInAll(includeInAll, this)) {
                    context.allEntries().addText(names.fullName(), parser.text(), boost);
                }
            }
        }
        if (fieldType.indexOptions() != IndexOptions.NONE || fieldType.stored()) {
            CustomLongNumericField field = new CustomLongNumericField(this, value, fieldType);
            field.setBoost(boost);
            fields.add(field);
        }
        if (hasDocValues()) {
            addDocValue(context, fields, value);
        }
    }

    @Override
    protected String contentType() {
        return CONTENT_TYPE;
    }

    @Override
    public void merge(Mapper mergeWith, MergeContext mergeContext) throws MergeMappingException {
        super.merge(mergeWith, mergeContext);
        if (!this.getClass().equals(mergeWith.getClass())) {
            return;
        }
        if (!mergeContext.mergeFlags().simulate()) {
            this.nullValue = ((LongFieldMapper) mergeWith).nullValue;
            this.nullValueAsString = ((LongFieldMapper) mergeWith).nullValueAsString;
        }
    }

    @Override
    protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
        super.doXContentBody(builder, includeDefaults, params);

        if (includeDefaults || precisionStep != Defaults.PRECISION_STEP_64_BIT) {
            builder.field("precision_step", precisionStep);
        }
        if (includeDefaults || nullValue != null) {
            builder.field("null_value", nullValue);
        }
        if (includeInAll != null) {
            builder.field("include_in_all", includeInAll);
        } else if (includeDefaults) {
            builder.field("include_in_all", false);
        }
    }

    @Override
    public FieldStats stats(Terms terms, int maxDoc) throws IOException {
        long minValue = NumericUtils.getMinLong(terms);
        long maxValue = NumericUtils.getMaxLong(terms);
        return new FieldStats.Long(
                maxDoc, terms.getDocCount(), terms.getSumDocFreq(), terms.getSumTotalTermFreq(), minValue, maxValue
        );
    }

    public static class CustomLongNumericField extends CustomNumericField {

        private final long number;

        private final NumberFieldMapper mapper;

        public CustomLongNumericField(NumberFieldMapper mapper, long number, FieldType fieldType) {
            super(mapper, number, fieldType);
            this.mapper = mapper;
            this.number = number;
        }

        @Override
        public TokenStream tokenStream(Analyzer analyzer, TokenStream previous) throws IOException {
            if (fieldType().indexOptions() != IndexOptions.NONE) {
                return mapper.popCachedStream().setLongValue(number);
            }
            return null;
        }

        @Override
        public String numericAsString() {
            return java.lang.Long.toString(number);
        }
    }
}


text:
package com.emc.ecs.nfsclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.junit.Assert;
import org.junit.Assume;

/**
 * @author seibed
 *
 */
public class NfsTestBase extends Assert {

    /**
     * Name of the properties file holding unit test parameters. This is
     * searched for in the classpath and the home directory, e.g., =>
     * $HOME/test.properties.
     */
    private static final String DEFAULT_FILE_NAME = "test";

    /**
     * Properties key for the NFS server.
     */
    private static final String NFS_SERVER = "nfs.server";

    /**
     * Property key for the path exported by the NFS server.
     */
    private static final String NFS_EXPORT = "nfs.export";

    /**
     * Properties for use in testing.
     */
    private final Properties _properties;

    /**
     * The server to use for testing.
     */
    private final String _server;

    /**
     * The exported path to use for testing.
     */
    private final String _exportedPath;

    /**
     * Protected to force subclassing. This will throw an exception if test
     * properties have not been properly configured.
     *
     * @throws IOException
     */
    protected NfsTestBase() throws IOException {
        _properties = loadProperties();
        _server = getProperty(NFS_SERVER);
        _exportedPath = getProperty(NFS_EXPORT);
    }

    /**
     * @param propertyKey The key for the property.
     * @return The property value.
     */
    protected final String getProperty(String propertyKey) {
        return _properties.getProperty(propertyKey);
    }

    /**
     * @return The server to use for testing.
     */
    protected final String getServer() {
        Assume.assumeTrue(StringUtils.isNotBlank(_server));
        return _server;
    }

    /**
     * @return The exported path to use for testing.
     */
    protected final String getExportedPath() {
        Assume.assumeTrue(StringUtils.isNotBlank(_exportedPath));
        return _exportedPath;
    }

    /**
     * @return The absolute path to use for testing.
     */
    protected final String getAbsolutePath() {
        return getServer() + ":" + getExportedPath();
    }

    /**
     * Loads the default properties, throws an exception if they cannot be
     * loaded.
     *
     * @return The properties.
     * @throws IOException
     */
    protected static Properties loadProperties() throws IOException {
        return loadProperties(DEFAULT_FILE_NAME);
    }

    /**
     * Locates and loads the properties file for the test configuration. This
     * file can reside in one of two places: somewhere in the CLASSPATH or in
     * the user's home directory.
     *
     * @param fileName The file name.
     * @return the contents of the properties file as a
     *         {@link java.util.Properties} object.
     * @throws IOException
     */
    protected static Properties loadProperties(String fileName) throws IOException {
        String fullFileName = fileName + ".properties";
        InputStream inputStream = NfsTestBase.class.getClassLoader().getResourceAsStream(fullFileName);
        if (inputStream == null) {
            // Check in home directory
            File homeProperties = new File(System.getProperty("user.home") + File.separator + fullFileName);
            if (homeProperties.exists()) {
                inputStream = new FileInputStream(homeProperties);
            }
        }

        Assume.assumeNotNull(inputStream);

        Properties properties = new Properties();
        properties.load(inputStream);
        inputStream.close();
        return properties;
    }

}


text:
<?php

namespace BetterknowBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Gem
 *
 * @ORM\Table(name="gem")
 * @ORM\Entity(repositoryClass="BetterknowBundle\Repository\GemRepository")
 */
class Gem
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var bool
     *
     * @ORM\Column(name="gender", type="boolean", unique=false, nullable=true)
     */
    private $gender;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="timeReceive", type="time", unique=false)
     */
    private $timeReceive;

    /**
     * A gem belong to a user
     * @ORM\ManyToOne(targetEntity="BetterknowBundle\Entity\User", inversedBy="gems")
     * @ORM\JoinColumn(nullable=false)
     */
    private $user;

    public function __construct()
    {
        $this->timeReceive = new \DateTime();
    }

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set gender
     *
     * @param integer $gender
     *
     * @return Gem
     */
    public function setGender($gender)
    {
        $this->gender = $gender;

        return $this;
    }

    /**
     * Get gender
     *
     * @return int
     */
    public function getGender()
    {
        return $this->gender;
    }

    /**
     * Set timeReceive
     *
     * @param \DateTime $timeReceive
     *
     * @return Gem
     */
    public function setTimeReceive($timeReceive)
    {
        $this->timeReceive = $timeReceive;

        return $this;
    }

    /**
     * Get timeReceive
     *
     * @return \DateTime
     */
    public function getTimeReceive()
    {
        return $this->timeReceive;
    }

    /**
     * Set user
     *
     * @param \BetterknowBundle\Entity\User $user
     *
     * @return Gem
     */
    public function setUser(\BetterknowBundle\Entity\User $user)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \BetterknowBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}


text:
/*
 * 9. Create a method that places a new order in the Northwind database.
 * The order should contain several order items.
 * Use transaction to ensure the data consistency.
 */

namespace EntityFramework.ConsoleClient
{
    using System;
    using System.Linq;
    using Northwind.Models;

    /// <remarks>
    /// In all versions of Entity Framework, whenever you execute SaveChanges()
    /// to insert, update or delete on the database the framework will wrap that
    /// operation in a transaction. This transaction lasts only long enough to
    /// execute the operation and then completes. When you execute another such
    /// operation a new transaction is started.
    ///
    /// More information: https://coderwall.com/p/jnniww
    /// </remarks>
    public class WorkingWithTransactions
    {
        public static void Main()
        {
            Console.WriteLine("({0} affected row(s))\n", TestOnExplicitlyStartedTransaction());
            Console.WriteLine("({0} affected row(s))\n", TestOnImplicitlyStartedTransaction());
        }

        /// <summary>
        /// Started the transaction explicitly. We have options to commit / roll-back transactions.
        /// </summary>
        private static int TestOnExplicitlyStartedTransaction()
        {
            var affectedRows = 0;
            var customerId = "VINET";
            var employeeId = 5;

            var invalidEmployeeId = int.MaxValue;

            using (var dbContext = new NorthwindEntities())
            {
                using (var transaction = dbContext.Database.BeginTransaction())
                {
                    try
                    {
                        #region [Add Orders]

                        // This cause an error
                        var firstOrder = new Order()
                        {
                            CustomerID = customerId,
                            EmployeeID = invalidEmployeeId // employeeId
                        };

                        dbContext.Orders.Add(firstOrder);

                        var secondOrder = new Order()
                        {
                            CustomerID = customerId,
                            EmployeeID = employeeId
                        };

                        secondOrder.Order_Details.Add(new Order_Detail()
                        {
                            OrderID = secondOrder.OrderID,
                            ProductID = 5,
                            UnitPrice = 12.34m,
                            Quantity = 100,
                            Discount = 0.2f
                        });

                        dbContext.Orders.Add(secondOrder);

                        #endregion

                        affectedRows = dbContext.SaveChanges();

                        // Finish successfully => Commit transaction
                        transaction.Commit();

                        // Test to Rollback() insted of Commit() and you will see that the changes are rolled-back
                        //transaction.Rollback();

                        Console.WriteLine("- Finish successfully => Commit transaction");
                    }
                    catch (Exception)
                    {
                        // Finish Unsuccessfully => Rollback transaction
                        transaction.Rollback();

                        Console.WriteLine("- Exception: Finish Unsuccessfully => Rollback transaction");
                    }
                }
            }

            return affectedRows;
        }

        /// <summary>
        /// Started the transaction implicitly.
        /// </summary>
        private static int TestOnImplicitlyStartedTransaction()
        {
            var affectedRows = 0;
            var customerId = "RATTC";
            var employeeId = 6;

            var invalidEmployeeId = int.MaxValue;

            using (var dbContext = new NorthwindEntities())
            {
                try
                {
                    #region [Add Orders]

                    // This cause an error
                    var firstOrder = new Order()
                    {
                        CustomerID = customerId,
                        EmployeeID = invalidEmployeeId // employeeId
                    };

                    dbContext.Orders.Add(firstOrder);

                    var secondOrder = new Order()
                    {
                        CustomerID = customerId,
                        EmployeeID = employeeId
                    };

                    secondOrder.Order_Details.Add(new Order_Detail()
                    {
                        OrderID = secondOrder.OrderID,
                        ProductID = 5,
                        UnitPrice = 12.34m,
                        Quantity = 100,
                        Discount = 0.2f
                    });

                    dbContext.Orders.Add(secondOrder);

                    #endregion

                    affectedRows = dbContext.SaveChanges();

                    Console.WriteLine("- Finish successfully => Commit transaction");
                }
                catch (Exception)
                {
                    Console.WriteLine("- Exception: Finish Unsuccessfully => Rollback transaction");
                }
            }

            return affectedRows;
        }
    }
}


text:
<load target="./js/module_admin.js" />

{$lang->filebox}

<form action="{getUrl('')}" method="post" enctype="multipart/form-data">
	<input type="hidden" name="module" value="module" />
	<input type="hidden" name="act" value="procModuleFileBoxAdd" />
	<input type="hidden" name="vid" value="{$vid}" />
	<input type="hidden" name="filter" value="{$filter}" />
	<input type="hidden" name="input" value="{$input}" />

				{$lang->description}
				<input type="text" name="comment" />

				{$lang->file}
				<input type="file" name="addfile" />

						{@sprintf($lang->about_file_extension,join(", ",$arrfilter ))}

		<input class="btn" type="submit" value="{$lang->cmd_submit}" />

</form>


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/** \file SymmetryGroup.hpp
 *  \brief Write Me!!!!!!
 *  \author Ryan M. Richard
 *  \version 1.0
 *  \date April 20, 2016
 */

#ifndef PULSAR_GUARD_SYMMETRYGROUP_HPP
#define PULSAR_GUARD_SYMMETRYGROUP_HPP

#include <unordered_set>
#include <string>
#include <iostream>
#include "pulsar/system/symmetry/SymmetryElement.hpp"

namespace pulsar {
namespace system{

///Base class for a group of symmetry elements
struct SymmetryGroup{
    ///Builds a new SymmetryGroup, auto adds identity
    SymmetryGroup(const std::unordered_set<SymmetryElement>& Es,
                  const std::string SSym,const std::string HMSym);

    ///The set of elements in this group
    const std::unordered_set<SymmetryElement> symmetry_elements;
    ///Schoenflies symbol
    const std::string schoenflies_symbol;
    ///Hermann-Mauguin symbol
    const std::string hm_symbol;
    ///Returns the order of the group, throws if group is infinite order
    size_t order()const;
    ///True if this is a finite group
    bool finite()const;
    ///prints the group the given buffer
    void print(std::ostream& os)const{os<<schoenflies_symbol;}
};

inline std::ostream& operator<<(std::ostream& os, const SymmetryGroup& G){
    G.print(os);
    return os;
}

///Follows flow-chart logic to assign point group
SymmetryGroup assign_group(const std::unordered_set<SymmetryElement>& Elems);

///This namespace contains interfaces whose entire purpose is to set up the
///SymmetryGroup correctly and then be sliced off
namespace PointGroup{//These names are short so namespace protect them

#define PGMacro(name)\
    struct name: public SymmetryGroup{\
    name(const std::unordered_set<SymmetryElement>&,size_t);\
    name(size_t);};

///Helper for cyclic groups
PGMacro(Cn)
///Helper for pyramidal groups
PGMacro(Cnv)
///Helper for cyclic reflection groups
PGMacro(Cnh)
///Helper for improper rotation group (n must be even or you have a Cnh group)
PGMacro(Sn)
///Helper for dihedral groups
PGMacro(Dn)
///Helper for prismatic groups
PGMacro(Dnh)
///Helper for antiprismatic groups
PGMacro(Dnd)

#undef PGMacro
struct Cs:public SymmetryGroup{
        Cs(const std::unordered_set<SymmetryElement>&Es):
    SymmetryGroup(Es,"Cs","m"){}
        Cs();

};
struct Ci:public SymmetryGroup{
        Ci(const std::unordered_set<SymmetryElement>&Es):
    SymmetryGroup(Es,"Ci","[1]"){}
        Ci();
};

///Helper for linear w/ no inversion
struct Coov:public SymmetryGroup{
    Coov(const std::unordered_set<SymmetryElement>&Es):
    SymmetryGroup(Es,"Coov","oom"){}
    Coov();
};

///Helper for linear w/ inversion
struct Dooh:public SymmetryGroup{
    Dooh(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"Dooh","oo/mm"){}
    Dooh();
};

struct T:public SymmetryGroup{
    T(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"T","23"){}
};

struct Th:public SymmetryGroup{
    Th(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"Th","m[3]"){}
};

struct Td:public SymmetryGroup{
    Td(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"Td","[4]3m"){}
};

struct O:public SymmetryGroup{
    O(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"O","432"){}
};

struct Oh:public SymmetryGroup{
    Oh(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"Oh","m[3]m"){}
};

struct I:public SymmetryGroup{
    I(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"I","532"){}
};

struct Ih:public SymmetryGroup{
    Ih(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"Ih","[53]m"){}
};

struct Kh:public SymmetryGroup{
    Kh(const std::unordered_set<SymmetryElement>& Es):
    SymmetryGroup(Es,"Kh","oo/moo"){}
    Kh():Kh(std::unordered_set<SymmetryElement>()){}
};

}//End namespace PointGroup

}//End namespace system
}//End namespace pulsar
#endif /* PULSAR_GHUARD_SYMMETRYGROUP_HPP */