text:
<!doctype html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Spacial - Blog timeline</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="shortcut icon" href="images/favicon.ico">

  <link rel="stylesheet" type="text/css" href="scss/bootstrap/bootstrap.css" />
  <link rel="stylesheet" type="text/css" href="dist/theme.min.css" />

        Spacial

      <button class="navbar-toggler" data-toggle="collapse" data-target="#navbar-collapse">

      </button>

              Home pages

              Business
              Web app
              Features showcase
              Creative agency
              App showcase
              App showcase 2
              App showcase 3
              App showcase 4
              Hero Slider
              Photography
              Dark background
              Restaurant
              Event
              Video background
              Intro

              Blogs

              Blog list
              Blog columns
              Blog grid
              Blog sidebar
              Blog masonry
              Blog timeline
              Single blog post
              Single blog post 2
              Single blog post 3

              Pages

                  About us

                  About us 1
                  About us 2

                  Portfolio

                  2 columns
                  3 columns
                  4 columns

                  Contact

                  Contact us 1
                  Contact us 2
                  Contact us project

              Project showcase
              Pricing
              Pricing charts
              Careers
              Careers job post
              Support
              Support topic
              Customer stories
              Single customer story

              Sign up
              Sign in
              Recover password
              Timeline
              Coming soon
              API docs

              Features

                  Headers

                  Light
                  Dark
                  Transparent light
                  Transparent dark
                  Transparent fixed light
                  Transparent fixed dark
                  Sidebar left
                  Sidebar right
                  Navbar left
                  Dark submenu
                  Bottom fixed
                  Logo center
                  All center
                  Full width

                  Footers

                  Dark
                  Light
                  Big Menu
                  Sign up
                  Agency

                  Covers

                  Panorama View
                  360º Image

                  Email templates

                    Newsletter

                    Receipt

                    Simple announcement

                    Formal text

              Grid system
              Animations
              Typography

              Components

                   Alerts
                   Animations
                   Badges
                   Buttons
                   Button groups
                   Cards

                   Carousel
                   Accordion
                   Call to action
                   Dropdowns
                   Forms
                   Input groups

                   Icons
                   List groups
                   Modals
                   Navs
                   Navbars
                   New plugins

                   Progress bars
                   Stats cards
                   Tables
                   Typography

              Shop

              Home page
              Products grid
              Products list
              Products grid w/ sidebar
              Products list w/ sidebar
              Single product
              Cart
              Search results
              Checkout
              Checkout ship & payment
              Checkout confirmation
              My account order history
              My account wishlist
              My account profile
              Order invoice
              Sign up
              Sign in

            Theme Docs

        <form>
          <input type="text" class="form-control" placeholder="Search the blog...">

        </form>

          Latest news

        Latest updates and interesting news from us

Art is part of life

              Some people say design is about solving problems.

              Design is about cultural invention.

                10 ways to improve your web development skills in just 1 month

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take? The cat in the window that you got from your mother, or the chair you have?

              Read more

              New Feature

            12 December

                Spacial Themes announce the addition of new pages and products.

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take? The cat in the window that you got from your mother, or the chair you have?

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum.

              Read more

              New Feature

            12 December

Day at the Beach

              Some people say design is about solving problems.

              Design is about cultural invention.

                Spacial Themes announce the addition of new pages and products.

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take? The cat in the window that you got from your mother, or the chair you have?

              Read more

              New Feature

            12 December

Some Forest

              Some people say design is about solving problems.

              Design is about cultural invention.

                What Video Game Designers Can Teach You About Influencing To Buy

              Checkout is an embeddable payment form for desktop, tablet, and mobile devices. It works within your site—customers can pay instantly, without being redirected away to complete the transaction.

              This is designed to make showing off your best photos extremely fast and simple. There aren't many settings to configure.

              Read more

              New Feature

            12 December

                Spacial Themes announce the addition of new pages and products.

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take? The cat in the window that you got from your mother, or the chair you have?

              Read more

              New Feature

            12 December

                Spacial Themes announce the addition of new pages and products.

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take? The cat in the window that you got from your mother, or the chair you have?

              Read more

              New Feature

            12 December

Our Best Vacations

              Some people say design is about solving problems.

              Design is about cultural invention.

Our Best Vacations

              Some people say design is about solving problems.

              Design is about cultural invention.

                Spacial Themes announce the addition of new pages and products.

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take? The cat in the window that you got from your mother, or the chair you have?

              Read more

              News

            03 January

                Spacial Themes announce the addition of new pages and products.

              Functionality is so over-valued in design, and we've kept design very small in that way. Functionality is the sheer minimum. If your house burns down, what do you take?

              The cat in the window that you got from your mother, or the chair you have?

              Read more

              News

            03 January

Our Best Vacations

              Some people say design is about solving problems.

              Design is about cultural invention.

        Older posts

            About spacial

              Home Pages

              Theme Features

              Services

              StoreFront

              Portfolio

            Connect with us

                Instagram

                Twitter

                Dribbble

                Facebook

            Get awesome updates

            Enter your email address for news and product launches in the Awesome Space.

          <form class="newsletter-form" autocomplete="off">
            <input type="email" id="mc-email" class="form-control" placeholder="Email address" required />

            <button type="submit">

            </button>

          </form>

Privacy

Legal

Language


text:
title: XML Add Attribute
linkText: Add Attribute
description: Add attribute XML format
---

# XML Add Attribute

## Description

Will add an attribute to an already existing node in the XML

## Notes

This has been deprecated in favour of [SetAttribute](../set-attribute)

## Example

### Base File

```XML
{% raw %}
<root>
    <node>value</node>
</root>
{% endraw %}
```

### Substitution

```XML
{% raw %}
<Change type="AddAttribute" xPath="/root/node" attributeName="attrVal" value="true" />
{% endraw %}
```

### Output

```XML
{% raw %}
<root>
    <node attrVal="true">value</node>
</root>
{% endraw %}
```

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\FuncionarioLaboratorio;

/**
 * FuncionarioLaboratorioSearch represents the model behind the search form about `app\models\FuncionarioLaboratorio`.
 */
class FuncionarioLaboratorioSearch extends FuncionarioLaboratorio
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['FULA_ID', 'FUNC_ID', 'LABO_ID'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = FuncionarioLaboratorio::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'FULA_ID' => $this->FULA_ID,
            'FUNC_ID' => $this->FUNC_ID,
            'LABO_ID' => $this->LABO_ID,
        ]);

        return $dataProvider;
    }

    public function search2($params)
    {
       $consulta='select * FROM TBL_FUNCIONALABORATORIO  WHERE LABO_ID ='.$params;
        $query = FuncionarioLaboratorio::findBySql($consulta);
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!$this->validate()) {
            return $dataProvider;
        }
        return $dataProvider;
    }
}


text:
all: bandwidth-test multi-bandwidth-test

bandwidth-test: bandwidth-test.c
	gcc -g bandwidth-test.c -o bandwidth-test -lpthread

multi-bandwidth-test: multi-bandwidth-test.c
	gcc -g multi-bandwidth-test.c -o multi-bandwidth-test -lpthread


text:
setup.git
=========
Clone and run this on a new EC2 instance running Ubuntu 12.04.2 LTS to
configure both the machine and your individual development environment as
follows:

```sh
cd $HOME
sudo apt-get install -y git-core
git clone https://github.com/startup-class/setup.git
./setup/setup.sh
```

See also http://github.com/startup-class/dotfiles and
[Startup Engineering Video Lectures 4a/4b](https://class.coursera.org/startup-001/lecture/index)
for more details.


text:
package org.wso2.carbon.automation.extensions.jmeter;

import java.io.File;

public class JMeterTest {
    private String jmeterLogLevel = "1";
    private File testFile = null;
    private File jMeterPropertyFile = null;

    public JMeterTest(File testScript) {
        testFile = testScript;
    }

    public String getLogLevel() {
        return this.jmeterLogLevel;
    }

    public void setLogLevel(String level) {
        this.jmeterLogLevel = level;
    }

    public File getTestFile() {
        return this.testFile;
    }

    public File getJMeterPropertyFile() {
        return this.jMeterPropertyFile;
    }

    public void setJMeterPropertyFile(File jMeterPropertyFile) {
        this.jMeterPropertyFile = jMeterPropertyFile;
    }
}


text:
export class AsyncInMemoryStore {
  private store: {[key: string]: string}

  public constructor() {
    this.store = {}
  }

  private secureKey(key: string, login: string): string {
    return `__key/${key}/${login}`
  }

  public setItem(key: string, loginOrValue: string, secureValue?: string): Promise<void> {
    if (secureValue) {
      const internalKey = this.secureKey(key, loginOrValue)
      this.store[internalKey] = secureValue
    } else {
      this.store[key] = loginOrValue
    }
    return Promise.resolve()
  }

  public getItem(key: string, login?: string): Promise<string | null> {
    const internalKey = login ? this.secureKey(key, login) : key
    return Promise.resolve(this.store[internalKey] || null)
  }

  public deleteItem(key: string, login: string): Promise<boolean> {
    delete this.store[this.secureKey(key, login)]
    return Promise.resolve(true)
  }
}


text:
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "multienumattributesaver.h"
#include "multivalueattributesaverutils.h"
#include <vespa/searchcommon/attribute/multivalue.h>

#include <vespa/log/log.h>
LOG_SETUP(".searchlib.attribute.multi_enum_attribute_saver");

using vespalib::GenerationHandler;
using search::multivalueattributesaver::CountWriter;
using search::multivalueattributesaver::WeightWriter;

namespace search {

namespace {

/*
 * Class to write enum indexes mapped over to either enum values
 * or values, depending on the requirements of the save target.
 */
class DatWriter
{
    std::vector<IEnumStore::Index>        _indexes;
    const EnumAttributeSaver::Enumerator &_enumerator;
    std::unique_ptr<search::BufferWriter> _datWriter;
    std::function<bool()>                 _compaction_interferred;

public:
    DatWriter(IAttributeSaveTarget &saveTarget,
              const EnumAttributeSaver::Enumerator &enumerator,
              std::function<bool()> compaction_interferred)
        : _indexes(),
          _enumerator(enumerator),
          _datWriter(saveTarget.datWriter().allocBufferWriter()),
          _compaction_interferred(compaction_interferred)
    {
        assert(saveTarget.getEnumerated());
        _indexes.reserve(1000);
    }

    ~DatWriter()
    {
        assert(_indexes.empty());
        _datWriter->flush();
    }

    void flush()
    {
        if (!_indexes.empty()) {
            for (auto ref : _indexes) {
                uint32_t enumValue = _enumerator.map_entry_ref_to_enum_value_or_zero(ref);
                assert(enumValue != 0u || _compaction_interferred());
                // Enumerator enumerates known entry refs (based on
                // dictionary tree) to values >= 1, but file format
                // starts enumeration at 0.
                --enumValue;
                _datWriter->write(&enumValue, sizeof(uint32_t));
            }
            _indexes.clear();
        }
    }

    template <typename MultiValueT>
    void
    writeValues(vespalib::ConstArrayRef<MultiValueT> values) {
        for (const MultiValueT &valueRef : values) {
            if (_indexes.size() >= _indexes.capacity()) {
                flush();
            }
            _indexes.push_back(multivalue::get_value_ref(valueRef).load_acquire());
        }
    }
};

}

template <typename MultiValueT>
MultiValueEnumAttributeSaver<MultiValueT>::
MultiValueEnumAttributeSaver(GenerationHandler::Guard &&guard,
                             const attribute::AttributeHeader &header,
                             const MultiValueMapping &mvMapping,
                             const IEnumStore &enumStore)
    : Parent(std::move(guard), header, mvMapping),
      _mvMapping(mvMapping),
      _enumSaver(enumStore),
      _enum_store(enumStore),
      _compaction_count(enumStore.get_compaction_count())
{
}

template <typename MultiValueT>
bool
MultiValueEnumAttributeSaver<MultiValueT>::compaction_interferred() const
{
    return _compaction_count != _enum_store.get_compaction_count();
}

template <typename MultiValueT>
MultiValueEnumAttributeSaver<MultiValueT>::~MultiValueEnumAttributeSaver() = default;

template <typename MultiValueT>
bool
MultiValueEnumAttributeSaver<MultiValueT>::
onSave(IAttributeSaveTarget &saveTarget)
{
    bool compaction_broke_save = false;
    CountWriter countWriter(saveTarget);
    WeightWriter<multivalue::is_WeightedValue_v<MultiValueType>> weightWriter(saveTarget);
    DatWriter datWriter(saveTarget, _enumSaver.get_enumerator(),
                        [this]() { return compaction_interferred(); });
    _enumSaver.writeUdat(saveTarget);
    _enumSaver.get_enumerator().enumerateValues();
    for (uint32_t docId = 0; docId < _frozenIndices.size(); ++docId) {
        vespalib::datastore::EntryRef idx = _frozenIndices[docId];
        vespalib::ConstArrayRef<MultiValueType> handle(_mvMapping.getDataForIdx(idx));
        countWriter.writeCount(handle.size());
        weightWriter.writeWeights(handle);
        datWriter.writeValues(handle);
        if (((docId % 0x1000) == 0) && compaction_interferred()) {
            compaction_broke_save = true;
            break;
        }
    }
    datWriter.flush();
    _enumSaver.clear();
    if (compaction_interferred()) {
        compaction_broke_save = true;
    }
    if (compaction_broke_save) {
        LOG(warning, "Aborted save of attribute vector to '%s' due to compaction of unique values", get_file_name().c_str());
    }
    return !compaction_broke_save;
}

using EnumIdxArray = vespalib::datastore::AtomicEntryRef;
using EnumIdxWset = multivalue::WeightedValue<vespalib::datastore::AtomicEntryRef>;

template class MultiValueEnumAttributeSaver<EnumIdxArray>;
template class MultiValueEnumAttributeSaver<EnumIdxWset>;

}  // namespace search


text:
from threading import Thread
from datetime import datetime, timedelta
import time

from app import db
from app.models import PackageModel
from config import REMOVE_PACKAGES_OLDER_THAN_HOURS, RUN_CLEANER_EVERY_SECONDS

class DatabaseCleaner(Thread):
    """
    Provide database automatic cleaning
    """
    def __init__(self, name='database_cleaner'):
        Thread.__init__(self, name=name)

    def run(self):
        """
        Run database cleaning procedure in a periodic loop
        :return: None
        """
        while True:
            current_time = datetime.utcnow()
            maximum_old_time = current_time - timedelta(hours=REMOVE_PACKAGES_OLDER_THAN_HOURS)

            old_packages = db.session.query(PackageModel).filter(PackageModel.sent_time < maximum_old_time)
            old_packages.delete()
            db.session.commit()

            time.sleep(RUN_CLEANER_EVERY_SECONDS)


text:
package io.skysail.server.rendering.test;

import static org.hamcrest.CoreMatchers.hasItems;
import static org.junit.Assert.assertThat;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.junit.Test;

import io.skysail.server.rendering.RenderingMode;

public class RenderingModeTest {

    @Test
    public void testValues() {
        List<String> values = Arrays.stream(RenderingMode.values()).map(v -> v.name()).collect(Collectors.toList());
        assertThat(values,hasItems("DEFAULT", "DEBUG", "EDIT"));
    }
}


text:
package gitlab

import (
	"github.com/plouc/go-gitlab-client/test"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestGitlab_Projects(t *testing.T) {
	ts := test.CreateMockServer(t, []string{
		"projects/projects",
	})
	defer ts.Close()
	gitlab := NewGitlab(ts.URL, "", "")

	projects, meta, err := gitlab.Projects(nil)

	assert.NoError(t, err)

	assert.Equal(t, len(projects.Items), 2)

	assert.IsType(t, new(ResponseMeta), meta)
	assert.Equal(t, 1, meta.Page)
	assert.Equal(t, 10, meta.PerPage)
}

/*
func TestProject(t *testing.T) {
	ts, gitlab := Stub("stubs/projects/show.json")
	project, err := gitlab.Project("1")

	assert.NoError(t, err)
	assert.IsType(t, new(Project), project)
	assert.Equal(t, project.SshRepoUrl, "git@example.com:diaspora/diaspora-project-site.git")
	assert.Equal(t, project.HttpRepoUrl, "http://example.com/diaspora/diaspora-project-site.git")
	assert.Equal(t, project.WebUrl, "http://example.com/diaspora/diaspora-project-site")
	defer ts.Close()
}

func TestAddProject(t *testing.T) {
	ts, gitlab := Stub("stubs/projects/add.json")
	defer ts.Close()

	project := &Project{
		Name:        "Diaspora Client",
		Path:        "diaspora-client",
		NamespaceId: 3,
		Visibility:  VisibilityPrivate,
	}
	newProject, err := gitlab.AddProject(project)

	assert.NoError(t, err)
	assert.Equal(t, newProject.Name, project.Name)
	assert.Equal(t, newProject.Description, project.Description)
	assert.Equal(t, newProject.SshRepoUrl, "git@example.com:diaspora/diaspora-client.git")
	assert.Equal(t, newProject.HttpRepoUrl, "http://example.com/diaspora/diaspora-client.git")
	assert.Equal(t, newProject.WebUrl, "http://example.com/diaspora/diaspora-client")
}

func TestUpdateProject(t *testing.T) {
	ts, gitlab := Stub("stubs/projects/show.json")
	project := Project{
		Description: "Project Description",
	}

	_, err := gitlab.UpdateProject("1", &project)
	assert.NoError(t, err)
	defer ts.Close()
}

func TestProjectBranches(t *testing.T) {
	ts, gitlab := Stub("stubs/projects/branches/index.json")
	branches, err := gitlab.ProjectBranches("1")

	assert.NoError(t, err)
	assert.Equal(t, len(branches), 2)
	defer ts.Close()
}

func TestRemoveProject(t *testing.T) {
	ts, gitlab := Stub("stubs/projects/remove.json")
	defer ts.Close()

	result, err := gitlab.RemoveProject("1")

	assert.NoError(t, err)
	assert.Equal(t, result, true)
}
*/


text:
layout: post
title: "Schedule updated"
categories:
---
The [class schedule]({{ site.baseurl }}/schedule) has been updated to reflect some changes in the recent lecture topics, and includes due dates for the new homework.

The reading schedule has not changed.


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Address extends Model
{
    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = "addresses";

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        "user_id",
        "title",
        "phone_number",
        "line_1",
        "line_2",
        "line_3",
        "neighborhood",
        "city",
        "description",
    ];

    public function user()
    {
        return $this->belongsTo("App\User");
    }

    public function orders()
    {
        return $this->hasMany("App\Order");
    }

    public function __toString()
    {
        return $this->attributes["line_1"];
    }
}


text:
import base64
import errno
import os
import shelve
import uuid

from Crypto.PublicKey import RSA
from oslo_config import cfg

from solum.api.handlers import assembly_handler
from solum.api.handlers import handler
from solum.common import clients
from solum.common import exception
from solum.common import keystone_utils
from solum.common import repo_utils
from solum.deployer import api as deploy_api
from solum import objects
from solum.objects import assembly
from solum.objects import image
from solum.openstack.common import log as logging

API_PARAMETER_OPTS = [
    cfg.StrOpt('system_param_store',
               default='database',
               help="Tells where to store system generated parameters, e.g. "
                    "deploy keys for cloning a private repo. "
                    "Options: database, barbican, local_file. "
                    "Defaults to database"),
    cfg.StrOpt('system_param_file',
               default='/etc/solum/secrets/git_secrets.db',
               help="The local file to store system generated parameters when "
                    "system_param_store is set to 'local_file'"),
]

def list_opts():
    yield 'api', API_PARAMETER_OPTS

CONF = cfg.CONF
CONF.register_opts(API_PARAMETER_OPTS, group='api')

LOG = logging.getLogger(__name__)

ASSEMBLY_STATES = assembly.States
IMAGE_STATES = image.States

sys_param_store = CONF.api.system_param_store

class PlanHandler(handler.Handler):
    """Fulfills a request on the plan resource."""

    def get(self, id):
        """Return a plan."""
        return objects.registry.Plan.get_by_uuid(self.context, id)

    def update(self, id, data):
        """Modify existing plan."""
        db_obj = objects.registry.Plan.get_by_uuid(self.context, id)
        db_obj.raw_content.update(dict((k, v) for k, v in data.items()
                                       if k != 'parameters'))
        to_update = {'raw_content': db_obj.raw_content}
        if 'name' in data:
            to_update['name'] = data['name']

        updated = objects.registry.Plan.update_and_save(self.context,
                                                        id, to_update)
        return updated

    def delete(self, id):
        """Delete existing plan."""
        db_obj = objects.registry.Plan.get_by_uuid(self.context, id)
        # Delete the trust.
        keystone_utils.delete_delegation_token(self.context, db_obj.trust_id)
        self._delete_params(db_obj.id)
        deploy_api.API(context=self.context).destroy_app(
            app_id=db_obj.id)

    def create(self, data):
        """Create a new plan."""
        db_obj = objects.registry.Plan()
        if 'name' in data:
            db_obj.name = data['name']
        db_obj.uuid = str(uuid.uuid4())
        db_obj.user_id = self.context.user
        db_obj.project_id = self.context.tenant
        db_obj.trigger_id = str(uuid.uuid4())

        # create a delegation trust_id\token, if required
        db_obj.trust_id = keystone_utils.create_delegation_token(self.context)
        db_obj.username = self.context.user_name

        sys_params = self._generate_sys_params(db_obj, data)
        user_params = data.get('parameters', {})
        self._process_ports(user_params, data)

        db_obj.raw_content = dict((k, v) for k, v in data.items()
                                  if k != 'parameters')
        db_obj.create(self.context)
        if user_params or sys_params:
            self._create_params(db_obj.id, user_params, sys_params)
        return db_obj

    def get_all(self):
        """Return all plans."""
        return objects.registry.PlanList.get_all(self.context)

    def _generate_sys_params(self, plan_obj, data):
        # NOTE: this method may modify the input 'data'
        sys_params = {}
        deploy_keys = []
        for artifact in data.get('artifacts', []):
            if (('content' not in artifact) or
                    ('private' not in artifact['content']) or
                    (not artifact['content']['private'])):
                continue
            new_key = RSA.generate(2048)
            public_key = new_key.publickey().exportKey("OpenSSH")
            private_key = new_key.exportKey("PEM")
            artifact['content']['public_key'] = public_key
            deploy_keys.append({'source_url': artifact['content']['href'],
                                'private_key': private_key})
        if deploy_keys:
            encoded_payload = base64.b64encode(bytes(str(deploy_keys)))
            repo_deploy_keys = ''
            if sys_param_store == 'database':
                repo_deploy_keys = encoded_payload
            elif sys_param_store == 'local_file':
                secrets_file = CONF.api.system_param_file
                try:
                    os.makedirs(os.path.dirname(secrets_file), 0o700)
                except OSError as ex:
                    if ex.errno != errno.EEXIST:
                        raise
                s = shelve.open(secrets_file)
                try:
                    s[plan_obj.uuid] = encoded_payload
                    repo_deploy_keys = plan_obj.uuid
                finally:
                    s.close()
            elif sys_param_store == 'barbican':
                client = clients.OpenStackClients(None).barbican().admin_client
                repo_deploy_keys = client.secrets.create(
                    name=plan_obj.uuid,
                    payload=encoded_payload,
                    payload_content_type='application/octet-stream',
                    payload_content_encoding='base64').store()

            if repo_deploy_keys:
                sys_params['REPO_DEPLOY_KEYS'] = repo_deploy_keys
        return sys_params

    def _process_ports(self, user_params, data):
        # NOTE: This method may modify the input 'user_params' and 'data'
        for artifact in data.get('artifacts', []):
            new_ports = None
            ports = artifact.get('ports', [])
            if isinstance(ports, list):
                new_ports = list(it for it in set(ports) if it is not None)
            elif isinstance(ports, dict):
                new_ports = list(it for it in set(ports.values())
                                 if it is not None)
                user_params.update(dict((k, v) for k, v in ports.items()
                                        if (k and v)))
            elif type(ports) is int:
                new_ports = [ports]
            artifact['ports'] = new_ports or [80]

    def trigger_workflow(self, trigger_id, commit_sha='',
                         status_url=None, collab_url=None, workflow=None):
        """Get trigger by trigger id and start git workflow associated."""
        # Note: self.context will be None at this point as this is a
        # non-authenticated request.
        plan_obj = objects.registry.Plan.get_by_trigger_id(None, trigger_id)
        # get the trust context and authenticate it.
        try:
            self.context = keystone_utils.create_delegation_context(
                plan_obj, self.context)
            self.context.tenant = plan_obj.project_id
            self.context.user = plan_obj.user_id
            self.context.user_name = plan_obj.username

        except exception.AuthorizationFailure as auth_ex:
            LOG.warning(auth_ex)
            return

        artifacts = plan_obj.raw_content.get('artifacts', [])
        for arti in artifacts:
            if repo_utils.verify_artifact(arti, collab_url):
                self._build_artifact(plan_obj, artifact=arti,
                                     commit_sha=commit_sha,
                                     status_url=status_url,
                                     workflow=workflow)

    def _build_artifact(self, plan, artifact, verb='build', commit_sha='',
                        status_url=None, workflow=None):

        if workflow is None:
            workflow = ['unittest', 'build', 'deploy']
        ahand = assembly_handler.AssemblyHandler(self.context)
        plandata = {
            'plan_id': plan.id,
            'name': "%s-%s" % (plan.name, artifact['name']),
            'description': '',
            'workflow': workflow,
            }
        ahand.create(plandata, commit_sha=commit_sha, status_url=status_url)

    def _create_params(self, plan_id, user_params, sys_params):
        param_obj = objects.registry.Parameter()
        param_obj.plan_id = plan_id
        if user_params:
            param_obj.user_defined_params = user_params
        if sys_params:
            param_obj.sys_defined_params = sys_params
        param_obj.create(self.context)

    def _delete_params(self, plan_id):
        param_obj = objects.registry.Parameter.get_by_plan_id(self.context,
                                                              plan_id)
        if param_obj:
            sys_params = param_obj.sys_defined_params
            if sys_params and 'REPO_DEPLOY_KEYS' in sys_params:
                # sys_params['REPO_DEPLOY_KEYS'] is just a reference to
                # deploy keys when sys_param_store is not 'database'
                if sys_param_store == 'local_file':
                    secrets_file = CONF.api.system_param_file
                    s = shelve.open(secrets_file)
                    del s[sys_params['REPO_DEPLOY_KEYS'].encode("utf-8")]
                    s.close()
                elif sys_param_store == 'barbican':
                    osc = clients.OpenStackClients(None)
                    client = osc.barbican().admin_client
                    client.secrets.delete(sys_params['REPO_DEPLOY_KEYS'])

            param_obj.destroy(self.context)


text:
cask "motrix" do
  version "1.5.15"
  sha256 "f918e23d01fabe75d1970d7839e80a2a2b220b9f66b9ae69d056734e8bb9046c"

  # github.com/ was verified as official when first introduced to the cask
  url "https://github.com/agalwood/Motrix/releases/download/v#{version}/Motrix-#{version}.dmg"
  appcast "https://github.com/agalwood/Motrix/releases.atom"
  name "Motrix"
  homepage "https://motrix.app/"

  app "Motrix.app"

  zap trash: [
    "~/Library/Application Support/Motrix",
    "~/Library/Preferences/net.agalwood.Motrix.plist",
    "~/Library/Saved Application State/net.agalwood.Motrix.savedState",
    "~/Library/Logs/Motrix",
    "~/Library/Caches/net.agalwood.Motrix",
  ]
end


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

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

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

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

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

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

package tuwien.auto.calimero.knxnetip.servicetype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import tuwien.auto.calimero.cemi.CEMI;
import tuwien.auto.calimero.cemi.CEMIDevMgmt;
import tuwien.auto.calimero.cemi.CEMIFactory;
import tuwien.auto.calimero.exception.KNXFormatException;
import tuwien.auto.calimero.exception.KNXIllegalArgumentException;

/**
 * Common service request structure, used to send requests over established KNXnet/IP
 * communication channels.
 *

 * Such a service request is used for tunnel or device management connections. It carries
 * a cEMI frame containing the actual KNX frame data.

 * A service request is contained in the body of a KNXnet/IP frame.
 *
 * @see tuwien.auto.calimero.knxnetip.servicetype.ServiceAck
 */
public class ServiceRequest extends ServiceType
{
	private static final int CONN_HEADER_SIZE = 4;
	private final short channelid;
	private final short seq;
	private CEMI cemi;

	/**
	 * Creates a new service request out of a byte array.
	 *

	 *
	 * @param serviceType service request type identifier describing the request in
	 *        data, 0 <= type <= 0xFFFF
	 * @param data byte array containing a service request structure
	 * @param offset start offset in bytes of request in data
	 * @param length the length in bytes of the whole request contained in
	 *        data
	 * @throws KNXFormatException if buffer is too short for request, on unsupported
	 *         service type or connection header structure
	 */
	public ServiceRequest(int serviceType, byte[] data, int offset, int length)
		throws KNXFormatException
	{
		this(serviceType, data, offset, length, null);
		if (svcType == KNXnetIPHeader.TUNNELING_REQ)
			cemi = CEMIFactory.create(data, offset + CONN_HEADER_SIZE, length
				- CONN_HEADER_SIZE);
		else if (svcType == KNXnetIPHeader.DEVICE_CONFIGURATION_REQ)
			cemi = new CEMIDevMgmt(data, offset + CONN_HEADER_SIZE, length
				- CONN_HEADER_SIZE);
		else
			throw new KNXIllegalArgumentException("unsupported service request type");
	}

	/**
	 * Creates a new service request.
	 *

	 *
	 * @param serviceType service request type identifier, 0 <= type <= 0xFFFF
	 * @param channelID channel ID of communication this request belongs to, 0 <= id
	 *        <= 255
	 * @param seqNumber the sending sequence number of the communication channel, 0 <=
	 *        number <= 255
	 * @param frame cEMI frame carried with the request
	 */
	public ServiceRequest(int serviceType, int channelID, int seqNumber, CEMI frame)
	{
		super(serviceType);
		if (serviceType < 0 || serviceType > 0xffff)
			throw new KNXIllegalArgumentException(
				"service request out of range [0..0xffff]");
		if (channelID < 0 || channelID > 0xff)
			throw new KNXIllegalArgumentException("channel ID out of range [0..0xff]");
		if (seqNumber < 0 || seqNumber > 0xff)
			throw new KNXIllegalArgumentException(
				"sequence number out of range [0..0xff]");
		channelid = (short) channelID;
		seq = (short) seqNumber;
		cemi = CEMIFactory.copy(frame);
	}

	// frame might be null, toByteArray will throw NPE then
	ServiceRequest(int serviceType, byte[] data, int offset, int length, CEMI frame)
		throws KNXFormatException
	{
		super(serviceType);
		if (length < CONN_HEADER_SIZE + 1)
			throw new KNXFormatException("buffer too short for service request");
		final ByteArrayInputStream is = new ByteArrayInputStream(data, offset, length);
		if (is.read() != CONN_HEADER_SIZE)
			throw new KNXFormatException("unsupported connection header");
		channelid = (short) is.read();
		seq = (short) is.read();
		/* final int reserved = */is.read();
		cemi = frame;
	}

	/**
	 * Returns the service type identifier of the request.
	 *

	 *
	 * @return service type as unsigned short
	 */
	public final int getServiceType()
	{
		return svcType;
	}

	/**
	 * Returns the communication channel identifier associated with the request.
	 *

	 *
	 * @return communication channel ID as unsigned byte
	 */
	public final short getChannelID()
	{
		return channelid;
	}

	/**
	 * Returns the sequence number of the sending endpoint.
	 *

	 *
	 * @return sequence number as unsigned byte
	 */
	public final short getSequenceNumber()
	{
		return seq;
	}

	/**
	 * Returns the cEMI frame carried by the request.
	 *

	 *
	 * @return a cEMI type
	 */
	public final CEMI getCEMI()
	{
		return CEMIFactory.copy(cemi);
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#getStructLength()
	 */
	short getStructLength()
	{
		return (short) (CONN_HEADER_SIZE + (cemi != null ? cemi.getStructLength() : 0));
	}

	/* (non-Javadoc)
	 * @see tuwien.auto.calimero.knxnetip.servicetype.ServiceType#toByteArray
	 *      (java.io.ByteArrayOutputStream)
	 */
	byte[] toByteArray(ByteArrayOutputStream os)
	{
		os.write(CONN_HEADER_SIZE);
		os.write(channelid);
		os.write(seq);
		os.write(0);
		final byte[] buf = cemi.toByteArray();
		os.write(buf, 0, buf.length);
		return os.toByteArray();
	}
}


text:
<?php

namespace Application\Model\ORM;

use Application\Model\Entity\Responsavel;
use Doctrine\ORM\EntityManager;
use Exception;

/**
 * Nome: ResponsavelORM.php
 * @author Leonardo Pereira Magalhães <falecomleonardopereira@gmail.com>
 * Descricao: Classe com acesso doctrine
 */
class ResponsavelORM extends KleoORM {
/**
     * Localizar todos os responsaveis
     * @return Responsavel[]
     * @throws Exception
     */
    public function encontrarTodos() {
        $entidades = $this->getEntityManager()->getRepository($this->getEntity())->findAll();
        if (!$entidades) {
            throw new Exception("Não foi encontrado nenhum registro");
        }
        return $entidades;
    }
}


text:
#include "vpx_ports/config.h"
#include <stddef.h>

#include "../treewriter.h"
#include "../tokenize.h"
#include "../onyx_int.h"

#define ct_assert(name,cond) \
    static void assert_##name(void) UNUSED;\
    static void assert_##name(void) {switch(0){case 0:case !!(cond):;}}

#define DEFINE(sym, val) int sym = val;

/*
#define BLANK() asm volatile("\n->" : : )
*/

/*
 * int main(void)
 * {
 */

DEFINE(vp8_writer_lowvalue,                     offsetof(vp8_writer, lowvalue));
DEFINE(vp8_writer_range,                        offsetof(vp8_writer, range));
DEFINE(vp8_writer_value,                        offsetof(vp8_writer, value));
DEFINE(vp8_writer_count,                        offsetof(vp8_writer, count));
DEFINE(vp8_writer_pos,                          offsetof(vp8_writer, pos));
DEFINE(vp8_writer_buffer,                       offsetof(vp8_writer, buffer));

DEFINE(tokenextra_token,                        offsetof(TOKENEXTRA, Token));
DEFINE(tokenextra_extra,                        offsetof(TOKENEXTRA, Extra));
DEFINE(tokenextra_context_tree,                  offsetof(TOKENEXTRA, context_tree));
DEFINE(tokenextra_skip_eob_node,                offsetof(TOKENEXTRA, skip_eob_node));
DEFINE(TOKENEXTRA_SZ,                           sizeof(TOKENEXTRA));

DEFINE(vp8_extra_bit_struct_sz,                   sizeof(vp8_extra_bit_struct));

DEFINE(vp8_token_value,                         offsetof(vp8_token, value));
DEFINE(vp8_token_len,                           offsetof(vp8_token, Len));

DEFINE(vp8_extra_bit_struct_tree,                 offsetof(vp8_extra_bit_struct, tree));
DEFINE(vp8_extra_bit_struct_prob,                 offsetof(vp8_extra_bit_struct, prob));
DEFINE(vp8_extra_bit_struct_prob_bc,               offsetof(vp8_extra_bit_struct, prob_bc));
DEFINE(vp8_extra_bit_struct_len,                  offsetof(vp8_extra_bit_struct, Len));
DEFINE(vp8_extra_bit_struct_base_val,              offsetof(vp8_extra_bit_struct, base_val));

DEFINE(vp8_comp_tplist,                         offsetof(VP8_COMP, tplist));
DEFINE(vp8_comp_common,                         offsetof(VP8_COMP, common));
DEFINE(vp8_comp_bc2,                            offsetof(VP8_COMP, bc2));

DEFINE(tokenlist_start,                         offsetof(TOKENLIST, start));
DEFINE(tokenlist_stop,                          offsetof(TOKENLIST, stop));
DEFINE(TOKENLIST_SZ,                            sizeof(TOKENLIST));

DEFINE(vp8_common_mb_rows,                       offsetof(VP8_COMMON, mb_rows));

// These two sizes are used in vp7cx_pack_tokens.  They are hard coded
//  so if the size changes this will have to be adjusted.
ct_assert(TOKENEXTRA_SZ, sizeof(TOKENEXTRA) == 20)
ct_assert(vp8_extra_bit_struct_sz, sizeof(vp8_extra_bit_struct) == 20)

//add asserts for any offset that is not supported by assembly code
//add asserts for any size that is not supported by assembly code
/*
 * return 0;
 * }
 */


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2011 The Android Open Source Project

     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.
-->
<view class="sk.ksp.callcentrum.dialpad.DialpadFragment$DialpadSlidingLinearLayout"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >
    <!-- spacer view -->
    <View
        android:id="@+id/spacer"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#00000000" />
    <!-- Dialpad shadow -->
    <View
        android:layout_width="match_parent"
        android:layout_height="3dp"
        android:background="@drawable/shadow_fade_up" />
    <view class="sk.ksp.callcentrum.dialpad.DialpadFragment$HoverIgnoringLinearLayout"
        android:id="@+id/top"
        android:animateLayoutChanges="true"
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:layout_gravity="bottom"
        android:orientation="vertical"
        android:layoutDirection="ltr"
        android:background="@color/background_dialpad">

        <Space
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@color/dialpad_separator_line_color" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="10dp" />

        <include layout="@layout/dialpad_digits"/>

        <Space
            android:layout_width="match_parent"
            android:layout_height="8dp" />

        <include layout="@layout/dialpad" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="8dp" />

        <Space
            android:layout_width="match_parent"
            android:layout_height="2dp"
            android:background="@color/dialpad_separator_line_color" />

        <!-- "Dialpad chooser" UI, shown only when the user brings up the
             Dialer while a call is already in progress.
             When this UI is visible, the other Dialer elements
             (the textfield/button and the dialpad) are hidden. -->
        <ListView android:id="@+id/dialpadChooser"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:visibility="gone" />

    </view>
</view>


text:
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

#include "p_mysql.h"

static SQL_STATEMENT_API mysql_statement_api = {
	sql_statement_def_queryinterface_,
	sql_statement_def_addref_,
	sql_statement_mysql_free_,
	sql_statement_mysql_connection_,
	sql_statement_mysql_statement_,
	sql_statement_mysql_set_results_,
	sql_statement_mysql_columns_,
	sql_statement_mysql_rows_,
	sql_statement_mysql_affected_,
	sql_statement_mysql_field_,
	sql_statement_mysql_null_,
	sql_statement_mysql_value_,
	sql_statement_mysql_valueptr_,
	sql_statement_mysql_valuelen_,
	sql_statement_mysql_eof_,
	sql_statement_mysql_next_,
	sql_statement_mysql_cur_,
	sql_statement_mysql_rewind_,
	sql_statement_mysql_seek_
};

/* Create a new statement or result-set */
SQL_STATEMENT *
sql_mysql_statement_(SQL *restrict me, const char *restrict statement)
{
	SQL_STATEMENT *p;

	p = (SQL_STATEMENT *) calloc(1, sizeof(SQL_STATEMENT));
	if(!p)
	{
		return NULL;
	}
	p->api = &mysql_statement_api;
	p->refcount = 1;
	p->sql = me;
	p->cur = (unsigned long long) -1;
	if(statement)
	{
		p->statement = strdup(statement);
		if(!p->statement)
		{
			free(p);
			return NULL;
		}
	}
	return p;
}

/* Free the resources used by a statement */
unsigned long
sql_statement_mysql_free_(SQL_STATEMENT *me)
{
	me->refcount--;
	if(me->refcount)
	{
		return me->refcount;
	}
	if(me->result)
	{
		mysql_free_result(me->result);
	}
	free(me->statement);
	free(me);
	return 0;
}

/* Return the connection associated with this statement */
SQL *
sql_statement_mysql_connection_(SQL_STATEMENT *me)
{
	return me->sql;
}

/* Return the (parameterised) SQL statement */
const char *
sql_statement_mysql_statement_(SQL_STATEMENT *me)
{
	return me->statement;
}

/* Update the result-set with a new MYSQL_RES pointer */
int
sql_statement_mysql_set_results_(SQL_STATEMENT *restrict me, void *data)
{
	if(me->result)
	{
		mysql_free_result(me->result);
	}
	me->result = (MYSQL_RES *) data;
	me->affected = mysql_affected_rows(&(me->sql->mysql));
	me->lengths = NULL;
	me->cur = (unsigned long long) -1;
	if(data)
	{
		me->fields = mysql_fetch_fields(me->result);
		me->columns = mysql_field_count(&(me->sql->mysql));
		me->rows = mysql_num_rows(me->result);
		me->row = mysql_fetch_row(me->result);
		if(me->row)
		{
			me->lengths = mysql_fetch_lengths(me->result);
			me->cur = 0;
		}
	}
	else
	{
		me->fields = NULL;
		me->columns = 0;
		me->row = NULL;
		me->rows = 0;
	}
	return 0;
}

/* Return the number of columns in the result-set */
unsigned int
sql_statement_mysql_columns_(SQL_STATEMENT *me)
{
	return me->columns;
}

/* Return the number of rows in the result-set */
unsigned long long
sql_statement_mysql_rows_(SQL_STATEMENT *me)
{
	return me->rows;
}

/* Return the number of rows affected by the query */
unsigned long long
sql_statement_mysql_affected_(SQL_STATEMENT *me)
{
	return me->affected;
}

/* Return 1 if we have reached the end of the result-set, or 0 otherwise */
int
sql_statement_mysql_eof_(SQL_STATEMENT *me)
{
	if(me->row)
	{
		return 0;
	}
	return 1;
}

/* Move to the next row; returns 1 if there was a row, 0 if not or -1 if an error occurred */
int
sql_statement_mysql_next_(SQL_STATEMENT *me)
{
	if(!me->result)
	{
		return 0;
	}
	me->row = mysql_fetch_row(me->result);
	me->lengths = NULL;
	if(me->row)
	{
		me->lengths = mysql_fetch_lengths(me->result);
		me->cur++;
		return 1;
	}
	me->cur = (unsigned long long) -1;
	return 0;
}

/* Retrieve the contents of a column in the current row */
size_t
sql_statement_mysql_value_(SQL_STATEMENT *restrict me, unsigned int col, char *restrict buf, size_t buflen)
{
	size_t l;

	if(buf)
	{
		*buf = 0;
	}
	if(!me->row || col >= me->columns)
	{
		return 0;
	}
	if(buf)
	{
		l = me->lengths[col];
		if(l >= buflen)
		{
			l = buflen - 1;
		}
		memcpy(buf, me->row[col], l);
		buf[l] = 0;
	}
	return me->lengths[col] + 1;
}

/* Retrieve a pointer to the first byte in a field, or NULL if the value is NULL */
const unsigned char *
sql_statement_mysql_valueptr_(SQL_STATEMENT *me, unsigned int col)
{
	if(!me->row || col >= me->columns)
	{
		return NULL;
	}
	return (const unsigned char *) me->row[col];
}

/* Return 1 if the specified column in the current row is NULL */
int
sql_statement_mysql_null_(SQL_STATEMENT *me, unsigned int col)
{
	if(!me->row || col >= me->columns)
	{
		return 1;
	}
	if(!me->row[col])
	{
		return 1;
	}
	return 0;
}

/* Retrieve the length of the data in a column in the current row, including terminating NULL */
size_t
sql_statement_mysql_valuelen_(SQL_STATEMENT *me, unsigned int col)
{
	if(!me->row || col >= me->columns)
	{
		return 0;
	}
	return me->lengths[col] + 1;
}

/* Return the row index of the current row */
unsigned long long
sql_statement_mysql_cur_(SQL_STATEMENT *me)
{
	return me->cur;
}

/* Seek to a particular row in the result-set */
int
sql_statement_mysql_seek_(SQL_STATEMENT *me, unsigned long long row)
{
	if(!me->result || row > me->rows)
	{
		return -1;
	}
	mysql_data_seek(me->result, row);
	me->row = mysql_fetch_row(me->result);
	me->lengths = NULL;
	if(me->row)
	{
		me->lengths = mysql_fetch_lengths(me->result);
		me->cur = row;
		return 0;
	}
	me->cur = (unsigned long long) -1;
	return -1;
}

/* Rewind the current pointer into the result-set back to the start */
int
sql_statement_mysql_rewind_(SQL_STATEMENT *me)
{
	return sql_statement_mysql_seek_(me, 0);
}


text:
Register

  <form ng-submit="register(user)">

      <input type="name" ng-model="user.name" placeholder="Name" class="form-control" required>

      <input type="email" ng-model="user.email" placeholder="Email" class="form-control" required>

      <input type="password" ng-model="user.password" placeholder="Password" class="form-control" required>

    <input type="submit" value="Register" class="btn btn-danger">
  </form>


text:
package com.taotao.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.taotao.common.pojo.PictureResult;
import com.taotao.common.utils.JsonUtils;
import com.taotao.service.PictureService;

/**
 * 图片上传
 *
 * @author Jerry
 *
 */
@Controller
public class PictureController {

	@Autowired
	private PictureService PictureService;

	@RequestMapping("/pic/upload")
	@ResponseBody
	public String upload(MultipartFile uploadFile) {
		PictureResult result = PictureService.uploadPicture(uploadFile);
		return JsonUtils.objectToJson(result);
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. I. Liro Mycotheca Fennica, Fasc. 16 109 (1939)

#### Original name
Ustilago nannfeldtii Liro, 1939

### Remarks
null


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Cake.Common.Tests.Fixtures.Tools.DotNetCore.Execute;
using Cake.Common.Tools.DotNetCore.Execute;
using Cake.Testing;
using Xunit;

namespace Cake.Common.Tests.Unit.Tools.DotNetCore.Execute
{
    public sealed class DotNetCoreExecutorTests
    {
        public sealed class TheExecuteMethod
        {
            [Fact]
            public void Should_Throw_If_Settings_Are_Null()
            {
                // Given
                var fixture = new DotNetCoreExecutorFixture();
                fixture.AssemblyPath = "./bin/Debug/app.dll";
                fixture.Arguments = "--args";
                fixture.Settings = null;
                fixture.GivenDefaultToolDoNotExist();

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                AssertEx.IsArgumentNullException(result, "settings");
            }

            [Fact]
            public void Should_Throw_If_Process_Was_Not_Started()
            {
                // Given
                var fixture = new DotNetCoreExecutorFixture();
                fixture.AssemblyPath = "./bin/Debug/app.dll";
                fixture.Arguments = "--args";
                fixture.Settings = new DotNetCoreExecuteSettings();
                fixture.GivenProcessCannotStart();

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                AssertEx.IsCakeException(result, ".NET Core CLI: Process was not started.");
            }

            [Fact]
            public void Should_Throw_If_Process_Has_A_Non_Zero_Exit_Code()
            {
                // Given
                var fixture = new DotNetCoreExecutorFixture();
                fixture.AssemblyPath = "./bin/Debug/app.dll";
                fixture.Arguments = "--args";
                fixture.Settings = new DotNetCoreExecuteSettings();
                fixture.GivenProcessExitsWithCode(1);

                // When
                var result = Record.Exception(() => fixture.Run());

                // Then
                AssertEx.IsCakeException(result, ".NET Core CLI: Process returned an error (exit code 1).");
            }

            [Fact]
            public void Should_Add_Mandatory_Arguments()
            {
                // Given
                var fixture = new DotNetCoreExecutorFixture();
                fixture.AssemblyPath = "./bin/Debug/app.dll";
                fixture.Settings = new DotNetCoreExecuteSettings();

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("\"/Working/bin/Debug/app.dll\"", result.Args);
            }

            [Fact]
            public void Should_Add_Famework_Version()
            {
                // Given
                var fixture = new DotNetCoreExecutorFixture();
                fixture.AssemblyPath = "./Some Folder/Debug/app.dll";
                fixture.Settings.FrameworkVersion = "1.0.3";

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("--fx-version 1.0.3 \"/Working/Some Folder/Debug/app.dll\"", result.Args);
            }

            [Fact]
            public void Should_Add_Host_Arguments()
            {
                // Given
                var fixture = new DotNetCoreExecutorFixture();
                fixture.AssemblyPath = "./bin/Debug/app.dll";
                fixture.Settings.DiagnosticOutput = true;

                // When
                var result = fixture.Run();

                // Then
                Assert.Equal("--diagnostics \"/Working/bin/Debug/app.dll\"", result.Args);
            }
        }
    }
}


text:
"""
This module implements the Field class, which simply a WeightedGraph
(see the graph.py) module, plus an arrray that yields (possibly
multi-dimnesional) features associated with graph vertices. This
allows some kinds of computations (all thoses relating to mathematical
morphology, diffusion etc.)

Certain functions are provided to Instantiate Fields easily, given a
WeightedGraph and feature data.

Author:Bertrand Thirion, 2006--2011
"""
from __future__ import print_function
from __future__ import absolute_import

from warnings import warn
import numpy as np

from .graph import WeightedGraph, Graph

NEGINF = -np.inf

def field_from_coo_matrix_and_data(x, data):
    """ Instantiates a weighted graph from a (sparse) coo_matrix

    Parameters
    ----------
    x: (V, V) scipy.sparse.coo_matrix instance,
       the input matrix
    data: array of shape (V, dim),
          the field data

    Returns
    -------
    ifield: resulting Field instance
    """
    if x.shape[0] != x.shape[1]:
        raise ValueError("the input coo_matrix is not square")
    if data.shape[0] != x.shape[0]:
        raise ValueError("data and x do not have consistent shapes")
    i, j = x.nonzero()
    edges = np.vstack((i, j)).T
    weights = x.data
    ifield = Field(x.shape[0], edges, weights, data)
    return ifield

def field_from_graph_and_data(g, data):
    """ Instantiate a Fieldfrom a WeightedGraph plus some feature data
    Parameters
    ----------
    x: (V, V) scipy.sparse.coo_matrix instance,
       the input matrix
    data: array of shape (V, dim),
          the field data

    Returns
    -------
    ifield: resulting field instance
    """
    if data.shape[0] != g.V:
        raise ValueError("data and g do not have consistent shapes")
    ifield = Field(g.V, g.edges, g.weights, data)
    return ifield

class Field(WeightedGraph):
    """
    This is the basic field structure,
         which contains the weighted graph structure
         plus an array of data (the 'field')
    field is an array of size(n, p)
          where n is the number of vertices of the graph
          and p is the field dimension
    """

    def __init__(self, V, edges=None, weights=None, field=None):
        """
        Parameters
        ----------
        V (int > 0) the number of vertices of the graph
        edges=None: the edge array of the graph
        weights=None: the asociated weights array
        field=None: the field data itself
        """
        V = int(V)
        if V < 1:
            raise ValueError('cannot create graph with no vertex')
        self.V = int(V)
        self.E = 0
        self.edges = []
        self.weights = []
        if (edges is not None) or (weights is not None):
            if len(edges) == 0:
                E = 0
            elif edges.shape[0] == np.size(weights):
                E = edges.shape[0]
            else:
                raise ValueError('Incompatible size of the edges \
                                  and weights matrices')
            self.V = V
            self.E = E
            self.edges = edges
            self.weights = weights
        self.field = []
        if field is None:
            pass
        else:
            if np.size(field) == self.V:
                field = np.reshape(field, (self.V, 1))
            if field.shape[0] != self.V:
                raise ValueError('field does not have a correct size')
            else:
                self.field = field

    def get_field(self):
        return self.field

    def set_field(self, field):
        if np.size(field) == self.V:
            field = np.reshape(field, (self.V, 1))
        if field.shape[0] != self.V:
            raise ValueError('field does not have a correct size')
        else:
            self.field = field

    def closing(self, nbiter=1):
        """Morphological closing of the field data.
        self.field is changed inplace

        Parameters
        ----------
        nbiter=1 : the number of iterations required
        """
        nbiter = int(nbiter)
        self.dilation(nbiter)
        self.erosion(nbiter)

    def opening(self, nbiter=1):
        """Morphological opening of the field data.
        self.field is changed inplace

        Parameters
        ----------
        nbiter: int, optional, the number of iterations required
        """
        nbiter = int(nbiter)
        self.erosion(nbiter)
        self.dilation(nbiter)

    def dilation(self, nbiter=1, fast=True):
        """Morphological dilation of the field data, changed in place

        Parameters
        ----------
        nbiter: int, optional, the number of iterations required

        Note
        ----
        When data dtype is not float64, a slow version of the code is used
        """
        nbiter = int(nbiter)
        if self.field.dtype != np.float64:
            warn('data type is not float64; a slower version is used')
            fast = False
        if fast:
            from ._graph import dilation
            if self.E > 0:
                if (self.field.size == self.V):
                    self.field = self.field.reshape((self.V, 1))
                idx, neighb, _ = self.compact_neighb()
                for i in range(nbiter):
                    dilation(self.field, idx, neighb)
        else:
            from scipy.sparse import dia_matrix
            adj = self.to_coo_matrix() + dia_matrix(
                (np.ones(self.V), 0), (self.V, self.V))
            rows = adj.tolil().rows
            for i in range(nbiter):
                self.field = np.array([self.field[row].max(0) for row in rows])

    def highest_neighbor(self, refdim=0):
        """Computes the neighbor with highest field value along refdim

        Parameters
        ----------
        refdim: int, optional,
                the dimension of the field under consideration

        Returns
        -------
        hneighb: array of shape(self.V),
                 index of the neighbor with highest value
        """
        from scipy.sparse import dia_matrix
        refdim = int(refdim)
        # add self-edges to avoid singularities, when taking the maximum
        adj = self.to_coo_matrix() + dia_matrix(
            (np.ones(self.V), 0), (self.V, self.V))
        rows = adj.tolil().rows
        hneighb = np.array([row[self.field[row].argmax()] for row in rows])
        return hneighb

    def erosion(self, nbiter=1):
        """Morphological openeing of the field

        Parameters
        ----------
        nbiter: int, optional, the number of iterations required
        """
        nbiter = int(nbiter)
        lil = self.to_coo_matrix().tolil().rows.tolist()
        for i in range(nbiter):
            nf = np.zeros_like(self.field)
            for k, neighbors in enumerate(lil):
                nf[k] = self.field[neighbors].min(0)
            self.field = nf

    def get_local_maxima(self, refdim=0, th=NEGINF):
        """
        Look for the local maxima of one dimension (refdim) of self.field

        Parameters
        ----------
        refdim (int) the field dimension over which the maxima are looked after
        th = float, optional
            threshold so that only values above th are considered

        Returns
        -------
        idx: array of shape (nmax)
             indices of the vertices that are local maxima
        depth: array of shape (nmax)
               topological depth of the local maxima :
               depth[idx[i]] = q means that idx[i] is a q-order maximum
        """
        depth_all = self.local_maxima(refdim, th)
        idx = np.ravel(np.where(depth_all))
        depth = depth_all[idx]
        return idx, depth

    def local_maxima(self, refdim=0, th=NEGINF):
        """Returns all the local maxima of a field

        Parameters
        ----------
        refdim (int) field dimension over which the maxima are looked after
        th: float, optional
            threshold so that only values above th are considered

        Returns
        -------
        depth: array of shape (nmax)
               a labelling of the vertices such that
               depth[v] = 0 if v is not a local maximum
               depth[v] = 1 if v is a first order maximum
               ...
               depth[v] = q if v is a q-order maximum
        """
        refdim = int(refdim)
        if np.size(self.field) == 0:
            raise ValueError('No field has been defined so far')
        if self.field.shape[1] - 1 < refdim:
            raise ValueError(refdim > self.shape[1])
        depth = np.zeros(self.V, np.int)

        # create a subfield(thresholding)
        sf = self.subfield(self.field.T[refdim] >= th)
        initial_field = sf.field.T[refdim]
        sf.field = initial_field.astype(np.float64)

        # compute the depth in the subgraph
        ldepth = sf.V * np.ones(sf.V, np.int)
        for k in range(sf.V):
            dilated_field_old = sf.field.ravel().copy()
            sf.dilation(1)
            non_max = sf.field.ravel() > dilated_field_old
            ldepth[non_max] = np.minimum(k, ldepth[non_max])
            if (non_max == False).all():
                ldepth[sf.field.ravel() == initial_field] = np.maximum(k, 1)
                break

        # write all the depth values
        depth[self.field[:, refdim] >= th] = ldepth
        return depth

    def diffusion(self, nbiter=1):
        """diffusion of the field data in the weighted graph structure
        self.field is changed inplace

        Parameters
        ----------
        nbiter: int, optional the number of iterations required

        Notes
        -----
        The process is run for all the dimensions of the field
        """
        nbiter = int(nbiter)
        adj = self.to_coo_matrix()
        for i in range(nbiter):
            self.field = adj * self.field

    def custom_watershed(self, refdim=0, th=NEGINF):
        """ customized watershed analysis of the field.
        Note that bassins are found around each maximum
        (and not minimum as conventionally)

        Parameters
        ----------
        refdim: int, optional
        th: float optional, threshold of the field

        Returns
        -------
        idx: array of shape (nbassins)
             indices of the vertices that are local maxima
        label : array of shape (self.V)
              labelling of the vertices according to their bassin
        """
        import numpy.ma as ma

        if (np.size(self.field) == 0):
            raise ValueError('No field has been defined so far')
        if self.field.shape[1] - 1 < refdim:
            raise ValueError('refdim>field.shape[1]')

        label = - np.ones(self.V, np.int)

        # create a subfield(thresholding)
        sf = self.subfield(self.field[:, refdim] >= th)

        # compute the basins
        hneighb = sf.highest_neighbor()
        edges = np.vstack((hneighb, np.arange(sf.V))).T
        edges = np.vstack((edges, np.vstack((np.arange(sf.V), hneighb)).T))
        aux = Graph(sf.V, edges.shape[0], edges)
        llabel = aux.cc()
        n_bassins = len(np.unique(llabel))

        # write all the depth values
        label[self.field[:, refdim] >= th] = llabel
        idx = np.array([ma.array(
                    self.field[:, refdim], mask=(label != c)).argmax()
                        for c in range(n_bassins)])
        return idx, label

    def threshold_bifurcations(self, refdim=0, th=NEGINF):
        """Analysis of the level sets of the field:
        Bifurcations are defined as changes in the topology in the level sets
        when the level (threshold) is varied
        This can been thought of as a kind of Morse analysis

        Parameters
        ----------
        th: float, optional,
            threshold so that only values above th are considered

        Returns
        -------
        idx: array of shape (nlsets)
             indices of the vertices that are local maxima
        height: array of shape (nlsets)
                the depth of the local maxima
                depth[idx[i]] = q means that idx[i] is a q-order maximum
                Note that this is also the diameter of the basins
                associated with local maxima
        parents: array of shape (nlsets)
                 the label of the maximum which dominates each local maximum
                 i.e. it describes the hierarchy of the local maxima
        label: array of shape (self.V)
               a labelling of thevertices according to their bassin
        """
        import numpy.ma as ma
        if (np.size(self.field) == 0):
            raise ValueError('No field has been defined so far')
        if self.field.shape[1] - 1 < refdim:
            raise ValueError('refdim>field.shape[1]')

        label = - np.ones(self.V, np.int)

        # create a subfield(thresholding)
        sf = self.subfield(self.field[:, refdim] >= th)
        initial_field = sf.field[:, refdim].copy()
        sf.field = initial_field.copy()

        # explore the subfield
        order = np.argsort(- initial_field)
        rows = sf.to_coo_matrix().tolil().rows
        llabel = - np.ones(sf.V, np.int)
        parent, root =  np.arange(2 * self.V), np.arange(2 * self.V)
        # q will denote the region index
        q = 0
        for i in order:
            if (llabel[rows[i]] > - 1).any():
                nlabel = np.unique(llabel[rows[i]])
                if nlabel[0] == -1:
                    nlabel = nlabel[1:]
                nlabel = np.unique(root[nlabel])
                if len(nlabel) == 1:
                    # we are at a regular point
                    llabel[i] = nlabel[0]
                else:
                    # we are at a saddle point
                    llabel[i] = q
                    parent[nlabel] = q
                    root[nlabel] = q
                    for j in nlabel:
                        root[root == j] = q
                    q += 1
            else:
                # this is a new component
                llabel[i] = q
                q += 1
        parent = parent[:q]

        # write all the depth values
        label[self.field[:, refdim] >= th] = llabel
        idx = np.array([ma.array(
                    self.field[:, refdim], mask=(label != c)).argmax()
                         for c in range(q)])
        return idx, parent, label

    def constrained_voronoi(self, seed):
        """Voronoi parcellation of the field starting from the input seed

        Parameters
        ----------
        seed: int array of shape(p), the input seeds

        Returns
        -------
        label: The resulting labelling of the data

        Fixme
        -----
        deal with graphs with several ccs
        """
        if np.size(self.field) == 0:
            raise ValueError('No field has been defined so far')
        seed = seed.astype(np.int)
        weights = np.sqrt(np.sum((self.field[self.edges.T[0]] -
                                  self.field[self.edges.T[1]]) ** 2, 1))
        g = WeightedGraph(self.V, self.edges, weights)
        label = g.voronoi_labelling(seed)
        return label

    def geodesic_kmeans(self, seeds=None, label=None, maxiter=100, eps=1.e-4,
                        verbose=0):
        """ Geodesic k-means algorithm
        i.e. obtention of clusters that are topologically
        connected and minimally variable concerning the information
        of self.field

        Parameters
        ----------
        seeds: array of shape(p), optional,
               initial indices of the seeds within the field
               if seeds==None the labels are used as initialization
        labels: array of shape(self.V) initial labels, optional,
                it is expected that labels take their values
                in a certain range (0..lmax)
                if Labels==None, this is not used
                if seeds==None and labels==None,  an ewxception is raised
        maxiter: int, optional,
                 maximal number of iterations
        eps: float, optional,
             increase of inertia at which convergence is declared

        Returns
        -------
        seeds: array of shape (p), the final seeds
        label : array of shape (self.V), the resulting field label
        J: float, inertia value
        """
        if np.size(self.field) == 0:
            raise ValueError('No field has been defined so far')

        if (seeds is None) and (label is None):
            raise ValueError('No initialization has been provided')
        k = np.size(seeds)
        inertia_old = NEGINF
        if seeds is None:
            k = label.max() + 1
            if np.size(np.unique(label)) != k:
                raise ValueError('missing values, cannot proceed')
            seeds = np.zeros(k).astype(np.int)
            for  j in range(k):
                lj = np.nonzero(label == j)[0]
                cent = np.mean(self.field[lj], 0)
                tj = np.argmin(np.sum((cent - self.field[lj]) ** 2, 1))
                seeds[j] = lj[tj]
        else:
            k = np.size(seeds)

        for i in range(maxiter):
            # voronoi labelling
            label = self.constrained_voronoi(seeds)
            # update the seeds
            inertia = 0
            pinteria = 0
            for  j in range(k):
                lj = np.nonzero(label == j)[0]
                pinteria += np.sum(
                    (self.field[seeds[j]] - self.field[lj]) ** 2)
                cent = np.mean(self.field[lj], 0)
                tj = np.argmin(np.sum((cent - self.field[lj]) ** 2, 1))
                seeds[j] = lj[tj]
                inertia += np.sum((cent - self.field[lj]) ** 2)
            if verbose:
                print(i, inertia)
            if np.absolute(inertia_old - inertia) < eps:
                break
            inertia_old = inertia
        return seeds, label, inertia

    def ward(self, nbcluster):
        """Ward's clustering of self

        Parameters
        ----------
        nbcluster: int,
                   the number of desired clusters

        Returns
        -------
        label: array of shape (self.V)
               the resulting field label
        J (float): the resulting inertia
        """
        from nipy.algorithms.clustering.hierarchical_clustering\
             import ward_segment
        label, J = ward_segment(self, self.field, qmax=nbcluster)

        # compute the resulting inertia
        inertia = 0
        for  j in range(nbcluster):
            lj = np.nonzero(label == j)[0]
            cent = np.mean(self.field[lj], 0)
            inertia += np.sum((cent - self.field[lj]) ** 2)
        return label, inertia

    def copy(self):
        """ copy function
        """
        return Field(self.V, self.edges.copy(),
                     self.weights.copy(), self.field.copy())

    def subfield(self, valid):
        """Returns a subfield of self, with only vertices such that valid > 0

        Parameters
        ----------
        valid: array of shape (self.V),
               nonzero for vertices to be retained

        Returns
        -------
        F: Field instance,
           the desired subfield of self

        Notes
        -----
        The vertices are renumbered as [1..p] where p = sum(valid>0) when
        sum(valid) == 0 then None is returned
        """
        G = self.subgraph(valid)
        if G is None:
            return None
        field = self.field[valid]
        if len(G.edges) == 0:
            edges = np.array([[], []]).T
        else:
            edges = G.edges
        return Field(G.V, edges, G.weights, field)


text:
@import "base.css";
body {
	background: url(image.png);
	correct: a;
}


text:
"""Strings for Alexa to say"""
from settings import SITE_NAME_SPEAKABLE

SITE_NAME = SITE_NAME_SPEAKABLE

# Breaks
BREAK = '<break strength="{strength}">'
XS_BREAK = BREAK.format(strength='x-strong')
S_BREAK = BREAK.format(strength='strong')

# Greet and dismiss
WELCOME_REPROMPT = \
"""
You can ask {site_name} for an answer to a question.
For example, try, Ask {site_name}{break1} what is node j s.
""".format(site_name=SITE_NAME, break1=S_BREAK)

WELCOME = ("Welcome to the Alexa {site_name} Skill. " + WELCOME_REPROMPT).format(site_name=SITE_NAME)
GOODBYE = "Thank you for trying the Alexa {site_name} app.".format(site_name=SITE_NAME)

# Report of what has been found
REPORT_ON_QUESTION = "The closest question match on " + SITE_NAME + ' is {question}...'
REPORT_ON_ANSWER = "The top rated answer for that question by {answerer} with {votes} upvotes is {answer}."
REPORT = S_BREAK.join([REPORT_ON_QUESTION, REPORT_ON_ANSWER])

# Failure to parse and reprompt
FAILURE = "I'm sorry, I didn't catch your question. Please try again."
PROMPT_ASK = "Your questions will be relayed to {site_name}.".format(site_name=SITE_NAME)

# Nothing found responses
NO_QUESTIONS = "I'm sorry, that didn't return any results on {site_name}.".format(site_name=SITE_NAME)
NO_ANSWERS = NO_QUESTIONS + "However there is a question waiting to be answered."


text:
#include "service.h"
#include "gatt_dbus.h"
#include "utils.h"
#include "bluez.h"

#include "cagattservice.h"
#include "logger.h"
#include "oic_malloc.h"

#include <inttypes.h>
#include <stdio.h>
#include <assert.h>

// Logging tag.
static char const TAG[] = "BLE_SERVICE";

static GVariant * CAGattServiceGetProperties(GattService1 * service)
{
    /*
      Create a variant containing the @c GattService1 properties, of
      the form @c a{sa{sv}}.
    */

    /**
     * Populate the property table, and create the variant to be
     * embedded in the results of the
     * @c org.freedesktop.Dbus.ObjectManager.GetManagedObjects()
     * method call.
     *
     * The @c "Device" property is only available on the client side
     * so we don't bother returning it here.
     *
     * @todo Do we care about the @c "Includes" property?
     *       @c "Includes" isn't implemented by BlueZ as of version
     *       5.30, so we can leave it out.
    */
    CADBusSkeletonProperty const properties[] = {
        { "UUID",
          g_variant_new_string(gatt_service1_get_uuid(service)) },
        { "Primary",
          g_variant_new_boolean(gatt_service1_get_primary(service)) },
        { "Characteristics",
          g_variant_new_objv(
              gatt_service1_get_characteristics(service),
              -1) }
    };

    return
        CAMakePropertyDictionary(
            BLUEZ_GATT_SERVICE_INTERFACE,
            properties,
            sizeof(properties) / sizeof(properties[0]));
}

/**
 * Implementation of the
 * @c org.freedesktop.DBus.ObjectManager.GetManagedObjects() method
 * for the @c org.bluez.GattService1 interface.
 */
static gboolean CAGattServiceHandleGetManagedObjects(
    ObjectManager * object,
    GDBusMethodInvocation * invocation,
    gpointer user_data)
{
    /**
     * @note Ideally we shouldn't need this implementation, and should
     *       be able to simply rely GDBusObjectManagerServer instead.
     *       Unfortunately, BlueZ expects the @c
     *       org.bluez.GattService1 object to implement the @c
     *       ObjectManager interface, and both interfaces must rooted
     *       at the same object path, as well.  That requirement
     *       prevents us from using @c GDBusObjectManagerServer since
     *       it won't allow us to export more than interface on a
     *       given object path.
     */

    /*
      Build the object array containing the IoTivity
      org.bluez.GattService1 hierarchy.

      a{oa{sa{sv}}}
    */
    CAGattService * const service = user_data;

    GVariantBuilder builder;
    g_variant_builder_init(&builder, G_VARIANT_TYPE("a{oa{sa{sv}}}"));

    // Start out with the service itself.
    g_variant_builder_add(&builder,
                          "{o@a{sa{sv}}}",
                          service->object_path,
                          CAGattServiceGetProperties(service->service));

    /*
      Add the request characteristic and user description
      descriptor.
    */
    CAGattCharacteristic * const request_chrc =
        &service->request_characteristic;

    g_variant_builder_add(&builder,
                          "{o@a{sa{sv}}}",
                          request_chrc->object_path,
                          CAGattCharacteristicGetProperties(
                              request_chrc->characteristic));

    CAGattDescriptor * const request_desc = &request_chrc->descriptor;

    g_variant_builder_add(&builder,
                          "{o@a{sa{sv}}}",
                          request_desc->object_path,
                          CAGattDescriptorGetProperties(
                              request_desc->descriptor));

    /*
      Add the response characteristic and user description
      descriptor.
    */
    CAGattCharacteristic * const response_chrc =
        &service->response_characteristic;

    g_variant_builder_add(&builder,
                          "{o@a{sa{sv}}}",
                          response_chrc->object_path,
                          CAGattCharacteristicGetProperties(
                              response_chrc->characteristic));

    CAGattDescriptor * const response_desc = &response_chrc->descriptor;

    g_variant_builder_add(&builder,
                          "{o@a{sa{sv}}}",
                          response_desc->object_path,
                          CAGattDescriptorGetProperties(
                              response_desc->descriptor));

    GVariant * const objects = g_variant_builder_end(&builder);

    object_manager_complete_get_managed_objects(object,
                                                invocation,
                                                objects);

    return TRUE;
}

char * CAGattServiceMakePeerAddress(CAGattService * s)
{
    assert(s != NULL);

    /*
      Since there is no direct way to obtain the client address
      associated with the GATT characterstics on the server side,
      embed a stringified pointer to this GATT service of the form
      "&ABCDEF01" as the address instead so that we can use it to
      refer to the client.  This works since:
          1) only one LE central is ever connected to an LE peripheral
          2) the CA layer doesn't directly interpret the client
             address
     */

    /*
      Length of stringified pointer in hexadecimal format, plus one
      for the leading ampersand, and one more for the null
      terminator.
    */
    static size_t const PSEUDO_ADDR_LEN = sizeof(uintptr_t) * 2 + 2;

    assert(MAX_ADDR_STR_SIZE_CA > PSEUDO_ADDR_LEN);

    char * const addr = OICMalloc(PSEUDO_ADDR_LEN);

    if (addr == NULL)
    {
        return addr;
    }

    int const count = snprintf(addr,
                               PSEUDO_ADDR_LEN,
                               "&%" PRIxPTR,
                               (uintptr_t) s);

    if (count < 0 || count >= (int) PSEUDO_ADDR_LEN)
    {
        OIC_LOG(ERROR,
                TAG,
                "Error creating peer address on server side.");

        OICFree(addr);

        return NULL;
    }

    return addr;
}

CAGattService * CAGattServiceDecodeAddress(char const * address)
{
    /*
      The peer address is actually the value of the pointer to the
      CAGattService object containing the response characteristic.
     */
    uintptr_t s = (uintptr_t) NULL;
    (void) sscanf(address, "&%" SCNxPTR, &s);

    return (CAGattService *) s;
}

bool CAGattServiceInitialize(CAGattService * s,
                             char const * hci_name,
                             CALEContext * context)
{
    assert(s != NULL);
    assert(context != NULL);
    assert(hci_name != NULL);

    // Path of the form /org/iotivity/gatt/hci0/service0.
    s->object_path =
        g_strdup_printf("%s/%s/%s",
                        CA_GATT_SERVICE_ROOT_PATH,
                        hci_name,
                        CA_GATT_SERVICE_PATH);

    assert(g_variant_is_object_path(s->object_path));

    s->object_manager = object_manager_skeleton_new();
    s->service = gatt_service1_skeleton_new();

    gatt_service1_set_uuid(s->service, CA_GATT_SERVICE_UUID);
    gatt_service1_set_primary(s->service, TRUE);

    if (!CAGattRequestCharacteristicInitialize(s, context)
        || !CAGattResponseCharacteristicInitialize(s, context))
    {
        CAGattServiceDestroy(s);
        return false;
    }

    /*
      The characteristic object paths are not fixed at compile-time.
      Retrieve the object paths that were set at run-time.
    */
    char const * const characteristic_paths[] = {
        s->request_characteristic.object_path,
        s->response_characteristic.object_path,
        NULL
    };

    gatt_service1_set_characteristics(s->service, characteristic_paths);

    /*
      Set the org.freedesktop.DBus.ObjectManager.GetManagedObjects()
      handler for our BlueZ GATT service.
    */
    g_signal_connect(
        s->object_manager,
        "handle-get-managed-objects",
        G_CALLBACK(CAGattServiceHandleGetManagedObjects),
        s);

    /*
      BlueZ expects both the org.freedesktop.DBus.ObjectManager and
      org.bluez.GattService1 interfaces to be rooted at the same
      object path.  Export the service and object manager interface
      skeletons with the same object path.
     */
    GError * error = NULL;
    if (!g_dbus_interface_skeleton_export(
            G_DBUS_INTERFACE_SKELETON(s->object_manager),
            context->connection,
            s->object_path,
            &error)
        || !g_dbus_interface_skeleton_export(
            G_DBUS_INTERFACE_SKELETON(s->service),
            context->connection,
            s->object_path,
            &error))
    {
        OIC_LOG_V(ERROR,
                  TAG,
                  "Unable to export GATT service interfaces: %s",
                  error->message);

        return false;
    }

    return true;
}

void CAGattServiceDestroy(CAGattService * s)
{
    /**
     * @todo If necessary, emit the
     *       @c org.freedesktop.DBus.ObjectManager.InterfacesRemoved
     *       signal via @c object_manager_emit_interfaces_removed() if
     *       the CA GATT service objects were removed from the
     *       @c ObjectManager.
     */

    assert(s != NULL);  // As designed, s is always non-NULL.

    g_clear_object(&s->gatt_manager);

    CAGattCharacteristicDestroy(&s->response_characteristic);
    CAGattCharacteristicDestroy(&s->request_characteristic);

    g_clear_object(&s->service);
    g_clear_object(&s->object_manager);

    g_free(s->object_path);
    s->object_path = NULL;
}


text:
=head1 NAME

Cache::RemovalStrategy - abstract Removal Strategy interface for a Cache

=head1 DESCRIPTION

=head1 METHODS

=over

=cut
package Cache::RemovalStrategy;

require 5.006;
use strict;
use warnings;
use Carp;

our $VERSION = '2.04';

sub new {
    my Cache::RemovalStrategy $self = shift;

    ref $self or croak 'Must use a subclass of Cache::RemovalStrategy';
    return $self;
}

=item $r->remove_size( $cache, $size )

When invoked, removes entries from the cache that total at least $size in
size.

=cut

sub remove_size;

1;
__END__

=head1 SEE ALSO

Cache

=head1 AUTHOR

 Chris Leishman <chris@leishman.org>
 Based on work by DeWitt Clinton <dewitt@unto.net>

=head1 COPYRIGHT

 Copyright (C) 2003-2006 Chris Leishman.  All Rights Reserved.

This module is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND,
either expressed or implied. This program is free software; you can
redistribute or modify it under the same terms as Perl itself.

$Id: RemovalStrategy.pm,v 1.4 2006/01/31 15:23:58 caleishm Exp $

=cut


text:
<!DOCTYPE html>
<html>
  <head>
    <title>Fauxe is proudly part of HODUTU family</title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>


text:
Goal of this document is to describe how kilda works with switches that supports
multi-table mode.

## Kilda OF Rules

There are 4 types of rules that controller installs to the switch:
* Default Rules
* Ingress Rules
* Transit Rules
* Egress Rules

### Default Rules

Kilda has set of default switch rules that handles telemetry and discovery process and also
verify link consistency:

* Drop Rule - custom rule to track all unresolved or un-routable packets
* Verification Broadcast rule - catches discovery packets and passes them back to speaker
* Verification Unicast rule - catches customer flow ping packets and passes them back to speaker
* Drop Verification Loop rule - prevents flood of discovery packets among switches
* Catch BFD rule - catch bdf telemetry packets and passes them to the switch
* Round Trip Latency Rule - copies disco packets with timestamp writing and passes it back to speaker
* Verification Unicast VxLAN rule - catches customer flow ping packets for vxlan encapsulated flow

### Customer Flow Rules

Along with default rules there are 4 types that belongs to customer flows

* Ingress Flow rule - match packet by port/vlan encapsulate it with vlan/vxlan and passes to the next hop
* Single Switch Flow rule match packet by port/vlan optionally re-tag packet and pass it to customer port
* Transit Flow rule - match packet by port and (transit vlan/vxlan) and pass to the next hop
* Egress Flow rule - match packet by port and (transit vlan/vxlan) removes transit encapsulation in case of
vxlan and optionally retags vlan, after that passes packet out to customer port

## Single-Table Mode Design

In a single-table mode all flows are being installed in table 0. This approach is very straightforward,
but at the same time doesn't allow build flexible solutions, i.e. q-n-q, applications, etc. Since all flows
are placed in a single table you couldn't properly use metadata and can suffer from table size limitations.
For mode details on single-table mode refer [Single Table Mode](SingleTableMode.pdf)

## Multi-Table Mode

To address problems of single-table mode it's proposed to split rules by tables and specify a set of additional
rules that will wire them them together. In this mode controller will operate 7 tables of the switch:
* Input table(0) - entry point for the packet
* Pre Ingress Table(1) - first table in a chain to handle customer port traffic could contain additional matches.
* Ingress Table(2) - second table in a chain for the ingress traffic
* Post Ingress Table(3) - last table in a chain for the ingress traffic
* Egress Table(4) - table for egress rules
* Transit Table(5) - table for transit rules
* Applications Table(6) - table for mirroring traffic based on enabled apps for flow

Aggregated list of rules for Multi-Table Mode is available  [here](MultiTableMode.pdf).

### Input Table Rules

In multi-table mode input table(0) is responsible for doing several things:
* Provide backward compatibility for single-table mode customer flows
* Color traffic by port and pass it to proper table
* Maintain default rules

Here is a set of possible rules and it's actions that could be placed in a table(0):
![Table_0](Table_0.png "Table 0")

#### Service Default Rules

To dispatch packet to proper tables there are should be additional set of rules:

* Ingress Pass Through rules - matches traffic by port and passes them to ingress tables.
* VxLAN Egress rule - matches traffic by eth_dst and vxlan ports and pass it directly into Egress table(VxLan shortcut)
* VxLAN Transit rule - matches traffic by in port and vxlan ports and pass it directly into Transit table(VxLan shortcut)
* Isl Vlan Egress rule - if traffic comes from ISL port but doesn't have VxLAN encapsulation, pass it to egress table for futher processing.
NOTICE: Egress Table defaulted to passing packets down to transit. This one is made since it's impossible to figure out whether
the switch is terminating for customer flow or transit. For details check VxLAN vs VLAN encapsulation.

#### Backward-compatibility

While process of switching to Multi-Table mode all existing flows will remain in table 0 as they are in a
Single-Table mode. Service default rules won't steal it's traffic since they has priority lower than these rules.

### Pre Ingress Table Rules

Pre Ingress Table could be used as a first step in ingress packets handling, notice that it's default fallback
is to pass traffic to ingress table.

 ![Table_Pre Ingress](Table_PreIngress.png "Table Pre Ingress")

### Ingress Table Rules

Ingress Table could be used as a second step in ingress packets handling, notice by default it drops packet.

 ![Table Ingress](Table_Ingress.png "Table Ingress")

### Post Ingress Table Rules

Post Ingress Table is a third table in ingress packet processing, notice by default it drops packet.

 ![Table PostIngress](Table_PostIngress.png "Table Post Ingress")

### Egress Table Rules

Egress Table contains rule to retag customer packets and remove vxlan, by default it passes packet down to Transit Table.

 ![Table Egress](Table_Egress.png "Table Egress")

### Transit Table Rules

Transit Table pass traffic to the next switch, by default drops unmatched packets.

 ![Table Transit](Table_Transit.png "Table Transit")

## Modes Change and Customer Flow migration

To migrate to Multi-Table mode operator should do the following steps for each switch:

* Enable MultiTable for the switch via NorthBound API see `PUT` `/v1/switches/{switch-id}/properties`.
* Validate switch and verify that there are no rule discrepancies
* Sync flow that goes through the switch one by one, starting from `default` flows
* Validate switch and verify that all rules are installed, check flow statistics for the traffic details.

NOTE: In case of migration from Multi-Table to Single-Table mode all the steps remain the same, except flow sync.
Operator should start migrating `non-default` flows first and finish with default ones.

To change mode of the existing switch from Single-Table to Multi-Table operator should use
switch properties endpoint in the Northbound API.

NOTE: change of the mode will cause switch sync procedure. It's responsible to create default and service rules
for the mode setup. But will not migrate customer flow to the new pipeline.

IMPORTANT: if the switch is operating in multi-table mode and there are multi-table customer flow on it, changing
property back want remove default and service rules. Since they are required for the customer flow rules.

Flow migration to from one mode to another could be achieved by various ways:
* Flow sync
* Flow update
* Flow re-route(NOTE: reroute will migrate flow only if it happens. The re-route logic assures that the current flow
path and new one is not the same and the flow is not in up state. If the checks passes actual re-route will happen)

NOTE: default flows should be migrated to multi-table mode first.

## Implementation Details

### Isl Lifecycle Management

Refer isl service rule lifecycle management  [here](../network-discovery/ISL-FSM.png)

### Database changes

For the smooth flow migration to the Multi-Table pipeline new fields were added to the `Flow`
and `PathSegment` nodes. `src_with_multi_table` and `dst_with_multi_table` are boolean flags
that are responsible for tracking information about actual state in which the flow was created
per each switch respectively. NOTE: since single switch flows doesn't have path segments in DB,
the tracking is made on the both levels.

New switch property and kilda configuration parameters are introduced and added to rest api as well.
Kilda configuration is responsible for handling newly added switches, while switch property changes
switch mode on the fly.


text:
@interface LBViewController : UIViewController <LBYouTubePlayerControllerDelegate> {
    LBYouTubePlayerController* controller;
}

@property (nonatomic, strong) LBYouTubePlayerController* controller;

@end