text:
require 'rails_helper'

describe SortableEvents do
  let(:agent_class) {
    Class.new(Agent) do
      include SortableEvents

      default_schedule 'never'

      def self.valid_type?(name)
        true
      end
    end
  }

  def new_agent(events_order = nil)
    options = {}
    options['events_order'] = events_order if events_order
    agent_class.new(name: 'test', options: options) { |agent|
      agent.user = users(:bob)
    }
  end

  describe 'validations' do
    let(:agent_class) {
      Class.new(Agent) do
        include SortableEvents

        default_schedule 'never'

        def self.valid_type?(name)
          true
        end
      end
    }

    def new_agent(events_order = nil)
      options = {}
      options['events_order'] = events_order if events_order
      agent_class.new(name: 'test', options: options) { |agent|
        agent.user = users(:bob)
      }
    end

    it 'should allow events_order to be unspecified, null or an empty array' do
      expect(new_agent()).to be_valid
      expect(new_agent(nil)).to be_valid
      expect(new_agent([])).to be_valid
    end

    it 'should not allow events_order to be a non-array object' do
      agent = new_agent(0)
      expect(agent).not_to be_valid
      expect(agent.errors[:base]).to include(/events_order/)

      agent = new_agent('')
      expect(agent).not_to be_valid
      expect(agent.errors[:base]).to include(/events_order/)

      agent = new_agent({})
      expect(agent).not_to be_valid
      expect(agent.errors[:base]).to include(/events_order/)
    end

    it 'should not allow events_order to be an array containing unexpected objects' do
      agent = new_agent(['{{key}}', 1])
      expect(agent).not_to be_valid
      expect(agent.errors[:base]).to include(/events_order/)

      agent = new_agent(['{{key1}}', ['{{key2}}', 'unknown']])
      expect(agent).not_to be_valid
      expect(agent.errors[:base]).to include(/events_order/)
    end

    it 'should allow events_order to be an array containing strings and valid tuples' do
      agent = new_agent(['{{key1}}', ['{{key2}}'], ['{{key3}}', 'number']])
      expect(agent).to be_valid

      agent = new_agent(['{{key1}}', ['{{key2}}'], ['{{key3}}', 'number'], ['{{key4}}', 'time', true]])
      expect(agent).to be_valid
    end
  end

  describe 'sort_events' do
    let(:payloads) {
      [
        { 'title' => 'TitleA', 'score' => 4,  'updated_on' => '7 Jul 2015' },
        { 'title' => 'TitleB', 'score' => 2,  'updated_on' => '25 Jun 2014' },
        { 'title' => 'TitleD', 'score' => 10, 'updated_on' => '10 Jan 2015' },
        { 'title' => 'TitleC', 'score' => 10, 'updated_on' => '9 Feb 2015' },
      ]
    }

    let(:events) {
      payloads.map { |payload| Event.new(payload: payload) }
    }

    it 'should sort events by a given key' do
      agent = new_agent(['{{title}}'])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleA TitleB TitleC TitleD])

      agent = new_agent([['{{title}}', 'string', true]])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleD TitleC TitleB TitleA])
    end

    it 'should sort events by multiple keys' do
      agent = new_agent([['{{score}}', 'number'], '{{title}}'])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleB TitleA TitleC TitleD])

      agent = new_agent([['{{score}}', 'number'], ['{{title}}', 'string', true]])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleB TitleA TitleD TitleC])
    end

    it 'should sort events by time' do
      agent = new_agent([['{{updated_on}}', 'time']])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleB TitleD TitleC TitleA])
    end

    it 'should sort events stably' do
      agent = new_agent(['<constant>'])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC])

      agent = new_agent([['<constant>', 'string', true]])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC])
    end

    it 'should support _index_' do
      agent = new_agent([['{{_index_}}', 'number', true]])
      expect(agent.__send__(:sort_events, events).map { |e| e.payload['title'] }).to eq(%w[TitleC TitleD TitleB TitleA])
    end
  end

  describe 'automatic event sorter' do
    describe 'declaration' do
      let(:passive_agent_class) {
        Class.new(Agent) do
          include SortableEvents

          cannot_create_events!
        end
      }

      let(:active_agent_class) {
        Class.new(Agent) do
          include SortableEvents
        end
      }

      describe 'can_order_created_events!' do
        it 'should refuse to work if called from an Agent that cannot create events' do
          expect {
            passive_agent_class.class_eval do
              can_order_created_events!
            end
          }.to raise_error('Cannot order events for agent that cannot create events')
        end

        it 'should work if called from an Agent that can create events' do
          expect {
            active_agent_class.class_eval do
              can_order_created_events!
            end
          }.not_to raise_error()
        end
      end

      describe 'can_order_created_events?' do
        it 'should return false unless an Agent declares can_order_created_events!' do
          expect(active_agent_class.can_order_created_events?).to eq(false)
          expect(active_agent_class.new.can_order_created_events?).to eq(false)
        end

        it 'should return true if an Agent declares can_order_created_events!' do
          active_agent_class.class_eval do
            can_order_created_events!
          end

          expect(active_agent_class.can_order_created_events?).to eq(true)
          expect(active_agent_class.new.can_order_created_events?).to eq(true)
        end
      end
    end

    describe 'behavior' do
      class Agents::EventOrderableAgent < Agent
        include SortableEvents

        default_schedule 'never'

        can_order_created_events!

        attr_accessor :payloads_to_emit

        def self.valid_type?(name)
          true
        end

        def check
          payloads_to_emit.each do |payload|
            create_event payload: payload
          end
        end

        def receive(events)
          events.each do |event|
            payloads_to_emit.each do |payload|
              create_event payload: payload.merge('title' => payload['title'] + event.payload['title_suffix'])
            end
          end
        end
      end

      let :new_agent do
        options = {}
        options['events_order'] = @events_order
        Agents::EventOrderableAgent.new(name: 'test', options: options) { |agent|
          agent.user = users(:bob)
          agent.payloads_to_emit = payloads
        }
      end

      let(:payloads) {
        [
          { 'title' => 'TitleA', 'score' => 4,  'updated_on' => '7 Jul 2015' },
          { 'title' => 'TitleB', 'score' => 2,  'updated_on' => '25 Jun 2014' },
          { 'title' => 'TitleD', 'score' => 10, 'updated_on' => '10 Jan 2015' },
          { 'title' => 'TitleC', 'score' => 10, 'updated_on' => '9 Feb 2015' },
        ]
      }

      it 'should keep the order of created events unless events_order is specified' do
        [nil, []].each do |events_order|
          @events_order = events_order
          agent = new_agent
          agent.save!
          expect { agent.check }.to change { Event.count }.by(4)
          events = agent.events.last(4).sort_by(&:id)
          expect(events.map(&:payload)).to match_array(payloads)
          expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC])
        end
      end

      it 'should sort events created in check() in the order specified in events_order' do
        @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]]
        agent = new_agent
        agent.save!
        expect { agent.check }.to change { Event.count }.by(4)
        events = agent.events.last(4).sort_by(&:id)
        expect(events.map(&:payload)).to match_array(payloads)
        expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleB TitleA TitleD TitleC])
      end

      it 'should sort events created in receive() in the order specified in events_order' do
        @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]]
        agent = new_agent
        agent.save!
        expect {
          agent.receive([Event.new(payload: { 'title_suffix' => ' [new]' }),
                         Event.new(payload: { 'title_suffix' => ' [popular]' })])
        }.to change { Event.count }.by(8)
        events = agent.events.last(8).sort_by(&:id)
        expect(events.map { |event| event.payload['title'] }).to eq([
          'TitleB [new]',     'TitleA [new]',     'TitleD [new]',     'TitleC [new]',
          'TitleB [popular]', 'TitleA [popular]', 'TitleD [popular]', 'TitleC [popular]',
        ])
      end

      describe 'with the include_sort_info option enabled' do
        let :new_agent do
          agent = super()
          agent.options['include_sort_info'] = true
          agent
        end

        it 'should add sort_info to events created in check() when events_order is not specified' do
          agent = new_agent
          agent.save!
          expect { agent.check }.to change { Event.count }.by(4)
          events = agent.events.last(4).sort_by(&:id)
          expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleA TitleB TitleD TitleC])
          expect(events.map { |event| event.payload['sort_info'] }).to eq((1..4).map{ |pos| { 'position' => pos, 'count' => 4 } })
        end

        it 'should add sort_info to events created in check() when events_order is specified' do
          @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]]
          agent = new_agent
          agent.save!
          expect { agent.check }.to change { Event.count }.by(4)
          events = agent.events.last(4).sort_by(&:id)
          expect(events.map { |event| event.payload['title'] }).to eq(%w[TitleB TitleA TitleD TitleC])
          expect(events.map { |event| event.payload['sort_info'] }).to eq((1..4).map{ |pos| { 'position' => pos, 'count' => 4 } })
        end

        it 'should add sort_info to events created in receive() when events_order is specified' do
          @events_order = [['{{score}}', 'number'], ['{{title}}', 'string', true]]
          agent = new_agent
          agent.save!
          expect {
            agent.receive([Event.new(payload: { 'title_suffix' => ' [new]' }),
                           Event.new(payload: { 'title_suffix' => ' [popular]' })])
          }.to change { Event.count }.by(8)
          events = agent.events.last(8).sort_by(&:id)
          expect(events.map { |event| event.payload['title'] }).to eq([
            'TitleB [new]',     'TitleA [new]',     'TitleD [new]',     'TitleC [new]',
            'TitleB [popular]', 'TitleA [popular]', 'TitleD [popular]', 'TitleC [popular]',
          ])
          expect(events.map { |event| event.payload['sort_info'] }).to eq((1..4).map{ |pos| { 'position' => pos, 'count' => 4 } } * 2)
        end
      end
    end
  end
end


text:
//
//  BMOverlayImageView.h
//  BMCommons
//
//  Created by Werner Altewischer on 6/21/10.
//  Copyright 2010 BehindMedia. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <BMCommons/BMAnimatedImageView.h>

/**
 Image view with support for an overlay view.
 */
@interface BMOverlayImageView : BMAnimatedImageView

@property (nonatomic, strong) UIView *overlayView;

- (void)setImage:(UIImage *)theImage withOverlayView:(UIView *)theOverlayView;

@end

redpajama_set_name: RedPajamaGithub


text:
[![Packagist](https://img.shields.io/packagist/v/gr8shivam/laravel-sms-api.svg)](https://packagist.org/packages/gr8shivam/laravel-sms-api) [![Packagist](https://img.shields.io/packagist/dt/gr8shivam/laravel-sms-api.svg)](https://packagist.org/packages/gr8shivam/laravel-sms-api) [![GitHub license](https://img.shields.io/badge/license-MIT-blue.svg)](https://raw.githubusercontent.com/gr8shivam/laravel-sms-api/master/LICENSE)

# Integrate SMS API with Laravel
Laravel package to provide SMS API integration. Any SMS vendor that provides REST API can be used.

#### [Star ⭐](https://github.com/gr8shivam/laravel-sms-api) repo to show suport 😊

## Installation

### Install Package
Require this package with composer:
```
composer require gr8shivam/laravel-sms-api
```
### Add Service Provider & Facade

#### For Laravel 5.5+
Once the package is added, the service provider and facade will be autodiscovered.

#### For Older versions of Laravel
Add the ServiceProvider to the providers array in `config/app.php`:
```
Gr8Shivam\SmsApi\SmsApiServiceProvider::class,
```

Add the Facade to the aliases array in `config/app.php`:
```
'SmsApi': Gr8Shivam\SmsApi\SmsApiFacade::class,
```

### Publish Config
Once done, publish the config to your config folder using:
```
php artisan vendor:publish --provider="Gr8Shivam\SmsApi\SmsApiServiceProvider"
```

## Configuration
Once the config file is published, open `config/sms-api.php`

#### Global config
`country_code` : The default country code to be used

`default` : Default gateway

#### Gateway Config
Use can define multiple gateway configs like this:-
```
//    Gateway Configuration
    'gateway_name' => [
        'method' => 'GET', //Choose Request Method (GET/POST) Default:GET
        'url' => 'BaseUrl', //Base URL
        'params' => [
            'send_to_param_name' => '', //Send to Parameter Name
            'msg_param_name' => '', //Message Parameter Name
            'others' => [
                'param1' => '',
                'param2' => '',
                'param3' => '',
                //More params can be added
            ],
        ],
        'headers' => [
            'header1' => '',
            'header2' => '',
            //More headers can be added
        ],
//        'json' => true, // OPTIONAL: Use if you want the params to be sent in JSON format instead of query params (accepts true/false)
//        'wrapper' => 'wrapper_name', // OPTIONAL: Use only if you want the JSON request to be wrapped (accepts string)
        'add_code' => true, //Include Country Code (true/false)
    ],
```

#### Special Parameters in Gateway Config

##### `json` Parameter
The `json` parameter accepts `true/false`. When `true`, it sends `params` as a JSON payload. It also takes care of `'Content-Type' => 'application/json'` header.

##### `jsonToArray` Parameter
The `jsonToArray` parameter accepts `true/false`. When `true`, it sends a single mobile number in an encapsulated array in the JSON payload. When `false`, a single mobile number is sent as text. Valid only when `json` parameter is `true`.

##### `wrapper` Parameter
The `wrapper` is a special parameter which will be required only with some gateways. It wraps the JSON payload in the following structure:
```
"wrapper_name": [
    {
      "message": "Message",
      "to": [
        "Receipient1",
        "Receipient2"
      ]
    }
  ]
```

##### `wrapperParams` Parameter
Accepts array. Used to add custom Wrapper Parameters. Parameters can also be added while calling the `smsapi()` function like `smsapi()->addWrapperParams(['wrapperParam1'=>'paramVal'])->sendMessage("TO", "Message")`

## Usage
### Direct Use
Use the `smsapi()` helper function or `SmsApi` facade to send the messages.

`TO`: Single mobile number or Multiple comma-separated mobile numbers

`MESSAGE`: Message to be sent

#### Using Helper function
- Basic Usage `smsapi("TO", "Message");` or `smsapi()->sendMessage("TO","MESSAGE");`

- Adding extra parameters `smsapi("TO", "Message", ["param1" => "val"]);` or `smsapi()->sendMessage("TO", "Message", ["param1" => "val"]);`

- Adding extra headers `smsapi("TO", "Message", ["param1" => "val"], ["header1" => "val"]);` or `smsapi()->sendMessage("TO", "Message", ["param1" => "val"], ["header1" => "val"]);`

- Using a different gateway `smsapi()->gateway('GATEWAY_NAME')->sendMessage("TO", "Message");`

- Using a different country code `smsapi()->countryCode('COUNTRY_CODE')->sendMessage("TO", "Message");`

- Sending message to multiple mobiles `smsapi(["Mobile1","Mobile2","Mobile3"], "Message");` or `smsapi()->sendMessage(["Mobile1","Mobile2","Mobile3"],"MESSAGE");`

#### Using SmsApi facade
- Basic Usage `SmsApi::sendMessage("TO","MESSAGE");`

- Adding extra parameters `SmsApi::sendMessage("TO", "Message", ["param1" => "val"]);`

- Adding extra headers `SmsApi::sendMessage("TO", "Message", ["param1" => "val"], ["header1" => "val"]);`

- Using a different gateway `SmsApi::gateway('GATEWAY_NAME')->sendMessage("TO", "Message");`

- Using a different country code `SmsApi::countryCode('COUNTRY_CODE')->sendMessage("TO", "Message");`

- Sending message to multiple mobiles `SmsApi::sendMessage(["Mobile1","Mobile2","Mobile3"],"MESSAGE");`

### Use in Notifications

#### Setting up the Route for Notofication
Add the method `routeNotificationForSmsApi()` to your Notifiable model :
```
public function routeNotificationForSmsApi() {
        return $this->phone; //Name of the field to be used as mobile
    }
```

By default, your User model uses Notifiable.

#### Setting up Notification

Add

`use Gr8Shivam\SmsApi\Notifications\SmsApiChannel;`

and

`use Gr8Shivam\SmsApi\Notifications\SmsApiMessage;`

to your notification.

You can create a new notification with `php artisan make:notification NOTIFICATION_NAME`

In the `via` function inside your notification, add `return [SmsApiChannel::class];` and add a new function `toSmsApi($notifiable)` to return the message body and parameters.

Notification example:-
```
namespace App\Notifications;

use Gr8Shivam\SmsApi\Notifications\SmsApiChannel;
use Gr8Shivam\SmsApi\Notifications\SmsApiMessage;
use Illuminate\Notifications\Notification;

class ExampleNotification extends Notification
{
    public function via($notifiable)
    {
        return [SmsApiChannel::class];
    }

    public function toSmsApi($notifiable)
    {
        return (new SmsApiMessage)
            ->content("Hello");
    }
}
```
You can also use `->params(["param1" => "val"])` to add extra parameters to the request and `->headers(["header1" => "val"])` to add extra headers to the request.

### Getting Response
You can get response by using `->response()` or get the Response Code using `->getResponseCode()`. For example, `smsapi()->sendMessage("TO","MESSAGE")->response();`

## Support
Feel free to post your issues in the issues section.

## Credits
Developed by [Shivam Agarwal](https://github.com/gr8shivam "Shivam Agarwal")

Thanks to [laravel-ovh-sms](https://github.com/MarceauKa/laravel-ovh-sms "laravel-ovh-sms") & [softon-sms](https://github.com/softon/sms "softon-sms")

## License
MIT


text:
using System.Runtime.CompilerServices;
using Orleans.CodeGeneration;

[assembly: InternalsVisibleTo("UnitTests")]
[assembly: SkipCodeGeneration]


text:
namespace mozc {
namespace japanese_util_rule {

#define DECLARE_RULE(name)                              \
  extern const char name##_table[];                     \
  extern const DoubleArray name##_da[]

DECLARE_RULE(hiragana_to_katakana);
DECLARE_RULE(hiragana_to_romanji);
DECLARE_RULE(katakana_to_hiragana);
DECLARE_RULE(romanji_to_hiragana);
DECLARE_RULE(fullwidthkatakana_to_halfwidthkatakana);
DECLARE_RULE(halfwidthkatakana_to_fullwidthkatakana);
DECLARE_RULE(halfwidthascii_to_fullwidthascii);
DECLARE_RULE(fullwidthascii_to_halfwidthascii);
DECLARE_RULE(normalize_voiced_sound);
DECLARE_RULE(kanjinumber_to_arabicnumber);

#undef DECLARE_RULE

}  // namespace japanese_util_rule
}  // namespace mozc

#endif  // MOZC_BASE_JAPANESE_UTIL_RULE_H_


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.4"/>
<title>OPTRAJ: Répertoire de référence de /home/sacapuces/optraj.istic.univ-rennes1.fr/vagrant/optraj.istic.univ-rennes1.fr/src/tests/interfacebdd</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

OPTRAJ

Page principale

Paquetages

Classes

Fichiers

          <input type="text" id="MSearchField" value="Recherche" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

 Tout Classes Espaces de nommage Fichiers Fonctions Variables

vagrant

optraj.istic.univ-rennes1.fr

src

tests

interfacebdd

Répertoire de référence de interfacebdd

Graphe des dépendances de répertoires pour interfacebdd:

This browser is not able to show SVG: try Firefox, Chrome, Safari, or Opera instead.

Fichiers

fichier  	__init__.py

fichier  	test_carDAO.py

fichier  	test_craftDAO.py

fichier  	test_needDAO.py

fichier  	test_passengerDAO.py

fichier  	test_pickupDAO.py

fichier  	test_pickupLinkDAO.py

fichier  	test_positionDAO.py

fichier  	test_qualificationDAO.py

fichier  	test_shuttleDAO.py

fichier  	test_siteDAO.py

fichier  	test_workerDAO.py

<address class="footer">
Généré le Jeudi Avril 24 2014 13:03:21 pour OPTRAJ par

 1.8.4
</address>


text:
var noteManager = function (options) {
    this.parameters = options;
    this.defaults = {
        defaultSort: 'newer'
    };
};

noteManager.prototype = {

    init: function() {
      // merge defaults options and user's ones
      this.options = $.extend({}, this.defaults, this.parameters);
      this.plugEvents();
    },

    plugEvents: function() {

      this.displayNotes();
      if (this.options.defaultSort === "older") {
        this.reverseOrder();
      }

      var that = this;

      // Save note and display it
      $(document).on('click', '#new-note-form button[type="submit"]', function(e){
        e.preventDefault();
        var form = $(this).closest('form');
        var note = that.getNote(form);
        if (note.content !== '' || note.title !== '') {
          that.saveNote(note);
          //that.clearForm();
          // TODO : animate opacity
          form.remove();
          that.displaySingleNote(note);
        }else{
          alert("You can't submit an empty note !");
        }

      });

      $('#new-note').on('click', function(){
        if (!$('#new-note-form').length) {
          that.newForm();
          $("html, body").animate({
            scrollTop: 0
          }, 600);
          $('.card .mdi-navigation-close').on('click', function(){
            // TODO : Animate opacity
            $(this).closest('form').remove();
          });
        }
      });

      // Delete all notes
      $('#delete').on('click', $.proxy(function(){
        if (confirm("All notes will be deleted, are you sure ?")) {
          this.deleteNotes();
        }
      }, this));

      // Delete a note
      $(document).on('click', 'div[id^="note-"] button.delete', function(){
        if (confirm("This note will be deleted, are you sure ?")) {
          var id = $(this).parents('div[id^="note-"]').attr('id');
          id = id.substr(5, id.length);
          that.deleteSingleNote(id);
          // Force update of all notes ids
          // TODO : find a cleaner way to do this
          $('div[id^="note-"]').remove();
          that.displayNotes();
        }
      });

      // Edit a note
      $(document).on('click', 'div[id^="note-"] button.edit', function(){
        var id = $(this).parents('div[id^="note-"]').attr('id');
        id = id.substr(5, id.length);
        that.editNote(id);
      });

      // Only when editing a note
      $(document).on('click', '#edit-note-form button[type="submit"]', function(e){
        e.preventDefault();
        var form = $(this).closest('form');
        var note = that.getNote(form);
        that.saveNote(note);

        var id = $(form).data("note-id");
        that.deleteSingleNote(id);
        that.displaySingleNote(note);
      });

      // Sort by time
      $('#sort').on('click', $.proxy(function(e){
        e.preventDefault();
        this.reverseOrder();
      }, this));

      // Sort by tag
      $(document).on('click', '.note span[id^="tag-"], #tagsButton span', function(){
        var tag = $(this).text();
        that.searchByTag(tag);
      });

      // Tag search
      $('#search-by-tag').on('mouseenter', $.proxy(function(){
        var tags = this.getAllTags();

        if (tags) {
          var html = this.displayAllTags(tags);

          if (html !== '') {
            $('#tagsButton').html(html);
          }
        }

      }, this));

      // Text search
      $('#search-input').on('keyup', function(){
        var value = $(this).val();
        $('div[id^="note-"]').hide();
        $('div[id^="note-"]:contains("'+value+'")').show();
      });

       /* Export to Dropbox
       * /!\  Can't save a file from localhost (Dropbox need access to the server)
       */
      $('#dropbox-export').on('click', $.proxy(function(){
        if (Dropbox.isBrowserSupported()) {

          var id = this.createJSONfile(localStorage.getItem("WebNotes"));

          id.success(function(id){
            var dropboxOptions = {
              files: [
                  {'url': document.URL+'/temp/WebNotes-'+id+'.json', 'filename': 'WebNotes.json'},
              ],
              error: function (errorMessage) {
                alert('An error occured, try again later.\nSorry for the inconvenience.');
                console.log('Error when saving to Dropbox: '+errorMessage);
              }
            };

            Dropbox.save(dropboxOptions);
          });

          id.error(function(){
            alert('An error occured, try again later.\nSorry for the inconvenience.');
            console.log('Error generating JSON');
          });
        }else{
          alert("Your browser is not supported by the Dropbox API, it's probably time to update your browser, check : \n\noutdatedbrowser.com");
        }

      }, this));

      // Import from Dropbox
      $('#dropbox-import').on('click', $.proxy(function(){

        if (Dropbox.isBrowserSupported()) {

          var that = this;
          var options = {
            // Required. Called when a user selects an item in the Chooser.
            success: function(files) {
                $.get( files[0].link, function( data ) {
                  localStorage.setItem("WebNotes", data);
                  $('div[id^="note-"]').remove();
                  that.displayNotes();
                });
            },
            // Direct link to the content of the file
            linkType: "direct",
            multiselect: false,
            // User will be able to select only json files
            extensions: ['.json'],
          };

          if (confirm("This will erase all your current notes and replace them by the ones you choose to import, are you sure ?")) {
            Dropbox.choose(options);
          }
        }else{
          alert("Your browser is not supported by the Dropbox API, it's probably time to update your browser, check : \n\noutdatedbrowser.com");
        }

      }, this));

    }, // End plugEvents

    /******************
      CORE FUNCTIONS
    ******************/
    // TODO : Add tags field
    newForm: function(){
      var formHTML =
      '<form class="col s12 m3" id="new-note-form">'+
        '
'+
          '
'+
              'Add a new note'+
              '
'+
                '<input type="text" id="title" autofocus>'+
                'Title'+
              '
'+
              '
'+
                '<textarea class="materialize-textarea"></textarea>'+
                'Content of your note'+
              '
'+
              '

'+
          '
'+
          '
'+
            '<button class="btn waves-effect waves-light" type="submit" name="action">Submit</button>'+
          '
'+
        '
'+
      '</form>';

      $('main .container .row').prepend(formHTML);
    },

    /**
     * Get form data and return it as a JSON object
     * @param {HTML Object} form   The form generating this note
     * @return {JSON}   Note as JSON object
     */
    getNote: function(form) {
      var title = form.find('#title').val();
      var content = form.find('textarea').val();
      var url = this.containsURL(content);
      var today = this.formatDate();
      var date = today[0];
      var time = today[1];
          // FIXME
          //tags = this.formatTags(form.find('.tags').val());
      var tags = '';

      var note = this.formatNote(title, content, date, time, tags, url);
      return note;
    },

    /**
     * Format note to JSON with form data
     * @param  {string} title     Note title
     * @param  {string} content   Note text content
     * @param  {string} date      Note date
     * @param  {string} time      Note hour
     * @param  {string} tags      Note tags
     * @param  {string} url       URL contained in note
     * @return {JSON}             Note as JSON object
     */
    formatNote: function(title, content, date, time, tags, url) {
      var note = {
            "title": title,
            "content": content,
            "date": date,
            "time": time,
            "tags": tags,
            "url": url,
          };

      return note;
    },

    /**
     * If notes already exist in local storage, add the new one and save
     * else create the object and save it in local storage.
     * @param  {JSON}
     */
    saveNote: function(note) {
      var notes;
      if (localStorage.getItem("WebNotes") === null) {
        notes = [ note ];
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
      }else{
        notes = $.parseJSON(localStorage.getItem("WebNotes"));
        notes.push(note);
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
      }
    },

    /**
     * Display all notes
     */
    displayNotes: function() {
      if (localStorage.getItem("WebNotes") !== null) {

        var notes = $.parseJSON(localStorage.getItem("WebNotes"));
        var tags;

        for (var i = notes.length-1 ; i >= 0; i--) {
          tags = '';
          for (var j = 0; j < notes[i].tags.length; j++) {
            if (notes[i].tags[j]) {
              if (j === 0 ) {
                tags = '#' + notes[i].tags[j] + '';
              }else{
                tags = tags + ' #' + notes[i].tags[j] + '';
              }
            }
          }

          // Replace url in text by a link
          var url = this.containsURL(notes[i].content);
          if (typeof url !== undefined) {
            var regexp = /^(www)/;
            if (regexp.exec(url)) {
              if (notes[i].type === "video" || notes[i].type === "sound"){
                notes[i].content = notes[i].content.replace(url, '');
              }else{
                var urlWithoutProtocol = url;
                url = 'http://'+url;
                notes[i].content = notes[i].content.replace(urlWithoutProtocol, ''+urlWithoutProtocol+'');
              }
            }else{
              if (notes[i].type == "video" || notes[i].type == "sound") {
                notes[i].content = notes[i].content.replace(url, '');
              }else{
                notes[i].content = notes[i].content.replace(url, ''+url+'');
              }
            }
          }

          // Keep line breaks
          notes[i].content = this.nl2br(notes[i].content);

          $('main .container .row').append(
            '

'+
              '
'+
                ''+notes[i].title+''+
                '
'+notes[i].content+'
'+
              '
'+
              '
'+
                '
'+ tags +'
'+
                ''+notes[i].date+' - '+notes[i].time+''+
                '<button class="edit"></button>'+
                '<button class="delete"></button>'+
              '
'+
            '

'
          );

          if (notes[i].url) {
            this.generateWidget(i, notes[i].url);
          }
        }

      }
    },

    /**
     * Display a single note
     * @param {JSON} note
     */
    displaySingleNote: function(note) {
      var tags = '';
      var notesLength = $.parseJSON(localStorage.getItem("WebNotes")).length;
      notesLength = notesLength-1; // Number of next note

      for (var j = 0; j < note.tags.length; j++) {
         if (note.tags[j]) {
          if (j === 0 ) {
            tags = '#' + note.tags[j] + '';
          }else{
            tags = tags + ' #' + note.tags[j] + '';
          }
        }
      }

      // Replace url in text by a link
      var url = this.containsURL(note.content);
      if (typeof url !== undefined) {
        var regexp = /^(www)/;
        if (regexp.exec(url)) {
          var urlWithoutProtocol = url;
          url = 'http://'+url;
          note.content = note.content.replace(urlWithoutProtocol, ''+urlWithoutProtocol+'');
        }else{
          note.content = note.content.replace(url, ''+url+'');
        }
      }

      // Keep line breaks
      note.content = this.nl2br(note.content);
      var noteHTML = '

'+
                        '
'+
                          ''+note.title+''+
                          '
'+note.content+'
'+
                        '
'+
                        '
'+
                          '
'+ tags +'
'+
                          ''+note.date+' - '+note.time+''+
                          '<button class="edit"></button>'+
                          '<button class="delete"></button>'+
                        '
'+
                      '

';

      if (this.options.defaultSort === "older") {
        $('main .container .row').append(noteHTML);
      }else{
        $('main .container .row').prepend(noteHTML);
      }

      if (note.url) {
        this.generateWidget(notesLength, note.url);
      }

      // TODO Find a cleaner way to do this
      if ($('#note-'+notesLength).hasClass('video') || $('#note-'+notesLength).hasClass('sound')){
        var content = $('#note-'+notesLength+' p').text();
        content = content.replace(url, '');
        $('#note-'+notesLength+' p').text(content);
      }
    },

    /**
     * Delete all notes
     */
    deleteNotes: function() {
      localStorage.removeItem("WebNotes");
      $('div[id^="note-"]').remove();
      $('#dropdown1').html('You have currently no notes with a tag, add tags to your notes !');
    },

    /**
     * Delete a single note
     * @param  {int} id  ID of the note to be deleted
     */
    deleteSingleNote: function(id) {
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      if (id != -1) {
        notes.splice(id, 1);
        notes = JSON.stringify(notes);
        localStorage.setItem("WebNotes", notes);
        $('#note-'+id+'').remove();
      }
    },

    /**
     * Edit a note
     * @param  {int} id  ID of the note to be edited
     */
    editNote: function(id) {
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      var note = notes[id];

      var editForm =
        '<form class="col s12" id="edit-note-form" data-note-id="'+id+'">'+
          '
'+
            '
'+
                'Edit a note'+
                '
'+
                  '<input type="text" id="title" value="'+note.title+'">'+
                  'Title'+
                '
'+
                '
'+
                  '<textarea class="materialize-textarea">'+note.content+'</textarea>'+
                  'Content of your note'+
                '
'+
                '

'+
            '
'+
            '
'+
              '<button class="btn waves-effect waves-light" type="submit" name="action">Submit</button>'+
            '
'+
          '
'+
        '</form>';

     $('#note-'+id).html(editForm);

     // FIXME : bug in materialize framework with autofill
     $('#note-'+id+' label').addClass('active');

     // TODO : tag input
    /* $('#note-'+id+' .tags').tagsInput({
       'height': 'auto',
       'width' : 'auto',
      });*/
    },

    /**
     * Fetch all tags from each note
     * @return {array} Array of all tags
     */
    getAllTags: function(){
      var notes = $.parseJSON(localStorage.getItem("WebNotes"));
      var tags = [];

      if (notes !== null) {
        for (var i = notes.length-1 ; i >= 0; i--) {
          for (var j = 0; j < notes[i].tags.length; j++) {
            if (notes[i].tags[j] && $.inArray(notes[i].tags[j], tags) === -1) {
               tags.push(notes[i].tags[j]);
            }
          }
        }
        return tags;
      }

    },

    /**
     * Get all notes tags and return HTML code with a list of all the tags
     * @param  {array} tags  Array of all tags
     * @return {string}      HTML code
     */
    displayAllTags: function(tags){
      var html = '';
      for (var i = 0; i < tags.length; i++) {
        html = html + ''+tags[i]+'';
      }
      return html;
    },

    /**
     * Show the notes containing the selected tag
     * @param  {string} tag
     */
    searchByTag: function(tag){
      // Hide all notes and then show only the ones with the selected tag
      $('div.note').hide();
      $('div.note .tools span:contains("'+tag+'")').parent().parent().show();
    },

    /******************
     TOOLKIT FUNCTIONS
    ******************/
    // Useless ?
    /*clearForm: function() {
      $('form input.title, form textarea').val('');
      $('div.tagsinput span').remove();
      $('.tagsInput input').val('');
      $('input.tags').val('');
    },*/

    /**
     * Get current date and time and format it
     * @return {array}    containing current date and hour
     */
    formatDate: function() {
      var today = new Date();
      var dd = today.getDate();
      var mm = today.getMonth()+1; //January is 0!
      var yyyy = today.getFullYear();

      if(dd<10){
          dd='0'+dd;
      }
      if(mm<10){
          mm='0'+mm;
      }

      var h = today.getHours();
      var m = today.getMinutes();
      //var s = today.getSeconds();

      today = dd+'/'+mm+'/'+yyyy;

      var time = h + 'h' + m + 'min';

      return [today, time];
    },

    /**
     * Convert a list of tags into an array
     * @param  {string} tags    list of tags
     * @return {array}          array of tags
     */
    formatTags: function(tags) {
      var tagsArray = tags.split(',');

      return tagsArray;
    },

    /**
     * Convert line breaks to

     * http://phpjs.org/functions/nl2br/
     * @param  {string}  str      String to be formated
     * @param  {Boolean} is_xhtml XHTML compatibility
     * @return {string}           String formated with
 tags
     */
    nl2br : function(str, is_xhtml){
      var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '
' : '
';
      return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
    },

    /**
     * Ajax request to generate a JSON file through a PHP script
     * @param  {JSON} notes    object containing all notes
     */
    createJSONfile: function(notes) {
      return $.ajax({
        type : "POST",
        url : "php-tools/json.php",
        data : {
            json : notes
        }
      });
    },

    /**
     * Display all notes in reverse order : old ones first
     */
    reverseOrder: function() {
      $('main .container .row > div:not(#new-note-form)').each(function() {
        $(this).prependTo(this.parentNode);
      });
      $('main .container .row').prepend($('#new-note-form'));
    },

    /**
     * Check for an URL inside a string
     * @param  {string} s
     * @return {string}   Matched URL
     */
    containsURL: function(s) {
      var regexp = /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/;
      if (regexp.exec(s)) {
        return regexp.exec(s)[0];
      }
    },

    /**
     * Test for compatible websites and return a widget or a picture
     * @param  {int}    id  ID of the note containing the url
     * @param  {string} s   URL to be tested
     */
    generateWidget: function(id, s) {
      var regexp = /(youtube\.com|youtu\.be|soundcloud\.com|imdb\.com|allocine\.fr|jpe?g|gif|png)/;
      var that = this;
      var movieTitle;

      if (regexp.exec(s)) {
        switch (regexp.exec(s)[0]) {
          case 'youtube.com':
          case 'youtu.be':
            s = this.getYoutubeId(s);
            // Only if correct youtube URL
            if (s !== '') {
              var iframe = '';
               $('#note-'+id+' .card').prepend(iframe);

              // Add type to note
              var notes = $.parseJSON(localStorage.getItem("WebNotes"));
              notes[id].type = "video";
              notes = JSON.stringify(notes);
              localStorage.setItem("WebNotes", notes);

              $('#note-'+id).attr('class',"col s12 m4 video");
              $('#note-'+id+' .card').addClass('red darken-2');
            }
          break;

          case 'soundcloud.com':
            SC.initialize({
              client_id: config.SoundCloud_client_id
            });

            var track_url = s;
            SC.oEmbed(track_url, { auto_play: false, show_comments: false, maxheight: 150 }, function(oEmbed) {
              $('#note-'+id+' .card').prepend(oEmbed.html);
            });

            // Add type to note
            var notes = $.parseJSON(localStorage.getItem("WebNotes"));
            notes[id].type = "sound";
            notes = JSON.stringify(notes);
            localStorage.setItem("WebNotes", notes);

            $('#note-'+id).attr('class',"col s12 m5 sound");
            $('#note-'+id+' .card').addClass('orange lighten-1');
          break;

          case 'imdb.com':
            movieTitle = this.getTitleFromUrl(s);

            movieTitle.success(function(movieTitle){
              // Remove year from title
              var regex = /(\(.*\))/;
              movieTitle = movieTitle.replace(regex.exec(movieTitle)[0], '');

              var movie = that.getMovie(movieTitle);
              movie.success(function(movie){
                var url = 'http://image.tmdb.org/t/p/w342'+movie.results[0].poster_path;

                // Append the image
                var img = '
'+
                            ''+
                          '
';

                $('#note-'+id+' .card').prepend(img);
                $('#note-'+id).attr('class', 'col s12 m4');
                $('#note-'+id+' .card').addClass('amber lighten-1');

                // Change note url to image URL instead of IMDB's one
                // so that there is juste one API call (first time the note is saved)
                notes = $.parseJSON(localStorage.getItem("WebNotes"));
                notes[id].url = url;
                notes[id].type = "movie";
                notes = JSON.stringify(notes);
                localStorage.setItem("WebNotes", notes);
              });
            });
          break;

          case 'allocine.fr':
            movieTitle = this.getTitleFromUrl(s);

            movieTitle.success(function(movieTitle){
              var movie = that.getMovie(movieTitle);

              movie.success(function(movie){
                var url = 'http://image.tmdb.org/t/p/w342'+movie.results[0].poster_path;

                // Append the image
                var img = '
'+
                            ''+
                          '
';

                $('#note-'+id+' .card').prepend(img);
                $('#note-'+id).attr('class', 'col s12 m4');
                $('#note-'+id+' .card').addClass('amber lighten-1');

                // Change note url to image URL instead of Allocine's one
                // so that there is juste one API call (first time the note is saved)
                notes = $.parseJSON(localStorage.getItem("WebNotes"));
                notes[id].url = url;
                notes[id].type = "movie";
                notes = JSON.stringify(notes);
                localStorage.setItem("WebNotes", notes);
              });
            });
          break;

          case 'jpeg':
          case 'jpg':
          case 'png':
          case 'gif':
            var img = '
'+
                        ''+
                      '
';

            $('#note-'+id+' .card').prepend(img);
            $('#note-'+id).attr('class', 'col s12 m4');

            //  Add type to note (on 2nd call, movies are handled like images
            //  so we need to test if the type is not already defined
            //  in this case only it's really an image and not a poster)
            notes = $.parseJSON(localStorage.getItem("WebNotes"));
            if (notes[id].type !== 'movie') {
              if (notes[id].type === undefined) {
                notes[id].type = "image";
                notes = JSON.stringify(notes);
                localStorage.setItem("WebNotes", notes);
              }
            }else{
              $('#note-'+id+' .card').addClass('amber lighten-1');
            }

          break;
        }
      }

    },

    /**
     * Get the ID from a Youtube video
     * @param  {string} url  URL of the video
     * @return {string}      ID of the video
     */
    getYoutubeId: function(url){
      var ID = '';
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match(regExp);
      if (match && match[7].length == 11){
        ID = match[7];
      }
      return ID;
    },

    /**
     * Get the movie title from an IMDB/Allocine URL
     * @param  {strin} url  Webpage url
     */
    getTitleFromUrl: function(url) {
      // If link starts with www add protocol (http) to it
      var regexp = /^(www)/;
      if (regexp.exec(url)) {
        url = 'http://'+url;
      }
      return $.ajax({
        type : "POST",
        url : "php-tools/getTitle.php",
        data : {
            'url' : url
        }
      });
    },

    /**
     * Call to The Movie Database API in order to get infos about a movie
     * @param  {string} movie  Name of the movie
     */
    getMovie: function(movieTitle) {
      movieTitle = encodeURI(movieTitle);
      var url = 'http://api.themoviedb.org/3/search/movie?query='+movieTitle+'&api_key='+config.TMDB_api_key;

      return $.ajax({
        type : "GET",
        url : url,
        dataType: "jsonp",
      });

    },

};


text:
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Input.Bindings;
using osu.Game.Rulesets.UI.Scrolling;
using osu.Game.Skinning;
using osuTK;
using osuTK.Graphics;

namespace osu.Game.Rulesets.Mania.Skinning.Legacy
{
    public class LegacyColumnBackground : LegacyManiaColumnElement, IKeyBindingHandler<ManiaAction>
    {
        private readonly IBindable<ScrollingDirection> direction = new Bindable<ScrollingDirection>();

        private Container lightContainer;
        private Sprite light;

        public LegacyColumnBackground()
        {
            RelativeSizeAxes = Axes.Both;
        }

        [BackgroundDependencyLoader]
        private void load(ISkinSource skin, IScrollingInfo scrollingInfo)
        {
            string lightImage = skin.GetManiaSkinConfig<string>(LegacyManiaSkinConfigurationLookups.LightImage)?.Value
                                ?? "mania-stage-light";

            float lightPosition = GetColumnSkinConfig<float>(skin, LegacyManiaSkinConfigurationLookups.LightPosition)?.Value
                                  ?? 0;

            Color4 lightColour = GetColumnSkinConfig<Color4>(skin, LegacyManiaSkinConfigurationLookups.ColumnLightColour)?.Value
                                 ?? Color4.White;

            InternalChildren = new[]
            {
                lightContainer = new Container
                {
                    Origin = Anchor.BottomCentre,
                    RelativeSizeAxes = Axes.Both,
                    Padding = new MarginPadding { Bottom = lightPosition },
                    Child = light = new Sprite
                    {
                        Anchor = Anchor.BottomCentre,
                        Origin = Anchor.BottomCentre,
                        Colour = LegacyColourCompatibility.DisallowZeroAlpha(lightColour),
                        Texture = skin.GetTexture(lightImage),
                        RelativeSizeAxes = Axes.X,
                        Width = 1,
                        Alpha = 0
                    }
                }
            };

            direction.BindTo(scrollingInfo.Direction);
            direction.BindValueChanged(onDirectionChanged, true);
        }

        private void onDirectionChanged(ValueChangedEvent<ScrollingDirection> direction)
        {
            if (direction.NewValue == ScrollingDirection.Up)
            {
                lightContainer.Anchor = Anchor.TopCentre;
                lightContainer.Scale = new Vector2(1, -1);
            }
            else
            {
                lightContainer.Anchor = Anchor.BottomCentre;
                lightContainer.Scale = Vector2.One;
            }
        }

        public bool OnPressed(ManiaAction action)
        {
            if (action == Column.Action.Value)
            {
                light.FadeIn();
                light.ScaleTo(Vector2.One);
            }

            return false;
        }

        public void OnReleased(ManiaAction action)
        {
            // Todo: Should be 400 * 100 / CurrentBPM
            const double animation_length = 250;

            if (action == Column.Action.Value)
            {
                light.FadeTo(0, animation_length);
                light.ScaleTo(new Vector2(1, 0), animation_length);
            }
        }
    }
}


text:
class Ticket < ActiveRecord::Base

  # Associations
  belongs_to :group
  belongs_to :status
  belongs_to :priority
  belongs_to :creator, :class_name => "User", :foreign_key => "created_by"
  belongs_to :owner, :class_name => "User", :foreign_key => "owned_by"
  belongs_to :cliente
  has_many :comments, :dependent => :destroy
  has_many :attachments, :dependent => :destroy, :class_name => '::Attachment'
  has_many :alerts, :dependent => :destroy
  has_many :alert_users, :through => :alerts, :class_name => 'User', :source => :user

  # Validations
  validates_presence_of :title, :group_id, :status_id, :priority_id, :cliente_id, :created_by

  # Callbacks
  before_update :set_closed_at

  # Scopes
  named_scope :not_closed, :joins => :status, :conditions => ['statuses.name <> ?', 'Closed']
  named_scope :recently_assigned_to, lambda { | user_id | { :limit => 5, :conditions => { :owned_by => user_id }, :include => [:creator, :owner, :group, :status, :priority, :cliente], :order => 'updated_at DESC' } }
  named_scope :active_tickets, :limit => 5, :include => [:creator, :owner, :group, :status, :priority], :order => 'updated_at DESC'
  named_scope :closed_tickets, :limit => 5, :joins => :status, :include => [:creator, :owner, :group, :status, :priority], :conditions => ['statuses.name = ?', 'Closed'], :order => 'closed_at DESC'
  named_scope :mytickets, lambda { | user_id | { :limit => 5, :conditions => { :owned_by => user_id }, :include => [:creator, :owner, :group, :status, :priority, :cliente], :order => 'updated_at DESC' } }
 # named_scope :mytickets, :limit => 5, :joins => :status, :include => [:creator, :owner, :group, :status, :priority], :conditions => ['statuses.name = ?', 'Closed'], :order => 'closed_at DESC'

  def self.timeline_opened_tickets
    #self.count(:group => 'date(created_at)', :having => ['date_created_at >= ? and date_created_at <= ?', (Time.zone.now.beginning_of_day - 30.days).to_s, (Time.zone.now.end_of_day - 1.day).to_s])
    self.count(:group => '(created_at)', :having => ['created_at >= ? and created_at <= ?', (Time.zone.now.beginning_of_day - 30.days).to_s, (Time.zone.now.end_of_day - 1.day).to_s])

  end

  def self.timeline_closed_tickets
#    self.count(:group => 'date(closed_at)', :having => ['date_closed_at >= ? and date_closed_at <= ?', (Time.zone.now.beginning_of_day - 30.days).to_s, (Time.zone.now.end_of_day - 1.day).to_s])
    self.count(:group => '(closed_at)', :having => ['closed_at >= ? and closed_at <= ?', (Time.zone.now.beginning_of_day - 30.days).to_s, (Time.zone.now.end_of_day - 1.day).to_s])

  end

  def closed?
    status.name == 'Closed'
  end

  def only_touched?
    self.changed.size == 1 and self.changed[0] == "updated_at"
  end

  protected

  def set_closed_at
    # update the closed_at timestamp if the ticket is being closed
    if closed?
      self.closed_at = DateTime.now if self.closed_at.nil?
    else
      self.closed_at = nil unless self.closed_at.nil?
    end
  end

end


text:
ID: 38
post_title: Colab
author: open@colab.at
post_date: 2016-02-19 13:40:30
post_excerpt: ""
layout: page
permalink: http://beta.colab.at/colab/
published: true
---
Redirect this to project page colab.at/colab


text:
#include <tchar.h>
#include <Windows.h>
#include <iostream>
#include <string>
#include <atlbase.h>
#include <algorithm>

// COM Includes of 3MF Library
#include "NMR_COMFactory.h"

// Use NMR namespace for the interfaces
using namespace NMR;

// Utility functions to create vertices and triangles
MODELMESHVERTEX fnCreateVertex(float x, float y, float z)
{
	MODELMESHVERTEX result;
	result.m_fPosition[0] = x;
	result.m_fPosition[1] = y;
	result.m_fPosition[2] = z;
	return result;
}

MODELMESHTRIANGLE fnCreateTriangle(int v0, int v1, int v2)
{
	MODELMESHTRIANGLE result;
	result.m_nIndices[0] = v0;
	result.m_nIndices[1] = v1;
	result.m_nIndices[2] = v2;
	return result;
}

MODELTRANSFORM createTranslationMatrix(float x, float y, float z)
{
	MODELTRANSFORM mMatrix;
	int i, j;
	for (i = 0; i < 4; i++) {
		for (j = 0; j < 3; j++) {
			mMatrix.m_fFields[j][i] = (i == j) ? 1.0f : 0.0f;
		}
	}

	mMatrix.m_fFields[0][3] = x;
	mMatrix.m_fFields[1][3] = y;
	mMatrix.m_fFields[2][3] = z;

	return mMatrix;
}

int _tmain(int argc, _TCHAR* argv[])
{
	// General Variables
	HRESULT hResult;
	DWORD nInterfaceVersion;
	MODELTRANSFORM mTransform;

	// Objects
	CComPtr<ILib3MFModel> pModel;
	CComPtr<ILib3MFModelFactory> pFactory;
	CComPtr<ILib3MFModelWriter> pSTLWriter;
	CComPtr<ILib3MFModelWriter> p3MFWriter;
	CComPtr<ILib3MFModelMeshObject> pMeshObject;
	CComPtr<ILib3MFModelComponentsObject> pComponentsObject;
	CComPtr<ILib3MFModelBuildItem> pBuildItem;
	CComPtr<ILib3MFModelComponent> pComponent1;
	CComPtr<ILib3MFModelComponent> pComponent2;
	CComPtr<ILib3MFModelComponent> pComponent3;

	std::cout << "------------------------------------------------------------------" << std::endl;
	std::cout << "3MF Components example" << std::endl;
	std::cout << "------------------------------------------------------------------" << std::endl;

	// Initialize COM
	hResult = CoInitialize(nullptr);
	if (hResult != S_OK) {
		std::cout << "could not initialize COM: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create Factory Object
	hResult = NMRCreateModelFactory(&pFactory);
	if (hResult != S_OK) {
		std::cout << "could not get Model Factory: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Check 3MF Library Version
	hResult = pFactory->GetInterfaceVersion(&nInterfaceVersion);
	if (hResult != S_OK) {
		std::cout << "could not get 3MF Library version: " << std::hex << hResult << std::endl;
		return -1;
	}

	if ((nInterfaceVersion != NMR_APIVERSION_INTERFACE)) {
		std::cout << "invalid 3MF Library version: " << NMR_APIVERSION_INTERFACE << std::endl;
		return -1;
	}

	// Create Model Instance
	hResult = pFactory->CreateModel(&pModel);
	if (hResult != S_OK) {
		std::cout << "could not create model: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create Mesh Object
	hResult = pModel->AddMeshObject(&pMeshObject);
	if (hResult != S_OK) {
		std::cout << "could not add mesh object: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create mesh structure of a cube
	MODELMESHVERTEX pVertices[8];
	MODELMESHTRIANGLE pTriangles[12];
	float fSizeX = 10.0f;
	float fSizeY = 20.0f;
	float fSizeZ = 30.0f;

	// Manually create vertices
	pVertices[0] = fnCreateVertex(0.0f, 0.0f, 0.0f);
	pVertices[1] = fnCreateVertex(fSizeX, 0.0f, 0.0f);
	pVertices[2] = fnCreateVertex(fSizeX, fSizeY, 0.0f);
	pVertices[3] = fnCreateVertex(0.0f, fSizeY, 0.0f);
	pVertices[4] = fnCreateVertex(0.0f, 0.0f, fSizeZ);
	pVertices[5] = fnCreateVertex(fSizeX, 0.0f, fSizeZ);
	pVertices[6] = fnCreateVertex(fSizeX, fSizeY, fSizeZ);
	pVertices[7] = fnCreateVertex(0.0f, fSizeY, fSizeZ);

	// Manually create triangles
	pTriangles[0] = fnCreateTriangle(2, 1, 0);
	pTriangles[1] = fnCreateTriangle(0, 3, 2);
	pTriangles[2] = fnCreateTriangle(4, 5, 6);
	pTriangles[3] = fnCreateTriangle(6, 7, 4);
	pTriangles[4] = fnCreateTriangle(0, 1, 5);
	pTriangles[5] = fnCreateTriangle(5, 4, 0);
	pTriangles[6] = fnCreateTriangle(2, 3, 7);
	pTriangles[7] = fnCreateTriangle(7, 6, 2);
	pTriangles[8] = fnCreateTriangle(1, 2, 6);
	pTriangles[9] = fnCreateTriangle(6, 5, 1);
	pTriangles[10] = fnCreateTriangle(3, 0, 4);
	pTriangles[11] = fnCreateTriangle(4, 7, 3);

	hResult = pMeshObject->SetGeometry(pVertices, 8, pTriangles, 12);
	if (hResult != S_OK) {
		std::cout << "could not set mesh geometry: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create Component Object
	hResult = pModel->AddComponentsObject(&pComponentsObject);
	if (hResult != S_OK) {
		std::cout << "could not add mesh object: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create model transform for second cube
	mTransform = createTranslationMatrix(0.0f, 0.0f, 0.0f);

	hResult = pComponentsObject->AddComponent(pMeshObject, &mTransform, &pComponent1);
	if (hResult != S_OK) {
		std::cout << "could not add component 1: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create model transform for second cube
	mTransform = createTranslationMatrix(40.0f, 60.0f, 80.0f);

	// Add Build Item for Mesh
	hResult = pComponentsObject->AddComponent(pMeshObject, &mTransform, &pComponent2);
	if (hResult != S_OK) {
		std::cout << "could not add component 2: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create model transform for third cube
	mTransform = createTranslationMatrix(120.0f, 30.0f, 70.0f);

	// Add Build Item for Mesh
	hResult = pComponentsObject->AddComponent(pMeshObject, &mTransform, &pComponent3);
	if (hResult != S_OK) {
		std::cout << "could not add component 3: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Add Build Item for Component
	mTransform = createTranslationMatrix(0.0f, 0.0f, 0.0f);
	hResult = pModel->AddBuildItem(pComponentsObject, &mTransform, &pBuildItem);
	if (hResult != S_OK) {
		std::cout << "could not create build item: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Add second Build Item for Component
	mTransform = createTranslationMatrix(200.0f, 40.0f, 10.0f);
	hResult = pModel->AddBuildItem(pComponentsObject, &mTransform, &pBuildItem);
	if (hResult != S_OK) {
		std::cout << "could not create build item: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Add third Build Item for Mesh Object
	mTransform = createTranslationMatrix(-40.0f, 0.0f, 20.0f);
	hResult = pModel->AddBuildItem(pMeshObject, &mTransform, &pBuildItem);
	if (hResult != S_OK) {
		std::cout << "could not create build item: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Output scene as STL and 3MF

	// Create Model Writer
	hResult = pModel->QueryWriter(L"stl", &pSTLWriter);
	if (hResult != S_OK) {
		std::cout << "could not create model reader: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Export Model into File
	std::cout << "writing components.stl..." << std::endl;
	hResult = pSTLWriter->WriteToFile(L"components.stl");
	if (hResult != S_OK) {
		std::cout << "could not write file: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Create Model Writer
	hResult = pModel->QueryWriter(L"3mf", &p3MFWriter);
	if (hResult != S_OK) {
		std::cout << "could not create model reader: " << std::hex << hResult << std::endl;
		return -1;
	}

	// Export Model into File
	std::cout << "writing components.3mf..." << std::endl;
	hResult = p3MFWriter->WriteToFile(L"components.3mf");
	if (hResult != S_OK) {
		std::cout << "could not write file: " << std::hex << hResult << std::endl;
		return -1;
	}

	std::cout << "done" << std::endl;

	return 0;
}


text:
package org.ggp.base.apps.kiosk.games;

import java.awt.Color;
import java.awt.Graphics;
import java.util.Set;

import org.ggp.base.apps.kiosk.templates.CommonGraphics;
import org.ggp.base.apps.kiosk.templates.GameCanvas_FancyGrid;

public class TTCC4Canvas extends GameCanvas_FancyGrid {
    private static final long serialVersionUID = 1L;

    @Override
	public String getGameName() { return "TTCC4"; }
    @Override
	protected String getGameKey() { return "ttcc4_2player"; }
    @Override
	protected int getGridHeight() { return 7; }
    @Override
	protected int getGridWidth() { return 7; }

    @Override
	protected final boolean useGridVisualization() { return false; }
    @Override
	protected final boolean coordinatesStartAtOne() { return true; }

    @Override
	protected final void renderCellBackground(Graphics g, int xCell, int yCell) {
        int width = g.getClipBounds().width;
        int height = g.getClipBounds().height;

        yCell = 8 - yCell;

        // Highlight the Tic-Tac-Toe board
        if(xCell >= 3 && xCell <= 5 && yCell >= 3 && yCell <= 5) {
            g.setColor(Color.LIGHT_GRAY);
            g.fillRect(0, 0, width, height);
        }

        CommonGraphics.drawCellBorder(g);

        // Clear out the edges
        if(xCell == 1 || xCell == 7 || yCell == 1 || yCell == 7) {
            g.setColor(Color.DARK_GRAY);
            g.fillRect(0, 0, width, height);
        }
    }

    @Override
    protected Set<String> getLegalMovesForCell(int xCell, int yCell) {
        yCell = 8 - yCell;

        Set<String> theMoves = gameStateHasLegalMovesMatching("\\( pawnMove " + xCell + " " + yCell + " (.*) \\)");
        theMoves.addAll(gameStateHasLegalMovesMatching("\\( knightMove " + xCell + " " + yCell + " (.*) \\)"));
        theMoves.addAll(gameStateHasLegalMovesMatching("\\( checkerMove " + xCell + " " + yCell + " (.*) \\)"));
        theMoves.addAll(gameStateHasLegalMovesMatching("\\( jump " + xCell + " " + yCell + " (.*) \\)"));

        if(theMoves.size() == 0)
            theMoves.addAll(gameStateHasLegalMovesMatching("\\( drop " + xCell + " \\)"));

        if(theMoves.size() == 0)
            theMoves.add("noop");

        return theMoves;
    }

    @Override
    protected Set<String> getFactsAboutCell(int xCell, int yCell) {
        yCell = 8 - yCell;
        return gameStateHasFactsMatching("\\( cell " + xCell + " " + yCell + " (.*) \\)");
    }

    @Override
    protected void renderCellContent(Graphics g, Set<String> theFacts) {
        if(theFacts.size() == 0) return;
        String theFact = theFacts.iterator().next();

        String[] cellFacts = theFact.split(" ");
        String cellType = cellFacts[4];
        if(!cellType.equals("b")) {
            Color myColor = null;
            if(cellType.startsWith("light")) myColor = Color.red;
            if(cellType.startsWith("dark")) myColor = Color.blue;
            if(myColor == null) {
                System.err.println("Got weird piece: " + cellType);
                return;
            }

            int width = g.getClipBounds().width;
            int height = g.getClipBounds().height;

            g.setColor(myColor);
            g.fillOval(2, 2, width-4, height-4);

            if(cellType.contains("Pawn")) {
                CommonGraphics.drawChessPiece(g, "bp");
            } else if(cellType.contains("Knight")) {
                CommonGraphics.drawChessPiece(g, "bn");
            } else if(cellType.contains("Checker")) {
                CommonGraphics.drawCheckersPiece(g, "bk");
            } else if(cellType.contains("Disc")) {
                ;
            }
        }
    }

    @Override
    protected void renderMoveSelectionForCell(Graphics g, int xCell, int yCell, String theMove) {
        int width = g.getClipBounds().width;
        int height = g.getClipBounds().height;

        yCell = 8 - yCell;

        String[] moveParts = theMove.split(" ");

        if(moveParts.length == 4) {
            int xDrop = Integer.parseInt(moveParts[2]);
            if(xCell == xDrop) {
                g.setColor(Color.GREEN);
                g.drawRect(3, 3, width-6, height-6);
                g.drawRect(4, 4, width-8, height-8);
            }
        } else if(moveParts.length == 7) {
            int xTarget = Integer.parseInt(moveParts[4]);
            int yTarget = Integer.parseInt(moveParts[5]);
            if(xTarget == xCell && yCell == yTarget) {
                g.setColor(Color.GREEN);
                g.drawRect(3, 3, width-6, height-6);
                g.drawRect(4, 4, width-8, height-8);
                CommonGraphics.fillWithString(g, "X", 3);
            }
        } else if(moveParts.length == 9) {
            int xTarget = Integer.parseInt(moveParts[6]);
            int yTarget = Integer.parseInt(moveParts[7]);
            if(xTarget == xCell && yCell == yTarget) {
                g.setColor(Color.GREEN);
                g.drawRect(3, 3, width-6, height-6);
                g.drawRect(4, 4, width-8, height-8);
                CommonGraphics.fillWithString(g, "X", 3);
            }
        }
    }
}


text:
from __future__ import absolute_import

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import celery_app  # noqa

__author__ = 'AlexStarov'


text:
package io.grpc.spanner;

import com.google.api.core.ApiFuture;
import com.google.cloud.spanner.ErrorCode;
import com.google.cloud.spanner.SpannerException;
import com.google.common.io.CharStreams;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import org.HdrHistogram.Histogram;

public class TestMain {
  private static final Logger logger = Logger.getLogger(TestMain.class.getName());
  private static Histogram histogram = new Histogram(6000L, 1);

  public static void main(String[] args) throws Exception {
    Args argsObj = new Args(args);
    setUpLogs(argsObj);

    SpannerClient spannerClient = new SpannerClient(argsObj);
    logger.log(Level.INFO, "Number of operation is {0}", argsObj.numRpcs);
    logger.log(Level.INFO, "Operation timeout is {0} ms", argsObj.timeoutMs);

    // warm up
    logger.log(Level.INFO, "Warm up start.");
    for (int i = 0; i < 10; ++i) {
      try {
        spannerClient.singleWrite();
      } catch (SpannerException e) {
      }
    }
    for (int i = 0; i < 10; ++i) {
      try {
        spannerClient.singleQuery();
      } catch (SpannerException e) {
      }
    }

    // use sync operation to measure the latency
    for (int i = 0; i < 10; ++i) {
      long start = System.currentTimeMillis();
      try {
        spannerClient.singleQuery();
      } catch (SpannerException e) {
      }
      int latency = (int) (System.currentTimeMillis() - start);
      histogram.recordValue(latency);
    }
    logger.log(
        Level.INFO,
        "Warm up complete. In total {0} RPCs. "
            + "\n         Min  p10  p25  p50  p90  p99  p99.5  p99.9  Max"
            + "\nTime(ms) {1}   {2}   {3}   {4}   {5}   {6}   {7}    {8}    {9}"
            + "\n {10}% samples has < 2x median RTT",
        new Object[] {
          histogram.getTotalCount(),
          histogram.getMinValue(),
          histogram.getValueAtPercentile(10),
          histogram.getValueAtPercentile(25),
          histogram.getValueAtPercentile(50),
          histogram.getValueAtPercentile(90),
          histogram.getValueAtPercentile(99),
          histogram.getValueAtPercentile(99.5),
          histogram.getValueAtPercentile(99.9),
          histogram.getMaxValue(),
          histogram.getPercentileAtOrBelowValue(histogram.getValueAtPercentile(50) * 2)
        });

    // use async method to measure error rate
    int numSucceed = 0;
    int numDeadlineErr = 0;
    int numInternalErr = 0;
    int numOtherErr = 0;
    List<ApiFuture<Void>> readFutureList = new ArrayList<>();
    logger.log(Level.INFO, "Async read starts");

    TcpkillManageThread tcpkillManageThread =
        new TcpkillManageThread(argsObj.logFilename + ".log", argsObj.tcpkillMs);
    if (argsObj.tcpkillMs > 0) {
      tcpkillManageThread.start();
    }
    IptablesManageThread iptablesManageThread =
        new IptablesManageThread(
            argsObj.logFilename + ".log", argsObj.iptablesMs, argsObj.iptablesDurationMs);
    if (argsObj.iptablesMs > 0) {
      iptablesManageThread.start();
    }

    for (int i = 0; i < argsObj.numRpcs; ++i) {
      readFutureList.add(spannerClient.singleQueryAsync());
      Thread.sleep(sampleExpDist(argsObj.intervalMs));
    }
    for (int i = 0; i < readFutureList.size(); ++i) {
      try {
        readFutureList.get(i).get(10_000, TimeUnit.MILLISECONDS);
        numSucceed++;
      } catch (InterruptedException e) {
        logger.log(Level.SEVERE, "Async read RPC closed with IterruptedException");
      } catch (ExecutionException e) {
        logger.log(Level.SEVERE, "Async read RPC closed with ExecutionException");
        SpannerException se = (SpannerException) e.getCause();
        if (se.getErrorCode() == ErrorCode.DEADLINE_EXCEEDED) {
          numDeadlineErr++;
        } else if (se.getErrorCode() == ErrorCode.INTERNAL) {
          numInternalErr++;
        } else {
          numOtherErr++;
        }
      } catch (TimeoutException e) {
        logger.log(Level.SEVERE, "Async read RPC closed with TimeoutException");
      }
    }

    // print result
    double numTotalRPC = numSucceed + numDeadlineErr + numInternalErr + numOtherErr;
    logger.log(
        Level.INFO,
        "{0} async read RPCs completed.\n"
            + " Deadline_exceed error rate is {1}, internal error rate is {2}, other error rate is"
            + " {3}.",
        new Object[] {
          numTotalRPC,
          String.format("%.4f", (numDeadlineErr / numTotalRPC)),
          String.format("%.4f", (numInternalErr / numTotalRPC)),
          String.format("%.4f", (numOtherErr / numTotalRPC))
        });

    tcpkillManageThread.isExit = true;
    iptablesManageThread.isExit = true;
    spannerClient.cleanUp();
  }

  /*
   * This thread manages iptables operation
   */
  private static class IptablesManageThread extends Thread {
    public volatile boolean isExit = false;
    private int iptablesMs;
    private int iptablesDurationMs;
    private String logFilename;

    IptablesManageThread(String name, int interval, int duration) {
      logFilename = name;
      iptablesMs = interval;
      iptablesDurationMs = duration;
    }

    @Override
    public void run() {
      logger.log(Level.FINE, "Iptables manage thread: start, log file is {0}", logFilename);
      while (!isExit) {
        IptablesThread iptablesThread = new IptablesThread(logFilename, iptablesDurationMs);
        iptablesThread.start();
        try {
          Thread.sleep(iptablesMs + iptablesDurationMs);
        } catch (InterruptedException e) {
        }
      }
      logger.log(Level.FINE, "Iptables manage thread: exit.");
    }
  }

  /*
   * This thread use iptables to blackhole a port
   */
  private static class IptablesThread extends Thread {
    private String logFilename;
    private int iptablesDurationMs;

    IptablesThread(String name, int duration) {
      logFilename = name;
      iptablesDurationMs = Math.max(duration, 5000);
    }

    @Override
    public void run() {
      logger.log(Level.FINE, "Iptables thread: start");
      if (logFilename.isEmpty()) {
        logger.log(Level.FINE, "Please specify logFilename and enable fineLog");
        return;
      }
      try {
        String grep_cmd =
            "grep 'OUTBOUND HEADERS' "
                + logFilename
                + " | grep 'ExecuteStreamingSql' | tail -1 | awk '{print $4}' | awk '{print"
                + " substr($0,length($0)-4)}' | tr '\n' ' '";
        Process grep_process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", grep_cmd});
        grep_process.waitFor();
        String port =
            CharStreams.toString(new InputStreamReader(grep_process.getInputStream(), "UTF-8"));
        if (port.isEmpty()) {
          logger.log(Level.INFO, "Iptables thread: could not find a valid port");
          return;
        }

        String blackhole_cmd = "sudo iptables -I INPUT -p tcp --dport " + port + " -j DROP";
        logger.log(Level.FINE, "Iptables thread: blockhole port " + port);
        Process blackhole_process =
            Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", blackhole_cmd});
        blackhole_process.waitFor();

        Thread.sleep(iptablesDurationMs);

        String whitelist_cmd = "sudo iptables -I INPUT -p tcp --dport " + port + " -j ACCEPT";
        logger.log(Level.FINE, "Iptables thread: whitelist port " + port);
        Process whitelist_process =
            Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", whitelist_cmd});
        whitelist_process.waitFor();
      } catch (IOException | InterruptedException e) {
      }
      logger.log(Level.FINE, "Iptables thread: exit");
    }
  }

  /*
   * This thread manages tcpkill operation
   */
  private static class TcpkillManageThread extends Thread {
    public volatile boolean isExit = false;
    private int tcpkillMs;
    private String logFilename;

    TcpkillManageThread(String name, int interval) {
      logFilename = name;
      tcpkillMs = interval;
    }

    @Override
    public void run() {
      logger.log(Level.FINE, "Tcpkill manage thread: start, log file is {0}", logFilename);
      try {
        String cmd = "sudo killall tcpkill";
        Process process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmd});
        process.waitFor();
        logger.log(Level.INFO, "Tcpkill manage thread: killall tcpkill");
      } catch (IOException | InterruptedException e) {
      }
      while (!isExit) {
        TcpkillThread tcpKillThread = new TcpkillThread(logFilename);
        tcpKillThread.start();
        try {
          Thread.sleep(tcpkillMs);
        } catch (InterruptedException e) {
        }
        tcpKillThread.interrupt();
      }
      logger.log(Level.FINE, "Tcpkill manage thread: exit.");
    }
  }

  /*
   * This thread use tcpkill to kill a port
   */
  private static class TcpkillThread extends Thread {
    private String logFilename;

    TcpkillThread(String name) {
      logFilename = name;
    }

    @Override
    public void run() {
      logger.log(Level.FINE, "Tcpkill thread: start");
      if (logFilename.isEmpty()) {
        logger.log(Level.FINE, "Please specify logFilename and enable fineLog");
        return;
      }
      try {
        String grep_cmd =
            "grep 'OUTBOUND HEADERS' "
                + logFilename
                + " | grep 'ExecuteStreamingSql' | tail -1 | awk '{print $4}' | awk '{print"
                + " substr($0,length($0)-4)}' | tr '\n' ' '";
        Process grep_process = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", grep_cmd});
        grep_process.waitFor();
        String port =
            CharStreams.toString(new InputStreamReader(grep_process.getInputStream(), "UTF-8"));
        if (port.isEmpty()) {
          logger.log(Level.INFO, "Tcpkill thread: could not find a valid port");
          return;
        }
        logger.log(Level.INFO, "Tcpkill thread: kill port " + port);
        String tcpkill_cmd = "sudo tcpkill port " + port;
        Process tcpkill_process =
            Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", tcpkill_cmd});
        tcpkill_process.waitFor();
      } catch (IOException | InterruptedException e) {
      }
      logger.log(Level.FINE, "Tcpkill thread: exit");
    }
  }

  /*
   * Sample an exponential distribution
   */
  private static int sampleExpDist(int expectation) {
    return (int) (-expectation * Math.log(1 - (new Random().nextDouble())) + 0.5);
  }

  private static void setUpLogs(Args args) throws IOException {
    if (!args.fineLogs && args.logFilename.isEmpty() && args.logConfig.isEmpty()) {
      return;
    }
    if (!args.logConfig.isEmpty()) {
      File configFile = new File(args.logConfig);
      InputStream configStream = new FileInputStream(configFile);
      LogManager.getLogManager().readConfiguration(configStream);
      return;
    }
    String handlers = "java.util.logging.ConsoleHandler";
    String consoleHandlerProps =
        "java.util.logging.ConsoleHandler.level = ALL\n"
            + "java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter\n";
    String fileHandlerProps = "";
    if (!args.logFilename.isEmpty()) {
      if (args.disableConsoleLog) {
        handlers = "java.util.logging.FileHandler";
        consoleHandlerProps = "";
      } else {
        handlers = handlers + ", java.util.logging.FileHandler";
      }
      fileHandlerProps =
          "java.util.logging.FileHandler.level = ALL\n"
              + "java.util.logging.FileHandler.formatter = java.util.logging.SimpleFormatter\n";
      String filename = args.logFilename;
      if (args.logMaxFiles > 0) {
        filename += ".%g";
        fileHandlerProps += "java.util.logging.FileHandler.count = " + args.logMaxFiles + "\n";
      }
      filename += ".log";
      if (args.logMaxSize > 0) {
        fileHandlerProps += "java.util.logging.FileHandler.limit = " + args.logMaxSize + "\n";
      }
      fileHandlerProps += "java.util.logging.FileHandler.pattern = " + filename + "\n";
    }
    String fineProps = "";
    if (args.fineLogs) {
      fineProps = ".level = FINEST\n";
    }
    LogManager.getLogManager()
        .readConfiguration(
            new ByteArrayInputStream(
                ("handlers="
                        + handlers
                        + "\n"
                        + consoleHandlerProps
                        + fileHandlerProps
                        + fineProps
                        + "java.util.logging.SimpleFormatter.format=%1$tY-%1$tm-%1$td"
                        + " %1$tH:%1$tM:%1$tS.%1$tN %2$s%n%4$s: %5$s%6$s%n\n")
                    .getBytes(StandardCharsets.UTF_8)));
  }
}


text:
#include "config.h"

#include "BucketHeap.h"
#include "TimeUtility.h"

#ifndef OLD_BUCKET_HEAP
// ////////////////////////////////////////////////////////////////////////
// Functions for new BucketHeap
// ////////////////////////////////////////////////////////////////////////
BucketHeap::BucketHeap(RoutingMap* theMap)
{
   m_map = theMap;
   for(uint32 i=0; i < ROWS; ++i ) {
      m_buckets[i] = new Bucket(theMap, COLUMNS);
   }
   // Largecosts bucket.
   m_buckets[ROWS] = new Bucket(theMap, COLUMNS*ROWS);
   reset();
}

BucketHeap::~BucketHeap()
{
   for(uint32 i=0; i < (ROWS + 1) ; ++i ) {
      delete m_buckets[i];
   }
}

void
BucketHeap::tryToEmptyLargeCostsBucket()
{
   uint32 startTime = TimeUtility::getCurrentTime();
   mc2dbg << "[BH]: tryToEmptyLargeCostsBucket m_totalNbrUsed = "
          << m_totalNbrUsed << endl;
   Bucket* oldLargeCosts = m_buckets[ROWS];
   m_buckets[ROWS] = new Bucket(m_map, ROWS*COLUMNS);
   for( RoutingNode* node = oldLargeCosts->dequeue();
        node != NULL;
        node = oldLargeCosts->dequeueUnordered()) {
      enqueue(node);
      // Enqueue increases the value of m_totalNbrUsed
      --m_totalNbrUsed;
   }
   delete oldLargeCosts;
   uint32 stopTime = TimeUtility::getCurrentTime();
   uint32 totTime = stopTime - startTime;
   if ( totTime > 5 ) {
      mc2dbg << "[BH]: tryToEmptyLargeCostsBucket time = "
             << totTime << endl;
   }
}

#else

// ////////////////////////////////////////////////////////////////////////
// Functions for old BucketHeap
// ////////////////////////////////////////////////////////////////////////
BucketHeap::BucketHeap()
{
   m_overflowHasOccurred = false;
   reset();

   for (uint32 i = 0; i < ROWS; i++)
      m_overflowLists[i] = new Head;

   m_largeCostsOverflow = new Head;
}

BucketHeap::~BucketHeap()
{
   for (uint32 i = 0; i < ROWS; i++)
      delete m_overflowLists[i];

   delete m_largeCostsOverflow;
}

void BucketHeap::reset()
{
   if (m_overflowHasOccurred) {
      for (uint32 j = 0; j < ROWS; j++)
         m_overflowLists[j]->clear();

      m_largeCostsOverflow->clear();
      m_overflowHasOccurred    = false;
   }

   for (uint32 i = 0; i < ROWS; i++) {
      m_nbrUsed[i] = 0;
#ifdef UNORDERED_BUCKET_HEAP
      m_nbrDestinations[i] = 0;
#endif
   }

   m_nbrUsedInLargeCostsBucket = 0;
   m_heapStartIndex            = 0;
   m_leastExpectedCostInHeap   = 0;
   m_totalNbrUsed              = 0;
}

void BucketHeap::dump()
{
   cout << "--------------------------------------" << endl;
   cout << "Dumping heap data......." << endl;
   for (uint32 i = 0; i < ROWS; i++) {
      if (m_nbrUsed[i]) {
         cout << "Number used in bucket " << i << ": " << m_nbrUsed[i];
         if (!m_overflowLists[i]->empty())
            cout << "Number in overflowList " << i << ": "
                 << m_overflowLists[i]->cardinal();
         cout << "  ===> ";
      }

      for (uint32 j = 0; j < m_nbrUsed[i]; j++)
         cout << m_matrix[i][j]->getEstCost(m_map) << " ";
      if (m_nbrUsed[i])
         cout << endl;
   }

   cout << "Large costs Bucket: " << m_nbrUsedInLargeCostsBucket <<  endl;
   for (uint32 j = 0; j < m_nbrUsedInLargeCostsBucket; j++)
      cout << m_largeCostsBucket[j]->getEstCost(m_map) << " ";
   if (m_nbrUsedInLargeCostsBucket)
      cout << endl;

   cout << "Current status: " << endl;
   cout << "m_heapStartIndex: " << m_heapStartIndex << endl;
   cout << "m_nbrUsed[m_heapStartIndex]: " << m_nbrUsed[m_heapStartIndex]
        << endl;
   cout << "m_leastExpectedCostInHeap: " << m_leastExpectedCostInHeap
        << endl;
   cout << "m_nbrUsedInLargeCostsBucket: " << m_nbrUsedInLargeCostsBucket
        << endl;
   cout << "m_totalNbrUsed: " << m_totalNbrUsed << endl;
   cout << "--------------------------------------" << endl;
}

void BucketHeap::tryToEmptyLargeCostsBucket()
{
   mc2dbg << "[BH]: tryToEmptyLargeCostsBucket - m_totalNbrUsed = "
          << m_totalNbrUsed << endl;
   uint32 nbrElements  = m_nbrUsedInLargeCostsBucket;
   uint32 index        = 0;
   uint32 costsHandled = m_leastExpectedCostInHeap +
      RANGE_OF_COSTS_IN_HEAP;

   for (uint32 i = 0; i < nbrElements; i++) {
         // Check if the node should not be touched
      uint32 cost = m_largeCostsBucket[index]->getEstCost(m_map);
      if (cost > costsHandled)
            // Just go to next space
         index++;
      else {
            // replace the node with the last in the bucket
         RoutingNode* nodeToEnqueue = m_largeCostsBucket[index];
         m_largeCostsBucket[index] =
            m_largeCostsBucket[--m_nbrUsedInLargeCostsBucket];

            // enqueue the node
         int32 rowIndex;
         if (cost < m_leastExpectedCostInHeap)
            rowIndex = m_heapStartIndex;
         else
            rowIndex = ((cost - m_leastExpectedCostInHeap)
                        >> BUCKET_COST_DIFFERENCE_EXP) + m_heapStartIndex;

         while (rowIndex >= (int32)ROWS)
            rowIndex -= ROWS;

         if (m_nbrUsed[rowIndex] < COLUMNS) {
            m_matrix[rowIndex][m_nbrUsed[rowIndex]++] = nodeToEnqueue;
#ifdef UNORDERED_BUCKET_HEAP
//              if ( nodeToEnqueue->isDest() )
//                 m_nbrDestinations[rowIndex]++;
            m_nbrDestinations[rowIndex] += nodeToEnqueue->isDest();
#endif
         } else {
            overflowEnqueue(nodeToEnqueue, rowIndex);
         }
      }
   }
} // tryToEmptyLargeCostsBucket

void BucketHeap::overflowEnqueue(RoutingNode* routingNode, int32 rowIndex)
{
   if (false && !m_overflowHasOccurred) {
      mc2dbg << "Overflow in BucketHeap, normal heap"
             << "Row " << rowIndex << " nbr over "
             << m_overflowLists[rowIndex]->cardinal()
             <<  endl;
   }

   m_overflowHasOccurred = true;

   OverflowNode* listNode = new OverflowNode(routingNode);
   if (rowIndex != MAX_INT32)
      listNode->into(m_overflowLists[rowIndex]);
   else
      listNode->into(m_largeCostsOverflow);
}

RoutingNode* BucketHeap::overflowDequeue()
{
   RoutingNode* minNode = NULL;
   RoutingNode* tempNode;
   uint32 minCost = MAX_UINT32;

   bool minimumCostNodeFoundInList = true;

      // First browse the list to find its minimum cost node
   OverflowNode* listNode =
      static_cast<OverflowNode*>(m_overflowLists[m_heapStartIndex]->first());
   OverflowNode* minOverflowNode = listNode;

   while (listNode != NULL) {
      tempNode = listNode->getNode();
      if (tempNode->getEstCost(m_map) < minCost) {
         minNode = tempNode;
         minCost = tempNode->getEstCost(m_map);
         minOverflowNode = listNode;
      }
      listNode = static_cast<OverflowNode*>(listNode->suc());
   }

      // Then browse the bucket
      // See dequeue
   uint32 minIndex = 0;
   RoutingNode** minimumCostBucket = m_matrix[m_heapStartIndex];

   for (uint32 i = 0; i < COLUMNS; i++) {
      tempNode = minimumCostBucket[i];
      if (tempNode->getEstCost(m_map) < minCost) {
         minCost  = tempNode->getEstCost();
         minNode  = tempNode;
         minIndex = i;
         minimumCostNodeFoundInList = false;
      }
   }

   if (minimumCostNodeFoundInList) { // Found min in list
      minOverflowNode->out();
      delete minOverflowNode;
   } else { // found min in bucket
      OverflowNode* firstInList = static_cast<OverflowNode*>
         (m_overflowLists[m_heapStartIndex]->first());
      firstInList->out();
      minimumCostBucket[minIndex] = firstInList->getNode();
      delete firstInList;
#ifdef UNORDERED_BUCKET_HEAP
         // Check if the node is a destination and decrease counter.
//           if ( minNode->isDest() )
//              --m_nbrDestinations[minIndex];
      m_nbrDestinations[m_heapStartIndex] +=
         (minimumCostBucket[minIndex]->isDest() == true);
      m_nbrDestinations[m_heapStartIndex] -= (minNode->isDest() == true);
#endif
   }
   return minNode;
} // overflowDequeue

void BucketHeap::emptyLargeCostsOverflow(uint32 costsHandled)
{
      // This is used to print the MC2INFO statements below only once
   static bool firstLargeCostsOverflow = true;

   if (firstLargeCostsOverflow) {
      MC2INFO("Trying to empty the overflow of large costs bucket");
      MC2INFO("This is _very_ seldom seen");
      firstLargeCostsOverflow = false;
   }

   OverflowNode* nodeInList = static_cast<OverflowNode*>
      (m_largeCostsOverflow->first());

   while (nodeInList != NULL) {
      OverflowNode* newNodeInList = static_cast<OverflowNode*>
         (nodeInList->suc());
      RoutingNode* routingNode = nodeInList->getNode();
      uint32 cost = routingNode->getEstCost(m_map);

      if (cost > costsHandled) {
            // keep this node in the overflow bucket/list
         if (m_nbrUsedInLargeCostsBucket < LARGE_COSTS_BUCKET_SIZE) {
            m_largeCostsBucket[m_nbrUsedInLargeCostsBucket++] = routingNode;
            nodeInList->out();
            delete nodeInList;
         }
      }
      else {
            // put this node at its right place in the heap
         int32 rowIndex = ((cost - m_leastExpectedCostInHeap) >>
                           BUCKET_COST_DIFFERENCE_EXP) + m_heapStartIndex;
         while (rowIndex >= (int32) ROWS)
            rowIndex -= ROWS;

         if (m_nbrUsed[rowIndex] < COLUMNS) {
            m_matrix[rowIndex][m_nbrUsed[rowIndex]++] = routingNode;
#ifdef UNORDERED_BUCKET_HEAP
//              if ( routingNode->isDest() )
//                 m_nbrDestinations[rowIndex]++;
            m_nbrDestinations[rowIndex] += ( routingNode->isDest() == true );
#endif
         } else {
            overflowEnqueue(routingNode, rowIndex);
         }

         nodeInList->out();
         delete nodeInList;
      }

      nodeInList = newNodeInList;
   }
} // emptyLargeCostsOverflow

bool BucketHeap::checkHeapConsistency()
{
   bool anyErrors = false;
   uint32 lowestCorrectCost = m_leastExpectedCostInHeap -
      m_heapStartIndex * BUCKET_COST_DIFFERENCE;
   uint32 highestCorrectCost = lowestCorrectCost +
      BUCKET_COST_DIFFERENCE - 1;

      // First check the matrix for wrongly placed elements
   for (uint32 i = 0; i < ROWS; i++) {

      if (m_nbrUsed[i] > 0)
         for (uint32 j = 0; j < m_nbrUsed[i]; j++) {
            uint32 cost = m_matrix[i][j]->getEstCost(m_map);
            if ((cost < lowestCorrectCost) ||
                (cost > highestCorrectCost)) {
               anyErrors = true;
               cout << "Consistency failure" << endl;
               cout << "Bucket, space " << i << ", " << j << endl;
               cout << "Cost range in bucket is between " <<
                  lowestCorrectCost << " and " << highestCorrectCost
                    << endl;
               cout << "Cost found is " << cost << endl;
               RoutingNode* noNode = NULL;
               noNode->getItemID();
            }
         }

      if (!m_overflowLists[i]->empty()) {
         cout << "overflowList " << i << " is not NULL" << endl;
         if (m_overflowHasOccurred) {
            anyErrors = true;
            cout << "overflowList is not empty, but m_overflowHasOccurred"
                 << " says true" << endl;
            RoutingNode* noNode = NULL;
            noNode->getItemID();
         }
      }

      lowestCorrectCost  += BUCKET_COST_DIFFERENCE;
      highestCorrectCost += BUCKET_COST_DIFFERENCE;
   }

      // And now the large costs Bucket
   uint32 minimumTooLargeCost = m_leastExpectedCostInHeap +
      ROWS * BUCKET_COST_DIFFERENCE;
   for (uint32 k = 0; k < m_nbrUsedInLargeCostsBucket; k++)
      if (m_largeCostsBucket[k]->getEstCost(m_map) < minimumTooLargeCost) {
         cout << "Consistency failure" << endl;
         cout << "Space " << k << " in large costs bucket" <<endl;
         cout << "The lowest cost to be too large is " <<
              minimumTooLargeCost << endl;
         cout << "Cost found is " << m_largeCostsBucket[k]->getEstCost(m_map)
              << endl;
         anyErrors = true;
      }

   if (!m_largeCostsOverflow->empty()) {
      MC2INFO("large costs bucket's overflow list is not NULL");
      if (m_overflowHasOccurred) {
         anyErrors = true;
         cout << "This will never happen" << endl;
         RoutingNode* noNode = NULL;
         noNode->getItemID();
      }
   }

   return anyErrors;
} // checkHeapConsistency
#endif


text:
package org.apache.apex.examples.transform;

import java.util.HashMap;
import java.util.Map;

import org.apache.apex.malhar.lib.function.Function;
import org.apache.apex.malhar.lib.function.FunctionOperator;
import org.apache.apex.malhar.lib.function.FunctionOperatorUtil;
import org.apache.hadoop.conf.Configuration;

import com.google.common.annotations.VisibleForTesting;

import com.datatorrent.api.Context;
import com.datatorrent.api.DAG;
import com.datatorrent.api.StreamingApplication;
import com.datatorrent.api.annotation.ApplicationAnnotation;
import com.datatorrent.common.partitioner.StatelessPartitioner;
import com.datatorrent.lib.transform.TransformOperator;

@ApplicationAnnotation(name = "TransformExample")
/**
 * @since 3.7.0
 */
public class SimpleTransformApplication implements StreamingApplication
{
  @VisibleForTesting
  Function.MapFunction<Object, ?> outputFn = FunctionOperatorUtil.CONSOLE_SINK_FN;

  @VisibleForTesting
  POJOGenerator pojoDataGenerator;

  @Override
  public void populateDAG(DAG dag, Configuration conf)
  {
    pojoDataGenerator = dag.addOperator("Input", new POJOGenerator());
    TransformOperator transform = dag.addOperator("Process", new TransformOperator());
    // Set expression map
    Map<String, String> expMap = new HashMap<>();
    expMap.put("name", "{$.firstName}.concat(\" \").concat({$.lastName})");
    expMap.put("age", "(new java.util.Date()).getYear() - {$.dateOfBirth}.getYear()");
    expMap.put("address", "{$.address}.toLowerCase()");
    transform.setExpressionMap(expMap);
    FunctionOperator.MapFunctionOperator<Object, ?> output = dag.addOperator("out",
        new FunctionOperator.MapFunctionOperator<>(outputFn));

    dag.addStream("InputToTransform", pojoDataGenerator.output, transform.input);
    dag.addStream("TransformToOutput", transform.output, output.input);

    dag.setInputPortAttribute(transform.input, Context.PortContext.TUPLE_CLASS, CustomerEvent.class);
    dag.setOutputPortAttribute(transform.output, Context.PortContext.TUPLE_CLASS, CustomerInfo.class);
    setPartitioner(dag,conf,transform);
  }

  void setPartitioner(DAG dag,Configuration conf, TransformOperator transform)
  {
    dag.setAttribute(transform, Context.OperatorContext.PARTITIONER,
        new StatelessPartitioner<TransformOperator>(2));
  }
}


text:
package org.opensmartgridplatform.adapter.domain.microgrids.infra.jms.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import org.opensmartgridplatform.shared.infra.jms.RequestMessage;
import org.opensmartgridplatform.shared.infra.jms.UnknownMessageTypeException;

@Component(value = "domainMicrogridsIncomingOsgpCoreRequestMessageProcessor")
public class OsgpCoreRequestMessageProcessor {

    private static final Logger LOGGER = LoggerFactory.getLogger(OsgpCoreRequestMessageProcessor.class);

    public void processMessage(final RequestMessage requestMessage, final String messageType)
            throws UnknownMessageTypeException {

        final String organisationIdentification = requestMessage.getOrganisationIdentification();
        final String deviceIdentification = requestMessage.getDeviceIdentification();
        final String correlationUid = requestMessage.getCorrelationUid();
        final Object dataObject = requestMessage.getRequest();

        LOGGER.info(
                "Received request message from OSGP-CORE messageType: {} deviceIdentification: {}, organisationIdentification: {}, correlationUid: {}, className: {}",
                messageType, deviceIdentification, organisationIdentification, correlationUid,
                dataObject.getClass().getCanonicalName());

        throw new UnknownMessageTypeException("Unknown JMSType: " + messageType);
    }
}


text:
template class __gnu_cxx::__versa_string<int, std::char_traits<int>,
					 std::allocator<char> >;


text:
Install [KeePassX](https://www.keepassx.org/), a free and open source cross-platform password solution.

## Usage

```puppet
include keepassx
```

## Required Puppet Modules

* `boxen`

## Development

Write code. Run `script/cibuild` to test it. Check the `script`
directory for other useful tools.


text:
#ifndef SERIAL_INTERFACE_H
#define SERIAL_INTERFACE_H

int read_serial(char *msg, int len);

#endif