text:
Rails.application.configure do
  # Settings specified here will take precedence over those in
  # config/application.rb.

  # Code is not reloaded between requests.
  config.cache_classes = true

  # Eager load code on boot. This eager loads most of Rails and
  # your application in memory, allowing both threaded web servers
  # and those relying on copy on write to perform better.
  # Rake tasks automatically ignore this option for performance.
  config.eager_load = true

  # Full error reports are disabled and caching is turned on.
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.cache_store = :memory_store, { size: 64.megabytes }

  # Enable Rack::Cache to put a simple HTTP cache in front of your application
  # Add `rack-cache` to your Gemfile before enabling this.
  # For large-scale production use, consider using a caching reverse proxy like
  # NGINX, varnish or squid.
  # config.action_dispatch.rack_cache = true

  # Disable serving static files from the `/public` folder by default since
  # Apache or NGINX already handles this.
  # config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
  config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?

  # We want to serve compressed values
  config.assets.compress = true

  # Compress JavaScripts and CSS.
  config.assets.js_compressor = :uglifier
  config.assets.css_compressor = :sass

  # Do not fallback to assets pipeline if a precompiled asset is missed.
  config.assets.compile = true

  # Asset digests allow you to set far-future HTTP expiration dates on all
  # assets, # yet still be able to expire them through the digest params.
  config.assets.digest = true

  # `config.assets.precompile` and `config.assets.version` have moved to
  # config/initializers/assets.rb

  # Specifies the header that your server uses for sending files.
  # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
  # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX

  # Force all access to the app over SSL, use Strict-Transport-Security, and use
  # secure cookies.
  config.force_ssl = true unless ENV['DISABLE_FORCE_SSL']

  # Use the :info log level by default, not the lowest (:debug);
  # the site is now busy enough that ":debug" floods the logs.
  # You can override this using RAILS_LOG_LEVEL
  config.log_level = (ENV['RAILS_LOG_LEVEL'] || :info).to_sym

  # Prepend all log lines with the following tags.
  # config.log_tags = [ :subdomain, :uuid ]

  # Use a different logger for distributed setups.
  # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)

  # Use a different cache store in production.
  # config.cache_store = :mem_cache_store

  # Enable serving of images, stylesheets, and JavaScripts from an asset server.
  # config.action_controller.asset_host = 'http://assets.example.com'

  # Configure email server.
  # For discussion about how to do this, see:
  # https://www.railstutorial.org/book/account_activation_password_reset
  config.action_mailer.raise_delivery_errors = true
  config.action_mailer.delivery_method = :smtp
  host = (ENV['PUBLIC_HOSTNAME'] || 'public-hostname-not-configured')
  config.action_mailer.default_url_options = { host: host }
  ActionMailer::Base.smtp_settings = {
    address: 'smtp.sendgrid.net',
    port: '587',
    authentication: :plain,
    user_name: ENV['SENDGRID_USERNAME'],
    password: ENV['SENDGRID_PASSWORD'],
    domain: 'heroku.com',
    enable_starttls_auto: true
  }

  # Enable locale fallbacks for I18n (makes lookups for any locale fall back to
  # the I18n.default_locale when a translation cannot be found).
  config.i18n.fallbacks = true

  # Send deprecation notices to registered listeners.
  config.active_support.deprecation = :notify

  # Use default logging formatter so that PID and timestamp are not suppressed.
  config.log_formatter = ::Logger::Formatter.new

  # Do not dump schema after migrations.
  config.active_record.dump_schema_after_migration = false

  # Use Fastly as a CDN. See: https://devcenter.heroku.com/articles/fastly
  # config.action_controller.asset_host = ENV['FASTLY_CDN_URL']
  # Use CDN directly for static assets
  # TODO: Do we need to set this to true?
  # The documentation for Fastly suggests setting
  # "config.serve_static_assets = true".  However, this has since been
  # renamed to "config.serve_static_files", which we already conditionally set.

  # Cache static content.  Cache for a long time; the asset cache is
  config.public_file_server.headers =
    {
      'Cache-Control' =>
        'public, s-maxage=31536000, max-age=31536000, immutable'
    }

  # Enable Rack's built-in compression mechanism; this is important for people
  # with slow network connections
  config.middleware.use Rack::Deflater

  # In production and fake_production environments turn on "lograge".
  # This makes the logs easier to read and removes cruft that, while useful
  # in development, can be overwhelming in production.
  config.lograge.enabled = true

  # Report user_id in logs
  # https://github.com/roidrage/lograge/issues/23
  config.lograge.custom_options =
    lambda do |event|
      uid = event.payload[:uid]
      if uid
        { uid: uid }
      else
        {}
      end
    end

  # As a failsafe, trigger an exception if the response just hangs for
  # too long.  We only do this in production, because it's not
  # supposed to happen in normal use - this is simply an automatic
  # recovery mechanism if things get stuck.  We don't do this in test or
  # development, because it interferes with their purposes.
  # The "use" form is preferred, but it doesn't actually work when placed
  # in this file, so we'll just set the timeout directly.
  # Ignore exceptions - in fake_production this will fail.  That's good,
  # because we do *not* want timeouts during a debug session.
  # rubocop:disable Lint/HandleExceptions
  begin
    Rack::Timeout.service_timeout = 30 # seconds
    # The timeout reports are really noisy, and don't seem to help debug
    # typical problems (if anything they get in the way).  Disable them.
    Rack::Timeout.unregister_state_change_observer(:logger)
  rescue NameError
    # Do nothing if it's unavailable (this happens if we didn't load the gem)
  end
  # rubocop:enable Lint/HandleExceptions
end
# rubocop:enable Metrics/BlockLength


text:
"""
Integration tests for the model API
"""
from __future__ import print_function
import config as cfg
from datetime import datetime
from pynamodb.models import Model
from pynamodb.indexes import GlobalSecondaryIndex, AllProjection, LocalSecondaryIndex
from pynamodb.attributes import (
    UnicodeAttribute, BinaryAttribute, UTCDateTimeAttribute, NumberSetAttribute, NumberAttribute
)

class LSIndex(LocalSecondaryIndex):
    """
    A model for the local secondary index
    """
    class Meta:
        projection = AllProjection()
    forum = UnicodeAttribute(hash_key=True)
    view = NumberAttribute(range_key=True)

class GSIndex(GlobalSecondaryIndex):
    """
    A model for the secondary index
    """
    class Meta:
        projection = AllProjection()
        read_capacity_units = 2
        write_capacity_units = 1
    epoch = UTCDateTimeAttribute(hash_key=True)

class TestModel(Model):
    """
    A model for testing
    """
    class Meta:
        region = 'us-east-1'
        table_name = 'pynamodb-ci'
        host = cfg.DYNAMODB_HOST
    forum = UnicodeAttribute(hash_key=True)
    thread = UnicodeAttribute(range_key=True)
    view = NumberAttribute(default=0)
    view_index = LSIndex()
    epoch_index = GSIndex()
    epoch = UTCDateTimeAttribute(default=datetime.now)
    content = BinaryAttribute(null=True)
    scores = NumberSetAttribute()

if not TestModel.exists():
    print("Creating table")
    TestModel.create_table(read_capacity_units=1, write_capacity_units=1, wait=True)

obj = TestModel('1', '2')
obj.save()
obj.refresh()
obj = TestModel('foo', 'bar')
obj.save()
obj2 = TestModel('foo2', 'bar2')
obj3 = TestModel('setitem', 'setrange', scores={1, 2.1})
obj3.save()
obj3.refresh()

with TestModel.batch_write() as batch:
    items = [TestModel('hash-{0}'.format(x), '{0}'.format(x)) for x in range(10)]
    for item in items:
        batch.save(item)

item_keys = [('hash-{0}'.format(x), 'thread-{0}'.format(x)) for x in range(10)]

for item in TestModel.batch_get(item_keys):
    print(item)

for item in TestModel.query('setitem', thread__begins_with='set'):
    print("Query Item {0}".format(item))

with TestModel.batch_write() as batch:
    items = [TestModel('hash-{0}'.format(x), '{0}'.format(x)) for x in range(10)]
    for item in items:
        print("Batch delete")
        batch.delete(item)

for item in TestModel.scan():
    print("Scanned item: {0}".format(item))

tstamp = datetime.now()
query_obj = TestModel('query_forum', 'query_thread')
query_obj.forum = 'foo'
query_obj.save()
query_obj.update_item('view', 1, action='add')
for item in TestModel.epoch_index.query(tstamp):
    print("Item queried from index: {0}".format(item))

for item in TestModel.view_index.query('foo', view__gt=0):
    print("Item queried from index: {0}".format(item.view))

print(query_obj.update_item('view', 1, action='add', view=1, forum__null=False))

redpajama_set_name: RedPajamaGithub


text:
var test = require('tape');

var crypto = require('crypto');
var cryptoB = require('../');
var fs = require('fs');

function assertSame(name, fn) {
    test(name, function (t) {
        t.plan(1);
        fn(crypto, function (err, expected) {
            fn(cryptoB, function (err, actual) {
                t.equal(actual, expected);
                t.end();
            });
        });
    });
}

var algorithms = ['sha1', 'sha256', 'md5'];
var encodings = ['binary', 'hex', 'base64'];

algorithms.forEach(function (algorithm) {
    encodings.forEach(function (encoding) {
        assertSame(algorithm + ' hash using ' + encoding, function (crypto, cb) {
            cb(null, crypto.createHash(algorithm).update('hellø', 'utf-8').digest(encoding));
        })

        assertSame(algorithm + ' hmac using ' + encoding, function (crypto, cb) {
            cb(null, crypto.createHmac(algorithm, 'secret').update('hellø', 'utf-8').digest(encoding))
        })
    });

    assertSame(algorithm + ' with raw binary', function (crypto, cb) {
        var seed = 'hellø';
        for (var i = 0; i < 1000; i++) {
            seed = crypto.createHash(algorithm).update(new Buffer(seed)).digest('binary');
        }
        cb(null, crypto.createHash(algorithm).update(new Buffer(seed)).digest('hex'));
    });

    assertSame(algorithm + ' empty string', function (crypto, cb) {
        cb(null, crypto.createHash(algorithm).update('').digest('hex'));
    });
});

function pad(n, w) {
  n = n + ''; return new Array(w - n.length + 1).join('0') + n;
}

var vectors = fs.readdirSync(__dirname + '/vectors').sort().
    filter(function (t) { return t.match(/\.dat$/); }).
    map(function (t) { return fs.readFileSync(__dirname + '/vectors/' + t); });

['md5', 'sha1', 'sha256'].forEach(function (algorithm) {
    test(algorithm, function (t) {
        function hash(data) { return cryptoB.createHash(algorithm).update(data).digest('hex'); }

        var hashes = fs.readFileSync(__dirname + '/vectors/byte-hashes.' + algorithm).toString().split(/\r?\n/);
        t.plan(vectors.length);
        for (var i = 0; i < vectors.length; i++) {
            t.equal(hash(vectors[i]), hashes[i], 'byte' + pad(i, 4) + '.dat');
        }
    });
});

test('randomBytes', function (t) {
    t.plan(5);
    t.equal(cryptoB.randomBytes(10).length, 10);
    t.ok(cryptoB.randomBytes(10) instanceof Buffer);
    cryptoB.randomBytes(10, function(ex, bytes) {
        t.error(ex);
        t.equal(bytes.length, 10);
        t.ok(bytes instanceof Buffer);
        t.end();
  });
});


text:
package org.opendaylight.opflex.genie.content.parse.pnaming;

import org.opendaylight.opflex.genie.content.model.mclass.DefinitionScope;
import org.opendaylight.opflex.genie.content.model.mnaming.MNamer;
import org.opendaylight.opflex.genie.engine.model.Item;
import org.opendaylight.opflex.genie.engine.model.Pair;
import org.opendaylight.opflex.genie.engine.parse.model.ParseNode;
import org.opendaylight.opflex.genie.engine.parse.model.ProcessorNode;
import org.opendaylight.opflex.genie.engine.parse.modlan.Node;
import org.opendaylight.opflex.genie.engine.parse.modlan.ParseDirective;
import org.opendaylight.opflex.modlan.utils.Strings;

/**
 * Created by midvorki on 8/1/14.
 */
public class PNamedNode extends ParseNode
{
    public PNamedNode(String aInName)
    {
        super(aInName);
    }

    protected void addParent(ProcessorNode aInParent)
    {
        super.addParent(aInParent);
        scope = DefinitionScope.get(aInParent.getName());
    }

    public Pair<ParseDirective,Item> beginCB(Node aInData, Item aInParentItem)
    {
        return new Pair<ParseDirective, Item>(ParseDirective.CONTINUE,
                                              MNamer.get(
                                                      (DefinitionScope.CLASS == scope ?
                                                              aInParentItem.getGID().getName() :
                                                              aInData.getNamedValue(Strings.CLASS,
                                                                                aInData.getNamedValue(Strings.NAME, null, false),
                                                                                true)),
                                                      true));
    }

    private DefinitionScope scope = DefinitionScope.NONE;

}


text:
{-
Copyright (C) 2006-2011 John Goerzen <jgoerzen@complete.org>

All rights reserved.

For license and copyright information, see the file LICENSE
-}

module ProgressTrackertest(tests) where
import Data.Progress.Tracker
import Test.HUnit
import Control.Concurrent.MVar

setup =
    do timem <- newMVar 0
       let timesource = readMVar timem
       po <- newProgress' (ProgressStatus 0 100 0 "" timesource) []
       return (po, timem)

settime timem newval = swapMVar timem newval >> return ()

test_incrP =
    do (po, timem) <- setup
       incrP po 5
       withStatus po $ \s ->
                  do assertEqual "completedUnits" 5 (completedUnits s)
                     assertEqual "totalUnits" 100 (totalUnits s)
       incrP po 95
       withStatus po $ \s ->
                  do assertEqual "completedUnits" 100 (completedUnits s)
                     assertEqual "totalUnits" 100 (totalUnits s)
       incrP po 5
       withStatus po $ \s ->
                  do assertEqual "completedUnits" 105 (completedUnits s)
                     assertEqual "totalUnits" 105 (totalUnits s)
       incrP' po 5
       withStatus po $ \s ->
                  do assertEqual "completedUnits" 110 (completedUnits s)
                     assertEqual "totalUnits" 105 (totalUnits s)
       incrTotal po 10
       withStatus po $ \s ->
                  do 110 @=? completedUnits s
                     115 @=? totalUnits s

test_setP =
    do (po, timem) <- setup
       setP po 5
       withStatus po $ \s ->
           do 5 @=? completedUnits s
              100 @=? totalUnits s
       setP po 100
       withStatus po $ \s ->
           do 100 @=? completedUnits s
              100 @=? totalUnits s
       setP po 105
       withStatus po $ \s ->
           do 105 @=? completedUnits s
              105 @=? totalUnits s
       setP' po 110
       withStatus po $ \s ->
           do 110 @=? completedUnits s
              105 @=? totalUnits s
       setTotal po 115
       withStatus po $ \s ->
           do 110 @=? completedUnits s
              115 @=? totalUnits s

test_speed =
    do (po, timem) <- setup
       getSpeed po >>= assertEqual "initial speed" 0
       getETR po >>= assertEqual "initial ETR" 0
       getETA po >>= assertEqual "initial ETA" 0

       incrP po 10
       getSpeed po >>= assertEqual "speed after incr" 0
       getETR po >>= assertEqual "ETR after incr" 0
       getETA po >>= assertEqual "ETA after incr" 0

       settime timem 5
       getSpeed po >>= assertEqual "first speed" 2.0
       getETR po >>= assertEqual "first ETR" 45
       getETA po >>= assertEqual "first ETA" 50

       incrP po 90
       getSpeed po >>= assertEqual "speed 2" 20.0
       getETR po >>= assertEqual "etr 2" 0
       getETA po >>= assertEqual "eta 2" 5

       settime timem 400
       setP po 90
       getSpeed po >>= assertEqual "speed 3" 0.225
       getETR po >>= assertEqual "etr 2" 44
       getETA po >>= assertEqual "eta 2" 444

test_callback =
    do (po, _) <- setup
       mcounter <- newMVar (0::Int)
       mcounter1 <- newMVar (0::Int)
       mcounter2 <- newMVar (0::Int)
       (po2, _) <- setup
       (po3, _) <- setup

       addCallback po (minc mcounter)
       addParent po po2
       incrP po 5
       readMVar mcounter >>= assertEqual "cb1" 1
       withStatus po (\x -> 5 @=? completedUnits x)
       withStatus po2 (\x -> do 5 @=? completedUnits x
                                200 @=? totalUnits x)

       addCallback po2 (minc mcounter2)
       incrP po 100
       readMVar mcounter2 >>= (\x -> assertBool "cb2" (0 /= x))
       withStatus po2 (\x -> do 105 @=? completedUnits x
                                205 @=? totalUnits x)

       incrP' po 5
       withStatus po2 (\x -> do 110 @=? completedUnits x
                                205 @=? totalUnits x)

       finishP po
       withStatus po2 (\x -> do 110 @=? completedUnits x
                                210 @=? totalUnits x)

    where minc mv _ _ = modifyMVar_ mv (\x -> return $ x + 1)

tests = TestList [TestLabel "incrP" (TestCase test_incrP),
                  TestLabel "setP" (TestCase test_setP),
                  TestLabel "speed" (TestCase test_speed),
                  TestLabel "test_callback" (TestCase test_callback)]


text:
maintainer       "RightScale, Inc."
maintainer_email "support@rightscale.com"
license          "Copyright RightScale, Inc. All rights reserved."
description      "Manages the Subversion version control system"
long_description IO.read(File.join(File.dirname(__FILE__), 'README.rdoc'))
version          "0.0.1"

depends "repo"

recipe  "repo_svn::default", "Default pattern of loading packages and resources provided"


text:
"""This example gets all URL channels in a host ad client.

To get ad clients, run get_all_ad_clients_for_host.py.

Tags: urlchannels.list
"""

__author__ = 'jalc@google.com (Jose Alcerreca)'

import argparse
import sys

from apiclient import sample_tools
from oauth2client import client

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
    'ad_client_id',
    help='The ad client ID for which to get URL channels')

MAX_PAGE_SIZE = 50

def main(argv):
  # Authenticate and construct service.
  service, flags = sample_tools.init(
      argv, 'adsensehost', 'v4.1', __doc__, __file__, parents=[argparser])
  ad_client_id = flags.ad_client_id

  try:
    # Retrieve URL channel list in pages and display data as we receive it.
    request = service.urlchannels().list(adClientId=ad_client_id,
                                         maxResults=MAX_PAGE_SIZE)

    while request is not None:
      result = request.execute()
      if 'items' in result:
        url_channels = result['items']
        for url_channel in url_channels:
          print ('URL channel with ID "%s" and URL pattern "%s" was found.'
                 % (url_channel['id'], url_channel['urlPattern']))

        request = service.customchannels().list_next(request, result)
      else:
        print 'No URL channels were found.'
        break

  except client.AccessTokenRefreshError:
    print ('The credentials have been revoked or expired, please re-run the '
           'application to re-authorize')

if __name__ == '__main__':
  main(sys.argv)


text:
FactoryGirl.define do
  factory :location do
    name 'VRS Services'
    description 'Provides jobs training'
    short_desc 'short description'
    accessibility [:tape_braille, :disabled_parking]
    latitude 37.583939
    longitude(-122.3715745)
    organization
    address

    factory :location_with_admin do
      admin_emails ['moncef@smcgov.org']
    end

    factory :location_for_org_admin do
      name 'Samaritan House'
      urls ['http://samaritanhouse.com']
    end

    factory :loc_with_extra_whitespace do
      description ' Provides job training'
      hours ' Monday-Friday 10am-3pm '
      name 'VRS   Services '
      short_desc 'Provides job training. '
      transportation ' BART stop 1 block away.'
      urls [' http://samaritanhouse.com  ']
      admin_emails [' foo@bar.com  ']
      emails [' bar@foo.com  ']
    end
  end

  factory :nearby_loc, class: Location do
    name 'Library'
    description 'great books about jobs'
    short_desc 'short description'
    accessibility [:elevator]
    latitude 37.5808591
    longitude(-122.343072)
    association :address, factory: :near
    languages %w(spanish Arabic)
    association :organization, factory: :nearby_org
  end

  factory :no_address, class: Location do
    name 'No Address'
    description 'no coordinates'
    short_desc 'short description'
    association :mail_address, factory: :po_box
    organization
  end

  factory :farmers_market_loc, class: Location do
    name 'Belmont Farmers Market'
    description 'yummy food about jobs'
    short_desc 'short description'
    latitude 37.3180168
    longitude(-122.2743951)
    association :address, factory: :far_west
    organization
  end

  factory :far_loc, class: Location do
    name 'Belmont Farmers Market'
    description 'yummy food'
    short_desc 'short description'
    latitude 37.6047797
    longitude(-122.3984501)
    association :address, factory: :far
    languages %w(spanish Arabic)
    organization
  end

  factory :loc_with_nil_fields, class: Location do
    name 'Belmont Farmers Market with cat'
    description 'yummy food'
    short_desc 'short description'
    address
    organization
    latitude 37.568272
    longitude(-122.3250474)
  end

  factory :soup_kitchen, class: Location do
    name 'Soup Kitchen'
    description 'daily hot soups'
    short_desc 'short description'
    latitude 37.3180168
    longitude(-122.2743951)
    association :address, factory: :far_west
    association :organization, factory: :food_pantry
  end
end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>SCIONLab Coordination Service</title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel='icon' type='image/x-icon' href='/public/img/favicon.ico'/>
  <link rel="stylesheet" href="/public/css/style.css">
  <link rel="stylesheet" href="https://unpkg.com/bootstrap@3.3.6/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic">
  <link rel="stylesheet" href="https://unpkg.com/adminlte@2.4.0/dist/css/AdminLTE.css">
  <link rel="stylesheet" href="https://unpkg.com/lightbox2@2.10.0/dist/css/lightbox.min.css">
  <link rel="stylesheet" href="/public/css/hover-caption.css">
  <link rel="stylesheet" href="https://unpkg.com/font-awesome@4.5.0/css/font-awesome.min.css">

Login

Register

Tutorials

SCION Architecture

Account

          Admin

          User

          Logout

SCIONLab Coordination Service

© SCIONLab 2018


text:
<?php

namespace Wiser\Event;

use Wiser\View;
use Symfony\Component\EventDispatcher\Event;

class GetViewEvent extends Event
{
	/**
	 * @var \Wiser\View
	 */
	protected $view;

	public function __construct(View $view)
	{
		$this->view = $view;
	}

	/**
	 * @return \Wiser\View
	 */
	public function getView()
	{
		return $this->view;
	}

	/**
	 * @param \Wiser\View $view
	 */
	public function setView(View $view)
	{
		$this->view = $view;
	}
}


text:
package br.gov.servicos.servico.publicoAlvo;

import br.gov.servicos.busca.Buscador;
import br.gov.servicos.servico.Servico;
import lombok.experimental.FieldDefaults;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static java.util.Optional.ofNullable;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;
import static lombok.AccessLevel.PRIVATE;

@Controller
@FieldDefaults(level = PRIVATE, makeFinal = true)
class PublicoAlvoController {

    Buscador buscador;

    @Autowired
    PublicoAlvoController(Buscador buscador) {
        this.buscador = buscador;
    }

    @RequestMapping("/publico-alvo/{id}")
    ModelAndView publicoAlvo(@PathVariable String id,
                             @RequestParam(required = false) Character letra) {

        Character primeiraLetra = ofNullable(letra).map(Character::toUpperCase).orElse('A');
        Map<Character, List<Servico>> servicosPorLetraInicial = servicosAgrupadosPorLetraInicial(id);

        Map<String, Object> model = new HashMap<>();
        model.put("letraAtiva", primeiraLetra);
        model.put("publicoAlvo", extraiPublicoAlvo(id, servicosPorLetraInicial.get(primeiraLetra)));
        model.put("servicos", servicosPorLetraInicial.get(primeiraLetra));
        model.put("letras", letrasDisponiveis(servicosPorLetraInicial.keySet()));

        return new ModelAndView("publico-alvo", model);
    }

    private Map<Character, List<Servico>> servicosAgrupadosPorLetraInicial(String publicoAlvo) {
        return buscador.buscaPor("publicosAlvo.id", ofNullable(publicoAlvo))
                .stream()
                .collect(groupingBy(s -> s.getTitulo().trim().toUpperCase().charAt(0)));
    }

    private List<Character> letrasDisponiveis(Set<Character> letras) {
        return letras
                .stream()
                .sorted()
                .collect(toList());
    }

    private PublicoAlvo extraiPublicoAlvo(String id, List<Servico> servicos) {
        return servicos
                .stream()
                .flatMap(s -> s.getPublicosAlvo().stream())
                .filter(p -> p.getId().equals(id))
                .findFirst()
                .get();
    }

}


text:
Implemented as a liquid filter for the Jekyll static website generator. Add `jekyll-scholmd.rb` to the `_plugins`folder of your Jekyll site and include `{{ content | to_scholmd }}` in your template, e.g. default.html.

Currently supported identifiers:

* IGSN. [International Geosample Number](http://dokuwiki.gfz-potsdam.de/datawiki/doku.php?id=igsn:syntax)
* MGI identifiers for genetically modified mouse strains in the [Internal Mouse Strain Resource](http://www.findmice.org/about)
* ENA. [Genbank / ENA / DDBJ nucleotide sequences](http://www.ebi.ac.uk/ena/about/about)
* UniProt protein sequences from the [UniProt database](http://www.uniprot.org/help/about)
* PDB. [Protein Data Bank protein structure information](http://www.rcsb.org/pdb/static.do?p=home/faq.html)

Please open an issue for additional identifiers and/or improvements in the regex patterns used.

The software is released under a [MIT license](license.txt).


text:
package ubic.gemma.web.remote;

/**
 * @author kelsey
 *
 */

// Private inner class for converting doubple point to a point of strings.
public class StringPoint {

    private static int PERCISSION = 4;

    private String x;
    private String y;

    StringPoint() {
        super();
    }

    StringPoint( Double x, Double y ) {
        this();
        this.x = Double.toString( x );
        this.y = Double.toString( y );

        if ( this.x.length() > PERCISSION ) this.x = this.x.substring( 0, PERCISSION );

        if ( this.y.length() > PERCISSION ) this.y = this.y.substring( 0, PERCISSION );

    }
}


text:
package com.dgrid.util.webclient.jakarta;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;

import com.dgrid.util.webclient.HttpResponse;

public class JakartaCommonsHttpResponse implements HttpResponse {

	private HttpMethod method;

	private int responseCode;

	private String contentType;

	private String contentCharset;

	private long contentLength;

	public JakartaCommonsHttpResponse(HttpMethod method, int responseCode,
			String contentType, String charset, long contentLength) {
		this.method = method;
		this.responseCode = responseCode;
		this.contentType = contentType;
		this.contentCharset = charset;
		this.contentLength = contentLength;
	}

	public int getResponseCode() {
		return (responseCode);
	}

	public String getURI() {
		try {
			return method.getURI().toString();
		} catch (URIException e) {
			throw new RuntimeException(e);
		}
	}

	public String getContentType() {
		return (contentType);
	}

	public String getContentCharset() {
		return contentCharset;
	}

	public long getContentLength() {
		return contentLength;
	}

	public String getResponseBodyAsString() throws IOException {
		return (method.getResponseBodyAsString());
	}

	public InputStream getResponseBodyAsStream() throws IOException {
		return (method.getResponseBodyAsStream());
	}

	public void releaseConnection() {
		method.releaseConnection();
	}

}


text:
layout: plain
title: Saturday Academy Apprenticeships in Science & Engineering (ASE)
subtitle: Summer 2018
permalink: /teaching/su18ase/
modified: <2019-12-17 Tue>
---
## News

* Check out some photos during this summer program!

{% include image-gallery.html folder='/images/2018_ase_pic' %}

## About

*   **When**: 2018.06 - 2018.08
*   **Where**: [Computer Science Department](http://www.pdx.edu/computer-science/){:target="_blank"}, Portland State University
*   **What**: [ASE internship](https://www.saturdayacademy.org/ase){:target="_blank"} - [Simulating Quantum Algorithms](https://www.saturdayacademy.org/simulating-quantum-algorithms-quantum-cloud-platforms)
*   **Interns**: *Sydney Von Arx* [Lake Oswego High School](https://www.losdschools.org/site/Default.aspx?PageID=25){:target="_blank"}; *Marshal Xu* [Lincoln High School](https://www.pps.net/Domain/136){:target="_blank"}
*   **Mentor**: Fang Song, Assistant Professor, CS@PSU. Office: FAB 120-07. Phone: 503-725-4060
*   **Slack**: [quantumase18](https://quantumase18.slack.com/) for communications.
*   **Useful Contacts**
    *  ASE teacher monitor: Albert Lee. Phone: (503) 830-5292.
    *  CS Department @ PSU: 503-725-4036
	*  PSU [Campus Public Safety](https://www.pdx.edu/cpso/campus-public-safety): 633 SW Montgomery St. Portland, OR 97201. Emergency: **503-725-4404**; Non-Emergency: **503-725-4407**

## Schedule

| Dates  | Topic | Note  |
| :---------: |:----------:|:-----:|
| June 18 - June 24 | Welcome and Registration| |
| June 25 - July 1 | Quantum Basics: Qubits, Quantum Gates, and Entanglement  | [IBM Q Beinners Guide](https://quantumexperience.ng.bluemix.net/qx/tutorial?sectionId=beginners-guide&page=introduction)|
| July 2 - July 8  | Quantum Teleportation and Superdense coding
 Experiment with GUI  | [IBM Q Beinners Guide](https://quantumexperience.ng.bluemix.net/qx/tutorial?sectionId=beginners-guide&page=introduction)
 [IBM QISKIT Tutorial](https://nbviewer.jupyter.org/github/QISKit/qiskit-tutorial/blob/master/index.ipynb): Section 2.2|
| July 9 - July 15 | Setting up QISKIT
 Implement simple QAlgs: Teloportation and Super dense coding
 More alg's: Deutsch-Josza and Simon's | [IBM QISKIT Tutorial](https://nbviewer.jupyter.org/github/QISKit/qiskit-tutorial/blob/master/index.ipynb) Section 2.1,2.2,2.5
 Watrous note: Lec5 [PDF](https://cs.uwaterloo.ca/~watrous/CPSC519/LectureNotes/05.pdf){:target="_blank"}, Lec6 [PDF](https://cs.uwaterloo.ca/~watrous/CPSC519/LectureNotes/06.pdf){:target="_blank"} |
| July 12 | [Mid-summer Conference](https://www.saturdayacademy.org/about/events/ase-midsummer-conference) | Corvallis, OR |
| July 16 - July 22| Advanced Quantum Algorithms
 Bernstein-Vazirani, Grover's Search, etc. | [IBM QISKIT Tutorial](https://nbviewer.jupyter.org/github/QISKit/qiskit-tutorial/blob/master/index.ipynb) Section 2.5 |
| July 23 - July 29 | Implement Advanced Quantum Algorithms | [IBM QISKIT Tutorial](https://nbviewer.jupyter.org/github/QISKit/qiskit-tutorial/blob/master/reference/qis/teleportation_superdensecoding.ipynb) Section 2.5 |
| July 30 - August 5 | Implement Advanced Quantum Algorithms | [QImeplementation for Beginners](https://arxiv.org/abs/1804.03719) Section 2,3,4 |
| August 6 - August 12 | Analysis | [QImeplementation for Beginners](https://arxiv.org/abs/1804.03719) Section 2,3,4 |
| August 13 - August 17 |  Wrap up and Presentation | [QImeplementation for Beginners](https://arxiv.org/abs/1804.03719) Section 2,3,4 |
| August 17 |[ASE Symposium](https://www.saturdayacademy.org/about/events/ase-symposium) | University of Portland |
{:.mbtablestyle}

## Peer lectures

Interns are expected to give regular lectures to the peers on their work, typically on Mondays and Thursdays. FAB 88-03 M/Tu 2 - 4pm June 25 - July 12; 3 - 5pm the rest of the term.

|Date| Presentor| Topic|
| :---------: |:----------:|:-----:|
|June 25 | Marshal | Qubit and Single-qubit gates |
|June 28 | Sydney | Multi-qubit Gates |
| July 5 | Marshal & Sydney| Teleportation and Superdense coding|
|July 9 | Sydney & Marshal | Deutsch-Josza and Simon's algorithms |
|July 16 | Sydney & Marshal | Simon's algorithm analysis and Grover algorithm |
|July 19 | Sydney | Shor's algorithm |
| July 23 | |TBD|
{:.mbtablestyle}

## Resources

*  IBM Q Experience [Beginner's Guide](https://quantumexperience.ng.bluemix.net/qx/tutorial?sectionId=beginners-guide&page=introduction); [Full User Guide](https://quantumexperience.ng.bluemix.net/qx/tutorial?sectionId=full-user-guide&page=introduction); [QISKIT](https://www.qiskit.org/)
*  Umesh Vazirani's video lectures on quantum basics [youtube](https://www.youtube.com/playlist?list=PLDAjb_zu5aoFazE31_8yT0OfzsTcmvAVg)
*  Scott Aaronson's nice set of lectures that give a gentle
introduction of theory of computation and QC
[Democritus](https://www.scottaaronson.com/democritus/)
*  John Watrous's (more formal and mathematical) [lecture notes on QC](https://cs.uwaterloo.ca/~watrous/LectureNotes/CPSC519.Winter2006/all.pdf)
*  Quantum Algorithm Implementations for Beginners [arXiv](https://arxiv.org/abs/1804.03719)


text:
var QueryOrdering;
(function(){
    dependenciesLoader(["$", "Mousetrap", "React", "ReactDOM", "Loader", "Synchronise", "Typeahead", "QueryResultPreview", "panelFlow" /* Instance of the flow */], function(){
        QueryOrdering = React.createClass({
            getInitialState: function(){
                return {
                    loadingRules               : false,
                    loadingListFieldsAvailable : false,
                    saving                     : false,
                    query_id                   : "",
                    orderings                  : Array(),
                    listFieldsAvailable        : Array()
                };
            },
            componentDidMount: function(){
                var target = this;

                $("#blocks").on('panelWillAppear', function(e, block){
                    if(block.blockId() == "ordering"){
                        $("#titleBlock h1 small").text("Define ordering");
                    }
                });

                target.setState({
                    loadingRules: true,
                    query_id: urlH.getParam("query"),
                    loadingListFieldsAvailable: true
                });

                Synchronise.Cloud.run("orderingRules", {id_query: urlH.getParam("query"), realtime: true}, {
                    success: function(result){
                        target.setState({orderings: result});
                    },
                    error: function(err){
                        new ModalErrorParse(err);
                    },
                    always: function(){
                        target.setState({loadingRules: false});
                    }
                });

                Synchronise.Cloud.run("fieldsAvailableForOrderingInQuery", {id_query: urlH.getParam("query"), realtime: true}, {
                    success: function(fields){
                        fields.forEach(function(item, i, fields){
                            fields[i].text = item.tableName + " > " + item.fieldName;
                        });
                        target.setState({listFieldsAvailable: fields});
                    },
                    always: function(){
                        target.setState({loadingListFieldsAvailable: false});
                    }
                });
            },
            fieldSelected: function(itemSelected){
                var target = this;
                if(!this.state.saving){
                    target.setState({saving: true});

                    Synchronise.Cloud.run("createOrderingRule", {id_query: this.state.query_id, id_field: itemSelected.item.displayedFieldId}, {
                        always: function(){
                            target.setState({saving: false});
                        },
                        error: function(err){
                            new ModalErrorParse(err);
                        }
                    });
                }
            },
            goToFieldsSelection: function(){
                panelFlow.scrollToBlock("fields");
            },
            render: function(){
                var target = this;

                // No fields selected to be displayed on the query
                var noFieldsWarning = "";
                if(!this.state.loadingListFieldsAvailable && !this.state.loadingRules){
                    if(!this.state.listFieldsAvailable.length && !this.state.orderings.length){
                        noFieldsWarning = (

You haven't selected any fields. It's okay we forgive you. Click here to go and select some super awesome fields.

);
                    }
                }

                // Displays the list of fields that are selectable
                var selectableFields = "";
                var dataForSelectableFields = "";
                if(!this.state.loadingListFieldsAvailable && this.state.listFieldsAvailable.length){
                    dataForSelectableFields = (

                            <Typeahead options={this.state.listFieldsAvailable}
                                       onSelected={this.fieldSelected}
                                       typeContent="text"
                                       className="form-control input-lg"
                                       placeholder="Type the name of a field that you have previously selected to display"/>
                            {target.state.listFieldsAvailable.map(function(item){
                                return <QueryOrderingAvailableField data={item}
                                                                    itemClicked={target.fieldSelected}
                                                                    saving={target.state.saving}
                                                                    key={"queryorderingavailable"+item.displayedFieldId}/>;
                            })}

                    );
                }else if(this.state.loadingListFieldsAvailable){
                    dataForSelectableFields = <Loader/>;
                }else if(!this.state.listFieldsAvailable.length){
                    dataForSelectableFields = (
You have already selected all of the available fields for ordering for this query
);
                }

                selectableFields = (

                                <legend>Selectable fields</legend>
                                {dataForSelectableFields}

                );

                var selectedFields = "";
                var fields = "";
                // If ordering rules available
                if(this.state.orderings.length){
                    fields = (

                            {target.state.orderings.map(function(item){
                                return (<OrderingRule type={item.type}
                                                      tableName={item.tableName}
                                                      fieldName={item.fieldName}
                                                      ordering={item.ordering}
                                                      id={item.id}
                                                      id_query={urlH.getParam("query")}
                                                      key={"ordering"+item.id}/>);
                            })}

                    );
                }else if(!this.state.loadingRules){
                    // If not loading and no rules defined, displays an informational message
                    fields = (

There is no fields selected for ordering at the moment

                    );
                }

                // If loading the list of ordering rules displays a loader
                if(this.state.loadingRules){
                    fields = (
<Loader/>
);
                }

                // Displays the list of fields that have been selected
                selectedFields = (

                        <legend>Selected fields</legend>
                        {fields}

                );

                var resultPreview = (

                        <legend style={{marginBottom: "10px"}}>Results</legend>
                        <QueryResultPreview id_query={urlH.getParam("query")}/>

                );

                return (

In some cases your queries will return multiple results. You can reorder the list of results by applying ordering rules

                        {noFieldsWarning}

                            {selectableFields}
                            {selectedFields}
                            {resultPreview}

                );
            }
        });

        var QueryOrderingAvailableField = React.createClass({
            getInitialState: function(){
                return { adding: false };
            },
            selected: function(e){
                if(!this.state.adding && !this.props.saving){
                    this.setState({adding: true});
                    this.props.itemClicked({item: this.props.data});
                    $(ReactDOM.findDOMNode(this)).animate({
                        opacity: 0.3
                    });
                }else{
                    $(ReactDOM.findDOMNode(this)).effect("highlight");
                }
            },
            render: function(){
                return (

                            {this.props.data.type}
                            {this.props.data.tableName}
                            {this.props.data.fieldName}

                );
            }
        });

        // Displays a row of ordering rule
        // Props :
        // - type : the type of data (number, string, date ...)
        // - tableName : the name of the table that own of the field
        // - fieldName : the name of the field concerned by the ordering
        // - ordering : the actual ordering (asc|desc)
        var OrderingRule = React.createClass({
            getInitialState: function(){
                return {
                    ordering: null,
                    removing: false
                };
            },
            componentDidMount: function(){
                  this.setState({
                      ordering: this.props.ordering
                  });
            },
            changeAscDesc: function(ev){
                console.log(ev.target.value);
                this.setState({
                    ordering: ev.target.value
                });
            },
            remove: function(){
                var target = this;

                if(!target.state.removing){
                    target.setState({removing: true});

                    $(ReactDOM.findDOMNode(target)).animate({
                        opacity: 0.3
                    });

                    Synchronise.Cloud.run("removeOrderingRule", {id_rule: this.props.id, id_query: this.props.id_query}, {
                        error: function(err){
                            new ModalErrorParse(err);
                        },
                        always: function(){
                            target.setState({removing: false});
                        }
                    });
                }
            },
            render: function(){
                return (

                                    {this.props.type}
                                    {this.props.tableName}
                                    {this.props.fieldName}

                                    <select className="form-control ascDescValue" value={this.state.ordering} onChange={this.changeAscDesc}>
                                        <option value="asc">Ascending</option>
                                        <option value="desc">Descending</option>
                                    </select>

                                <button className="btn btn-xs btn-default cbutton cbutton--effect-novak">Remove</button>

                );
            }
        });

        ReactDOM.render(<QueryOrdering />, document.getElementById("ordering"));
    });
})();


text:
from threading import local

from django import forms
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _

from plata.discount import models
from plata.utils import jsonize

# Internal state tracking helper for config fields
_discount_admin_state = local()

class DiscountAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(DiscountAdminForm, self).__init__(*args, **kwargs)

        self.fields['config'].required = False # Seems to be necessary because of
                                               # the custom validation

        self.fields['config_options'] = forms.MultipleChoiceField(
            choices=((key, cfg.get('title', key)) for key, cfg in self._meta.model.CONFIG_OPTIONS),
            label=_('Configuration options'),
            help_text=_('Save and continue editing to configure options.'),
            )

        _discount_admin_state._plata_discount_config_fieldsets = []

        # Determine the list of selected configuration options
        # 1. POST data
        # 2. get data from the instance we are editing
        # 3. fall back to allowing all products in the discount

        try:
            selected = self.data.getlist('config_options')
        except AttributeError:
            if self.instance.pk:
                selected = self.instance.config.keys()
            else:
                selected = None

        selected = selected or ('all',)
        self.fields['config_options'].initial = selected

        for s in selected:
            cfg = dict(self._meta.model.CONFIG_OPTIONS)[s]

            # Always create a fieldset for selected configuration options,
            # even if we do not have any form fields.
            fieldset = [
                _('Discount configuration: %s') % cfg.get('title', s),
                {'fields': []},
                ]

            for k, f in cfg.get('form_fields', []):
                self.fields['%s_%s' % (s, k)] = f

                # Set initial value if we have one already in the configuration
                if k in self.instance.config.get(s, {}):
                    f.initial = self.instance.config[s].get(k)

                fieldset[1]['fields'].append('%s_%s' % (s, k))

            _discount_admin_state._plata_discount_config_fieldsets.append(fieldset)

    def clean(self):
        data = self.cleaned_data

        if 'config' in self.changed_data:
            return data

        selected = data.get('config_options', [])
        config_options = {}

        for s in selected:
            cfg = dict(self._meta.model.CONFIG_OPTIONS)[s]

            option_item = {}
            for k, f in cfg.get('form_fields', []):
                key = '%s_%s' % (s, k)
                if key in data:
                    option_item[k] = data.get(key)

            config_options[s] = option_item

        self.instance.config = jsonize(config_options)
        data['config'] = self.instance.config
        return data

class DiscountAdmin(admin.ModelAdmin):
    form = DiscountAdminForm
    list_display = ('name', 'type', 'is_active', 'valid_from',
        'valid_until', 'code', 'value')
    list_filter = ('type', 'is_active')
    ordering = ('-valid_from',)
    search_fields = ('name', 'code', 'config')

    def get_fieldsets(self, request, obj=None):
        fieldsets = super(DiscountAdmin, self).get_fieldsets(request, obj)
        fieldsets[0][1]['fields'].remove('config')

        fieldsets.append((_('Raw configuration'), {
            'fields': ('config',),
            'classes': ('collapse',),
            }))
        fieldsets.append((_('Configuration'), {
            'fields': ('config_options',),
            }))

        fieldsets.extend(_discount_admin_state._plata_discount_config_fieldsets)
        del _discount_admin_state._plata_discount_config_fieldsets

        return fieldsets

admin.site.register(models.Discount, DiscountAdmin)


text:
import { URL } from './config';

export const GET_EXPENSES_REQUEST = 'getExpenses.request'
export const GET_EXPENSES_SUCCESS = 'getExpenses.success'
export const GET_EXPENSES_FAILURE = 'getExpenses.failure'
export const DELTE_EXPENSES_REQUEST = 'deleteExpenses.request'
export const DELTE_EXPENSES_SUCCESS = 'deleteExpenses.success'
export const DELTE_EXPENSES_FAILURE = 'deleteExpenses.failure'

export function getExpensesSuccess(expenses) {
    return {
        type: GET_EXPENSES_SUCCESS,
        expenses
    }
}
export function getExpensesRequest() {
    return {
        type: GET_EXPENSES_REQUEST,
    }
}
export function getExpensesFailure(error) {
    return {
        type: GET_EXPENSES_FAILURE,
        error
    }
}

export function deleteExpensesSuccess(id) {
    return {
        type: DELETE_EXPENSES_SUCCESS,
    }
}
export function deleteExpensesRequest() {
    return {
        type: DELETE_EXPENSES_REQUEST,
    }
}
export function deleteExpensesFailure(error) {
    return {
        type: DELETE_EXPENSES_FAILURE,
        error
    }
}

export function getExpenses() {
    return (dispatch) => {

       dispatch(getExpensesRequest())

        return fetch(URL + "/api/expenses/", {
                method: "GET",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.json().then(json => ({
                json,
                response
            })))
            .then(({
                json,
                response
            }) => {
                if (response.ok === false) {
                    console.log('error_ ' + JSON.stringify(response));

                    return Promise.reject(response, json)
                }
                return json
            })
            .then(
                // success
                data => {
                    console.log('getExpenses***sucesssucesssucesssucesssucesssucesssucesssucess ' + JSON.stringify(data));
                    dispatch(getExpensesSuccess(data));
                },
                // failure
                (data) => dispatch(getExpensesFailure(data.status || 'Something failed'))
            ).catch((error) => console.warn("fetch error:", error))
    }
}

export function deleteExpenses(expense_id) {
    return (dispatch) => {

        return fetch(URL + "/api/expenses/" + expense_id, {
                method: "DELETE",
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
            }).then(response => response.json().then(json => ({
                json, response
            })))
            .then(({
                json, response
            }) => {
                if (response.ok === false) {
                    console.log('error_ ' + JSON.stringify(response));

                    return Promise.reject(response, json)
                }
                return json
            })
            .then(
                // success
                data => {
                    console.log('sucess ' + JSON.stringify(data));
                    dispatch(getExpenses());
                },
                // failure
                (data) => dispatch(deleteFailure(data.status || 'Deleting failed'))
            ).catch((error) => console.warn("fetch error:", error))
    }
}

export function editExpenses(expense_id) {
  return (dispatch) => {

    //dispatch(editRequest())

    var hash = {

          };
          var formBody = [];
          for (var property in hash) {
              var encodedKey = encodeURIComponent(property);
              var encodedValue = encodeURIComponent(hash[property]);
              formBody.push(encodedKey + "=" + encodedValue);
          }

          formBody = formBody.join("&");

         return fetch(URL+"/api/expenses/" + expense_id, {
                  method: "PUT",
                  headers: {
                      'Accept': 'application/json',
                      'Content-Type': 'application/x-www-form-urlencoded'
                  },
                  body: formBody
              })
    .then(response => response.json().then(json => ({ json, response })))
    .then(({json, response}) => {
      if (response.ok === false) {
        console.log('error_ '+JSON.stringify(response));

        return Promise.reject(response, json)
      }
      return json
    })
    .then(
      // success
      data => {

        console.log('sucess ' +JSON.stringify(data));
        dispatch(editSuccess(hash, data.userName));
        //dispatch(replaceRoute('home')); ---get the parent route

      },
      // failure
      (data) => dispatch(editFailure(data.status || 'Editing failed'))
    ).catch((error) => console.warn("fetch error:", error))
  }
}


text:
package play.db.jpa;

import play.api.Configuration;
import play.api.Environment;
import play.api.inject.Binding;
import play.api.inject.Module;
import scala.collection.Seq;

/**
 * Injection module with default JPA components.
 */
public class JPAModule extends Module {

    @Override
    public Seq<Binding<?>> bindings(Environment environment, Configuration configuration) {
        return seq(
            bind(JPAApi.class).toProvider(DefaultJPAApi.JPAApiProvider.class),
            bind(JPAConfig.class).toProvider(DefaultJPAConfig.JPAConfigProvider.class)
        );
    }

}


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Widget_Favorite extends Widget {

    /**
     * @var  Model_Article|NULL  current article
     */
    protected $article = NULL;

    public function run()
    {
        $view = View::factory('widget/favorite');

        // Get id of article
        $article_id = $this->article->id;

        // Get id of current user
        $current_user_id = isset($this->user) ? $this->user->id : NULL;

        // Get ids of users
        $user_ids = Model_User::get_user_ids($article_id);

        // Set variable of view
        $view->set(array(
            'article_id'      => $article_id,
            'current_user_id' => $current_user_id,
            'user_ids'        => $user_ids,
        ));

        return $view;
    }
}


text:
This folder contains instructions that guide you through the process of setting up a GCP based MLOps environment as depicted on the below diagram.

![Reference topology](/images/mlops-env.png)

The core services in the environment are:
- [AI Platform Notebooks](https://cloud.google.com/ai-platform/notebooks/docs/): ML experimentation and development
- [AI Platform Training](https://cloud.google.com/ai-platform/training/docs/): Scalable, serverless model training
- [AI Platform Prediction](https://cloud.google.com/ai-platform/prediction/docs/): Scalable, serverless model serving
- [Dataflow](https://cloud.google.com/dataflow/docs): Distributed batch and streaming data processing
- [BigQuery](https://cloud.google.com/bigquery/docs): Scalable analytics data warehouse
- [Google Cloud Storage](https://cloud.google.com/bigquery/docs): Artifact storage
- [Kubeflow Pipelines](https://www.kubeflow.org/docs/pipelines/installation/standalone-deployment/): Kubeflow standalone machine learning pipeline deployed on [Google Kubernetes Engine (GKE)](https://cloud.google.com/kubernetes-engine/docs/)
- [Cloud SQL](https://cloud.google.com/sql/docs/mysql/connect-kubernetes-engine): Machine learning metadata management
- [Cloud Build](https://cloud.google.com/cloud-build/docs/): CI/CD tooling to build and deploy custom container image
- [Container Registry](https://cloud.google.com/container-registry/docs/): secure, private container image storage

In this environment, all services are provisioned in the same [Google Cloud Project](https://cloud.google.com/storage/docs/projects).

An instance of **AI Platform Notebooks** is used as a primary experimentation/development workbench. The instance is configured using a custom container image built with **Cloud Build** and hosted on **Container Registry** that should be optimized for a given ML project. In this example, you will configure the instance optimized for developing **Kubeflow Pipelines (KFP)** and TensorFlow Extended (TFX) solutions.

The environment uses a [standalone deployment of Kubeflow Pipelines on GKE](https://www.kubeflow.org/docs/pipelines/installation/standalone-deployment/), as depicted on the below diagram:

![KFP Deployment](/images/kfp.png)

The KFP services are deployed to a GKE cluster and configured to use a **Cloud SQL**  instance for ML Metadata and **Google Cloud Storage** for artifact storage. The KFP services access the Cloud SQL through [Cloud SQL Proxy](https://cloud.google.com/sql/docs/mysql/sql-proxy). External clients use [Inverting Proxy](https://github.com/google/inverting-proxy) to interact with the KFP services.

The provisioning of the environment has been split into two hands-on labs.

## [Creating an AI Platform Notebook instance](creating-notebook-instance/README.md)

In the first lab you create an instance of **AI Platform Notebooks**.

## [Provisioning a standalone deployment of Kubeflow Pipelines](provisioning-kfp/README.md)

 In the second lab you provision other services comprising the environment, including a standalone deployment of **Kubeflow Pipelines**.

# Before you begin

You need to have **Project Owner**  permissions in your GCP project to walk through the labs.


text:
"""Config flow to configure zone component."""
from typing import Optional

import voluptuous as vol

from iaqualink import AqualinkClient, AqualinkLoginException

from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.helpers import ConfigType

from .const import DOMAIN

@config_entries.HANDLERS.register(DOMAIN)
class AqualinkFlowHandler(config_entries.ConfigFlow):
    """Aqualink config flow."""

    VERSION = 1
    CONNECTION_CLASS = config_entries.CONN_CLASS_CLOUD_POLL

    async def async_step_user(self, user_input: Optional[ConfigType] = None):
        """Handle a flow start."""
        # Supporting a single account.
        entries = self.hass.config_entries.async_entries(DOMAIN)
        if entries:
            return self.async_abort(reason="already_setup")

        errors = {}

        if user_input is not None:
            username = user_input[CONF_USERNAME]
            password = user_input[CONF_PASSWORD]

            try:
                aqualink = AqualinkClient(username, password)
                await aqualink.login()
                return self.async_create_entry(title=username, data=user_input)
            except AqualinkLoginException:
                errors["base"] = "connection_failure"

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str}
            ),
            errors=errors,
        )

    async def async_step_import(self, user_input: Optional[ConfigType] = None):
        """Occurs when an entry is setup through config."""
        return await self.async_step_user(user_input)


text:
To work on the Liberty application cookbook first ensure you have [Bundler][] installed.

```bash
$ gem install bundler
```

Next, use [Bundler][] to install Liberty application cookbook dependencies:

```bash
$ bundle install
```

Finally, use [Rake][] to execute various tasks. For example:

```bash
$ rake all
```

[Bundler]: http://bundler.io/
[Rake]: http://rake.rubyforge.org/

# Testing

To check syntax of the cookbook files execute:

```bash
$ rake syntax
```

To run [Foodcritic][] (lint-like tool) on the cookbook execute:

```bash
$ rake foodcritic
```

To run [test-kitchen][] tests execute:

```bash
$ rake kitchen
```

In order to run the [test-kitchen][] tests you must first configure them. Please see [How to run 'test kitchen' tests](https://github.com/WASdev/ci.chef.wlp/wiki/How-to-run-%27test-kitchen%27-tests) for more information. The tests and cookbooks used by [test-kitchen][] are located in the **test/** directory.

[Foodcritic]: http://acrmp.github.io/foodcritic/
[test-kitchen]: https://github.com/opscode/test-kitchen


text:
package com.medievallords.carbyne.squads.commands;

import com.medievallords.carbyne.Carbyne;
import com.medievallords.carbyne.squads.Squad;
import com.medievallords.carbyne.utils.MessageManager;
import com.medievallords.carbyne.utils.StaticClasses;
import com.medievallords.carbyne.utils.command.BaseCommand;
import com.medievallords.carbyne.utils.command.Command;
import com.medievallords.carbyne.utils.command.CommandArgs;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;

import java.util.ArrayList;
import java.util.UUID;

/**
 * Created by Williams on 2017-03-13.
 * for the Carbyne project.
 */
public class SquadChatCommand extends BaseCommand implements Listener {

    private ArrayList<UUID> partyChatters = new ArrayList<>();

    public SquadChatCommand() {
        Bukkit.getPluginManager().registerEvents(this, Carbyne.getInstance());
    }

    @Command(name = "squad.chat", inGameOnly = true, aliases = {"squad.ch", "party.ch", "p.chat", "p.ch", "p.c", "s.chat", "s.ch"})
    public void execute(CommandArgs commandArgs) {
        String[] args = commandArgs.getArgs();
        Player player = commandArgs.getPlayer();
        Squad squad = StaticClasses.squadManager.getSquad(player.getUniqueId());

        if (squad == null) {
            MessageManager.sendMessage(player, "&cYou are not in a squad.");
            return;
        }

        if (args.length == 0) {
            if (!partyChatters.contains(player.getUniqueId())) {
                partyChatters.add(player.getUniqueId());

                MessageManager.sendMessage(player, "&aYou have entered the squad chat.");
            } else {
                partyChatters.remove(player.getUniqueId());

                MessageManager.sendMessage(player, "&aYou have left the squad chat.");
            }
        } else if (args.length > 0) {
            String message = StringUtils.join(args, ' ', 0, args.length);

            squad.sendAllMembersMessage(ChatColor.translateAlternateColorCodes('&', "&b" + player.getName() + ": ") + ChatColor.AQUA + message);
        }
    }

    @EventHandler
    public void onChat(AsyncPlayerChatEvent event) {
        if (partyChatters.contains(event.getPlayer().getUniqueId())) {
            Squad squad = StaticClasses.squadManager.getSquad(event.getPlayer().getUniqueId());

            if (squad == null) {
                partyChatters.remove(event.getPlayer().getUniqueId());
                return;
            }

            event.setCancelled(true);

            squad.sendAllMembersMessage(ChatColor.translateAlternateColorCodes('&', "&b" + event.getPlayer().getName() + ": ") + ChatColor.AQUA + event.getMessage());
        }
    }
}


text:
module Fog
  module Compute
    class Cloudstack

      class Real
        # Stops a virtual machine.
        #
        # {CloudStack API Reference}[http://cloudstack.apache.org/docs/api/apidocs-4.3/root_admin/stopVirtualMachine.html]
        def stop_virtual_machine(id, options={})
          options.merge!(
            'command' => 'stopVirtualMachine',
            'id' => id
          )
          request(options)
        end
      end

    end
  end
end


text:
int main(int, char **) {
	controld::ListenSocket listenSock(controld::Address::Any, controld::Port(1337));
	while(listenSock) {
		auto clientSock = listenSock.Accept();
		controld::Message message;
		clientSock >> message;
		std::cout << message << std::endl;
		clientSock << "set red LED intensity to " << std::to_string(message.red) << '\n';
		clientSock << "set green LED intensity to " << std::to_string(message.green) << '\n';
		clientSock << "set blue LED intensity to " << std::to_string(message.blue) << '\n';
		std::cerr << "TODO: set LED intensities" << std::endl;
	}
	return 0;
}


text:
package org.databene.commons.operation;

import org.databene.commons.Operation;

/**
 * Combines boolean arguments with an 'and' condition ignoring null arguments.
 * If the number of arguments is zero, true is returned.
 * Created: 05.03.2008 07:56:59
 * @since 0.4.0
 * @author Volker Bergmann
 */
public class AndOperation implements Operation<Boolean, Boolean> {

    @Override
	public Boolean perform(Boolean... args) {
        for (Boolean arg : args)
            if (arg != null && arg)
                return Boolean.TRUE;
        return Boolean.FALSE;
    }

}


text:
<?php

	require("../functions.php");

	require("../class/Helper.class.php");
	$Helper = new Helper();

	require("../class/Event.class.php");
	$Event = new Event($mysqli);

	if(isset($_GET["delete"])){
		$Event->deletePerson($_GET["id"]);
		header("Location: a_otsing.php");
		exit();
	}

	if(isset($_POST["update"])){

        var_dump($_POST);

        $id = $Helper->cleanInput($_POST["id"]);
        $name = $Helper->cleanInput($_POST["name"]);
		$type = $Helper->cleanInput($_POST["type"]);
		$county = $Helper->cleanInput($_POST["county"]);
		$city = $Helper->cleanInput($_POST["city"]);
        $parish = $Helper->cleanInput($_POST["parish"]);
		$address = $Helper->cleanInput($_POST["address"]);
		$postcode = $Helper->cleanInput($_POST["postcode"]);
		$webpage = $Helper->cleanInput($_POST["webpage"]);

		$Event->updatePerson($id, $name, $type, $county, $city, $parish, $address, $postcode, $webpage);

		header("Location: a_otsing.php?id=".$_POST["id"]."&success=true");
        exit();

	}

    if(isset($_POST["id"])){
        $p = $Event->getSinglePerosonData($_POST["id"]);
    }else{
	    $p = $Event->getSinglePerosonData($_GET["id"]);
    }

?>

<!DOCTYPE html>

		<meta charset="UTF-8">
		<title>Koolileht</title>
		<link href="../css/normalize.css" rel="stylesheet" type="text/css">
		<link href="../css/stiil.css" rel="stylesheet" type="text/css">

  <button class="buttons"> OTSING</button>
  <button class="buttons">LISAMINE</button>

      <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" >

KOOLI NIMI

          <input type="hidden" name="id" value="<?php echo $_GET['id'];?>"><input type="hidden" name="name" id="nameInput" value="<?php echo $p->name;?>">
<?php echo $p->name;?>

KOOLI TÜÜP

          <input type="hidden" name="type" id="typeInput" value="<?php echo $p->type;?>">
<?php echo $p->type;?>

MAAKOND

          <input type="hidden" name="county" id="countyInput" value="<?php echo $p->county;?>">
<?php echo $p->county;?>

VALD/LINN

          <input type="hidden" name="city" id="cityInput" value="<?php echo $p->city;?>">
<?php echo $p->city;?>

ALEVIK/LINNAOSA

          <input type="hidden" name="parish" id="parishInput" value="<?php echo $p->parish;?>">
<?php echo $p->parish;?>

ADDRESS

          <input type="hidden" name="address" id="addressInput" value="<?php echo $p->address;?>">
<?php echo $p->address;?>

POSTCODE

          <input type="hidden" name="postcode" id="postcodeInput" value="<?php echo $p->postcode;?>">
<?php echo $p->postcode;?>

WEBPAGE

          <input type="hidden" name="webpage" id="webpageInput" value="<?php echo $p->webpage;?>">
<?php echo $p->webpage;?>

      <input type="submit" name="update" value="Salvesta">

      </form>

<a href="?id=<?=$_GET["id"];?>&delete=true">kustuta


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: object_detection/protos/anchor_generator.proto

#ifndef PROTOBUF_object_5fdetection_2fprotos_2fanchor_5fgenerator_2eproto__INCLUDED
#define PROTOBUF_object_5fdetection_2fprotos_2fanchor_5fgenerator_2eproto__INCLUDED

#include <string>

#include <google/protobuf/stubs/common.h>

#if GOOGLE_PROTOBUF_VERSION < 3004000
#error This file was generated by a newer version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please update
#error your headers.
#endif
#if 3004000 < GOOGLE_PROTOBUF_MIN_PROTOC_VERSION
#error This file was generated by an older version of protoc which is
#error incompatible with your Protocol Buffer headers.  Please
#error regenerate this file with a newer version of protoc.
#endif

#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/arena.h>
#include <google/protobuf/arenastring.h>
#include <google/protobuf/generated_message_table_driven.h>
#include <google/protobuf/generated_message_util.h>
#include <google/protobuf/metadata.h>
#include <google/protobuf/message.h>
#include <google/protobuf/repeated_field.h>  // IWYU pragma: export
#include <google/protobuf/extension_set.h>  // IWYU pragma: export
#include <google/protobuf/unknown_field_set.h>
#include "object_detection/protos/flexible_grid_anchor_generator.pb.h"
#include "object_detection/protos/grid_anchor_generator.pb.h"
#include "object_detection/protos/multiscale_anchor_generator.pb.h"
#include "object_detection/protos/ssd_anchor_generator.pb.h"
// @@protoc_insertion_point(includes)
namespace object_detection {
namespace protos {
class AnchorGenerator;
class AnchorGeneratorDefaultTypeInternal;
extern AnchorGeneratorDefaultTypeInternal _AnchorGenerator_default_instance_;
}  // namespace protos
}  // namespace object_detection

namespace object_detection {
namespace protos {

namespace protobuf_object_5fdetection_2fprotos_2fanchor_5fgenerator_2eproto {
// Internal implementation detail -- do not call these.
struct TableStruct {
  static const ::google::protobuf::internal::ParseTableField entries[];
  static const ::google::protobuf::internal::AuxillaryParseTableField aux[];
  static const ::google::protobuf::internal::ParseTable schema[];
  static const ::google::protobuf::uint32 offsets[];
  static const ::google::protobuf::internal::FieldMetadata field_metadata[];
  static const ::google::protobuf::internal::SerializationTable serialization_table[];
  static void InitDefaultsImpl();
};
void AddDescriptors();
void InitDefaults();
}  // namespace protobuf_object_5fdetection_2fprotos_2fanchor_5fgenerator_2eproto

// ===================================================================

class AnchorGenerator : public ::google::protobuf::Message /* @@protoc_insertion_point(class_definition:object_detection.protos.AnchorGenerator) */ {
 public:
  AnchorGenerator();
  virtual ~AnchorGenerator();

  AnchorGenerator(const AnchorGenerator& from);

  inline AnchorGenerator& operator=(const AnchorGenerator& from) {
    CopyFrom(from);
    return *this;
  }
  #if LANG_CXX11
  AnchorGenerator(AnchorGenerator&& from) noexcept
    : AnchorGenerator() {
    *this = ::std::move(from);
  }

  inline AnchorGenerator& operator=(AnchorGenerator&& from) noexcept {
    if (GetArenaNoVirtual() == from.GetArenaNoVirtual()) {
      if (this != &from) InternalSwap(&from);
    } else {
      CopyFrom(from);
    }
    return *this;
  }
  #endif
  inline const ::google::protobuf::UnknownFieldSet& unknown_fields() const {
    return _internal_metadata_.unknown_fields();
  }
  inline ::google::protobuf::UnknownFieldSet* mutable_unknown_fields() {
    return _internal_metadata_.mutable_unknown_fields();
  }

  static const ::google::protobuf::Descriptor* descriptor();
  static const AnchorGenerator& default_instance();

  enum AnchorGeneratorOneofCase {
    kGridAnchorGenerator = 1,
    kSsdAnchorGenerator = 2,
    kMultiscaleAnchorGenerator = 3,
    kFlexibleGridAnchorGenerator = 4,
    ANCHOR_GENERATOR_ONEOF_NOT_SET = 0,
  };

  static inline const AnchorGenerator* internal_default_instance() {
    return reinterpret_cast<const AnchorGenerator*>(
               &_AnchorGenerator_default_instance_);
  }
  static PROTOBUF_CONSTEXPR int const kIndexInFileMessages =
    0;

  void Swap(AnchorGenerator* other);
  friend void swap(AnchorGenerator& a, AnchorGenerator& b) {
    a.Swap(&b);
  }

  // implements Message ----------------------------------------------

  inline AnchorGenerator* New() const PROTOBUF_FINAL { return New(NULL); }

  AnchorGenerator* New(::google::protobuf::Arena* arena) const PROTOBUF_FINAL;
  void CopyFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
  void MergeFrom(const ::google::protobuf::Message& from) PROTOBUF_FINAL;
  void CopyFrom(const AnchorGenerator& from);
  void MergeFrom(const AnchorGenerator& from);
  void Clear() PROTOBUF_FINAL;
  bool IsInitialized() const PROTOBUF_FINAL;

  size_t ByteSizeLong() const PROTOBUF_FINAL;
  bool MergePartialFromCodedStream(
      ::google::protobuf::io::CodedInputStream* input) PROTOBUF_FINAL;
  void SerializeWithCachedSizes(
      ::google::protobuf::io::CodedOutputStream* output) const PROTOBUF_FINAL;
  ::google::protobuf::uint8* InternalSerializeWithCachedSizesToArray(
      bool deterministic, ::google::protobuf::uint8* target) const PROTOBUF_FINAL;
  int GetCachedSize() const PROTOBUF_FINAL { return _cached_size_; }
  private:
  void SharedCtor();
  void SharedDtor();
  void SetCachedSize(int size) const PROTOBUF_FINAL;
  void InternalSwap(AnchorGenerator* other);
  private:
  inline ::google::protobuf::Arena* GetArenaNoVirtual() const {
    return NULL;
  }
  inline void* MaybeArenaPtr() const {
    return NULL;
  }
  public:

  ::google::protobuf::Metadata GetMetadata() const PROTOBUF_FINAL;

  // nested types ----------------------------------------------------

  // accessors -------------------------------------------------------

  // optional .object_detection.protos.GridAnchorGenerator grid_anchor_generator = 1;
  bool has_grid_anchor_generator() const;
  void clear_grid_anchor_generator();
  static const int kGridAnchorGeneratorFieldNumber = 1;
  const ::object_detection::protos::GridAnchorGenerator& grid_anchor_generator() const;
  ::object_detection::protos::GridAnchorGenerator* mutable_grid_anchor_generator();
  ::object_detection::protos::GridAnchorGenerator* release_grid_anchor_generator();
  void set_allocated_grid_anchor_generator(::object_detection::protos::GridAnchorGenerator* grid_anchor_generator);

  // optional .object_detection.protos.SsdAnchorGenerator ssd_anchor_generator = 2;
  bool has_ssd_anchor_generator() const;
  void clear_ssd_anchor_generator();
  static const int kSsdAnchorGeneratorFieldNumber = 2;
  const ::object_detection::protos::SsdAnchorGenerator& ssd_anchor_generator() const;
  ::object_detection::protos::SsdAnchorGenerator* mutable_ssd_anchor_generator();
  ::object_detection::protos::SsdAnchorGenerator* release_ssd_anchor_generator();
  void set_allocated_ssd_anchor_generator(::object_detection::protos::SsdAnchorGenerator* ssd_anchor_generator);

  // optional .object_detection.protos.MultiscaleAnchorGenerator multiscale_anchor_generator = 3;
  bool has_multiscale_anchor_generator() const;
  void clear_multiscale_anchor_generator();
  static const int kMultiscaleAnchorGeneratorFieldNumber = 3;
  const ::object_detection::protos::MultiscaleAnchorGenerator& multiscale_anchor_generator() const;
  ::object_detection::protos::MultiscaleAnchorGenerator* mutable_multiscale_anchor_generator();
  ::object_detection::protos::MultiscaleAnchorGenerator* release_multiscale_anchor_generator();
  void set_allocated_multiscale_anchor_generator(::object_detection::protos::MultiscaleAnchorGenerator* multiscale_anchor_generator);

  // optional .object_detection.protos.FlexibleGridAnchorGenerator flexible_grid_anchor_generator = 4;
  bool has_flexible_grid_anchor_generator() const;
  void clear_flexible_grid_anchor_generator();
  static const int kFlexibleGridAnchorGeneratorFieldNumber = 4;
  const ::object_detection::protos::FlexibleGridAnchorGenerator& flexible_grid_anchor_generator() const;
  ::object_detection::protos::FlexibleGridAnchorGenerator* mutable_flexible_grid_anchor_generator();
  ::object_detection::protos::FlexibleGridAnchorGenerator* release_flexible_grid_anchor_generator();
  void set_allocated_flexible_grid_anchor_generator(::object_detection::protos::FlexibleGridAnchorGenerator* flexible_grid_anchor_generator);

  AnchorGeneratorOneofCase anchor_generator_oneof_case() const;
  // @@protoc_insertion_point(class_scope:object_detection.protos.AnchorGenerator)
 private:
  void set_has_grid_anchor_generator();
  void set_has_ssd_anchor_generator();
  void set_has_multiscale_anchor_generator();
  void set_has_flexible_grid_anchor_generator();

  inline bool has_anchor_generator_oneof() const;
  void clear_anchor_generator_oneof();
  inline void clear_has_anchor_generator_oneof();

  ::google::protobuf::internal::InternalMetadataWithArena _internal_metadata_;
  ::google::protobuf::internal::HasBits<1> _has_bits_;
  mutable int _cached_size_;
  union AnchorGeneratorOneofUnion {
    AnchorGeneratorOneofUnion() {}
    ::object_detection::protos::GridAnchorGenerator* grid_anchor_generator_;
    ::object_detection::protos::SsdAnchorGenerator* ssd_anchor_generator_;
    ::object_detection::protos::MultiscaleAnchorGenerator* multiscale_anchor_generator_;
    ::object_detection::protos::FlexibleGridAnchorGenerator* flexible_grid_anchor_generator_;
  } anchor_generator_oneof_;
  ::google::protobuf::uint32 _oneof_case_[1];

  friend struct protobuf_object_5fdetection_2fprotos_2fanchor_5fgenerator_2eproto::TableStruct;
};
// ===================================================================

// ===================================================================

#if !PROTOBUF_INLINE_NOT_IN_HEADERS
#ifdef __GNUC__
  #pragma GCC diagnostic push
  #pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif  // __GNUC__
// AnchorGenerator

// optional .object_detection.protos.GridAnchorGenerator grid_anchor_generator = 1;
inline bool AnchorGenerator::has_grid_anchor_generator() const {
  return anchor_generator_oneof_case() == kGridAnchorGenerator;
}
inline void AnchorGenerator::set_has_grid_anchor_generator() {
  _oneof_case_[0] = kGridAnchorGenerator;
}
inline void AnchorGenerator::clear_grid_anchor_generator() {
  if (has_grid_anchor_generator()) {
    delete anchor_generator_oneof_.grid_anchor_generator_;
    clear_has_anchor_generator_oneof();
  }
}
inline  const ::object_detection::protos::GridAnchorGenerator& AnchorGenerator::grid_anchor_generator() const {
  // @@protoc_insertion_point(field_get:object_detection.protos.AnchorGenerator.grid_anchor_generator)
  return has_grid_anchor_generator()
      ? *anchor_generator_oneof_.grid_anchor_generator_
      : ::object_detection::protos::GridAnchorGenerator::default_instance();
}
inline ::object_detection::protos::GridAnchorGenerator* AnchorGenerator::mutable_grid_anchor_generator() {
  if (!has_grid_anchor_generator()) {
    clear_anchor_generator_oneof();
    set_has_grid_anchor_generator();
    anchor_generator_oneof_.grid_anchor_generator_ = new ::object_detection::protos::GridAnchorGenerator;
  }
  // @@protoc_insertion_point(field_mutable:object_detection.protos.AnchorGenerator.grid_anchor_generator)
  return anchor_generator_oneof_.grid_anchor_generator_;
}
inline ::object_detection::protos::GridAnchorGenerator* AnchorGenerator::release_grid_anchor_generator() {
  // @@protoc_insertion_point(field_release:object_detection.protos.AnchorGenerator.grid_anchor_generator)
  if (has_grid_anchor_generator()) {
    clear_has_anchor_generator_oneof();
    ::object_detection::protos::GridAnchorGenerator* temp = anchor_generator_oneof_.grid_anchor_generator_;
    anchor_generator_oneof_.grid_anchor_generator_ = NULL;
    return temp;
  } else {
    return NULL;
  }
}
inline void AnchorGenerator::set_allocated_grid_anchor_generator(::object_detection::protos::GridAnchorGenerator* grid_anchor_generator) {
  clear_anchor_generator_oneof();
  if (grid_anchor_generator) {
    set_has_grid_anchor_generator();
    anchor_generator_oneof_.grid_anchor_generator_ = grid_anchor_generator;
  }
  // @@protoc_insertion_point(field_set_allocated:object_detection.protos.AnchorGenerator.grid_anchor_generator)
}

// optional .object_detection.protos.SsdAnchorGenerator ssd_anchor_generator = 2;
inline bool AnchorGenerator::has_ssd_anchor_generator() const {
  return anchor_generator_oneof_case() == kSsdAnchorGenerator;
}
inline void AnchorGenerator::set_has_ssd_anchor_generator() {
  _oneof_case_[0] = kSsdAnchorGenerator;
}
inline void AnchorGenerator::clear_ssd_anchor_generator() {
  if (has_ssd_anchor_generator()) {
    delete anchor_generator_oneof_.ssd_anchor_generator_;
    clear_has_anchor_generator_oneof();
  }
}
inline  const ::object_detection::protos::SsdAnchorGenerator& AnchorGenerator::ssd_anchor_generator() const {
  // @@protoc_insertion_point(field_get:object_detection.protos.AnchorGenerator.ssd_anchor_generator)
  return has_ssd_anchor_generator()
      ? *anchor_generator_oneof_.ssd_anchor_generator_
      : ::object_detection::protos::SsdAnchorGenerator::default_instance();
}
inline ::object_detection::protos::SsdAnchorGenerator* AnchorGenerator::mutable_ssd_anchor_generator() {
  if (!has_ssd_anchor_generator()) {
    clear_anchor_generator_oneof();
    set_has_ssd_anchor_generator();
    anchor_generator_oneof_.ssd_anchor_generator_ = new ::object_detection::protos::SsdAnchorGenerator;
  }
  // @@protoc_insertion_point(field_mutable:object_detection.protos.AnchorGenerator.ssd_anchor_generator)
  return anchor_generator_oneof_.ssd_anchor_generator_;
}
inline ::object_detection::protos::SsdAnchorGenerator* AnchorGenerator::release_ssd_anchor_generator() {
  // @@protoc_insertion_point(field_release:object_detection.protos.AnchorGenerator.ssd_anchor_generator)
  if (has_ssd_anchor_generator()) {
    clear_has_anchor_generator_oneof();
    ::object_detection::protos::SsdAnchorGenerator* temp = anchor_generator_oneof_.ssd_anchor_generator_;
    anchor_generator_oneof_.ssd_anchor_generator_ = NULL;
    return temp;
  } else {
    return NULL;
  }
}
inline void AnchorGenerator::set_allocated_ssd_anchor_generator(::object_detection::protos::SsdAnchorGenerator* ssd_anchor_generator) {
  clear_anchor_generator_oneof();
  if (ssd_anchor_generator) {
    set_has_ssd_anchor_generator();
    anchor_generator_oneof_.ssd_anchor_generator_ = ssd_anchor_generator;
  }
  // @@protoc_insertion_point(field_set_allocated:object_detection.protos.AnchorGenerator.ssd_anchor_generator)
}

// optional .object_detection.protos.MultiscaleAnchorGenerator multiscale_anchor_generator = 3;
inline bool AnchorGenerator::has_multiscale_anchor_generator() const {
  return anchor_generator_oneof_case() == kMultiscaleAnchorGenerator;
}
inline void AnchorGenerator::set_has_multiscale_anchor_generator() {
  _oneof_case_[0] = kMultiscaleAnchorGenerator;
}
inline void AnchorGenerator::clear_multiscale_anchor_generator() {
  if (has_multiscale_anchor_generator()) {
    delete anchor_generator_oneof_.multiscale_anchor_generator_;
    clear_has_anchor_generator_oneof();
  }
}
inline  const ::object_detection::protos::MultiscaleAnchorGenerator& AnchorGenerator::multiscale_anchor_generator() const {
  // @@protoc_insertion_point(field_get:object_detection.protos.AnchorGenerator.multiscale_anchor_generator)
  return has_multiscale_anchor_generator()
      ? *anchor_generator_oneof_.multiscale_anchor_generator_
      : ::object_detection::protos::MultiscaleAnchorGenerator::default_instance();
}
inline ::object_detection::protos::MultiscaleAnchorGenerator* AnchorGenerator::mutable_multiscale_anchor_generator() {
  if (!has_multiscale_anchor_generator()) {
    clear_anchor_generator_oneof();
    set_has_multiscale_anchor_generator();
    anchor_generator_oneof_.multiscale_anchor_generator_ = new ::object_detection::protos::MultiscaleAnchorGenerator;
  }
  // @@protoc_insertion_point(field_mutable:object_detection.protos.AnchorGenerator.multiscale_anchor_generator)
  return anchor_generator_oneof_.multiscale_anchor_generator_;
}
inline ::object_detection::protos::MultiscaleAnchorGenerator* AnchorGenerator::release_multiscale_anchor_generator() {
  // @@protoc_insertion_point(field_release:object_detection.protos.AnchorGenerator.multiscale_anchor_generator)
  if (has_multiscale_anchor_generator()) {
    clear_has_anchor_generator_oneof();
    ::object_detection::protos::MultiscaleAnchorGenerator* temp = anchor_generator_oneof_.multiscale_anchor_generator_;
    anchor_generator_oneof_.multiscale_anchor_generator_ = NULL;
    return temp;
  } else {
    return NULL;
  }
}
inline void AnchorGenerator::set_allocated_multiscale_anchor_generator(::object_detection::protos::MultiscaleAnchorGenerator* multiscale_anchor_generator) {
  clear_anchor_generator_oneof();
  if (multiscale_anchor_generator) {
    set_has_multiscale_anchor_generator();
    anchor_generator_oneof_.multiscale_anchor_generator_ = multiscale_anchor_generator;
  }
  // @@protoc_insertion_point(field_set_allocated:object_detection.protos.AnchorGenerator.multiscale_anchor_generator)
}

// optional .object_detection.protos.FlexibleGridAnchorGenerator flexible_grid_anchor_generator = 4;
inline bool AnchorGenerator::has_flexible_grid_anchor_generator() const {
  return anchor_generator_oneof_case() == kFlexibleGridAnchorGenerator;
}
inline void AnchorGenerator::set_has_flexible_grid_anchor_generator() {
  _oneof_case_[0] = kFlexibleGridAnchorGenerator;
}
inline void AnchorGenerator::clear_flexible_grid_anchor_generator() {
  if (has_flexible_grid_anchor_generator()) {
    delete anchor_generator_oneof_.flexible_grid_anchor_generator_;
    clear_has_anchor_generator_oneof();
  }
}
inline  const ::object_detection::protos::FlexibleGridAnchorGenerator& AnchorGenerator::flexible_grid_anchor_generator() const {
  // @@protoc_insertion_point(field_get:object_detection.protos.AnchorGenerator.flexible_grid_anchor_generator)
  return has_flexible_grid_anchor_generator()
      ? *anchor_generator_oneof_.flexible_grid_anchor_generator_
      : ::object_detection::protos::FlexibleGridAnchorGenerator::default_instance();
}
inline ::object_detection::protos::FlexibleGridAnchorGenerator* AnchorGenerator::mutable_flexible_grid_anchor_generator() {
  if (!has_flexible_grid_anchor_generator()) {
    clear_anchor_generator_oneof();
    set_has_flexible_grid_anchor_generator();
    anchor_generator_oneof_.flexible_grid_anchor_generator_ = new ::object_detection::protos::FlexibleGridAnchorGenerator;
  }
  // @@protoc_insertion_point(field_mutable:object_detection.protos.AnchorGenerator.flexible_grid_anchor_generator)
  return anchor_generator_oneof_.flexible_grid_anchor_generator_;
}
inline ::object_detection::protos::FlexibleGridAnchorGenerator* AnchorGenerator::release_flexible_grid_anchor_generator() {
  // @@protoc_insertion_point(field_release:object_detection.protos.AnchorGenerator.flexible_grid_anchor_generator)
  if (has_flexible_grid_anchor_generator()) {
    clear_has_anchor_generator_oneof();
    ::object_detection::protos::FlexibleGridAnchorGenerator* temp = anchor_generator_oneof_.flexible_grid_anchor_generator_;
    anchor_generator_oneof_.flexible_grid_anchor_generator_ = NULL;
    return temp;
  } else {
    return NULL;
  }
}
inline void AnchorGenerator::set_allocated_flexible_grid_anchor_generator(::object_detection::protos::FlexibleGridAnchorGenerator* flexible_grid_anchor_generator) {
  clear_anchor_generator_oneof();
  if (flexible_grid_anchor_generator) {
    set_has_flexible_grid_anchor_generator();
    anchor_generator_oneof_.flexible_grid_anchor_generator_ = flexible_grid_anchor_generator;
  }
  // @@protoc_insertion_point(field_set_allocated:object_detection.protos.AnchorGenerator.flexible_grid_anchor_generator)
}

inline bool AnchorGenerator::has_anchor_generator_oneof() const {
  return anchor_generator_oneof_case() != ANCHOR_GENERATOR_ONEOF_NOT_SET;
}
inline void AnchorGenerator::clear_has_anchor_generator_oneof() {
  _oneof_case_[0] = ANCHOR_GENERATOR_ONEOF_NOT_SET;
}
inline AnchorGenerator::AnchorGeneratorOneofCase AnchorGenerator::anchor_generator_oneof_case() const {
  return AnchorGenerator::AnchorGeneratorOneofCase(_oneof_case_[0]);
}
#ifdef __GNUC__
  #pragma GCC diagnostic pop
#endif  // __GNUC__
#endif  // !PROTOBUF_INLINE_NOT_IN_HEADERS

// @@protoc_insertion_point(namespace_scope)

}  // namespace protos
}  // namespace object_detection

// @@protoc_insertion_point(global_scope)

#endif  // PROTOBUF_object_5fdetection_2fprotos_2fanchor_5fgenerator_2eproto__INCLUDED


text:
import httplib
try:
    import simplejson as json
except ImportError:
    import json
import os
import sys
from urlparse import urljoin

try:
    import requests
except ImportError:
    raise ImportError('Missing dependency "requests". Do ``pip install requests``.')

try:
    import yaml
except ImportError:
    raise ImportError('Missing dependency "pyyaml". Do ``pip install pyyaml``.')

# ST2 configuration

ST2_API_BASE_URL = 'http://localhost:9101/v1'
ST2_AUTH_BASE_URL = 'http://localhost:9100'
ST2_USERNAME = None
ST2_PASSWORD = None
ST2_AUTH_TOKEN = None

ST2_AUTH_PATH = 'tokens'
ST2_WEBHOOKS_PATH = 'webhooks/st2/'
ST2_TRIGGERS_PATH = 'triggertypes/'
ST2_TRIGGERTYPE_PACK = 'sensu'
ST2_TRIGGERTYPE_NAME = 'event_handler'
ST2_TRIGGERTYPE_REF = '.'.join([ST2_TRIGGERTYPE_PACK, ST2_TRIGGERTYPE_NAME])

REGISTERED_WITH_ST2 = False

OK_CODES = [httplib.OK, httplib.CREATED, httplib.ACCEPTED, httplib.CONFLICT]

def _create_trigger_type():
    try:
        url = _get_st2_triggers_url()
        payload = {
            'name': ST2_TRIGGERTYPE_NAME,
            'pack': ST2_TRIGGERTYPE_PACK,
            'description': 'Trigger type for sensu event handler.'
        }
        # sys.stdout.write('POST: %s: Body: %s\n' % (url, payload))
        headers = {}
        headers['Content-Type'] = 'application/json; charset=utf-8'

        if ST2_AUTH_TOKEN:
            headers['X-Auth-Token'] = ST2_AUTH_TOKEN

        post_resp = requests.post(url, data=json.dumps(payload), headers=headers)
    except:
        sys.stderr.write('Unable to register trigger type with st2.')
        raise
    else:
        status = post_resp.status_code
        if status not in OK_CODES:
            sys.stderr.write('Failed to register trigger type with st2. HTTP_CODE: %d\n' %
                             status)
            raise
        else:
            sys.stdout.write('Registered trigger type with st2.\n')

def _get_auth_url():
    return urljoin(ST2_AUTH_BASE_URL, ST2_AUTH_PATH)

def _get_auth_token():
    global ST2_AUTH_TOKEN
    auth_url = _get_auth_url()
    try:
        resp = requests.post(auth_url, json.dumps({'ttl': 5 * 60}),
                             auth=(ST2_USERNAME, ST2_PASSWORD))
    except:
        sys.stderr.write('Cannot get auth token from st2. Trying unauthed.')
    else:
        if resp.status_code not in OK_CODES:
            raise Exception("Cannot authenticate: %s\n" % resp.text)

        ST2_AUTH_TOKEN = resp.json()['token']

def _register_with_st2():
    global REGISTERED_WITH_ST2
    try:
        url = urljoin(_get_st2_triggers_url(), ST2_TRIGGERTYPE_REF)
        # sys.stdout.write('GET: %s\n' % url)
        if not ST2_AUTH_TOKEN:
            _get_auth_token()

        if ST2_AUTH_TOKEN:
            get_resp = requests.get(url, headers={'X-Auth-Token': ST2_AUTH_TOKEN})
        else:
            get_resp = requests.get(url)

        if get_resp.status_code != httplib.OK:
            _create_trigger_type()
        else:
            body = json.loads(get_resp.text)
            if len(body) == 0:
                _create_trigger_type()
    except:
        raise
    else:
        REGISTERED_WITH_ST2 = True

def _get_st2_triggers_url():
    url = urljoin(ST2_API_BASE_URL, ST2_TRIGGERS_PATH)
    return url

def _get_st2_webhooks_url():
    url = urljoin(ST2_API_BASE_URL, ST2_WEBHOOKS_PATH)
    return url

def _post_event_to_st2(url, body):
    headers = {}
    headers['X-ST2-Integration'] = 'sensu.'
    headers['Content-Type'] = 'application/json; charset=utf-8'
    if ST2_AUTH_TOKEN:
        headers['X-Auth-Token'] = ST2_AUTH_TOKEN
    try:
        sys.stdout.write('POST: url: %s, body: %s\n' % (url, body))
        r = requests.post(url, data=json.dumps(body), headers=headers)
    except:
        sys.stderr.write('Cannot connect to st2 endpoint.')
    else:
        status = r.status_code
        if status not in OK_CODES:
            sys.stderr.write('Failed posting sensu event to st2. HTTP_CODE: %d\n' % status)
        else:
            sys.stdout.write('Sent sensu event to st2. HTTP_CODE: %d\n' % status)

def main(args):
    body = {}
    body['trigger'] = ST2_TRIGGERTYPE_REF
    body['payload'] = json.loads(sys.stdin.read().strip())
    _post_event_to_st2(_get_st2_webhooks_url(), body)

if __name__ == '__main__':
    if len(sys.argv) > 1:
        st2_config_file = sys.argv[1]
    else:
        sys.stderr.write('Error: config file missing.\n')
        sys.stderr.write('Usage: %s ST2_CONFIG_FILE\n' % sys.argv[0])
        sys.exit(2)

    try:
        if not os.path.exists(st2_config_file):
            sys.stderr.write('Configuration file not found. Exiting.\n')
            sys.exit(1)

        with open(st2_config_file) as f:
            config = yaml.safe_load(f)
            ST2_USERNAME = config['st2_username']
            ST2_PASSWORD = config['st2_password']
            ST2_API_BASE_URL = config['st2_api_base_url']
            ST2_AUTH_BASE_URL = config['st2_auth_base_url']

        if not REGISTERED_WITH_ST2:
            _register_with_st2()
    except Exception as e:
        sys.stderr.write(
            'Failed registering with st2. Won\'t post event.\n%s' % e)
        import traceback
        traceback.print_exc()
    else:
        main(sys.argv)


text:
package com.redhat.approval.value;

public enum RequestStatus {

	CREATED,PENDING_REVIEW,NEED_MORE_INFO,APPROVED,DENIED;

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2013 Aaron Knauf
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<ivy-module version="2.3"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd"
            xmlns:m="http://ant.apache.org/ivy/maven"
        >
    <info organisation="com.github.unlog" module="unlog" revision="0.1">
        <license name="The Apache Software License, Version 2.0" url="http://www.apache.org/licenses/LICENSE-2.0.txt"/>
        <description homepage="https://github.com/unlog/unlog">UnLog - An (almost) invisible logging framework.
        </description>
    </info>

    <configurations defaultconf="default">
        <conf name="default"/>
        <conf name="test"/>
        <conf name="sources"/>
    </configurations>

    <publications>
        <artifact type="pom" ext="pom" conf="default"/>
        <artifact type="jar" ext="jar" conf="default"/>
        <artifact type="javadoc" ext="jar" conf="default" m:classifier="javadoc"/>
        <artifact type="source" ext="jar" conf="sources" m:classifier="sources"/>
    </publications>

    <dependencies>
        <dependency org="junit" name="junit" rev="4.11" conf="test->*"/>
        <dependency org="org.jmock" name="jmock-junit4" rev="2.6.0" conf="test->*"/>
    </dependencies>

</ivy-module>


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('blog', '0030_auto_20170517_1959'),
    ]

    operations = [
        migrations.AlterField(
            model_name='post',
            name='restaurant_card',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='posts', to='cards.Restaurant', verbose_name='Ficha de restaurante'),
        ),
    ]


text:
package org.eclipse.jetty.websocket.jsr356.server.samples.idletimeout;

import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.MessageHandler;
import javax.websocket.Session;

public class OnOpenIdleTimeoutEndpoint extends Endpoint implements MessageHandler.Whole<String>
{
    private Session session;

    @Override
    public void onOpen(Session session, EndpointConfig config)
    {
        this.session = session;
        session.addMessageHandler(this);
        session.setMaxIdleTimeout(500);
    }

    @Override
    public void onMessage(String message)
    {
        // echo message back (this is an indication of timeout failure)
        session.getAsyncRemote().sendText(message);
    }
}