text:
import sys
import os
import re
import logging
import pkgutil
import importlib
import traceback
from collections import OrderedDict
from importlib import import_module
import optparse
from getpass import getpass

from substance import Shell
from substance.exceptions import InvalidCommandError

logger = logging.getLogger('substance')

class Parser(optparse.OptionParser):
    pass
#  def format_description(self, formatter):
#    return self.description if self.description else ""

    def format_epilog(self, formatter):
        return "\n" + self.epilog if self.epilog else ""

class PassThroughParser(Parser):
    def _process_long_opt(self, rargs, values):
        try:
            optparse.OptionParser._process_long_opt(self, rargs, values)
        except optparse.BadOptionError as err:
            self.largs.append(err.opt_str)

    def _process_short_opts(self, rargs, values):
        try:
            optparse.OptionParser._process_short_opts(self, rargs, values)
        except optparse.BadOptionError as err:
            self.largs.append(err.opt_str)

class CLI(object):
    def __init__(self):
        self.args = None
        self.options = None
        self.input = None
        self.parser = None
        self.name = None
        self.parent = None

    def getHelp(self):
        """Returns the help description for this particular command"""
        return self.getParser().format_help()

    def getHelpTitle(self):
        return ""

    def getHelpDetails(self):
        return ""

    def getUsage(self):
        return "command: USAGE [options]"

    def getParserClass(self):
        return Parser

    def getParser(self, interspersed=True):
        usage = self.getUsage()
        parserClass = self.getParserClass()
        parser = parserClass(usage=usage, conflict_handler="resolve", add_help_option=False,
                             description=self.getHelpTitle(), epilog=self.getHelpDetails())
        self.getShellOptions(parser)
        if interspersed:
            parser.enable_interspersed_args()
        else:
            parser.disable_interspersed_args()
        return parser

    def parseShellInput(self, interspersed=True):
        """Return the options and arguments for this command as a tuple"""
        usage = self.getUsage()
        parser = self.getParser(interspersed)
        (opts, args) = parser.parse_args(self.input)
        return (opts, args)

    def getShellOptions(self, optparser):
        return optparser

    def execute(self, args=None):
        self.input = args
        (self.options, self.args) = self.parseShellInput()
        return self.main()

    def initialize(self):
        pass

    def main(self):
        """The main function body"""
        pass

    def getOptions(self):
        return self.options

    def hasOption(self, key):
        if self.options and hasattr(self.options, key):
            return True

    def getOption(self, key):
        if self.hasOption(key):
            return getattr(self.options, key, None)
        return None

    def getArgs(self):
        return self.args

    def hasArg(self, argno):
        if len(self.args) < argno + 1:
            return False
        return True

    def getArg(self, argno):
        if self.hasArg(argno):
            return self.args[argno]
        return None

    def read(self, msg=""):
        return input(msg)

    def readln(self, msg=""):
        return input(msg + "\n")

    def readpwd(self, msg=""):
        return getpass(msg)

    def readpwdln(self, msg=""):
        return getpass(msg + "\n")

    def exitOK(self, msg=None):
        if msg:
            logger.info(msg)
        sys.exit(0)

    def exitHelp(self, msg=None, code=1):
        logger.info(self.getHelp())
        logger.info("")
        if msg:
            logger.info(msg)
        sys.exit(1)

    def exitError(self, msg=None, code=1):
        if msg and isinstance(msg, Exception):
            logger.error("%s (%s)" % (msg, type(msg).__name__))
        elif msg:
            logger.error(msg)
        sys.exit(1)

class Program(CLI):
    def __init__(self):
        super(Program, self).__init__()
        self.cmdString = None
        self.commandInput = None
        self.command = None
        self.core = None
        self.commands = OrderedDict()
        self.addCommand('help', 'substance.command.help')

    def setupCommands(self):
        pass

    def getCommands(self):
        k = list(self.commands.keys())
        v = [self.getCommand(x) for x in k]
        return OrderedDict(list(zip(k, v)))

    def getCommand(self, commandName):
        if commandName in self.commands:
            commandModule = self.commands[commandName]
            commandClass = commandName.title()
        else:
            commandModule = 'substance.command.fallback'
            commandClass = 'Fallback'

        module_ = importlib.import_module(commandModule)
        class_ = getattr(module_, commandClass)
        command = class_()
        command.parent = self
        command.name = commandName
        return command

    def addCommand(self, commandName, commandModule):
        if commandName in self.commands:
            raise ValueError(
                "Command '%s' is already registered." % commandName)
        self.commands[commandName] = commandModule

    def removeCommand(self, commandName):
        if commandName not in self.commands:
            raise ValueError("Command '%s' is not registered." % commandName)
        self.commands.pop(commandName, None)

    def getHelpDetails(self):
        helpUsage = "Commands:\n\n"
        for name, command in self.getCommands().items():
            helpUsage += "  %-20s%s\n" % (name, command.getHelpTitle())
        return helpUsage

    def setupEnv(self):
        """Setup the Environment """

    def setupLogging(self):
        if self.getOption('debug'):
            logging.getLogger('substance').handlers[0].setLevel(logging.DEBUG)
            logging.getLogger('subwatch').setLevel(logging.DEBUG)
            logging.getLogger('watchdog').setLevel(logging.INFO)
            logging.getLogger('paramiko').setLevel(logging.INFO)

    def execute(self, args=None):
        self.input = args
        (self.options, self.args) = self.parseShellInput(False)
        self.main()

    def initialize(self):
        self.setupLogging()
        self.setupEnv()
        self.setupCommands()

    def main(self):
        try:
            self.initialize()

            if not len(self.args) > 0:
                self.cmdString = 'help'
                self.commandInput = []
            else:
                self.cmdString = self.args[0]
                self.commandInput = self.args[1:]

            self.runCommand(self.cmdString)
        except Exception as err:
            logger.error(traceback.format_exc())
            self.exitError("Error running command %s: %s" %
                           (self.cmdString, err), code=2)

    def runCommand(self, commandName):
        command = self.getCommand(commandName)
        self.command = self.initCommand(command)
        self.command.execute(self.commandInput)

class Command(CLI):

    def __init__(self):
        super(Command, self).__init__()

    def ask(self, msg):
        return Shell.printConfirm(msg, assumeYes=self.core.getAssumeYes())

    # ---- Validation Helpers

    def getInputName(self):
        if len(self.args) <= 0:
            return self.exitError("Please specify an engine name.")

        name = self.args[0]
        if not name or not self.validateEngineName(name):
            return self.exitError("Invalid name specified. Please use only letters, numbers, dash or underscores.")
        return name

    def validateEngineName(self, name):
        return bool(re.match(r'^[a-zA-Z0-9\-_]*$', name))

    def validateDriver(self, driver):
        return self.core.validateDriver(driver)

    def validateInteger(self, value):
        try:
            val = int(value)
            return True
        except ValueError:
            return False

class SubProgram(Program):
    def initialize(self):
        self.setupCommands()


text:
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NUnit.Framework;
using Testura.Code.Generators.Common.Arguments.ArgumentTypes;
using Testura.Code.Models.References;
using Testura.Code.Statements;

namespace Testura.Code.Tests.Generators.Common.Arguments.ArgumentTypes;

[TestFixture]
public class InvocationArgumentTests
{
    [Test]
    public void GetArgumentSyntax_WhenUsingMethod_ShouldGetCode()
    {
        var argument =
            new InvocationArgument(Statement.Expression.Invoke(new MethodReference("Do")).AsExpression());
        var syntax = argument.GetArgumentSyntax();

        Assert.IsInstanceOf<ArgumentSyntax>(syntax);
        Assert.AreEqual("Do()", syntax.ToString());
    }

    [Test]
    public void GetArgumentSyntax_WhenUsingMethodAsNamedArgument_ShouldGetCode()
    {
        var argument =
            new InvocationArgument(Statement.Expression.Invoke(new MethodReference("Do")).AsExpression(), namedArgument: "namedArgument");
        var syntax = argument.GetArgumentSyntax();

        Assert.IsInstanceOf<ArgumentSyntax>(syntax);
        Assert.AreEqual("namedArgument:Do()", syntax.ToString());
    }

    [Test]
    public void GetArgumentSyntax_WhenUsingReference_ShouldGetCode()
    {
        var argument =
            new InvocationArgument(new MethodReference("Do"));
        var syntax = argument.GetArgumentSyntax();

        Assert.IsInstanceOf<ArgumentSyntax>(syntax);
        Assert.AreEqual("Do()", syntax.ToString());
    }

    [Test]
    public void GetArgumentSyntax_WhenUsingMethodAndCasting_ShouldGetCode()
    {
        var argument =
            new InvocationArgument(Statement.Expression.Invoke(new MethodReference("Do")).AsExpression(), typeof(int));
        var syntax = argument.GetArgumentSyntax();

        Assert.IsInstanceOf<ArgumentSyntax>(syntax);
        Assert.AreEqual("(int)Do()", syntax.ToString());
    }
}

redpajama_set_name: RedPajamaGithub


text:
[![Gem Version](https://badge.fury.io/rb/validate_zipcode.png)](http://badge.fury.io/rb/validate_zipcode)
[![Build Status](https://secure.travis-ci.org/RamonHossein/validate_zipcode.png?branch=master)](http://travis-ci.org/RamonHossein/validate_cpf)
[![Coverage Status](https://coveralls.io/repos/RamonHossein/validate_zipcode/badge.png?branch=master)](https://coveralls.io/r/RamonHossein/validate_zipcode)

Adds ZipCode / PostalCode validation support to Rails (ActiveModel) and test it in a simple way.

Any other country's postal code that not on the [list of country identification](https://github.com/RamonHossein/validate_zipcode/blob/master/LIST.md) will validate without errors.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'validate_zipcode'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install validate_zipcode

## Usage

Just use as any other validator passing the country:

ValidateZipcode expects the model has an attribute called country to contain the country identification.

This Gem use as country identification the codes supplied by the ISO 3166-2 (International Organization for Standardization).

```ruby
class Address < ActiveRecord::Base
  validates :zipcode, zipcode: {country: "US"}
end
```

## Error Message

If you need to localize the error message, just add this to your I18n locale file:

```ruby
errors:
  messages:
    this_zip_code_is_invalid: "This zip code is invalid"
```

You can provide your own message using :message option.

```ruby
validates :zipcode, zipcode: {country: "US", message: "new error message"}
```

## Mantainers

[RamonHossein](https://github.com/RamonHossein)

## Contributors

To see the generous people who have contributed code, take a look at the [contributors list](http://github.com/RamonHossein/validate_zipcode/contributors).

## Contributing

1. Fork it
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Added some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create new Pull Request

## License

The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).


text:
<!DOCTYPE html>

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<title><%section name="pagetitle"%></title>

        <link rel="stylesheet" type="text/css" media="Screen" href="html/bootstrap.min.css" />
		<link rel="stylesheet" type="text/css" media="Screen" href="html/bootstrap-theme.css" />
		<link rel="stylesheet" type="text/css" media="Screen" href="html/font-awesome.css" />
		<link rel="stylesheet" type="text/css" media="Screen" href="html/yacrs-base.css" />

		<link rel="stylesheet" type="text/css" media="Screen" href="html/yacrs-theme.css" />
        <%scripts%>
        <%autoscript%>

Class Response

						<%section name="logoutLink" div_id="logoutLink"%>

					<%section name="breadcrumb" div_id="breadcrumb"%>
					<%section name="sideLinks" div_id="links"%>

						<%section name="headings"%>
	          			<%section name="loginBox" div_id="loginBox"%>
	                    <%section name="coursesBlock" div_id="coursesBlock"%>
	                    <%section name="sideInfo" div_id="linksArea"%>
			  			<%section name="mainBody"%>

  <%section name="afterContent"%>


text:
<?php
/**
 * @author gareth.evans
 */

namespace Qubes\Defero\Applications\Defero\Wizard;

class WizardStepIterator extends \ArrayIterator implements IWizardStepIterator
{
  /**
   * @param IWizardStep $step
   *
   * @return void
   */
  public function addStep(IWizardStep $step)
  {
    $this->append($step);
  }

  /**
   * Checks that the next key exists and returns the step. If the key does not
   * exist we return null.
   *
   * @return IWizardStep|null
   */
  public function getNextStep()
  {
    $nextKey = $this->key() + 1;

    if($this->offsetExists($nextKey))
    {
      return $this->offsetGet($nextKey);
    }

    return null;
  }

  /**
   * Moves the pointer forward, checks that the key exists and returns the step.
   * If the key does not exist we return null.
   *
   * @return IWizardStep|null
   */
  public function getNextStepAndMovePointer()
  {
    $this->next();

    return $this->getCurrentStep();
  }

  /**
   * @return null|IWizardStep
   */
  public function getCurrentStep()
  {

    if($this->valid())
    {
      return $this->current();
    }

    return null;
  }
}


text:
package se.liu.rtslab.energybox.engines;

import se.liu.rtslab.energybox.Packet;
import se.liu.rtslab.energybox.StatisticsEntry;
import se.liu.rtslab.energybox.properties.device.PropertiesDevice3G;
import se.liu.rtslab.energybox.properties.network.Properties3G;
import javafx.collections.ObservableList;
import javafx.scene.chart.XYChart;
/**
 * @author Rihards Polis
 * Linkoping University
 */
public class Engine3G extends Engine
{
    enum State
    {
        IDLE(0), FACH(1), DCH(3);
        private final int value;
        private State(int value){this.value = value;}
        public int getValue() { return this.value; }
    }

    // Pie chart data
    private double timeInFACH;
    private double timeInIDLE;
    private double timeInDCH;

    // VARIABLES TAKEN FROM THE CONSTRUCTOR
    Properties3G networkProperties;
    PropertiesDevice3G deviceProperties;

    // CHART VARIABLES
    XYChart.Series<Double, Integer> fachSeries = new XYChart.Series<>();
    XYChart.Series<Double, Integer> dchSeries = new XYChart.Series<>();

    // MAIN CONSTRUCTOR
    public Engine3G(ObservableList<Packet> packetList,
            String sourceIP,
            Properties3G networkProperties,
            PropertiesDevice3G deviceProperties)
    {
        this.packetList = packetList;
        this.networkProperties = networkProperties;
        this.deviceProperties = deviceProperties;
        this.packetList = sortUplinkDownlink(packetList, sourceIP);
        this.sourceIP = sourceIP;
    }

    @Override
    public XYChart.Series<Double, Integer> modelStates()
    {
        // Buffer control variables
        int bufferIDLEtoFACHuplink = 0, bufferIDLEtoFACHdownlink = 0,
            bufferFACHtoDCHuplink = 0, bufferFACHtoDCHdownlink = 0;
        // Timer variables
        long deltaDownlink = 0,
                deltaUplink = 0,
                deltaT = 0,
                previousTimeUplink =  packetList.get(0).getTimeInMicros(),
                previousTimeDownlink = packetList.get(0).getTimeInMicros(),
                previousTime = packetList.get(0).getTimeInMicros(), // might wanna replace the variable with packetList.get(i-1).getTime()
                timeToEmptyUplink = 0; // timeToEmptyDownlink is a constant : networkProperties.getDOWNLINK_BUFFER_EMPTY_TIME;
        State state = State.IDLE; // State enumeration

        stateSeriesData.beforeChanges();

        // Packet list points
        for (int i = 0; i < packetList.size(); i++)
        {
            // Populating the packetChart series
            // to temporary data structure, so too many events are not sent
            // to observers. Very bad for performance!
            // Actually update the Chart data using updatePacketChart() later when
            // all packets have been added.
            packetChartEntry(packetList.get(i));

            // Update deltas and previous times (uplink and downlink seperately
            // for buffer calculations)
            deltaT = packetList.get(i).getTimeInMicros() - previousTime;

            if (packetList.get(i).getUplink())
                deltaUplink = packetList.get(i).getTimeInMicros() - previousTimeUplink;
            else
                deltaDownlink = packetList.get(i).getTimeInMicros() - previousTimeDownlink;

            // DEMOTIONS
            switch (state)
            {
                case FACH:
                {
                    // FACH to IDLE
                    if (deltaT > networkProperties.getFACH_IDLE_INACTIVITY_TIME())
                    {
                        fachToIdle(previousTime + networkProperties.getFACH_IDLE_INACTIVITY_TIME());
                        drawState(previousTime + (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
                        state = State.IDLE;
                        drawState(previousTime + (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
                    }
                }
                break;

                case DCH:
                {
                    // DCH to FACH to IDLE due to deltaT being higher than
                    // both timers combined.
                    if (deltaT > networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                            networkProperties.getFACH_IDLE_INACTIVITY_TIME())
                    {
                        dchToFach(previousTime + networkProperties.getDCH_FACH_INACTIVITY_TIME());
                        fachToIdle(previousTime +
                                networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                                networkProperties.getFACH_IDLE_INACTIVITY_TIME());
                        drawState(previousTime + (long)networkProperties.getDCH_FACH_INACTIVITY_TIME(), state.getValue());
                        state = State.FACH;
                        drawState(previousTime + (long)networkProperties.getDCH_FACH_INACTIVITY_TIME(), state.getValue());
                        drawState(previousTime +
                                (long)networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                                (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
                        state = State.IDLE;
                        drawState(previousTime +
                                (long)networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                                (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
                        break; // so that it wouldn't demote to FACH twice
                    }
                    // DCH to FACH
                    if (deltaT > networkProperties.getDCH_FACH_INACTIVITY_TIME())
                    {
                        dchToFach(previousTime + networkProperties.getDCH_FACH_INACTIVITY_TIME());
                        drawState(previousTime + (long)networkProperties.getDCH_FACH_INACTIVITY_TIME(), state.getValue());
                        state = State.FACH;
                        drawState(previousTime + (long)networkProperties.getDCH_FACH_INACTIVITY_TIME(), state.getValue());
                    }
                }
                break;
            }
            // PROMOTIONS
            switch (state)
            {
                case IDLE:
                {
                    // Uplink packets
                    if (packetList.get(i).getUplink())
                    {
                        // If the packet is larger than
                        if (packetList.get(i).getLength() > networkProperties.getUPLINK_BUFFER_IDLE_TO_FACH_OR_DCH())
                        {
                            // Bug correction for when the trace is not realistic.
                            // Ignores the the transition time if there are packets
                            // before the transition is suppose to end.
                            //if (packetList.get(i+1).getTimeInMicros() > packetList.get(i).getTimeInMicros() + networkProperties.getIDLE_TO_DCH_TRANSITION_TIME())
                            if ((packetList.get(i).getTimeInMicros() + networkProperties.getIDLE_TO_DCH_TRANSITION_TIME()) < (double)packetList.get(i+1).getTimeInMicros())
                            {
                                System.out.println("Next packet at : " + (double)packetList.get(i+1).getTimeInMicros());
                                System.out.println("Proomotion at: " + (packetList.get(i).getTimeInMicros() + networkProperties.getIDLE_TO_DCH_TRANSITION_TIME()));
                                idleToDch(packetList.get(i).getTimeInMicros() + networkProperties.getIDLE_TO_DCH_TRANSITION_TIME());
                                drawState(packetList.get(i).getTimeInMicros() + (long)networkProperties.getIDLE_TO_DCH_TRANSITION_TIME(), state.getValue());
                                state = State.DCH;
                                drawState(packetList.get(i).getTimeInMicros() + (long)networkProperties.getIDLE_TO_DCH_TRANSITION_TIME(), state.getValue());
                            }
                            else
                            {
                                idleToDch((double)packetList.get(i).getTimeInMicros());
                                drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                                state = State.DCH;
                                drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                            }
                        }
                        else
                        {
                            idleToFach((double)packetList.get(i).getTimeInMicros());
                            drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                            state = State.FACH;
                            drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                            bufferIDLEtoFACHuplink += packetList.get(i).getLength();
                        }
                    }
                    // Downlink packets
                    else
                    {
                        if (packetList.get(i).getLength() > networkProperties.getDOWNLINK_BUFFER_IDLE_TO_FACH_OR_DCH())
                        {
                            idleToDch((double)packetList.get(i).getTimeInMicros());// + networkProperties.getIDLE_TO_DCH_TRANSITION_TIME());
                            drawState(packetList.get(i).getTimeInMicros(), state.getValue());// + (long)networkProperties.getIDLE_TO_DCH_TRANSITION_TIME(), state.getValue());
                            state = State.DCH;
                            drawState(packetList.get(i).getTimeInMicros(), state.getValue());// + (long)networkProperties.getIDLE_TO_DCH_TRANSITION_TIME(), state.getValue());
                        }
                        else
                        {
                            idleToFach((double)packetList.get(i).getTimeInMicros());
                            drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                            state = State.FACH;
                            drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                            bufferIDLEtoFACHdownlink += packetList.get(i).getLength();
                        }
                    }
                }
                break;

                case FACH:
                {
                    bufferIDLEtoFACHdownlink = 0;
                    bufferIDLEtoFACHuplink = 0;
                    timeToEmptyUplink = timeToEmptyUplink(bufferFACHtoDCHuplink);

                    // If timeToEmptyUplink or DOWNLINK_BUFFER_EMPTY_TIME has passed, clear the RLCBuffer
                    if (deltaUplink > timeToEmptyUplink)
                        bufferFACHtoDCHuplink = 0;
                    if (deltaDownlink > networkProperties.getDOWNLINK_BUFFER_EMPTY_TIME())
                        bufferFACHtoDCHdownlink = 0;

                    // Uplink packets
                    if (packetList.get(i).getUplink())
                    {
                        drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                        bufferFACHtoDCHuplink += packetList.get(i).getLength();
                        if (bufferFACHtoDCHuplink > networkProperties.getUPLINK_BUFFER_FACH_TO_DCH())
                        {
                            fachToDch((double)packetList.get(i).getTimeInMicros());
                            state = State.DCH;
                            bufferFACHtoDCHuplink = 0;
                        }
                        drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                    }
                    // Downlink packets
                    else
                    {
                        drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                        bufferFACHtoDCHdownlink += packetList.get(i).getLength();
                        if (bufferFACHtoDCHdownlink > networkProperties.getDOWNLINK_BUFFER_FACH_TO_DCH())
                        {
                            fachToDch((double)packetList.get(i).getTimeInMicros());
                            state = State.DCH;
                            bufferFACHtoDCHdownlink = 0;
                        }
                        drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                    }
                }
                break;

                case DCH:
                {
                    drawState(packetList.get(i).getTimeInMicros(), state.getValue());
                    bufferIDLEtoFACHuplink = 0;
                    bufferIDLEtoFACHdownlink = 0;
                    bufferFACHtoDCHuplink = 0;
                    bufferFACHtoDCHdownlink = 0;
                }
                break;
            }
            // Save timestamps for the next loop
            previousTime = packetList.get(i).getTimeInMicros();
            if (packetList.get(i).getUplink())
                previousTimeUplink = packetList.get(i).getTimeInMicros();
            else
                previousTimeDownlink = packetList.get(i).getTimeInMicros();
        }

        // update charts here for performance reasons
        updatePacketCharts();

        // Finish the trace if the final state is FACH or DCH
        if (state == State.DCH)
        {
            dchToFach(previousTime + networkProperties.getDCH_FACH_INACTIVITY_TIME());
            fachToIdle(previousTime +
                    networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                    networkProperties.getFACH_IDLE_INACTIVITY_TIME());
            drawState(previousTime + (long)networkProperties.getDCH_FACH_INACTIVITY_TIME(), state.getValue());
            state = State.FACH;
            drawState(previousTime + (long)networkProperties.getDCH_FACH_INACTIVITY_TIME(), state.getValue());

            drawState(previousTime +
                    (long)networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                    (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
            state = State.IDLE;
            drawState(previousTime +
                    (long)networkProperties.getDCH_FACH_INACTIVITY_TIME() +
                    (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
        }
        else if (state == State.FACH)
        {
            fachToIdle(previousTime + networkProperties.getFACH_IDLE_INACTIVITY_TIME());
            drawState(previousTime + (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
            state = State.IDLE;
            drawState(previousTime + (long)networkProperties.getFACH_IDLE_INACTIVITY_TIME(), state.getValue());
        }

        stateSeriesData.afterChanges();

        distrStatisticsList.add(new StatisticsEntry("Nr of UL packets", getUplinkPacketCount()));
        distrStatisticsList.add(new StatisticsEntry("Nr of DL packets", getDownlinkPacketCount()));
        return stateSeries;
    }

    @Override
    public void calculatePower() {
        timeInIDLE = 0.0;
        timeInFACH = 0.0;
        timeInDCH = 0.0;
        for (int i = 1; i < stateSeries.getData().size(); i++) {
            double timeDifference = (stateSeries.getData().get(i).getXValue() - stateSeries.getData().get(i - 1).getXValue());
            switch (stateSeries.getData().get(i - 1).getYValue()) {
                case 0: {
                    power += timeDifference * deviceProperties.getPOWER_IN_IDLE();
                    timeInIDLE += timeDifference;
                }
                break;

                case 1: {
                    power += timeDifference * deviceProperties.getPOWER_IN_FACH();
                    timeInFACH += timeDifference;
                }
                break;

                case 3: {
                    power += timeDifference * deviceProperties.getPOWER_IN_DCH();
                    timeInDCH += timeDifference;
                }
                break;
            }
        }
        // Total power used rounded down to four decimal places
        statisticsList.add(new StatisticsEntry("Total Power Used", ((double) Math.round(power * 10000) / 10000)));
    }

    @Override
    public String getName() {
        return "3G";
    }

    // State transition drawing methods to seperate state series
    private void dchToFach(Double time)
    {
        time = time / 1000000;
        dchSeries.getData().add(pointDch(time));
        dchSeries.getData().add(pointZero(time));

        fachSeries.getData().add(pointZero(time));
        fachSeries.getData().add(pointFach(time));
    }

    private void fachToIdle(Double time)
    {
        time = time / 1000000;
        fachSeries.getData().add(pointFach(time));
        fachSeries.getData().add(pointZero(time));
    }

    private void idleToFach(Double time)
    {
        time = time / 1000000;
        fachSeries.getData().add(pointZero(time));
        fachSeries.getData().add(pointFach(time));
    }

    private void idleToDch(Double time)
    {
        time = time / 1000000;
        dchSeries.getData().add(pointZero(time));
        dchSeries.getData().add(pointDch(time));
    }

    private void fachToDch(Double time)
    {
        time = time / 1000000;
        fachSeries.getData().add(pointFach(time));
        fachSeries.getData().add(pointZero(time));

        dchSeries.getData().add(pointZero(time));
        dchSeries.getData().add(pointDch(time));
    }

    // Formula for calculating buffer empty time depending on buffer occupancy
    // (Downlink is modeled with a constant occupancy - the value in networkProperties)
    public long timeToEmptyUplink(int buffer) { return (long)networkProperties.getUPLINK_BUFFER_EMPTY_TIME() * buffer + 10; }

    // GETTERS
    public XYChart.Series<Double, Integer> getFACH(){ return fachSeries; }
    public XYChart.Series<Double, Integer> getDCH(){ return dchSeries; }

    public double getTimeInFACH() { return timeInFACH; }
    public double getTimeInDCH() { return timeInDCH; }
    public double getTimeInIDLE() { return timeInIDLE; }

    private XYChart.Data<Double, Integer> pointDch(Double time) {
        return new XYChart.Data<Double, Integer>(time, State.DCH.getValue());
    }

    private XYChart.Data<Double, Integer> pointFach(Double time) {
        return new XYChart.Data<Double, Integer>(time, State.FACH.getValue());
    }

    private XYChart.Data<Double, Integer> pointZero(Double time) {
        return new XYChart.Data<Double, Integer>(time, 0);
    }
}


text:
import org.stellar.base._;

object StellarExample {
  def main(args: Array[String]) {
    // Uncoment when using Public network
    //Network.usePublicNetwork();

    // GCXA7A4DQSJDDJSI3UADO7WK7XLQVSFD2PMDBPOTDPRY3LAKU5O7VEJN
    val sourceKeyPair = KeyPair.fromSecretSeed("SBBC3BQTSA5O7JFJQAQTWPVHZ2OCSDOXWQTZB7IA3WSIPIEZICHB2V6L");
    val destination = KeyPair.fromAddress("GBXXA7ASHOWRMKAGKX32SFVUFDU4R34VXEC2HVHI23ZCU2NWW66UZSZJ");

    println(sourceKeyPair.getSecretSeed());
    println(sourceKeyPair.getAddress());

    var sourceAccount = new Account(sourceKeyPair, 3009998980382720L);

    val operation = new PaymentOperation.Builder(destination, new AssetTypeNative(), 20000000).build();
    val transaction = new Transaction.Builder(sourceAccount)
      .addOperation(operation)
      .addMemo(Memo.text("Scala FTW!"))
      .build();

    transaction.sign(sourceKeyPair);

    println(transaction.toEnvelopeXdrBase64());
  }
}


text:
var ESCLIEngine = require('eslint').CLIEngine,
    colors = require('colors'),
    eslintGlobals = require('../config/eslint/globals.js'),
    LintChecker = require('./LintChecker.js');

function EsLintChecker(ext) {
    this.extension = ext;
}
EsLintChecker.prototype = Object.create(LintChecker.prototype);
EsLintChecker.prototype.processFile = function(aFile) {
    var self = this,
        eslint = new ESCLIEngine({
            useEslintrc: true,
            configFile: this.getConfig(),
            globals: eslintGlobals});
    eslint
        .executeOnFiles([aFile.path])
        .results[0].messages.forEach(function(aResult) {
            self.addResult(aFile, aResult);
        });
    return aFile.issues;
};

EsLintChecker.prototype.getLocalConfig = function(aResolver) {
    return aResolver.findFile('.eslintrc', this.getGlobalConfig());
};

EsLintChecker.prototype.getGlobalConfig = function(aResolver) {
    return aResolver.pathInConfigDirectory('eslint/eslint.json');
};

EsLintChecker.prototype.type = 'eslint'.cyan.bold;

module.exports = EsLintChecker;


text:
namespace WebApplication.Models
{
    using System.ComponentModel.DataAnnotations;

    public class Category: BaseModel.BaseModel
    {
        [Required(ErrorMessage = "Обязательно для заполнения!")]
        [Display(Name = "Название категории")]
        [MaxLength(50, ErrorMessage = "Превышена максимальная длина записи(50 символов)")]
        public string Name { get; set; }
    }
}


text:
require 'capybara/helpers'
require 'rspec/expectations'

require_relative 'form_helpers.rb'

World FormHelper

LOTS = {
  all: 'All categories',
  SaaS: 'Software as a Service',
  PaaS: 'Platform as a Service',
  IaaS: 'Infrastructure as a Service',
  SCS: 'Specialist Cloud Services'
}.freeze

META_DATA_XPATHS = {
  location: '//*[@class="search-result"]//*[@class="search-result-important-metadata"][1]//*[@class="search-result-metadata-item"][2]',
  lot: '//*[@class="search-result"]//*[@class="search-result-metadata"][1]//*[@class="search-result-metadata-item"][1]',
  role: '//*[@class="search-result"]//*[@class="search-result-metadata"][1]//*[@class="search-result-metadata-item"][2]',
  status: '//*[@class="search-result"]//*[@class="search-result-metadata"][2]//*[@class="search-result-metadata-item"][1]'
}.freeze

CLOSED_OUTCOMES = {
  Awarded: 'Closed: awarded',
  Cancelled: 'Closed: cancelled',
  Closed: 'Closed: awaiting outcome',
  Unsuccessful: 'Closed: no suitable suppliers'
}.freeze

def full_lot(lot)
  LOTS[lot.to_sym]
end

def search_result_metadata_items(type)
  all(:xpath, META_DATA_XPATHS[type])
end

def closed_outcome?(status)
  CLOSED_OUTCOMES.key?(status.to_sym)
end

def closed_outcome_status?(text)
  CLOSED_OUTCOMES.value?(text)
end

def normalize_whitespace(text)
  text.to_s.gsub(/[[:space:]]+/, ' ').strip
end

## finding and selecting invisible fields

def merge_fields_and_print_answers(answer)
  @fields.merge! answer
  puts answer
end

def is_js_hidden?(html_element)
  html_element["class"] && html_element["class"].include?("js-hidden")
end

def remove_js_hidden_fields_from_results(results)
  results.each do |result|
    ancestor_divs = result.find_xpath("ancestor::div")
    if ancestor_divs
      ancestor_divs.each do |ancestor|
        if is_js_hidden?(ancestor)
          results.delete(result)
          break
        end
      end
    end
  end
  results
end

def find_elements_by_xpath(sel)
  # this function is used in places where the test wants to check for "all" elements matching a selector
  # but doesn't want to wait (effectively at all), but using an actual nil `wait` value will cause the
  # synchronize method to not be called at all. the problem being that this will bypass the "fix" we've
  # put in to make the test wait for the page not to be in a "loading" state (see
  # `synchronize_with_unload_wait`). so instead we give capybara a miniscule wait time so as ensure our
  # mechanism is called but not significantly slow down the test.
  page.all(:xpath, sel, wait: 0.001, visible: :all)
end

def all_fields(locator, options = { wait: false })
  results = all(:field, locator, options.merge(visible: :all)).to_a
  remove_js_hidden_fields_from_results(results)
end

def first_field(locator, options = { wait: false })
  all_fields(locator, options)[0]
end

def return_element(type, locator_or_element, options = { wait: false })
  if locator_or_element.is_a? Capybara::Node::Element
    element = locator_or_element
  else
    # when passing in the value of the element we want to choose/check, we pass it in as {:option => "value"}
    # but when we're finding it, we need to pass it in as {:with => "value"}
    find_options = options[:option] ? { with: options[:option] } : {}
    element = first_field(locator_or_element, find_options.merge(type: type))
    unless element
      broader_search_for_element = first_field(locator_or_element)
      if broader_search_for_element["type"] == type
        element = broader_search_for_element
      end
    end
  end
  # If the label for this radio/checkbox is not visible, it is effectively hidden from the user
  expect(find_elements_by_xpath(
    "//label[@for='#{element[:id]}']"
  )[0].visible?).to be(true), "Expected label for #{type} \"#{element.value}\" to be visible"

  element
end

def choose_radio(locator_or_radio, options = { wait: false })
  begin
    radio = return_element('radio', locator_or_radio, options)
    choose(radio[:id], options.merge(allow_label_click: true, wait: false, id: radio[:id]))
  rescue Capybara::ElementNotFound
    choose(radio[:id], allow_label_click: true, wait: false, id: radio[:id])
  end
  puts "Radio button value: #{radio.value}"
end

def check_checkbox(locator_or_checkbox, options = { wait: false })
  checkbox = return_element('checkbox', locator_or_checkbox, options)

  check(checkbox[:id], options.merge(allow_label_click: true))
  puts "Checkbox value: #{checkbox.value}"
end

def uncheck_checkbox(locator_or_checkbox, options = { wait: false })
  checkbox = return_element('checkbox', locator_or_checkbox, options)

  uncheck(checkbox[:id], options.merge(allow_label_click: true))
  puts "Unselected: #{checkbox.value}"
end

def urls_are_equal(url1, url2)
  # horrible hack, if it's a relative href stick a fake scheme and prefix on
  if url1.start_with? "/"
    if !url2.start_with? "/"
      return false
    end

    url1 = "http://localhost#{url1}"
    url2 = "http://localhost#{url2}"
  end
  url1 = URI::parse(url1)
  url2 = URI::parse(url2)
  %i[scheme host path].each do |key|
    if url1.send(key) != url2.send(key)
      return false
    end
  end
  # query and fragment parameters can appear in any order
  %i[query fragment].each do |key|
    if url1.send(key)
      if !url2.send(key)
        return false
      elsif CGI::parse(url1.send(key)) != CGI::parse(url2.send(key))
        return false
      end
    end
  end
  true
end

RSpec::Matchers.define :match_url do |expected|
  match do |actual|
    urls_are_equal(expected, actual)
  end
end

RSpec::Matchers.define :include_url do |expected|
  match do |actual_list|
    actual_list.map { |actual| urls_are_equal(actual, expected) }.include?(true)
  end
end

class String
  def camelize(arg = :lower)
    return self if self !~ /_/ && self =~ /[A-Z]+.*/

    split('_').map.with_index { |e, i| i == 0 && arg == :lower ? e.downcase : e.capitalize }.join
  end
end

class Hash
  def camelize(arg = :lower)
    # this both squashes out entries with nil values (to ensure they don't override a colliding key with a real value
    # and converts keys to camelcase
    map.reject { |k, v| v == nil }.map { |k, v| [k.camelize(arg), v] }.to_h
  end
end

def detect_boolean_strings(input)
  input_norm = input.respond_to?(:downcase) ? input.downcase : input
  if %w[f false].include? input_norm
    return false
  end
  if %w[t true].include? input_norm
    return true
  end

  input
end

# from https://github.com/ilyakatz/capybara/blob/c0844c8cf43801fa1d88e502b71b8e75ed6da017/lib/capybara/xpath.rb#L8
def escape_xpath(string)
  if string.include?("'")
    string = string.split("'", -1).map do |substr|
      "'#{substr}'"
    end.join(%q{,"'",})
    "concat(#{string})"
  else
    "'#{string}'"
  end
end

def get_table_rows_by_caption(caption)
  # Have to account for both toolkit summary table and govukTable. Can simplify once fully moved to GOVUK.
  result_table_xpath = "//caption[normalize-space(string())=#{escape_xpath(caption)}]/parent::table"
  rows_xpath = "/tbody/tr[@class='summary-item-row']"
  govuk_rows_xpath = "/tbody/tr[@class='govuk-table__row']"
  # Use the Xpath "or" operator to look for toolkit summary table rows and govukTable rows
  result_table_rows_xpath = result_table_xpath + rows_xpath + "|" + result_table_xpath + govuk_rows_xpath
  page.all(:xpath, result_table_rows_xpath)
end

def get_summary_list_rows_by_preceding_heading(heading)
  # do we even h5?
  heading_xpath = "//*[self::h1 or self::h2 or self::h3 or self::h4][normalize-space(string())=normalize-space(#{escape_xpath(heading)})]"
  dl_rows_xpath = "/following-sibling::*[position()=1][self::dl]/*"
  paragraph_xpath = '/following-sibling::p'
  # some lists have a preceding paragraph
  page.all(:xpath, heading_xpath + dl_rows_xpath).any? ? page.all(:xpath, heading_xpath + dl_rows_xpath) : page.all(:xpath, heading_xpath + paragraph_xpath + dl_rows_xpath)
end

def convert_log(log)
  message = JSON.parse(log.message)
  message.store(:timestamp, log.timestamp)
  message
end

def slow_type(element, text, delay = 0.01)
  text.chars.each { |c|
    element.send_keys(c)
    sleep(delay)
  }
end

def inline_http_requests
  # Chrome does not support network_traffic, instead we can extract this from the performance logs
  logs = page.driver.browser.manage.logs.get(:performance)
  # Store messages in a structure which is easier to work with
  messages_array = logs.map { |l| convert_log(l) }
  # Filter to only messages after test has started and requests with headers
  messages_after_test_start = messages_array.select { |m| m[:timestamp] > @timestamp }
  messages_after_test_start.map { |l| l.dig('message', 'params', 'headers') }.compact
end


text:
using System;
using Mono.Addins;

using Hyena;
using Banshee.Base;

namespace Banshee.Configuration
{
    public static class ConfigurationClient
    {
        private static IConfigurationClient client;

        private static void Initialize ()
        {
            lock (typeof (ConfigurationClient)) {
                if (client != null) {
                    return;
                }

                if (AddinManager.IsInitialized) {
                    foreach (TypeExtensionNode node in AddinManager.GetExtensionNodes (
                        "/Banshee/Platform/ConfigurationClient")) {
                        try {
                            client = (IConfigurationClient)node.CreateInstance (typeof (IConfigurationClient));
                            if (client != null) {
                                break;
                            }
                        } catch (Exception e) {
                            Log.Warning ("Configuration client extension failed to load", e.Message);
                        }
                    }

                    if (client == null) {
                        client = new XmlConfigurationClient ();
                    }
                } else {
                    client = new MemoryConfigurationClient ();
                }

                Log.DebugFormat ("Configuration client extension loaded ({0})", client.GetType ().FullName);
            }
        }

        public static IConfigurationClient Client {
            get {
                if (client == null) {
                    Initialize ();
                }
                return client;
            }
        }

        public static T Get<T>(SchemaEntry<T> entry)
        {
            return Get<T>(entry.Namespace, entry.Key, entry.DefaultValue);
        }

        public static T Get<T>(SchemaEntry<T> entry, T fallback)
        {
            return Get<T>(entry.Namespace, entry.Key, fallback);
        }

        public static T Get<T>(string key, T fallback)
        {
            return Get<T>(null, key, fallback);
        }

        public static T Get<T>(string namespce, string key, T fallback)
        {
            T result;
            return TryGet<T> (namespce, key, out result) ? result : fallback;
        }

        public static bool TryGet<T> (string @namespace, string key, out T result)
        {
            return Client.TryGet<T> (@namespace, key, out result);
        }

        public static void Set<T> (SchemaEntry<T> entry, T value)
        {
            Set (entry.Namespace, entry.Key, value);
        }

        public static void Set<T> (string key, T value)
        {
            Set (null, key, value);
        }

        public static void Set<T> (string @namespace, string key, T value)
        {
            Client.Set<T> (@namespace, key, value);
        }
    }
}


text:
#include <PiPei.h>

#include <Guid/SystemNvDataGuid.h>
#include <Guid/FaultTolerantWrite.h>
#include <Library/PeiServicesLib.h>
#include <Library/PcdLib.h>
#include <Library/DebugLib.h>
#include <Library/BaseMemoryLib.h>
#include <Library/HobLib.h>

EFI_PEI_PPI_DESCRIPTOR     mPpiListVariable = {
  (EFI_PEI_PPI_DESCRIPTOR_PPI | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST),
  &gEdkiiFaultTolerantWriteGuid,
  NULL
};

/**
  Get the last Write Header pointer.
  The last write header is the header whose 'complete' state hasn't been set.
  After all, this header may be a EMPTY header entry for next Allocate.

  @param FtwWorkSpaceHeader Pointer of the working block header
  @param FtwWorkSpaceSize   Size of the work space
  @param FtwWriteHeader     Pointer to retrieve the last write header

  @retval  EFI_SUCCESS      Get the last write record successfully
  @retval  EFI_ABORTED      The FTW work space is damaged

**/
EFI_STATUS
FtwGetLastWriteHeader (
  IN EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER  *FtwWorkSpaceHeader,
  IN UINTN                                    FtwWorkSpaceSize,
  OUT EFI_FAULT_TOLERANT_WRITE_HEADER         **FtwWriteHeader
  )
{
  UINTN                           Offset;
  EFI_FAULT_TOLERANT_WRITE_HEADER *FtwHeader;

  *FtwWriteHeader = NULL;
  FtwHeader       = (EFI_FAULT_TOLERANT_WRITE_HEADER *) (FtwWorkSpaceHeader + 1);
  Offset          = sizeof (EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER);

  while (FtwHeader->Complete == FTW_VALID_STATE) {
    Offset += FTW_WRITE_TOTAL_SIZE (FtwHeader->NumberOfWrites, FtwHeader->PrivateDataSize);
    //
    // If Offset exceed the FTW work space boudary, return error.
    //
    if (Offset >= FtwWorkSpaceSize) {
      *FtwWriteHeader = FtwHeader;
      return EFI_ABORTED;
    }

    FtwHeader = (EFI_FAULT_TOLERANT_WRITE_HEADER *) ((UINT8 *) FtwWorkSpaceHeader + Offset);
  }
  //
  // Last write header is found
  //
  *FtwWriteHeader = FtwHeader;

  return EFI_SUCCESS;
}

/**
  Get the last Write Record pointer. The last write Record is the Record
  whose DestinationCompleted state hasn't been set. After all, this Record
  may be a EMPTY record entry for next write.

  @param FtwWriteHeader  Pointer to the write record header
  @param FtwWriteRecord  Pointer to retrieve the last write record

  @retval EFI_SUCCESS        Get the last write record successfully
  @retval EFI_ABORTED        The FTW work space is damaged

**/
EFI_STATUS
FtwGetLastWriteRecord (
  IN EFI_FAULT_TOLERANT_WRITE_HEADER          *FtwWriteHeader,
  OUT EFI_FAULT_TOLERANT_WRITE_RECORD         **FtwWriteRecord
  )
{
  UINTN                           Index;
  EFI_FAULT_TOLERANT_WRITE_RECORD *FtwRecord;

  *FtwWriteRecord = NULL;
  FtwRecord       = (EFI_FAULT_TOLERANT_WRITE_RECORD *) (FtwWriteHeader + 1);

  //
  // Try to find the last write record "that has not completed"
  //
  for (Index = 0; Index < FtwWriteHeader->NumberOfWrites; Index += 1) {
    if (FtwRecord->DestinationComplete != FTW_VALID_STATE) {
      //
      // The last write record is found
      //
      *FtwWriteRecord = FtwRecord;
      return EFI_SUCCESS;
    }

    FtwRecord++;

    if (FtwWriteHeader->PrivateDataSize != 0) {
      FtwRecord = (EFI_FAULT_TOLERANT_WRITE_RECORD *) ((UINTN) FtwRecord + (UINTN) FtwWriteHeader->PrivateDataSize);
    }
  }
  //
  //  if Index == NumberOfWrites, then
  //  the last record has been written successfully,
  //  but the Header->Complete Flag has not been set.
  //  also return the last record.
  //
  if (Index == FtwWriteHeader->NumberOfWrites) {
    *FtwWriteRecord = (EFI_FAULT_TOLERANT_WRITE_RECORD *) ((UINTN) FtwRecord - FTW_RECORD_SIZE (FtwWriteHeader->PrivateDataSize));
    return EFI_SUCCESS;
  }

  return EFI_ABORTED;
}

/**
  Check to see if it is a valid work space.

  @param WorkingHeader   Pointer of working block header
  @param WorkingLength   Working block length

  @retval TRUE          The work space is valid.
  @retval FALSE         The work space is invalid.

**/
BOOLEAN
IsValidWorkSpace (
  IN EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER    *WorkingHeader,
  IN UINTN                                      WorkingLength
  )
{
  UINT8 Data;

  if (WorkingHeader == NULL) {
    return FALSE;
  }

  if ((WorkingHeader->WorkingBlockValid != FTW_VALID_STATE) || (WorkingHeader->WorkingBlockInvalid == FTW_VALID_STATE)) {
    DEBUG ((EFI_D_ERROR, "FtwPei: Work block header valid bit check error\n"));
    return FALSE;
  }

  if (WorkingHeader->WriteQueueSize != (WorkingLength - sizeof (EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER))) {
    DEBUG ((EFI_D_ERROR, "FtwPei: Work block header WriteQueueSize check error\n"));
    return FALSE;
  }

  //
  // Check signature with gEdkiiWorkingBlockSignatureGuid
  //
  if (!CompareGuid (&gEdkiiWorkingBlockSignatureGuid, &WorkingHeader->Signature)) {
    DEBUG ((EFI_D_ERROR, "FtwPei: Work block header signature check error, it should be gEdkiiWorkingBlockSignatureGuid\n"));
    //
    // To be compatible with old signature gEfiSystemNvDataFvGuid.
    //
    if (!CompareGuid (&gEfiSystemNvDataFvGuid, &WorkingHeader->Signature)) {
      return FALSE;
    } else {
      Data = *(UINT8 *) (WorkingHeader + 1);
      if (Data != 0xff) {
        DEBUG ((EFI_D_ERROR, "FtwPei: Old format FTW structure can't be handled\n"));
        ASSERT (FALSE);
        return FALSE;
      }
    }
  }

  return TRUE;

}

/**
  Main entry for Fault Tolerant Write PEIM.

  @param[in]  FileHandle              Handle of the file being invoked.
  @param[in]  PeiServices             Pointer to PEI Services table.

  @retval EFI_SUCCESS  If the interface could be successfully installed
  @retval Others       Returned from PeiServicesInstallPpi()

**/
EFI_STATUS
EFIAPI
PeimFaultTolerantWriteInitialize (
  IN       EFI_PEI_FILE_HANDLE  FileHandle,
  IN CONST EFI_PEI_SERVICES     **PeiServices
  )
{
  EFI_STATUS                                Status;
  EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER   *FtwWorkingBlockHeader;
  EFI_FAULT_TOLERANT_WRITE_HEADER           *FtwLastWriteHeader;
  EFI_FAULT_TOLERANT_WRITE_RECORD           *FtwLastWriteRecord;
  EFI_PHYSICAL_ADDRESS                      WorkSpaceAddress;
  UINTN                                     WorkSpaceLength;
  EFI_PHYSICAL_ADDRESS                      SpareAreaAddress;
  UINTN                                     SpareAreaLength;
  EFI_PHYSICAL_ADDRESS                      WorkSpaceInSpareArea;
  FAULT_TOLERANT_WRITE_LAST_WRITE_DATA      FtwLastWrite;

  FtwWorkingBlockHeader = NULL;
  FtwLastWriteHeader = NULL;
  FtwLastWriteRecord = NULL;

  WorkSpaceAddress = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageFtwWorkingBase64);
  if (WorkSpaceAddress == 0) {
    WorkSpaceAddress = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageFtwWorkingBase);
  }
  WorkSpaceLength = (UINTN) PcdGet32 (PcdFlashNvStorageFtwWorkingSize);

  SpareAreaAddress = (EFI_PHYSICAL_ADDRESS) PcdGet64 (PcdFlashNvStorageFtwSpareBase64);
  if (SpareAreaAddress == 0) {
    SpareAreaAddress = (EFI_PHYSICAL_ADDRESS) PcdGet32 (PcdFlashNvStorageFtwSpareBase);
  }
  SpareAreaLength = (UINTN) PcdGet32 (PcdFlashNvStorageFtwSpareSize);

  //
  // The address of FTW working base and spare base must not be 0.
  //
  ASSERT ((WorkSpaceAddress != 0) && (SpareAreaAddress != 0));

  FtwWorkingBlockHeader = (EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER *) (UINTN) WorkSpaceAddress;
  if (IsValidWorkSpace (FtwWorkingBlockHeader, WorkSpaceLength)) {
    Status = FtwGetLastWriteHeader (
               FtwWorkingBlockHeader,
               WorkSpaceLength,
               &FtwLastWriteHeader
               );
    if (!EFI_ERROR (Status)) {
      Status = FtwGetLastWriteRecord (
                 FtwLastWriteHeader,
                 &FtwLastWriteRecord
                 );
    }

    if (!EFI_ERROR (Status)) {
      ASSERT (FtwLastWriteRecord != NULL);
      if ((FtwLastWriteRecord->SpareComplete == FTW_VALID_STATE) && (FtwLastWriteRecord->DestinationComplete != FTW_VALID_STATE)) {
        //
        // If FTW last write was still in progress with SpareComplete set and DestinationComplete not set.
        // It means the target buffer has been backed up in spare block, then target block has been erased,
        // but the target buffer has not been writen in target block from spare block, we need to build
        // FAULT_TOLERANT_WRITE_LAST_WRITE_DATA GUID hob to hold the FTW last write data.
        //
        FtwLastWrite.TargetAddress = (EFI_PHYSICAL_ADDRESS) (UINTN) ((INT64) SpareAreaAddress + FtwLastWriteRecord->RelativeOffset);
        FtwLastWrite.SpareAddress = SpareAreaAddress;
        FtwLastWrite.Length = SpareAreaLength;
        DEBUG ((
          EFI_D_INFO,
          "FtwPei last write data: TargetAddress - 0x%x SpareAddress - 0x%x Length - 0x%x\n",
          (UINTN) FtwLastWrite.TargetAddress,
          (UINTN) FtwLastWrite.SpareAddress,
          (UINTN) FtwLastWrite.Length));
        BuildGuidDataHob (&gEdkiiFaultTolerantWriteGuid, (VOID *) &FtwLastWrite, sizeof (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA));
      }
    }
  } else {
    FtwWorkingBlockHeader = NULL;
    //
    // If the working block workspace is not valid, try to find workspace in the spare block.
    //
    WorkSpaceInSpareArea = SpareAreaAddress + SpareAreaLength - WorkSpaceLength;
    while (WorkSpaceInSpareArea >= SpareAreaAddress) {
      if (CompareGuid (&gEdkiiWorkingBlockSignatureGuid, (EFI_GUID *) (UINTN) WorkSpaceInSpareArea)) {
        //
        // Found the workspace.
        //
        DEBUG ((EFI_D_INFO, "FtwPei: workspace in spare block is at 0x%x.\n", (UINTN) WorkSpaceInSpareArea));
        FtwWorkingBlockHeader = (EFI_FAULT_TOLERANT_WORKING_BLOCK_HEADER *) (UINTN) WorkSpaceInSpareArea;
        break;
      }
      WorkSpaceInSpareArea = WorkSpaceInSpareArea - sizeof (EFI_GUID);
    }
    if ((FtwWorkingBlockHeader != NULL) && IsValidWorkSpace (FtwWorkingBlockHeader, WorkSpaceLength)) {
      //
      // It was workspace self reclaim, build FAULT_TOLERANT_WRITE_LAST_WRITE_DATA GUID hob for it.
      //
      FtwLastWrite.TargetAddress = WorkSpaceAddress - (WorkSpaceInSpareArea - SpareAreaAddress);
      FtwLastWrite.SpareAddress = SpareAreaAddress;
      FtwLastWrite.Length = SpareAreaLength;
      DEBUG ((
        EFI_D_INFO,
        "FtwPei last write data: TargetAddress - 0x%x SpareAddress - 0x%x Length - 0x%x\n",
        (UINTN) FtwLastWrite.TargetAddress,
        (UINTN) FtwLastWrite.SpareAddress,
        (UINTN) FtwLastWrite.Length));
      BuildGuidDataHob (&gEdkiiFaultTolerantWriteGuid, (VOID *) &FtwLastWrite, sizeof (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA));
    } else {
      //
      // Both are invalid.
      //
      DEBUG ((EFI_D_ERROR, "FtwPei: Both working and spare block are invalid.\n"));
    }
  }

  //
  // Install gEdkiiFaultTolerantWriteGuid PPI to inform the check for FTW last write data has been done.
  //
  return PeiServicesInstallPpi (&mPpiListVariable);
}


text:
package com.netease.nim.uikit.recent;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;

import com.netease.nim.uikit.NimUIKit;
import com.netease.nim.uikit.cache.NimUserInfoCache;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.MemberPushOption;
import com.netease.nimlib.sdk.msg.model.RecentContact;
import com.netease.nimlib.sdk.team.model.TeamMember;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hzchenkang on 2016/12/5.
 */

public class AitHelper {

    private static final String KEY_AIT = "ait";

    public static String getAitAlertString(String content) {
        return "[有人@你] " + content;
    }

    public static void replaceAitForeground(String value, SpannableString mSpannableString) {
        if (TextUtils.isEmpty(value) || TextUtils.isEmpty(mSpannableString)) {
            return;
        }
        Pattern pattern = Pattern.compile("(\\[有人@你\\])");
        Matcher matcher = pattern.matcher(value);
        while (matcher.find()) {
            int start = matcher.start();
            if (start != 0) {
                continue;
            }
            int end = matcher.end();
            mSpannableString.setSpan(new ForegroundColorSpan(Color.RED), start, end, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
        }
    }

    public static boolean isAitMessage(IMMessage message) {
        if (message == null || message.getSessionType() != SessionTypeEnum.Team) {
            return false;
        }
        MemberPushOption option = message.getMemberPushOption();
        boolean isForce = option != null && option.isForcePush() &&
                (option.getForcePushList() == null || option.getForcePushList().contains(NimUIKit.getAccount()));

        return isForce;
    }

    private static boolean isContentAit(String content) {
        if (TextUtils.isEmpty(content)) {
            return false;
        }
        Pattern pattern = Pattern.compile("(@" + NimUIKit.getAccount() + " )");
        Matcher matcher = pattern.matcher(content);
        return matcher.find();
    }

    public static boolean hasAitExtention(RecentContact recentContact) {
        if (recentContact == null || recentContact.getSessionType() != SessionTypeEnum.Team) {
            return false;
        }
        Map<String, Object> ext = recentContact.getExtension();
        if (ext == null) {
            return false;
        }
        List<String> mid = (List<String>) ext.get(KEY_AIT);

        return mid != null && !mid.isEmpty();
    }

    public static void clearRecentContactAited(RecentContact recentContact) {
        if (recentContact == null || recentContact.getSessionType() != SessionTypeEnum.Team) {
            return;
        }
        Map<String, Object> exts = recentContact.getExtension();
        if (exts != null) {
            exts.put(KEY_AIT, null);
        }
        recentContact.setExtension(exts);
        NIMClient.getService(MsgService.class).updateRecent(recentContact);
    }

    public static void buildAitExtentionByMessage(Map<String, Object> extention, IMMessage message) {

        if (extention == null || message == null || message.getSessionType() != SessionTypeEnum.Team) {
            return;
        }
        List<String> mid = (List<String>) extention.get(KEY_AIT);
        if (mid == null) {
            mid = new ArrayList<>();
        }
        if (!mid.contains(message.getUuid())) {
            mid.add(message.getUuid());
        }
        extention.put(KEY_AIT, mid);
    }

    public static void setRecentContactAited(RecentContact recentContact, Set<IMMessage> messages) {

        if (recentContact == null || messages == null ||
                recentContact.getSessionType() != SessionTypeEnum.Team) {
            return;
        }

        Map<String, Object> extention = recentContact.getExtension();

        if (extention == null) {
            extention = new HashMap<>();
        }

        Iterator<IMMessage> iterator = messages.iterator();
        while (iterator.hasNext()) {
            IMMessage msg = iterator.next();
            buildAitExtentionByMessage(extention, msg);
        }

        recentContact.setExtension(extention);
        NIMClient.getService(MsgService.class).updateRecent(recentContact);
    }

    public static ImageSpan getInputAitSpan(String name, float textsize) {
        if (TextUtils.isEmpty(name)) {
            return null;
        }
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        paint.setAntiAlias(true);
        paint.setTextSize(textsize);
        Rect rect = new Rect();

        paint.getTextBounds(name, 0, name.length(), rect);

        // 获取字符串在屏幕上的长度
        int width = (int) (paint.measureText(name));

        final Bitmap bmp = Bitmap.createBitmap(width, rect.height(),
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);

        canvas.drawText(name, rect.left, rect.height() - rect.bottom, paint);

        return new ImageSpan(NimUIKit.getContext(), bmp, ImageSpan.ALIGN_BOTTOM);
    }

    // 群昵称 > 用户昵称 > 账号
    public static String getAitName(TeamMember member) {

        if (member == null) {
            return "";
        }
        String memberNick = member.getTeamNick();
        if (!TextUtils.isEmpty(memberNick)) {
            return memberNick;
        }

        return NimUserInfoCache.getInstance().getUserName(member.getAccount());

    }
}


text:
SingleWordReader
================

Inspired by spritzinc, I built a little python program that takes a txt file and turns it into single words at high speeds


text:
<!DOCTYPE HTML>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Werkzeug Documentation</title>
    <link rel="stylesheet" href="_static/style.css" type="text/css">
    <link rel="stylesheet" href="_static/print.css" type="text/css" media="print">
    <link rel="stylesheet" href="_static/pygments.css" type="text/css">

    <link rel="contents" title="Global table of contents" href="contents.html">
    <link rel="index" title="Global index" href="genindex.html">
    <link rel="search" title="Search" href="search.html">
    <link rel="top" title="Werkzeug v0.6.1 documentation" href="#">
    <link rel="next" title="Installation" href="installation.html">

Werkzeug

Documentation Overview

Installation »

Table Of Contents

Documentation Overview

Getting Started

Serving and Testing

Reference

Deployment

Contributed Modules

Additional Information

Documentation Overview¶

Welcome to the Werkzeug 0.6.1 documentation.  You can find different
editions of the documentation online.

Getting Started¶

If you are new to Werkzeug or WSGI development in general you
should start here.

Installation

Installing a released version

Installing the development version

Werkzeug Tutorial

Part 0: The Folder Structure

Part 1: The WSGI Application

Part 2: The Utilities

Intermission: And Now For Something Completely Different

Part 3: Database Models

Part 4: The View Functions

Part 5: The Templates

Intermission: Adding The Design

Part 6: Listing Public URLs

The End Result

Bonus: Styling 404 Error Pages

Outro

API Levels

Example

High or Low?

Quickstart

WSGI Environment

Enter Request

Header Parsing

Responses

Serving and Testing¶

The development server and testing support and management script
utilities are covered here:

Serving WSGI Applications

Virtual Hosts

Troubleshooting

SSL

Test Utilities

Diving In

Environment Building

Testing API

Debugging Applications

Enabling the Debugger

Using the Debugger

Pasting Errors

Management Script Utilities

Basic Usage

Using The Scripts

Writing Actions

Action Discovery

Reference

Example Scripts

Reference¶

Request / Response Objects

How they Work

Mutability and Reusability of Wrappers

Base Wrappers

Mixin Classes

URL Routing

Quickstart

Rule Format

Builtin Converters

Maps, Rules and Adapters

Rule Factories

Rule Templates

Custom Converters

WSGI Helpers

Iterator / Stream Helpers

Environ Helpers

Convenience Helpers

HTTP Utilties

Date Functions

Form Data Parsing

Header Parsing

Header Utilities

Conditional Response Helpers

Constants

Data Structures

General Purpose

HTTP Related

Others

Utilities

URL Helpers

HTML Helpers

General Helpers

Security Helpers

Mini Templates

Syntax Elements

Missing Variables

The Template Class

Context Locals

Middlewares

HTTP Exceptions

Usage Example

Error Classes

Baseclass

Special HTTP Exceptions

Simple Aborting

Custom Errors

Deployment¶

This section covers running your application in production on a web
server such as Apache or lighttpd.

Application Deployment

CGI

Creating a .cgi file

Server Setup

mod_wsgi (Apache)

Installing mod_wsgi

Creating a .wsgi file

Configuring Apache

FastCGI

Creating a .fcgi file

Configuring lighttpd

Configuring nginx

Debugging

HTTP Proxying

Creating a .py server

Configuring nginx

Contributed Modules¶

A lot of useful code contributed by the community is shipped with Werkzeug
as part of the contrib module:

Contributed Modules

Atom Syndication

Sessions

Application Integration

Reference

Secure Cookie

Application Integration

Reference

Cache

How Caching Works

Creating a Cache Object

Cache System API

Cache Systems

Extra Wrappers

Iter IO

Fixers

WSGI Application Profiler

Lint Validation Middleware

Additional Information¶

Important Terms

WSGI

Response Object

View Function

Unicode

Unicode in Python

Unicode in HTTP

Error Handling

Request and Response Objects

Dealing with Request Data

Missing EOF Marker on Input Stream

When does Werkzeug Parse?

How does it Parse?

Limiting Request Data

How to extend Parsing?

Werkzeug Changelog

Werkzeug Changelog

API Changes

If you can't find the information you're looking for, have a look at the
index or try to find it using the search function:

Index

Search Page

        © Copyright 2008 by the Pocoo Team,
        documentation generated by Sphinx


text:
package org.wallride.autoconfigure;

import com.amazonaws.util.EC2MetadataUtils;
import jp.co.tagbangers.jgroups.S3_CLIENT_PING;
import org.infinispan.configuration.cache.CacheMode;
import org.infinispan.configuration.cache.ConfigurationBuilder;
import org.infinispan.configuration.global.GlobalConfigurationBuilder;
import org.infinispan.configuration.parsing.ConfigurationBuilderHolder;
import org.infinispan.configuration.parsing.ParserRegistry;
import org.infinispan.eviction.EvictionStrategy;
import org.infinispan.eviction.EvictionType;
import org.infinispan.hibernate.search.impl.DefaultCacheManagerService;
import org.infinispan.lucene.LuceneKey2StringMapper;
import org.infinispan.manager.DefaultCacheManager;
import org.infinispan.manager.EmbeddedCacheManager;
import org.infinispan.persistence.jdbc.configuration.JdbcStringBasedStoreConfigurationBuilder;
import org.infinispan.spring.provider.SpringEmbeddedCacheManager;
import org.jgroups.conf.ClassConfigurator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;
import java.io.IOException;

@Configuration
@EnableCaching
public class WallRideCacheConfiguration extends CachingConfigurerSupport {

	public static final String BLOG_CACHE = "blogs";
	public static final String POPULAR_POST_CACHE = "popularPosts";
	public static final String ARTICLE_CACHE = "articles";
	public static final String PAGE_CACHE = "pages";
	public static final String CATEGORY_CACHE = "categories";
	public static final String CUSTOM_FIELD_CACHE = "customFields";
	public static final String MEDIA_CACHE = "medias";
	public static final String BANNER_CACHE = "banners";
	public static final String USER_CACHE = "users";

	@Autowired
	private DataSource dataSource;

	@Autowired
	private Environment environment;

	@Autowired
	private DataSourceProperties dataSourceProperties;

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

	@Bean
	@Override
	public CacheManager cacheManager() {
		// JGroups settings
		String jgroupsConfigurationFile = environment.getRequiredProperty("jgroups.configurationFile");
		if ("jgroups-ec2.xml".equals(jgroupsConfigurationFile)) {
			ClassConfigurator.addProtocol((short) 1000, S3_CLIENT_PING.class);
			String ipAddress = EC2MetadataUtils.getPrivateIpAddress();
			logger.info("jgroups.tcp.address -> {}", ipAddress);
			System.setProperty("jgroups.tcp.address", ipAddress);
			System.setProperty("jgroups.s3.bucket", environment.getRequiredProperty("jgroups.s3.bucket"));
		}

		Resource hibernateSearchConfig = new ClassPathResource(DefaultCacheManagerService.DEFAULT_INFINISPAN_CONFIGURATION_RESOURCENAME);
		ParserRegistry parserRegistry = new ParserRegistry();
		ConfigurationBuilderHolder holder;
		try {
			holder = parserRegistry.parse(hibernateSearchConfig.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}

		// GlobalConfiguration
		// @formatter:off
		GlobalConfigurationBuilder globalBuilder = holder.getGlobalConfigurationBuilder();
		globalBuilder
			.globalJmxStatistics()
				.allowDuplicateDomains(true)
			.transport()
				.defaultTransport()
					.addProperty("configurationFile", jgroupsConfigurationFile);
		// @formatter:on

		// DefaultConfiguration
		// @formatter:off
		for (ConfigurationBuilder luceneIndexesBuilder : holder.getNamedConfigurationBuilders().values()) {
			if ("mysql".equals(dataSourceProperties.getPlatform())) {
				luceneIndexesBuilder
					.persistence()
						.addStore(JdbcStringBasedStoreConfigurationBuilder.class)
							.preload(true)
							.shared(true)
							.key2StringMapper(LuceneKey2StringMapper.class)
								.table()
								.tableNamePrefix("ispn_string_table")
								.idColumnName("id_column")
								.idColumnType("varchar(255)")
								.dataColumnName("data_column")
								.dataColumnType("longblob")
								.timestampColumnName("timestamp_column")
								.timestampColumnType("bigint")
								.dropOnExit(false)
								.createOnStart(true)
							.async()
								.enable()
								.threadPoolSize(10)
							.fetchPersistentState(true)
							.ignoreModifications(false)
							.purgeOnStartup(false)
							.connectionFactory(InfinispanDataSourceConnectionFactoryConfigurationBuilder.class).dataSource(dataSource);
			} else if ("postgresql".equals(dataSourceProperties.getPlatform())) {
				luceneIndexesBuilder
					.persistence()
						.addStore(JdbcStringBasedStoreConfigurationBuilder.class)
							.preload(true)
							.shared(true)
							.key2StringMapper(LuceneKey2StringMapper.class)
								.table()
								.tableNamePrefix("ispn_string_table")
								.idColumnName("id_column")
								.idColumnType("varchar(255)")
								.dataColumnName("data_column")
								.dataColumnType("bytea")
								.timestampColumnName("timestamp_column")
								.timestampColumnType("bigint")
								.dropOnExit(false)
								.createOnStart(true)
							.async()
								.enable()
								.threadPoolSize(10)
							.fetchPersistentState(true)
							.ignoreModifications(false)
							.purgeOnStartup(false)
							.connectionFactory(InfinispanDataSourceConnectionFactoryConfigurationBuilder.class).dataSource(dataSource);
			} else {
				throw new IllegalStateException();
			}
		}
		// @formatter:on

		// @formatter:off
		ConfigurationBuilder cacheBuilder = new ConfigurationBuilder();
		cacheBuilder
			.clustering()
				.cacheMode(CacheMode.REPL_SYNC)
				.eviction()
					.type(EvictionType.COUNT)
					.strategy(EvictionStrategy.LIRS)
					.size(1000);
//				.indexing()
//					.index(Index.NONE);
		// @formatter:on

		holder.getNamedConfigurationBuilders().put(BLOG_CACHE, cacheBuilder);
//		holder.getNamedConfigurationBuilders().put("settings", cacheBuilder);
		holder.getNamedConfigurationBuilders().put(POPULAR_POST_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(ARTICLE_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(PAGE_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(CATEGORY_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(CUSTOM_FIELD_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(MEDIA_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(BANNER_CACHE, cacheBuilder);
		holder.getNamedConfigurationBuilders().put(USER_CACHE, cacheBuilder);

		EmbeddedCacheManager embeddedCacheManager = new DefaultCacheManager(holder, true);
		InfinispanSingletonCacheManagerDirectoryProvider.cacheManager = embeddedCacheManager;
		return new SpringEmbeddedCacheManager(embeddedCacheManager);
	}

	@Bean
	@Override
	public KeyGenerator keyGenerator() {
		return new CacheKeyGenerator();
	}
}


text:
echo $env:USERNAME
$wc = New-Object System.Net.WebClient
$certificatePath = "C:\mytemp\medic-bootstrap\CordovaApp.Store_0.0.2.0_AnyCPU_Debug.cer"

#Installing nodejs; Chocolatey cannot install it successfully under SYSTEM account
# so we have to do it explicitly
$source = "http://nodejs.org/dist/v0.10.29/node-v0.10.29-x86.msi"
$destination = $($env:TEMP + "\node-v0.10.29-x86.msi")
$wc.DownloadFile($source, $destination)

msiexec /qn /norestart /l* $($env:TEMP + "\node_inst.log") /i $destination ALLUSERS=1
$env:Path+=";C:\Program Files (x86)\nodejs"

#Python section
choco install python2

#Setup Tools section
Write-Host "Installing pip ..."
cinst pip
$env:Path+=";C:\tools\python2\Scripts"

Write-Host "Updating Python PATH ..."
$oldPath=(Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" -Name PATH).Path
$newPath=$oldPath+";C:\tools\python2;C:\tools\python2\Scripts"
#Next line will fail w/o Administrator privileges
Set-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" -Name PATH –Value $newPath
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\tools\python2;C:\tools\python2\Scripts", "Machine")

cinst PyWin32

#Buildbot prepare and install section
Write-Host "Installing buildslave and dependencies ..."
pip install buildbot-slave
Write-Host ""

#SDKs and VS install section

if($args[0] -eq "windows81") {
    #choco install VisualStudioExpress2013Windows
    #choco install VS2013.2

    choco install jdk8

    choco install ant

    choco install android-sdk
    Write-Host "Updating Android SDK PATH ..."
    $oldPath=(Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" -Name PATH).Path
    $newPath=$oldPath+";C:\Users\"+[Environment]::UserName+"\AppData\Local\Android\android-sdk\tools"
    #Next line will fail w/o Administrator privileges
    Set-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" -Name PATH –Value $newPath

    certutil.exe -addstore TrustedPeople $certificatePath
} else {
    if($args[0] -eq "windows80") {
        choco install VisualStudioExpress2012Windows8
        choco install VisualStudioExpress2012WindowsPhone
    }
}

#Grunt-cli install section
Write-Host "Installing Grunt-cli and dependencies ..."
npm install -g grunt-cli
$oldPath=(Get-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" -Name PATH).Path
$newPath=$oldPath+";C:\Users\"+[Environment]::UserName+"\AppData\Roaming\npm"
#Next line will fail w/o Administrator privileges
Set-ItemProperty -Path "Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment" -Name PATH –Value $newPath
Write-Host ""
$env:Path += ";C:\Users\"+[Environment]::UserName+"\AppData\Roaming\npm"

Install-WindowsFeature Desktop-Experience

$runValue = $("powershell -ExecutionPolicy Unrestricted C:\mytemp\medic-bootstrap\final.ps1 " + $args[0])
New-ItemProperty -Path registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce -Name Installer -Value $runValue

# Disable hyperprotective IE policy to make Developer License Registration window available
Set-ItemProperty -Path "registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}" -Name IsInstalled -Value 0

shutdown /r

Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")


text:
> Layout styles

## Installation

```shell
$ npm install @cyclic/atom-layout
```

## License

MIT © [Cyclic Materials](http://github.com/CyclicMaterials)


text:
<?xml version="1.0" encoding="UTF-8"?>
<gfc:FC_FeatureCatalogue xmlns:gfc="http://www.isotc211.org/2005/gfc" xmlns:gco="http://www.isotc211.org/2005/gco" xmlns:gmd="http://www.isotc211.org/2005/gmd" xmlns:geonet="http://www.fao.org/geonetwork" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" uuid="2f9f2420-4faa-432e-8931-685681493035" xsi:schemaLocation="http://www.isotc211.org/2005/gfc http://www.isotc211.org/2005/gfc/gfc.xsd">
  <gmx:name xmlns:gmx="http://www.isotc211.org/2005/gmx">
    <gco:CharacterString>Localisation des toilettes publiques sur la ville de Rennes (diffusion) - Dictionnaire des attributs</gco:CharacterString>
  </gmx:name>
  <gfc:producer>
    <gmd:CI_ResponsibleParty>
      <gmd:organisationName>
        <gco:CharacterString>Rennes Métropole - DRPF</gco:CharacterString>
      </gmd:organisationName>
      <gmd:contactInfo>
        <gmd:CI_Contact>
          <gmd:address>
            <gmd:CI_Address>
              <gmd:electronicMailAddress>
                <gco:CharacterString>drpf@ville-rennes.fr</gco:CharacterString>
              </gmd:electronicMailAddress>
            </gmd:CI_Address>
          </gmd:address>
        </gmd:CI_Contact>
      </gmd:contactInfo>
      <gmd:role>
        <gmd:CI_RoleCode codeListValue="pointOfContact" codeList="CI_RoleCode" />
      </gmd:role>
    </gmd:CI_ResponsibleParty>
  </gfc:producer>
  <gfc:featureType>
    <gfc:FC_FeatureType>
      <gfc:typeName>
        <gco:LocalName>Table attributaire</gco:LocalName>
      </gfc:typeName>
      <gfc:definition>
        <gco:CharacterString>Description de la table attributaire</gco:CharacterString>
      </gfc:definition>
      <gfc:isAbstract>
        <gco:Boolean>false</gco:Boolean>
      </gfc:isAbstract>
      <gfc:featureCatalogue />
      <gfc:carrierOfCharacteristics>
        <gfc:FC_FeatureAttribute>
          <gfc:memberName>
            <gco:LocalName>nom</gco:LocalName>
          </gfc:memberName>
          <gfc:definition>
            <gco:CharacterString>nom d'usage donnée au site / aux locaux</gco:CharacterString>
          </gfc:definition>
          <gfc:cardinality>
            <gco:Multiplicity>
              <gco:range>
                <gco:MultiplicityRange>
                  <gco:lower>
                    <gco:Integer>1</gco:Integer>
                  </gco:lower>
                  <gco:upper>
                    <gco:UnlimitedInteger isInfinite="true" xsi:nil="true" />
                  </gco:upper>
                </gco:MultiplicityRange>
              </gco:range>
            </gco:Multiplicity>
          </gfc:cardinality>
          <gfc:valueType>
            <gco:TypeName>
              <gco:aName>
                <gco:CharacterString>VARCHAR</gco:CharacterString>
              </gco:aName>
            </gco:TypeName>
          </gfc:valueType>
        </gfc:FC_FeatureAttribute>
      </gfc:carrierOfCharacteristics>
      <gfc:carrierOfCharacteristics>
        <gfc:FC_FeatureAttribute>
          <gfc:memberName>
            <gco:LocalName>lieu</gco:LocalName>
          </gfc:memberName>
          <gfc:definition>
            <gco:CharacterString>indication sur l'adresse ou la localisation des toilettes[définition]</gco:CharacterString>
          </gfc:definition>
          <gfc:cardinality>
            <gco:Multiplicity>
              <gco:range>
                <gco:MultiplicityRange>
                  <gco:lower>
                    <gco:Integer>1</gco:Integer>
                  </gco:lower>
                  <gco:upper>
                    <gco:UnlimitedInteger isInfinite="true" xsi:nil="true" />
                  </gco:upper>
                </gco:MultiplicityRange>
              </gco:range>
            </gco:Multiplicity>
          </gfc:cardinality>
          <gfc:valueType>
            <gco:TypeName>
              <gco:aName>
                <gco:CharacterString>VARCHAR</gco:CharacterString>
              </gco:aName>
            </gco:TypeName>
          </gfc:valueType>
        </gfc:FC_FeatureAttribute>
      </gfc:carrierOfCharacteristics>
      <gfc:carrierOfCharacteristics>
        <gfc:FC_FeatureAttribute>
          <gfc:featureType>
            <gfc:FC_FeatureType>
              <gfc:typeName>
                <gco:LocalName />
              </gfc:typeName>
              <gfc:isAbstract>
                <gco:Boolean />
              </gfc:isAbstract>
              <gfc:featureCatalogue />
            </gfc:FC_FeatureType>
          </gfc:featureType>
          <gfc:featureType>
            <gfc:FC_FeatureType>
              <gfc:typeName>
                <gco:LocalName />
              </gfc:typeName>
              <gfc:isAbstract>
                <gco:Boolean />
              </gfc:isAbstract>
              <gfc:featureCatalogue />
            </gfc:FC_FeatureType>
          </gfc:featureType>
          <gfc:memberName>
            <gco:LocalName>horaires</gco:LocalName>
          </gfc:memberName>
          <gfc:definition>
            <gco:CharacterString>horaires d'ouverture</gco:CharacterString>
          </gfc:definition>
          <gfc:cardinality>
            <gco:Multiplicity>
              <gco:range>
                <gco:MultiplicityRange>
                  <gco:lower>
                    <gco:Integer>0</gco:Integer>
                  </gco:lower>
                  <gco:upper>
                    <gco:UnlimitedInteger isInfinite="true" xsi:nil="true" />
                  </gco:upper>
                </gco:MultiplicityRange>
              </gco:range>
            </gco:Multiplicity>
          </gfc:cardinality>
          <gfc:valueType>
            <gco:TypeName>
              <gco:aName>
                <gco:CharacterString>VARCHAR</gco:CharacterString>
              </gco:aName>
            </gco:TypeName>
          </gfc:valueType>
        </gfc:FC_FeatureAttribute>
      </gfc:carrierOfCharacteristics>
      <gfc:carrierOfCharacteristics>
        <gfc:FC_FeatureAttribute>
          <gfc:memberName>
            <gco:LocalName>pmr</gco:LocalName>
          </gfc:memberName>
          <gfc:definition>
            <gco:CharacterString>indique si les toilettes sont accessibles aux personnes à mobilité</gco:CharacterString>
          </gfc:definition>
          <gfc:cardinality>
            <gco:Multiplicity>
              <gco:range>
                <gco:MultiplicityRange>
                  <gco:lower>
                    <gco:Integer>0</gco:Integer>
                  </gco:lower>
                  <gco:upper>
                    <gco:UnlimitedInteger isInfinite="true" xsi:nil="true" />
                  </gco:upper>
                </gco:MultiplicityRange>
              </gco:range>
            </gco:Multiplicity>
          </gfc:cardinality>
          <gfc:valueType>
            <gco:TypeName>
              <gco:aName>
                <gco:CharacterString>VARCHAR</gco:CharacterString>
              </gco:aName>
            </gco:TypeName>
          </gfc:valueType>
        </gfc:FC_FeatureAttribute>
      </gfc:carrierOfCharacteristics>
    </gfc:FC_FeatureType>
  </gfc:featureType>
</gfc:FC_FeatureCatalogue>


text:
' Copyright (c) 2015 ZZZ Projects. All rights reserved
' Licensed under MIT License (MIT) (https://github.com/zzzprojects/Z.ExtensionMethods)
' Website: http://www.zzzprojects.com/
' Feedback / Feature Requests / Issues : http://zzzprojects.uservoice.com/forums/283927
' All ZZZ Projects products: Entity Framework Extensions / Bulk Operations / Extension Methods /Icon Library

Public Module Extensions_341

	''' <summary>
	'''     An object extension method that query if '@this' is valid System.DateTime.
	''' </summary>
	''' <param name="this">The @this to act on.</param>
	''' <returns>true if valid System.DateTime, false if not.</returns>
	<System.Runtime.CompilerServices.Extension> _
	Public Function IsValidDateTime(this As Object) As Boolean
		If this Is Nothing Then
			Return True
		End If

		Dim result As DateTime
		Return DateTime.TryParse(this.ToString(), result)
	End Function
End Module


text:
import DS from 'ember-data';

var User = DS.Model.extend({
  userName: DS.attr('string'),
  isEditing: DS.attr('boolean', {defaultValue: false}),
  isRemoved: DS.attr('boolean', {defaultValue: false}),
  rev: DS.attr('string')
});

export default User;


text:
'use strict'
var validate = require('aproba')
var npa = require('npm-package-arg')
var npm = require('../npm.js')
var flattenTree = require('./flatten-tree.js')

function nonRegistrySource (pkg) {
  validate('O', arguments)
  var requested = pkg._requested || (pkg._from && npa(pkg._from))
  if (!requested) return false

  if (requested.type === 'hosted') return true
  if (requested.type === 'local') return true
  return false
}

function pkgAreEquiv (aa, bb) {
  var aaSha = (aa.dist && aa.dist.shasum) || aa._shasum
  var bbSha = (bb.dist && bb.dist.shasum) || bb._shasum
  if (aaSha === bbSha) return true
  if (aaSha || bbSha) return false
  if (nonRegistrySource(aa) || nonRegistrySource(bb)) return false
  if (aa.version === bb.version) return true
  return false
}

function getNameAndVersion (pkg) {
  var versionspec = pkg._shasum

  if (!versionspec && nonRegistrySource(pkg)) {
    if (pkg._requested) {
      versionspec = pkg._requested.spec
    } else if (pkg._from) {
      versionspec = npa(pkg._from).spec
    }
  }
  if (!versionspec) {
    versionspec = pkg.version
  }
  return pkg.name + '@' + versionspec
}

function pushAll (aa, bb) {
  Array.prototype.push.apply(aa, bb)
}

module.exports = function (oldTree, newTree, differences, log, next) {
  validate('OOAOF', arguments)
  pushAll(differences, sortActions(diffTrees(oldTree, newTree)))
  log.finish()
  next()
}

function isLink (node) {
  return node && node.isLink
}

function requiredByAllLinked (node) {
  if (!node.requiredBy.length) return false
  return node.requiredBy.filter(isLink).length === node.requiredBy.length
}

function isNotReqByTop (req) {
  return req !== '/' &&     // '/' is the top level itself
         req !== '#USER' && // #USER
         req !== '#EXTRANEOUS'
}

var sortActions = module.exports.sortActions = function (differences) {
  var actions = {}
  differences.forEach(function (action) {
    var child = action[1]
    actions[child.package._location] = action
  })

  var sorted = []
  var added = {}

  var sortedlocs = Object.keys(actions).sort(sortByLocation)

  // Do top level deps first, this stops the sorting by required order from
  // unsorting these deps.
  var toplocs = sortedlocs.filter(function (location) {
    var mod = actions[location][1]
    if (!mod.package._requiredBy) return true
    // If the module is required by ANY non-top level package
    // then we don't want to include this.
    return !mod.package._requiredBy.some(isNotReqByTop)
  })

  toplocs.concat(sortedlocs).forEach(function (location) {
    sortByDeps(actions[location])
  })

  function sortByLocation (aa, bb) {
    return bb.localeCompare(aa)
  }
  function sortByDeps (action) {
    var mod = action[1]
    if (added[mod.package._location]) return
    added[mod.package._location] = action
    mod.package._requiredBy.sort().forEach(function (location) {
      if (actions[location]) sortByDeps(actions[location])
    })
    sorted.unshift(action)
  }

  return sorted
}

function diffTrees (oldTree, newTree) {
  validate('OO', arguments)
  var differences = []
  var flatOldTree = flattenTree(oldTree)
  var flatNewTree = flattenTree(newTree)
  var toRemove = {}
  var toRemoveByNameAndVer = {}
  // find differences
  Object.keys(flatOldTree).forEach(function (flatname) {
    if (flatNewTree[flatname]) return
    var pkg = flatOldTree[flatname]
    toRemove[flatname] = pkg
    var namever = getNameAndVersion(pkg.package)
    if (!toRemoveByNameAndVer[namever]) toRemoveByNameAndVer[namever] = []
    toRemoveByNameAndVer[namever].push(flatname)
  })
  Object.keys(flatNewTree).forEach(function (path) {
    var pkg = flatNewTree[path]
    pkg.oldPkg = flatOldTree[path]
    pkg.isInLink = (pkg.oldPkg && isLink(pkg.oldPkg.parent)) ||
                   (pkg.parent && isLink(pkg.parent)) ||
                   requiredByAllLinked(pkg)
    if (pkg.fromBundle) {
      if (npm.config.get('rebuild-bundle')) differences.push(['rebuild', pkg])
      if (pkg.oldPkg) differences.push(['remove', pkg])
    } else if (pkg.oldPkg) {
      if (!pkg.directlyRequested && pkgAreEquiv(pkg.oldPkg.package, pkg.package)) return
      if (!pkg.isInLink && (isLink(pkg.oldPkg) || isLink(pkg))) {
        differences.push(['update-linked', pkg])
      } else {
        differences.push(['update', pkg])
      }
    } else {
      var vername = getNameAndVersion(pkg.package)
      if (toRemoveByNameAndVer[vername] && toRemoveByNameAndVer[vername].length) {
        var flatname = toRemoveByNameAndVer[vername].shift()
        pkg.fromPath = toRemove[flatname].path
        differences.push(['move', pkg])
        delete toRemove[flatname]
      } else {
        differences.push(['add', pkg])
      }
    }
  })
  Object
    .keys(toRemove)
    .map(function (path) { return toRemove[path] })
    .forEach(function (pkg) {
      differences.push(['remove', pkg])
    })
  return differences
}


text:
require_relative "../../../../../../base"
require_relative "../shared/pip_ansible_install_examples"

require Vagrant.source_root.join("plugins/provisioners/ansible/cap/guest/debian/ansible_install")

describe VagrantPlugins::Ansible::Cap::Guest::Debian::AnsibleInstall do
  include_context "unit"

  subject { VagrantPlugins::Ansible::Cap::Guest::Debian::AnsibleInstall }

  let(:iso_env) do
    # We have to create a Vagrantfile so there is a root path
    env = isolated_environment
    env.vagrantfile("")
    env.create_vagrant_env
  end

  let(:machine) { iso_env.machine(iso_env.machine_names[0], :dummy) }
  let(:communicator) { double("comm") }

  before do
    allow(machine).to receive(:communicate).and_return(communicator)
    allow(communicator).to receive(:execute).and_return(true)
  end

  describe "#ansible_install" do

    it_behaves_like "Ansible setup via pip on Debian-based systems"

    describe "when install_mode is :default (or unknown)" do
      it "installs ansible with apt package manager" do
        install_backports_if_wheezy_release = <<INLINE_CRIPT
CODENAME=`lsb_release -cs`
if [ x$CODENAME == 'xwheezy' ]; then
  echo 'deb http://http.debian.net/debian wheezy-backports main' > /etc/apt/sources.list.d/wheezy-backports.list
fi
INLINE_CRIPT

        expect(communicator).to receive(:sudo).once.ordered.with(install_backports_if_wheezy_release)
        expect(communicator).to receive(:sudo).once.ordered.with("apt-get update -y -qq")
        expect(communicator).to receive(:sudo).once.ordered.with("DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --option \"Dpkg::Options::=--force-confold\" ansible")

        subject.ansible_install(machine, :default, "", "", "")
      end
    end
  end

end


text:
title:  Za globlje proučevanje
date:   01/11/2019
---

Preberi v knjigi Preroki in kralji poglavje »Graja zoper oderuštvo«, str. 387.

»Ko je Nehemija slišal za to okrutno odiranje, se je njegovo srce napolnilo ogorčenja. Piše: ›Ko sem slišal njihovo vpitje in take besede, sem se silno razsrdil.‹ (Neh 5,6) Dojel je, da se mora odločno potegniti za pravico, če želi prekiniti zatiralsko oderuško navado. Z njemu značilno vnemo in odločnostjo je ukrepal za olajšanje svojim bratom.« /Ellen G. White, Preroki in kralji, str. 388/

»Jezus je naprej razlagal načelo, po katerem prisega postane nepotrebna. Uči, da je natančna resnica zakon govorjenja. ›Vaš govor naj bo 'da', 'da', 'ne', 'ne'; kar je več kot to, je od hudega.‹ (Mt 5,37)

Te besede obsojajo vse tiste besedne zveze brez pomena in puhlice, ki mejijo na nespodobno govorjenje. Obsojajo neresnične pohvale, izogibanje resnici, laskave besedne zveze, pretiravanja, lažno predstavljanje pri trgovanju, ki se jih danes poslužujejo v družbi in poslovnem svetu. Učijo, da ni resnicoljuben, kdor koli si prizadeva pustiti vtis, da je tisto, kar ni, ali katerega besede ne izražajo njegovih dejanskih občutkov.« /Ellen G. White, Thoughts From the Mount of Blessing, str. 67-68/

**Vprašanja za pogovor**

`1. 	Zakaj je sebičnost bistvo človeških težav, kadar gre za finance in medosebne odnose?`

`2. 	Kako se lahko Božje ljudstvo ogne pohlepu? Kaj je Bog naredil proti temu? Prouči naslednja besedila: Iz 58,3-12; Mih 6,6-8.`

`3. 	Globlje razmisli o daru govora in moči naših besed. Kaj naj bi pomenilo besedilo v Jn 1,1-2, ko Jezusa imenuje »Beseda«? Kako to pomaga razumeti pomembnost besed in kaj je njihov pomen?`

`4. 	Osupljivo je, da je Jezus pred tisočimi leti rekel, da bodo ubogi vedno med nami. Spodbujeni smo tudi pomagati ljudem v potrebi. Kako ti zamisli spadata skupaj v spodbujanju kristjanov, da delajo za manj srečne?`