// Copyright 2014 Splunk, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.

exports.setup = function() {
    var splunkjs        = require("../../index");
    var ET              = require("elementtree");
    var ModularInputs   = splunkjs.ModularInputs;
    var Logger          = ModularInputs.Logger;
    var ModularInput    = ModularInputs.ModularInput;
    var Event           = ModularInputs.Event;
    var EventWriter     = ModularInputs.EventWriter;
    var Scheme          = ModularInputs.Scheme;
    var Argument        = ModularInputs.Argument;
    var utils           = ModularInputs.utils;
    var testUtils       = require("./utils");

    splunkjs.Logger.setLevel("ALL");

    var TEST_SCRIPT_PATH = "__IGNORED_SCRIPT_PATH__";

    return {
        "ModularInput tests": {
            setUp: function(done) {
                done();
            },

            "ModularInputs logger works, severity: DEBUG": function(test) {
                var err = testUtils.getDuplexStream();
                try {
                    Logger.debug("Modular Input Tests", "Something happened!", err);
                    test.ok(utils.startsWith(err._read(), Logger.DEBUG));
                }
                catch (e) {
                    test.ok(false);
                }
                test.done();
            },

            "ModularInputs logger works, severity: INFO": function(test) {
                var err = testUtils.getDuplexStream();
                try {
                    Logger.info("Modular Input Tests", "Something happened!", err);
                    test.ok(utils.startsWith(err._read(), Logger.INFO));
                }
                catch (e) {
                    test.ok(false);
                }
                test.done();
            },

            "ModularInputs logger works, severity: WARN": function(test) {
                var err = testUtils.getDuplexStream();
                try {
                    Logger.warn("Modular Input Tests", "Something happened!", err);
                    test.ok(utils.startsWith(err._read(), Logger.WARN));
                }
                catch (e) {
                    test.ok(false);
                }
                test.done();
            },

            "ModularInputs logger works, severity: ERROR": function(test) {
                var err = testUtils.getDuplexStream();
                try {
                    Logger.error("Modular Input Tests", "Something happened!", err);
                    test.ok(utils.startsWith(err._read(), Logger.ERROR));
                }
                catch (e) {
                    test.ok(false);
                }
                test.done();
            },

            "ModularInputs logger works, severity: FATAL": function(test) {
                var err = testUtils.getDuplexStream();
                try {
                    Logger.fatal("Modular Input Tests", "Something happened!", err);
                    test.ok(utils.startsWith(err._read(), Logger.FATAL));
                }
                catch (e) {
                    test.ok(false);
                }
                test.done();
            },

            "An error happens when a ModularInput gets bad args": function(test) {
                // A script that returns a null scheme should generate no output on stdout
                // and an error on stderr saying that the scheme was null.

                exports.getScheme = function() {
                    return null;
                };

                exports.streamEvents = function() {
                    // Not used
                    return null;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var args = [TEST_SCRIPT_PATH, "foobar"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    var error = ew._err._read();

                    test.ok(utils.startsWith(error, "ERROR Modular input Invalid arguments to modular input script:"));
                    test.strictEqual(1, scriptStatus);
                    test.done();
                });
            },

            "An error happens when a ModularInput has a null scheme": function(test) {
                // A script that returns a null scheme should generate no output on stdout
                // and an error on stderr saying that the scheme was null.

                exports.getScheme = function() {
                    return null;
                };

                exports.streamEvents = function() {
                    // Not used
                    return null;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var args = [TEST_SCRIPT_PATH, "--scheme"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    var error = ew._err._read();

                    test.strictEqual(error, "FATAL Modular input script returned a null scheme.\n");
                    test.strictEqual(1, scriptStatus);
                    test.done();
                });
            },

            "ModularInput properly generates Scheme": function(test) {
                // Check that a scheme generated by a script is what we expect.

                exports.getScheme = function() {
                    var scheme = new Scheme("abcd");
                    scheme.description = "\uC3BC and \uC3B6 and <&> f\u00FCr";
                    scheme.streamingMode = Scheme.streamingModeSimple;
                    scheme.useExternalValidation = false;
                    scheme.useSingleInstance = true;

                    var arg1 = new Argument("arg1");
                    scheme.addArgument(arg1);

                    var arg2 = new Argument("arg2");
                    arg2.description = "\uC3BC and \uC3B6 and <&> f\u00FCr";
                    arg2.dataType = Argument.dataTypeNumber;
                    arg2.requiredOnCreate = true;
                    arg2.requiredOnEdit = true;
                    arg2.validation = "is_pos_int('some_name')";
                    scheme.addArgument(arg2);

                    return scheme;
                };

                exports.streamEvents = function() {
                    // Not used
                    return null;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var args = [TEST_SCRIPT_PATH, "--scheme"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    var expected = utils.readFile(__filename, "../data/scheme_without_defaults.xml");
                    var output = ew._out._read();

                    test.ok(testUtils.XMLCompare(ET.parse(expected), ET.parse(output)));
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
            },

            "ModularInput Input Validation succeeds": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.validateInput = function(definition, done) {
                    // Always succeed
                    done();
                };

                exports.streamEvents = function() {
                    // not used
                    return;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var validationFile = utils.readFile(__filename, "../data/validation.xml");

                var inStream = testUtils.getReadableStream();

                var args = [TEST_SCRIPT_PATH, "--validate-arguments"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(!err);

                    test.strictEqual("", ew._out._read());
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(validationFile));
            },

            "ModularInput Input Validation succeeds when validateInput is undefined": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.validateInput = undefined;

                exports.streamEvents = function() {
                    // not used
                    return;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var validationFile = utils.readFile(__filename, "../data/validation.xml");

                var inStream = testUtils.getReadableStream();

                var args = [TEST_SCRIPT_PATH, "--validate-arguments"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(!err);

                    test.strictEqual("", ew._out._read());
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(validationFile));
            },

            "ModularInput Input Validation times out after 30s with impartial XML": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.validateInput = function() {
                    return;
                };
                exports.validateInput = undefined;

                exports.streamEvents = function() {
                    // not used
                    return;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var validationFile = utils.readFile(__filename, "../data/validation.xml");

                var inStream = testUtils.getReadableStream();

                var startTime = Date.now();

                var args = [TEST_SCRIPT_PATH, "--validate-arguments"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(err);
                    test.strictEqual("Receiving validation definition prior to validating timed out.", err.message);

                    test.ok(Date.now() - startTime >= 30000); // Make sure it times out only after 30 seconds
                    test.strictEqual("", ew._out._read());
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(1, scriptStatus);
                    test.done();
                });
                // Remove the closing </items> tag to send impartial data
                inStream.emit("data", new Buffer(validationFile.replace("</items>", "")));
            },

            "ModularInput Input Validation fails": function(test) {
                // Make logger noop so testoutput is cleaner
                var loggerErrorBackup = Logger.error;
                Logger.error = function(){};

                exports.getScheme = function() {
                    return null;
                };

                exports.validateInput = function(definition, done) {
                    done(new Error("Big fat validation error!"));
                };

                exports.streamEvents = function() {
                    // not used
                    return;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var validationFile = utils.readFile(__filename, "../data/validation.xml");

                var args = [TEST_SCRIPT_PATH, "--validate-arguments"];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(err);
                    var output = ew._out._read();

                    var expected = ET.parse(utils.readFile(__filename, "../data/validation_error.xml")).getroot();
                    var found = ET.parse(output).getroot();

                    test.strictEqual(expected.tag, found.tag);
                    test.strictEqual(expected.text.trim(), found.text.trim());
                    test.strictEqual(expected.tail, found.tail);
                    test.strictEqual(expected.getchildren().length, found.getchildren().length);

                    var expectedChildren = expected.getchildren();
                    var foundChildren = found.getchildren();
                    for (var i = 0; i < expectedChildren.length; i++) {
                        var expectedchild = expectedChildren[i];
                        var foundChild = foundChildren[i];
                        test.strictEqual(expectedchild.tag, foundChild.tag);
                        test.strictEqual(expectedchild.text.trim(), foundChild.text.trim());
                        test.strictEqual(expectedchild.tail, foundChild.tail);
                    }

                    test.ok(testUtils.XMLCompare(expected, found));
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(1, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(validationFile));
            },

            "ModularInput streaming events works - 2 inputs": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.streamEvents = function(name, input, eventWriter, callback) {
                    var myEvent = new Event({
                        data: "This is a test of the emergency broadcast system.",
                        stanza: "fubar",
                        time: 1372275124.466,
                        host: "localhost",
                        index: "main",
                        source: "hilda",
                        sourcetype: "misc",
                        done: true,
                        unbroken: true
                    });

                    try {
                        eventWriter.writeEvent(myEvent);
                        callback(null);
                    }
                    catch (e) {
                        callback(e);
                    }
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_2_inputs.xml");

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(!err);

                    var expected = utils.readFile(__filename, "../data/stream_with_two_events.xml");
                    var found = ew._out._read();
                    test.ok(testUtils.XMLCompare(ET.parse(expected).getroot(), ET.parse(found).getroot()));
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(inputConfiguration));
            },

            "ModularInput streaming events works - 5 inputs": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                var num = 1;
                exports.streamEvents = function(name, input, eventWriter, callback) {
                    var myEvent = new Event({
                        data: "This is a test of the emergency broadcast system. " + num,
                        stanza: "fubar",
                        time: 1372275124.466,
                        host: "localhost",
                        index: "main",
                        source: "hilda",
                        sourcetype: "misc",
                        done: true,
                        unbroken: true
                    });

                    try {
                        eventWriter.writeEvent(myEvent);
                        num++;
                        callback(null);
                    }
                    catch (e) {
                        callback(e);
                    }
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_5_inputs.xml");

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(!err);

                    var expected = utils.readFile(__filename, "../data/stream_with_five_events.xml");
                    var found = ew._out._read();

                    var expectedChildren = ET.parse(expected).getroot().getchildren();
                    var foundChildren = ET.parse(found).getroot().getchildren();

                    // Loop through instead of comparing to hardcoded XML, since
                    // streamEvents() will be called several times in parallel
                    // and the events MAY not get streamed in the order they're sent.
                    var totalFound = 0;
                    // We're expecting 5 events to have data ending in a different value between 1 and 5
                    for (var i = 1; i <= 5; i++) {
                        // Iterate over the individual events
                        for (var c = 0; c < foundChildren.length; c++) {
                            // Iterate over the tags of the current event
                            var tags = foundChildren[c].getchildren();
                            for (var t = 0; t < tags.length; t++) {
                                // When we find the <data> tag, read the text and check if it ends with the current value we're looking for
                                // between 1 and 5
                                if (tags[t].tag === "data") {
                                    if (tags[t].text.indexOf("This is a test of the emergency broadcast system. " + i) >= 0) {
                                        totalFound++;
                                        i++;
                                    }
                                }
                            }
                        }
                    }

                    test.equal(5, totalFound); // Did we find as many events as we expected?
                    test.equal(5, expectedChildren.length);
                    test.equal(expectedChildren.length, foundChildren.length);

                    test.ok(testUtils.XMLCompare(ET.parse(expected).getroot(), ET.parse(found).getroot()));
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(inputConfiguration));
            },

            "ModularInput streaming events works - as object": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                var asObject = false;
                exports.streamEvents = function(name, input, eventWriter, callback) {
                    var myEvent = new Event({
                        data: "{\"some\":\"json\"}",
                        stanza: "fubar",
                        time: 1372275124.466,
                        host: "localhost",
                        index: "main",
                        source: "hilda",
                        sourcetype: "misc",
                        done: true,
                        unbroken: true
                    });

                    if (asObject) {
                        myEvent.data = {some:"json object"}; // Write a JS object
                    }

                    try {
                        eventWriter.writeEvent(myEvent);
                        asObject = true;
                        callback(null);
                    }
                    catch (e) {
                        callback(e);
                    }
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_2_inputs.xml");

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(!err);

                    var expected = utils.readFile(__filename, "../data/stream_with_two_json_events.xml");
                    var found = ew._out._read();

                    test.ok(asObject);
                    test.ok(testUtils.XMLCompare(ET.parse(expected).getroot(), ET.parse(found).getroot()));
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(inputConfiguration));
            },

            "ModularInput streaming events times out after 30s with impartial XML": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.streamEvents = function(name, input, eventWriter, callback) {
                    var myEvent = new Event({
                        data: "This is a test of the emergency broadcast system.",
                        stanza: "fubar",
                        time: 1372275124.466,
                        host: "localhost",
                        index: "main",
                        source: "hilda",
                        sourcetype: "misc",
                        done: true,
                        unbroken: true
                    });

                    try {
                        eventWriter.writeEvent(myEvent);
                        callback(null);
                    }
                    catch (e) {
                        callback(e);
                    }
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_2_inputs.xml");

                var startTime = Date.now();

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(err);
                    test.strictEqual("Receiving input definitions prior to streaming timed out.", err.message);

                    test.ok(Date.now() - startTime >= 30000); // Make sure it times out only after 30 seconds
                    test.strictEqual("", ew._out._read());
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(1, scriptStatus);
                    test.done();
                });
                // Remove the closing </input> tag to send impartial data
                inStream.emit("data", new Buffer(inputConfiguration.replace("</input>", "")));
            },

            "ModularInput streaming events times out after 30s with no data sent": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.streamEvents = function(name, input, eventWriter, callback) {
                    return;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_2_inputs.xml");

                var startTime = Date.now();

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(err);
                    test.strictEqual("Receiving input definitions prior to streaming timed out.", err.message);

                    test.ok(Date.now() - startTime >= 30000); // Make sure it times out only after 30 seconds
                    test.strictEqual("", ew._out._read());
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(1, scriptStatus);
                    test.done();
                });
            },

            "ModularInput streaming events times out after 30s with data sent after 30s": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.streamEvents = function(name, input, eventWriter, callback) {
                    return;
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_2_inputs.xml");

                var startTime = Date.now();

                // Emit the data 1.5 seconds after the timeout threshold
                setTimeout(function() {
                    inStream.emit("data", new Buffer(inputConfiguration));
                    test.done();
                }, 32000);

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(err);
                    test.strictEqual("Receiving input definitions prior to streaming timed out.", err.message);

                    test.ok(Date.now() - startTime >= 30000); // Make sure it times out only after 30 seconds
                    test.strictEqual("", ew._out._read());
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(1, scriptStatus);
                });
            },

            "ModularInput gets a valid Service": function(test) {
                exports.getScheme = function() {
                    return null;
                };

                exports.validateInput = function(definition) {
                    return null;
                };

                exports.streamEvents = function(name, input, eventWriter, callback) {
                    var service = ModularInput.service();

                    test.ok(service instanceof splunkjs.Service);
                    test.strictEqual(service.prefix, this._inputDefinition.metadata["server_uri"]);
                    callback(null);
                };

                var out = testUtils.getDuplexStream();
                var err = testUtils.getDuplexStream();
                var ew = new EventWriter(out, err);

                var inStream = testUtils.getReadableStream();

                var inputConfiguration = utils.readFile(__filename, "../data/conf_with_2_inputs.xml");

                test.ok(utils.isUndefined(ModularInput._service));

                var args = [TEST_SCRIPT_PATH];
                ModularInput.runScript(exports, args, ew, inStream, function(err, scriptStatus) {
                    test.ok(!err);
                    test.strictEqual("", ew._err._read());
                    test.strictEqual(0, scriptStatus);
                    test.done();
                });
                inStream.emit("data", new Buffer(inputConfiguration));
            }
        }
    };
};

if (module === require.main) {
    var splunkjs    = require('../../index');
    var test        = require('../../contrib/nodeunit/test_reporter');

    var suite = exports.setup();
    test.run([{"Tests": suite}]);
}

{'repo_name': 'splunk/splunk-sdk-javascript', 'stars': '161', 'repo_language': 'JavaScript', 'file_name': 'splunk.ui.timeline.js', 'mime_type': 'text/plain', 'hash': -1752934788750509608, 'source_dataset': 'data'}


uniform vec2 center;
uniform vec2 resolution;
uniform vec2 u_screenSize;
//uniform float     iChannelTime[4];       // channel playback time (in seconds)
//uniform vec3      iChannelResolution[4]; // channel resolution (in pixels)
vec4      iMouse = vec4(0,0,0,0);                // mouse pixel coords. xy: current (if MLB down), zw: click
//uniform sampler2D iChannel0;          // input channel. XX = 2D/Cube

/*by musk License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

 Trying to get some interesting looking lens flares.

 13/08/13:
 published

 muuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuusk!*/

uniform vec4 u_Time;

float noise(float t)
{
	return 0.;
}
float noise(vec2 t)
{
	return 0.;
}

vec3 lensflare(vec2 uv,vec2 pos)
{
	vec2 main = uv-pos;
	vec2 uvd = uv*(length(uv));

	float ang = atan(main.x,main.y);
	float dist=length(main); dist = pow(dist,.1);
	float n = noise(vec2(ang*16.0,dist*32.0));

	float f0 = 1.0/(length(uv-pos)*16.0+1.0);

	f0 = f0+f0*(sin(noise((pos.x+pos.y)*2.2+ang*4.0+5.954)*16.0)*.1+dist*.1+.8);

	float f1 = max(0.01-pow(length(uv+1.2*pos),1.9),.0)*7.0;

	float f2 = max(1.0/(1.0+32.0*pow(length(uvd+0.8*pos),2.0)),.0)*00.25;
	float f22 = max(1.0/(1.0+32.0*pow(length(uvd+0.85*pos),2.0)),.0)*00.23;
	float f23 = max(1.0/(1.0+32.0*pow(length(uvd+0.9*pos),2.0)),.0)*00.21;

	vec2 uvx = mix(uv,uvd,-0.5);

	float f4 = max(0.01-pow(length(uvx+0.4*pos),2.4),.0)*6.0;
	float f42 = max(0.01-pow(length(uvx+0.45*pos),2.4),.0)*5.0;
	float f43 = max(0.01-pow(length(uvx+0.5*pos),2.4),.0)*3.0;

	uvx = mix(uv,uvd,-.4);

	float f5 = max(0.01-pow(length(uvx+0.2*pos),5.5),.0)*2.0;
	float f52 = max(0.01-pow(length(uvx+0.4*pos),5.5),.0)*2.0;
	float f53 = max(0.01-pow(length(uvx+0.6*pos),5.5),.0)*2.0;

	uvx = mix(uv,uvd,-0.5);

	float f6 = max(0.01-pow(length(uvx-0.3*pos),1.6),.0)*6.0;
	float f62 = max(0.01-pow(length(uvx-0.325*pos),1.6),.0)*3.0;
	float f63 = max(0.01-pow(length(uvx-0.35*pos),1.6),.0)*5.0;

	vec3 c = vec3(.0);

	c.r+=f2+f4+f5+f6; c.g+=f22+f42+f52+f62; c.b+=f23+f43+f53+f63;
	c = c*1.3 - vec3(length(uvd)*.05);
	c+=vec3(f0);

	return c;
}

vec3 cc(vec3 color, float factor,float factor2) // color modifier
{
	float w = color.x+color.y+color.z;
	return mix(color,vec3(w)*factor,w*factor2);
}

void main(void)
{
#ifdef METAL
	vec2 fragCoord = vec2(gl_FragCoord.x, u_screenSize.y - gl_FragCoord.y);
#else
	vec2 fragCoord = gl_FragCoord.xy;
#endif
    vec2   iResolution = resolution;           // viewport resolution (in pixels)
    float  iGlobalTime = u_Time[1];           // shader playback time (in seconds)

	//vec2 uv = gl_FragCoord.xy / iResolution.xy - 0.5;
    vec2 uv = (fragCoord.xy - center.xy) / iResolution.xy;
	uv.x *= iResolution.x/iResolution.y; //fix aspect ratio
	vec3 mouse = vec3(iMouse.xy/iResolution.xy - 0.5,iMouse.z-.5);
	mouse.x *= iResolution.x/iResolution.y; //fix aspect ratio
	if (iMouse.z<.5)
	{
		mouse.x=sin(iGlobalTime)*.5;
		mouse.y=sin(iGlobalTime*.913)*.5;
	}

	vec3 color = vec3(1.4,1.2,1.0)*lensflare(uv,mouse.xy);
	color -= noise(fragCoord.xy)*.015;
	color = cc(color,.5,.1);
	gl_FragColor = vec4(color,1.0);
}

{'repo_name': 'cocos2d/cocos2d-x', 'stars': '14513', 'repo_language': 'C++', 'file_name': 'CocosBuildSet.cmake', 'mime_type': 'text/plain', 'hash': -8394603472404105614, 'source_dataset': 'data'}


<?php

/**
 * MembersOfBlogWidget виджет для вывода участников блога
 *
 * @author yupe team <team@yupe.ru>
 * @link https://yupe.ru
 * @copyright 2009-2013 amyLabs && Yupe! team
 * @package yupe.modules.blog.widgets
 * @since 0.1
 *
 */

Yii::import('application.modules.blog.models.*');

/**
 * Class MembersOfBlogWidget
 */
class MembersOfBlogWidget extends yupe\widgets\YWidget
{
    /**
     * @var
     */
    public $blogId;

    /**
     * @var
     */
    public $blog;

    /**
     * @var string
     */
    public $view = 'membersofblog';

    /**
     * @throws CException
     */
    public function run()
    {
        if (!$this->blog) {
            $this->blog = Blog::model()->with('members')->findByPk($this->blogId);
        }

        $this->render($this->view, ['model' => $this->blog]);
    }
}

{'repo_name': 'yupe/yupe', 'stars': '599', 'repo_language': 'PHP', 'file_name': 'index-test.php', 'mime_type': 'text/x-php', 'hash': -7483602232070123481, 'source_dataset': 'data'}


ZombieRocker[] =
{
	{Loot_GROUP,		6,		Consumable},
	{Loot_GROUP,		1,		AmmoCivilian},
	{Loot_MAGAZINE,		3,		ItemBandage},
	{Loot_MAGAZINE,		2,		ItemPainkiller},
	{Loot_MAGAZINE,		2,		ItemAntibacterialWipe},
	{Loot_MAGAZINE,		3,		ItemDocument}
};

ZombieRockerViral[] =
{
	{Loot_GROUP,		10,		ZombieRocker},
	{Loot_MAGAZINE,		1,		ItemAntibiotic1}
};

{'repo_name': 'EpochModTeam/DayZ-Epoch', 'stars': '201', 'repo_language': 'C++', 'file_name': 'rules.sqf', 'mime_type': 'text/plain', 'hash': 995873458034889603, 'source_dataset': 'data'}


/*!
 * Connect - cookieSession
 * Copyright(c) 2011 Sencha Inc.
 * MIT Licensed
 */

/**
 * Module dependencies.
 */

var utils = require('./../utils')
  , Cookie = require('./session/cookie')
  , debug = require('debug')('connect:cookieSession')
  , signature = require('cookie-signature')
  , crc32 = require('buffer-crc32');

/**
 * Cookie Session:
 *
 *   Cookie session middleware.
 *
 *      var app = connect();
 *      app.use(connect.cookieParser());
 *      app.use(connect.cookieSession({ secret: 'tobo!', cookie: { maxAge: 60 * 60 * 1000 }}));
 *
 * Options:
 *
 *   - `key` cookie name defaulting to `connect.sess`
 *   - `secret` prevents cookie tampering
 *   - `cookie` session cookie settings, defaulting to `{ path: '/', httpOnly: true, maxAge: null }`
 *   - `proxy` trust the reverse proxy when setting secure cookies (via "x-forwarded-proto")
 *
 * Clearing sessions:
 *
 *  To clear the session simply set its value to `null`,
 *  `cookieSession()` will then respond with a 1970 Set-Cookie.
 *
 *     req.session = null;
 *
 * @param {Object} options
 * @return {Function}
 * @api public
 */

module.exports = function cookieSession(options){
  // TODO: utilize Session/Cookie to unify API
  options = options || {};
  var key = options.key || 'connect.sess'
    , trustProxy = options.proxy;

  return function cookieSession(req, res, next) {

    // req.secret is for backwards compatibility
    var secret = options.secret || req.secret;
    if (!secret) throw new Error('`secret` option required for cookie sessions');

    // default session
    req.session = {};
    var cookie = req.session.cookie = new Cookie(options.cookie);

    // pathname mismatch
    if (0 != req.originalUrl.indexOf(cookie.path)) return next();

    // cookieParser secret
    if (!options.secret && req.secret) {
      req.session = req.signedCookies[key] || {};
      req.session.cookie = cookie;
    } else {
      // TODO: refactor
      var rawCookie = req.cookies[key];
      if (rawCookie) {
        var unsigned = utils.parseSignedCookie(rawCookie, secret);
        if (unsigned) {
          var originalHash = crc32.signed(unsigned);
          req.session = utils.parseJSONCookie(unsigned) || {};
          req.session.cookie = cookie;
        }
      }
    }

    res.on('header', function(){
      // removed
      if (!req.session) {
        debug('clear session');
        cookie.expires = new Date(0);
        res.setHeader('Set-Cookie', cookie.serialize(key, ''));
        return;
      }

      delete req.session.cookie;

      // check security
      var proto = (req.headers['x-forwarded-proto'] || '').toLowerCase()
        , tls = req.connection.encrypted || (trustProxy && 'https' == proto.split(/\s*,\s*/)[0])
        , secured = cookie.secure && tls;

      // only send secure cookies via https
      if (cookie.secure && !secured) return debug('not secured');

      // serialize
      debug('serializing %j', req.session);
      var val = 'j:' + JSON.stringify(req.session);

      // compare hashes, no need to set-cookie if unchanged
      if (originalHash == crc32.signed(val)) return debug('unmodified session');

      // set-cookie
      val = 's:' + signature.sign(val, secret);
      val = cookie.serialize(key, val);
      debug('set-cookie %j', cookie);
      res.setHeader('Set-Cookie', val);
    });

    next();
  };
};

{'repo_name': 'tangguangyao/know', 'stars': '106', 'repo_language': 'JavaScript', 'file_name': 'show.ejs', 'mime_type': 'text/html', 'hash': 3083520600179912567, 'source_dataset': 'data'}


package com.szmirren.vxApi.core.common;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

import io.netty.handler.codec.http.QueryStringDecoder;
import io.vertx.core.MultiMap;
import io.vertx.core.http.CaseInsensitiveHeaders;

/**
 * HTTP相关的工具
 *
 * @author Mirren
 *
 */
public class HttpUtils {
	/**
	 * 解码URI中的参数,既?后面的参数
	 *
	 * @param uri
	 *          uri参数,默认以utf-8方式
	 * @return 返回解码后的结果或者返回新的MultiMap
	 */
	public static MultiMap decoderUriParams(String uri) {
		return decoderUriParams(uri, Charset.forName("UTF-8"));
	}

	/**
	 * 解码URI中的参数,既?后面的参数
	 *
	 * @param uri
	 *          uri参数
	 * @param charset
	 *          解码格式,如果该字段为空则默认为utf-8方式
	 * @return 返回解码后的结果或者返回新的MultiMap,如果发生异常返回新的MultiMap
	 */
	public static MultiMap decoderUriParams(String uri, Charset charset) {
		try {
			if (charset == null) {
				charset = Charset.forName("UTF-8");
			}
			QueryStringDecoder decode = new QueryStringDecoder(uri, charset, false);
			Map<String, List<String>> paramMap = decode.parameters();
			MultiMap params = new CaseInsensitiveHeaders();
			if (!paramMap.isEmpty()) {
				for (Map.Entry<String, List<String>> entry : paramMap.entrySet()) {
					params.add(entry.getKey(), entry.getValue());
				}
			}
			return params;
		} catch (Exception e) {
			return new CaseInsensitiveHeaders();
		}
	}
}

{'repo_name': 'EliMirren/VX-API-Gateway', 'stars': '293', 'repo_language': 'Java', 'file_name': 'GetServerUnixTimestampHandler.java', 'mime_type': 'text/html', 'hash': -8039124371774174235, 'source_dataset': 'data'}


// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2012 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2012 Mateusz Loskot, London, UK.
// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_ALGORITHMS_REVERSE_HPP
#define BOOST_GEOMETRY_ALGORITHMS_REVERSE_HPP

#include <algorithm>

#include <boost/range.hpp>
#include <boost/type_traits/remove_reference.hpp>

#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/static_visitor.hpp>
#include <boost/variant/variant_fwd.hpp>

#include <boost/geometry/algorithms/detail/interior_iterator.hpp>
#include <boost/geometry/algorithms/detail/multi_modify.hpp>
#include <boost/geometry/core/interior_rings.hpp>
#include <boost/geometry/core/tags.hpp>
#include <boost/geometry/geometries/concepts/check.hpp>

namespace boost { namespace geometry
{

#ifndef DOXYGEN_NO_DETAIL
namespace detail { namespace reverse
{

struct range_reverse
{
    template <typename Range>
    static inline void apply(Range& range)
    {
        std::reverse(boost::begin(range), boost::end(range));
    }
};

struct polygon_reverse: private range_reverse
{
    template <typename Polygon>
    static inline void apply(Polygon& polygon)
    {
        range_reverse::apply(exterior_ring(polygon));

        typename interior_return_type<Polygon>::type
            rings = interior_rings(polygon);

        for (typename detail::interior_iterator<Polygon>::type
                it = boost::begin(rings); it != boost::end(rings); ++it)
        {
            range_reverse::apply(*it);
        }
    }
};

}} // namespace detail::reverse
#endif // DOXYGEN_NO_DETAIL

#ifndef DOXYGEN_NO_DISPATCH
namespace dispatch
{

template <typename Geometry, typename Tag = typename tag<Geometry>::type>
struct reverse
{
    static inline void apply(Geometry&)
    {}
};

template <typename Ring>
struct reverse<Ring, ring_tag>
    : detail::reverse::range_reverse
{};

template <typename LineString>
struct reverse<LineString, linestring_tag>
    : detail::reverse::range_reverse
{};

template <typename Polygon>
struct reverse<Polygon, polygon_tag>
    : detail::reverse::polygon_reverse
{};

template <typename Geometry>
struct reverse<Geometry, multi_linestring_tag>
    : detail::multi_modify
        <
            Geometry,
            detail::reverse::range_reverse
        >
{};

template <typename Geometry>
struct reverse<Geometry, multi_polygon_tag>
    : detail::multi_modify
        <
            Geometry,
            detail::reverse::polygon_reverse
        >
{};

} // namespace dispatch
#endif

namespace resolve_variant
{

template <typename Geometry>
struct reverse
{
    static void apply(Geometry& geometry)
    {
        concept::check<Geometry>();
        dispatch::reverse<Geometry>::apply(geometry);
    }
};

template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
struct reverse<boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> >
{
    struct visitor: boost::static_visitor<void>
    {
        template <typename Geometry>
        void operator()(Geometry& geometry) const
        {
            reverse<Geometry>::apply(geometry);
        }
    };

    static inline void apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)>& geometry)
    {
        boost::apply_visitor(visitor(), geometry);
    }
};

} // namespace resolve_variant

/*!
\brief Reverses the points within a geometry
\details Generic function to reverse a geometry. It resembles the std::reverse
   functionality, but it takes the geometry type into account. Only for a ring
   or for a linestring it is the same as the std::reverse.
\ingroup reverse
\tparam Geometry \tparam_geometry
\param geometry \param_geometry which will be reversed

\qbk{[include reference/algorithms/reverse.qbk]}
*/
template <typename Geometry>
inline void reverse(Geometry& geometry)
{
    resolve_variant::reverse<Geometry>::apply(geometry);
}

}} // namespace boost::geometry

#endif // BOOST_GEOMETRY_ALGORITHMS_REVERSE_HPP

{'repo_name': 'Achain-Dev/Achain', 'stars': '176', 'repo_language': 'C++', 'file_name': 'dumpfile.h', 'mime_type': 'text/x-c++', 'hash': 5447929215890197942, 'source_dataset': 'data'}


// Code generated by protoc-gen-go. DO NOT EDIT.
// source: google/protobuf/struct.proto

package structpb

import (
	fmt "fmt"
	proto "github.com/golang/protobuf/proto"
	math "math"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package

// `NullValue` is a singleton enumeration to represent the null value for the
// `Value` type union.
//
//  The JSON representation for `NullValue` is JSON `null`.
type NullValue int32

const (
	// Null value.
	NullValue_NULL_VALUE NullValue = 0
)

var NullValue_name = map[int32]string{
	0: "NULL_VALUE",
}

var NullValue_value = map[string]int32{
	"NULL_VALUE": 0,
}

func (x NullValue) String() string {
	return proto.EnumName(NullValue_name, int32(x))
}

func (NullValue) EnumDescriptor() ([]byte, []int) {
	return fileDescriptor_df322afd6c9fb402, []int{0}
}

func (NullValue) XXX_WellKnownType() string { return "NullValue" }

// `Struct` represents a structured data value, consisting of fields
// which map to dynamically typed values. In some languages, `Struct`
// might be supported by a native representation. For example, in
// scripting languages like JS a struct is represented as an
// object. The details of that representation are described together
// with the proto support for the language.
//
// The JSON representation for `Struct` is JSON object.
type Struct struct {
	// Unordered map of dynamically typed values.
	Fields               map[string]*Value `protobuf:"bytes,1,rep,name=fields,proto3" json:"fields,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
	XXX_NoUnkeyedLiteral struct{}          `json:"-"`
	XXX_unrecognized     []byte            `json:"-"`
	XXX_sizecache        int32             `json:"-"`
}

func (m *Struct) Reset()         { *m = Struct{} }
func (m *Struct) String() string { return proto.CompactTextString(m) }
func (*Struct) ProtoMessage()    {}
func (*Struct) Descriptor() ([]byte, []int) {
	return fileDescriptor_df322afd6c9fb402, []int{0}
}

func (*Struct) XXX_WellKnownType() string { return "Struct" }

func (m *Struct) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Struct.Unmarshal(m, b)
}
func (m *Struct) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Struct.Marshal(b, m, deterministic)
}
func (m *Struct) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Struct.Merge(m, src)
}
func (m *Struct) XXX_Size() int {
	return xxx_messageInfo_Struct.Size(m)
}
func (m *Struct) XXX_DiscardUnknown() {
	xxx_messageInfo_Struct.DiscardUnknown(m)
}

var xxx_messageInfo_Struct proto.InternalMessageInfo

func (m *Struct) GetFields() map[string]*Value {
	if m != nil {
		return m.Fields
	}
	return nil
}

// `Value` represents a dynamically typed value which can be either
// null, a number, a string, a boolean, a recursive struct value, or a
// list of values. A producer of value is expected to set one of that
// variants, absence of any variant indicates an error.
//
// The JSON representation for `Value` is JSON value.
type Value struct {
	// The kind of value.
	//
	// Types that are valid to be assigned to Kind:
	//	*Value_NullValue
	//	*Value_NumberValue
	//	*Value_StringValue
	//	*Value_BoolValue
	//	*Value_StructValue
	//	*Value_ListValue
	Kind                 isValue_Kind `protobuf_oneof:"kind"`
	XXX_NoUnkeyedLiteral struct{}     `json:"-"`
	XXX_unrecognized     []byte       `json:"-"`
	XXX_sizecache        int32        `json:"-"`
}

func (m *Value) Reset()         { *m = Value{} }
func (m *Value) String() string { return proto.CompactTextString(m) }
func (*Value) ProtoMessage()    {}
func (*Value) Descriptor() ([]byte, []int) {
	return fileDescriptor_df322afd6c9fb402, []int{1}
}

func (*Value) XXX_WellKnownType() string { return "Value" }

func (m *Value) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_Value.Unmarshal(m, b)
}
func (m *Value) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_Value.Marshal(b, m, deterministic)
}
func (m *Value) XXX_Merge(src proto.Message) {
	xxx_messageInfo_Value.Merge(m, src)
}
func (m *Value) XXX_Size() int {
	return xxx_messageInfo_Value.Size(m)
}
func (m *Value) XXX_DiscardUnknown() {
	xxx_messageInfo_Value.DiscardUnknown(m)
}

var xxx_messageInfo_Value proto.InternalMessageInfo

type isValue_Kind interface {
	isValue_Kind()
}

type Value_NullValue struct {
	NullValue NullValue `protobuf:"varint,1,opt,name=null_value,json=nullValue,proto3,enum=google.protobuf.NullValue,oneof"`
}

type Value_NumberValue struct {
	NumberValue float64 `protobuf:"fixed64,2,opt,name=number_value,json=numberValue,proto3,oneof"`
}

type Value_StringValue struct {
	StringValue string `protobuf:"bytes,3,opt,name=string_value,json=stringValue,proto3,oneof"`
}

type Value_BoolValue struct {
	BoolValue bool `protobuf:"varint,4,opt,name=bool_value,json=boolValue,proto3,oneof"`
}

type Value_StructValue struct {
	StructValue *Struct `protobuf:"bytes,5,opt,name=struct_value,json=structValue,proto3,oneof"`
}

type Value_ListValue struct {
	ListValue *ListValue `protobuf:"bytes,6,opt,name=list_value,json=listValue,proto3,oneof"`
}

func (*Value_NullValue) isValue_Kind() {}

func (*Value_NumberValue) isValue_Kind() {}

func (*Value_StringValue) isValue_Kind() {}

func (*Value_BoolValue) isValue_Kind() {}

func (*Value_StructValue) isValue_Kind() {}

func (*Value_ListValue) isValue_Kind() {}

func (m *Value) GetKind() isValue_Kind {
	if m != nil {
		return m.Kind
	}
	return nil
}

func (m *Value) GetNullValue() NullValue {
	if x, ok := m.GetKind().(*Value_NullValue); ok {
		return x.NullValue
	}
	return NullValue_NULL_VALUE
}

func (m *Value) GetNumberValue() float64 {
	if x, ok := m.GetKind().(*Value_NumberValue); ok {
		return x.NumberValue
	}
	return 0
}

func (m *Value) GetStringValue() string {
	if x, ok := m.GetKind().(*Value_StringValue); ok {
		return x.StringValue
	}
	return ""
}

func (m *Value) GetBoolValue() bool {
	if x, ok := m.GetKind().(*Value_BoolValue); ok {
		return x.BoolValue
	}
	return false
}

func (m *Value) GetStructValue() *Struct {
	if x, ok := m.GetKind().(*Value_StructValue); ok {
		return x.StructValue
	}
	return nil
}

func (m *Value) GetListValue() *ListValue {
	if x, ok := m.GetKind().(*Value_ListValue); ok {
		return x.ListValue
	}
	return nil
}

// XXX_OneofWrappers is for the internal use of the proto package.
func (*Value) XXX_OneofWrappers() []interface{} {
	return []interface{}{
		(*Value_NullValue)(nil),
		(*Value_NumberValue)(nil),
		(*Value_StringValue)(nil),
		(*Value_BoolValue)(nil),
		(*Value_StructValue)(nil),
		(*Value_ListValue)(nil),
	}
}

// `ListValue` is a wrapper around a repeated field of values.
//
// The JSON representation for `ListValue` is JSON array.
type ListValue struct {
	// Repeated field of dynamically typed values.
	Values               []*Value `protobuf:"bytes,1,rep,name=values,proto3" json:"values,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *ListValue) Reset()         { *m = ListValue{} }
func (m *ListValue) String() string { return proto.CompactTextString(m) }
func (*ListValue) ProtoMessage()    {}
func (*ListValue) Descriptor() ([]byte, []int) {
	return fileDescriptor_df322afd6c9fb402, []int{2}
}

func (*ListValue) XXX_WellKnownType() string { return "ListValue" }

func (m *ListValue) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ListValue.Unmarshal(m, b)
}
func (m *ListValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ListValue.Marshal(b, m, deterministic)
}
func (m *ListValue) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ListValue.Merge(m, src)
}
func (m *ListValue) XXX_Size() int {
	return xxx_messageInfo_ListValue.Size(m)
}
func (m *ListValue) XXX_DiscardUnknown() {
	xxx_messageInfo_ListValue.DiscardUnknown(m)
}

var xxx_messageInfo_ListValue proto.InternalMessageInfo

func (m *ListValue) GetValues() []*Value {
	if m != nil {
		return m.Values
	}
	return nil
}

func init() {
	proto.RegisterEnum("google.protobuf.NullValue", NullValue_name, NullValue_value)
	proto.RegisterType((*Struct)(nil), "google.protobuf.Struct")
	proto.RegisterMapType((map[string]*Value)(nil), "google.protobuf.Struct.FieldsEntry")
	proto.RegisterType((*Value)(nil), "google.protobuf.Value")
	proto.RegisterType((*ListValue)(nil), "google.protobuf.ListValue")
}

func init() { proto.RegisterFile("google/protobuf/struct.proto", fileDescriptor_df322afd6c9fb402) }

var fileDescriptor_df322afd6c9fb402 = []byte{
	// 417 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0x41, 0x8b, 0xd3, 0x40,
	0x14, 0xc7, 0x3b, 0xc9, 0x36, 0x98, 0x17, 0x59, 0x97, 0x11, 0xb4, 0xac, 0xa2, 0xa1, 0x7b, 0x09,
	0x22, 0x29, 0xd6, 0x8b, 0x18, 0x2f, 0x06, 0xd6, 0x5d, 0x30, 0x2c, 0x31, 0xba, 0x15, 0xbc, 0x94,
	0x26, 0x4d, 0x63, 0xe8, 0x74, 0x26, 0x24, 0x33, 0x4a, 0x8f, 0x7e, 0x0b, 0xcf, 0x1e, 0x3d, 0xfa,
	0xe9, 0x3c, 0xca, 0xcc, 0x24, 0xa9, 0xb4, 0xf4, 0x94, 0xbc, 0xf7, 0x7e, 0xef, 0x3f, 0xef, 0xff,
	0x66, 0xe0, 0x71, 0xc1, 0x58, 0x41, 0xf2, 0x49, 0x55, 0x33, 0xce, 0x52, 0xb1, 0x9a, 0x34, 0xbc,
	0x16, 0x19, 0xf7, 0x55, 0x8c, 0xef, 0xe9, 0xaa, 0xdf, 0x55, 0xc7, 0x3f, 0x11, 0x58, 0x1f, 0x15,
	0x81, 0x03, 0xb0, 0x56, 0x65, 0x4e, 0x96, 0xcd, 0x08, 0xb9, 0xa6, 0xe7, 0x4c, 0x2f, 0xfc, 0x3d,
	0xd8, 0xd7, 0xa0, 0xff, 0x4e, 0x51, 0x97, 0x94, 0xd7, 0xdb, 0xa4, 0x6d, 0x39, 0xff, 0x00, 0xce,
	0x7f, 0x69, 0x7c, 0x06, 0xe6, 0x3a, 0xdf, 0x8e, 0x90, 0x8b, 0x3c, 0x3b, 0x91, 0xbf, 0xf8, 0x39,
	0x0c, 0xbf, 0x2d, 0x88, 0xc8, 0x47, 0x86, 0x8b, 0x3c, 0x67, 0xfa, 0xe0, 0x40, 0x7c, 0x26, 0xab,
	0x89, 0x86, 0x5e, 0x1b, 0xaf, 0xd0, 0xf8, 0x8f, 0x01, 0x43, 0x95, 0xc4, 0x01, 0x00, 0x15, 0x84,
	0xcc, 0xb5, 0x80, 0x14, 0x3d, 0x9d, 0x9e, 0x1f, 0x08, 0xdc, 0x08, 0x42, 0x14, 0x7f, 0x3d, 0x48,
	0x6c, 0xda, 0x05, 0xf8, 0x02, 0xee, 0x52, 0xb1, 0x49, 0xf3, 0x7a, 0xbe, 0x3b, 0x1f, 0x5d, 0x0f,
	0x12, 0x47, 0x67, 0x7b, 0xa8, 0xe1, 0x75, 0x49, 0x8b, 0x16, 0x32, 0xe5, 0xe0, 0x12, 0xd2, 0x59,
	0x0d, 0x3d, 0x05, 0x48, 0x19, 0xeb, 0xc6, 0x38, 0x71, 0x91, 0x77, 0x47, 0x1e, 0x25, 0x73, 0x1a,
	0x78, 0xa3, 0x54, 0x44, 0xc6, 0x5b, 0x64, 0xa8, 0xac, 0x3e, 0x3c, 0xb2, 0xc7, 0x56, 0x5e, 0x64,
	0xbc, 0x77, 0x49, 0xca, 0xa6, 0xeb, 0xb5, 0x54, 0xef, 0xa1, 0xcb, 0xa8, 0x6c, 0x78, 0xef, 0x92,
	0x74, 0x41, 0x68, 0xc1, 0xc9, 0xba, 0xa4, 0xcb, 0x71, 0x00, 0x76, 0x4f, 0x60, 0x1f, 0x2c, 0x25,
	0xd6, 0xdd, 0xe8, 0xb1, 0xa5, 0xb7, 0xd4, 0xb3, 0x47, 0x60, 0xf7, 0x4b, 0xc4, 0xa7, 0x00, 0x37,
	0xb7, 0x51, 0x34, 0x9f, 0xbd, 0x8d, 0x6e, 0x2f, 0xcf, 0x06, 0xe1, 0x0f, 0x04, 0xf7, 0x33, 0xb6,
	0xd9, 0x97, 0x08, 0x1d, 0xed, 0x26, 0x96, 0x71, 0x8c, 0xbe, 0xbc, 0x28, 0x4a, 0xfe, 0x55, 0xa4,
	0x7e, 0xc6, 0x36, 0x93, 0x82, 0x91, 0x05, 0x2d, 0x76, 0x4f, 0xb1, 0xe2, 0xdb, 0x2a, 0x6f, 0xda,
	0x17, 0x19, 0xe8, 0x4f, 0x95, 0xfe, 0x45, 0xe8, 0x97, 0x61, 0x5e, 0xc5, 0xe1, 0x6f, 0xe3, 0xc9,
	0x95, 0x16, 0x8f, 0xbb, 0xf9, 0x3e, 0xe7, 0x84, 0xbc, 0xa7, 0xec, 0x3b, 0xfd, 0x24, 0x3b, 0x53,
	0x4b, 0x49, 0xbd, 0xfc, 0x17, 0x00, 0x00, 0xff, 0xff, 0xe8, 0x1b, 0x59, 0xf8, 0xe5, 0x02, 0x00,
	0x00,
}

{'repo_name': 'munnerz/kubewg', 'stars': '135', 'repo_language': 'Go', 'file_name': 'main.go', 'mime_type': 'text/x-c', 'hash': -1351727782000956420, 'source_dataset': 'data'}


/*
 * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package javax.lang.model.element;

import java.util.Map;
import javax.lang.model.type.DeclaredType;

/**
 * Represents an annotation.  An annotation associates a value with
 * each element of an annotation type.
 *
 *
 Annotations should be compared using the {@code equals}
 * method.  There is no guarantee that any particular annotation will
 * always be represented by the same object.
 *
 * @author Joseph D. Darcy
 * @author Scott Seligman
 * @author Peter von der Ahé
 * @since 1.6
 */
public interface AnnotationMirror {

    /**
     * Returns the type of this annotation.
     *
     * @return the type of this annotation
     */
    DeclaredType getAnnotationType();

    /**
     * Returns the values of this annotation's elements.
     * This is returned in the form of a map that associates elements
     * with their corresponding values.
     * Only those elements with values explicitly present in the
     * annotation are included, not those that are implicitly assuming
     * their default values.
     * The order of the map matches the order in which the
     * values appear in the annotation's source.
     *
     *
Note that an annotation mirror of a marker annotation type
     * will by definition have an empty map.
     *
     *
To fill in default values, use {@link
     * javax.lang.model.util.Elements#getElementValuesWithDefaults
     * getElementValuesWithDefaults}.
     *
     * @return the values of this annotation's elements,
     *          or an empty map if there are none
     */
    Map<? extends ExecutableElement, ? extends AnnotationValue> getElementValues();
}

{'repo_name': 'AdoptOpenJDK/openjdk-jdk11', 'stars': '130', 'repo_language': 'Java', 'file_name': 'markSweep.cpp', 'mime_type': 'text/x-c', 'hash': -6276541138459622741, 'source_dataset': 'data'}


// stdafx.h : include file for standard system include files,
//  or project specific include files that are used frequently, but
//      are changed infrequently
//

#if !defined(AFX_STDAFX_H__67B7A4EE_2E7B_4E7B_8D52_7BF588CF5304__INCLUDED_)
#define AFX_STDAFX_H__67B7A4EE_2E7B_4E7B_8D52_7BF588CF5304__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

// TODO: reference additional headers your program requires here
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include "PELock.h"

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_STDAFX_H__67B7A4EE_2E7B_4E7B_8D52_7BF588CF5304__INCLUDED_)

{'repo_name': 'PELock/PELock-Software-Protection-and-Licensing-SDK', 'stars': '101', 'repo_language': 'C++', 'file_name': 'stdafx.h', 'mime_type': 'text/x-c', 'hash': 8466396564719964164, 'source_dataset': 'data'}


function varargout = process_import_data_event( varargin )
% PROCESS_IMPORT_DATA_EVENT: Import continuous files in the database, based on event markers.

% @=============================================================================
% This function is part of the Brainstorm software:
% https://neuroimage.usc.edu/brainstorm
%
% Copyright (c)2000-2020 University of Southern California & McGill University
% This software is distributed under the terms of the GNU General Public License
% as published by the Free Software Foundation. Further details on the GPLv3
% license can be found at http://www.gnu.org/copyleft/gpl.html.
%
% FOR RESEARCH PURPOSES ONLY. THE SOFTWARE IS PROVIDED "AS IS," AND THE
% UNIVERSITY OF SOUTHERN CALIFORNIA AND ITS COLLABORATORS DO NOT MAKE ANY
% WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO WARRANTIES OF
% MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, NOR DO THEY ASSUME ANY
% LIABILITY OR RESPONSIBILITY FOR THE USE OF THIS SOFTWARE.
%
% For more information type "brainstorm license" at command prompt.
% =============================================================================@
%
% Authors: Francois Tadel, 2012-2019

eval(macro_method);
end

%% ===== GET DESCRIPTION =====
function sProcess = GetDescription() %#ok<DEFNU>
    % Description the process
    sProcess.Comment     = 'Import MEG/EEG: Events';
    sProcess.Category    = 'File';
    sProcess.SubGroup    = {'Import', 'Import recordings'};
    sProcess.Index       = 22;
    sProcess.Description = 'https://neuroimage.usc.edu/brainstorm/Tutorials/Epoching';
    % Definition of the input accepted by this process
    sProcess.InputTypes  = {'import', 'raw',  'data'};
    sProcess.OutputTypes = {'data',   'data', 'data'};
    sProcess.nInputs     = 1;
    sProcess.nMinFiles   = 0;
    % Option: Subject name
    sProcess.options.subjectname.Comment = 'Subject name:';
    sProcess.options.subjectname.Type    = 'subjectname';
    sProcess.options.subjectname.Value   = 'NewSubject';
    % Option: Condition
    sProcess.options.condition.Comment = 'Folder name:';
    sProcess.options.condition.Type    = 'text';
    sProcess.options.condition.Value   = '';
    % Option: File to import (only if not processing the output of another process)
    sProcess.options.datafile.Comment    = 'Files to import:';
    sProcess.options.datafile.Type       = 'datafile';
    sProcess.options.datafile.InputTypes = {'import'};
    sProcess.options.datafile.Value      = {...
        '', ...                                % Filename
        '', ...                                % FileFormat
        'open', ...                            % Dialog type: {open,save}
        'Import EEG/MEG recordings...', ...    % Window title
        'ImportData', ...                      % LastUsedDir: {ImportData,ImportChannel,ImportAnat,ExportChannel,ExportData,ExportAnat,ExportProtocol,ExportImage,ExportScript}
        'multiple', ...                        % Selection mode: {single,multiple}
        'files_and_dirs', ...                  % Selection mode: {files,dirs,files_and_dirs}
        bst_get('FileFilters', 'raw'), ...    % Get all the available file formats
        'DataIn'};                             % Default file format (field name in DefaultFormats)
    % Separator
    sProcess.options.sep2.Type    = 'separator';
    sProcess.options.sep2.Comment = ' ';
    % Event name
    sProcess.options.labelevt.Comment = 'To import multiple events: separate them with commas,
or use regular expressions (eg. evt.* selects evt1, evtA, evtTest...) ';
    sProcess.options.labelevt.Type    = 'label';
    sProcess.options.eventname.Comment = 'Event names: ';
    sProcess.options.eventname.Type    = 'text';
    sProcess.options.eventname.Value   = '';
    % Time window
    sProcess.options.timewindow.Comment = 'Time window: ';
    sProcess.options.timewindow.Type    = 'timewindow';
    sProcess.options.timewindow.Value   = [];
    % Epoch time
    sProcess.options.epochtime.Comment = 'Epoch time: ';
    sProcess.options.epochtime.Type    = 'range';
    sProcess.options.epochtime.Value   = {[-0.100, 0.300], 'ms', []};
    % Separator
    sProcess.options.separator.Type = 'separator';
    sProcess.options.separator.Comment = ' ';
    % Create conditions
    sProcess.options.createcond.Comment = 'Create a separate folder for each event type';
    sProcess.options.createcond.Type    = 'checkbox';
    sProcess.options.createcond.Value   = 1;
    % Ignore shorter epochs
    sProcess.options.ignoreshort.Comment = 'Ignore shorter epochs';
    sProcess.options.ignoreshort.Type    = 'checkbox';
    sProcess.options.ignoreshort.Value   = 1;
    % Align sensors
    sProcess.options.channelalign.Comment = 'Align sensors using headpoints';
    sProcess.options.channelalign.Type    = 'checkbox';
    sProcess.options.channelalign.Value   = 1;
    sProcess.options.channelalign.InputTypes = {'import'};
    % Use CTF Comp
    sProcess.options.usectfcomp.Comment = 'Use CTF compensation';
    sProcess.options.usectfcomp.Type    = 'checkbox';
    sProcess.options.usectfcomp.Value   = 1;
    % Use SSP/ICA
    sProcess.options.usessp.Comment = 'Use SSP/ICA projectors';
    sProcess.options.usessp.Type    = 'checkbox';
    sProcess.options.usessp.Value   = 1;
    % Don't forget DC/resample
    sProcess.options.labeldc.Comment = '
Remove DC offset and Resample: add separate processes.

';
    sProcess.options.labeldc.Type    = 'label';
    % Resample (not displayed)
    sProcess.options.freq.Comment = 'Resample: ';
    sProcess.options.freq.Type    = 'Value';
    sProcess.options.freq.Value   = [];
    sProcess.options.freq.Hidden  = 1;
    % Remove DC offset (not displayed)
    sProcess.options.baseline.Comment = 'Remove DC offset: ';
    sProcess.options.baseline.Type    = 'baseline';
    sProcess.options.baseline.Value   = [];
    sProcess.options.baseline.Hidden  = 1;
end

%% ===== FORMAT COMMENT =====
function Comment = FormatComment(sProcess) %#ok<DEFNU>
    Comment = sProcess.Comment;
end

%% ===== RUN =====
function OutputFiles = Run(sProcess, sInput) %#ok<DEFNU>
    OutputFiles = {};

    % ===== GET FILES TO IMPORT =====
    % Get filename to import
    isDirectImport = isfield(sProcess.options, 'datafile') && ~isempty(sProcess.options.datafile.Value) && ~isempty(sProcess.options.datafile.Value{1});
    if isDirectImport
        FileNames  = sProcess.options.datafile.Value{1};
        FileFormat = sProcess.options.datafile.Value{2};
    elseif ~isempty(sInput)
        % Error if nothing in input
        if strcmpi(sInput(1).FileType, 'import')
            bst_report('Error', sProcess, sInput, 'No file selected.');
            return
        end
        % Get file info
        isRaw = strcmpi(sInput(1).FileType, 'raw');
        FileNames = {sInput.FileName};
        if isRaw
            FileMat    = in_bst_data(FileNames{1}, 'F');
            sFile      = FileMat.F;
            FileFormat = sFile.format;
            % Read channel file
            ChannelFile = bst_get('ChannelFileForStudy', FileNames{1});
            ChannelMat = in_bst_channel(ChannelFile);
        else
            FileFormat = 'BST-DATA';
            [sFile, ChannelMat] = in_fopen(FileNames{1}, FileFormat);
        end
    else
        FileNames = {};
    end
    % No files in input
    if isempty(FileNames)
        bst_report('Error', sProcess, sInput, 'No file selected.');
        return
    end

    % ===== GET OPTIONS =====
    % Get subject name
    SubjectName = file_standardize(sProcess.options.subjectname.Value);
    if isempty(SubjectName) && ~isempty(sInput.SubjectName)
        SubjectName = sInput.SubjectName;
    elseif isempty(SubjectName)
        bst_report('Error', sProcess, sInput, 'Subject name is empty.');
        return
    end
    % Get condition name
    CreateConditions = sProcess.options.createcond.Value;
    if CreateConditions
        Condition = [];
    else
        Condition = file_standardize(sProcess.options.condition.Value);
    end
    % Get time range
    if isfield(sProcess.options, 'timewindow') && isfield(sProcess.options.timewindow, 'Value') && iscell(sProcess.options.timewindow.Value) && ~isempty(sProcess.options.timewindow.Value)
        TimeRange = sProcess.options.timewindow.Value{1};
    else
        TimeRange = [];
    end
    % Event names
    EvtNames = strtrim(str_split(sProcess.options.eventname.Value, ',;'));
    if isempty(EvtNames)
        bst_report('Error', sProcess, [], 'No events to import.');
        return;
    end
    % Channel align: only if not import from a link to raw file
    if isfield(sProcess.options, 'channelalign') && ~isempty(sProcess.options.channelalign.Value)
        ChannelReplace = 2;
        ChannelAlign = 2 * double(sProcess.options.channelalign.Value);
    else
        ChannelReplace = 0;
        ChannelAlign = 0;
    end
    % Epoch time: time units
    EventsTimeRange = sProcess.options.epochtime.Value{1};
    % Import options
    ImportOptions = db_template('ImportOptions');
    ImportOptions.ImportMode        = 'Event';
    ImportOptions.TimeRange         = TimeRange;
    ImportOptions.UseEvents         = 1;
    ImportOptions.EventsTimeRange   = EventsTimeRange;
    ImportOptions.iEpochs           = 1;
    ImportOptions.SplitRaw          = 0;
    ImportOptions.UseCtfComp        = sProcess.options.usectfcomp.Value;
    ImportOptions.UseSsp            = sProcess.options.usessp.Value;
    ImportOptions.CreateConditions  = CreateConditions;
    ImportOptions.ChannelReplace    = ChannelReplace;
    ImportOptions.ChannelAlign      = ChannelAlign;
    ImportOptions.IgnoreShortEpochs = 2 * sProcess.options.ignoreshort.Value;
    ImportOptions.EventsMode        = 'ignore';
    ImportOptions.EventsTrackMode   = 'value';
    ImportOptions.DisplayMessages   = 0;
    % Extra options: Remove DC Offset
    if isfield(sProcess.options, 'baseline') && ~isempty(sProcess.options.baseline.Value)
        if ~isempty(sProcess.options.baseline.Value{1})
            ImportOptions.RemoveBaseline = 'time';
            ImportOptions.BaselineRange  = sProcess.options.baseline.Value{1};
        else
            ImportOptions.RemoveBaseline = 'all';
        end
    else
        ImportOptions.RemoveBaseline = 'no';
    end
    % Extra options: Resample
    if isfield(sProcess.options, 'freq') && ~isempty(sProcess.options.freq.Value) && iscell(sProcess.options.freq.Value) && ~isempty(sProcess.options.freq.Value{1})
        ImportOptions.Resample     = 1;
        ImportOptions.ResampleFreq = sProcess.options.freq.Value{1};
    else
        ImportOptions.Resample = 0;
    end

    % ===== IMPORT FILES =====
    % Get subject
    [sSubject, iSubject] = bst_get('Subject', SubjectName);
    % Create subject if it does not exist yet
    if isempty(sSubject)
        [sSubject, iSubject] = db_add_subject(SubjectName);
    end
    % Define output study
    if ~isempty(Condition)
        % Get condition asked by user
        [sStudy, iStudy] = bst_get('StudyWithCondition', bst_fullfile(SubjectName, Condition));
        % Condition does not exist: create it
        if isempty(sStudy)
            iStudy = db_add_condition(SubjectName, Condition, 1);
            if isempty(iStudy)
                bst_report('Error', sProcess, sInput, ['Cannot create condition : "' bst_fullfile(SubjectName, Condition) '"']);
                return;
            end
        end
    else
        iStudy = [];
    end
    % Import files
    for iFile = 1:length(FileNames)
        % If file is not linked yet in the database: open the file to get the events
        if ~isempty(sInput) && (iFile >= 2)
            isRaw = ~isempty(strfind(FileNames{iFile}, '_0raw'));
            if isRaw
                % Get sFile structure
                FileMat = in_bst_data(FileNames{iFile}, 'F');
                sFile   = FileMat.F;
                % Read channel file
                ChannelFile = bst_get('ChannelFileForStudy', FileNames{iFile});
                ChannelMat = in_bst_channel(ChannelFile);
            else
                [sFile, ChannelMat] = in_fopen(FileNames{iFile}, FileFormat, ImportOptions);
            end
        elseif isempty(sInput) || strcmpi(sInput(1).FileType, 'import')
            [sFile, ChannelMat] = in_fopen(FileNames{iFile}, FileFormat, ImportOptions);
        end
        % No events in file
        if isempty(sFile.events)
            bst_report('Error', sProcess, [], ['No events in file: ' 10 FileNames{iFile}]);
            continue;
        end

        % Get selected events
        iSelEvents = [];
        for iSelEvt = 1:length(EvtNames)
            % Find input event in file
            iEvt = find(strcmpi(EvtNames{iSelEvt}, {sFile.events.label}));
            % If not found with exact names, try searching interpreting strings as regular expressions
            if isempty(iEvt)
                iEvt = find(~cellfun(@isempty, regexp({sFile.events.label}, EvtNames{iSelEvt})));
            end
            % Event found / not found
            if ~isempty(iEvt)
                iSelEvents = [iSelEvents, iEvt];
            else
                bst_report('Warning', sProcess, [], ['Event "' EvtNames{iSelEvt} '" does not exist in file: ' 10 FileNames{iFile}]);
                continue;
            end
        end
        if isempty(iSelEvents)
            bst_report('Error', sProcess, [], ['No events with matching names found in file: ' 10 FileNames{iFile}]);
            continue;
        end
        % Exclude duplicates
        iSelEvents = unique(iSelEvents);
        % Initialize events structure
        events = repmat(sFile.events, 0);
        % Select all the the occurrences of all the events in the selected time window
        for iEvt = iSelEvents
            newEvt = sFile.events(iEvt);
            % Find events that are in time window
            if ~isempty(ImportOptions.TimeRange)
                selTime = ImportOptions.TimeRange + [-1,1] ./ sFile.prop.sfreq;
                iOcc = find(all(newEvt.times >= selTime(1), 1) & all(newEvt.times <= selTime(2), 1));
            else
                iOcc = 1:size(newEvt.times,2);
            end
            % No occurrence for this event: skip to next event
            if isempty(iOcc)
                continue;
            end
            % Get the selected occurrences
            newEvt.times    = newEvt.times(:, iOcc);
            newEvt.epochs   = newEvt.epochs(iOcc);
            newEvt.channels = newEvt.channels(iOcc);
            newEvt.notes    = newEvt.notes(iOcc);
            % Add to the list of events to import
            events(end+1) = newEvt;
        end
        % No events to import found in the file
        if isempty(events)
            bst_report('Error', sProcess, [], ['No events to import found in file: ' 10 FileNames{iFile}]);
            continue;
        end
        % Copy into events options
        ImportOptions.events = events;
        % Import file
        NewFiles = import_data(sFile, ChannelMat, FileFormat, iStudy, iSubject, ImportOptions);
        OutputFiles = cat(2, OutputFiles, NewFiles);

        % === COPY VIDEO LINK ===
        % If only one file imported: Copy linked videos in destination folder
        if ~isDirectImport && (length(NewFiles) == 1)
            % Find file in database
            sStudyIn = bst_get('DataFile', FileNames{iFile});
            % If there are video links to copy, copy them
            if ~isempty(sStudyIn) && ~isempty(sStudyIn.Image)
                CopyVideoLinks(NewFiles{1}, sStudyIn);
            end
        end
    end
    % Report number of files generated
    if ~isempty(OutputFiles)
        bst_report('Info', sProcess, sInput, sprintf('%d epochs imported.', length(OutputFiles)));
    else
        bst_report('Error', sProcess, sInput, 'No good trials imported from these files.');
    end
end

%% ===== COPY VIDEO LINKS =====
% Copy linked videos in destination folder
function sStudyOut = CopyVideoLinks(NewDataFile, sStudyIn)
    % No images, nothing to do
    if isempty(sStudyIn.Image)
        return;
    end
    % Get destination file info
    [sStudyOut, iStudyOut, iData] = bst_get('DataFile', NewDataFile);
    % Get new and old time start
    NewMat = in_bst_data(NewDataFile, {'Time', 'History'});
    oldStart = NewMat.Time(1);
    offsetStart = 0;
    iEntry = find(strcmpi(NewMat.History(:,2), 'import_time'), 1, 'last');
    if ~isempty(iEntry)
        newTime = str2num(NewMat.History{iEntry,3});
        if ~isempty(newTime)
            offsetStart = oldStart - newTime(1);
        end
    end
    % Copy all the links
    for iFile = 1:length(sStudyIn.Image)
        if strcmpi(file_gettype(sStudyIn.Image(iFile).FileName), 'videolink')
            % Read link
            VideoLinkMat = load(file_fullpath(sStudyIn.Image(iFile).FileName));
            % Modify comment
            VideoLinkMat.Comment = [VideoLinkMat.Comment, ' | ', sStudyOut.Data(iData).Comment];
            % Set start time
            if ~isfield(VideoLinkMat, 'VideoStart') || isempty(VideoLinkMat.VideoStart)
                VideoLinkMat.VideoStart = 0;
            end
            VideoLinkMat.VideoStart = VideoLinkMat.VideoStart + offsetStart;
            % Create output filename
            [fPath, fBase] = bst_fileparts(sStudyIn.Image(iFile).FileName);
            OutputFile = bst_fullfile(bst_fileparts(file_fullpath(sStudyOut.FileName)), [file_standardize(fBase), '.mat']);
            OutputFile = file_unique(OutputFile);
            % Save new file in Brainstorm format
            bst_save(OutputFile, VideoLinkMat, 'v7');

            % === UPDATE DATABASE ===
            % Create structure
            sImage = db_template('image');
            sImage.FileName = file_short(OutputFile);
            sImage.Comment  = VideoLinkMat.Comment;
            % Add to study
            iImage = length(sStudyOut.Image) + 1;
            sStudyOut.Image(iImage) = sImage;
        end
    end
    % Save study
    bst_set('Study', iStudyOut, sStudyOut);
    % Update tree
    panel_protocols('UpdateNode', 'Study', iStudyOut);
end

{'repo_name': 'brainstorm-tools/brainstorm3', 'stars': '156', 'repo_language': 'MATLAB', 'file_name': 'BfsEstimation.html', 'mime_type': 'text/html', 'hash': -6821035285698413976, 'source_dataset': 'data'}


<?php

namespace Blogger\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="Blogger\BlogBundle\Repository\BlogRepository")
 * @ORM\Table(name="blog")
 * @ORM\HasLifecycleCallbacks()
 */
class Blog
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $title;

    /**
     * @ORM\Column(type="string")
     */
    protected $slug;

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $author;

    /**
     * @ORM\Column(type="text")
     */
    protected $blog;

    /**
     * @ORM\Column(type="string", length=20)
     */
    protected $image;

    /**
     * @ORM\Column(type="text")
     */
    protected $tags;

    /**
     * @ORM\OneToMany(targetEntity="Comment", mappedBy="blog")
     */
    protected $comments;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     * @ORM\Column(type="datetime")
     */
    protected $updated;

    public function __construct()
    {
        $this->comments = new ArrayCollection();

        $this->setCreated(new \DateTime());
        $this->setUpdated(new \DateTime());
    }

    /**
     * @ORM\prePersist
     */
    public function setCreatedValue()
    {
        $this->setCreated(new \DateTime());
        $this->setUpdated(new \DateTime());
    }

    /**
     * @ORM\preUpdate
     */
    public function setUpdatedValue()
    {
       $this->setUpdated(new \DateTime());
    }

    public function __toString()
    {
        return $this->getTitle();
    }

    public function slugify($text)
    {
        // replace non letter or digits by -
        $text = preg_replace('#[^\\pL\d]+#u', '-', $text);

        // trim
        $text = trim($text, '-');

        // transliterate
        if (function_exists('iconv'))
        {
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        }

        // lowercase
        $text = strtolower($text);

        // remove unwanted characters
        $text = preg_replace('#[^-\w]+#', '', $text);

        if (empty($text))
        {
            return 'n-a';
        }

        return $text;
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;

        $this->setSlug($this->title);
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set author
     *
     * @param string $author
     */
    public function setAuthor($author)
    {
        $this->author = $author;
    }

    /**
     * Get author
     *
     * @return string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Set blog
     *
     * @param text $blog
     */
    public function setBlog($blog)
    {
        $this->blog = $blog;
    }

    /**
     * Get blog
     *
     * @return text
     */
    public function getBlog($length = null)
    {
        if (false === is_null($length) && $length > 0)
            return substr($this->blog, 0, $length);
        else
            return $this->blog;
    }

    /**
     * Set image
     *
     * @param string $image
     */
    public function setImage($image)
    {
        $this->image = $image;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set tags
     *
     * @param text $tags
     */
    public function setTags($tags)
    {
        $this->tags = $tags;
    }

    /**
     * Get tags
     *
     * @return text
     */
    public function getTags()
    {
        return $this->tags;
    }

    /**
     * Set created
     *
     * @param datetime $created
     */
    public function setCreated($created)
    {
        $this->created = $created;
    }

    /**
     * Get created
     *
     * @return datetime
     */
    public function getCreated()
    {
        return $this->created;
    }

    /**
     * Set updated
     *
     * @param datetime $updated
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;
    }

    /**
     * Get updated
     *
     * @return datetime
     */
    public function getUpdated()
    {
        return $this->updated;
    }

    /**
     * Add comments
     *
     * @param Blogger\BlogBundle\Entity\Comment $comments
     */
    public function addComments(\Blogger\BlogBundle\Entity\Comment $comments)
    {
        $this->comments[] = $comments;
    }

    /**
     * Get comments
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getComments()
    {
        return $this->comments;
    }

    /**
     * Set slug
     *
     * @param string $slug
     */
    public function setSlug($slug)
    {
        $this->slug = $this->slugify($slug);
    }

    /**
     * Get slug
     *
     * @return string
     */
    public function getSlug()
    {
        return $this->slug;
    }

    /**
     * Add comments
     *
     * @param Blogger\BlogBundle\Entity\Comment $comments
     */
    public function addComment(\Blogger\BlogBundle\Entity\Comment $comments)
    {
        $this->comments[] = $comments;
    }
}

{'repo_name': 'dsyph3r/symblog', 'stars': '207', 'repo_language': 'PHP', 'file_name': 'base.html.twig', 'mime_type': 'text/html', 'hash': -6886782552378574785, 'source_dataset': 'data'}


#!/usr/bin/env bash
# Base16 Atelier Savanna - Mate Terminal color scheme install script
# Bram de Haan (http://atelierbram.github.io/syntax-highlighting/atelier-schemes/savanna)

[[ -z "$PROFILE_NAME" ]] && PROFILE_NAME="Base 16 Atelier Savanna Light"
[[ -z "$PROFILE_SLUG" ]] && PROFILE_SLUG="base-16-ateliersavanna-light"
[[ -z "$DCONFTOOL" ]] && DCONFTOOL=dconf
[[ -z "$BASE_KEY" ]] && BASE_KEY=/org/mate/terminal/profiles

PROFILE_KEY="$BASE_KEY/$PROFILE_SLUG"

dset() {
  local key="$1"; shift
  local val="$1"; shift

  "$DCONFTOOL" write "$PROFILE_KEY/$key" "$val"
}

# Because gconftool doesn't have "append"
glist_append() {
  local key="$1"; shift
  local val="$1"; shift

  local entries="$(
    {
      "$DCONFTOOL" read "$key" | tr -d '[]' | tr , "\n" | fgrep -v "$val"
      echo "'$val'"
    } | head -c-1 | tr "\n" ,
  )"

  "$DCONFTOOL" write "$key" "[$entries]"
}

# Append the Base16 profile to the profile list
glist_append /org/mate/terminal/global/profile-list "$PROFILE_SLUG"

dset visible-name "'$PROFILE_NAME'"
dset palette "'#ecf4ee:#b16139:#489963:#a07e3b:#478c90:#55859b:#1c9aa0:#87928a:#5f6d64:#b16139:#489963:#a07e3b:#478c90:#55859b:#1c9aa0:#171c19'"
dset background-color "'#ecf4ee'"
dset foreground-color "'#526057'"
dset bold-color "'#526057'"
dset bold-color-same-as-fg "true"
dset use-theme-colors "false"
dset use-theme-background "false"

{'repo_name': 'atelierbram/syntax-highlighting', 'stars': '101', 'repo_language': 'CSS', 'file_name': 'solarized.yml', 'mime_type': 'text/plain', 'hash': 2973496310769623543, 'source_dataset': 'data'}