text:
"""
Support for Tellstick Net/Telstick Live.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.tellduslive/

"""
import logging

from homeassistant.components.tellduslive import TelldusLiveEntity
from homeassistant.const import TEMP_CELSIUS

_LOGGER = logging.getLogger(__name__)

SENSOR_TYPE_TEMP = 'temp'
SENSOR_TYPE_HUMIDITY = 'humidity'
SENSOR_TYPE_RAINRATE = 'rrate'
SENSOR_TYPE_RAINTOTAL = 'rtot'
SENSOR_TYPE_WINDDIRECTION = 'wdir'
SENSOR_TYPE_WINDAVERAGE = 'wavg'
SENSOR_TYPE_WINDGUST = 'wgust'
SENSOR_TYPE_WATT = 'watt'
SENSOR_TYPE_LUMINANCE = 'lum'

SENSOR_TYPES = {
    SENSOR_TYPE_TEMP: ['Temperature', TEMP_CELSIUS, 'mdi:thermometer'],
    SENSOR_TYPE_HUMIDITY: ['Humidity', '%', 'mdi:water'],
    SENSOR_TYPE_RAINRATE: ['Rain rate', 'mm', 'mdi:water'],
    SENSOR_TYPE_RAINTOTAL: ['Rain total', 'mm', 'mdi:water'],
    SENSOR_TYPE_WINDDIRECTION: ['Wind direction', '', ''],
    SENSOR_TYPE_WINDAVERAGE: ['Wind average', 'm/s', ''],
    SENSOR_TYPE_WINDGUST: ['Wind gust', 'm/s', ''],
    SENSOR_TYPE_WATT: ['Watt', 'W', ''],
    SENSOR_TYPE_LUMINANCE: ['Luminance', 'lx', ''],
}

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup Tellstick sensors."""
    if discovery_info is None:
        return
    add_devices(TelldusLiveSensor(hass, sensor) for sensor in discovery_info)

class TelldusLiveSensor(TelldusLiveEntity):
    """Representation of a Telldus Live sensor."""

    @property
    def device_id(self):
        """Return id of the device."""
        return self._id[0]

    @property
    def _type(self):
        """Return the type of the sensor."""
        return self._id[1]

    @property
    def _value(self):
        """Return value of the sensor."""
        return self.device.value(*self._id[1:])

    @property
    def _value_as_temperature(self):
        """Return the value as temperature."""
        return round(float(self._value), 1)

    @property
    def _value_as_luminance(self):
        """Return the value as luminance."""
        return round(float(self._value), 1)

    @property
    def _value_as_humidity(self):
        """Return the value as humidity."""
        return int(round(float(self._value)))

    @property
    def name(self):
        """Return the name of the sensor."""
        return '{} {}'.format(
            super().name,
            self.quantity_name or '')

    @property
    def state(self):
        """Return the state of the sensor."""
        if not self.available:
            return None
        elif self._type == SENSOR_TYPE_TEMP:
            return self._value_as_temperature
        elif self._type == SENSOR_TYPE_HUMIDITY:
            return self._value_as_humidity
        elif self._type == SENSOR_TYPE_LUMINANCE:
            return self._value_as_luminance
        else:
            return self._value

    @property
    def quantity_name(self):
        """Name of quantity."""
        return SENSOR_TYPES[self._type][0] \
            if self._type in SENSOR_TYPES else None

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement."""
        return SENSOR_TYPES[self._type][1] \
            if self._type in SENSOR_TYPES else None

    @property
    def icon(self):
        """Return the icon."""
        return SENSOR_TYPES[self._type][2] \
            if self._type in SENSOR_TYPES else None


text:
using base::win::ScopedBstr;
using base::win::ScopedComPtr;

namespace app_host {

namespace {
const int kInstallationPollingIntervalMs = 50;
}  // namespace

// Attempts to install the Chrome Binaries using the IGoogleUpdate3 interface.
// Blocks until the installation process completes, without message pumping.
HRESULT InstallBinaries() {
  base::win::ScopedCOMInitializer initialize_com;

  HRESULT hr = S_OK;
  if (!initialize_com.succeeded()) {
    LOG(ERROR) << "COM initialization failed";
    hr = E_FAIL;
  }

  ScopedComPtr<IGoogleUpdate3> update3;
  if (SUCCEEDED(hr)) {
    hr = internal::CreateGoogleUpdate3(update3.Receive());
  }

  ScopedBstr ap_value;
  if (SUCCEEDED(hr)) {
    hr = internal::SelectBinariesApValue(update3, ap_value.Receive());
  }

  ScopedComPtr<IAppBundle> app_bundle;
  if (SUCCEEDED(hr)) {
    hr = internal::CreateAppBundle(update3, app_bundle.Receive());
  }

  ScopedComPtr<IApp> app;
  if (SUCCEEDED(hr)) {
    hr = internal::CreateBinariesIApp(app_bundle, ap_value, app.Receive());
  }

  if (SUCCEEDED(hr)) {
    hr = app_bundle->checkForUpdate();
    if (FAILED(hr)) {
      LOG(ERROR) << "Failed to initiate update check: " << hr;
    }
  }

  if (SUCCEEDED(hr)) {
    // We rely upon Omaha to eventually time out and transition to a failure
    // state.
    while (!internal::CheckIfDone(app_bundle, app, &hr)) {
      base::PlatformThread::Sleep(base::TimeDelta::FromMilliseconds(
          kInstallationPollingIntervalMs));
    }
  }

  return hr;
}

}  // namespace app_host

redpajama_set_name: RedPajamaGithub


text:
package org.apache.camel.test.blueprint;

import java.io.File;
import java.io.FileOutputStream;
import java.net.URL;
import java.net.URLClassLoader;

import org.apache.aries.util.io.IOUtils;
import org.apache.camel.ProducerTemplate;
import org.junit.Test;
import org.ops4j.pax.swissbox.tinybundles.core.TinyBundle;
import org.ops4j.pax.swissbox.tinybundles.core.TinyBundles;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class MainTest {

    private static final String SYMBOLIC_NAME = "testMainWithoutIncludingTestBundle";

    @Test
    public void testMyMain() throws Exception {
        Main main = new Main();
        main.setBundleName("MyMainBundle");
        // as we run this test without packing ourselves as bundle, then include ourselves
        main.setIncludeSelfAsBundle(true);
        // setup the blueprint file here
        main.setDescriptors("org/apache/camel/test/blueprint/main-loadfile.xml");
        // set the configAdmin persistent id
        main.setConfigAdminPid("stuff");
        // set the configAdmin persistent file name
        main.setConfigAdminFileName("src/test/resources/etc/stuff.cfg");
        main.start();

        ProducerTemplate template = main.getCamelTemplate();
        assertNotNull("We should get the template here", template);

        String result = template.requestBody("direct:start", "hello", String.class);
        assertEquals("Get a wrong response", "Bye hello", result);
        main.stop();
    }

    @Test
    public void testMainWithoutIncludingTestBundle() throws Exception {
        TinyBundle bundle = TinyBundles.newBundle();
        bundle.add("OSGI-INF/blueprint/camel.xml", getClass().getResourceAsStream("main-loadfile.xml"));
        bundle.set("Manifest-Version", "2")
                .set("Bundle-ManifestVersion", "2")
                .set("Bundle-SymbolicName", SYMBOLIC_NAME)
                .set("Bundle-Version", "1.0.0");
        File tb = File.createTempFile(SYMBOLIC_NAME + "-", ".jar", new File("target"));
        FileOutputStream out = new FileOutputStream(tb);
        IOUtils.copy(bundle.build(), out);
        out.close();

        // simulate `camel:run` which is run after packaging the artifact, so a "bundle" (location with
        // META-INF/MANIFEST.MF) is detected in target/classes
        URLClassLoader loader = new URLClassLoader(new URL[] {tb.toURI().toURL()}, getClass().getClassLoader());

        Main main = new Main();
        main.setLoader(loader);
        // bundle name will be used as filter for blueprint container filter
        main.setBundleName(SYMBOLIC_NAME);
        // don't include test bundle (which is what `mvn camel:run` actually does)
        main.setIncludeSelfAsBundle(false);
        // don't setup the blueprint file here - it'll be picked up from a bundle on classpath
        //main.setDescriptors("none!");
        // set the configAdmin persistent id
        main.setConfigAdminPid("stuff");
        // set the configAdmin persistent file name
        main.setConfigAdminFileName("src/test/resources/etc/stuff.cfg");
        main.doStart();

        ProducerTemplate template = main.getCamelTemplate();
        assertNotNull("We should get the template here", template);

        String result = template.requestBody("direct:start", "hello", String.class);
        assertEquals("Get a wrong response", "Bye hello", result);
        main.stop();
    }

}


text:
Bruce KV based B-tree design
============================

- Stores keys and values.
- Stores counts in intermediate nodes so we can quickly do offset (paging)
  queries.
- Designed s.t. it's reasy to run on DynamoDB, without needing a transactioning
  system. We do structure-sharing updates instead of in-place updates s.t.
  aborts at any point don't need any cleanup beyond recycling newly created
  nodes.

Node types
----------

- Intermediate nodes, contains list of (key, pointer, count).
- Leaf nodes, contains list of (key, value).

Storage
-------

- Pluggable block engines (memory, file, disk).
- Blocks are immutable, but can be recycled.
- Serialization using FlatBuffers.
- Blocks are compressed using libz.
- Cached
- Configurable block sizes (block engines are supposed to throw an exception if
  they can't accept blocks of a particular size).
- Reused blocks are added to a recycler list.

bruce<<cache<file>, 1024>

Public interface
----------------

- bruce (engine plus a reference to a key engine)
    - .new() -> node
    - .get(id) -> node
    - .cleanup(nodelist)

- node (a root path of ids and a reference to the bruce instance)
    - .all() -> iterator
    - .find(key) -> iterator
    - .find(minkey, maxkey_exclusive) -> iterator
    - .insert(key, value) -> mutation
    - .remove(key) -> mutation
    - .parent() -> optional<node>

- iterator (reference to a node and a position in a node, and an end key)
    - .skip(n)
    - operator bool() -> bool
    - .current() -> pair
    - operator++()

- mutation(success, newroot, newnodes, recyclednodes)
    - .commit() -> nodelist(recyclednodes)
    - .rollback() -> nodelist(newnodes)

Overflow Block Rules
--------------------

The same key can occur multiple times in a single leaf node, but never in more
than one leaf node. To store keys that won't fit anymore in a single leaf node,
leaf nodes can have a linked list of "overflow" blocks trailing them.

INVARIANT
- All values in the overflow node have the same key, which is the same key as
  the last key in the leaf node.

INSERTING
- When splitting, put as much as can go into the overflow block as possible,
  multiple blocks if necessary.
- When inserting at the end and there's and overflow block, insert into the
  overflow block
- When splitting a leaf, any existing overflow block should go to the right.

REMOVING
- When removing an arbitrary key, prefer removing from the overflow chain if
  present.
- When removing a key/value pair, we may need to shift a key from the overflow
  block to the end of the leaf node (which may lead to a split if that k/v pair
  causes the leaf to bloat).


text:
package org.hippoecm.repository.jackrabbit;

import java.util.Collections;

import javax.jcr.RepositoryException;
import javax.jcr.UnsupportedRepositoryOperationException;

import org.apache.jackrabbit.core.SessionImpl;
import org.apache.jackrabbit.core.cluster.ClusterNode;
import org.apache.jackrabbit.core.observation.EventFilter;
import org.apache.jackrabbit.core.observation.ObservationDispatcher;
import org.apache.jackrabbit.core.observation.ObservationManagerImpl;
import org.apache.jackrabbit.core.observation.RevisionEventJournalImpl;
import org.hippoecm.repository.api.RevisionEventJournal;

public class HippoObservationManager extends ObservationManagerImpl {

    private final SessionImpl session;
    private final ClusterNode clusterNode;

    public HippoObservationManager(final ObservationDispatcher dispatcher, final SessionImpl session, final ClusterNode clusterNode) {
        super(dispatcher, session, clusterNode);
        this.clusterNode = clusterNode;
        this.session = session;
    }

    public RevisionEventJournal getEventJournal(
            int eventTypes, String absPath, boolean isDeep,
            String[] uuid, String[] nodeTypeName)
            throws RepositoryException {

        if (clusterNode == null) {
            throw new UnsupportedRepositoryOperationException(
                    "Event journal is only available in cluster deployments");
        }

        EventFilter filter = createEventFilter(
                eventTypes, Collections.singletonList(absPath), isDeep, uuid, nodeTypeName, false, false, false);
        return new RevisionEventJournalImpl(
                filter, clusterNode.getJournal(), clusterNode.getId(), session);
    }

}


text:
Ínteres por tipo de alimento

            <button class="btn btn-box-tool" data-widget="collapse"></button>
            <button class="btn btn-box-tool" data-widget="remove"></button>

        <canvas id="pieChart" style="height:250px"></canvas>


text:
'use strict';

var fs = require('fs'),
    path = require('path'),
    chalk = require('chalk'),
    // Processes
    eslint = require('eslint'),
    // Helpers
    log = require('./helpers/log');

module.exports = function(command) {
    var options = command.parent;

    return new Promise(function(resolve) {
        log.title('lint:js');
        log('Loading ESLint configuration...');

        var engine = new eslint.CLIEngine({
            configFile: path.join(process.cwd(), '.eslintrc')
        });

        log('Linting files...');

        resolve(engine.executeOnFiles([
            options.js,
            options.js.replace('js', 'tests'),
            './tasks'
        ]));
    })

    // Display the report
    .then(function(report) {
        if (report.errorCount === 0 && report.warningCount === 0) {
            log.success('JavaScript linted');
            return report;
        }

        if (report.warningCount) {
            log.warn(report.warningCount + ' warnings detected');
        }

        if (report.errorCount) {
            log.error(report.errorCount + ' errors detected');
        }

        report.results.forEach(function(result) {
            if (!result.messages.length) {
                return;
            }

            log(result.filePath, 1, 1);

            result.messages.forEach(function(message) {
                var meta = message.line + ':' + message.column + ' ' + message.ruleId,
                    msg = message.message;

                if (message.severity === 2) {
                    msg = chalk.red(msg);
                } else {
                    msg = chalk.yellow(msg);
                }

                log('[' + chalk.gray(meta) + '] ' + msg, 2);
            });
        });

        return report;
    });
};


text:
#ifndef OS_TYPEBASE_H
#define OS_TYPEBASE_H

#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#if defined (__cplusplus)
extern "C" {
#endif

#define OS_STRUCT(name)  struct name##_s
#define OS_EXTENDS(type) OS_STRUCT(type) _parent
#define OS_CLASS(name)   typedef OS_STRUCT(name) *name
#define OS_SIZEOF(name)  sizeof(OS_STRUCT(name))
#define OS_SUPER(obj)    (&((obj)->_parent))

#define OS_ALIGNMENT       (8)

#if defined (__cplusplus)
}
#endif

#endif /* OS_TYPEBASE_H */


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width initial-scale=1" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    <title>193 Camí</title>
    <meta name="description" content="A simple, whitespace, helvetica based portfolio theme.
">

    <link rel="stylesheet" href="/css/main.css">
    <link rel="canonical" href="/poetry/2018-02-25-193-Cami/">

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

        blog

          id

          sen

          por

          pro

193 Camí

February 25, 2018 — 00:00

No hi ha ningun camí massa llarg

per a qui avança amb parsimònia

i sense apresuraments indeguts;

no hi ha honors llunyans

per a qui es prepara

per a ells amb paciència.

Jean de la Breyère

This site was built using Jekyll and is hosted on Github Photos from Unsplash and text generated with Hipster Ipsum. © 2015


text:
package mockit.coverage;

import java.io.*;
import java.util.*;

import mockit.coverage.data.*;

final class DataFileMerging
{
   private final List<File> inputFiles;

   DataFileMerging(String[] inputPaths)
   {
      inputFiles = new ArrayList<File>(inputPaths.length);

      for (String path : inputPaths) {
         addInputFileToList(path.trim());
      }
   }

   private void addInputFileToList(String path)
   {
      if (path.length() > 0) {
         File inputFile = new File(path);

         if (inputFile.isDirectory()) {
            inputFile = new File(inputFile, "coverage.ser");
         }

         inputFiles.add(inputFile);
      }
   }

   CoverageData merge() throws IOException
   {
      CoverageData mergedData = null;

      for (File inputFile : inputFiles) {
         if (inputFile.exists()) {
            CoverageData existingData = CoverageData.readDataFromFile(inputFile);

            if (mergedData == null) {
               mergedData = existingData;
            }
            else {
               mergedData.merge(existingData);
            }
         }
      }

      if (mergedData == null) {
         throw new IllegalArgumentException("No input \"coverage.ser\" files found");
      }

      return mergedData;
   }
}


text:
require 'coveralls'
Coveralls.wear!

require 'faker'
require 'webmock/rspec'
require_relative '../lib/pesapal'

WebMock.disable_net_connect!(allow_localhost: true)

RSpec.configure do |config|
  config.expect_with :rspec do |c|
    c.syntax = :expect
  end
end


text:
<#
    .EXAMPLE
    Add a new host to the host file
#>
configuration RevertDSCServerHostFile
{
    param
    (
        [string[]]
        $NodeName = 'localhost'
    )

    Import-DSCResource -ModuleName xNetworking
    $h = 0

    Node $NodeName
    {
        Foreach ($Computer in $config.AllNodes.Where{$_.Role -match "DC" -or $_.Role -match "Member"}) {
            xHostsFile "HostEntry$h" {
                HostName = $Computer.Nodename
                IPAddress = $Computer.IPAddress
                Ensure = 'Absent'
            }
            $h++
        }

    }
}

$config = Invoke-Expression (Get-content $PSScriptRoot\NewDevDomainByConfigFile.psd1 -Raw)
RevertDSCServerHostFile -configurationData $config
Start-DscConfiguration .\RevertDSCServerHostFile\ -Wait -Verbose -Force


text:
    Home
    Projects
    About


text:
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')

describe Garterbelt::View, "Caching" do
  class Cached < Garterbelt::View
  end

  class SpecialCached < Garterbelt::View
    def self.cache_store_key
      :foo
    end
  end

  describe 'cache access' do
    describe 'class level #cache_store_key' do
      it 'defaults to :default' do
        Garterbelt::View.cache_store_key.should == :default
        Cached.cache_store_key.should == :default
      end

      it 'can be customized' do
        SpecialCached.cache_store_key.should == :foo
      end
    end

    describe 'instance level #cache_store_key' do
      it 'defaults to the class' do
        Cached.new.cache_store_key.should == :default
        SpecialCached.new.cache_store_key.should == :foo
      end

      it 'can be set independently' do
        cached = Cached.new
        cached.cache_store_key = :boo
        cached.cache_store_key.should == :boo
      end
    end

    describe 'cache_store' do
      it 'returns a cache object' do
        Cached.new.cache_store.should == Garterbelt.cache
      end

      it 'uses the instance level cache_store_key' do
        cached = Cached.new
        Garterbelt.cache_hash[:foo] = 'foo'
        cached.cache_store_key = :foo
        cached.cache_store.should == 'foo'
      end
    end

    describe 'cache key base' do
      describe 'class level' do
        it 'is the underscored version of the class by default' do
          Cached.cache_key_base.should == 'cached'
          SpecialCached.cache_key_base.should == 'special_cached'
        end

        it 'can be customized' do
          Cached.cache_key_base = 'custom_cache_key_base'
          Cached.cache_key_base.should == 'custom_cache_key_base'
        end
      end

      describe 'instance level' do
        it 'defaults to the class' do
          Cached.cache_key_base = 'cached'
          Cached.new.cache_key_base.should == 'cached'
        end

        it 'can be customized, which is probably a bad idea, but maybe necessary in crappy code' do
          Cached.cache_key_base.should == 'cached'
          cached = Cached.new
          cached.cache_key_base = 'foo'
          cached.cache_key_base.should == 'foo'
        end
      end
    end

    describe '#cache_key' do
      it 'it contains the instance level base' do
        cache = Cached.new
        cache.cache_key.should include "cached"
        cache.cache_key_base = 'foo'
        cache.cache_key.should include 'foo'
      end

      it 'has a default _default argument that is concatenated' do
        cache = Cached.new
        cache.cache_key.should == 'cached_default'
      end

      it 'takes a custom key argument' do
        cache = Cached.new
        cache.cache_key(:foo).should == 'cached_foo'
      end

      it 'uses the default when passed nil' do
        cache = Cached.new
        cache.cache_key(nil).should == 'cached_default'
      end
    end
  end

  describe '#cache' do
    before do
      @view = Cached.new
    end

    it 'makes a Cache object' do
      Garterbelt::Cache.should_receive(:new).and_return('foo')
      @view.cache("user_8") do
        puts "bar"
      end
    end

    it 'passes the correct key and the view' do
      Garterbelt::Cache.should_receive(:new).with(:view => @view, :key => "cached_user_8").and_return('foo')
      @view.cache("user_8") do
        puts "bar"
      end
    end

    it 'adds the Cache object to the render buffer' do
      @view.cache("foo_you") do
        puts "bar"
      end
      cache = @view._buffer.last
      cache.is_a?(Garterbelt::Cache).should be_true
      cache.key.should == 'cached_foo_you'
    end

    it 'passes on correctly the :expires_in option' do
      @view.cache("my_key", :expires_in => 24*3600) do
        puts "foo"
      end
      cache = @view._buffer.last
      cache.expires_in.should == 24*3600
    end
  end
end


text:
namespace Google.Cloud.Monitoring.V3.Snippets
{
    // [START monitoring_v3_generated_AlertPolicyService_GetAlertPolicy_sync_flattened_resourceNames2]
    using Google.Api.Gax;
    using Google.Cloud.Monitoring.V3;

    public sealed partial class GeneratedAlertPolicyServiceClientSnippets
    {
        /// <summary>Snippet for GetAlertPolicy</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void GetAlertPolicyResourceNames2()
        {
            // Create client
            AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
            // Initialize request argument(s)
            IResourceName name = new UnparsedResourceName("a/wildcard/resource");
            // Make the request
            AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name);
        }
    }
    // [END monitoring_v3_generated_AlertPolicyService_GetAlertPolicy_sync_flattened_resourceNames2]
}


text:
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Factories',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=30)),
                ('province', models.CharField(max_length=50)),
                ('state', models.CharField(max_length=50)),
                ('country', models.CharField(max_length=50)),
                ('city', models.CharField(max_length=50)),
                ('contact', models.CharField(max_length=30)),
                ('telephone', models.CharField(max_length=30)),
                ('email', models.EmailField(max_length=75)),
                ('bank_account', models.CharField(max_length=30)),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='PowerStations',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=30)),
                ('province', models.CharField(max_length=50)),
                ('country', models.CharField(max_length=50)),
                ('city', models.CharField(max_length=50)),
                ('contact', models.CharField(max_length=30)),
                ('telephone', models.CharField(max_length=30)),
                ('email', models.EmailField(max_length=75)),
                ('bank_account', models.CharField(max_length=30)),
                ('factory', models.ForeignKey(to='wind.Factories')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='UserProfile',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('telephone', models.CharField(max_length=30)),
                ('address', models.CharField(max_length=50)),
                ('level', models.CharField(max_length=10)),
                ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='WindTurbines',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=30)),
                ('longitude', models.CharField(max_length=12)),
                ('latitude', models.CharField(max_length=12)),
                ('contact', models.CharField(max_length=30)),
                ('telephone', models.CharField(max_length=30)),
                ('email', models.EmailField(max_length=75)),
                ('powerstation', models.ForeignKey(to='wind.PowerStations')),
                ('user', models.ForeignKey(to=settings.AUTH_USER_MODEL, unique=True)),
            ],
            options={
            },
            bases=(models.Model,),
        ),
    ]


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<link href="style.css" type="text/css" rel="stylesheet">
<title>IDIV—Signed Divide </title>

IDIV—Signed Divide

Opcode
Instruction
Op/En
64-Bit Mode
Compat/Leg Mode
Description

F6 /7
IDIV r/m8
M
Valid
Valid
Signed divide AX by r/m8, with result stored in: AL ← Quotient, AH ← Remainder.

REX + F6 /7
IDIV r/m8*
M
Valid
N.E.
Signed divide AX by r/m8, with result stored in AL ← Quotient, AH ← Remainder.

F7 /7
IDIV r/m16
M
Valid
Valid
Signed divide DX:AX by r/m16, with result stored in AX ← Quotient, DX ← Remainder.

F7 /7
IDIV r/m32
M
Valid
Valid
Signed divide EDX:EAX by r/m32, with result stored in EAX ← Quotient, EDX ← Remainder.

REX.W + F7 /7
IDIV r/m64
M
Valid
N.E.
Signed divide RDX:RAX by r/m64, with result stored in RAX ← Quotient, RDX ← Remainder.

NOTES:

*

In 64-bit mode, r/m8 can not be encoded to access the following byte registers if a REX prefix is used: AH, BH, CH, DH.

Instruction Operand Encoding

Op/En
Operand 1
Operand 2
Operand 3
Operand 4

M
ModRM:r/m (r)
NA
NA
NA

Description

Divides the (signed) value in the AX, DX:AX, or EDX:EAX (dividend) by the source operand (divisor) and stores the result in the AX (AH:AL), DX:AX, or EDX:EAX registers. The source operand can be a general-purpose register or a memory location. The action of this instruction depends on the operand size (dividend/divisor).

Non-integral results are truncated (chopped) towards 0. The remainder is always less than the divisor in magni-tude. Overflow is indicated with the #DE (divide error) exception rather than with the CF flag.

In 64-bit mode, the instruction's default operation size is 32 bits. Use of the REX.R prefix permits access to addi-tional registers (R8-R15). Use of the REX.W prefix promotes operation to 64 bits. In 64-bit mode when REX.W is applied, the instruction divides the signed value in RDX:RAX by the source operand. RAX contains a 64-bit quotient; RDX contains a 64-bit remainder.

See the summary chart at the beginning of this section for encoding data and limits. See Table 3-60.

Table 3-60.  IDIV Results

Operand Size
Dividend
Divisor
Quotient
Remainder
Quotient Range

Word/byte

Doubleword/word

Quadword/doubleword

Doublequadword/ quadword

AX

DX:AX

EDX:EAX

RDX:RAX

r/m8

r/m16

r/m32

r/m64

AL

AX

EAX

RAX

AH

DX

EDX

RDX

−128 to +127

−32,768 to +32,767

−231 to 231 − 1

−263 to 263 − 1

Operation

IF SRC = 0
    THEN #DE; (* Divide error *)
FI;
IF OperandSize = 8 (* Word/byte operation *)
    THEN
         temp ← AX / SRC; (* Signed division *)
         IF (temp > 7FH) or (temp < 80H)
         (* If a positive result is greater than 7FH or a negative result is less than 80H *)
              THEN #DE; (* Divide error *)
              ELSE
                    AL ← temp;
                    AH ← AX SignedModulus SRC;
         FI;
    ELSE IF OperandSize = 16 (* Doubleword/word operation *)
         THEN
              temp ← DX:AX / SRC; (* Signed division *)
              IF (temp > 7FFFH) or (temp < 8000H)
              (* If a positive result is greater than 7FFFH
              or a negative result is less than 8000H *)
                    THEN
                         #DE; (* Divide error *)
                    ELSE
                         AX ← temp;
                         DX ← DX:AX SignedModulus SRC;
              FI;
         FI;
    ELSE IF OperandSize = 32 (* Quadword/doubleword operation *)
              temp ← EDX:EAX / SRC; (* Signed division *)
              IF (temp > 7FFFFFFFH) or (temp < 80000000H)
              (* If a positive result is greater than 7FFFFFFFH
              or a negative result is less than 80000000H *)
                    THEN
                         #DE; (* Divide error *)
                    ELSE
                         EAX ← temp;
                         EDX ← EDXE:AX SignedModulus SRC;
              FI;
         FI;
    ELSE IF OperandSize = 64 (* Doublequadword/quadword operation *)
              temp ← RDX:RAX / SRC; (* Signed division *)
              IF (temp > 7FFFFFFFFFFFFFFFH) or (temp < 8000000000000000H)
              (* If a positive result is greater than 7FFFFFFFFFFFFFFFH
              or a negative result is less than 8000000000000000H *)
                    THEN
                         #DE; (* Divide error *)
                    ELSE
                         RAX ← temp;
                         RDX ← RDE:RAX SignedModulus SRC;
              FI;
         FI;
FI;

Flags Affected

The CF, OF, SF, ZF, AF, and PF flags are undefined.

Protected Mode Exceptions

#DE

If the source operand (divisor) is 0.

The signed result (quotient) is too large for the destination.

#GP(0)

If a memory operand effective address is outside the CS, DS, ES, FS, or GS segment limit.

If the DS, ES, FS, or GS register is used to access memory and it contains a NULL segment selector.

#SS(0)
If a memory operand effective address is outside the SS segment limit.

#PF(fault-code)
If a page fault occurs.

#AC(0)
If alignment checking is enabled and an unaligned memory reference is made while the current privilege level is 3.

#UD
If the LOCK prefix is used.

Real-Address Mode Exceptions

#DE

If the source operand (divisor) is 0.

The signed result (quotient) is too large for the destination.

#GP
If a memory operand effective address is outside the CS, DS, ES, FS, or GS segment limit.

#SS
If a memory operand effective address is outside the SS segment limit.

#UD
If the LOCK prefix is used.

Virtual-8086 Mode Exceptions

#DE

If the source operand (divisor) is 0.

The signed result (quotient) is too large for the destination.

#GP(0)
If a memory operand effective address is outside the CS, DS, ES, FS, or GS segment limit.

#SS(0)
If a memory operand effective address is outside the SS segment limit.

#PF(fault-code)
If a page fault occurs.

#AC(0)
If alignment checking is enabled and an unaligned memory reference is made.

#UD
If the LOCK prefix is used.

Compatibility Mode Exceptions

Same exceptions as in protected mode.

64-Bit Mode Exceptions

#SS(0)
If a memory address referencing the SS segment is in a non-canonical form.

#GP(0)
If the memory address is in a non-canonical form.

#DE

If the source operand (divisor) is 0

If the quotient is too large for the designated register.

#PF(fault-code)
If a page fault occurs.

#AC(0)
If alignment checking is enabled and an unaligned memory reference is made while the current privilege level is 3.

#UD
If the LOCK prefix is used.


text:
#include "MyRadioHelper.h"
#include <termios.h>
#include <unistd.h>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>

using namespace joynr;

INIT_LOGGER(MyRadioHelper);

MyRadioHelper::MyRadioHelper()
{
}

int MyRadioHelper::getch()
{
    termios terminalSettingsBackup;
    tcgetattr(STDIN_FILENO, &terminalSettingsBackup);

    termios terminalSettings = terminalSettingsBackup;
    terminalSettings.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &terminalSettings);

    int ch = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &terminalSettingsBackup);

    return ch;
}

const std::string& MyRadioHelper::MISSING_NAME()
{
    static const std::string missingName("MISSING_NAME");
    return missingName;
}

void MyRadioHelper::pressQToContinue()
{
    JOYNR_LOG_INFO(logger, "*****************************************************");
    JOYNR_LOG_INFO(logger, "Please press \"q\" to quit the application\n");
    JOYNR_LOG_INFO(logger, "*****************************************************");

    while (getch() != 'q')
        ;
}

std::string MyRadioHelper::getAbsolutePathToExectuable(const std::string& executableName)
{
    boost::filesystem::path fullPath =
            boost::filesystem::system_complete(boost::filesystem::path(executableName));
    return fullPath.parent_path().string();
}

void MyRadioHelper::prettyLog(joynr::Logger& logger, const std::string& message)
{
    JOYNR_LOG_INFO(logger, "--------------------------------------------------");
    JOYNR_LOG_INFO(logger, message);
    JOYNR_LOG_INFO(logger, "--------------------------------------------------");
}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2017] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package Catalyst::Action::Deserialize;

use Moose;
use namespace::autoclean;

extends 'Catalyst::Action::SerializeBase';
use Module::Pluggable::Object;
use MRO::Compat;
use Moose::Util::TypeConstraints;

our $VERSION = '1.11';
$VERSION = eval $VERSION;

has plugins => ( is => 'rw' );

has deserialize_http_methods => (
    traits  => ['Hash'],
    isa     => do {
        my $tc = subtype as 'HashRef[Str]';
        coerce $tc, from 'ArrayRef[Str]',
            via { +{ map { ($_ => 1) } @$_ } };
        $tc;
    },
    coerce  => 1,
    builder => '_build_deserialize_http_methods',
    handles => {
        deserialize_http_methods         => 'keys',
        _deserialize_handles_http_method => 'exists',
    },
);

sub _build_deserialize_http_methods { [qw(POST PUT OPTIONS DELETE)] }

sub execute {
    my $self = shift;
    my ( $controller, $c ) = @_;

    if ( !defined($c->req->data) && $self->_deserialize_handles_http_method($c->request->method) ) {
        my ( $sclass, $sarg, $content_type ) =
          $self->_load_content_plugins( 'Catalyst::Action::Deserialize',
            $controller, $c );
        return 1 unless defined($sclass);
        my $rc;
        if ( defined($sarg) ) {
            $rc = $sclass->execute( $controller, $c, $sarg );
        } else {
            $rc = $sclass->execute( $controller, $c );
        }
        if ( $rc eq "0" ) {
            return $self->unsupported_media_type( $c, $content_type );
        } elsif ( $rc ne "1" ) {
            return $self->serialize_bad_request( $c, $content_type, $rc );
        }
    }

    $self->maybe::next::method(@_);

    return 1;
}

sub _load_content_plugins {
    my $self = shift;
    my ( $search_path, $controller, $c ) = @_;

    unless ( defined( $self->_loaded_plugins ) ) {
        $self->_loaded_plugins( {} );
    }

    # Load the Serialize Classes
    unless ( defined( $self->_serialize_plugins ) ) {
        my @plugins;
        my $mpo =
          Module::Pluggable::Object->new( 'search_path' => [$search_path], );
        @plugins = $mpo->plugins;
        $self->_serialize_plugins( \@plugins );
    }

    # Finally, we load the class.  If you have a default serializer,
    # and we still don't have a content-type that exists in the map,
    # we'll use it.
    my $sclass = $search_path . "::";
    my $sarg;
    my $map;

    my $config;

    if ( exists $controller->{'serialize'} ) {
        $c->log->info("Catalyst::Action::REST - deprecated use of 'serialize' for configuration.");
        $c->log->info("Please see 'CONFIGURATION' in Catalyst::Controller::REST.");
        $config = $controller->{'serialize'};
        # if they're using the deprecated config, they may be expecting a
        # default mapping too.
        $config->{map} ||= $controller->{map};
    } else {
        $config = $controller;
    }
    $map = $config->{'map'};

    # For deserializing, force content-type to be application/json
    my $content_type = 'application/json';

    return $self->unsupported_media_type($c, $content_type)
        if not $content_type;

    # carp about old text/x-json
    if ($content_type eq 'text/x-json') {
        $c->log->info('Using deprecated text/x-json content-type.');
        $c->log->info('Use application/json instead!');
    }

    if ( exists( $map->{$content_type} ) ) {
        my $mc;
        if ( ref( $map->{$content_type} ) eq "ARRAY" ) {
            $mc   = $map->{$content_type}->[0];
            $sarg = $map->{$content_type}->[1];
        } else {
            $mc = $map->{$content_type};
        }
        $sclass .= $mc;
        if ( !grep( /^$sclass$/, @{ $self->_serialize_plugins } ) ) {
            return $self->unsupported_media_type($c, $content_type);
        }
    } else {
        return $self->unsupported_media_type($c, $content_type);
    }
    unless ( exists( $self->_loaded_plugins->{$sclass} ) ) {
        my $load_class = $sclass;
        $load_class =~ s/::/\//g;
        $load_class =~ s/$/.pm/g;
        eval { require $load_class; };
        if ($@) {
            $c->log->error(
                "Error loading $sclass for " . $content_type . ": $!" );
            return $self->unsupported_media_type($c, $content_type);
        } else {
            $self->_loaded_plugins->{$sclass} = 1;
        }
    }

    return $sclass, $sarg, $content_type;
}

__PACKAGE__->meta->make_immutable;

1;


text:
import errno
import logging
import os

import psutil

LOG = logging.getLogger(__name__)

def _get_procs_of_pgid(wanted_pgid):
    procs = []
    for p in psutil.process_iter():
        try:
            pgid = os.getpgid(p.pid)
        except OSError as e:
            # ESRCH is returned if process just died in the meantime
            if e.errno != errno.ESRCH:
                raise
            continue
        if pgid == wanted_pgid:
            procs.append(p)
    return procs

def process_cleaner(parent):
    do_sigkill = False
    # NOTE(sileht): Add processes from process tree and process group
    # Relying on process tree only will not work in case of
    # parent dying prematuraly and double fork
    # Relying on process group only will not work in case of
    # subprocess calling again setsid()
    procs = set(_get_procs_of_pgid(parent.pid))
    try:
        LOG.debug("Terminating %s (%s)",
                  " ".join(parent.cmdline()), parent.pid)
        procs |= set(parent.children(recursive=True))
        procs.add(parent)
        parent.terminate()
    except psutil.NoSuchProcess:
        LOG.warning("`%s` is already gone, sending SIGKILL to its process "
                    "group", parent)
        do_sigkill = True
    else:
        # Waiting for all processes to stop
        for p in procs:
            try:
                LOG.debug("Waiting %s (%s)", " ".join(p.cmdline()), p.pid)
            except psutil.NoSuchProcess:
                pass
        gone, alive = psutil.wait_procs(procs, timeout=10)
        if alive:
            do_sigkill = True
            LOG.warning("`%s` didn't terminate cleanly after 10 seconds, "
                        "sending SIGKILL to its process group", parent)

    if do_sigkill and procs:
        for p in procs:
            try:
                LOG.debug("Killing %s (%s)", " ".join(p.cmdline()), p.pid)
                p.kill()
            except psutil.NoSuchProcess:
                pass
        gone, alive = psutil.wait_procs(procs, timeout=10)
        if alive:
            LOG.warning("`%s` survive SIGKILL", alive)

    # Be sure to get returncode
    parent.wait()


text:
Basic replace
=============

Use <replace> to replace a theme node with a content node.  Put an
attribute on the theme node to ensure that the result doesn't have the
attribute.


text:
package org.apache.geode.tools.pulse.tests.rules;

import static org.junit.Assert.assertNotNull;

import java.util.concurrent.TimeUnit;

import org.apache.commons.lang.StringUtils;
import org.junit.rules.ExternalResource;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class WebDriverRule extends ExternalResource {
  private WebDriver driver;
  static final int MAX_RETRIES = 10;
  private String pulseUrl;
  private String username;
  private String password;

  public WebDriverRule(String pulseUrl) {
    this.pulseUrl = pulseUrl;
  }

  public WebDriverRule(String username, String password, String pulseUrl) {
    this(pulseUrl);
    this.username = username;
    this.password = password;
  }

  public WebDriver getDriver() {
    return this.driver;
  }

  public String getPulseURL() {
    return pulseUrl;
  }

  @Override
  public void before() throws Throwable {
    setUpWebDriver();

    try {
      driver.get(getPulseURL() + "login.html");
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("before: driver get exception " + e.getMessage());
      throw e;
    }

    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
      try {
        login();
      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("before: login exception " + e.getMessage());
        throw e;
      }
    }

    driver.navigate().refresh();
  }

  @Override
  public void after() {
    driver.quit();
  }

  private void login() {
    WebElement userNameElement = waitForElementById("user_name", 60);
    WebElement passwordElement = waitForElementById("user_password");
    userNameElement.sendKeys(username);
    passwordElement.sendKeys(password);
    passwordElement.submit();

    driver.get(getPulseURL() + "clusterDetail.html");
    WebElement userNameOnPulsePage =
        (new WebDriverWait(driver, 30, 1000)).until(
            (ExpectedCondition<WebElement>) d -> d.findElement(By.id("userName")));
    assertNotNull(userNameOnPulsePage);
  }

  private void setUpWebDriver() {
    ChromeOptions options = new ChromeOptions();
    options.addArguments("headless");
    options.addArguments("no-sandbox");
    options.addArguments("window-size=1200x600");
    driver = new ChromeDriver(options);
    driver.manage().window().maximize();
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    driver.manage().timeouts().pageLoadTimeout(300, TimeUnit.SECONDS);
  }

  private WebElement waitForElementById(final String id) {
    return waitForElementById(id, 10);
  }

  private WebElement waitForElementById(final String id, int timeoutInSeconds) {
    WebElement element =
        (new WebDriverWait(driver, timeoutInSeconds, 1000))
            .until((ExpectedCondition<WebElement>) d -> d.findElement(By.id(id)));
    assertNotNull(element);
    return element;
  }
}


text:
var lowercaseCount = require('../Solutions/Regex_count_lowercase_letters.js');
require('should');

describe('Regex count lowercase letters', function() {
    it('should work', function() {
        lowercaseCount('abc').should.equal(3);
        lowercaseCount('abcABC123').should.equal(3);
        lowercaseCount('abcABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~').should.equal(3);
        lowercaseCount('').should.equal(0)
        lowercaseCount('ABC123!@€£#$%^&*()_-+=}{[]|\':;?/>.<,~').should.equal(0)
        lowercaseCount('abcdefghijklmnopqrstuvwxyz').should.equal(26);
    });
});


text:
package com.querydsl.core.domain.query2;

import static com.querydsl.core.types.PathMetadataFactory.forVariable;

import java.io.Serializable;

import com.querydsl.core.domain.CommonIdentifiable;
import com.querydsl.core.types.PathMetadata;
import com.querydsl.core.types.dsl.BeanPath;
import com.querydsl.core.types.dsl.EntityPathBase;
import com.querydsl.core.types.dsl.NumberPath;
import com.querydsl.core.types.dsl.SimplePath;

/**
 * QCommonIdentifiable is a Querydsl query type for CommonIdentifiable
 */
public class QCommonIdentifiableType extends EntityPathBase<CommonIdentifiable<? extends Serializable>> {

    private static final long serialVersionUID = 1818647030;

    public static final QCommonIdentifiableType commonIdentifiable = new QCommonIdentifiableType("commonIdentifiable");

    public final QCommonPersistenceType _super = new QCommonPersistenceType(this);

    public final SimplePath<java.io.Serializable> id = createSimple("id", java.io.Serializable.class);

    //inherited
    public final NumberPath<Long> version = _super.version;

    @SuppressWarnings("unchecked")
    public QCommonIdentifiableType(String variable) {
        super((Class) CommonIdentifiable.class, forVariable(variable));
    }

    public QCommonIdentifiableType(BeanPath<? extends CommonIdentifiable<? extends java.io.Serializable>> entity) {
        super(entity.getType(), entity.getMetadata());
    }

    @SuppressWarnings("unchecked")
    public QCommonIdentifiableType(PathMetadata metadata) {
        super((Class) CommonIdentifiable.class, metadata);
    }

}


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

<title>Rectangle2</title>
<meta name="date" content="2013-03-07">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.tyrlib2.graphics.renderables

Class Rectangle2

java.lang.Object

com.tyrlib2.graphics.scene.SceneObject

com.tyrlib2.graphics.scene.BoundedSceneObject

com.tyrlib2.graphics.renderer.BoundedRenderable

com.tyrlib2.graphics.renderer.Renderable

com.tyrlib2.graphics.renderer.Renderable2

com.tyrlib2.graphics.renderables.Rectangle2

All Implemented Interfaces:

IRenderable

public class Rectangle2
extends Renderable2

A 2D rectangle

Author:

Sascha

Field Summary

Fields

Modifier and Type
Field and Description

static int
DEFAULT_BORDER_WIDTH

static Color
DEFAULT_COLOR

static short[]
DRAW_ORDER_BORDER

static short[]
DRAW_ORDER_QUAD

Constructor Summary

Constructors

Constructor and Description

Rectangle2(Vector2 size)

Rectangle2(Vector2 size,
          Color color)

Method Summary

Methods

Modifier and Type
Method and Description

Color
getColor()

Vector2
getSize()

void
render(float[] vpMatrix)

Render this object

void
setBorder(int borderWidth)

void
setFilled(boolean filled)

Methods inherited from class com.tyrlib2.graphics.renderer.Renderable2

getAlpha, getBoundingBox, setAlpha

Methods inherited from class com.tyrlib2.graphics.renderer.Renderable

attachTo, createShallowCopy, getMaterial, getMesh, init, setMaterial, setMesh

Methods inherited from class com.tyrlib2.graphics.renderer.BoundedRenderable

getUntransformedBoundingBox, setBoundingBoxVisible

Methods inherited from class com.tyrlib2.graphics.scene.BoundedSceneObject

detach, isDity, onTransformed, setClean

Methods inherited from class com.tyrlib2.graphics.scene.SceneObject

getAbsolutePos, getModelMatrix, getParent, getRelativePos

Methods inherited from class java.lang.Object

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

Field Detail

DEFAULT_COLOR

public static final Color DEFAULT_COLOR

DEFAULT_BORDER_WIDTH

public static final int DEFAULT_BORDER_WIDTH

See Also:

Constant Field Values

DRAW_ORDER_QUAD

public static final short[] DRAW_ORDER_QUAD

DRAW_ORDER_BORDER

public static final short[] DRAW_ORDER_BORDER

Constructor Detail

Rectangle2

public Rectangle2(Vector2 size,
          Color color)

Rectangle2

public Rectangle2(Vector2 size)

Method Detail

getSize

public Vector2 getSize()

setFilled

public void setFilled(boolean filled)

setBorder

public void setBorder(int borderWidth)

render

public void render(float[] vpMatrix)

Description copied from class: Renderable

Render this object

Specified by:

render in interface IRenderable

Overrides:

render in class Renderable2

getColor

public Color getColor()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
<?php

/*
|--------------------------------------------------------------------------
| Routes File
|--------------------------------------------------------------------------
|
| Here is where you will register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/

/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| This route group applies the "web" middleware group to every route
| it contains. The "web" middleware group is defined in your HTTP
| kernel and includes session state, CSRF protection, and more.
|
*/

Route::group(['middleware' => ['web']], function () {

    Route::get('/', function () {
        return view('welcome');
    })->middleware('guest');

    Route::get('/tasks', 'TaskController@index');
    Route::post('/task', 'TaskController@store');
    Route::delete('/task/{task}', 'TaskController@destroy');
    Route::get('/task/edit/{task}', 'TaskController@edit');
    Route::patch('/task/{task}', 'TaskController@update');

    Route::auth();

});


text:
bool ends_with(std::string_view text, std::string_view ending) {
    if (ending.size() > text.size()) return false;
    if (text.empty()) return false;
    if (ending.empty()) return true;
    return text.substr(text.size() - ending.size(), ending.size()) == ending;
}

float volume_int_to_float(int vol) noexcept { return static_cast<float>(vol) / 100.f; }

unsigned int volume_float_to_int(float vol) noexcept {
    return static_cast<unsigned int>(vol * 100.f);
}

char easytolower(char in) noexcept {
    if (in <= 'Z' && in >= 'A') {
        return static_cast<char>(in - ('Z' - 'z'));
    }
    return in;
}

std::string string_to_lower(const std::string& str) {
    std::string lowered;
    lowered.resize(str.size());
    std::transform(str.begin(), str.end(), lowered.begin(), easytolower);
    return lowered;
}

std::string replace_dollar_with_version_number(std::string_view text) {
    std::string version = std::to_string(RADIOSTREAM_VERSION_MAJOR) + '.' +
                          std::to_string(RADIOSTREAM_VERSION_MINOR) + '.' +
                          std::to_string(RADIOSTREAM_VERSION_PATCH);
    std::replace(version.begin(), version.end(), '\0', '0');
    std::string replaced_text = std::string(text);
    auto pos = replaced_text.find_first_of('$');
    replaced_text.erase(pos, 1);
    replaced_text.insert(pos, version);
    return replaced_text;
}


text:
from lxml.builder import E

# module packages
from jnpr.junos.cfg import Resource
from jnpr.junos import jxml as JXML

class NatSrcRule(Resource):

    """
    [edit security nat source rule-set <ruleset-name> rule <rule-name>]
    """

    PROPERTIES = [
        "match_src_addr",
        "match_dst_addr",
        "pool"
    ]

    # -----------------------------------------------------------------------
    # XML read
    # -----------------------------------------------------------------------

    def _xml_at_top(self):
        return E.security(E.nat(E.source(
            E('rule-set',
              E.name(self.P._name),
              E.rule(E.name(self._name))
              )
        )))

    def _xml_at_res(self, xml):
        return xml.find('.//rule')

    def _xml_to_py(self, as_xml, to_py):
        """
        converts Junos XML to native Python
        """
        Resource._r_has_xml_status(as_xml, to_py)
        e = as_xml.find('src-nat-rule-match')
        to_py['match_src_addr'] = e.find('source-address').text
        to_py['match_dst_addr'] = e.find('destination-address').text
        to_py['pool'] = as_xml.find('.//pool-name').text

    # -----------------------------------------------------------------------
    # XML write
    # -----------------------------------------------------------------------

    def _xml_hook_build_change_begin(self, xml):
        """
        when doing a write, assign default values if they are not present
        """
        def _default_to(prop, value):
            if prop not in self.should:
                self.should[prop] = value

        if self.is_new:
            _default_to('match_dst_addr', '0.0.0.0/0')
            _default_to('match_src_addr', '0.0.0.0/0')

    def _xml_change_match_src_addr(self, xml):
        xml.append(E('src-nat-rule-match',
                     E('source-address',
                       JXML.REPLACE,
                       self.should['match_src_addr'])
                     ))
        return True

    def _xml_change_match_dst_addr(self, xml):
        xml.append(E('src-nat-rule-match',
                     E('destination-address',
                       JXML.REPLACE,
                       self.should['match_dst_addr'])
                     ))
        return True

    def _xml_change_pool(self, xml):
        xml.append(E.then(
            E('source-nat', E.pool(E('pool-name', self.should['pool'])))
        ))
        return True

    # -----------------------------------------------------------------------
    # Manager List, Catalog
    # -----------------------------------------------------------------------

    def _r_list(self):
        self._rlist = self.P['$rules']

    def _r_catalog(self):
        get = E.security(E.nat(E.source(
            E('rule-set',
              E.name(self.P._name),
              )
        )))
        got = self.D.rpc.get_config(get)
        for rule in got.xpath('.//rule'):
            name = rule.find('name').text
            self._rcatalog[name] = {}
            self._xml_to_py(rule, self._rcatalog[name])


text:
policy 'sdf-gen-listy-1.1' do
  # Define a 'webservice' resource to protect the webapp.
  # Inbound requests to the webapp will be intercepted by a gatekeeper, which will
  # check that the inbound role has the necessary privilege corresponding to the HTTP method.
  webapp_service = resource "webservice", "webapp"
  # Define a 'webservice' resource to protect the backend.
  backend_service = resource "webservice", "backend"

  # User group who can 'admin' the webapp.
  # This group can read, create, and update.
  group "admin" do
    %w(read create update).each do |privilege|
      can privilege, webapp_service
    end
  end

  # User group who can 'use' the webapp.
  # This group can only read.
  group "users" do
    %w(read).each do |privilege|
      can privilege, webapp_service
    end
  end

  # Machines in the webapp. These machines are privileged to read,
  # create, and update the backend.
  layer 'webapp' do
    %w(read create update).each do |privilege|
      can privilege, backend_service
    end
  end
end


text:
package com.dayu.lotto.service.impl;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.ml.Pipeline;
import org.apache.spark.ml.PipelineStage;
import org.apache.spark.ml.classification.LogisticRegression;
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator;
import org.apache.spark.ml.feature.HashingTF;
import org.apache.spark.ml.feature.Tokenizer;
import org.apache.spark.ml.param.ParamMap;
import org.apache.spark.ml.tuning.CrossValidator;
import org.apache.spark.ml.tuning.CrossValidatorModel;
import org.apache.spark.ml.tuning.ParamGridBuilder;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dayu.lotto.algorithm.JavaLabeledDocument;
import com.dayu.lotto.algorithm.WeightedSelector;
import com.dayu.lotto.dao.LottoDAO;
import com.dayu.lotto.entity.Division;
import com.dayu.lotto.entity.LottoNumberPrediction.SinglePredictionObject;
import com.dayu.lotto.entity.LottoTicket;
import com.dayu.lotto.entity.OZLottoPrediction;
import com.dayu.lotto.entity.OZLottoResult;
import com.dayu.lotto.entity.OZLottoTicket;

@Service
public class OZLottoServiceImpl extends AbstractLottoService<OZLottoTicket, OZLottoResult, OZLottoPrediction> {

	@Autowired
	private LottoDAO lottoDAO;

	@Autowired
	private JavaSparkContext javaSparkContext;

	private static Logger log = LoggerFactory.getLogger(OZLottoServiceImpl.class);
	private static final int SAMPLE = 20;

	public void uploadResults(InputStream is) throws Exception {
		BufferedReader reader = null;
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		try {
			reader = new BufferedReader (new InputStreamReader(is));
			String line;
			int lineNumber = 1;
			while ((line = reader.readLine()) != null)
			{
				if (lineNumber > 1)
				{
					OZLottoResult ozLottoResult = new OZLottoResult();

					String[] columns = line.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");

					// remove quotes
					for (int i =0; i < columns.length ; i++)
					{
						columns[i] = columns[i].replaceAll("\"", "");
					}

					if (columns.length == 18)
					{
						Date drawDate = df.parse(columns[1]);

						ozLottoResult.setDrawNumber(Integer.parseInt(columns[0]));
						ozLottoResult.setDrawDate(drawDate);
						List<Integer> winningNumbers = new ArrayList<Integer>();

						winningNumbers.add(Integer.parseInt(columns[2]));
						winningNumbers.add(Integer.parseInt(columns[3]));
						winningNumbers.add(Integer.parseInt(columns[4]));
						winningNumbers.add(Integer.parseInt(columns[5]));
						winningNumbers.add(Integer.parseInt(columns[6]));
						winningNumbers.add(Integer.parseInt(columns[7]));
						winningNumbers.add(Integer.parseInt(columns[8]));

						Collections.sort(winningNumbers);
						ozLottoResult.setWinningNumbers(winningNumbers);

						List<Integer> supplementaryNumbers = new ArrayList<Integer>();

						supplementaryNumbers.add(Integer.parseInt(columns[9]));
						supplementaryNumbers.add(Integer.parseInt(columns[10]));

						Collections.sort(supplementaryNumbers);
						ozLottoResult.setSupplementaryNumbers(supplementaryNumbers);

						List<Division> divisions = new ArrayList<Division>();
						divisions.add(new Division(1, BigDecimal.valueOf(Double.parseDouble(columns[11].replaceAll("[^\\d.]+", "")))));
						divisions.add(new Division(2, BigDecimal.valueOf(Double.parseDouble(columns[12].replaceAll("[^\\d.]+", "")))));
						divisions.add(new Division(3, BigDecimal.valueOf(Double.parseDouble(columns[13].replaceAll("[^\\d.]+", "")))));
						divisions.add(new Division(4, BigDecimal.valueOf(Double.parseDouble(columns[14].replaceAll("[^\\d.]+", "")))));
						divisions.add(new Division(5, BigDecimal.valueOf(Double.parseDouble(columns[15].replaceAll("[^\\d.]+", "")))));
						divisions.add(new Division(6, BigDecimal.valueOf(Double.parseDouble(columns[16].replaceAll("[^\\d.]+", "")))));
						divisions.add(new Division(7, BigDecimal.valueOf(Double.parseDouble(columns[17].replaceAll("[^\\d.]+", "")))));
						Collections.sort(divisions);
						ozLottoResult.setDivisions(divisions);

						lottoDAO.save(ozLottoResult);
					}
					else
					{
						log.error(" line " + lineNumber + " is illigal with length " + columns.length);
					}
				}
				lineNumber++;
			}
		}
		finally
		{
			reader.close();
			is.close();
		}
	}

	public int numberToPick() {
		return 7;
	}

	public int pool() {
		return 45;
	}

	public String draw(WeightedSelector selector, int draw, int games) {
		List<OZLottoResult> results = findLast(SAMPLE);
		CrossValidatorModel cvModel = getCrossValidatorModel();

		// all numbers collected from results
		List<Integer> allDraws = new ArrayList<Integer>();
		for (OZLottoResult result : results)
		{
			allDraws.addAll(result.getWinningNumbers());

			allDraws.addAll(result.getSupplementaryNumbers());
		}

		List<OZLottoTicket.Result> ticketResults = new ArrayList<OZLottoTicket.Result>();

		// build model and predict
		for (int i = 0; i < games; i++)
		{
			OZLottoTicket.Result ticketResult = new OZLottoTicket().newResult();

			Map<Integer, Integer> model = selector.buildWeightingModel(allDraws);

			int totalWeight = 0;
			for (int key: model.keySet()) {
				totalWeight += model.get(key);
			}

			ticketResult.setNumbers(selector.select(numberToPick(), model, totalWeight, cvModel));

			ticketResults.add(ticketResult);
		}

		OZLottoTicket ticket = new OZLottoTicket();
		ticket.setDraw(draw);
		ticket.setResults(ticketResults);

		return lottoDAO.save(ticket);
	}

	public void checkTicket(LottoTicket lottoTicket) {
		OZLottoTicket ozLottoTicket = (OZLottoTicket) lottoTicket;

		OZLottoResult lottoResult = findResultByDraw(ozLottoTicket.getDraw());

		if (lottoResult != null)
		{
			BigDecimal prize = BigDecimal.ZERO;
			for (OZLottoTicket.Result result : ozLottoTicket.getResults())
			{
				int winNumbers = 0;
				int supNumbers = 0;

				for (int n : result.getNumbers())
				{
					if (lottoResult.getWinningNumbers().contains(n))
						winNumbers++;
					else if (lottoResult.getSupplementaryNumbers().contains(n))
						supNumbers++;
				}
				if (winNumbers == 7)
				{
					log.info("1st prize: " + result.getNumbers().toString());
					log.info("Prize win $" + lottoResult.getDivisions().get(0).getAmount());
					prize = prize.add(lottoResult.getDivisions().get(0).getAmount());
				}
				else if (winNumbers == 6)
				{
					if (supNumbers > 0)
					{
						log.info("2nd prize: " + result.getNumbers().toString());
						log.info("Prize win $" + lottoResult.getDivisions().get(1).getAmount());
						prize = prize.add(lottoResult.getDivisions().get(1).getAmount());
					}
					else
					{
						log.info("3rd prize: " + result.getNumbers().toString());
						log.info("Prize win $" + lottoResult.getDivisions().get(2).getAmount());
						prize = prize.add(lottoResult.getDivisions().get(2).getAmount());
					}
				}
				else if (winNumbers == 5)
				{
					if (supNumbers > 0)
					{
						log.info("4th prize: " + result.getNumbers().toString());
						log.info("Prize win $" + lottoResult.getDivisions().get(3).getAmount());
						prize = prize.add(lottoResult.getDivisions().get(3).getAmount());
					}
					else
					{
						log.info("5th prize: " + result.getNumbers().toString());
						log.info("Prize win $" + lottoResult.getDivisions().get(4).getAmount());
						prize = prize.add(lottoResult.getDivisions().get(4).getAmount());
					}
				}
				else if (winNumbers == 4)
				{
					log.info("6th prize: " + result.getNumbers().toString());
					log.info("Prize win $" + lottoResult.getDivisions().get(5).getAmount());
					prize = prize.add(lottoResult.getDivisions().get(5).getAmount());
				}
				else if (winNumbers == 3)
				{
					if (supNumbers > 0)
					{
						log.info("7th prize: " + result.getNumbers().toString());
						log.info("Prize win $" + lottoResult.getDivisions().get(6).getAmount());
						prize = prize.add(lottoResult.getDivisions().get(6).getAmount());
					}
				}
			}
			lottoDAO.updateTicketPrize(ozLottoTicket.getId(), prize, OZLottoTicket.class);
		}
	}

	public List<OZLottoTicket> findTicketsByDraw(int draw) {
		return lottoDAO.findTicketsByDraw(draw, OZLottoTicket.class);
	}

	public List<OZLottoTicket> findAllTickets() {
		return lottoDAO.findAllTickets(OZLottoTicket.class);
	}

	public List<OZLottoResult> findLast(int limit) {
		return lottoDAO.findLastResults(limit, OZLottoResult.class);
	}

	public OZLottoResult findResultByDraw(int draw) {
		return lottoDAO.findResultByDraw(draw, OZLottoResult.class);
	}

	public int supplementaries() {
		return 2;
	}

	public OZLottoTicket findByTicketId(String id) {
		return lottoDAO.findTicketById(id, OZLottoTicket.class);
	}

	@Override
	public List<JavaLabeledDocument> buildTrainingData(int max) {

		List<JavaLabeledDocument> numbers = new ArrayList<JavaLabeledDocument>();
		long id = 1l;
		for (OZLottoResult result: findLast(max))
		{
			String winText = "";
			String nonWinText = "";

			// non winning number
			for (int i = 1; i <= pool(); i++)
			{
				if ( result.getWinningNumbers().contains(i))
					winText += i + " ";
				else
					nonWinText += i + " ";
			}

			numbers.add(new JavaLabeledDocument(id++, winText, 1.0));
			numbers.add(new JavaLabeledDocument(id++, nonWinText, 0.0));
		}

		return numbers;
	}

	public CrossValidatorModel getCrossValidatorModel()
	{
		SparkSession spark = SparkSession
				.builder()
				.appName("getOZCrossValidatorModel")
				.getOrCreate();

		// $example on$
		// Prepare training documents, which are labeled.
		Dataset<Row> training = spark.createDataFrame(buildTrainingData(SAMPLE), JavaLabeledDocument.class);

		// Configure an ML pipeline, which consists of three stages: tokenizer, hashingTF, and lr.
		Tokenizer tokenizer = new Tokenizer()
		.setInputCol("text")
		.setOutputCol("words");
		HashingTF hashingTF = new HashingTF()
		.setNumFeatures(1000)
		.setInputCol("words")
		.setOutputCol("features");
		LogisticRegression lr = new LogisticRegression()
		.setMaxIter(3)
		.setRegParam(0.01);

		Pipeline pipeline = new Pipeline()
		.setStages(new PipelineStage[] {tokenizer, hashingTF, lr});

		// We use a ParamGridBuilder to construct a grid of parameters to search over.
		// With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
		// this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
		ParamMap[] paramGrid = new ParamGridBuilder()
		.addGrid(hashingTF.numFeatures(), new int[] {100, 1000})
		.addGrid(lr.regParam(), new double[] {0.1, 0.01})
		.build();

		// We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
		// This will allow us to jointly choose parameters for all Pipeline stages.
		// A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
		// Note that the evaluator here is a BinaryClassificationEvaluator and its default metric
		// is areaUnderROC.
		CrossValidator cv = new CrossValidator()
		.setEstimator(pipeline)
		.setEvaluator(new BinaryClassificationEvaluator())
		.setEstimatorParamMaps(paramGrid)
		.setNumFolds(2);  // Use 3+ in practice

		// Run cross-validation, and choose the best set of parameters.
		return cv.fit(training);
	}

	@Override
	public void generateNumberPredictions(String drawNumber) {
		// build model
    	super.buildForrestRandomModel(Integer.parseInt(drawNumber));

    	// DB Object
    	OZLottoPrediction ozLottoPrediction = new OZLottoPrediction();
    	ozLottoPrediction.setDrawNumber(drawNumber);

		//Build RandomForrest Model
		SparkSession spark = SparkSession
				.builder()
				.appName("OZLottoRandomForestClassifierExample")
				.getOrCreate();

		List<SinglePredictionObject> predictionObjects = forrestRandomPredict(spark, ozLottoPrediction);

		//spark.stop();

		ozLottoPrediction.setPredictionObjects(predictionObjects);
		lottoDAO.saveOrUpdateNumberPrediction(ozLottoPrediction);
	}

	@Override
	public List<OZLottoResult> findLastResultsFromDraw(int draw, int limit) {
		return lottoDAO.findLastResultsFromDraw(draw, limit, OZLottoResult.class);
	}

	@Override
	public List<OZLottoPrediction> findAllForestRandomPredictions() {
		return lottoDAO.findAllForestRandomPrediction(OZLottoPrediction.class);
	}

	@Override
	public OZLottoPrediction findForestRandomPredictionByDraw(int draw) {
		return lottoDAO.findAllForestRandomPredictionByDraw(String.valueOf(draw), OZLottoPrediction.class);
	}
}


text:
#include "AgentLayer.h"

#include "paddle/utils/Logging.h"

#include "paddle/utils/Stat.h"

namespace paddle {

REGISTER_LAYER(agent, AgentLayer);

bool AgentLayer::init(const LayerMap& layerMap,
                      const ParameterMap& parameterMap) {
  CHECK_EQ(config_.inputs_size(), 0);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setNeedGradient(true);
  return true;
}

void AgentLayer::forward(PassType passType) {
  Layer::forward(passType);

  Argument& realOutput = realLayer_->getOutput();
  int realHeight = realOutput.getBatchSize();
  CHECK_LE(numSamples_, realHeight);

  // get Arguments from real layers
  if (numSamples_ > 0 && numSamples_ < realHeight) {
    if (realOutput.ids) {
      output_.ids->subVecFrom(*realOutput.ids, 0, numSamples_);
    } else {
      output_.subArgFrom(realOutput, /* offset */ 0, numSamples_, getSize(),
                         useGpu_);
    }
  } else {
    output_ = realOutput;
  }
}

void SequenceAgentLayer::forward(PassType passType) {
  Layer::forward(passType);

  Argument& realOutput = realLayer_->getOutput();
  int realNumSequences = realOutput.getNumSequences();
  CHECK_LE(numSamples_, realNumSequences);

  // get Arguments from real layers
  if (numSamples_ > 0 && numSamples_ < realNumSequences) {
    int numRows = realOutput.sequenceStartPositions->
                  getData(false)[numSamples_];
    CHECK(!realOutput.ids) << "Not supported";
    output_.subArgFrom(realOutput, /* offset */ 0, numRows, getSize(), useGpu_,
                       /* trans */ false, /* seqFlag */ true,
                       /* seqStart */ 0, /* seqSize */ numSamples_ + 1);
  } else {
    output_ = realOutput;
  }
}

REGISTER_LAYER(sequence_agent, SequenceAgentLayer);

bool GatherAgentLayer::init(const LayerMap& layerMap,
                            const ParameterMap& parameterMap) {
  CHECK_EQ(config_.inputs_size(), 0);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setNeedGradient(true);
  return true;
}

void GatherAgentLayer::copyIdAndSequenceInfo(const Argument& input,
                                             const IVectorPtr& ids,
                                             const std::vector<int>& idIndex) {
  output_.sequenceStartPositions = input.sequenceStartPositions;
  output_.subSequenceStartPositions = input.subSequenceStartPositions;
  realLayers_.clear();
  allIds_ = ids;
  idIndex_ = idIndex;
}

void GatherAgentLayer::forward(PassType passType) {
  Layer::forward(passType);

  int height = allIds_->getSize();
  int width = this->getSize();
  resetOutput(height, width);
  idsVec_.resize(idIndex_.size());

  const MatrixPtr& outV = getOutputValue();

  for (size_t i = 0; i < realLayers_.size(); ++i) {
    const MatrixPtr& realV = realLayers_[i]->getOutputValue();
    idsVec_[i] = IVector::create(allIds_->getData() + idIndex_[i],
                                 /* size */ realV->getHeight(), useGpu_);
    realV->addToRows(*outV, *idsVec_[i]);
  }
}

void GatherAgentLayer::backward(const UpdateCallback& callback) {
  (void)callback;
  const MatrixPtr& outputGrad = getOutputGrad();

  for (size_t i = 0; i < realLayers_.size(); ++i) {
    const MatrixPtr& realG = realLayers_[i]->getOutputGrad();
    if (realG) {
      realG->selectRows(*outputGrad, *idsVec_[i]);
    }
  }
}

bool ScatterAgentLayer::init(const LayerMap& layerMap,
                             const ParameterMap& parameterMap) {
  CHECK_EQ(config_.inputs_size(), 0);
  if (!Layer::init(layerMap, parameterMap)) {
    return false;
  }
  setNeedGradient(true);
  return true;
}

void ScatterAgentLayer::forward(PassType passType) {
  Layer::forward(passType);
  CHECK_EQ(realLayer_->getDeviceId(), this->getDeviceId());

  if (realLayer_->getOutput().ids) {  // ids scatter
    IVector::resizeOrCreate(output_.ids, ids_->getSize(), useGpu_);
    output_.ids->selectFrom(*realLayer_->getOutput().ids, *ids_);
  } else {  // value scatter
    int width = this->getSize();
    if (realOutArg_.value) {
      output_.subArgFrom(realOutArg_, /* offset */ idIndex_ * width, idSize_,
                         width, useGpu_);
    } else {  // used in generation
      int height = ids_->getSize();
      resetOutput(height, width);

      const MatrixPtr& outV = getOutputValue();
      const MatrixPtr& realV = realLayer_->getOutputValue();
      outV->selectRows(*realV, *ids_);
    }
  }
}

void ScatterAgentLayer::backward(const UpdateCallback& callback) {
  (void)callback;

  const MatrixPtr& outputGrad = realOutArg_.grad;
  const MatrixPtr& realGrad = realLayer_->getOutputGrad();
  if (realGrad) {
    // for agent in inFrameLines and memoryFrameLines,
    // only first scatterAgentLayer should do addToRows in backward
    if (idIndex_ == 0) {
      outputGrad->addToRows(*realGrad, *ids_);
    }
  }
}

REGISTER_LAYER(gather_agent, GatherAgentLayer);
REGISTER_LAYER(scatter_agent, ScatterAgentLayer);

void SequenceGatherAgentLayer::forward(PassType passType) {
  Layer::forward(passType);
  int height = 0;
  int* starts = output_.subSequenceStartPositions->getMutableData(false);
  IVectorPtr idReal = realLayers_[0]->getOutputLabel();
  if (idReal) {
    // Gather generator.idsVec
    // if is beam search generation result. Get first result.
    if (idReal->getData()[idReal->getSize() - 1] == -1) {
      for (size_t i = 0; i < realLayers_.size(); ++i) {
        // The first element stores first result size
        idReal = realLayers_[i]->getOutputLabel();
        idReal->subVecFrom(*idReal, 1, idReal->getData()[0]);
      }
    }
    for (size_t i = 0; i < realLayers_.size(); ++i) {
      CHECK(realLayers_[i]->getOutputLabel());
      starts[i] = height;
      height += realLayers_[i]->getOutputLabel()->getSize();
    }
    starts[realLayers_.size()] = height;
    output_.sequenceStartPositions->getMutableData(false)[1] = height;

    IVector::resizeOrCreate(output_.ids, height, false);
    for (size_t i = 0; i < realLayers_.size(); ++i) {
      output_.ids->subVec(starts[i], starts[i + 1] - starts[i])
          ->copyFrom(*realLayers_[i]->getOutputLabel());
    }
  } else {
    // Gather output.value, same as GatherAgentLayer
    CHECK(output_.subSequenceStartPositions);
    GatherAgentLayer::forward(passType);
  }
}

void SequenceScatterAgentLayer::forward(PassType passType) {
  Layer::forward(passType);
  CHECK_EQ(realLayer_->getDeviceId(), this->getDeviceId());
  CHECK(!realLayer_->getOutput().ids) << "Not supported";

  const Argument& input = realLayer_->getOutput();
  CHECK_EQ(input.value->getWidth(), this->getSize());
  int width = this->getSize();

  AsyncGpuBlock asyncGpuBlock;
  REGISTER_TIMER_INFO("SequenceAgentLayerForward", getName().c_str());

  if (realOutArg_.value) {
    CHECK(realOutArg_.sequenceStartPositions);
    output_.subArgFrom(realOutArg_, /* offset */ idIndex_ * width, idSize_,
                       width, useGpu_, /* trans */ false, /* seqFlag */ true,
                       /* seqStart */ seqStartPosIndex_,
                       /* seqSize */ numSequences_);
  } else {
    // used in generation
    int height = 0;
    size_t numSequences = ids_->getSize();
    const int* starts = input.getCpuStartPositions();
    size_t size = input.hasSubseq() ? input.getNumSubSequences()
                                    : input.getNumSequences();
    const int* cpuIds = cpuIds_->getData();

    for (size_t i = 0; i < numSequences; ++i) {
      size_t seqId = cpuIds[i];
      CHECK_LT(seqId, size);
      height += starts[seqId + 1] - starts[seqId];
    }
    reserveOutput(height, width);

    const MatrixPtr& outputValue = getOutputValue();

    CHECK_NE(input.sequenceStartPositions.get(),
             output_.sequenceStartPositions.get());
    ICpuGpuVector::resizeOrCreate(output_.sequenceStartPositions,
                                   numSequences + 1, false);
    int* outStarts = output_.sequenceStartPositions->getMutableData(false);

    IVector::resizeOrCreate(cpuInputStartPos_, height, false);
    int* inStarts = cpuInputStartPos_->getData();
    size_t offsetOut = 0;
    for (size_t i = 0; i < numSequences; ++i) {
      outStarts[i] = offsetOut;
      size_t seqId = cpuIds[i];
      int size = starts[seqId + 1] - starts[seqId];
      for (int j = 0; j < size; j++) {
        inStarts[offsetOut + j] = starts[seqId] + j;
      }
      offsetOut += size;
    }
    outStarts[numSequences] = offsetOut;

    if (useGpu_) {
      IVector::resizeOrCreate(inputStartPos_, height, true);
      inputStartPos_->copyFrom(*cpuInputStartPos_, HPPL_STREAM_DEFAULT);
    } else {
      inputStartPos_ = cpuInputStartPos_;
    }
    outputValue->copyByRowIndex(*input.value, *inputStartPos_);
  }
}

REGISTER_LAYER(sequence_gather_agent, SequenceGatherAgentLayer);
REGISTER_LAYER(sequence_scatter_agent, SequenceScatterAgentLayer);

}  // namespace paddle


text: module.exports = require('./configurations/default');


text:
require 'rubygems'
require 'test/unit'

$LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
require 'cql_ruby'

class Test::Unit::TestCase
end