text:
describe('MatrixCall', function() {
    var $q, $timeout, $rootScope;

    // webrtc deps
    var testPeerConnection = {
        addStream: function(){},
        close: function(){},

        ngsetLocalDescription: function(){},
        ngsetRemoteDescription: function(){},
        ngcreateOffer: function(){},
        ngcreateAnswer: function(){},
        ngsetLocalDescription: function(){}
    };

    var testUserMedia = {
        getVideoTracks: function() {
            return [];
        },
        getAudioTracks: function() {
            return [];
        }
    };

    // dependencies
    var matrixService = {
        getTurnServer: function(){},
        config: function(){},
        sendEvent: function(){}
    };

    var matrixPhoneService = {
        callPlaced: function(){}
    };

    var modelService = {
        getRoom: function(){},
        getMember: function(){}
    };

    var webRtcService = {
        getUserMedia: function(){},
        isWebRTCSupported: function(){},
        isOpenWebRTC: function(){},
        createPeerConnection: function(){},
        newIceCandidate: function(){},
        newRTCSessionDescription: function(){}
    };

    beforeEach(function() {
        // mocked dependencies
        module(function ($provide) {
            $provide.value('matrixService', matrixService);
            $provide.value('matrixPhoneService', matrixPhoneService);
            $provide.value('modelService', modelService);
            $provide.value('webRtcService', webRtcService);
        });

        // tested service
        module('MatrixCall');
    });

    beforeEach(inject(function(_$q_, _$timeout_, _$rootScope_) {
        $q = _$q_;
        $timeout = _$timeout_;
        $rootScope = _$rootScope_;
    }));

    it('should use the TURN servers provided.', inject(
    function(MatrixCall) {
        var turnDefer = $q.defer();
        var turnResponse = {
            password: "pass",
            username: "fwibble",
            ttl: 14234625,
            uris: [
                "turn:uri1?transport=udp",
                "turn:uri2?transport=tcp"
            ]
        };
        spyOn(matrixService, "getTurnServer").and.returnValue(turnDefer.promise);

        // do the HTTP hit
        MatrixCall.getTurnServer();
        turnDefer.resolve({data: turnResponse});
        $rootScope.$digest();

        // make a call
        var roomId = "!foo:bar";
        var call = new MatrixCall(roomId);

        spyOn(webRtcService, "createPeerConnection").and.returnValue(testPeerConnection);
        var offerDefer = $q.defer();
        spyOn(testPeerConnection, "ngcreateOffer").and.returnValue(offerDefer.promise);

        var mediaDefer = $q.defer();
        mediaDefer.resolve(testUserMedia);
        spyOn(webRtcService, "getUserMedia").and.returnValue(mediaDefer.promise);
        call.placeVoiceCall();
        $rootScope.$digest();

        expect(webRtcService.createPeerConnection).toHaveBeenCalledWith(turnResponse);

    }));

    it('should be able to receive an incoming call from an invite.', inject(
    function(MatrixCall) {
        var event = {
            content: {
                offer: {
                    type: "offer",
                    sdp: "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]"
                },
                lifetime: 4252,
                call_id: "2423426452callid"
            },
            age: 1299,
            type: "m.call.invite"
        };

        spyOn(webRtcService, "createPeerConnection").and.returnValue(testPeerConnection);
        var remoteDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetRemoteDescription").and.returnValue(remoteDefer.promise);

        var roomId = "!foo:bar";
        var call = new MatrixCall(roomId);
        call.call_id = event.content.call_id;
        call.initWithInvite(event);
        expect(webRtcService.createPeerConnection).toHaveBeenCalled();

        remoteDefer.resolve({});
        $rootScope.$digest();

        expect(call.state).toEqual("ringing");
        expect(call.direction).toEqual("inbound");
    }));

    it('should be able to answer an incoming call.', inject(
    function(MatrixCall) {
        var roomId = "!foo:bar";
        var userId = "@user:name";

        // setup spies
        spyOn(matrixService, "config").and.returnValue({
            user_id: userId
        });
        spyOn(modelService, "getRoom").and.returnValue({
            room_id: roomId,
            current_room_state: {
                members: {
                    "@user:name": {
                        event: {
                            content: {
                                membership: "join" // already joined the room
                            }
                        }
                    }
                }
            }
        });
        var eventDefer = $q.defer();
        spyOn(matrixService, "sendEvent").and.returnValue(eventDefer.promise);
        var mediaDefer = $q.defer();
        spyOn(webRtcService, "getUserMedia").and.returnValue(mediaDefer.promise);
        spyOn(webRtcService, "createPeerConnection").and.returnValue(testPeerConnection);
        var remoteDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetRemoteDescription").and.returnValue(remoteDefer.promise);
        var createAnswerDefer = $q.defer();
        spyOn(testPeerConnection, "ngcreateAnswer").and.returnValue(createAnswerDefer.promise);
        var localDescDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetLocalDescription").and.callFake(function(desc) {
            testPeerConnection.localDescription = desc; // assign it since it may be used later
            return localDescDefer.promise;
        });

        // the incoming call
        var event = {
            content: {
                offer: {
                    type: "offer",
                    sdp: "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]"
                },
                lifetime: 4252,
                call_id: "2423426452callid"
            },
            age: 1299,
            type: "m.call.invite"
        };

        // the expected response
        var webRtcAnswer = {
            type: "answer",
            sdp: "v=0\r\no=- 6111111111111114 2 IN IP4 127.0.0.1[...]"
        }
        var answerContent = {
            version: 0,
            call_id: "2423426452callid",
            answer: webRtcAnswer
        };

        // recv the call
        var call = new MatrixCall(roomId);
        call.call_id = event.content.call_id;
        call.initWithInvite(event);

        // answer the call
        call.answer();
        expect(call.state).toEqual("wait_local_media");
        expect(call.direction).toEqual("inbound");

        // grant access to media
        mediaDefer.resolve(testUserMedia);
        $rootScope.$digest();
        expect(call.state).toEqual("create_answer");

        // return the answer
        createAnswerDefer.resolve(webRtcAnswer);
        $rootScope.$digest();
        localDescDefer.resolve({});
        $rootScope.$digest();
        expect(call.state).toEqual("connecting");

        // technically don't care about the undefined
        expect(matrixService.sendEvent).toHaveBeenCalledWith(roomId, "m.call.answer", undefined,
        answerContent);

        eventDefer.resolve({data:{event_id:"foo"}});
        $rootScope.$digest();
    }));

    it('should be able to reject an incoming call.', inject(
    function(MatrixCall) {
        var roomId = "!foo:bar";
        var userId = "@user:name";

        // setup spies
        var eventDefer = $q.defer();
        spyOn(matrixService, "sendEvent").and.returnValue(eventDefer.promise);
        var mediaDefer = $q.defer();
        spyOn(webRtcService, "getUserMedia").and.returnValue(mediaDefer.promise);
        spyOn(webRtcService, "createPeerConnection").and.returnValue(testPeerConnection);
        var remoteDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetRemoteDescription").and.returnValue(remoteDefer.promise);
        var createAnswerDefer = $q.defer();
        spyOn(testPeerConnection, "ngcreateAnswer").and.returnValue(createAnswerDefer.promise);
        var localDescDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetLocalDescription").and.callFake(function(desc) {
            testPeerConnection.localDescription = desc; // assign it since it may be used later
            return localDescDefer.promise;
        });
        spyOn(testPeerConnection, "close");

        // the incoming call
        var event = {
            content: {
                offer: {
                    type: "offer",
                    sdp: "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]"
                },
                lifetime: 4252,
                call_id: "2423426452callid"
            },
            age: 1299,
            type: "m.call.invite"
        };

        // the expected hangup content
        var hangupContent = {
            version: 0,
            call_id: "2423426452callid",
            reason: "some reason"
        };

        // recv the call
        var call = new MatrixCall(roomId);
        call.call_id = event.content.call_id;
        call.initWithInvite(event);

        // pretend to attach a hangup listener
        call.onHangup = function(){};
        spyOn(call, "onHangup");

        // hangup the call
        call.hangup("some reason");
        expect(call.state).toEqual("ended");
        expect(call.direction).toEqual("inbound");
        expect(testPeerConnection.close).toHaveBeenCalled();
        expect(call.onHangup).toHaveBeenCalled();

        // technically don't care about the undefined
        expect(matrixService.sendEvent).toHaveBeenCalledWith(roomId, "m.call.hangup", undefined, hangupContent);
    }));

    it('should be able to place an outgoing voice call.', inject(
    function(MatrixCall) {
        var roomId = "!foo:bar";
        var userId = "@user:name";

        // setup spies
        spyOn(matrixService, "config").and.returnValue({
            user_id: userId
        });
        spyOn(modelService, "getRoom").and.returnValue({
            room_id: roomId,
            current_room_state: {
                members: {
                    "@user:name": {
                        event: {
                            content: {
                                membership: "join" // already joined the room
                            }
                        }
                    }
                }
            }
        });
        var eventDefer = $q.defer();
        spyOn(matrixService, "sendEvent").and.returnValue(eventDefer.promise);
        var mediaDefer = $q.defer();
        spyOn(webRtcService, "getUserMedia").and.returnValue(mediaDefer.promise);
        spyOn(webRtcService, "createPeerConnection").and.returnValue(testPeerConnection);
        var remoteDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetRemoteDescription").and.returnValue(remoteDefer.promise);
        var createOfferDefer = $q.defer();
        spyOn(testPeerConnection, "ngcreateOffer").and.returnValue(createOfferDefer.promise);
        var localDescDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetLocalDescription").and.callFake(function(desc) {
            testPeerConnection.localDescription = desc; // assign it since it may be used later
            return localDescDefer.promise;
        });

        // the incoming call
        var event = {
            content: {
                offer: {
                    type: "offer",
                    sdp: "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]"
                },
                lifetime: 4252,
                call_id: "2423426452callid"
            },
            age: 1299,
            type: "m.call.invite"
        };

        var webRtcOffer = {
            type: "offer",
            sdp: "v=0\r\no=- 6111111111111114 2 IN IP4 127.0.0.1[...]"
        }
        var offerContent = {
            version: 0,
            offer: webRtcOffer
        };

        // place the call
        var call = new MatrixCall(roomId);
        call.placeVoiceCall();
        expect(call.state).toEqual("wait_local_media");
        expect(call.direction).toEqual("outbound");

        // allow access to mic
        mediaDefer.resolve(testUserMedia);
        $rootScope.$digest();
        expect(call.state).toEqual("create_offer");

        // get the offer
        createOfferDefer.resolve(webRtcOffer);
        $rootScope.$digest();
        localDescDefer.resolve({});
        $rootScope.$digest();

        expect(call.state).toEqual("invite_sent");
        expect(matrixService.sendEvent).toHaveBeenCalledWith(roomId, "m.call.invite", undefined,
        jasmine.objectContaining(offerContent));
    }));

    it('should be able to hangup an outgoing call.', inject(
    function(MatrixCall) {
        var roomId = "!foo:bar";
        var userId = "@user:name";

        // setup spies
        spyOn(matrixService, "config").and.returnValue({
            user_id: userId
        });
        spyOn(modelService, "getRoom").and.returnValue({
            room_id: roomId,
            current_room_state: {
                members: {
                    "@user:name": {
                        event: {
                            content: {
                                membership: "join" // already joined the room
                            }
                        }
                    }
                }
            }
        });
        var eventDefer = $q.defer();
        spyOn(matrixService, "sendEvent").and.returnValue(eventDefer.promise);
        var mediaDefer = $q.defer();
        spyOn(webRtcService, "getUserMedia").and.returnValue(mediaDefer.promise);
        spyOn(webRtcService, "createPeerConnection").and.returnValue(testPeerConnection);
        var remoteDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetRemoteDescription").and.returnValue(remoteDefer.promise);
        var createOfferDefer = $q.defer();
        spyOn(testPeerConnection, "ngcreateOffer").and.returnValue(createOfferDefer.promise);
        var localDescDefer = $q.defer();
        spyOn(testPeerConnection, "ngsetLocalDescription").and.callFake(function(desc) {
            testPeerConnection.localDescription = desc; // assign it since it may be used later
            return localDescDefer.promise;
        });
        spyOn(testPeerConnection, "close");

        // the incoming call
        var event = {
            content: {
                offer: {
                    type: "offer",
                    sdp: "v=0\r\no=- 6584580628695956864 2 IN IP4 127.0.0.1[...]"
                },
                lifetime: 4252,
                call_id: "2423426452callid"
            },
            age: 1299,
            type: "m.call.invite"
        };

        var webRtcOffer = {
            type: "offer",
            sdp: "v=0\r\no=- 6111111111111114 2 IN IP4 127.0.0.1[...]"
        }
        var offerContent = {
            version: 0,
            offer: webRtcOffer
        };
        var hangupContent = {
            version: 0,
            reason: "a reason"
        };

        // place the call
        var call = new MatrixCall(roomId);
        call.placeVoiceCall();

        // pretend to attach a hangup listener
        call.onHangup = function(){};
        spyOn(call, "onHangup");

        // allow access to mic
        mediaDefer.resolve(testUserMedia);
        $rootScope.$digest();

        // get the offer
        createOfferDefer.resolve(webRtcOffer);
        $rootScope.$digest();
        localDescDefer.resolve({});
        $rootScope.$digest();

        // hangup
        call.hangup("a reason");
        expect(call.state).toEqual("ended");
        expect(call.direction).toEqual("outbound");
        expect(testPeerConnection.close).toHaveBeenCalled();
        expect(call.onHangup).toHaveBeenCalled();

        // technically don't care about the undefined
        expect(matrixService.sendEvent).toHaveBeenCalledWith(roomId, "m.call.hangup", undefined,
        jasmine.objectContaining(hangupContent));
    }));
});


text: const React = require('#flow-internal-react-server-module');

redpajama_set_name: RedPajamaGithub


text:
/* @test
   @bug 4090254
   @summary Test StringReader ready method*/

import java.io.*;

/**
 * This class tests to see if StringReader generates
 * an exception if ready is called on closed stream
 */

public class ClosedReady {

    public static void main( String argv[] ) throws Exception {

        StringReader in = new StringReader("aaaaaaaaaaaaaaa");
        in.read();
        in.close();

        try {
            in.ready(); // IOException should be thrown here
            throw new RuntimeException(" No exception during read on closed stream");
        }
        catch (IOException e) {
            System.err.println("Test passed: IOException is thrown");
        }
    }
}


text:
package org.apache.druid.segment.join;

import org.apache.druid.common.config.NullHandling;
import org.apache.druid.query.monomorphicprocessing.RuntimeShapeInspector;
import org.apache.druid.segment.ColumnValueSelector;

import javax.annotation.Nullable;
import java.util.function.BooleanSupplier;

/**
 * A {@link ColumnValueSelector} that wraps a base selector but might also generate null values on demand. This
 * is used for "righty" joins (see {@link JoinType#isRighty()}), which may need to generate nulls on the left-hand side.
 */
public class PossiblyNullColumnValueSelector<T> implements ColumnValueSelector<T>
{
  private final ColumnValueSelector<T> baseSelector;
  private final BooleanSupplier beNull;
  @Nullable
  private final T nullValue;

  PossiblyNullColumnValueSelector(final ColumnValueSelector<T> baseSelector, final BooleanSupplier beNull)
  {
    this.baseSelector = baseSelector;
    this.beNull = beNull;
    this.nullValue = NullHandling.defaultValueForClass(baseSelector.classOfObject());
  }

  @Override
  public double getDouble()
  {
    return beNull.getAsBoolean() ? NullHandling.ZERO_DOUBLE : baseSelector.getDouble();
  }

  @Override
  public float getFloat()
  {
    return beNull.getAsBoolean() ? NullHandling.ZERO_FLOAT : baseSelector.getFloat();
  }

  @Override
  public long getLong()
  {
    return beNull.getAsBoolean() ? NullHandling.ZERO_LONG : baseSelector.getLong();
  }

  @Override
  public void inspectRuntimeShape(RuntimeShapeInspector inspector)
  {
    baseSelector.inspectRuntimeShape(inspector);
    inspector.visit("beNull", beNull);
  }

  @Nullable
  @Override
  public T getObject()
  {
    return beNull.getAsBoolean() ? nullValue : baseSelector.getObject();
  }

  @Override
  public Class<? extends T> classOfObject()
  {
    return baseSelector.classOfObject();
  }

  @Override
  public boolean isNull()
  {
    return beNull.getAsBoolean() || baseSelector.isNull();
  }
}


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

<TITLE>
org.apache.hadoop.security.authentication.util (Hadoop 1.0.3.16 API)
</TITLE>

<META NAME="date" CONTENT="2012-10-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

org.apache.hadoop.security.authentication.util

Classes

KerberosUtil

Signer

Exceptions

SignerException


text:
<describe bug fix or new feature>

Fixes: #


text:
The enyo minifier uses NodeJS, [UglifyJS](http://github.com/mishoo/uglifyjs) and the enyo dependency loader to compress any enyo package into a minimized form.

## Invocation
For convenience, there are both Windows and Unix versions of the script that invokes the node tool.
They follow the same invocation:

	path/to/enyo/tools/minify/minify.sh package.js -output /relative/path/to/build/dir/buildfilename

An example for lib/onyx, a UI widget set, run from `lib/onyx/minify/minify.sh`, building to `lib/onyx/build`

	../../../enyo/tools/minify/minify.sh -output ../build/onyx package.js

The last parameter in the output path, if not ending in a `/`, will be used as the name of the output build files.
The `package.js` file must be in the same directory as the invocation.

For convenience, packages should include a `minify` folder with both a Windows batch and Unix shell script that runs the minifier.


text:
export GOOGLE_APPLICATION_CREDENTIALS=../../key.json
find ../src/content/en/updates/2018/01/ -iname "*.md" |
while read filename
do
  node translate.js -s $filename -t hi,fr,es,ja,de,vi,ru,id  \;
done

#find src/content/en/updates/2018/01/ -iname "*.md" -exec node translate.js -s '{}' -t hi,fr,es,ja,de,vi,ru,id \;


text:
v_cryptor = Utils.Cryptor('omnidb', 'iso-8859-1')

p_database.v_connection.Open()
p_database.v_connection.Execute('BEGIN TRANSACTION;')

v_table = p_database.v_connection.Query('SELECT user_id, password FROM users;')
for v_row in v_table.Rows:
    v_hashed_pwd = v_cryptor.Hash(v_row['password'])
    p_database.v_connection.Execute("UPDATE users SET password = '{0}' WHERE user_id = {1};".format(v_hashed_pwd, v_row['user_id']))

p_database.v_connection.Execute('''
    CREATE TABLE connections_bak AS
    SELECT *
    FROM connections;
''')

p_database.v_connection.Execute('DROP TABLE connections;')

p_database.v_connection.Execute('''
    CREATE TABLE connections (
        conn_id integer,
        user_id integer,
        dbt_st_name varchar(40),
        server varchar(500),
        port varchar(20),
        service varchar(500),
        user varchar(100),
        alias varchar(100),
        ssh_server varchar(500),
        ssh_port varchar(20),
        ssh_user varchar(100),
        ssh_password varchar(100),
        ssh_key text,
        use_tunnel integer,
        constraint pk_connections primary key (conn_id),
        constraint connections_fk_0 foreign key (user_id) references users (user_id)  on update CASCADE  on delete CASCADE,
        constraint connections_fk_1 foreign key (dbt_st_name) references db_type (dbt_st_name)  on update CASCADE  on delete CASCADE
    );
''')

p_database.v_connection.Execute('''
    INSERT INTO connections (
        conn_id,
        user_id,
        dbt_st_name,
        server,
        port,
        service,
        user,
        alias,
        ssh_server,
        ssh_port,
        ssh_user,
        ssh_password,
        ssh_key,
        use_tunnel
    )
    SELECT conn_id,
           user_id,
           dbt_st_name,
           server,
           port,
           service,
           user,
           alias,
           ssh_server,
           ssh_port,
           ssh_user,
           ssh_password,
           ssh_key,
           use_tunnel
    FROM connections_bak;
''')

p_database.v_connection.Execute('DROP TABLE connections_bak;')

p_database.v_connection.Execute('''
    CREATE TABLE cgroups (
      cgroup_id integer primary key,
      user_id integer references users (user_id) ON UPDATE CASCADE ON DELETE CASCADE,
      cgroup_name text
    );
''')

p_database.v_connection.Execute('''
    CREATE TABLE cgroups_connections (
        cgroup_id integer references cgroups (cgroup_id) ON UPDATE CASCADE ON DELETE CASCADE,
        conn_id integer references connections (conn_id) ON UPDATE CASCADE ON DELETE CASCADE,
        primary key (cgroup_id, conn_id)
    );
''')

p_database.v_connection.Execute("UPDATE version SET ver_id = '2.13.0';")

p_database.v_connection.Execute('COMMIT;')
p_database.v_connection.Close()
p_database.v_connection.Execute('VACUUM;')


text:
The Dancing Photographer
====================

My own photography site and blog.

This site uses [jekyll](https://jekyllrb.com/) with the [Photorama](https://github.com/sunbliss/photorama) theme.

##License

Unless otherwise noted, all photos are copyright Gerrit Vermeulen. If you would like to use them, please contact me (contact details can be found on the site).

The MIT License (MIT)

Copyright (c) 2014 Filippo Oretti, Dario Andrei

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
var Q = require('q');

var phantom = require('phantom');

var sitepage = null;
var phInstance = null;

function timeout(t){
    var defer = Q.defer();

    return function(res){
        setTimeout(()=>defer.resolve(res), t);
        return defer.promise;
    }
}

var customHeaders = {
    'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:46.0) Gecko/20100101 Firefox/46.0"
};

function RequestWebpage(url){
    return phantom.create()
    .then(instance => {
        phInstance = instance;
        return instance.createPage();
    })
    .then(page => {
        // This is how you set other header variables

        sitepage = page;
        page.on('onResourceRequested', function (requestData, networkRequest) {
            console.log(requestData.url);
            console.log(requestData);
            // networkRequest.abort();
        });
        page.on('onResourceReceived', function(response) {
            // console.log('Receive ' + JSON.stringify(response, undefined, 4));
            // console.log('R : ', response.status);
            if(response.redirectURL){
                console.log('Receive ' + JSON.stringify(response, undefined, 4));
                console.log('R : ', response.status);
                console.log('redirectURL : ', response.redirectURL);
            }
        });

        var process = require('process');
        page.on('onConsoleMessage', function(msg) {
            process.stdout.write(`console: ${msg}\n`);
        });

        page.on('onResourceError', function(resourceError) {
            console.error('= onResourceError()');
            console.error('  - unable to load url: "' + resourceError.url + '"');
            console.error('  - error code: ' + resourceError.errorCode + ', description: ' + resourceError.errorString );
        });

        page.on('onError', function(msg, trace) {
            console.error('= onError()');
            var msgStack = ['  ERROR: ' + msg];
            if (trace) {
                msgStack.push('  TRACE:');
                trace.forEach(function(t) {
                    msgStack.push('    -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
                });
            }
            console.error(msgStack.join('\n'));
        });

        page.on('onNavigationRequested', function(_url, type, willNavigate, main) {
            console.log("redirect caught", {main, type, _url, url})
            if (main && _url!=url) {
                myurl = _url;
                page.close()
            }
        });

        page.on('onUrlChanged', function(targetUrl) {
            console.log('New URL: ' + targetUrl);
        });

        page.on('onLoadStarted', function() {
            console.log('onLoadStarted', arguments);
            page.evaluate(function() {
                return window.location.href;
            })
            .then(currentUrl=>console.log('currentUrl', currentUrl));
        });

        return Q.all([
            , page.property('customHeaders', customHeaders)
            // ,return page.open('https://stackoverflow.com/')
            , page.setting('resourceTimeout', 3000)
            , page.setting('javascriptEnabled', true)
            , page.setting('loadImages', false)
            , page.setting('navigationLocked', true)
        ])
    })
    .then(()=>{
        var page = sitepage;

        var defer = Q.defer();
        page.on('onLoadFinished', function(status){
            console.log('phantom Status: ' + status);
            if(status == 'fail'){
                console.log(arguments);
                defer.reject(status);
            }
            else{
                defer.resolve(status);
            }
        })

        return page.open(url)
        .then(()=>{
            return defer.promise;
        })
        .then(timeout(2000))
        .then(()=>{
            return page.evaluate(function(){
                return document.documentElement.outerHTML;
            })
        })
    })
    // .then(status => {
    //     // console.log('document', sitepage.property('document'));
    //     return sitepage.property('content');
    // })
    .then(content => {
        console.log('phantom close');
        // console.log(content);
        sitepage.close();
        phInstance.exit();
        return content;
    })
    .catch(error => {
        console.log(error);
        phInstance.exit();
    });
}

module.exports = RequestWebpage;


text:
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    for (int i = 0; i<12; i++) {

        int R = i / COL;
        int C = i % COL;

        UIView *appview = [[UIView alloc] initWithFrame:CGRectMake(20, 20, 80, 90)];

        appview.backgroundColor = [UIColor redColor];

        [self.view addSubview:appview];

    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
**Bower**

    $ bower install fairbox.js --save

**Npm**

    $ npm install fairbox.js --save

----------
## Getting Started ##
- **Installation**
 - **Include the CSS in your `<head>` tag :**

		    <link href="path/to/fairbox.css rel="stylesheet">

 - **Include the JS after your `</body>` tag in the bottom :**

- **Don't forget to load jQuery !**

----------
**Initialize with html**

 - **Add a `data-fairbox` on your tag `<img>` tag:**

 - **Youtube video add  `data-youtube` and put your Youtube_ID video:**

	 - youtube.com/watch?v="**Youtube_ID**"

----------
## Options ##

**You can change option**

	    FairBox.option({
			'disablePreview' : true,
			'disableSlider' : true
		})

| Option              | Default        | Description                                                    |
| ------------------- |:-------------: | :--------------------------------------------------------------:|
| disablePreview      | false          | preview menu with miniature of your image in the popup |
| disableSlider       | false          | switch next image or previous image                        |

----------
## Licence ##

MIT Licence


text: export { WarningFilled as default } from "./";


text:
package operators

import (
	"context"
	"fmt"
	"regexp"
	"strings"

	g "github.com/onsi/ginkgo"
	"github.com/openshift/origin/pkg/test/ginkgo/result"
	exutil "github.com/openshift/origin/test/extended/util"
	v1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/kube-openapi/pkg/util/sets"
	e2e "k8s.io/kubernetes/test/e2e/framework"
)

var _ = g.Describe("[sig-arch] Managed cluster", func() {
	oc := exutil.NewCLIWithoutNamespace("operator-resources")

	// Pods that are part of the control plane should set both cpu and memory requests, but require an exception
	// to set limits on memory (CPU limits are generally not allowed). This enforces the rules described in
	// https://github.com/openshift/enhancements/blob/master/CONVENTIONS.md#resources-and-limits.
	//
	// This test enforces all pods in the openshift-*, kube-*, and default namespace have requests set for both
	// CPU and memory, and no limits set. Known bugs will transform this to a flake. Otherwise the test will fail.
	//
	// Release architects can justify an exception with text but must ensure CONVENTIONS.md is updated to document
	// why the exception is granted.
	g.It("should set requests but not limits", func() {
		pods, err := oc.KubeFramework().ClientSet.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{})
		if err != nil {
			e2e.Failf("unable to list pods: %v", err)
		}

		// pods that have a bug opened, every entry here must have a bug associated
		knownBrokenPods := map[string]string{
			//"<apiVersion>/<kind>/<namespace>/<name>/(initContainer|container)/<container_name>/<violation_type>": "<url to bug>",
		}

		// pods with an exception granted, the value should be the justification and the approver (a release architect)
		exceptionGranted := map[string]string{
			//"<apiVersion>/<kind>/<namespace>/<name>/(initContainer|container)/<container_name>/<violation_type>": "<github handle of approver>: <brief description of the reason for the exception>",

			// CPU limits on these containers may be inappropriate in the future
			"v1/Pod/openshift-etcd/installer-<revision>-<node>/container/installer/limit[cpu]":                          "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-etcd/installer-<revision>-<node>/container/installer/limit[memory]":                       "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-etcd/revision-pruner-<revision>-<node>/container/pruner/limit[cpu]":                       "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-etcd/revision-pruner-<revision>-<node>/container/pruner/limit[memory]":                    "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-apiserver/installer-<revision>-<node>/container/installer/limit[cpu]":                "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-apiserver/installer-<revision>-<node>/container/installer/limit[memory]":             "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-apiserver/revision-pruner-<revision>-<node>/container/pruner/limit[cpu]":             "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-apiserver/revision-pruner-<revision>-<node>/container/pruner/limit[memory]":          "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-controller-manager/installer-<revision>-<node>/container/installer/limit[cpu]":       "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-controller-manager/installer-<revision>-<node>/container/installer/limit[memory]":    "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-controller-manager/revision-pruner-<revision>-<node>/container/pruner/limit[cpu]":    "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-controller-manager/revision-pruner-<revision>-<node>/container/pruner/limit[memory]": "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-scheduler/installer-<revision>-<node>/container/installer/limit[cpu]":                "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-scheduler/installer-<revision>-<node>/container/installer/limit[memory]":             "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-scheduler/revision-pruner-<revision>-<node>/container/pruner/limit[cpu]":             "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",
			"v1/Pod/openshift-kube-scheduler/revision-pruner-<revision>-<node>/container/pruner/limit[memory]":          "smarterclayton: run-once pod with very well-known resource usage, does not vary based on workload or cluster size",

			"apps/v1/Deployment/openshift-monitoring/thanos-querier/container/thanos-query/limit[memory]": "smarterclayton: granted a temporary exception (reasses in 4.10) until Thanos can properly control resource usage from arbitrary queries",
		}

		reNormalizeRunOnceNames := regexp.MustCompile(`^(installer-|revision-pruner-)[\d]+-`)
		reNormalizeRetryNames := regexp.MustCompile(`-retry-[\d]+-`)

		waitingForFix := sets.NewString()
		notAllowed := sets.NewString()
		possibleFuture := sets.NewString()
		for _, pod := range pods.Items {
			// Only pods in the openshift-*, kube-*, and default namespaces are considered
			if !strings.HasPrefix(pod.Namespace, "openshift-") && !strings.HasPrefix(pod.Namespace, "kube-") && pod.Namespace != "default" {
				continue
			}
			// Must-gather runs are excluded from this rule
			if strings.HasPrefix(pod.Namespace, "openshift-must-gather") {
				continue
			}
			// var controlPlaneTarget bool
			// selector := labels.SelectorFromSet(pod.Spec.NodeSelector)
			// if !selector.Empty() && selector.Matches(labels.Set(map[string]string{"node-role.kubernetes.io/master": ""})) {
			// 	controlPlaneTarget = true
			// }

			// Find a unique string that identifies who creates the pod, or the pod itself
			var controller string
			for _, ref := range pod.OwnerReferences {
				if ref.Controller == nil || !*ref.Controller {
					continue
				}
				// simple hack to make the rules cluster better, if we get new hierarchies just add more checks here
				switch ref.Kind {
				case "ReplicaSet":
					if i := strings.LastIndex(ref.Name, "-"); i != -1 {
						name := ref.Name[0:i]
						if deploy, err := oc.KubeFramework().ClientSet.AppsV1().Deployments(pod.Namespace).Get(context.Background(), name, metav1.GetOptions{}); err == nil {
							ref.Name = deploy.Name
							ref.Kind = "Deployment"
							ref.APIVersion = "apps/v1"
						}
					}
				case "Job":
					if pod.Namespace == "openshift-marketplace" {
						ref.Name = "<batch_job>"
					}
				case "Node":
					continue
				}
				controller = fmt.Sprintf("%s/%s/%s/%s", ref.APIVersion, ref.Kind, pod.Namespace, ref.Name)
				break
			}
			if len(controller) == 0 {
				if len(pod.GenerateName) > 0 {
					name := strings.ReplaceAll(pod.GenerateName, pod.Spec.NodeName, "<node>")
					if pod.Spec.RestartPolicy != v1.RestartPolicyAlways {
						name = reNormalizeRunOnceNames.ReplaceAllString(name, "$1<revision>")
					}
					controller = fmt.Sprintf("v1/Pod/%s/%s", pod.Namespace, name)
				} else {
					name := strings.ReplaceAll(pod.Name, pod.Spec.NodeName, "<node>")
					if pod.Spec.RestartPolicy != v1.RestartPolicyAlways {
						name = reNormalizeRunOnceNames.ReplaceAllString(name, "$1<revision>-")
					}
					controller = fmt.Sprintf("v1/Pod/%s/%s", pod.Namespace, name)
				}
			}

			// Remove -retry-#- for, e.g. openshift-etcd/installer-<revision>-retry-1-<node>
			controller = reNormalizeRetryNames.ReplaceAllString(controller, "-")

			// These rules apply to both init and regular containers
			for containerType, containers := range map[string][]v1.Container{
				"initContainer": pod.Spec.InitContainers,
				"container":     pod.Spec.Containers,
			} {
				for _, c := range containers {
					key := fmt.Sprintf("%s/%s/%s", controller, containerType, c.Name)

					// Pods may not set limits
					if len(c.Resources.Limits) > 0 {
						for resource, v := range c.Resources.Limits {
							if resource == "management.workload.openshift.io/cores" { // limits are allowed on management.workload.openshift.io/cores resources
								continue
							}
							rule := fmt.Sprintf("%s/%s[%s]", key, "limit", resource)
							if len(exceptionGranted[rule]) == 0 {
								violation := fmt.Sprintf("%s defines a limit on %s of %s which is not allowed", key, resource, v.String())
								if bug, ok := knownBrokenPods[rule]; ok {
									waitingForFix.Insert(fmt.Sprintf("%s (bug %s)", violation, bug))
								} else {
									notAllowed.Insert(fmt.Sprintf("%s (rule: %q)", violation, rule))
								}
							}
						}
					}

					annotationForPreferringManagementCores := "target.workload.openshift.io/management"
					wpPodAnnotation := strings.Replace(pod.Annotations[annotationForPreferringManagementCores], " ", "", -1) // some pods have a space after the : in their annotation definition

					// Pods must have at least CPU and memory requests
					for _, resource := range []string{"cpu", "memory"} {
						if len(wpPodAnnotation) > 0 && resource == "cpu" { // don't check for CPU request if the pod has a WP annotation
							continue
						}
						v := c.Resources.Requests[v1.ResourceName(resource)]
						if !v.IsZero() {
							continue
						}
						rule := fmt.Sprintf("%s/%s[%s]", key, "request", resource)
						violation := fmt.Sprintf("%s does not have a %s request", key, resource)
						if len(exceptionGranted[rule]) == 0 {
							if bug, ok := knownBrokenPods[rule]; ok {
								waitingForFix.Insert(fmt.Sprintf("%s (bug %s)", violation, bug))
							} else {
								if containerType == "initContainer" {
									possibleFuture.Insert(fmt.Sprintf("%s (candidate rule: %q)", violation, rule))
								} else {
									notAllowed.Insert(fmt.Sprintf("%s (rule: %q)", violation, rule))
								}
							}
						}
					}
				}
			}
		}

		// Some things we may start checking in the future
		if len(possibleFuture) > 0 {
			e2e.Logf("Pods in platform namespaces had resource request/limit that we may enforce in the future:\n\n%s", strings.Join(possibleFuture.List(), "\n"))
		}

		// Users are not allowed to add new violations
		if len(notAllowed) > 0 {
			e2e.Failf("Pods in platform namespaces are not following resource request/limit rules or do not have an exception granted:\n  %s", strings.Join(notAllowed.List(), "\n  "))
		}

		// All known bugs are listed as flakes so we can see them as dashboards
		if len(waitingForFix) > 0 {
			result.Flakef("Pods in platform namespaces had known broken resource request/limit that have not been resolved:\n\n%s", strings.Join(waitingForFix.List(), "\n"))
		}
	})
})


text:
class Notification < ApplicationRecord

  belongs_to :notificationtype

  has_attached_file :image, styles: { medium: "600x350", thumb: "100x100", card: "450x250", show: "300x300" }
  # Validate content type
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

   # validations
  validates :title, presence: true
  validates :message, presence: true

  default_scope { order(updated_at: :desc) }

end


text:
#ifndef CLIF_EXAMPLES_WRAPPOD_WRAPPOD_H_
#define CLIF_EXAMPLES_WRAPPOD_WRAPPOD_H_

#include <string>
#include <vector>

namespace clif_example {
namespace wrappod {

struct MyClass {
 public:
  int a;  // Available in Python as an int value
  float f;  // Available in Python as a float value
  std::string s;  // Available in Python as a bytes object

  std::vector<int> v;  // Available in Python as a list of int values via
                       // getter and setter methods.
  std::pair<int, int> p;  // Available in Python as a 2-tuple

  double d;  // Not available in wrapped Python.
};

}  // namespace wrappod
}  // namespace clif_example

#endif  // CLIF_EXAMPLES_WRAPPOD_WRAPPOD_H_


text:
package helpers;

public class Flags {

	// Write SAMLRaiderDebug.log and load example certificates
	public static final boolean DEBUG = false;

}


text:
var http = require('http');
var url = require('url');
var azure = require('azure-storage');
var blobSvc = azure.createBlobService();

http.createServer(function (req, res) {
	var query = url.parse(req.url, true).query;

	if (typeof query.file === 'undefined') {
		res.end("Must specify querystring (e.g ?file=myfile.txt)");
	} else {
		res.setHeader('Content-disposition', 'attachment; filename='+query.file);
		blobSvc.createReadStream('testcontainer', query.file).pipe(res);
	}
}).listen(3333);

console.log("Server running at http://localhost:3333/");


text:
package net.zencal.snuffles.domain.dubtrack;

public class DubSong {
    protected String _id;
    protected String name;
    protected String description;
    protected String type;
    protected String fkid;
    protected String streamUrl;
    protected String fileUrl;
    protected String songArtist;
    protected Long songLength;
    protected String songBitrate;
    protected String songMeta;
    protected Long created;
    protected Integer updub;
    protected Integer downdub;
    protected String userid;
    protected Integer __v;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getFkid() {
        return fkid;
    }

    public void setFkid(String fkid) {
        this.fkid = fkid;
    }

    public String getStreamUrl() {
        return streamUrl;
    }

    public void setStreamUrl(String streamUrl) {
        this.streamUrl = streamUrl;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    public String getSongArtist() {
        return songArtist;
    }

    public void setSongArtist(String songArtist) {
        this.songArtist = songArtist;
    }

    public Long getSongLength() {
        return songLength;
    }

    public void setSongLength(Long songLength) {
        this.songLength = songLength;
    }

    public String getSongBitrate() {
        return songBitrate;
    }

    public void setSongBitrate(String songBitrate) {
        this.songBitrate = songBitrate;
    }

    public String getSongMeta() {
        return songMeta;
    }

    public void setSongMeta(String songMeta) {
        this.songMeta = songMeta;
    }

    public Long getCreated() {
        return created;
    }

    public void setCreated(Long created) {
        this.created = created;
    }

    public Integer getUpdub() {
        return updub;
    }

    public void setUpdub(Integer updub) {
        this.updub = updub;
    }

    public Integer getDowndub() {
        return downdub;
    }

    public void setDowndub(Integer downdub) {
        this.downdub = downdub;
    }

    public String getUserid() {
        return userid;
    }

    public void setUserid(String userid) {
        this.userid = userid;
    }

    public Integer get__v() {
        return __v;
    }

    public void set__v(Integer __v) {
        this.__v = __v;
    }

    @Override
    public String toString() {
        return "DubSong{" +
                "_id='" + _id + '\'' +
                ", name='" + name + '\'' +
                ", type='" + type + '\'' +
                ", fkid='" + fkid + '\'' +
                ", streamUrl='" + streamUrl + '\'' +
                ", fileUrl='" + fileUrl + '\'' +
                ", songArtist='" + songArtist + '\'' +
                ", songLength=" + songLength +
                ", songBitrate='" + songBitrate + '\'' +
                ", songMeta='" + songMeta + '\'' +
                ", created=" + created +
                ", updub=" + updub +
                ", downdub=" + downdub +
                ", userid='" + userid + '\'' +
                ", __v=" + __v +
                '}';
    }
}


text:
package org.lagonette.app.app.activity;

import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import org.lagonette.app.app.widget.performer.impl.SharedPreferencesPerformer;
import org.lagonette.app.tools.CrashReporter;

public abstract class BaseActivity
		extends AppCompatActivity {

	protected SharedPreferencesPerformer mSharedPreferencesPerformer;

	protected final void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initPerformer();
		initCrashlyticsIfNeeded();
		construct();
		setContentView(getContentView());
		inject(getWindow().getDecorView().getRootView());
		if (savedInstanceState == null) {
			init();
		}
		else {
			restore(savedInstanceState);
		}
		onConstructed();
	}

	protected void initCrashlyticsIfNeeded() {
		if (mSharedPreferencesPerformer.isCrashlitycsEnabled()) {
			CrashReporter.init(this);
		}
	}

	protected void initPerformer() {
		mSharedPreferencesPerformer = new SharedPreferencesPerformer(this);
	}

	protected abstract void construct();

	@LayoutRes
	protected abstract int getContentView();

	protected abstract void inject(@NonNull View view);

	protected abstract void init();

	protected abstract void restore(@NonNull Bundle savedInstanceState);

	protected abstract void onConstructed();

}


text:
"""Support for the Awair indoor air quality monitor."""

from datetime import timedelta
import logging
import math

from python_awair import AwairClient
import voluptuous as vol

from homeassistant.const import (
    CONF_ACCESS_TOKEN,
    CONF_DEVICES,
    DEVICE_CLASS_HUMIDITY,
    DEVICE_CLASS_TEMPERATURE,
    TEMP_CELSIUS,
)
from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.entity import Entity
from homeassistant.util import Throttle, dt

_LOGGER = logging.getLogger(__name__)

ATTR_SCORE = "score"
ATTR_TIMESTAMP = "timestamp"
ATTR_LAST_API_UPDATE = "last_api_update"
ATTR_COMPONENT = "component"
ATTR_VALUE = "value"
ATTR_SENSORS = "sensors"

CONF_UUID = "uuid"

DEVICE_CLASS_PM2_5 = "PM2.5"
DEVICE_CLASS_PM10 = "PM10"
DEVICE_CLASS_CARBON_DIOXIDE = "CO2"
DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS = "VOC"
DEVICE_CLASS_SCORE = "score"

SENSOR_TYPES = {
    "TEMP": {
        "device_class": DEVICE_CLASS_TEMPERATURE,
        "unit_of_measurement": TEMP_CELSIUS,
        "icon": "mdi:thermometer",
    },
    "HUMID": {
        "device_class": DEVICE_CLASS_HUMIDITY,
        "unit_of_measurement": "%",
        "icon": "mdi:water-percent",
    },
    "CO2": {
        "device_class": DEVICE_CLASS_CARBON_DIOXIDE,
        "unit_of_measurement": "ppm",
        "icon": "mdi:periodic-table-co2",
    },
    "VOC": {
        "device_class": DEVICE_CLASS_VOLATILE_ORGANIC_COMPOUNDS,
        "unit_of_measurement": "ppb",
        "icon": "mdi:cloud",
    },
    # Awair docs don't actually specify the size they measure for 'dust',
    # but 2.5 allows the sensor to show up in HomeKit
    "DUST": {
        "device_class": DEVICE_CLASS_PM2_5,
        "unit_of_measurement": "µg/m3",
        "icon": "mdi:cloud",
    },
    "PM25": {
        "device_class": DEVICE_CLASS_PM2_5,
        "unit_of_measurement": "µg/m3",
        "icon": "mdi:cloud",
    },
    "PM10": {
        "device_class": DEVICE_CLASS_PM10,
        "unit_of_measurement": "µg/m3",
        "icon": "mdi:cloud",
    },
    "score": {
        "device_class": DEVICE_CLASS_SCORE,
        "unit_of_measurement": "%",
        "icon": "mdi:percent",
    },
}

AWAIR_QUOTA = 300

# This is the minimum time between throttled update calls.
# Don't bother asking us for state more often than that.
SCAN_INTERVAL = timedelta(minutes=5)

AWAIR_DEVICE_SCHEMA = vol.Schema({vol.Required(CONF_UUID): cv.string})

PLATFORM_SCHEMA = cv.PLATFORM_SCHEMA.extend(
    {
        vol.Required(CONF_ACCESS_TOKEN): cv.string,
        vol.Optional(CONF_DEVICES): vol.All(cv.ensure_list, [AWAIR_DEVICE_SCHEMA]),
    }
)

# Awair *heavily* throttles calls that get user information,
# and calls that get the list of user-owned devices - they
# allow 30 per DAY. So, we permit a user to provide a static
# list of devices, and they may provide the same set of information
# that the devices() call would return. However, the only thing
# used at this time is the `uuid` value.
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
    """Connect to the Awair API and find devices."""

    token = config[CONF_ACCESS_TOKEN]
    client = AwairClient(token, session=async_get_clientsession(hass))

    try:
        all_devices = []
        devices = config.get(CONF_DEVICES, await client.devices())

        # Try to throttle dynamically based on quota and number of devices.
        throttle_minutes = math.ceil(60 / ((AWAIR_QUOTA / len(devices)) / 24))
        throttle = timedelta(minutes=throttle_minutes)

        for device in devices:
            _LOGGER.debug("Found awair device: %s", device)
            awair_data = AwairData(client, device[CONF_UUID], throttle)
            await awair_data.async_update()
            for sensor in SENSOR_TYPES:
                if sensor in awair_data.data:
                    awair_sensor = AwairSensor(awair_data, device, sensor, throttle)
                    all_devices.append(awair_sensor)

        async_add_entities(all_devices, True)
        return
    except AwairClient.AuthError:
        _LOGGER.error("Awair API access_token invalid")
    except AwairClient.RatelimitError:
        _LOGGER.error("Awair API ratelimit exceeded.")
    except (
        AwairClient.QueryError,
        AwairClient.NotFoundError,
        AwairClient.GenericError,
    ) as error:
        _LOGGER.error("Unexpected Awair API error: %s", error)

    raise PlatformNotReady

class AwairSensor(Entity):
    """Implementation of an Awair device."""

    def __init__(self, data, device, sensor_type, throttle):
        """Initialize the sensor."""
        self._uuid = device[CONF_UUID]
        self._device_class = SENSOR_TYPES[sensor_type]["device_class"]
        self._name = f"Awair {self._device_class}"
        unit = SENSOR_TYPES[sensor_type]["unit_of_measurement"]
        self._unit_of_measurement = unit
        self._data = data
        self._type = sensor_type
        self._throttle = throttle

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._name

    @property
    def device_class(self):
        """Return the device class."""
        return self._device_class

    @property
    def icon(self):
        """Icon to use in the frontend."""
        return SENSOR_TYPES[self._type]["icon"]

    @property
    def state(self):
        """Return the state of the device."""
        return self._data.data[self._type]

    @property
    def device_state_attributes(self):
        """Return additional attributes."""
        return self._data.attrs

    # The Awair device should be reporting metrics in quite regularly.
    # Based on the raw data from the API, it looks like every ~10 seconds
    # is normal. Here we assert that the device is not available if the
    # last known API timestamp is more than (3 * throttle) minutes in the
    # past. It implies that either hass is somehow unable to query the API
    # for new data or that the device is not checking in. Either condition
    # fits the definition for 'not available'. We pick (3 * throttle) minutes
    # to allow for transient errors to correct themselves.
    @property
    def available(self):
        """Device availability based on the last update timestamp."""
        if ATTR_LAST_API_UPDATE not in self.device_state_attributes:
            return False

        last_api_data = self.device_state_attributes[ATTR_LAST_API_UPDATE]
        return (dt.utcnow() - last_api_data) < (3 * self._throttle)

    @property
    def unique_id(self):
        """Return the unique id of this entity."""
        return f"{self._uuid}_{self._type}"

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity."""
        return self._unit_of_measurement

    async def async_update(self):
        """Get the latest data."""
        await self._data.async_update()

class AwairData:
    """Get data from Awair API."""

    def __init__(self, client, uuid, throttle):
        """Initialize the data object."""
        self._client = client
        self._uuid = uuid
        self.data = {}
        self.attrs = {}
        self.async_update = Throttle(throttle)(self._async_update)

    async def _async_update(self):
        """Get the data from Awair API."""
        resp = await self._client.air_data_latest(self._uuid)

        if not resp:
            return

        timestamp = dt.parse_datetime(resp[0][ATTR_TIMESTAMP])
        self.attrs[ATTR_LAST_API_UPDATE] = timestamp
        self.data[ATTR_SCORE] = resp[0][ATTR_SCORE]

        # The air_data_latest call only returns one item, so this should
        # be safe to only process one entry.
        for sensor in resp[0][ATTR_SENSORS]:
            self.data[sensor[ATTR_COMPONENT]] = round(sensor[ATTR_VALUE], 1)

        _LOGGER.debug("Got Awair Data for %s: %s", self._uuid, self.data)


text:
//--------------------------------------------------------------------------------------------------------------
// Created by		: Diego Parolin
// Copyright		: 2017.02.17
//--------------------------------------------------------------------------------------------------------------

using System.Collections.Generic;

namespace TAS.Data.Entity
{
	/// <summary>
	/// A basket of items.
	/// </summary>
	public class Basket: BaseEntity
	{
    /// <summary>
    /// Initializes a new instance of the <see cref="Basket"/> class.
    /// </summary>
    public Basket()
    {
      Items = new List<Item>();
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="Basket"/> class.
    /// </summary>
    /// <param name="code">The code.</param>
    /// <param name="description">The description.</param>
    /// <param name="items">The items.</param>
    public Basket(string code, string description, List<Item> items)
		{
      Code = code;
      Description = description;
			Items = items;
		}

		/// <summary>
		/// Gets or sets the items.
		/// </summary>
		/// <value>
		/// The items.
		/// </value>
		public List<Item> Items { get; set; }
	}
}


text:
namespace server
{
  class Logger
  {
  private:
    const char* _file_location;
    const char* _mode;
    void* _fd;
    bool _opened;
    std::mutex _write_lock;

    const char* time();
  public:
    Logger();
    Logger(const char* location, const char* mode);
    Logger(const char* location);
    ~Logger();
    void open(const char* location, const char* mode);
    void open(const char* location);

    const char* operator()(const char* message);

    const char* log(const char* message);

    void write_bin(void* write, size_t len);
    void write_hex(void* write, size_t len);

    size_t size();
    size_t clear();
  };
}
#endif


text:
const iframify_requires = [
  'cash',
  'lazyshow',
  'pseudo-styles',
  'iframeResizer.contentWindow',
  'iframeResizer',
  'iframify',
  'copied'
]

if (!('srcdoc' in document.createElement('iframe'))) {
  iframify_requires.push('srcdoc-polyfill')
}

$script(iframify_requires, () => {
  const lazy = window.lazy_iframify = new LazyShow('js-iframify')
  const options = iframify_options || {}
  const $doc = $(document)
  const extras = `

  `

  lazy.on('visible', function Visible() {
    const $obj = $(this)
    const html = $obj.text()
    $obj.html('')
    let iframe = $('

')[0]
    $obj.append(iframe)
    iframe = iframify(iframe, $.extend({}, options, {
      stylesSelector: 'nothing',
      sizingTimeout: 1000,
      bodyExtra: [
        html,
        options.bodyExtra,
        extras
      ].filter(Boolean).join('\n')
    }))

    const $iframe = $(iframe)
      .removeClass('js-iframify')
      .addClass('js-iframe-resize')

    $iframe.on('load', () => {
      iFrameResize({
        checkOrigin: false,
        minSize: 50,
        resizedCallback() {
          $iframe
            .parent()
            .addClass('u-lazy--in')
            .parent()
            .removeClass('u-loading u-loading--middle u-loading--huge is-loading')
          lazy.check()
        }
      }, iframe)
    })
  })

  $doc.on('click', '.js-frame .js-frame__view-state', function ViewState(e) {
    e.preventDefault()
    const $obj = $(this)
    const id = $obj.parent().data('index')

    $obj
      .closest('.js-frame')
      .find('.js-frame__section[data-type=escaped-state]')
      .each((item) => {
        const $item = $(item)
        const test = $item.data('index') === id
        $item
          .toggleClass('u-show', test)
          .toggleClass('u-hide', !test)
      })
  })

  $doc.on('click', '.js-frame__copy', function CopyToClipBoardButton(e) {
    e.preventDefault()
    const $frame = $(this).parents('.js-frame')
    const $code = $frame
      .find('.js-frame__section[data-type^="escape"]')
      // filters out hidden items
      .filter((elem) => !!(elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length))
      .find('code')
      .first()
    if ($code.length) {
      copy($code)
    }
  })
})


text:
/**
 * @file libmaple/gpio.c
 * @brief Generic STM32 GPIO support.
 */

#include <libmaple/gpio.h>
#include <libmaple/rcc.h>

/*
 * GPIO routines
 */

/**
 * Initialize a GPIO device.
 *
 * Enables the clock for and resets the given device.
 *
 * @param dev GPIO device to initialize.
 */
void gpio_init(gpio_dev *dev) {
    rcc_clk_enable(dev->clk_id);
    rcc_reset_dev(dev->clk_id);
}


text:
package com.github.openwebnet.iabutil;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.github.openwebnet.R;

/**
 * @author niqdev
 */
public class DonationDialogFragment extends DialogFragment {

    private static final String TAG_FRAGMENT = "donation_dialog";

    public DonationDialogFragment() {}

    public static void show(AppCompatActivity activity) {
        DialogFragment dialogFragment = new DonationDialogFragment();
        FragmentManager fm = activity.getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        Fragment prev = fm.findFragmentByTag(TAG_FRAGMENT);
        if (prev != null) {
            ft.remove(prev);
        }
        dialogFragment.show(ft, TAG_FRAGMENT);
    }

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        LinearLayout layout = (LinearLayout) LayoutInflater
            .from(getContext()).inflate(R.layout.dialog_donation, null);

        ListView list = (ListView) layout.findViewById(R.id.listViewDialogDonation);
        list.setAdapter(new DonationAdapter(this, IabUtil.getInstance().getDonationEntries()));

        return new AlertDialog.Builder(getActivity(), R.style.AppCompatAlertDialogStyle)
            .setTitle(R.string.dialog_donation_title)
            .setView(layout)
            .setPositiveButton(R.string.button_close, (dialog, which) -> dialog.dismiss())
            .create();
    }

}


text:
#ifndef INCLUDE_common_h__
#define INCLUDE_common_h__

#include "git2/common.h"
#include "cc-compat.h"

#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include <sys/types.h>
#include <sys/stat.h>

#ifdef GIT_WIN32

# include <io.h>
# include <direct.h>
# include <winsock2.h>
# include <windows.h>
# include "win32/msvc-compat.h"
# include "win32/mingw-compat.h"
# include "win32/error.h"
# ifdef GIT_THREADS
#	include "win32/pthread.h"
#endif

# define snprintf _snprintf

#else
# include <unistd.h>

# ifdef GIT_THREADS
#	include <pthread.h>
# endif
#endif

#include "git2/types.h"
#include "git2/errors.h"
#include "thread-utils.h"
#include "bswap.h"

#include <regex.h>

/**
 * Check a pointer allocation result, returning -1 if it failed.
 */
#define GITERR_CHECK_ALLOC(ptr) if (ptr == NULL) { return -1; }

/**
 * Set the error message for this thread, formatting as needed.
 */
void giterr_set(int error_class, const char *string, ...);

/**
 * Set the error message for a regex failure, using the internal regex
 * error code lookup and return a libgit error code.
 */
int giterr_set_regex(const regex_t *regex, int error_code);

/**
 * Check a versioned structure for validity
 */
GIT_INLINE(int) giterr__check_version(const void *structure, unsigned int expected_max, const char *name)
{
	unsigned int actual;

	if (!structure)
		return 0;

	actual = *(const unsigned int*)structure;
	if (actual > 0 && actual <= expected_max)
		return 0;

	giterr_set(GITERR_INVALID, "Invalid version %d on %s", actual, name);
	return -1;
}
#define GITERR_CHECK_VERSION(S,V,N) if (giterr__check_version(S,V,N) < 0) return -1

/**
 * Initialize a structure with a version.
 */
GIT_INLINE(void) git__init_structure(void *structure, size_t len, unsigned int version)
{
	memset(structure, 0, len);
	*((int*)structure) = version;
}
#define GIT_INIT_STRUCTURE(S,V) git__init_structure(S, sizeof(*S), V)

/* NOTE: other giterr functions are in the public errors.h header file */

#include "util.h"

#endif /* INCLUDE_common_h__ */


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:appcompat="http://schemas.android.com/apk/res-auto" >

    <item
        android:id="@+id/SEARCH_ID"
        android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
        android:title="@string/search_hint"
        appcompat:showAsAction="ifRoom"/>
    <item
        android:id="@+id/INSERT_ID"
        android:icon="@drawable/ic_add_black_48dp"
        android:title="@string/menu_insert"
        appcompat:showAsAction="always|withText"/>
    <item
        android:id="@+id/PREFS_ID"
        android:icon="@android:drawable/ic_menu_preferences"
        android:title="@string/menu_prefs"
        appcompat:showAsAction="never"/>

</menu>


text:
using BehaveAsSakura.Attributes;
using BehaveAsSakura.SerializationCompiler.Schema;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace BehaveAsSakura.SerializationCompiler
{
    static class CSharpSerializerWriter
    {
        public static string ToString(SchemaDef schema, string flatBuffersCodePath)
        {
            var builder = new StringBuilder();

            GenerateFlatbufferObjects(flatBuffersCodePath, builder);
            GenerateUnionSerializers(builder, schema);
            GenerateBaseSerializer(builder, schema);
            GenerateSerializers(builder, schema);
            GenerateBehaviorTreeSerializers(builder, schema);

            return builder.ToString();
        }

        public static void ToFile(SchemaDef schema, string flatBuffersCodePath, string path)
        {
            File.WriteAllText(path, ToString(schema, flatBuffersCodePath), Encoding.UTF8);
        }

        private static void GenerateFlatbufferObjects(string path, StringBuilder builder)
        {
            var code = File.ReadAllText(path, Encoding.UTF8);
            code = Regex.Replace(code, "^public enum", "enum", RegexOptions.Multiline);
            code = Regex.Replace(code, "^public struct", "struct", RegexOptions.Multiline);

            builder.AppendLine(code);
            builder.AppendLine();
        }

        private static void GenerateUnionSerializers(StringBuilder builder, SchemaDef schema)
        {
            builder.AppendLine($@"
namespace {schema.Namespace}
{{
    using FlatBuffers;
    using System;
    using System.Collections.Generic;
");

            foreach (var u in schema.Unions)
            {
                var unionFbName = ConvertTypeName(u.UnionType);

                builder.AppendLine($@"    static class {unionFbName}__UnionSerializer
    {{");

                AddUnionSerializeMethod(builder, u);
                AddUnionWrapperSerializeMethod(builder, u);
                AddUnionWrapperDeserializeMethod(builder, u);

                builder.AppendLine("    }");
                builder.AppendLine();
            }

            builder.AppendLine("}");
            builder.AppendLine();
        }

        private static void AddUnionSerializeMethod(StringBuilder builder, UnionDef union)
        {
            var unionFbName = ConvertTypeName(union.UnionType);
            var unionName = union.UnionType.FullName;

            builder.AppendLine($@"        public static bool Serialize(FlatBufferBuilder fbb, {unionName} obj, out int offset, out {unionFbName} type)
        {{
            if (obj == null)
            {{
                offset = 0;
                type = {unionFbName}.NONE;
                return false;
            }}
");

            foreach (var t in union.IncludedTypes)
            {
                var includedTypeName = t.Item1.FullName;
                var includedTypeSerializerName = ConvertSerializerName(t.Item1);
                var includedFbName = ConvertTypeName(t.Item1);

                builder.AppendLine($@"            if (obj is {includedTypeName})
            {{
                var o = {includedTypeSerializerName}.Instance.Serialize(fbb, ({includedTypeName})obj);
                offset = o.HasValue ? o.Value.Value : 0;
                type = {unionFbName}.{includedFbName};
                return true;
            }}
");
            }

            builder.AppendLine(@"            throw new NotSupportedException(obj.GetType().FullName);
        }");
        }

        private static void AddUnionWrapperSerializeMethod(StringBuilder builder, UnionDef union)
        {
            var unionFbName = ConvertTypeName(union.UnionType);
            var unionName = union.UnionType.FullName;
            var unionWrapperName = ConvertUnionWrapper(union.UnionType);

            builder.AppendLine($@"
        public static Offset<{unionWrapperName}>[] Serialize(FlatBufferBuilder fbb, IList<{unionName}> objects)
        {{
            if (objects == null)
                return null;

            var offsets = new Offset<{unionWrapperName}>[objects.Count];
            for (int i = 0; i < objects.Count; i++)
            {{
                var obj = objects[i];
                if (obj == null)
                {{
                    offsets[i] = {unionWrapperName}.Create{unionWrapperName}(fbb);
                    continue;
                }}
");

            foreach (var t in union.IncludedTypes)
            {
                var includedTypeName = t.Item1.FullName;
                var includedTypeSerializerName = ConvertSerializerName(t.Item1);
                var includedFbName = ConvertTypeName(t.Item1);

                builder.AppendLine($@"                if (obj is {includedTypeName})
                {{
                    var o = {includedTypeSerializerName}.Instance.Serialize(fbb, ({includedTypeName})obj);
                    var offset = o.HasValue ? o.Value.Value : 0;
                    offsets[i] = {unionWrapperName}.Create{unionWrapperName}(fbb,
                                {unionFbName}.{includedFbName},
                                offset);
                    continue;
                }}
");
            }

            builder.AppendLine(@"                throw new NotSupportedException(obj.GetType().FullName);
            }

            return offsets;
        }");
        }

        private static void AddUnionWrapperDeserializeMethod(StringBuilder builder, UnionDef union)
        {
            var unionName = union.UnionType.FullName;
            var unionFbName = ConvertTypeName(union.UnionType);
            var unionWrapperName = ConvertUnionWrapper(union.UnionType);

            builder.AppendLine($@"
        public static {unionName}[] Deserialize(int objectsLength, Func<int, {unionWrapperName}?> getObject)
        {{
            if (objectsLength == 0)
                return null;

            var objects = new {unionName}[objectsLength];
            for (int i = 0; i < objectsLength; i++)
            {{
                var wrapper = getObject(i);
                if (!wrapper.HasValue)
                    continue;

                switch (wrapper.Value.BodyType)
                {{");

            foreach (var t in union.IncludedTypes)
            {
                var includedTypeName = t.Item1.FullName;
                var includedTypeSerializerName = ConvertSerializerName(t.Item1);
                var includedFbName = ConvertTypeName(t.Item1);

                builder.AppendLine($@"                    case {unionFbName}.{includedFbName}:
                        objects[i] = {includedTypeSerializerName}.Instance.Deserialize(wrapper.Value.Body<{includedFbName}>());
                        break;
");
            }

            builder.AppendLine($@"                    case {unionFbName}.NONE:
                        break;

                    default:
                        throw new NotSupportedException(wrapper.Value.BodyType.ToString());
                }}
            }}

            return objects;
        }}");

        }

        private static void GenerateBaseSerializer(StringBuilder builder, SchemaDef schema)
        {
            builder.AppendLine($@"namespace {schema.Namespace}
{{
    using FlatBuffers;
    using System;
    using System.Collections.Generic;

    interface ISerializer
    {{
        byte[] Serialize(object obj);

        object Deserialize(byte[] data);
    }}

    interface ISerializer<TObject, TFlatBufferObject>
        where TFlatBufferObject : struct, IFlatbufferObject
    {{
        Offset<TFlatBufferObject>? Serialize(FlatBufferBuilder fbb, TObject obj);

        Offset<TFlatBufferObject>[] Serialize(FlatBufferBuilder fbb, IList<TObject> objects);

        TObject Deserialize(TFlatBufferObject? obj);

        TObject Deserialize(TFlatBufferObject obj);

        TObject[] Deserialize(int objectsLength, Func<int, TFlatBufferObject?> getObjects);
    }}

    abstract class Serializer<TObject, TFlatBufferObject> : ISerializer<TObject, TFlatBufferObject>, ISerializer
        where TFlatBufferObject : struct, IFlatbufferObject
    {{
        public byte[] Serialize(object obj)
        {{
            var fbb = new FlatBufferBuilder(1024);
            var offset = Serialize(fbb, (TObject)obj);
            if (offset.HasValue)
            {{
                fbb.Finish(offset.Value.Value);

                return fbb.SizedByteArray();
            }}
            else
                return null;
        }}

        public abstract Offset<TFlatBufferObject>? Serialize(FlatBufferBuilder fbb, TObject obj);

        public Offset<TFlatBufferObject>[] Serialize(FlatBufferBuilder fbb, IList<TObject> objects)
        {{
            if (objects == null)
                return null;

            var offsets = new Offset<TFlatBufferObject>[objects.Count];
            for (int i = 0; i < objects.Count; i++)
            {{
                var offset = Serialize(fbb, objects[i]);
                if (offset.HasValue)
                    offsets[i] = offset.Value;
            }}

            return offsets;
        }}

        public static StringOffset[] SerializeString(FlatBufferBuilder fbb, string[] objects)
        {{
            if (objects == null)
                return null;

            var offsets = new StringOffset[objects.Length];
            for (int i = 0; i < objects.Length; i++)
                offsets[i] = fbb.CreateString(objects[i]);

            return offsets;
        }}

        public object Deserialize(byte[] data)
        {{
            if (data == null)
                return default(TObject);

            return Deserialize(GetRootAs(new ByteBuffer(data)));
        }}

        protected abstract TFlatBufferObject GetRootAs(ByteBuffer buffer);

        public TObject Deserialize(TFlatBufferObject? obj)
        {{
            if (!obj.HasValue)
                return default(TObject);

            return Deserialize(obj.Value);
        }}

        public abstract TObject Deserialize(TFlatBufferObject obj);

        public TObject[] Deserialize(int objectsLength, Func<int, TFlatBufferObject?> getObjects)
        {{
            if (objectsLength == 0)
                return null;

            var objects = new TObject[objectsLength];
            for (int i = 0; i < objectsLength; i++)
                objects[i] = Deserialize(getObjects(i));

            return objects;
        }}

        public static T[] DeserializeScalar<T>(int objectsLength, Func<int, T> getObjects)
        {{
            if (objectsLength == 0)
                return null;

            var objects = new T[objectsLength];
            for (int i = 0; i < objectsLength; i++)
                objects[i] = getObjects(i);

            return objects;
        }}
    }}
}}");
        }

        private static void GenerateSerializers(StringBuilder builder, SchemaDef schema)
        {
            builder.AppendLine($@"
namespace {schema.Namespace}
{{
    using FlatBuffers;
    using System;
    using System.Collections.Generic;
    using System.Linq;
");

            foreach (var t in schema.Tables)
            {
                var serializerName = ConvertSerializerName(t.Type);
                var tableName = t.Type.FullName;
                var fbObjectName = ConvertTypeName(t.Type);

                builder.AppendLine($@"
    class {serializerName} : Serializer<{tableName}, {fbObjectName}>
    {{
        public static readonly {serializerName} Instance = new {serializerName}();
");

                AddSerializeMethod(builder, t, schema);
                AddGetRootAddMethod(builder, t);
                AddDeserializeMethod(builder, t, schema);

                builder.AppendLine("    }");
            }

            builder.AppendLine("}");
        }

        private static void AddSerializeMethod(StringBuilder builder, TableDef table, SchemaDef schema)
        {
            var tableName = table.Type.FullName;
            var fbObjectName = ConvertTypeName(table.Type);

            builder.AppendLine($@"        public override Offset<{fbObjectName}>? Serialize(FlatBufferBuilder fbb, {tableName} obj)
        {{
            if (obj == null)
                return null;");

            foreach (var f in table.Fields)
            {
                if (IsCollectionType(f.Type))
                {
                    var elementType = GetElementType(f.Type);
                    var toArray = IsListType(f.Type) ? ".ToArray()" : "";

                    if (elementType == typeof(string))
                    {
                        builder.AppendLine($@"            var vector{f.Name} = default(VectorOffset?);
            if (obj.{f.Name} != null)
            {{
                var offsets{f.Name} = SerializeString(fbb, obj.{f.Name}{toArray});
                vector{f.Name} = {fbObjectName}.Create{f.Name}Vector(fbb, offsets{f.Name});
            }}");
                    }
                    else if (IsScalarType(elementType))
                    {
                        builder.AppendLine($@"            var vector{f.Name} = default(VectorOffset?);
            if (obj.{f.Name} != null)
                vector{f.Name} = {fbObjectName}.Create{f.Name}Vector(fbb, obj.{f.Name}{toArray});");
                    }
                    else if (IsEnumType(elementType))
                    {
                        var underlyingTypeName = Enum.GetUnderlyingType(elementType).FullName;
                        var fbEnumTypeName = ConvertTypeName(elementType);

                        builder.AppendLine($@"            var vector{f.Name} = default(VectorOffset?);
            if (obj.{f.Name} != null)
            {{
                var casted{f.Name} = obj.{f.Name}.Select(e => ({fbEnumTypeName})({underlyingTypeName})e).ToArray();
                vector{f.Name} = {fbObjectName}.Create{f.Name}Vector(fbb, casted{f.Name});
            }}");
                    }
                    else if (IsUnionType(elementType, schema))
                    {
                        var unionSerializerName = $"{ConvertTypeName(elementType)}__UnionSerializer";

                        builder.AppendLine($@"            var vector{f.Name} = default(VectorOffset?);
            if (obj.{f.Name} != null)
            {{
                var offsets{f.Name} = {unionSerializerName}.Serialize(fbb, obj.{f.Name});
                vector{f.Name} = {fbObjectName}.Create{f.Name}Vector(fbb, offsets{f.Name});
            }}");
                    }
                    else
                    {
                        var elementSerializerName = ConvertSerializerName(elementType);

                        builder.AppendLine($@"            var vector{f.Name} = default(VectorOffset?);
            if (obj.{f.Name} != null)
            {{
                var offsets{f.Name} = {elementSerializerName}.Instance.Serialize(fbb, obj.{f.Name});
                vector{f.Name} = {fbObjectName}.Create{f.Name}Vector(fbb, offsets{f.Name});
            }}");
                    }
                }
                else
                {
                    if (f.Type == typeof(string))
                    {
                        builder.AppendLine($@"            var offset{f.Name} = default(StringOffset?);
            if (!string.IsNullOrEmpty(obj.{f.Name}))
                offset{f.Name} = fbb.CreateString(obj.{f.Name});");
                    }
                    else if (IsScalarType(f.Type) || IsEnumType(f.Type))
                    {
                        // Do nothing
                    }
                    else if (IsUnionType(f.Type, schema))
                    {
                        var union = schema.Unions.Find(u => u.UnionType == f.Type);
                        var unionFbName = ConvertTypeName(union.UnionType);

                        builder.AppendLine($@"            int offset{f.Name};
            {unionFbName} type{f.Name};
            {unionFbName}__UnionSerializer.Serialize(fbb, obj.{f.Name}, out offset{f.Name}, out type{f.Name});");
                    }
                    else
                    {
                        var fieldSerializerName = ConvertSerializerName(f.Type);

                        builder.AppendLine($@"            var offset{f.Name} = {fieldSerializerName}.Instance.Serialize(fbb, obj.{ f.Name});");
                    }
                }
            }

            builder.AppendLine($@"            {fbObjectName}.Start{fbObjectName}(fbb);");

            foreach (var f in table.Fields)
            {
                if (IsCollectionType(f.Type))
                {
                    builder.AppendLine($@"            if (vector{f.Name}.HasValue)
                {fbObjectName}.Add{f.Name}(fbb, vector{f.Name}.Value);");
                }
                else
                {
                    if (f.Type == typeof(string))
                    {
                        builder.AppendLine($@"            if (offset{f.Name}.HasValue)
                {fbObjectName}.Add{f.Name}(fbb, offset{f.Name}.Value);");
                    }
                    else if (IsScalarType(f.Type))
                    {
                        builder.AppendLine($"            {fbObjectName}.Add{f.Name}(fbb, obj.{f.Name});");
                    }
                    else if (IsEnumType(f.Type))
                    {
                        var underlyingTypeName = Enum.GetUnderlyingType(f.Type).FullName;
                        var fbEnumTypeName = ConvertTypeName(f.Type);
                        builder.AppendLine($"            {fbObjectName}.Add{f.Name}(fbb, ({fbEnumTypeName})({underlyingTypeName})obj.{f.Name});");
                    }
                    else if (IsUnionType(f.Type, schema))
                    {
                        var union = schema.Unions.Find(u => u.UnionType == f.Type);
                        var unionFbName = ConvertTypeName(union.UnionType);

                        builder.AppendLine($@"            if (type{f.Name} != {unionFbName}.NONE)
            {{
                {fbObjectName}.Add{f.Name}(fbb, offset{f.Name});
                {fbObjectName}.Add{f.Name}Type(fbb, type{f.Name});
            }}");
                    }
                    else
                    {
                        builder.AppendLine($@"            if (offset{f.Name}.HasValue)
                {fbObjectName}.Add{f.Name}(fbb, offset{f.Name}.Value);");
                    }
                }
            }

            builder.AppendLine($@"            return {fbObjectName}.End{fbObjectName}(fbb);");
            builder.AppendLine("        }");
        }

        private static void AddGetRootAddMethod(StringBuilder builder, TableDef table)
        {
            var tableName = table.Type.FullName;
            var fbObjectName = ConvertTypeName(table.Type);

            builder.AppendLine($@"        protected override {fbObjectName} GetRootAs(ByteBuffer buffer)
        {{
            return {fbObjectName}.GetRootAs{fbObjectName}(buffer);
        }}");
        }

        private static void AddDeserializeMethod(StringBuilder builder, TableDef table, SchemaDef schema)
        {
            var tableName = table.Type.FullName;
            var fbObjectName = ConvertTypeName(table.Type);
            var unionFields = new List<Tuple<FieldDef, UnionDef>>();

            builder.AppendLine($@"        public override {tableName} Deserialize({fbObjectName} obj)
        {{
            return new {tableName}()
            {{");

            foreach (var f in table.Fields)
            {
                if (IsCollectionType(f.Type))
                {
                    var elementType = GetElementType(f.Type);

                    if (elementType == typeof(string) || IsScalarType(elementType))
                    {
                        builder.Append($"                {f.Name} = DeserializeScalar<{elementType.FullName}>(obj.{f.Name}Length, obj.{f.Name})");
                    }
                    else if (IsEnumType(elementType))
                    {
                        var toArray = IsArrayType(f.Type) ? ".ToArray()" : "";
                        var enumName = ConvertEnumName(elementType);
                        var underlyingTypeName = Enum.GetUnderlyingType(elementType).FullName;

                        builder.Append($"                {f.Name} = DeserializeScalar(obj.{f.Name}Length, obj.{f.Name}).Select(e => ({enumName})({underlyingTypeName})e){toArray}");
                    }
                    else if (IsUnionType(elementType, schema))
                    {
                        var unionSerializerName = $"{ConvertTypeName(elementType)}__UnionSerializer";

                        builder.Append($"                {f.Name} = {unionSerializerName}.Deserialize(obj.{f.Name}Length, obj.{f.Name})");
                    }
                    else
                    {
                        var elementSerializerName = ConvertSerializerName(elementType);
                        builder.Append($"                {f.Name} = {elementSerializerName}.Instance.Deserialize(obj.{f.Name}Length, obj.{f.Name})");
                    }

                    if (IsListType(f.Type))
                        builder.Append(".ToList()");

                    builder.AppendLine(",");
                }
                else
                {
                    if (f.Type == typeof(string) || IsScalarType(f.Type))
                    {
                        builder.AppendLine($"                {f.Name} = obj.{f.Name},");
                    }
                    else if (IsEnumType(f.Type))
                    {
                        var enumName = ConvertEnumName(f.Type);
                        var underlyingTypeName = Enum.GetUnderlyingType(f.Type).FullName;
                        builder.AppendLine($"                {f.Name} = ({enumName})({underlyingTypeName})obj.{f.Name},");
                    }
                    else if (IsUnionType(f.Type, schema))
                    {
                        var union = schema.Unions.Find(u => u.UnionType == f.Type);
                        unionFields.Add(Tuple.Create(f, union));

                        builder.AppendLine($"                {f.Name} = Deserialize{f.Name}(obj),");
                    }
                    else
                    {
                        var fieldSerializerName = ConvertSerializerName(f.Type);
                        builder.AppendLine($"                {f.Name} = {fieldSerializerName}.Instance.Deserialize(obj.{f.Name}),");
                    }
                }
            }

            builder.AppendLine("            };");
            builder.AppendLine("        }");

            foreach (var f in unionFields)
                AddDeserializeUnionMethod(builder, table, f.Item1, f.Item2);
        }

        private static void AddDeserializeUnionMethod(StringBuilder builder, TableDef table, FieldDef field, UnionDef union)
        {
            var tableFbName = ConvertTypeName(table.Type);
            var unionName = union.UnionType.FullName;
            var unionFbName = ConvertTypeName(union.UnionType);

            builder.AppendLine($@"        private {unionName} Deserialize{field.Name}({tableFbName} obj)
        {{
            switch (obj.{field.Name}Type)
            {{");

            foreach (var t in union.IncludedTypes)
            {
                var includedFbName = ConvertTypeName(t.Item1);
                var includedSerializerName = ConvertSerializerName(t.Item1);

                builder.AppendLine($@"
                case {unionFbName}.{includedFbName}:
                    return {includedSerializerName}.Instance.Deserialize(obj.{field.Name}<{includedFbName}>());");
            }

            builder.AppendLine($@"
                case {unionFbName}.NONE:
                    return null;

                default:
                    throw new NotSupportedException(obj.{field.Name}Type.ToString());
            }}
        }}");
        }

        private static void GenerateBehaviorTreeSerializers(StringBuilder builder, SchemaDef schema)
        {
            var descSerializer = ConvertSerializerName(typeof(BehaviorTreeDesc));
            var propsSerializer = ConvertSerializerName(typeof(BehaviorTreeProps));

            builder.AppendLine($@"
namespace {schema.Namespace}
{{
    public class FlatBuffersSerializer : IBehaviorTreeSerializer
    {{
        public byte[] SerializeDesc(BehaviorTreeDesc desc)
        {{
            return {descSerializer}.Instance.Serialize(desc);
        }}

        public BehaviorTreeDesc DeserializeDesc(byte[] data)
        {{
            return {descSerializer}.Instance.Deserialize(data) as BehaviorTreeDesc;
        }}

        public byte[] SerializeProps(BehaviorTreeProps props)
        {{
            return {propsSerializer}.Instance.Serialize(props);
        }}

        public BehaviorTreeProps DeserializeProps(byte[] data)
        {{
            return {propsSerializer}.Instance.Deserialize(data) as BehaviorTreeProps;
        }}
    }}
}}");
        }

        private static string ConvertEnumName(Type type)
        {
            return type.FullName.Replace("+", "."); ;
        }

        private static string ConvertTypeName(Type type)
        {
            return type.FullName.Replace(".", "__").Replace("+", "___"); ;
        }

        private static string ConvertSerializerName(Type type)
        {
            return $"{ConvertTypeName(type)}__Serializer";
        }

        private static string ConvertUnionWrapper(Type type)
        {
            return $"{ConvertTypeName(type)}__UnionWrapper";
        }

        private static bool IsCollectionType(Type type)
        {
            return IsArrayType(type) || IsListType(type);
        }

        private static bool IsArrayType(Type type)
        {
            return type.IsArray;
        }

        private static bool IsListType(Type type)
        {
            return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>));
        }

        private static Type GetElementType(Type type)
        {
            if (type.IsArray)
                return type.GetElementType();

            if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
                return type.GetGenericArguments()[0];

            return null;
        }

        private static bool IsScalarType(Type type)
        {
            return type == typeof(bool)
                || type == typeof(byte)
                || type == typeof(sbyte)
                || type == typeof(short)
                || type == typeof(ushort)
                || type == typeof(int)
                || type == typeof(uint)
                || type == typeof(long)
                || type == typeof(ulong)
                || type == typeof(float)
                || type == typeof(double);
        }

        private static bool IsEnumType(Type type)
        {
            var attrs = type.GetCustomAttributes(typeof(BehaveAsEnumAttribute), false);

            return attrs != null && attrs.Length > 0;
        }

        private static bool IsUnionType(Type type, SchemaDef schema)
        {
            return schema.Unions.Exists(u => u.UnionType == type);
        }
    }
}


text:
package org.nexbook.utils

import org.joda.time.{DateTime, DateTimeZone}
import org.nexbook.domain._
import org.scalatest._

import scala.collection.immutable.List

/**
  * Created by milczu on 25.08.15.
  */
class NewOrderValidatorTest extends FlatSpec with Matchers {

  def sampleOrder(symbol: String = "EUR/PLN", size: Double = 1000.00): NewOrder = NewMarketOrder("a", symbol, "cl1", Buy, size, "FIX_ID", DateTime.now(DateTimeZone.UTC))

  def createValidator(allowedSymbolsList: List[String]): NewOrderValidator = {
	new NewOrderValidator {
	  override def allowedSymbols: List[String] = allowedSymbolsList
	}
  }

  "Order Validator" should "return validation error - now allowed symbol" in {
	val validator = createValidator(List("EUR/PLN"))
	val result = validator validate sampleOrder("EUR/USD")
	result shouldBe 'failure
	result.failed.get.getMessage should startWith("Not supported instrument: ")
  }

  "Order Validator" should "return validation error - incorrect size" in {
	val validator = createValidator(List("EUR/PLN"))
	val result = validator validate sampleOrder(size = -100.00)

	result.failed.get should have message "Invalid order size"
  }

  "Order Validator" should "return None - valid order" in {
	val validator = createValidator(List("EUR/PLN"))
	val result = validator validate sampleOrder()
	result shouldBe 'success
  }

}


text:
package org.camunda.bpm.engine.test.assertions.bpmn;

import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.assertThat;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.complete;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.runtimeService;
import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareTests.taskQuery;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.test.ProcessEngineRule;
import org.camunda.bpm.engine.test.assertions.helpers.Failure;
import org.camunda.bpm.engine.test.assertions.helpers.ProcessAssertTestCase;
import org.junit.Rule;
import org.junit.Test;

public class ProcessInstanceAssertIsStartedTest extends ProcessAssertTestCase {

  @Rule
  public ProcessEngineRule processEngineRule = new ProcessEngineRule();

  @Test
  @Deployment(resources = {"bpmn/ProcessInstanceAssert-isStarted.bpmn"
  })
  public void testIsStarted_AndActive_Success() {
    // When
    ProcessInstance processInstance = runtimeService().startProcessInstanceByKey(
      "ProcessInstanceAssert-isStarted"
    );
    // Then
    assertThat(processInstance).isStarted();
  }

  @Test
  @Deployment(resources = {"bpmn/ProcessInstanceAssert-isStarted.bpmn"
  })
  public void testIsStarted_AndEnded_Success() {
    // Given
    ProcessInstance processInstance = runtimeService().startProcessInstanceByKey(
      "ProcessInstanceAssert-isStarted"
    );
    // When
    complete(taskQuery().singleResult());
    // Then
    assertThat(processInstance).isStarted();
  }

  @Test
  @Deployment(resources = {"bpmn/ProcessInstanceAssert-isStarted.bpmn"
  })
  public void testIsStarted_Failure() {
    // When
    final ProcessInstance processInstance = mock(ProcessInstance.class);
    // And
    when(processInstance.getId()).thenReturn("someNonExistingId");
    // Then
    expect(new Failure() {
      @Override
      public void when() {
        assertThat(processInstance).isStarted();
      }
    });
  }

}


text:
namespace Anim
{
  // Anim définit une animation sur un type T (flottant, vecteur,
  // quaternion...)
  // Il faut que soient définies les fonctions
  // T interpolate(T, T, float)
  // T interpolate(T, T, T, T, float[4])
  template<typename T>
  struct cached
  {
    bool isComputed;
    T element;
  };

  template<typename T>
  class Anim
  {
  public:
    Anim();
    Anim(int numberOfFrames, unsigned int repeats = 1);
    Anim(const T & start, const T & end, date duration);
    ~Anim() {};

    void setAnim(int numberOfFrames, unsigned int repeats = 1);

    IFDBG(bool hasFrames() const;)

    date duration() const;
    void add(const date date, const T & frame);

    bool isCached() const;
    void createCache();

    T get(date localDate);

#if DEBUG

    const T & getPrev(date localDate) const;
    const T & getNext(date localDate) const;

#endif // DEBUG

  private:
    T _eval(date localDate);
    T _eval(int index, date seekDate) const;

    unsigned int	_repeats; // 0 => infini

    Array<date>		_dates;
    Array<T>		_frames;
    Array<cached<T> >	_cache;
  };
}

#include "anim.hxx"

#endif		// ANIM_HH


text:
package de.lemona.android.guice.providers.system;

import com.google.inject.Inject;

import android.app.AlarmManager;
import android.content.Context;
import de.lemona.android.guice.ContextSingleton;

@ContextSingleton
public class AlarmManagerProvider extends AbstractServiceProvider<AlarmManager> {

    @Inject
    public AlarmManagerProvider(Context context) {
        super(Context.ALARM_SERVICE, AlarmManager.class, context);
    }

}