text:
<?php

namespace Zend\Db\Metadata\Source;

use Zend\Db\Adapter\Adapter;

class PostgresqlMetadata extends AbstractSource
{
    protected function loadSchemaData()
    {
        if (isset($this->data['schemas'])) {
            return;
        }
        $this->prepareDataHierarchy('schemas');

        $p = $this->adapter->getPlatform();

        $sql = 'SELECT ' . $p->quoteIdentifier('schema_name')
            . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'schemata'))
            . ' WHERE ' . $p->quoteIdentifier('schema_name')
            . ' != \'information_schema\''
            . ' AND ' . $p->quoteIdentifier('schema_name') . " NOT LIKE 'pg_%'";

        $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);

        $schemas = array();
        foreach ($results->toArray() as $row) {
            $schemas[] = $row['schema_name'];
        }

        $this->data['schemas'] = $schemas;
    }

    protected function loadTableNameData($schema)
    {
        if (isset($this->data['table_names'][$schema])) {
            return;
        }
        $this->prepareDataHierarchy('table_names', $schema);

        $p = $this->adapter->getPlatform();

        $isColumns = array(
            array('t', 'table_name'),
            array('t', 'table_type'),
            array('v', 'view_definition'),
            array('v', 'check_option'),
            array('v', 'is_updatable'),
        );

        array_walk($isColumns, function (&$c) use ($p) { $c = $p->quoteIdentifierChain($c); });

        $sql = 'SELECT ' . implode(', ', $isColumns)
            . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'tables')) . ' t'

            . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'views')) . ' v'
            . ' ON ' . $p->quoteIdentifierChain(array('t', 'table_schema'))
            . '  = ' . $p->quoteIdentifierChain(array('v', 'table_schema'))
            . ' AND ' . $p->quoteIdentifierChain(array('t', 'table_name'))
            . '  = ' . $p->quoteIdentifierChain(array('v', 'table_name'))

            . ' WHERE ' . $p->quoteIdentifierChain(array('t', 'table_type'))
            . ' IN (\'BASE TABLE\', \'VIEW\')';

        if ($schema != self::DEFAULT_SCHEMA) {
            $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema'))
                . ' = ' . $p->quoteTrustedValue($schema);
        } else {
            $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema'))
                . ' != \'information_schema\'';
        }

        $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);

        $tables = array();
        foreach ($results->toArray() as $row) {
            $tables[$row['table_name']] = array(
                'table_type' => $row['table_type'],
                'view_definition' => $row['view_definition'],
                'check_option' => $row['check_option'],
                'is_updatable' => ('YES' == $row['is_updatable']),
            );
        }

        $this->data['table_names'][$schema] = $tables;
    }

    protected function loadColumnData($table, $schema)
    {
        if (isset($this->data['columns'][$schema][$table])) {
            return;
        }

        $this->prepareDataHierarchy('columns', $schema, $table);

        $platform = $this->adapter->getPlatform();

        $isColumns = array(
            'table_name',
            'column_name',
            'ordinal_position',
            'column_default',
            'is_nullable',
            'data_type',
            'character_maximum_length',
            'character_octet_length',
            'numeric_precision',
            'numeric_scale',
        );

        array_walk($isColumns, function (&$c) use ($platform) { $c = $platform->quoteIdentifier($c); });

        $sql = 'SELECT ' . implode(', ', $isColumns)
            . ' FROM ' . $platform->quoteIdentifier('information_schema')
            . $platform->getIdentifierSeparator() . $platform->quoteIdentifier('columns')
            . ' WHERE ' . $platform->quoteIdentifier('table_schema')
            . ' != \'information\''
            . ' AND ' . $platform->quoteIdentifier('table_name')
            . ' = ' . $platform->quoteTrustedValue($table);

        if ($schema != '__DEFAULT_SCHEMA__') {
            $sql .= ' AND ' . $platform->quoteIdentifier('table_schema')
                . ' = ' . $platform->quoteTrustedValue($schema);
        }

        $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);
        $columns = array();
        foreach ($results->toArray() as $row) {
            $columns[$row['column_name']] = array(
                'ordinal_position'          => $row['ordinal_position'],
                'column_default'            => $row['column_default'],
                'is_nullable'               => ('YES' == $row['is_nullable']),
                'data_type'                 => $row['data_type'],
                'character_maximum_length'  => $row['character_maximum_length'],
                'character_octet_length'    => $row['character_octet_length'],
                'numeric_precision'         => $row['numeric_precision'],
                'numeric_scale'             => $row['numeric_scale'],
                'numeric_unsigned'          => null,
                'erratas'                   => array(),
            );
        }

        $this->data['columns'][$schema][$table] = $columns;
    }

    protected function loadConstraintData($table, $schema)
    {
        if (isset($this->data['constraints'][$schema][$table])) {
            return;
        }

        $this->prepareDataHierarchy('constraints', $schema, $table);

        $isColumns = array(
            array('t', 'table_name'),
            array('tc', 'constraint_name'),
            array('tc', 'constraint_type'),
            array('kcu', 'column_name'),
            array('cc', 'check_clause'),
            array('rc', 'match_option'),
            array('rc', 'update_rule'),
            array('rc', 'delete_rule'),
            array('referenced_table_schema' => 'kcu2', 'table_schema'),
            array('referenced_table_name' => 'kcu2', 'table_name'),
            array('referenced_column_name' => 'kcu2', 'column_name'),
        );

        $p = $this->adapter->getPlatform();

        array_walk($isColumns, function (&$c) use ($p) {
            $alias = key($c);
            $c = $p->quoteIdentifierChain($c);
            if (is_string($alias)) {
                $c .= ' ' . $p->quoteIdentifier($alias);
            }
        });

        $sql = 'SELECT ' . implode(', ', $isColumns)
             . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'tables')) . ' t'

             . ' INNER JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'table_constraints')) . ' tc'
             . ' ON ' . $p->quoteIdentifierChain(array('t', 'table_schema'))
             . '  = ' . $p->quoteIdentifierChain(array('tc', 'table_schema'))
             . ' AND ' . $p->quoteIdentifierChain(array('t', 'table_name'))
             . '  = ' . $p->quoteIdentifierChain(array('tc', 'table_name'))

             . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'key_column_usage')) . ' kcu'
             . ' ON ' . $p->quoteIdentifierChain(array('tc', 'table_schema'))
             . '  = ' . $p->quoteIdentifierChain(array('kcu', 'table_schema'))
             . ' AND ' . $p->quoteIdentifierChain(array('tc', 'table_name'))
             . '  = ' . $p->quoteIdentifierChain(array('kcu', 'table_name'))
             . ' AND ' . $p->quoteIdentifierChain(array('tc', 'constraint_name'))
             . '  = ' . $p->quoteIdentifierChain(array('kcu', 'constraint_name'))

             . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'check_constraints')) . ' cc'
             . ' ON ' . $p->quoteIdentifierChain(array('tc', 'constraint_schema'))
             . '  = ' . $p->quoteIdentifierChain(array('cc', 'constraint_schema'))
             . ' AND ' . $p->quoteIdentifierChain(array('tc', 'constraint_name'))
             . '  = ' . $p->quoteIdentifierChain(array('cc', 'constraint_name'))

             . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'referential_constraints')) . ' rc'
             . ' ON ' . $p->quoteIdentifierChain(array('tc', 'constraint_schema'))
             . '  = ' . $p->quoteIdentifierChain(array('rc', 'constraint_schema'))
             . ' AND ' . $p->quoteIdentifierChain(array('tc', 'constraint_name'))
             . '  = ' . $p->quoteIdentifierChain(array('rc', 'constraint_name'))

             . ' LEFT JOIN ' . $p->quoteIdentifierChain(array('information_schema', 'key_column_usage')) . ' kcu2'
             . ' ON ' . $p->quoteIdentifierChain(array('rc', 'unique_constraint_schema'))
             . '  = ' . $p->quoteIdentifierChain(array('kcu2', 'constraint_schema'))
             . ' AND ' . $p->quoteIdentifierChain(array('rc', 'unique_constraint_name'))
             . '  = ' . $p->quoteIdentifierChain(array('kcu2', 'constraint_name'))
             . ' AND ' . $p->quoteIdentifierChain(array('kcu', 'position_in_unique_constraint'))
             . '  = ' . $p->quoteIdentifierChain(array('kcu2', 'ordinal_position'))

             . ' WHERE ' . $p->quoteIdentifierChain(array('t', 'table_name'))
             . ' = ' . $p->quoteTrustedValue($table)
             . ' AND ' . $p->quoteIdentifierChain(array('t', 'table_type'))
             . ' IN (\'BASE TABLE\', \'VIEW\')';

        if ($schema != self::DEFAULT_SCHEMA) {
            $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema'))
            . ' = ' . $p->quoteTrustedValue($schema);
        } else {
            $sql .= ' AND ' . $p->quoteIdentifierChain(array('t', 'table_schema'))
            . ' != \'information_schema\'';
        }

        $sql .= ' ORDER BY CASE ' . $p->quoteIdentifierChain(array('tc', 'constraint_type'))
              . " WHEN 'PRIMARY KEY' THEN 1"
              . " WHEN 'UNIQUE' THEN 2"
              . " WHEN 'FOREIGN KEY' THEN 3"
              . " WHEN 'CHECK' THEN 4"
              . " ELSE 5 END"
              . ', ' . $p->quoteIdentifierChain(array('tc', 'constraint_name'))
              . ', ' . $p->quoteIdentifierChain(array('kcu', 'ordinal_position'));

        $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);

        $name = null;
        $constraints = array();
        foreach ($results->toArray() as $row) {
            if ($row['constraint_name'] !== $name) {
                $name = $row['constraint_name'];
                $constraints[$name] = array(
                    'constraint_name' => $name,
                    'constraint_type' => $row['constraint_type'],
                    'table_name'      => $row['table_name'],
                );
                if ('CHECK' == $row['constraint_type']) {
                    $constraints[$name]['check_clause'] = $row['check_clause'];
                    continue;
                }
                $constraints[$name]['columns'] = array();
                $isFK = ('FOREIGN KEY' == $row['constraint_type']);
                if ($isFK) {
                    $constraints[$name]['referenced_table_schema'] = $row['referenced_table_schema'];
                    $constraints[$name]['referenced_table_name']   = $row['referenced_table_name'];
                    $constraints[$name]['referenced_columns']      = array();
                    $constraints[$name]['match_option']       = $row['match_option'];
                    $constraints[$name]['update_rule']        = $row['update_rule'];
                    $constraints[$name]['delete_rule']        = $row['delete_rule'];
                }
            }
            $constraints[$name]['columns'][] = $row['column_name'];
            if ($isFK) {
                $constraints[$name]['referenced_columns'][] = $row['referenced_column_name'];
            }
        }

        $this->data['constraints'][$schema][$table] = $constraints;
    }

    protected function loadTriggerData($schema)
    {
        if (isset($this->data['triggers'][$schema])) {
            return;
        }

        $this->prepareDataHierarchy('triggers', $schema);

        $p = $this->adapter->getPlatform();

        $isColumns = array(
            'trigger_name',
            'event_manipulation',
            'event_object_catalog',
            'event_object_schema',
            'event_object_table',
            'action_order',
            'action_condition',
            'action_statement',
            'action_orientation',
            array('action_timing' => 'condition_timing'),
            array('action_reference_old_table' => 'condition_reference_old_table'),
            array('action_reference_new_table' => 'condition_reference_new_table'),
            'created',
        );

        array_walk($isColumns, function (&$c) use ($p) {
            if (is_array($c)) {
                $alias = key($c);
                $c = $p->quoteIdentifierChain($c);
                if (is_string($alias)) {
                    $c .= ' ' . $p->quoteIdentifier($alias);
                }
            } else {
                $c = $p->quoteIdentifier($c);
            }
        });

        $sql = 'SELECT ' . implode(', ', $isColumns)
            . ' FROM ' . $p->quoteIdentifierChain(array('information_schema', 'triggers'))
            . ' WHERE ';

        if ($schema != self::DEFAULT_SCHEMA) {
            $sql .= $p->quoteIdentifier('trigger_schema')
                . ' = ' . $p->quoteTrustedValue($schema);
        } else {
            $sql .= $p->quoteIdentifier('trigger_schema')
                . ' != \'information_schema\'';
        }

        $results = $this->adapter->query($sql, Adapter::QUERY_MODE_EXECUTE);

        $data = array();
        foreach ($results->toArray() as $row) {
            $row = array_change_key_case($row, CASE_LOWER);
            $row['action_reference_old_row'] = 'OLD';
            $row['action_reference_new_row'] = 'NEW';
            if (null !== $row['created']) {
                $row['created'] = new \DateTime($row['created']);
            }
            $data[$row['trigger_name']] = $row;
        }

        $this->data['triggers'][$schema] = $data;
    }
}


text:
SYNONYM

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

#### Published in
null

#### Original name
Sacidium cystotricha Schulzer, 1871

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package limelight.ui.events.panel;

import org.junit.Test;

import static junit.framework.Assert.assertEquals;

public class ValueChangedEventTest
{
  @Test
  public void isNotInheritable() throws Exception
  {
    assertEquals(false, new ValueChangedEvent().isInheritable());
  }

}


text:
require "fluent/plugin/formatter_linebyline/version"

module Fluent
  module TextFormatter
    class FormatterLinebyline
      include Configurable # This enables the use of config_param

      #config_param :parameter_name, :type   defines configuration parameters

      def configure(conf)
        #Does nothing because no config parameters.  Left for plugin requirements.
      end

      def format(tag, time, record)

      	seperationLine = "----------------"
      	outputArray = [seperationLine, tag, time, ""]

        record.each do |key, value|
        	line = key + " : " + value
        	outputArray << line
        end

        outputArray.join("\n");
      end
    end

    register_template("linebyline", Proc.new { FormatterLinebyline.new })
  end
end


text:
import os
import fnmatch

from setuptools import setup, find_packages
from pip.req import parse_requirements
from Cython.Build import cythonize

reqs = [str(r.req)
        for r in parse_requirements('requirements.txt', session=False)]
reqs.append("MySQL-python==1.2.5")

pyx_files = list()
for dirpath, dirnames, files in os.walk('./app'):
    for file in fnmatch.filter(files, '*.pyx'):
        pyx_files.append(os.path.join(dirpath, file))
pyx_extensions = cythonize(pyx_files)

setup(
    name='2L',
    version='0.0.1',
    description='2L, There is a surprise!',
    long_description='2L, SB! BIG S! BIG B! BIG SB!!!',
    url='https://github.com/Damnever/2L',
    author='Damnever',
    author_emial='dxc.wolf@gmail.com',
    license='The BSD 3-Clause License',
    keywords='bbs, forum, 2L',
    classifiers=[
        'License :: OSI Approved :: BSD License',
        'Programming Language :: Python :: 2',
        'Programming Language :: Python :: 3',
    ],
    packages=find_packages(),
    include_package_data=True,
    install_requires=reqs,
    ext_modules=pyx_extensions,
    entry_points={
        'console_scripts': [
            '2L=app.commands:main',
        ]
    },
)


text:
title: "Tiistain tunnille"
tags: läksyt rub6.4
---

Katso pääsiäisloman aikana ruotsinkielinen elokuva, ruotsin teksteillä (mielellään leffa, mutta jos sarja, katso väh. 1h30min).

Valmistaudu kertomaan elokuvasta perustiedot, jotain juonesta ja tietysti mahdollisimman monipuolisesti oma mielipiteesi siitä.


text:
using FrazzApps.Xamarin.GestureMonitor.Abstractions;
using System;
using Xamarin.Forms;
using FrazzApps.Xamarin.GestureMonitor.WinPhone;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Collections.Generic;
using Xamarin.Forms.Platform.WinPhone;

[assembly: Dependency(typeof(GestureMonitor))]
namespace FrazzApps.Xamarin.GestureMonitor.WinPhone
{
    /// <summary>
    /// GestureMonitor Implementation
    /// </summary>
    public class GestureMonitor : IGestureMonitor
    {
        /// <summary>
        /// Used for registration with dependency service
        /// </summary>
        public static void Init() { }

        public event EventHandler<GestureMonitorEventArgs> GestureOccured;

        internal void RaiseEvent(Element element, GestureMonitorEventArgs eventArgs)
        {
                if (this.GestureOccured!=null)
                this.GestureOccured(element, eventArgs);
        }

        public void MonitorView(View view)
        {
            view.PropertyChanged += (_, propArgs) =>
            {
                // subscribe to UIElement events when the attached property Renderer is set
                if (propArgs.PropertyName == "Renderer")//Platform.RendererProperty.PropertyName)
                {

                    ViewRenderer renderer = view.GetRenderer() as ViewRenderer;
                 //   renderer.Element.BackgroundColor = Color.Red;

                    renderer.Hold += Control_Hold;
                    renderer.DoubleTap += Control_DoubleTap;
                    renderer.Tap += Control_Tap;
                    renderer.ManipulationCompleted += Control_ManipulationCompleted;
                    renderer.ManipulationStarted += Control_ManipulationStarted;
                    renderer.ManipulationDelta += Control_ManipulationDelta;
                }
            };
        }

        void Control_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
          //  e.ManipulationOrigin
        }

        void Control_ManipulationDelta(object sender, System.Windows.Input.ManipulationDeltaEventArgs e)
        {
            Element element = GetElement(sender);

            if (e.PinchManipulation != null)
            {
                double pinch = e.PinchManipulation.CumulativeScale;
                Console.WriteLine("Control_ManipulationDelta pinch = " + pinch);
                if (pinch > 1)
                {
                    this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Stretch));
                    e.Handled = true;
                }
                else if (pinch < 1)
                {
                    this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Pinch));
                    e.Handled = true;
                }
            }
            else if (e.DeltaManipulation != null)
            {
                System.Windows.Point p = e.DeltaManipulation.Translation;
                if (((p.X * p.X) + (p.Y * p.Y)) > 244)
                {
                    this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Swiping));

                    if (p.X > 10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipingRight));
                    }
                    if (p.X < -10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipingLeft));
                    }

                    if (p.Y > 10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipingDown));
                    }
                    if (p.Y < -10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipingUp));
                    }
                }
                else
                {
                    this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Panning));

                    if (p.X > 2)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.PanningRight));
                    }
                    if (p.X < -2)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.PanningLeft));
                    }

                    if (p.Y > 2)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.PanningDown));
                    }
                    if (p.Y < -2)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.PanningUp));
                    }
                }
            }
            else
            {
                Console.WriteLine("Control_ManipulationDelta ");
            }
        }

        void Control_ManipulationCompleted(object sender, System.Windows.Input.ManipulationCompletedEventArgs e)
        {

            if (e.TotalManipulation != null)
            {
                System.Windows.Point p = e.TotalManipulation.Translation;
                if (((p.X * p.X) + (p.Y * p.Y)) > 244)
                {

                    Element element = GetElement(sender);
                    this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Swipe));

                    if (p.X > 10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipeRight));
                    }
                    if (p.X < -10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipeLeft));
                    }

                    if (p.Y> 10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipeDown));
                    }
                    if (p.Y < -10)
                    {
                        this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.SwipeUp));
                    }
                }
            }
        }

        void Control_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Element element = GetElement(sender);
            this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Tap));
        }

        void Control_DoubleTap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Element element = GetElement(sender);
            this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.DoubleTap));
        }

        void Control_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Element element = GetElement(sender);
            this.RaiseEvent(element, new GestureMonitorEventArgs(element, GestureType.Hold));
        }

        Element GetElement(object sender)
        {
            ViewRenderer renderer = sender as ViewRenderer;
            if (renderer == null)
            {
                FrameworkElement control = sender as FrameworkElement;
                renderer = control.Parent as ViewRenderer;
            }

            Element element = renderer.Element;

            return element;
        }
    }
}


text:
[![CircleCI](https://circleci.com/gh/huangsam/chowist.svg?style=svg)](https://circleci.com/gh/huangsam/chowist)

Great places are chosen by great chowists.

This is an application that replicates core features of [Yelp](https://www.yelp.com/), and adds a couple more bells and whistles. A couple features/ideas that are in the process of being created:

- Homepage for marketing purposes
- Profile settings upon user login
- Places as list and detail views

## Getting started

Here are some things to be aware of in development and production.

### Local setup

Install dependencies and create a `virtualenv` instance:

    pipenv install
    pipenv shell

Then run database migration:

    python manage.py migrate

Finally, start up the Django development server:

    python manage.py runserver

For development, you might want test data to validate the app's functionality:

    python manage.py loaddata restaurant user

This loads restaurants and an `admin` user with password `admin`. The `admin` user allows you to enter the Django dashboard and view users/groups/data in a consolidated view.

**Note:** `DJANGO_SECRET` must be set to `dummy` for the `admin` user to work. Otherwise, you will need to create a new superuser with `python manage.py createsuperuser`.

### Dockerized setup

To finish the complete local setup with Docker:

    docker-compose -f compose/dev.yml -p chowist up --build -d

### Production setup

For production, you might want to use `gunicorn` for running the server:

    gunicorn -w 4 chowist.wsgi

When using Gunicorn, remember to host the static files from a web server.

## How to contribute

Feel free to create pull requests to the following assets:

- Update Django application logic
- Update media content (`JPG`, `SVG`, etc.)
- Add restaurants into `restaurant.json`


text:
title: Search
permalink: "/search/"
layout: page
sitemap: false
---

{% include _google_search.html %}


text:
package filter

import (
	"errors"

	magent "github.com/Dataman-Cloud/swan/mesos/agent"
)

var (
	errNoSatisfiedAgent = errors.New("no satisfied agent")
)

type constraintsFilter struct{}

func NewConstraintsFilter() *constraintsFilter {
	return &constraintsFilter{}
}

func (f *constraintsFilter) Filter(opts *FilterOptions, agents []*magent.Agent) ([]*magent.Agent, error) {
	var (
		constraints = opts.Constraints
		candidates  = make([]*magent.Agent, 0)
	)

	for _, agent := range agents {
		match := true
		for _, constraint := range constraints {
			if constraint.Match(agent.Attributes()) {
				continue
			}
			match = false
			break
		}

		if match {
			candidates = append(candidates, agent)
		}
	}

	if len(candidates) == 0 {
		return nil, errNoSatisfiedAgent
	}
	return candidates, nil
}


text:
use libc::{c_char, c_int, c_long};
use core::ptr;
use pyport::Py_ssize_t;
use object::PyObject;
use methodobject::PyMethodDef;

#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
    pub fn PyArg_Parse(args: *mut PyObject, format: *const c_char, ...)
     -> c_int;
    pub fn PyArg_ParseTuple(args: *mut PyObject,
                            format: *const c_char, ...)
     -> c_int;
    pub fn PyArg_ParseTupleAndKeywords(args: *mut PyObject,
                                       kw: *mut PyObject,
                                       format: *const c_char,
                                       keywords: *mut *mut c_char, ...)
     -> c_int;
    pub fn PyArg_UnpackTuple(args: *mut PyObject, name: *const c_char,
                             min: Py_ssize_t, max: Py_ssize_t, ...)
     -> c_int;
    pub fn Py_BuildValue(format: *const c_char, ...) -> *mut PyObject;
    //fn _Py_BuildValue_SizeT(arg1: *const c_char, ...)
    // -> *mut PyObject;
    //fn _PyArg_NoKeywords(funcname: *const c_char,
    //                     kw: *mut PyObject) -> c_int;
    pub fn PyModule_AddObject(module: *mut PyObject,
                              name: *const c_char,
                              value: *mut PyObject) -> c_int;
    pub fn PyModule_AddIntConstant(module: *mut PyObject,
                                   name: *const c_char,
                                   value: c_long) -> c_int;
    pub fn PyModule_AddStringConstant(module: *mut PyObject,
                                      name: *const c_char,
                                      value: *const c_char)
     -> c_int;

    #[cfg(all(target_pointer_width = "64", not(py_sys_config = "Py_TRACE_REFS")))]
    fn Py_InitModule4_64(name: *const c_char,
                             methods: *mut PyMethodDef,
                             doc: *const c_char, _self: *mut PyObject,
                             apiver: c_int) -> *mut PyObject;

    #[cfg(all(target_pointer_width = "64", py_sys_config = "Py_TRACE_REFS"))]
    fn Py_InitModule4TraceRefs_64(name: *const c_char,
                                  methods: *mut PyMethodDef,
                                  doc: *const c_char, _self: *mut PyObject,
                                  apiver: c_int) -> *mut PyObject;

    #[cfg(all(not(target_pointer_width = "64"), not(py_sys_config = "Py_TRACE_REFS")))]
    pub fn Py_InitModule4(name: *const c_char,
                             methods: *mut PyMethodDef,
                             doc: *const c_char, _self: *mut PyObject,
                             apiver: c_int) -> *mut PyObject;

    #[cfg(all(not(target_pointer_width = "64"), py_sys_config = "Py_TRACE_REFS"))]
    fn Py_InitModule4TraceRefs(name: *const c_char,
                                  methods: *mut PyMethodDef,
                                  doc: *const c_char, _self: *mut PyObject,
                                  apiver: c_int) -> *mut PyObject;
}

pub const PYTHON_API_VERSION : c_int = 1013;

#[cfg(all(target_pointer_width = "64", not(py_sys_config = "Py_TRACE_REFS")))]
#[inline(always)]
pub unsafe fn Py_InitModule4(name: *const c_char,
                      methods: *mut PyMethodDef,
                      doc: *const c_char, _self: *mut PyObject,
                      apiver: c_int) -> *mut PyObject {
    Py_InitModule4_64(name, methods, doc, _self, apiver)
}

#[cfg(all(target_pointer_width = "64", py_sys_config = "Py_TRACE_REFS"))]
#[inline(always)]
pub unsafe fn Py_InitModule4(name: *const c_char,
                      methods: *mut PyMethodDef,
                      doc: *const c_char, _self: *mut PyObject,
                      apiver: c_int) -> *mut PyObject {
    Py_InitModule4TraceRefs_64(name, methods, doc, _self, apiver)
}

#[cfg(all(not(target_pointer_width = "64"), py_sys_config = "Py_TRACE_REFS"))]
#[inline(always)]
pub unsafe fn Py_InitModule4(name: *const c_char,
                      methods: *mut PyMethodDef,
                      doc: *const c_char, _self: *mut PyObject,
                      apiver: c_int) -> *mut PyObject {
    Py_InitModule4TraceRefs(name, methods, doc, _self, apiver)
}

#[inline(always)]
pub unsafe fn Py_InitModule(name: *const c_char, methods: *mut PyMethodDef) -> *mut PyObject {
    Py_InitModule4(name, methods, ptr::null(), ptr::null_mut(), PYTHON_API_VERSION)
}

#[inline(always)]
pub unsafe fn Py_InitModule3(name: *const c_char, methods: *mut PyMethodDef, doc : *const c_char) -> *mut PyObject {
    Py_InitModule4(name, methods, doc, ptr::null_mut(), PYTHON_API_VERSION)
}


text:
package com.lchtime.safetyexpress.ui.circle.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.lchtime.safetyexpress.R;
import com.lchtime.safetyexpress.adapter.AddSubscribeAdapter;
import com.lchtime.safetyexpress.adapter.HeaderAndFooterWrapper;
import com.lchtime.safetyexpress.bean.AddSubscribBean;
import com.lchtime.safetyexpress.bean.InitInfo;
import com.lchtime.safetyexpress.bean.PostBean;
import com.lchtime.safetyexpress.bean.ProfessionBean;
import com.lchtime.safetyexpress.ui.circle.protocal.CircleProtocal;
import com.lchtime.safetyexpress.ui.vip.SelectCityActivity;
import com.lchtime.safetyexpress.utils.CommonUtils;
import com.lchtime.safetyexpress.utils.SpTools;
import com.lchtime.safetyexpress.utils.refresh.PullLoadMoreRecyclerView;
import com.lchtime.safetyexpress.views.CirclePopView;

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

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by yxn on 2017/4/23.
 */

public class SubscirbeAllFragment extends Fragment implements View.OnClickListener {
    @BindView(R.id.subscribe_all_rc)
    PullLoadMoreRecyclerView pullLoadMoreRecyclerView;
    RecyclerView subscribe_all_rc;
    private CirclePopView cp;

    private List<ProfessionBean.ProfessionItemBean> gwList = new ArrayList<>();
    private Context context;
    private String userid;
    public String currentSelected;
    public static final int CITY_REQUEST_CODE = 0;
    private AddSubscribeAdapter addSubscribeAdapter;
    private CircleProtocal protocal;
    public List<AddSubscribBean.ItemBean> allList = new ArrayList<>();

    private String request_hy = "";
    private String request_gw = "";
    private String request_addr = "";
    private String request_page = "0";
    private int totalPage;

    private HeaderAndFooterWrapper wrapper;
    private LinearLayout subscribe_all_ll;
    private TextView tv_adddy_hy;
    private TextView tv_adddy_gw;
    private TextView tv_adddy_addr;
//    private ImageView hy_indicator;
//    private ImageView gw_indicator;
//    private ImageView addr_indicator;
//    private LinearLayout subscribe_all_work;
//    private LinearLayout subscribe_all_gangwei;
//    private LinearLayout subscribe_all_address;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.subscribe_all_fragment,container,false);
        ButterKnife.bind(this,view);
        return view;
    }

    @Override
    public void onActivityCreated( Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
        initPopwindow();
        initData();

    }

    private void initView() {
        subscribe_all_rc = (RecyclerView) pullLoadMoreRecyclerView.findViewById(R.id.home_new_fragment_rc);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.subscribe_all_header , null);
        subscribe_all_ll = (LinearLayout) view.findViewById(R.id.subscribe_all_ll);
        tv_adddy_hy = (TextView) view.findViewById(R.id.tv_adddy_hy);
        tv_adddy_gw = (TextView) view.findViewById(R.id.tv_adddy_gw);
        tv_adddy_addr = (TextView) view.findViewById(R.id.tv_adddy_addr);
//        hy_indicator = (ImageView) view.findViewById(R.id.iv_hy_indicator);
//        gw_indicator = (ImageView) view.findViewById(R.id.iv_gw_indicator);
//        addr_indicator = (ImageView) view.findViewById(R.id.iv_addr_indicator);
//        subscribe_all_work = (LinearLayout) view.findViewById(R.id.subscribe_all_work);
//        subscribe_all_gangwei = (LinearLayout) view.findViewById(R.id.subscribe_all_gangwei);
//        subscribe_all_address = (LinearLayout) view.findViewById(R.id.subscribe_all_address);

        addSubscribeAdapter = new AddSubscribeAdapter(context,allList,SubscirbeAllFragment.this);
        wrapper = new HeaderAndFooterWrapper(addSubscribeAdapter);
        subscribe_all_rc.setAdapter(wrapper);
        wrapper.addHeaderView(view);
    }

    private Handler handler = new Handler();
    private void initListener() {
        pullLoadMoreRecyclerView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                refreshData("1");
            }

            @Override
            public void onLoadMore() {
                page++;
                if (page > totalPage){
                    CommonUtils.toastMessage("没有更多了");
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                        }
                    },300);

                    return;
                }
                isLoadMore = true;
                refreshData(page + "");
            }
        });
        tv_adddy_hy.setOnClickListener(this);
        tv_adddy_gw.setOnClickListener(this);
        tv_adddy_addr.setOnClickListener(this);
//        subscribe_all_work.setOnClickListener(this);
//        subscribe_all_gangwei.setOnClickListener(this);
//        subscribe_all_address.setOnClickListener(this);

    }

    private void initData() {
        userid = SpTools.getUserId(getContext());
        if (protocal == null){
            protocal = new CircleProtocal();
        }
        String ub_id = userid;
        String hy = request_hy;
        String gw = request_gw;
        String addr = request_addr;
        //0为推荐1为全部
        String action = "1";
        String page = request_page;

        protocal.getAddDyData(ub_id,hy, gw, addr, action, page, new CircleProtocal.NormalListener() {
            @Override
            public void normalResponse(Object response) {
                if (response == null){
                    CommonUtils.toastMessage("获取数据失败,请稍后再试");
                    return;
                }
                AddSubscribBean bean = (AddSubscribBean) response;
                totalPage = bean.totalpage;
                allList.clear();
                if (bean.all != null) {
                    allList.addAll(bean.all);
                }
                wrapper.notifyDataSetChanged();
            }
        });
    }

    //行业选择
    public static final String HANG_YE = "hy";
    //岗位选择
    public static final String GANG_WEI = "gw";
    //地理位置
    public static final String ADDRESS ="addr";
    private boolean hySelected = false;
    private boolean gwSelected = false;
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_adddy_hy:
                //改变ui
                //hy_indicator.setSelected(true);
                //hy_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector_red));
                tv_adddy_hy.setSelected(true);
                //tv_adddy_hy.setBackgroundColor(getResources().getColor(R.color.commen_reg));
                currentSelected = HANG_YE;
                if (InitInfo.professionBean != null) {
                    cp.setDataAdapter(InitInfo.professionBean.hy);

                    cp.showPopWindow(subscribe_all_ll);
                }
                break;
            case R.id.tv_adddy_gw:
                //改变ui
//                gw_indicator.setSelected(true);
//                gw_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector_red));
                tv_adddy_gw.setSelected(true);
                //tv_adddy_gw.setBackgroundColor(getResources().getColor(R.color.commen_reg));
                currentSelected = GANG_WEI;
                if (InitInfo.postBean != null) {
                    if (gwList.size() <= 0) {
                        for (PostBean.PostItemBean bean : InitInfo.postBean.gw) {
                            ProfessionBean.ProfessionItemBean itemBean = new ProfessionBean.ProfessionItemBean();
                            itemBean.isSelect = bean.isSelect;
                            itemBean.hy_name = bean.gw_name;
                            itemBean.hy_id = bean.gw_id;
                            gwList.add(itemBean);
                        }
                    }
                    cp.setDataAdapter(gwList);
                    cp.showPopWindow(subscribe_all_ll);
                }
                break;
            case R.id.tv_adddy_addr:
                String city = tv_adddy_addr.getText().toString();
                currentSelected = ADDRESS;
                Intent intent = new Intent(getActivity(), SelectCityActivity.class);
                intent.putExtra("city" ,city);
                Log.i("qza", "onClick: " +  city);
                startActivityForResult(intent,CITY_REQUEST_CODE);
                break;
        }

    }
//    @OnClick({R.id.subscribe_all_work,R.id.subscribe_all_gangwei,R.id.subscribe_all_address})
//    void setOnclick(View view){
//        switch (view.getId()){
//            case R.id.subscribe_all_work:
//                //改变ui
//                hy_indicator.setSelected(true);
//                hy_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector_red));
//                tv_adddy_hy.setSelected(true);
//                currentSelected = HANG_YE;
//                cp.setDataAdapter(InitInfo.professionBean.hy);
//                cp.showPopWindow(subscribe_all_ll);
//            break;
//            case R.id.subscribe_all_gangwei:
//                //改变ui
//                gw_indicator.setSelected(true);
//                gw_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector_red));
//                tv_adddy_gw.setSelected(true);
//                currentSelected = GANG_WEI;
//                if (gwList.size() <= 0) {
//                    for (PostBean.PostItemBean bean : InitInfo.postBean.gw) {
//                        ProfessionBean.ProfessionItemBean itemBean = new ProfessionBean.ProfessionItemBean();
//                        itemBean.isSelect = bean.isSelect;
//                        itemBean.hy_name = bean.gw_name;
//                        itemBean.hy_id = bean.gw_id;
//                        gwList.add(itemBean);
//                    }
//                }
//                cp.setDataAdapter(gwList);
//                cp.showPopWindow(subscribe_all_ll);
//                break;
//            case R.id.subscribe_all_address:
//                currentSelected = ADDRESS;
//                Intent intent = new Intent(getActivity(), SelectCityActivity.class);
//                startActivityForResult(intent,CITY_REQUEST_CODE);
//                break;
//        }
//
//    }
    private void initPopwindow() {
        subscribe_all_rc.setLayoutManager(new LinearLayoutManager(context));
        cp = new CirclePopView(getActivity());
        cp.setCirclePopInterface(new CirclePopView.CirclePopInterface() {
            @Override
            public void getPopIds(String positions) {
                //筛选条件
                //Toast.makeText(context,"position:===="+positions,Toast.LENGTH_SHORT).show();
                updataPop(positions);
            }
        });

        cp.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                hy_indicator.setSelected(false);
//                gw_indicator.setSelected(false);
//                addr_indicator.setSelected(false);
                if (HANG_YE.equals(currentSelected)&&hySelected == false){
                    tv_adddy_hy.setSelected(false);
                    tv_adddy_hy.setBackgroundColor(getResources().getColor(R.color.bg_f7));
//                    hy_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector));
                }else if(GANG_WEI.equals(currentSelected)&&gwSelected == false){
                    tv_adddy_gw.setSelected(false);
                    tv_adddy_gw.setBackgroundColor(getResources().getColor(R.color.bg_f7));
//                    gw_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector));
                }
            }
        });
    }

    //更新popubwindow标题的ui
    private void updataPop(String positions) {
        if (TextUtils.isEmpty(positions)){
            if (HANG_YE.equals(currentSelected)){
                tv_adddy_hy.setText("行业选择");
                tv_adddy_hy.setSelected(false);
                tv_adddy_hy.setBackgroundColor(getResources().getColor(R.color.bg_f7));
//                hy_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector));
                hySelected = false;
                request_hy = "";
            }else if (GANG_WEI.equals(currentSelected)){
                tv_adddy_gw.setText("岗位选择");
                tv_adddy_gw.setSelected(false);
                tv_adddy_gw.setBackgroundColor(getResources().getColor(R.color.bg_f7));
//                gw_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector));
                gwSelected = false;
                request_gw = "";
            }
        }else {
            String[] arr = positions.split(",");
            String title = "";
            if (HANG_YE.equals(currentSelected)) {
                tv_adddy_hy.setSelected(true);
                //tv_adddy_hy.setBackgroundColor(getResources().getColor(R.color.commen_reg));
//                hy_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector_red));
                hySelected = true;
                request_hy = "";
                for (int i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        title = title + InitInfo.professionBean.hy.get(Integer.parseInt(arr[i])).hy_name;
                        request_hy = request_hy + InitInfo.professionBean.hy.get(Integer.parseInt(arr[i])).hy_name;
                    } else {
                        title = title + "," + InitInfo.professionBean.hy.get(Integer.parseInt(arr[i])).hy_name;
                        request_hy = request_hy + "-" + InitInfo.professionBean.hy.get(Integer.parseInt(arr[i])).hy_name;
                    }
                }
                tv_adddy_hy.setText(title);
            } else if (GANG_WEI.equals(currentSelected)) {
                request_gw = "";
                tv_adddy_gw.setSelected(true);
                //tv_adddy_hy.setBackgroundColor(getResources().getColor(R.color.commen_reg));
//                gw_indicator.setImageDrawable(getResources().getDrawable(R.drawable.circle_indicator_selector_red));
                gwSelected = true;
                for (int i = 0; i < arr.length; i++) {
                    if (i == 0) {
                        title = title + gwList.get(Integer.parseInt(arr[i])).hy_name;
                        request_gw = request_gw + gwList.get(Integer.parseInt(arr[i])).hy_name;
                    } else {
                        title = title + "," + gwList.get(Integer.parseInt(arr[i])).hy_name;
                        request_gw = request_gw + "-" + gwList.get(Integer.parseInt(arr[i])).hy_name;
                    }
                }
                tv_adddy_gw.setText(title);
            }
        }
        refreshData("1");

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CITY_REQUEST_CODE){
            if (data != null) {
             /*   String selectCity = data.getStringExtra("city");
                request_addr = selectCity;
                refreshData("1");
                tv_adddy_addr.setText(selectCity);*/
                String selectCity = data.getStringExtra("city");
                //  Log.i("----------", "onActivityResult: " + selectCity);
                if(!"地理位置".equals(selectCity)){
                    request_addr = selectCity;
                    refreshData("1");
                    tv_adddy_addr.setText(selectCity);
                    //Log.i("----------", "onActivityResult:1 " + selectCity);
                }else{
                    request_addr = "";
                    refreshData("1");
                    tv_adddy_addr.setText("地理位置");
                    //  Log.i("----------", "onActivityResult:2 " + "地理位置");
                }
            }
        }
    }
    private int page= 1;
    private boolean isLoadMore = false;
    public void refreshData(String page) {
        String ub_id = userid;
        String hy = request_hy;
        String gw = request_gw;
        String addr = request_addr;
        //0为推荐1为全部
        String action = "1";

        protocal.getAddDyData(ub_id, hy, gw, addr, action, page, new CircleProtocal.NormalListener() {
            @Override
            public void normalResponse(Object response) {
                if (response == null){
                    CommonUtils.toastMessage("请检查网络");
                    pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                    return;
                }
                AddSubscribBean bean = (AddSubscribBean) response;
                totalPage = bean.totalpage;
                if (!isLoadMore) {
                    allList.clear();
                }
                if(bean.all != null) {
                    allList.addAll(bean.all);
                }
                wrapper.notifyDataSetChanged();
                pullLoadMoreRecyclerView.setPullLoadMoreCompleted();
                isLoadMore = false;
            }
        });
    }

}


text:
layout: page
title: Kramer 40th Anniversary
date: 2016-05-24
author: Jonathan Duarte
tags: weekly links, java
status: published
summary: Cras suscipit odio id dolor feugiat cursus. Nullam placerat, nunc.
banner: images/banner/office-01.jpg
booking:
  startDate: 10/24/2016
  endDate: 10/29/2016
  ctyhocn: MRTTNHX
  groupCode: K4A
published: true
---
Duis sed pretium ante, sit amet laoreet nibh. Maecenas vulputate pellentesque pharetra. Cras egestas blandit nisl. Nam tincidunt hendrerit lectus non congue. Mauris ac ante dapibus, molestie odio ac, posuere arcu. Proin bibendum justo nec eros rhoncus, hendrerit blandit nisl consectetur. Sed dui lectus, tempor a molestie sit amet, congue id sapien. Aliquam erat volutpat. Nam vel leo ante. Integer interdum maximus massa, in dignissim dui auctor ut. Vestibulum rutrum bibendum leo et euismod. Maecenas tortor massa, sodales interdum velit quis, vestibulum iaculis massa. Phasellus vitae luctus metus, vestibulum sagittis leo. Morbi mollis mauris vitae ante ullamcorper fringilla. Pellentesque interdum erat at sollicitudin aliquet.
Nullam sit amet urna eros. Sed id tempor elit. Praesent sit amet commodo sapien. Aliquam ligula neque, elementum a interdum at, cursus nec purus. Proin cursus rutrum ipsum. Nullam a nulla magna. Donec commodo lectus nunc, ac mattis velit feugiat at. Proin pharetra ligula nec est auctor, eget ultrices risus volutpat.

1 Vestibulum eget mauris nec felis facilisis maximus
1 Nullam ac mauris eget sapien sagittis consequat
1 Praesent faucibus mi eu lorem ultricies blandit
1 Ut iaculis nisl eu neque semper, vel egestas lacus gravida
1 Donec dapibus quam quis gravida tincidunt.

Donec sit amet pulvinar lectus. Aenean quis varius ipsum. Pellentesque vehicula est tincidunt pharetra tincidunt. Nunc eleifend nisl metus, sed tempor arcu pharetra et. Integer sodales libero ut velit venenatis, a vulputate sapien cursus. Praesent a eros quis lectus cursus imperdiet in a tortor. Nunc a enim posuere, elementum lacus a, lacinia ex. Aliquam eget nisl sed mi finibus lacinia. Cras et dui vel metus ultrices egestas. Aenean non blandit ex. Nunc id velit scelerisque libero fringilla tempus at non urna.


text:
mkdir -p "$PREFIX/bin"
export MACHTYPE=x86_64
export BINDIR=$(pwd)/bin
mkdir -p "$BINDIR"
(cd kent/src/lib && make)
(cd kent/src/htslib && make)
(cd kent/src/jkOwnLib && make)
(cd kent/src/hg/lib && make)
(cd kent/src/hg/utils/positionalTblCheck && make)
cp bin/positionalTblCheck "$PREFIX/bin"
chmod +x "$PREFIX/bin/positionalTblCheck"


text:
<?php

class Google_Service_Drive_DriveRestrictions extends Google_Model
{
  public $adminManagedRestrictions;
  public $copyRequiresWriterPermission;
  public $domainUsersOnly;
  public $driveMembersOnly;

  public function setAdminManagedRestrictions($adminManagedRestrictions)
  {
    $this->adminManagedRestrictions = $adminManagedRestrictions;
  }
  public function getAdminManagedRestrictions()
  {
    return $this->adminManagedRestrictions;
  }
  public function setCopyRequiresWriterPermission($copyRequiresWriterPermission)
  {
    $this->copyRequiresWriterPermission = $copyRequiresWriterPermission;
  }
  public function getCopyRequiresWriterPermission()
  {
    return $this->copyRequiresWriterPermission;
  }
  public function setDomainUsersOnly($domainUsersOnly)
  {
    $this->domainUsersOnly = $domainUsersOnly;
  }
  public function getDomainUsersOnly()
  {
    return $this->domainUsersOnly;
  }
  public function setDriveMembersOnly($driveMembersOnly)
  {
    $this->driveMembersOnly = $driveMembersOnly;
  }
  public function getDriveMembersOnly()
  {
    return $this->driveMembersOnly;
  }
}


text:
import uuid
import logging

from django.db import transaction
from django.utils import timezone

from Instanssi.store.methods import paytrail, no_method, PaymentMethod
from Instanssi.store.models import StoreTransaction, StoreItem, TransactionItem, StoreItemVariant

logger = logging.getLogger(__name__)

class TransactionException(Exception):
    pass

def validate_item(item: dict):
    # First, make sure the item exists at all
    try:
        store_item = StoreItem.items_available().get(id=item['item_id'])
    except StoreItem.DoesNotExist:
        raise TransactionException("Tuotetta ei ole saatavilla")

    # Make sure the variant exists and belongs to the requested item
    if item['variant_id']:
        try:
            store_item.variants.get(id=item['variant_id'])
        except StoreItemVariant.DoesNotExist:
            raise TransactionException("Tuotetyyppiä ei ole saatavilla")

    # Make sure there are enough items in the stock to satisfy this request
    if store_item.num_available() < item['amount']:
        raise TransactionException("Tuotetta {} ei ole saatavilla riittävästi!".format(store_item.name))

def get_item_and_variant(item: dict) -> (StoreItem, StoreItemVariant):
    """
    Return store item and variant (if any).
    """
    store_item = StoreItem.items_available().get(pk=item['item_id'])
    store_variant = store_item.variants.get(pk=item['variant_id']) if item['variant_id'] else None
    return store_item, store_variant

def validate_payment_method(items: list, method: PaymentMethod):
    """
    Make sure payment method is okay for the selected order. NO_METHOD is only acceptable when total sum of the order
    is 0 eur! Other methods are always acceptable.
    """

    if method == PaymentMethod.NO_METHOD:
        for item in items:
            store_item, store_variant = get_item_and_variant(item)
            purchase_price = store_item.get_discounted_unit_price(item['amount'])
            if purchase_price > 0:
                raise TransactionException("Valittu maksutapa ei ole sallittu tälle tilaukselle!")

def create_store_transaction(data: dict) -> StoreTransaction:
    # Handle creation of the order in a transaction to avoid creating crap to db in errors
    try:
        with transaction.atomic():
            ta = StoreTransaction()
            ta.firstname = data['first_name']
            ta.lastname = data['last_name']
            ta.company = data['company']
            ta.email = data['email']
            ta.telephone = data['telephone']
            ta.mobile = data['mobile']
            ta.street = data['street']
            ta.postalcode = data['postal_code']
            ta.city = data['city']
            ta.country = data['country']
            ta.information = data['information']
            ta.time_created = timezone.now()
            ta.key = uuid.uuid4().hex
            ta.save()

            # Check items
            for item in data['items']:
                store_item, store_variant = get_item_and_variant(item)

                # Find the price with discounts (if any)
                purchase_price = store_item.get_discounted_unit_price(item['amount'])

                # Form the transaction item(s)
                for m in range(item['amount']):
                    ta_item = TransactionItem()
                    ta_item.transaction = ta
                    ta_item.item = store_item
                    ta_item.variant = store_variant
                    ta_item.key = uuid.uuid4().hex
                    ta_item.purchase_price = purchase_price
                    ta_item.original_price = store_item.price
                    ta_item.save()

            return ta
    except Exception as e:
        logger.error("Unable to save store transaction: %s", str(e))
        raise

def begin_payment_process(method: PaymentMethod, ta: StoreTransaction):
    return {
        PaymentMethod.NO_METHOD: no_method.start_process,
        PaymentMethod.PAYTRAIL: paytrail.start_process
    }[method](ta)


text:
package uk.gov.hmrc.nisp.views

import play.api.test.Injecting
import uk.gov.hmrc.nisp.utils.Constants

class TimeoutViewSpec extends HtmlSpec with Injecting {

  val feedbackFrontendUrl: String = "/foo"
  lazy val html                   = inject[uk.gov.hmrc.nisp.views.html.iv.failurepages.timeout]
  lazy val source                 = asDocument(html().toString)

  "TimeoutView" should {

    "assert correct page title" in {
      val title    = source.title()
      val expected = messages("nisp.iv.failure.timeout.title") + Constants.titleSplitter + messages(
        "nisp.title.extension"
      ) + Constants.titleSplitter + messages("nisp.gov-uk")
      title should include(expected)
    }

    "assert correct heading title on page" in {
      val heading = source.getElementsByTag("h1").get(0).toString
      heading should include(messages("nisp.iv.failure.timeout.title"))
    }

    "assert correct paragraph one text on page" in {
      val paragraph = source.getElementsByTag("p").get(0).toString
      paragraph should include(messages("nisp.iv.failure.timeout.message"))
    }

    "assert correct paragraph two text on page" in {
      val paragraph = source.getElementsByTag("p").get(1).toString
      paragraph should include(messages("nisp.iv.failure.timeout.data"))
    }

    "assert correct button text on page" in {
      val button = source.getElementsByClass("govuk-button").text
      button should include(messages("nisp.iv.failure.timeout.button"))
    }

    "assert correct href on the start again button" in {
      val buttonHref = source.getElementsByClass("govuk-button").attr("href")
      buttonHref should include("/check-your-state-pension/account")
    }
  }
}


text:
package com.blackducksoftware.integration.hub.detect.tool.signaturescanner;

public class BlackDuckSignatureScannerOptions {
    private final String[] signatureScannerPaths;
    private final String[] exclusionPatterns;
    private final String[] exclusionNamePatterns;

    private final Integer scanMemory;
    private final Integer parrallelProcessors;
    private final Boolean cleanupOutput;
    private final Boolean dryRun;
    private final Boolean snippetMatching;
    private final String codeLocationPrefix;
    private final String codeLocationSuffix;
    private final String additionalArguments;
    private final Integer maxDepth;

    public BlackDuckSignatureScannerOptions(final String[] signatureScannerPaths, final String[] exclusionPatterns, final String[] exclusionNamePatterns, final Integer scanMemory, final Integer parrallelProcessors,
        final Boolean cleanupOutput, final Boolean dryRun, final Boolean snippetMatching, final String codeLocationPrefix, final String codeLocationSuffix, final String additionalArguments, final Integer maxDepth) {
        this.signatureScannerPaths = signatureScannerPaths;
        this.exclusionPatterns = exclusionPatterns;
        this.exclusionNamePatterns = exclusionNamePatterns;
        this.scanMemory = scanMemory;
        this.parrallelProcessors = parrallelProcessors;
        this.cleanupOutput = cleanupOutput;
        this.dryRun = dryRun;
        this.snippetMatching = snippetMatching;
        this.codeLocationPrefix = codeLocationPrefix;
        this.codeLocationSuffix = codeLocationSuffix;
        this.additionalArguments = additionalArguments;
        this.maxDepth = maxDepth;
    }

    public String[] getSignatureScannerPaths() {
        return signatureScannerPaths;
    }

    public String[] getExclusionPatterns() {
        return exclusionPatterns;
    }

    public String[] getExclusionNamePatterns() {
        return exclusionNamePatterns;
    }

    public Integer getScanMemory() {
        return scanMemory;
    }

    public Integer getParrallelProcessors() {
        return parrallelProcessors;
    }

    public Boolean getCleanupOutput() {
        return cleanupOutput;
    }

    public Boolean getDryRun() {
        return dryRun;
    }

    public Boolean getSnippetMatching() {
        return snippetMatching;
    }

    public String getCodeLocationPrefix() {
        return codeLocationPrefix;
    }

    public String getCodeLocationSuffix() {
        return codeLocationSuffix;
    }

    public String getAdditionalArguments() {
        return additionalArguments;
    }

    public Integer getMaxDepth() {
        return maxDepth;
    }
}


text:
namespace eshape
{

class StagePanel;
class ToolbarPanel;
class Symbol;

class EditDialog : public wxDialog
{
public:
	EditDialog(wxWindow* parent, const std::shared_ptr<Symbol>& sym);
	virtual ~EditDialog();

private:
	void onSize(wxSizeEvent& event);

	void InitLayout(const std::shared_ptr<Symbol>& sym);

	void OnCloseEvent(wxCloseEvent& event);

private:
	StagePanel* m_stage;

	ToolbarPanel* m_toolbar;

	DECLARE_EVENT_TABLE()

}; // EditDialog

}

#endif // _EASYSHAPE_ETID_DIALOG_H_


text:
version 2 also supports property [#16](./properties.md#16-mitmwrong-number-cannot-learn-or-confirm-keys)

### dependency: crypto_box

This protocol depends on the `crypto_box` primitive as implemented in [nacl](http://nacl.cr.yp.to/box.html).
Unfortunately, that primitive is not very well documented. I will attempt to explain it's properties here. The security model of this primitive is only briefly covered on the [documentation](http://nacl.cr.yp.to/box.html) site so this is based mainly on my reading of the code. Please do check my reasoning here, and make an issue if you think I missed something.

`crypto_box` takes a message, a nonce, a public key and a private key.
`crypto_box(message, nonce, alice.public_key, bob.private_key)` which is decrypted by
`crypto_box_open(boxed, nonce, bob.public_key, alice.private_key)`.
The message is encrypted with salsa20 cipher, and authenticated with poly1305. There is no length delimitation so if you wish to transmit this message it must be framed, or have a fixed size, the other party requires the same nonce in order to perform the decryption so that must be provided some way (i.e. either by sending it along with the message, or by having a protocol for determining the next nonce)

Although it's described as Bob _encrypting to_ Alice ("Bob boxes the message to Alice") the encryption is not directional, and either Bob _or_ Alice can decrypt the message. This is because it derives a shared key in the manner of a diffie-helman key exchange, _not_ by encrypting a key to Alice's pub key (which would be an operation that Bob could not reverse). This has a surprising property if this is used as an authentication primitive: If an attacker gains Bob's private key, and knows Alice's key then they can not only impersonate bob to Alice (or anyone), but surprisingly they can impersonate _anyone_ to Bob (provided they know that public key)!

This would make a compromise of his private key a decidedly schizophrenic experience for Bob! Although to other parties, Bob suddenly acting weird would be simple enough to diagnose - Bob has been hacked - but Bob may instead experience _everyone he knows_ suddenly going schizophrenic. This could potentially be more destructive than merely impersonating Bob. Hopefully loosing control of one's private keys is an extremely unlikely event, but the antics of bitcoin has certainly shown this is possible via a variety of avenues if attackers are sufficiently motivated. If it's reasonable to design a protocol to be forward secure (not leak information if keys are compromised) then it's reasonable to make other aspects of the protocol fail safely in the case of key compromise.

Therefore, my conclusion is that `crypto_box` is not suitable as a _user authentication primitive_, and signatures should be used instead (though, the signatures may be inside a `crypto_box` for privacy).

### protocol description

Alice: Hi call me Andy
> Alice generates a temporary key, Andy, and sends it to (the server she thinks is) Bob

Bob: Hi, call me Betty
> Bob generates a temporary key, Betty, and sends it back to whoever connected (doesn't know it's Alice yet)

Alice now sends a secure greeting to Bob that will prove her identity, but only to Bob.

Alice:
```
  //this is most complicated bit, easier to specify it as pseudocode.

  //encrypt the entire message to Betty (bob's temp key)
  box[Andy->Betty](
    //reveal long term identity (Alice) but only to Bob! (via a box)
    //this is inside the outer box to get forward security (eavesdropper will have outside box only)
    //Boxed from Andy, since Bob doesn't know it's Alice yet!
    box[Andy->Bob]([
      //send Alice's private key
      Alice.public_key,
      //creates a 3rd public key
      (Aaron = createKey()).public_key
      //sign the hash of the first two messages, this proves to bob this packet was created by holder
      //of Alice's key, and cannot be a replay or mitm attack because Bob knows Betty's key is brand new.
      sign(
        hash(Andy.public_key + Betty.public_key + Aaron.public_key),
        Alice.private_key
      )
    ])
  )
```

> Alice has now authenticated to Bob. Bob knows that Alice intended to connect to him. And since he opened the box, and found Alice's key, and a signature from Alice. Since Alice also signed something that didn't exist just a moment ago (Betty.public_key) then he knows it's not a replay attack. Since a man in the middle cannot know the temp key he generated (Betty _and_ Andy) then he knows there cannot be a mitm who is decrypting the packets (TODO: more discussion about what a mitm can achieve).

If the call was not for him (wrong number) then he cannot open the inner box, so the connection must be dropped (and Bob will not learn Alice's identity). If he doesn't wish to talk to Alice, then the call should also be dropped. This means a disconnection at this point does not confirm the server's identity.

Alice sends a new key (Aaron) which will be used for the remainder of the session - it might not be strictly necessary to use a third key, but I liked the idea of making the proof of security via cryptography instead of by protocol state.

If Bob does decide to connect with Alice, then he responds with another message containing a new key (Barbara) and signing it

Bob:

```
//encrypt to temp id...
box[Betty->Andy](
  //... a message eve can't see...
  box[Bob->Alice]([
    //containing a new key
    Barbara.public_key
    //with proof this message was just created by Bob!
    //note: also signing Aaron.public_key proves to alice that bob did actually decrypt the hello packet.
    sign(hash(hello + Barbara.public_key + Aaron.public_key), Bob.private_key)
  ])
)
```

Now Alice and Bob are mutually authenticated! Bob knows he's talking to Alice, and Alice knows she is talking to Bob. _as far as I have determined, no weird edge cases_. Of course, if your key is compromised, then someone can impersonate you, this is to be expected, and key revocation should be solved in another part of the cryptosystem.

the rest of the session is encrypted with Aaron/Barbara. Even the existence of these keys is a secret from both an eavesdropper or a man in the middle!

This design realizes _all_ the [desirable secure channel properties](./properties.md)


text:
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set ts=8 sts=4 et sw=4 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef HEAPCOPYOFSTACKARRAY_H_
#define HEAPCOPYOFSTACKARRAY_H_

#include "mozilla/Attributes.h"
#include "mozilla/Scoped.h"

#include <string.h>

namespace mozilla {

// Takes a stack array and copies it into a heap buffer.
// Useful to retain the convenience of declaring static arrays, while
// avoiding passing stack pointers to the GL (see bug 1005658).

template <typename ElemType>
class HeapCopyOfStackArray
{
public:
  template<size_t N>
  HeapCopyOfStackArray(ElemType (&array)[N])
    : mArrayLength(N)
    , mArrayData(new ElemType[N])
  {
    memcpy(mArrayData, &array[0], N * sizeof(ElemType));
  }

  ElemType* Data() const { return mArrayData; }
  size_t ArrayLength() const { return mArrayLength; }
  size_t ByteLength() const { return mArrayLength * sizeof(ElemType); }

private:
  HeapCopyOfStackArray() = delete;
  HeapCopyOfStackArray(const HeapCopyOfStackArray&) = delete;

  const size_t mArrayLength;
  ScopedDeletePtr<ElemType> const mArrayData;
};

}

#endif // HEAPCOPYOFSTACKARRAY_H_


text:
package com.kacper.popularmovies.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.kacper.popularmovies.R;
import com.kacper.popularmovies.data.model.Movie;
import com.kacper.popularmovies.utilities.NetworkUtils;

import java.net.URL;
import java.util.ArrayList;

import it.sephiroth.android.library.picasso.Picasso;

public class NetworkMoviesAdapter extends RecyclerView.Adapter<NetworkMoviesAdapter.PosterAdapterViewHolder> {

    private ArrayList<Movie> allMoviesOnPage;

    private Context context;
    private final PosterAdapterOnClickHandler onClickHandler;

    public interface PosterAdapterOnClickHandler{
        void onClick(Movie clickedMovie);
    }
    public NetworkMoviesAdapter(Context context, PosterAdapterOnClickHandler clickHandler){
        this.context = context;
        this.onClickHandler = clickHandler;
    }

    public class PosterAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public final ImageView singlePosterImage;
        public PosterAdapterViewHolder(View itemView) {
            super(itemView);
            singlePosterImage=(ImageView)itemView.findViewById(R.id.single_poster);
            itemView.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {
            int adapterPosition = getAdapterPosition();
            Movie tmpMovie = allMoviesOnPage.get(adapterPosition);
            onClickHandler.onClick(tmpMovie);
        }
        public void bind(){
            if(allMoviesOnPage.size()>0) {
                URL imageUrl = NetworkUtils.buildImageURL(allMoviesOnPage.get(getAdapterPosition()).getImageURI(), NetworkUtils.MEDIUM_SIZE_POSTER);
                Picasso.with(context).load(imageUrl.toString()).into(singlePosterImage);
            }
        }
    }

    @Override
    public PosterAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        int layoutIdForListItem = R.layout.poster_layout;
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(layoutIdForListItem, parent, false);
        return new PosterAdapterViewHolder(view);
    }

    @Override
    public void onBindViewHolder(PosterAdapterViewHolder holder, int position) {
        holder.bind();
    }

    @Override
    public int getItemCount() {
        if(allMoviesOnPage==null) return 0;
        else return allMoviesOnPage.size();
    }

    public void setAllMoviesOnPage(ArrayList<Movie> allMoviesOnPage) {
        this.allMoviesOnPage = allMoviesOnPage;
        notifyDataSetChanged();
    }
}


text:
import React from 'react';
import { Button, Card } from 'belle';

export default React.createClass({

  render() {
    return (
      <Card>

Button

Default Button

        <button>Press me …</button>

Disabled Default Button

        <button disabled>Press me …</button>

Default Button

        <Button>Press me …</Button>

Disabled Button

        <Button disabled>Press me …</Button>

Primary Button

        <Button primary>Primary Button</Button>

Disabled Primary Button

        <Button disabled primary>Press me …</Button>

Colored Buttons

        <Button primary hoverStyle={{ color: 'blue' }}>Primary Button</Button>

        <Button primary hoverStyle={{ color: 'red' }}>Primary Button</Button>

        <Button primary hoverStyle={{ color: 'green' }}>Primary Button</Button>
      </Card>
    );
  },
});


text:
package org.stuartgunter.dropwizard.cassandra.loadbalancing;

import com.datastax.driver.core.policies.LoadBalancingPolicy;
import com.datastax.driver.core.policies.RoundRobinPolicy;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * A factory for configuring and building {@link com.datastax.driver.core.policies.RoundRobinPolicy} instances.
 *

 * Configuration Parameters:
 *

 *

 *         Name
 *         Default
 *         Description
 *

 *

 *         No configuration options available.
 *

 *

 */
@JsonTypeName("roundRobin")
public class RoundRobinPolicyFactory implements LoadBalancingPolicyFactory {
    @Override
    public LoadBalancingPolicy build() {
        return new RoundRobinPolicy();
    }
}


text:
set -o errexit

readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
KYMA_PROJECT_DIR=${KYMA_PROJECT_DIR:-"/home/prow/go/src/github.com/kyma-project"}

# shellcheck source=prow/scripts/lib/log.sh
source "${SCRIPT_DIR}/lib/log.sh"
# shellcheck source=prow/scripts/lib/utils.sh
source "${SCRIPT_DIR}/lib/utils.sh"
# shellcheck source=prow/scripts/lib/gcp.sh
source "$SCRIPT_DIR/lib/gcp.sh"

cleanup() {
    ARG=$?
    log::info "Removing instance cli-integration-test-${RANDOM_ID}"
    date
    gcloud compute instances delete --zone="${ZONE}" "cli-integration-test-${RANDOM_ID}" || true ### Workaround: not failing the job regardless of the vm deletion result
    exit $ARG
}

function testCustomImage() {
    CUSTOM_IMAGE="$1"
    IMAGE_EXISTS=$(gcloud compute images list --filter "name:${CUSTOM_IMAGE}" | tail -n +2 | awk '{print $1}')
    if [[ -z "$IMAGE_EXISTS" ]]; then
        log::error "${CUSTOM_IMAGE} is invalid, it is not available in GCP images list, the script will terminate ..." && exit 1
    fi
}

gcp::authenticate \
    -c "${GOOGLE_APPLICATION_CREDENTIALS}"

RANDOM_ID=$(openssl rand -hex 4)

LABELS=""
if [[ -z "${PULL_NUMBER}" ]]; then
    LABELS=(--labels "branch=${PULL_BASE_REF/./-},job-name=cli-integration")
else
    LABELS=(--labels "pull-number=$PULL_NUMBER,job-name=cli-integration")
fi

# Support configuration via ENV vars (can be be overwritten by CLI args)
KUBERNETES_RUNTIME="${KUBERNETES_RUNTIME:=k3d}"

POSITIONAL=()
while [[ $# -gt 0 ]]
do

    key="$1"

    case ${key} in
        --image|-i)
            IMAGE="$2"
            testCustomImage "${IMAGE}"
            shift 2
            ;;
        --kyma-version|-kv)
            SOURCE="--source $2"
            shift 2
            ;;
        --kubernetes-runtime|-kr)
            KUBERNETES_RUNTIME="$2"
            shift 2
            ;;
        --*)
            echo "Unknown flag ${1}"
            exit 1
            ;;
        *)    # unknown option
            POSITIONAL+=("$1") # save it in an array for later
            shift # past argument
            ;;
    esac
done
set -- "${POSITIONAL[@]}" # restore positional parameters

if [[ -z "$IMAGE" ]]; then
    log::info "Provisioning vm using the latest default custom image ..."
    date
    IMAGE=$(gcloud compute images list --sort-by "~creationTimestamp" \
         --filter "family:custom images AND labels.default:yes" --limit=1 | tail -n +2 | awk '{print $1}')

    if [[ -z "$IMAGE" ]]; then
       log::error "There are no default custom images, the script will exit ..." && exit 1
    fi
 fi

ZONE_LIMIT=${ZONE_LIMIT:-5}
EU_ZONES=$(gcloud compute zones list --filter="name~europe" --limit="${ZONE_LIMIT}" | tail -n +2 | awk '{print $1}')

for ZONE in ${EU_ZONES}; do
    log::info "Attempting to create a new instance named cli-integration-test-${RANDOM_ID} in zone ${ZONE} using image ${IMAGE}"
    date
    gcloud compute instances create "cli-integration-test-${RANDOM_ID}" \
        --metadata enable-oslogin=TRUE \
        --image "${IMAGE}" \
        --machine-type n1-standard-4 \
        --zone "${ZONE}" \
        --boot-disk-size 200 "${LABELS[@]}" &&\
    log::info "Created cli-integration-test-${RANDOM_ID} in zone ${ZONE}" && break
    log::error "Could not create machine in zone ${ZONE}"
done || exit 1

trap cleanup exit INT

log::info "Building Kyma CLI"
date
cd "${KYMA_PROJECT_DIR}/cli"
make build-linux

utils::ssh_to_vm_with_script -z "${ZONE}" -n "cli-integration-test-${RANDOM_ID}" -c "mkdir \$HOME/bin"

log::info "Copying Kyma CLI to the instance"
#shellcheck disable=SC2088
utils::send_to_vm "${ZONE}" "cli-integration-test-${RANDOM_ID}" "${KYMA_PROJECT_DIR}/cli/bin/kyma-linux" "~/bin/kyma"
utils::ssh_to_vm_with_script -z "${ZONE}" -n "cli-integration-test-${RANDOM_ID}" -c "sudo cp \$HOME/bin/kyma /usr/local/bin/kyma"

# Provision Kubernetes runtime
log::info "Provisioning Kubernetes runtime '$KUBERNETES_RUNTIME'"
date
if [ "$KUBERNETES_RUNTIME" = 'k3d' ]; then
    utils::ssh_to_vm_with_script -z "${ZONE}" -n "cli-integration-test-${RANDOM_ID}" -c "yes | sudo kyma provision k3d --ci"
else
    log:error "Unknown Kubernetes runtime: $KUBERNETES_RUNTIME" && exit 1
fi

# Install kyma
log::info "Installing Kyma"
date
if [ "$KUBERNETES_RUNTIME" = 'k3d' ]; then
    utils::ssh_to_vm_with_script -z "${ZONE}" -n "cli-integration-test-${RANDOM_ID}" -c "yes | sudo kyma deploy --ci ${SOURCE}"
else
    utils::ssh_to_vm_with_script -z "${ZONE}" -n "cli-integration-test-${RANDOM_ID}" -c "yes | sudo kyma install --non-interactive ${SOURCE}"
fi

# Run test suite
# shellcheck disable=SC1090,SC1091
source "${SCRIPT_DIR}/lib/clitests.sh"

if [ "$KUBERNETES_RUNTIME" = 'k3d' ]; then
    if clitests::testSuiteExists "test-version"; then
        clitests::execute "test-version" "${ZONE}" "cli-integration-test-${RANDOM_ID}" "$SOURCE"
    else
        log::error "Test file 'test-version.sh' not found"
    fi
    if clitests::testSuiteExists "test-function"; then
        clitests::execute "test-function" "${ZONE}" "cli-integration-test-${RANDOM_ID}" "$SOURCE"
    else
        log::error "Test file 'test-function.sh' not found"
    fi
else
    if clitests::testSuiteExists "test-all"; then
        clitests::execute "test-all" "${ZONE}" "cli-integration-test-${RANDOM_ID}" "$SOURCE"
    else
        log::error "Test file 'test-all.sh' not found"
    fi
fi
log::info "Provisioning VM CLI's done"


text:
DB_USER=""
DB_PASSWORD=""
# --- CREDENTIALS_END   ---

# --- CONFIG BEGIN ---\
CORNERSTONE_WEBSITE_URL=""
CORNERSTONE_API_URL="api.cornerstone.test"
CORNERSTONE_WEBSITE_NAME=""
CORNERSTONE_EMAIL=""
CORNERSTONE_EMAIL_PASSWORD=""
CORNERSTONE_ADMIN_USER=""
CORNERSTONE_ADMIN_PASSWORD=""
CORNERSTONE_TIMEZONE=""
CORNERSTONE_SYSTEM_USER=""
# --- CONFIG END

export DB_USER
export DB_PASSWORD
export CORNERSTONE_WEBSITE_URL
export CORNERSTONE_API_URL
export CORNERSTONE_WEBSITE_NAME
export CORNERSTONE_EMAIL
export CORNERSTONE_EMAIL_PASSWORD
export CORNERSTONE_ADMIN_USER
export CORNERSTONE_ADMIN_PASSWORD
export CORNERSTONE_TIMEZONE
export CORNERSTONE_SYSTEM_USER


text:
/**
 * @module attributes/attributesDao
 */
import { UserDao } from '../user/userDao';
import { GeoPackage } from '../geoPackage';
import { AttributesTable } from './attributesTable';
import { AttributesRow } from './attributesRow';
import { Contents } from '../core/contents/contents';
import { DBValue } from '../db/dbAdapter';
import { GeoPackageDataType } from '../db/geoPackageDataType';

/**
 * Attribute DAO for reading attribute user data tables
 * @class AttributesDao
 * @extends UserDao
 * @param  {module:geoPackage~GeoPackage} geoPackage              geopackage object
 * @param  {module:attributes/attributesTable~AttributeTable} table           attribute table
 */
export class AttributesDao<T extends AttributesRow> extends UserDao<AttributesRow> {
  /**
   * Contents of this AttributeDao
   * @member {module:core/contents~Contents}
   */
  contents: Contents;

  constructor(geoPackage: GeoPackage, table: AttributesTable) {
    super(geoPackage, table);
    if (!table.contents) {
      throw new Error('Attributes table has null Contents');
    }

    this.contents = table.contents;
  }

  get table(): AttributesTable {
    return this._table as AttributesTable;
  }

  /**
   * Create a new attribute row with the column types and values
   * @param  {Array} columnTypes column types
   * @param  {module:dao/columnValues~ColumnValues[]} values      values
   * @return {module:attributes/attributesRow~AttributeRow}             attribute row
   */
  newRow(columnTypes?: { [key: string]: GeoPackageDataType }, values?: Record<string, DBValue>): AttributesRow {
    return new AttributesRow(this.table, columnTypes, values);
  }

  static readTable(geoPackage: GeoPackage, tableName: string): AttributesDao<AttributesRow> {
    return geoPackage.getAttributeDao(tableName);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center">

    <RelativeLayout
        android:layout_width="72dp"
        android:layout_height="100dp"
        android:layout_centerVertical="true"
        android:layout_margin="2dp">

        <ImageView
            android:id="@+id/pic"
            android:layout_width="58dp"
            android:layout_height="85dp"
            android:layout_centerInParent="true"
            android:scaleType="centerCrop"
            android:src="@drawable/ic_add_pic_long"
            android:text="@string/more"
            android:textColor="@color/text_hint"
            android:textSize="@dimen/text_size_1" />

        <ImageView
            android:id="@+id/ivDel"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:layout_alignParentRight="true"
            android:layout_gravity="right"
            android:paddingBottom="15dp"
            android:paddingLeft="15dp"
            android:scaleType="centerInside"
            android:src="@drawable/ic_del_x" />

    </RelativeLayout>

</RelativeLayout>


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is Mozilla Communicator client code, released
 * March 31, 1998.
 *
 * The Initial Developer of the Original Code is
 * Netscape Communications Corporation.
 * Portions created by the Initial Developer are Copyright (C) 1998
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

/**
   File Name:          15.9.3.1.js
   ECMA Section:       15.9.3.1 new Date (year, month, date, hours, minutes, seconds, ms)
   Description:        The [[Prototype]] property of the newly constructed
   object is set to the original Date prototype object,
   the one that is the initial value of Date.prototype.

   The [[Class]] property of the newly constructed object
   is set as follows:
   1. Call ToNumber(year)
   2. Call ToNumber(month)
   3. Call ToNumber(date)
   4. Call ToNumber(hours)
   5. Call ToNumber(minutes)
   6. Call ToNumber(seconds)
   7. Call ToNumber(ms)
   8.  If Result(1)is NaN and 0 <= ToInteger(Result(1)) <=
   99, Result(8) is 1900+ToInteger(Result(1)); otherwise,
   Result(8) is Result(1)
   9.  Compute MakeDay(Result(8), Result(2), Result(3)
   10. Compute MakeTime(Result(4), Result(5), Result(6),
   Result(7)
   11. Compute MakeDate(Result(9), Result(10))
   12. Set the [[Value]] property of the newly constructed
   object to TimeClip(UTC(Result(11))).

   This tests the returned value of a newly constructed
   Date object.

   Author:             christine@netscape.com
   Date:               7 july 1997
*/

var TIME        = 0;
var UTC_YEAR    = 1;
var UTC_MONTH   = 2;
var UTC_DATE    = 3;
var UTC_DAY     = 4;
var UTC_HOURS   = 5;
var UTC_MINUTES = 6;
var UTC_SECONDS = 7;
var UTC_MS      = 8;

var YEAR        = 9;
var MONTH       = 10;
var DATE        = 11;
var DAY         = 12;
var HOURS       = 13;
var MINUTES     = 14;
var SECONDS     = 15;
var MS          = 16;

//  for TCMS, the gTestcases array must be global.
var SECTION = "15.9.3.1";
var TITLE =   "Date( year, month, date, hours, minutes, seconds )";

writeHeaderToLog( SECTION+" " +TITLE );

var PST_FEB_29_2000 = UTC_FEB_29_2000 + 8*msPerHour;

// Dates around Feb 29, 2000
addNewTestCase( new Date(2000,1,28,16,0,0,0),
		"new Date(2000,1,28,16,0,0,0)",
		[UTC_FEB_29_2000,2000,1,29,2,0,0,0,0,2000,1,28,1,16,0,0,0,0] );

addNewTestCase( new Date(2000,1,29,0,0,0,0),
		"new Date(2000,1,29,0,0,0,0)",
		[PST_FEB_29_2000,2000,1,29,2,8,0,0,0,2000,1,29,2,0,0,0,0] );

addNewTestCase( new Date(2000,1,29,24,0,0,0),
		"new Date(2000,1,29,24,0,0,0)",
		[PST_FEB_29_2000+msPerDay,2000,2,1,3,8,0,0,0,2000,2,1,3,0,0,0,0] );

test();

function addNewTestCase( DateCase, DateString, ResultArray ) {
  //adjust hard-coded ResultArray for tester's timezone instead of PST
  adjustResultArray(ResultArray);

  new TestCase( SECTION, DateString+".getTime()", ResultArray[TIME],       DateCase.getTime() );
  new TestCase( SECTION, DateString+".valueOf()", ResultArray[TIME],       DateCase.valueOf() );

  new TestCase( SECTION, DateString+".getUTCFullYear()",      ResultArray[UTC_YEAR],   DateCase.getUTCFullYear() );
  new TestCase( SECTION, DateString+".getUTCMonth()",         ResultArray[UTC_MONTH],  DateCase.getUTCMonth() );
  new TestCase( SECTION, DateString+".getUTCDate()",          ResultArray[UTC_DATE],   DateCase.getUTCDate() );
  new TestCase( SECTION, DateString+".getUTCDay()",           ResultArray[UTC_DAY],    DateCase.getUTCDay() );
  new TestCase( SECTION, DateString+".getUTCHours()",         ResultArray[UTC_HOURS],  DateCase.getUTCHours() );
  new TestCase( SECTION, DateString+".getUTCMinutes()",       ResultArray[UTC_MINUTES],DateCase.getUTCMinutes() );
  new TestCase( SECTION, DateString+".getUTCSeconds()",       ResultArray[UTC_SECONDS],DateCase.getUTCSeconds() );
  new TestCase( SECTION, DateString+".getUTCMilliseconds()",  ResultArray[UTC_MS],     DateCase.getUTCMilliseconds() );

  new TestCase( SECTION, DateString+".getFullYear()",         ResultArray[YEAR],       DateCase.getFullYear() );
  new TestCase( SECTION, DateString+".getMonth()",            ResultArray[MONTH],      DateCase.getMonth() );
  new TestCase( SECTION, DateString+".getDate()",             ResultArray[DATE],       DateCase.getDate() );
  new TestCase( SECTION, DateString+".getDay()",              ResultArray[DAY],        DateCase.getDay() );
  new TestCase( SECTION, DateString+".getHours()",            ResultArray[HOURS],      DateCase.getHours() );
  new TestCase( SECTION, DateString+".getMinutes()",          ResultArray[MINUTES],    DateCase.getMinutes() );
  new TestCase( SECTION, DateString+".getSeconds()",          ResultArray[SECONDS],    DateCase.getSeconds() );
  new TestCase( SECTION, DateString+".getMilliseconds()",     ResultArray[MS],         DateCase.getMilliseconds() );

}


text:
require 'spec_helper'
require Rails.root.join('db', 'post_migrate', '20170508170547_add_head_pipeline_for_each_merge_request.rb')

describe AddHeadPipelineForEachMergeRequest, :delete do
  include ProjectForksHelper

  let(:migration) { described_class.new }

  let!(:project) { create(:project) } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:other_project) { fork_project(project) }

  let!(:pipeline_1) { create(:ci_pipeline, project: project, ref: "branch_1") } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:pipeline_2) { create(:ci_pipeline, project: other_project, ref: "branch_1") } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:pipeline_3) { create(:ci_pipeline, project: other_project, ref: "branch_1") } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:pipeline_4) { create(:ci_pipeline, project: project, ref: "branch_2") } # rubocop:disable RSpec/FactoriesInMigrationSpecs

  let!(:mr_1) { create(:merge_request, source_project: project, target_project: project, source_branch: "branch_1", target_branch: "target_1") } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:mr_2) { create(:merge_request, source_project: other_project, target_project: project, source_branch: "branch_1", target_branch: "target_2") } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:mr_3) { create(:merge_request, source_project: project, target_project: project, source_branch: "branch_2", target_branch: "master") } # rubocop:disable RSpec/FactoriesInMigrationSpecs
  let!(:mr_4) { create(:merge_request, source_project: project, target_project: project, source_branch: "branch_3", target_branch: "master") } # rubocop:disable RSpec/FactoriesInMigrationSpecs

  context "#up" do
    context "when source_project and source_branch of pipeline are the same of merge request" do
      it "sets head_pipeline_id of given merge requests" do
        migration.up

        expect(mr_1.reload.head_pipeline_id).to eq(pipeline_1.id)
        expect(mr_2.reload.head_pipeline_id).to eq(pipeline_3.id)
        expect(mr_3.reload.head_pipeline_id).to eq(pipeline_4.id)
        expect(mr_4.reload.head_pipeline_id).to be_nil
      end
    end
  end
end


text:
require 'masked/version'
require 'masked/mask'
require 'masked/railtie' if defined?(Rails)


text:
package com.vaadin.client.componentlocator;

import java.util.List;

import com.google.gwt.dom.client.Element;

/**
 * This interface should be implemented by all locator strategies. A locator
 * strategy is responsible for generating and decoding a string that identifies
 * an element in the DOM. A strategy can implement its own syntax for the
 * locator string, which may be completely different from any other strategy's
 * syntax.
 *
 * @since 7.2
 * @author Vaadin Ltd
 */
public interface LocatorStrategy {

    /**
     * Test the given input path for formatting errors. If a given path can not
     * be validated, the locator strategy will not be attempted.
     *
     * @param path
     *            a locator path expression
     * @return true, if the implementing class can process the given path,
     *         otherwise false
     */
    boolean validatePath(String path);

    /**
     * Generates a String locator which uniquely identifies the target element.
     * The {@link #getElementByPath(String)} method can be used for the inverse
     * operation, i.e. locating an element based on the return value from this
     * method.
     * <p>
     * Note that getElementByPath(getPathForElement(element)) == element is not
     * always true as #getPathForElement(Element) can return a path to another
     * element if the widget determines an action on the other element will give
     * the same result as the action on the target element.
     * </p>
     *
     * @param targetElement
     *            The element to generate a path for.
     * @return A String locator that identifies the target element or null if a
     *         String locator could not be created.
     */
    String getPathForElement(Element targetElement);

    /**
     * Locates an element using a String locator (path) which identifies a DOM
     * element. The {@link #getPathForElement(Element)} method can be used for
     * the inverse operation, i.e. generating a string expression for a DOM
     * element.
     *
     * @param path
     *            The String locator which identifies the target element.
     * @return The DOM element identified by {@code path} or null if the element
     *         could not be located.
     */
    Element getElementByPath(String path);

    /**
     * Locates an element using a String locator (path) which identifies a DOM
     * element. The path starts from the specified root element.
     *
     * @see #getElementByPath(String)
     *
     * @param path
     *            The String locator which identifies the target element.
     * @param root
     *            The element that is at the root of the path.
     * @return The DOM element identified by {@code path} or null if the element
     *         could not be located.
     */
    Element getElementByPathStartingAt(String path, Element root);

    /**
     * Locates all elements that match a String locator (path) which identifies
     * DOM elements.
     *
     * This functionality is limited in {@link LegacyLocatorStrategy}.
     *
     * @param path
     *            The String locator which identifies target elements.
     * @return List that contains all matched elements. Empty list if none
     *         found.
     */
    List<Element> getElementsByPath(String path);

    /**
     * Locates all elements that match a String locator (path) which identifies
     * DOM elements. The path starts from the specified root element.
     *
     * This functionality is limited in {@link LegacyLocatorStrategy}.
     *
     * @see #getElementsByPath(String)
     *
     * @param path
     *            The String locator which identifies target elements.
     * @param root
     *            The element that is at the root of the path.
     * @return List that contains all matched elements. Empty list if none
     *         found.
     */

    List<Element> getElementsByPathStartingAt(String path, Element root);
}