text:
using elp87.TSLab.Indicators.Helpers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using TSLab.Script;
using TSLab.Script.Handlers;
using TSLab.Script.Helpers;

namespace elp87.TSLab.Indicators
{
    [HandlerName("Элдер Импульс (выгрузка тест)")]
    public class ElderImpulse_DLFull : IBar2DoubleHandler
    {
        public IList<double> Execute(ISecurity source)
        {
            for (int EmaPeriodCounter = 3; EmaPeriodCounter <= 30; EmaPeriodCounter += 2)
            {
                for (int Macd1PeriodCounter = 3; Macd1PeriodCounter < 30; Macd1PeriodCounter += 2)
                {
                    for (int Macd2PeriodCounter = Macd1PeriodCounter + 1; Macd2PeriodCounter <= 30; Macd2PeriodCounter += 2)
                    {
                        for (int MacdSignalPeriodCounter = 3; MacdSignalPeriodCounter <= 30; MacdSignalPeriodCounter += 2)
                        {
                            IList<double> elderList = CalcElderFilter(source, EmaPeriodCounter, Macd1PeriodCounter, Macd2PeriodCounter, MacdSignalPeriodCounter);
                            SaveFilterFile(source, elderList, EmaPeriodCounter, Macd1PeriodCounter, Macd2PeriodCounter, MacdSignalPeriodCounter);
                        }
                    }
                }
            }
            List<double> returnList = new List<double>(source.Bars.Count);
            returnList.ForEach(var => var = 1);
            return returnList;
        }

        private IList<double> CalcElderFilter(ISecurity source, int EMAPeriod, int MACD1Period, int MACD2Period, int MACDSignalPeriod)
        {
            IList<double> elderList = (IList<double>)new List<double>(source.ClosePrices.Count);
            IList<double> list2 = Series.EMA(source.ClosePrices, EMAPeriod);
            IList<double> list3 = (IList<double>)new List<double>(source.ClosePrices.Count);
            IList<double> list4 = (IList<double>)new List<double>(source.ClosePrices.Count);
            IList<double> list5 = (IList<double>)new List<double>(source.ClosePrices.Count);
            IList<double> list6 = Series.EMA(source.ClosePrices, MACD1Period);
            IList<double> list7 = Series.EMA(source.ClosePrices, MACD2Period);
            int num1 = Math.Max(MACD1Period, MACD2Period);
            int index1 = 0;
            while (index1 < source.ClosePrices.Count)
            {
                double num2 = index1 >= num1 ? list6[index1] - list7[index1] : 0.0;
                list3.Add(num2);
                checked { ++index1; }
            }
            IList<double> list8 = Series.EMA(list3, MACDSignalPeriod);
            int index2 = 0;
            while (index2 < source.ClosePrices.Count)
            {
                double num2 = list3[index2] - list8[index2];
                list5.Add(num2);
                checked { ++index2; }
            }
            int index3 = 0;

            while (index3 < source.ClosePrices.Count)
            {
                double num2 = -5.0;
                if (index3 == 0)
                {
                    num2 = 0.0;
                }
                else
                {
                    if (list5[index3] > list5[checked(index3 - 1)] && list2[index3] > list2[checked(index3 - 1)])
                        num2 = 1.0;
                    if (list5[index3] < list5[checked(index3 - 1)] && list2[index3] < list2[checked(index3 - 1)])
                        num2 = -1.0;
                    if (list5[index3] <= list5[checked(index3 - 1)] && list2[index3] >= list2[checked(index3 - 1)] || list5[index3] >= list5[checked(index3 - 1)] && list2[index3] <= list2[checked(index3 - 1)])
                        num2 = 0.0;
                }
                elderList.Add(num2);
                checked { ++index3; }
            }
            return elderList;
        }

        private void SaveFilterFile(ISecurity source, IList<double> elderList, int EMAPeriod, int MACD1Period, int MACD2Period, int MACDSignalPeriod)
        {
            // Выгрузка данных
            int barCount = source.Bars.Count;
            int indCount = elderList.Count;
            int loadCount = Math.Min(barCount, indCount);

            int barEnumerator = barCount - 1;
            int indEnumerator = indCount - 1;
            int loadEnumerator = loadCount - 1;

            List<IndicatorDay> dayList = new List<IndicatorDay>();
            while (loadEnumerator > 0)
            {
                IndicatorDay day = new IndicatorDay()
                {

                    Date = source.Bars[barEnumerator].Date,
                    Value = elderList[indEnumerator]
                };
                dayList.Add(day);

                barEnumerator--;
                indEnumerator--;
                loadEnumerator--;
            }
            dayList.Sort();

            XElement headX = new XElement("FilterSet");
            XElement paramX = new XElement("Params",
                new XElement("EMAPeriod", EMAPeriod),
                new XElement("MACD1Period", MACD1Period),
                new XElement("MACD2Period", MACD2Period),
                new XElement("MACDSignalPeriod", MACDSignalPeriod)
                );
            headX.Add(paramX);

            XElement daysX = new XElement("Days");
            foreach (IndicatorDay day in dayList)
            {
                daysX.Add(new XElement("D",
                    new XElement("d", day.Date),
                    new XElement("v", day.Value)
                    ));
            }
            headX.Add(daysX);

            string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\Elder" + dayList.Min(day => day.Date).ToString("yyMMdd") + "_-_" + dayList.Max(day => day.Date).ToString("yyMMdd");
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }
            headX.Save(dirPath + @"\" + EMAPeriod.ToString() + "_" + MACD1Period.ToString() + "_" + MACD2Period + "_" + MACDSignalPeriod + ".xml");
        }
    }
}


text:
package world;

/*
    BenjaminWilcox
    Dec 5, 2016
    GNGH_2
 */
public class Resources
{

    private double mining;
    private double lumber;
    private double fertility;

    public double getMining()
    {
        return mining;
    }

    public void setMining(double mining)
    {
        this.mining = mining;
    }

    public double getLumber()
    {
        return lumber;
    }

    public void setLumber(double lumber)
    {
        this.lumber = lumber;
    }

    public double getFertility()
    {
        return fertility;
    }

    public void setFertility(double fertility)
    {
        this.fertility = fertility;
    }

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Jacquinia albiflora Lundell

### Remarks
null


text:
using System.IO;
using System.IO.Compression;
using System.Web;
using System.Web.Mvc;

namespace VsixMvcAppResult.UI.Web.Common.Mvc.Attributes
{
    //http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx
    //http://msdn.microsoft.com/en-us/magazine/gg232768.aspx
    public class CompressFilterActionAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;

            string acceptEncoding = request.Headers["Accept-Encoding"];

            if (string.IsNullOrEmpty(acceptEncoding))
            {
                return;
            }
            else
            {
                acceptEncoding = acceptEncoding.ToUpperInvariant();

                HttpResponseBase response = filterContext.HttpContext.Response;

                if (acceptEncoding.Contains("GZIP"))
                {
                    response.AppendHeader("Content-encoding", "gzip");
                    response.Filter = CompressFilterActionAttribute.Gzip(response.Filter);
                }
                else if (acceptEncoding.Contains("DEFLATE"))
                {
                    response.AppendHeader("Content-encoding", "deflate");
                    response.Filter = CompressFilterActionAttribute.Deflate(response.Filter);
                }
            }
        }

        public static GZipStream Gzip(Stream stream)
        {
            return new GZipStream(stream, CompressionMode.Compress);
        }

        public static DeflateStream Deflate(Stream stream)
        {
            return new DeflateStream(stream, CompressionMode.Compress);
        }
    }
}


text:
package org.jbb.lib.properties.encrypt;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.springframework.stereotype.Component;

import java.util.Optional;

import javax.annotation.PostConstruct;

import lombok.RequiredArgsConstructor;

import static org.jbb.lib.properties.encrypt.EncryptionPlaceholderUtils.extractFromDecPlaceholder;
import static org.jbb.lib.properties.encrypt.EncryptionPlaceholderUtils.extractFromEncPlaceholder;
import static org.jbb.lib.properties.encrypt.EncryptionPlaceholderUtils.isInDecPlaceholder;
import static org.jbb.lib.properties.encrypt.EncryptionPlaceholderUtils.isInEncPlaceholder;
import static org.jbb.lib.properties.encrypt.EncryptionPlaceholderUtils.surroundWithDecPlaceholder;

@Component
@RequiredArgsConstructor
public class PropertiesEncryption {
    private final StandardPBEStringEncryptor encryptor;
    private final PswdValueResolver pswdValueResolver;

    private boolean encryptionEnabled;

    @PostConstruct
    final void reconfigureEncryption() {
        pswdValueResolver.resolvePassword();
        Optional<String> password = pswdValueResolver.getPassword();
        if (password.isPresent()) {
            this.encryptor.setPassword(password.get());
            encryptionEnabled = true;
        } else {
            encryptionEnabled = false;
        }
    }

    public String encryptIfNeeded(String value) {
        if (isInEncPlaceholder(value)) {
            if (encryptionEnabled) {
                return surroundWithDecPlaceholder(encryptor.encrypt(extractFromEncPlaceholder(value)));
            } else {
                return extractFromEncPlaceholder(value);
            }
        } else {
            return value;
        }
    }

    public String decryptIfNeeded(String value) {
        if (isInDecPlaceholder(value)) {
            if (encryptionEnabled) {
                return encryptor.decrypt(extractFromDecPlaceholder(value));
            } else {
                throw new IllegalStateException("Can't decrypt '" + value + "' because properties encryption is disabled");
            }
        } else {
            return value;
        }
    }

    boolean isEncryptionEnabled() {
        return encryptionEnabled;
    }
}


text:
<?php

/**
 *
 * @package    symfony
 * @subpackage plugin
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @version    SVN: $Id: PluginsfGuardRememberKeyPeer.php 7634 2008-02-27 18:01:40Z fabien $
 */
class PluginsfGuardRememberKeyPeer extends BasesfGuardRememberKeyPeer
{
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace MVC6_Full_Version.Controllers
{
    public class LandingController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<Deployment xmlns="http://schemas.microsoft.com/windowsphone/2012/deployment" AppPlatformVersion="8.0">
  <DefaultLanguage xmlns="" code="en-US" />
  <App xmlns="" ProductID="{2620d7c4-2e97-4ec3-b854-783398521700}" Title="GreenScreenMagic" RuntimeType="Silverlight" Version="1.0.0.0" Genre="apps.normal" Author="GreenScreenMagic author" Description="Sample description" Publisher="GreenScreenMagic" PublisherID="{2c5952da-285a-4d11-808a-e0b7411b26be}">
    <IconPath IsRelative="true" IsResource="false">Assets\ApplicationIcon.png</IconPath>
    <Capabilities>
      <Capability Name="ID_CAP_NETWORKING" />
      <Capability Name="ID_CAP_MEDIALIB_AUDIO" />
      <Capability Name="ID_CAP_MEDIALIB_PLAYBACK" />
      <Capability Name="ID_CAP_SENSORS" />
      <Capability Name="ID_CAP_WEBBROWSERCOMPONENT" />
      <Capability Name="ID_CAP_REMOVABLE_STORAGE" />
      <Capability Name="ID_CAP_MEDIALIB_PHOTO" />
    </Capabilities>
    <Tasks>
      <DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
    </Tasks>
    <Tokens>
      <PrimaryToken TokenID="GreenScreenMagicToken" TaskName="_default">
        <TemplateFlip>
          <SmallImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileSmall.png</SmallImageURI>
          <Count>0</Count>
          <BackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileMedium.png</BackgroundImageURI>
          <Title>GreenScreenMagic</Title>
          <BackContent>
          </BackContent>
          <BackBackgroundImageURI>
          </BackBackgroundImageURI>
          <BackTitle>
          </BackTitle>
          <LargeBackgroundImageURI IsRelative="true" IsResource="false">Assets\Tiles\FlipCycleTileLarge.png</LargeBackgroundImageURI>
          <LargeBackContent />
          <LargeBackBackgroundImageURI IsRelative="true" IsResource="false">
          </LargeBackBackgroundImageURI>
          <DeviceLockImageURI>
          </DeviceLockImageURI>
          <HasLarge>True</HasLarge>
        </TemplateFlip>
      </PrimaryToken>
    </Tokens>
    <ScreenResolutions>
      <ScreenResolution Name="ID_RESOLUTION_WVGA" />
      <ScreenResolution Name="ID_RESOLUTION_WXGA" />
      <ScreenResolution Name="ID_RESOLUTION_HD720P" />
    </ScreenResolutions>
  </App>
</Deployment>


text:
.changelogItemContainer {
  margin-bottom: 1rem;
}


text:
package com.rhinoforms.devtool;

import java.io.FileReader;
import java.io.IOException;

import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;

public class RunScript {

	public static void main(String[] args) throws IOException {
		Context cx = Context.enter();
		try {
			Scriptable scope = cx.initStandardObjects();

			String script = "src/main/webapp/js/script.js";
			FileReader fileReader = new FileReader(script);
			cx.evaluateReader(scope, fileReader, script, 1, null);

			cx.evaluateString(scope, "var form = {a:'123'}", "<cmd>", 1, null);

			// Now evaluate the string we've colected.
			Object result = cx.evaluateString(scope, "matches('123', form.a)", "<cmd>", 1, null);

			// Convert the result to a string and print it.
			System.err.println(Context.toString(result));
		} finally {
			// Exit from the context.
			Context.exit();
		}
	}

}


text:
import { TeamcityAgentAdapter } from '../../../src/anticorruptionlayer/teamcity-agent-adapter';
import makeClientStub from './client-stub-factory.js'

describe('the teamcityAgentAdapter ', () => {
    describe('getAllAgents method', () => {
        it('asks all the agents from teamcity and transforms those to build objects from our domain', (done) => {
            let fetchResponse = {
                "count": 2,
                "href": "/guestAuth/app/rest/agents",
                "agent": [
                    {
                        "id": 3,
                        "name": "SomeAgent_1",
                        "typeId": 3,
                        "href": "/guestAuth/app/rest/agents/id:3"
                    },
                    {
                        "id": 2,
                        "name": "SomeAgent_2",
                        "typeId": 2,
                        "href": "/guestAuth/app/rest/agents/id:2"
                    }
                ]
            };

            let expectedBuilds = [
                {
                    "id": 3,
                    "name": "SomeAgent_1",
                    "url": "/guestAuth/app/rest/agents/id:3"
                },
                {
                    "id": 2,
                    "name": "SomeAgent_2",
                    "url": "/guestAuth/app/rest/agents/id:2"
                }
            ];

            new TeamcityAgentAdapter(makeClientStubForGettingAllAgents("test.com", fetchResponse))
                .getAllAgents("test.com")
                .then(returnedBuilds => expect(returnedBuilds).toEqual(expectedBuilds))
                .catch(error => expect(error).toBeUndefined())
                .finally(done);
        });
    })

    describe('getAllNotConnectedAgents method', () => {
        it('asks all the agents from teamcity and transforms those to build objects from our domain', (done) => {
            let fetchResponse = {
                "count": 2,
                "href": "/guestAuth/app/rest/agents",
                "agent": [
                    {
                        "id": 3,
                        "name": "SomeAgent_1",
                        "typeId": 3,
                        "href": "/guestAuth/app/rest/agents/id:3"
                    },
                    {
                        "id": 2,
                        "name": "SomeAgent_2",
                        "typeId": 2,
                        "href": "/guestAuth/app/rest/agents/id:2"
                    }
                ]
            };

            let expectedBuilds = [
                {
                    "id": 3,
                    "name": "SomeAgent_1",
                    "url": "/guestAuth/app/rest/agents/id:3"
                },
                {
                    "id": 2,
                    "name": "SomeAgent_2",
                    "url": "/guestAuth/app/rest/agents/id:2"
                }
            ];

            new TeamcityAgentAdapter(makeClientStubForGettingAllNotConnectedAgents("test.com", fetchResponse))
                .getAllNotConnectedAgents("test.com")
                .then(returnedBuilds => expect(returnedBuilds).toEqual(expectedBuilds))
                .catch(error => expect(error).toBeUndefined())
                .finally(done);
        });
    })

    function makeClientStubForGettingAllAgents(baseUrl, fetchResponse) {
        return makeClientStub('http://' + baseUrl + '/guestAuth/app/rest/agents', fetchResponse);
    }

    function makeClientStubForGettingAllNotConnectedAgents(baseUrl, fetchResponse) {
        return makeClientStub('http://' + baseUrl + '/guestAuth/app/rest/agents?locator=connected:false', fetchResponse);
    }
});


text:
/**
 * @author Pavel N. Vyssotski
 */
// AgentMonitor.cpp

#include "AgentMonitor.h"
#include "jvmti.h"

using namespace jdwp;

AgentMonitor::AgentMonitor(const char* name) throw(AgentException) {
    jvmtiError err;
    JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->CreateRawMonitor(name, &m_monitor));
    if (err != JVMTI_ERROR_NONE) {
        throw AgentException(err);
    }
}

AgentMonitor::~AgentMonitor() throw(AgentException) {
    jvmtiError err;
    JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->DestroyRawMonitor(m_monitor));
    // check for error only in debug mode
    JDWP_ASSERT(err==JVMTI_ERROR_NONE);
}

void AgentMonitor::Enter() const throw(AgentException) {
    jvmtiError err;
//    JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->RawMonitorEnter(m_monitor));
    err = AgentBase::GetJvmtiEnv()->RawMonitorEnter(m_monitor);
    if (err != JVMTI_ERROR_NONE) {
        throw AgentException(err);
    }
}

void AgentMonitor::Wait(jlong timeout) const throw(AgentException) {
    jvmtiError err;
    JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->RawMonitorWait(m_monitor, timeout));
//    err = AgentBase::GetJvmtiEnv()->RawMonitorWait(m_monitor, timeout);
    if (err != JVMTI_ERROR_NONE) {
        throw AgentException(err);
    }
}

void AgentMonitor::Notify() const throw(AgentException) {
    jvmtiError err;
    JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->RawMonitorNotify(m_monitor));
//    err = AgentBase::GetJvmtiEnv()->RawMonitorNotify(m_monitor);
    if (err != JVMTI_ERROR_NONE) {
        throw AgentException(err);
    }
}

void AgentMonitor::NotifyAll() const throw(AgentException) {
    jvmtiError err;
    JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->RawMonitorNotifyAll(m_monitor));
//    err = AgentBase::GetJvmtiEnv()->RawMonitorNotifyAll(m_monitor);
    if (err != JVMTI_ERROR_NONE) {
        throw AgentException(err);
    }
}

void AgentMonitor::Exit() const throw(AgentException) {
    jvmtiError err;
    //JVMTI_TRACE(err, AgentBase::GetJvmtiEnv()->RawMonitorExit(m_monitor));
    err = AgentBase::GetJvmtiEnv()->RawMonitorExit(m_monitor);
    if (err != JVMTI_ERROR_NONE) {
        throw AgentException(err);
    }
}


text:
import pytest

from merakicommons.ghost import Ghost, GhostLoadingRequiredError

TEST_VALUE = "TEST VALUE"
VALUE_COUNT = 100

class GhostObject(Ghost):
    def __init__(self) -> None:
        self.load_calls = 0
        self.last_loaded = None

    def __load__(self, load_group) -> None:
        self.load_calls += 1
        self._value = TEST_VALUE
        self.last_loaded = load_group

    @Ghost.property
    def value(self) -> str:
        try:
            return self._value
        except AttributeError:
            raise GhostLoadingRequiredError

    @Ghost.property
    def constant_value(self) -> str:
        return TEST_VALUE

    @Ghost.property
    def bad_value(self) -> None:
        return self._bad_value

    @property
    def unloaded_value(self) -> str:
        return TEST_VALUE

    def unloaded_method(self) -> str:
        return TEST_VALUE

def test_ghost_property():
    x = GhostObject()
    for _ in range(VALUE_COUNT):
        value = x.value
        assert type(value) is type(TEST_VALUE)
        assert value == TEST_VALUE
        assert x.last_loaded == "value"

def test_constant_value():
    x = GhostObject()
    for _ in range(VALUE_COUNT):
        value = x.constant_value
        assert type(value) is type(TEST_VALUE)
        assert value == TEST_VALUE
        assert x.last_loaded is None

def test_bad_value():
    x = GhostObject()
    for _ in range(VALUE_COUNT):
        with pytest.raises(AttributeError):
            x.bad_value
        assert x.last_loaded is None

def test_ghost_load_normal_attribute():
    x = GhostObject()
    assert x.load_calls == 0

    for _ in range(VALUE_COUNT):
        x.unloaded_value
        assert x.load_calls == 0
        assert x.last_loaded is None

    for _ in range(VALUE_COUNT):
        x.unloaded_method()
        assert x.load_calls == 0
        assert x.last_loaded is None

def test_ghost_load_required():
    x = GhostObject()
    assert x.load_calls == 0

    for _ in range(VALUE_COUNT):
        x.value
        assert x.load_calls == 1
        assert x.last_loaded == "value"

def test_ghost_load_not_required():
    x = GhostObject()
    assert x.load_calls == 0

    for _ in range(VALUE_COUNT):
        x.constant_value
        assert x.load_calls == 0
        assert x.last_loaded is None

def test_ghost_load_bad_value():
    x = GhostObject()
    assert x.load_calls == 0

    for count in range(VALUE_COUNT):
        with pytest.raises(AttributeError):
            x.bad_value
        assert x.load_calls == 0
        assert x.last_loaded is None


text:
package VulnDB::RDBO::MessageType::Manager;

use base qw(Rose::DB::Object::Manager);

use VulnDB::RDBO::MessageType;

sub object_class { 'VulnDB::RDBO::MessageType' }

__PACKAGE__->make_manager_methods('message_type');

1;


text:
// boot code needed for cocos2d-html5
// Not needed by cocos2d + JS bindings

var MW = MW || {};

(function () {
    var d = document;
    var c = {
        menuType:'canvas', //whether to use canvas mode menu or dom menu
        COCOS2D_DEBUG:2, //0 to turn debug off, 1 for basic debug, and 2 for full debug
        showFPS:true,
        loadExtension:true,
        frameRate:60,
        tag:'gameCanvas', //the dom element to run cocos2d on
        engineDir:'../../../cocos2d/',
        appFiles:[
            'src/Resource.js',
            'src/config/GameConfig.js',
            'src/config/EnemyType.js',
            'src/config/Level.js',
            'src/Effect.js',
            'src/Bullet.js',
            'src/Enemy.js',
            'src/Explosion.js',
            'src/Ship.js',
            'src/LevelManager.js',
            'src/GameController.js',
            'src/GameControlMenu.js',
            'src/GameLayer.js',
            'src/GameOver.js',
            'src/AboutLayer.js',
            'src/SettingsLayer.js',
            'src/SysMenu.js'
        ]
    };
    window.addEventListener('DOMContentLoaded', function () {
        //first load engine file if specified
        var s = d.createElement('script');
        /*********Delete this section if you have packed all files into one*******/
        if (c.SingleEngineFile && !c.engineDir) {
            s.src = c.SingleEngineFile;
        }
        else if (c.engineDir && !c.SingleEngineFile) {
            s.src = c.engineDir + 'platform/jsloader.js';
        }
        else {
            alert('You must specify either the single engine file OR the engine directory in "cocos2d.js"');
        }
        /*********Delete this section if you have packed all files into one*******/

            //s.src = 'Packed_Release_File.js'; //IMPORTANT: Un-comment this line if you have packed all files into one

        d.body.appendChild(s);
        document.ccConfig = c;
        s.id = 'cocos2d-html5';
        //else if single file specified, load singlefile
    });
})();


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use AppBundle\Entity\TblEmpleados;
use AppBundle\Form\TblEmpleadosType;

/**
 * TblEmpleados controller.
 *
 * @Route("/tblempleados")
 */
class TblEmpleadosController extends Controller
{
    /**
     * Lists all TblEmpleados entities.
     *
     * @Route("/", name="tblempleados_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $session = $request->getSession();
        if($session->has("id")){
            $em = $this->getDoctrine()->getManager();
            $db = $em->getConnection();
            $menuList = array();
            $subMenuList = array();

            $iduser = $session->get('id');
            $user = $em->getRepository('AppBundle:TblUsuarios')->find($iduser);
            $array = $this->obtenerMenus($iduser);
            $menuList = $array[0];
            $subMenuList = $array[1];

            $tblEmpleados = $em->getRepository('AppBundle:TblEmpleados')->findAll();

            return $this->render('tblempleados/index.html.twig', array(
                    'usuariologeado'=>$user,
                    'tblEmpleados' => $tblEmpleados,
                    'menuList'=>$menuList,
                    'subMenuList'=>$subMenuList
                    ));
        }else{
            $this->get("session")->getFlashBag()->add("mensaje","Debe estar logueado para ver este contenido.");
            return $this->redirect($this->generateUrl("login"));
        }

    }

    /**
     * Creates a new TblEmpleados entity.
     *
     * @Route("/new", name="tblempleados_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $tblEmpleado = new TblEmpleados();
        $form = $this->createForm('AppBundle\Form\TblEmpleadosType', $tblEmpleado);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($tblEmpleado);
            $em->flush();

            echo "<script language='Javascript' type='text/javascript'>
            window.opener.location='../tblempleados'
            window.close()
        </script>";
    }

    return $this->render('tblempleados/new.html.twig', array(
        'tblEmpleado' => $tblEmpleado,
        'form' => $form->createView(),
        ));
}

    /**
     * Finds and displays a TblEmpleados entity.
     *
     * @Route("/{id}", name="tblempleados_show")
     * @Method("GET")
     */
    public function showAction(TblEmpleados $tblEmpleado)
    {
        $deleteForm = $this->createDeleteForm($tblEmpleado);

        return $this->render('tblempleados/show.html.twig', array(
            'tblEmpleado' => $tblEmpleado,
            'delete_form' => $deleteForm->createView(),
            ));
    }

    /**
     * Displays a form to edit an existing TblEmpleados entity.
     *
     * @Route("/{id}/edit", name="tblempleados_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, TblEmpleados $tblEmpleado)
    {
        $deleteForm = $this->createDeleteForm($tblEmpleado);
        $editForm = $this->createForm('AppBundle\Form\TblEmpleadosType', $tblEmpleado);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($tblEmpleado);
            $em->flush();

            echo "<script language='Javascript' type='text/javascript'>
            window.opener.location='../../tblempleados'
            window.close()
        </script>";
    }

    return $this->render('tblempleados/edit.html.twig', array(
        'tblEmpleado' => $tblEmpleado,
        'edit_form' => $editForm->createView(),
        'delete_form' => $deleteForm->createView(),
        ));
}

    /**
     * Deletes a TblEmpleados entity.
     *
     * @Route("/{id}", name="tblempleados_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, TblEmpleados $tblEmpleado)
    {
        $form = $this->createDeleteForm($tblEmpleado);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($tblEmpleado);
            $em->flush();
        }

        echo "<script language='Javascript' type='text/javascript'>
        window.opener.location='../tblempleados'
        window.close()
    </script>";
}

    /**
     * Creates a form to delete a TblEmpleados entity.
     *
     * @param TblEmpleados $tblEmpleado The TblEmpleados entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(TblEmpleados $tblEmpleado)
    {
        return $this->createFormBuilder()
        ->setAction($this->generateUrl('tblempleados_delete', array('id' => $tblEmpleado->getIdempleado())))
        ->setMethod('DELETE')
        ->getForm()
        ;
    }

    /**
     * Finds and displays a TblEmpleados entity.
     *
     * @Route("/{id}/sup", name="tblempleados_sup")
     * @Method("GET")
     */
    public function supAction(TblEmpleados $tblEmpleado)
    {
        $deleteForm = $this->createDeleteForm($tblEmpleado);

        return $this->render('tblempleados/sup.html.twig', array(
            'tblEmpleado' => $tblEmpleado,
            'delete_form' => $deleteForm->createView(),
            ));
    }

    public function obtenerMenus($iduser){
        $em = $this->getDoctrine()->getManager();
        $db = $em->getConnection();
        $array = array();
        $menuList = array();
        $subMenuList = array();
        $query = "Select distinct m.* FROM tbl_menus m,
            tbl_perfildetalle pd,
            tbl_perfil p,
            tbl_usuariosperfiles up
            where up.idusuario = :pIduser
            and pd.idmenu is not null
            and pd.idmenu=m.idmenu
            and p.idperfil=pd.idperfil
            and up. idperfil = p.idperfil
            ORDER BY m.nombremenu ASC";
            $stmt = $db->prepare($query);
            $params = array('pIduser'=>$iduser);
            $stmt->execute($params);
            $menusList=$stmt->fetchAll();

            if($menusList){
                foreach ($menusList as $menuIter) {

                $emp = $this->getDoctrine()->getManager();
                $dbp = $emp->getConnection();
                $imenu = $menuIter["idmenu"];

                $queryp = "Select * FROM tbl_menus m,
                    tbl_menusub sm,
                    tbl_perfildetalle pd,
                    tbl_perfil p,
                    tbl_usuariosperfiles up
                    where up.idusuario= :pIduser
                    and m.idmenu = :pImenu
                    and pd.idsubmenu is not null
                    and sm.idmenu = m.idmenu
                    and pd.idmenu=m.idmenu
                    and pd.idsubmenu = sm.idsubmenu
                    and p.idperfil=pd.idperfil
                    and up. idperfil = p.idperfil
                    ORDER BY sm.nombresubmenu ASC";
                    $stmtp = $dbp->prepare($queryp);
                    $paramsp = array('pIduser'=>$iduser,'pImenu'=>$imenu);
                    $stmtp->execute($paramsp);
                    $subMenu=$stmtp->fetchAll();

                if($subMenu){
                    foreach ($subMenu as $sm) {
                        array_push($subMenuList,$sm);
                    }
                }
                array_push($menuList,$menuIter);
            }
        }
        array_push($array,$menuList);
        array_push($array,$subMenuList);
        return $array;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  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.

  Copyright 2017 Nextdoor.com, Inc
-->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <artifactId>bender</artifactId>
    <groupId>com.nextdoor.bender</groupId>
    <version>2.0.0-SNAPSHOT</version>
    <relativePath>../pom.xml</relativePath>
  </parent>

  <name>Bender Operations</name>
  <artifactId>bender-operations</artifactId>
  <packaging>jar</packaging>

  <dependencies>
    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>bender-core</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>bender-deserializers</artifactId>
      <version>${project.version}</version>
    </dependency>

    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-s3</artifactId>
      <version>${aws-java-sdk.version}</version>
    </dependency>

    <dependency>
      <groupId>com.amazonaws</groupId>
      <artifactId>aws-java-sdk-kms</artifactId>
      <version>${aws-java-sdk.version}</version>
    </dependency>

    <dependency>
      <groupId>com.jayway.jsonpath</groupId>
      <artifactId>json-path</artifactId>
      <version>${json-path.version}</version>
    </dependency>

    <dependency>
      <groupId>com.maxmind.geoip2</groupId>
      <artifactId>geoip2</artifactId>
      <version>${geoip2.version}</version>
    </dependency>

    <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>${google.gson.version}</version>
    </dependency>

    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-text</artifactId>
      <version>${commons-text.version}</version>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>bender-core</artifactId>
      <type>test-jar</type>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>${project.groupId}</groupId>
      <artifactId>bender-shaded</artifactId>
      <version>${project.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>com.github.stefanbirkner</groupId>
      <artifactId>system-rules</artifactId>
      <version>${system-rules.version}</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>${mockito-all.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>


text:
<?php

namespace Eater\Order\Util\UserProvider;

use Eater\Order\Util\ExecResult;

class Useradd extends Posix {
    public function create($name, $password, $groups, $shell, $home, $comment)
    {
        $cmd = 'useradd ' . escapeshellarg($name) . ' -m ';

        if ($password !== null) {
            $cmd .= ' -p ' . escapeshellarg($password);
        }

        if (!empty($groups)) {
            $cmd .= ' -G ' . escapeshellarg(implode(',', $groups));
        }

        if ($shell !== null) {
            $cmd .= ' -s ' . escapeshellarg($shell);
        }

        if ($home !== null) {
            $cmd .= ' -d ' . escapeshellarg($home);
        }

        if ($comment !== null) {
            $cmd .= ' -c ' . escapeshellarg($comment);
        }

        return ExecResult::createFromCommand($cmd . ' 2>&1');
    }

    public function update($name, $password, $groups, $shell, $home, $comment)
    {
        $current = $this->get($name);

        $cmd = 'usermod ' . escapeshellarg($name);

        if ($password !== null && $current['passwd'] !== $password) {
            $cmd .= ' -p ' . escapeshellarg($password);
        }

        if ($comment !== null && $current['gecos'] !== $comment) {
            $cmd .= ' -c ' . escapeshellarg($comment);
        }

        $diff = array_diff($current['groups'], $groups);
        if (!empty($diff)) {
            $cmd .= ' -G ' . escapeshellarg(implode(',', $groups));
        }

        if ($shell !== null && $current['shell'] !== $shell) {
            $cmd .= ' -s ' . escapeshellarg($shell);
        }

        if ($home !== null && $current['dir'] !== $home) {
            $cmd .= ' -d ' . escapeshellarg($home);
        }

        return ExecResult::createFromCommand($cmd . ' 2>&1');
    }

    public function get($name)
    {
        $user = parent::get($name);

        $entries = file('/etc/shadow');
        foreach ($entries as $entry) {
            list($username, $passwd) = explode(':', $entry);
            if ($name === $username) {
                $user['passwd'] = $passwd;
                return $user;
            }
        }

        return $user;
    }

    public function remove($name)
    {
        return ExecResult::createFromCommand('userdel ' . escapeshellarg($name) . ' 2>&1');
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by CodeZu.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

var Client = require('../../../../../client'), constants = Client.constants;

module.exports = Client.sub({
	getProductHandlingFeeRule: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/shipping/admin/profiles/{profilecode}/rules/producthandlingfees/{id}?responseFields={responseFields}'
	}),
	getProductHandlingFeeRules: Client.method({
		method: constants.verbs.GET,
		url: '{+tenantPod}api/commerce/shipping/admin/profiles/{profilecode}/rules/producthandlingfees?responseFields={responseFields}'
	}),
	createProductHandlingFeeRule: Client.method({
		method: constants.verbs.POST,
		url: '{+tenantPod}api/commerce/shipping/admin/profiles/{profilecode}/rules/producthandlingfees?responseFields={responseFields}'
	}),
	updateProductHandlingFeeRule: Client.method({
		method: constants.verbs.PUT,
		url: '{+tenantPod}api/commerce/shipping/admin/profiles/{profilecode}/rules/producthandlingfees/{id}?responseFields={responseFields}'
	}),
	deleteProductHandlingFeeRule: Client.method({
		method: constants.verbs.DELETE,
		url: '{+tenantPod}api/commerce/shipping/admin/profiles/{profilecode}/rules/producthandlingfees/{id}'
	})
});


text:
import os
from time import time

import numpy as np
from sklearn.externals import joblib
from sklearn.neural_network import MLPClassifier

from preprocessData import getDataXY

trainX, trainY, testX, testY, validX, validY = getDataXY()
print len(trainX), len(trainY), len(testX), len(testY), len(validX), len(validY)

X = trainX
y = trainY
# clf = SGDClassifier(loss="hinge", penalty="l2", n_iter=800)
# clf = tree.DecisionTreeClassifier()
# clf = NearestCentroid(metric='manhattan')
clf = MLPClassifier(solver='lbfgs', alpha=1e-5,
                    hidden_layer_sizes=(13, 5), random_state=1,
                    verbose=True, max_iter=100, early_stopping=True)

if not os.path.isfile('NNP0.61.pkl'):
    clf.fit(X, y)
else:
    clf = joblib.load('NNP0.61.pkl')

if not os.path.isfile('NNP0.61.pkl'):
    joblib.dump(clf, 'NNP0.61.pkl')

start = time()
valid_result = clf.predict(validX)
end = time()
print end - start
valid_accuracy = np.mean(valid_result.ravel() == validY.ravel()) * 100
print valid_accuracy

# def get_accuracy(predict, true):
#     right_num = 0
#     total_num = 0
#     for pre, tru in zip(predict, true):
#         total_num += 1
#         if pre == tru:
#             right_num += 1
#     print right_num, total_num
#     return right_num / 0.1 / total_num
#
#
# start = time()
# print get_accuracy(clf.predict(validX), validY)
# end = time()
# print end - start, 's'


text:
default[:rbenv][:user]           = "rbenv"
default[:rbenv][:group]          = "rbenv"
default[:rbenv][:manage_home]    = true
default[:rbenv][:group_users]    = Array.new
default[:rbenv][:git_repository] = "git://github.com/sstephenson/rbenv.git"
default[:rbenv][:git_revision]   = "master"
default[:rbenv][:install_prefix] = "/opt"
default[:rbenv][:root_path]      = "#{node[:rbenv][:install_prefix]}/rbenv"

default[:ruby_build][:git_repository] = "git://github.com/sstephenson/ruby-build.git"
default[:ruby_build][:git_revision]   = "master"

default[:rbenv_vars][:git_repository] = "git://github.com/sstephenson/rbenv-vars.git"
default[:rbenv_vars][:git_revision]   = "master"


text:
require 'spec_helper'
require 'logstasher/active_record/log_subscriber'

describe LogStasher::ActiveRecord::LogSubscriber do
  let(:log_output) { StringIO.new }
  let(:logger) do
    logger = Logger.new(log_output)
    logger.formatter = lambda { |_, _, _, msg|
      msg
    }
    def log_output.json
      JSON.parse! string
    end
    logger
  end
  before do
    LogStasher.logger = logger
    LogStasher.log_controller_parameters = true
    LogStasher.field_renaming = {}
    LogStasher::CustomFields.custom_fields = []
    allow(described_class).to receive(:runtime).and_return(0)
    allow(described_class).to receive(:runtime=)
  end
  after do
    LogStasher.log_controller_parameters = false
  end

  let(:event) do
    ActiveSupport::Notifications::Event.new(
      'identity.active_record', Time.now, Time.now, 1, { sql: 'SELECT * FROM nothing;' }
    )
  end

  describe '.process_action' do
    let(:logger)  { double }
    let(:json)    do
      '{"sql":"SELECT * FROM nothing;","duration":0.0,"request_id":"1","source":"unknown","tags":["request"],"@timestamp":"1970-01-01T00:00:00.000Z","@version":"1"}' + "\n"
    end
    before do
      LogStasher.store.clear
      allow(LogStasher).to receive(:request_context).and_return({ request_id: '1' })
      allow(LogStasher).to receive(:logger).and_return(logger)
      allow(Time).to receive(:now).and_return(Time.at(0))
    end
    it 'calls all extractors and outputs the json' do
      expect(LogStasher.logger).to receive(:<<).with(json)
      subject.identity(event)
    end
  end

  describe 'logstasher output' do
    it 'should contain request tag' do
      subject.identity(event)
      expect(log_output.json['tags']).to eq ['request']
    end

    it 'should contain identifier' do
      subject.identity(event)
      expect(log_output.json['sql']).to eq 'SELECT * FROM nothing;'
    end

    it 'should include duration time' do
      subject.identity(event)
      expect(log_output.json['duration']).to eq 0.00
    end

    it 'should not contain :connection' do
      event.payload[:connection] = Object.new

      subject.identity(event)
      expect(event.payload[:connection]).not_to be_nil
      expect(log_output.json['connection']).to be_nil
    end
  end

  describe 'with append_custom_params block specified' do
    let(:request) { double(remote_ip: '10.0.0.1', env: {}) }
    it 'should add default custom data to the output' do
      allow(request).to receive_messages(params: { controller: 'home', action: 'index' })
      LogStasher.add_default_fields_to_payload(event.payload.merge!(params: { foo: 'bar' }), request)
      subject.identity(event)
      expect(log_output.json['ip']).to eq '10.0.0.1'
      expect(log_output.json['route']).to eq 'home#index'
      expect(log_output.json['parameters']).to eq 'foo' => 'bar'
    end
  end

  describe 'with append_custom_params block specified' do
    before do
      allow(LogStasher).to receive(:add_custom_fields) do |&block|
        @block = block
      end
      LogStasher.add_custom_fields do |payload|
        payload[:user] = 'user'
      end
      LogStasher::CustomFields.custom_fields += [:user]
    end

    it 'should add the custom data to the output' do
      @block.call(event.payload)
      subject.identity(event)
      expect(log_output.json['user']).to eq 'user'
    end
  end

  describe 'db_runtime incrementing' do
    let(:event) do
      start = Time.now
      finish = Time.now + 1
      ActiveSupport::Notifications::Event.new(
        'identity.active_record', start, finish, 1, { sql: '' }
      )
    end

    it 'should increment runtime by event duration' do
      expect(described_class).to receive(:runtime=).with(be_within(0.05).of(1000.0))
      subject.identity(event)
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<actions>
        <action>
            <actionName>run</actionName>
            <packagings>
                <packaging>jar</packaging>
            </packagings>
            <goals>
                <goal>process-classes</goal>
                <goal>org.codehaus.mojo:exec-maven-plugin:1.2.1:exec</goal>
            </goals>
            <properties>
                <exec.args>-classpath %classpath GUI.MainGUI</exec.args>
                <exec.executable>java</exec.executable>
            </properties>
        </action>
        <action>
            <actionName>build</actionName>
            <preAction>build-with-dependencies</preAction>
            <packagings>
                <packaging>*</packaging>
            </packagings>
            <goals>
                <goal>install</goal>
            </goals>
        </action>
    </actions>


text:
import {
  report,
  ruleMessages,
  styleSearch,
  validateOptions,
} from "../../utils"

export const ruleName = "string-no-newline"

export const messages = ruleMessages(ruleName, {
  rejected: "Unexpected newline in string",
})

export default function (actual) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, { actual })
    if (!validOptions) { return }

    const cssString = root.toString()
    styleSearch({ source: cssString, target: "\n", withinStrings: true }, match => {
      if (cssString[match.startIndex - 1] === "\\") { return }
      report({
        message: messages.rejected,
        node: root,
        index: match.startIndex,
        result,
        ruleName,
      })
    })
  }
}


text:
#include "modules/prediction/network/net_util.h"

#include <unordered_map>

#include "modules/common/log.h"

namespace apollo {
namespace prediction {
namespace network {

float sigmoid(const float x) { return 1 / (1 + exp(-x)); }

float tanh(const float x) { return std::tanh(x); }

float linear(const float x) { return x; }

float hard_sigmoid(const float x) {
  const float z = 0.2 * x + 0.5;
  return z <= 0.0 ? 0.0 : (z <= 1.0 ? z : 1.0);
}

float relu(const float x) { return (x > 0.0) ? x : 0.0; }

std::function<float(float)> serialize_to_function(const std::string& str) {
  static const std::unordered_map<std::string, std::function<float(float)> >
      func_map({{"linear", linear},
                {"tanh", tanh},
                {"sigmoid", sigmoid},
                {"hard_sigmoid", hard_sigmoid},
                {"relu", relu}});
  return func_map.at(str);
}

bool LoadTensor(const TensorParameter& tensor_pb, Eigen::MatrixXf* matrix) {
  if (tensor_pb.data_size() == 0 || tensor_pb.shape_size() == 0) {
    AERROR << "Fail to load the necessary fields!";
    return false;
  }
  if (tensor_pb.shape_size() < 2) {
    ADEBUG << "Load tensor size: (1, " << tensor_pb.shape(0) << ")";
    matrix->resize(1, tensor_pb.shape(0));
    for (int i = 0; i < tensor_pb.shape(0); ++i) {
      (*matrix)(0, i) = static_cast<float>(tensor_pb.data(i));
    }
    return true;
  }
  ADEBUG << "Load tensor size: (" << tensor_pb.shape(0) << ", "
         << tensor_pb.shape(1) << ")";
  CHECK_EQ(tensor_pb.shape_size(), 2);
  matrix->resize(tensor_pb.shape(0), tensor_pb.shape(1));
  for (int i = 0; i < tensor_pb.shape(0); ++i) {
    for (int j = 0; j < tensor_pb.shape(1); ++j) {
      (*matrix)(i, j) =
          static_cast<float>(tensor_pb.data(i * tensor_pb.shape(1) + j));
    }
  }
  return true;
}

bool LoadTensor(const TensorParameter& tensor_pb, Eigen::VectorXf* vector) {
  if (tensor_pb.data_size() == 0 || tensor_pb.shape_size() == 0) {
    AERROR << "Fail to load the necessary fields!";
    return false;
  }
  ADEBUG << "Load tensor size: (" << tensor_pb.shape(0) << ", 1)";
  CHECK_EQ(tensor_pb.shape_size(), 1);
  if (tensor_pb.shape_size() == 1) {
    vector->resize(tensor_pb.shape(0));
    for (int i = 0; i < tensor_pb.shape(0); ++i) {
      (*vector)(i) = static_cast<float>(tensor_pb.data(i));
    }
  }
  return true;
}

}  // namespace network
}  // namespace prediction
}  // namespace apollo


text:
module Delta
  module Controller
    def self.included(base)
      base.class_eval do
        before_action do
          Delta.set_current_user_proc ->{
            begin
              self.send Delta.config.controller_user_method
            rescue => e
              Rails.logger.info "[Delta] Unable to get current " +
                                "user (#{e.class}: #{e.message})"
              nil
            end
          }
        end
      end
    end
  end
end


text:
package io.freefair.gradle.plugins.lombok;

import io.freefair.gradle.plugins.lombok.internal.ConfigUtil;
import io.freefair.gradle.plugins.lombok.tasks.LombokJarTask;
import io.freefair.gradle.plugins.lombok.tasks.LombokTask;
import lombok.Getter;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;

@Getter
public class LombokBasePlugin implements Plugin<Project> {

    private LombokExtension lombokExtension;
    private Configuration lombokConfiguration;

    @Override
    public void apply(Project project) {
        lombokExtension = project.getExtensions().create("lombok", LombokExtension.class);
        lombokExtension.getDisableConfig().convention(ConfigUtil.isDisableConfig(project));

        lombokConfiguration = project.getConfigurations().create("lombok");
        lombokConfiguration.defaultDependencies(dependencySet -> dependencySet.add(
                project.getDependencies().create("org.projectlombok:lombok:" + lombokExtension.getVersion().get())
        ));

        project.getTasks().withType(LombokTask.class)
                .configureEach(lombokTask -> lombokTask.getLombokClasspath().from(lombokConfiguration));

        project.getTasks().withType(LombokJarTask.class)
                .configureEach(lombokJarTask -> {
                    lombokJarTask.getArchiveVersion().convention(lombokExtension.getVersion());
                    lombokJarTask.getDestinationDirectory().convention(project.getLayout().getBuildDirectory().dir("lombok"));
                });

    }
}


text:
#include "gl/system/gl_system.h"
#include "w_wad.h"
#include "cmdlib.h"
#include "sc_man.h"
#include "m_crc32.h"

#include "gl/renderer/gl_renderstate.h"
#include "gl/renderer/gl_renderer.h"
#include "gl/scene/gl_drawinfo.h"
#include "gl/models/gl_models.h"
#include "gl/textures/gl_material.h"
#include "gl/shaders/gl_shader.h"

#define MAX_QPATH 64

static void UnpackVector(unsigned short packed, float & nx, float & ny, float & nz)
{
	// decode the lat/lng normal to a 3 float normal
	double lat = ( packed >> 8 ) & 0xff;
	double lng = ( packed & 0xff );
	lat *= PI/128;
	lng *= PI/128;

	nx = cos(lat) * sin(lng);
	ny = sin(lat) * sin(lng);
	nz = cos(lng);
}

bool FMD3Model::Load(const char * path, int, const char * buffer, int length)
{
	#pragma pack(4)
	struct md3_header_t
	{
		DWORD Magic;
		DWORD Version;
		char Name[MAX_QPATH];
		DWORD Flags;
		DWORD Num_Frames;
		DWORD Num_Tags;
		DWORD Num_Surfaces;
		DWORD Num_Skins;
		DWORD Ofs_Frames;
		DWORD Ofs_Tags;
		DWORD Ofs_Surfaces;
		DWORD Ofs_Eof;
	};

	struct md3_surface_t
	{
		DWORD Magic;
		char Name[MAX_QPATH];
		DWORD Flags;
		DWORD Num_Frames;
		DWORD Num_Shaders;
		DWORD Num_Verts;
		DWORD Num_Triangles;
		DWORD Ofs_Triangles;
		DWORD Ofs_Shaders;
		DWORD Ofs_Texcoord;
		DWORD Ofs_XYZNormal;
		DWORD Ofs_End;
	};

	struct md3_triangle_t
	{
		DWORD vt_index[3];
	};

	struct md3_shader_t
	{
		char Name[MAX_QPATH];
		DWORD index;
	};

	struct md3_texcoord_t
	{
		float s,t;
	};

	struct md3_vertex_t
	{
		short x,y,z,n;
	};

	struct md3_frame_t
	{
		float min_Bounds[3];
		float max_Bounds[3];
		float localorigin[3];
		float radius;
		char Name[16];
	};
	#pragma pack()

	md3_header_t * hdr=(md3_header_t *)buffer;

	numFrames = LittleLong(hdr->Num_Frames);
	numTags = LittleLong(hdr->Num_Tags);
	numSurfaces = LittleLong(hdr->Num_Surfaces);

	md3_frame_t * frm = (md3_frame_t*)(buffer + LittleLong(hdr->Ofs_Frames));

	frames = new MD3Frame[numFrames];
	for(int i=0;i<numFrames;i++)
	{
		strncpy(frames[i].Name, frm[i].Name, 16);
		for(int j=0;j<3;j++) frames[i].origin[j] = frm[i].localorigin[j];
	}

	md3_surface_t * surf = (md3_surface_t*)(buffer + LittleLong(hdr->Ofs_Surfaces));

	surfaces = new MD3Surface[numSurfaces];
	for(int i=0;i<numSurfaces;i++)
	{
		MD3Surface * s = &surfaces[i];
		md3_surface_t * ss = surf;

		surf = (md3_surface_t *)(((char*)surf) + LittleLong(surf->Ofs_End));

		s->numSkins = LittleLong(ss->Num_Shaders);
		s->numTriangles = LittleLong(ss->Num_Triangles);
		s->numVertices = LittleLong(ss->Num_Verts);

		// copy triangle indices
		md3_triangle_t * tris = (md3_triangle_t*)(((char*)ss)+LittleLong(ss->Ofs_Triangles));
		s->tris = new MD3Triangle[s->numTriangles];

		for(int i=0;i<s->numTriangles;i++) for (int j=0;j<3;j++)
		{
			s->tris[i].VertIndex[j]=LittleLong(tris[i].vt_index[j]);
		}

		// copy shaders (skins)
		md3_shader_t * shader = (md3_shader_t*)(((char*)ss)+LittleLong(ss->Ofs_Shaders));
		s->skins = new FTexture *[s->numSkins];

		for(int i=0;i<s->numSkins;i++)
		{
			// [BB] According to the MD3 spec, Name is supposed to include the full path.
			s->skins[i] = LoadSkin("", shader[i].Name);
			// [BB] Fall back and check if Name is relative.
			if ( s->skins[i] == NULL )
				s->skins[i] = LoadSkin(path, shader[i].Name);
		}

		// Load texture coordinates
		md3_texcoord_t * tc = (md3_texcoord_t*)(((char*)ss)+LittleLong(ss->Ofs_Texcoord));
		s->texcoords = new MD3TexCoord[s->numVertices];

		for(int i=0;i<s->numVertices;i++)
		{
			s->texcoords[i].s = tc[i].s;
			s->texcoords[i].t = tc[i].t;
		}

		// Load vertices and texture coordinates
		md3_vertex_t * vt = (md3_vertex_t*)(((char*)ss)+LittleLong(ss->Ofs_XYZNormal));
		s->vertices = new MD3Vertex[s->numVertices * numFrames];

		for(int i=0;i<s->numVertices * numFrames;i++)
		{
			s->vertices[i].x = LittleShort(vt[i].x)/64.f;
			s->vertices[i].y = LittleShort(vt[i].y)/64.f;
			s->vertices[i].z = LittleShort(vt[i].z)/64.f * rModelAspectMod;
			UnpackVector( LittleShort(vt[i].n), s->vertices[i].nx, s->vertices[i].ny, s->vertices[i].nz);
		}
	}
	return true;
}

void FMD3Model::BuildVertexBuffer(FModelVertexBuffer *buf)
{
	for (int i = 0; i < numSurfaces; i++)
	{
		MD3Surface * surf = &surfaces[i];

		surf->vindex = buf->vbo_shadowdata.Size();
		surf->iindex = buf->ibo_shadowdata.Size();
		for (int j = 0; j < numFrames * surf->numVertices; j++)
		{
			MD3Vertex* vert = surf->vertices + j;

			FModelVertex bvert;

			int tc = j % surf->numVertices;
			bvert.Set(vert->x, vert->z, vert->y, surf->texcoords[tc].s, surf->texcoords[tc].t);
			bvert.SetNormal(vert->nx, vert->nz, vert->ny);
			buf->vbo_shadowdata.Push(bvert);
		}

		for (int k = 0; k < surf->numTriangles; k++)
		{
			for (int l = 0; l < 3; l++)
			{
				buf->ibo_shadowdata.Push(surf->tris[k].VertIndex[l]);
			}
		}
	}
}

int FMD3Model::FindFrame(const char * name)
{
	for (int i=0;i<numFrames;i++)
	{
		if (!stricmp(name, frames[i].Name)) return i;
	}
	return -1;
}

void FMD3Model::RenderFrame(FTexture * skin, int frameno, int frameno2, double inter, int translation)
{
	if (frameno>=numFrames || frameno2>=numFrames) return;

	for(int i=0;i<numSurfaces;i++)
	{
		MD3Surface * surf = &surfaces[i];

		// [BB] In case no skin is specified via MODELDEF, check if the MD3 has a skin for the current surface.
		// Note: Each surface may have a different skin.
		FTexture *surfaceSkin = skin;
		if (!surfaceSkin)
		{
			if (surf->numSkins==0) return;
			surfaceSkin = surf->skins[0];
			if (!surfaceSkin) return;
		}

		FMaterial * tex = FMaterial::ValidateTexture(surfaceSkin);

		tex->Bind(0, translation);

		gl_RenderState.Apply();
		GLRenderer->mModelVBO->SetupFrame(surf->vindex + frameno * surf->numVertices, surf->vindex + frameno2 * surf->numVertices, inter);
		glDrawElements(GL_TRIANGLES, surf->numTriangles * 3, GL_UNSIGNED_INT, (void*)(intptr_t)(surf->iindex * sizeof(unsigned int)));
	}
}

FMD3Model::~FMD3Model()
{
	if (frames) delete [] frames;
	if (surfaces) delete [] surfaces;
	frames = NULL;
	surfaces = NULL;
}


text:
<!DOCTYPE HTML>

        <title>Geo</title>
        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
        <meta charset="utf-8">
        <link href="style/root.css" type="text/css" rel="stylesheet">
        <link href="style/shapes.css" type="text/css" rel="stylesheet">
        <link href="style/actionBox.css" type="text/css" rel="stylesheet">
        <link href="style/map.css" type="text/css" rel="stylesheet">


text:
class CreatePodcastSubscriptions < ActiveRecord::Migration[7.0]
  def change
    create_table :podcast_subscriptions do |t|
      t.references :user,   null: false, foreign_key: { on_delete: :cascade }
      t.references :feed,   null: false, foreign_key: { on_delete: :cascade }
      t.bigint     :status, null: false, default: 0
      t.text       :title
      t.timestamps
    end
    add_index :podcast_subscriptions, [:user_id, :feed_id], unique: true
  end
end


text:
package com.dmdirc.parser.irc;

/**
 * Capability states.
 * See: http://ircv3.atheme.org/specification/capability-negotiation-3.1
 */
public enum CapabilityState {
    /** Capability is invalid*/
    INVALID("Invalid", (char)0),

    /** Capability is disabled */
    DISABLED("Disabled", '-'),

    /** Capability is pending enabling, (needs ACK) */
    NEED_ACK("Needs ack", '~'),

    /** Capability is enabled entirely */
    ENABLED("Enabled", '+');

    /** Description. */
    private final String description;

    /**
     * Modifier.
     * This should probably be called symbol, but the docs refer to the symbols
     * as "capability modifiers". We just use them to make parsing the messages
     * a bit easier.
     */
    private final Character modifier;

    /**
     * Create a CapabilityState.
     *
     * @param description Description of capability.
     */
    CapabilityState(final String description, final Character modifier) {
        this.description = description;
        this.modifier = modifier;
    }

    /**
     * Get the description for this capability state.
     *
     * @return Description for this capability state.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Get the modifier for this capability state.
     *
     * @return modifier for this capability state.
     */
    public char getModifier() {
        return modifier;
    }

    /**
     * Get the capability state for the given modifier, or null.
     *
     * @param modifier Modifier to get the capability for
     *
     * @return state for the given modifier, or null.
     */
    public static CapabilityState fromModifier(final char modifier) {
        for (CapabilityState cs : CapabilityState.values()) {
            if (cs.getModifier() == modifier) {
                return cs;
            }
        }

        return CapabilityState.INVALID;
    }
}


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:fillViewport="true"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        tools:context="com.pedrocarrillo.expensetracker.ui.login.LoginFragment">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center">

            <android.support.v4.view.ViewPager
                android:id="@+id/vp_welcome"
                android:layout_width="match_parent"
                android:layout_height="match_parent"/>

            <com.viewpagerindicator.CirclePageIndicator
                android:id="@+id/cpi_welcome"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="@dimen/dimen_10dp"/>
        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="@dimen/dimen_15_10dp"
            android:elevation="@dimen/dimen_10dp"
            android:orientation="vertical"
            android:gravity="center">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/dimen_10dp"
                android:text="@string/start_using_expense"/>

            <!--<com.google.android.gms.common.SignInButton-->
                <!--android:id="@+id/sign_in_button"-->
                <!--android:layout_width="wrap_content"-->
                <!--android:layout_height="wrap_content" />-->
            <Button
                android:id="@+id/sign_in"
                android:layout_height="wrap_content"
                android:layout_width="@dimen/dimen_8_10dp"
                android:gravity="center"
                style="@style/ExpenseTrackerButton"
                android:text="@string/start"/>
        </LinearLayout>

    </LinearLayout>
</ScrollView>


text:
Map for search fields (local to remote).

    Object, default = {}

By default, if you search, it will submit column field to the searchData array to send to the server side for searching.
However, sometimes column field names are not the same as search names. The .searchMap allows to map search
fields differently.

You can defined it during object creation:
<textarea class="javascript">
let grid = new w2grid({
    name : 'grid',
    url  : 'url/to/server',
    columns: [
        { field: 'recid', text: 'ID', size: '50px' },
        { field: 'lname', text: 'Last Name', size: '30%' },
        { field: 'fname', text: 'First Name', size: '30%' },
        { field: 'email', text: 'Email', size: '40%' },
        { field: 'sdate', text: 'End Date', size: '120px' }
    ],
    searchMap: {
        lname : 'lastName',
        fname : 'firstName'
    }
});
</textarea>

Or any time during the run-time:
<textarea class="javascript">
w2ui.grid.searchMap['email'] = 'main.email';
</textarea>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Xml.XPath;
using Umbraco.Core.Logging;
using umbraco.interfaces.skinning;

namespace umbraco.cms.businesslogic.skinning
{
    public class Skin
    {
        public Skin()
        {

            Dependencies = new List<Dependency>();

        }

        public static Skin CreateFromFile(string filename)
        {
            XmlDocument manifest = new XmlDocument();

            FileInfo f = new FileInfo(filename);

            if (f.Exists)
            {
                manifest.Load(filename);

                Skin s = Skin.CreateFromXmlNode(manifest.SelectSingleNode("//Skin"));
                s.FullFileName = filename;
                s.Alias = f.Directory.Name;

                return s;
            }
            else
                return null;

        }

        public static string GetSkinNameFromFile(string filename)
        {
            XmlDocument manifest = new XmlDocument();

            FileInfo f = new FileInfo(filename);

            if (f.Exists)
            {
                manifest.Load(filename);
                return manifest.SelectSingleNode("//Skin/Name").InnerText;
            }
            else
                return null;
        }

        public static Skin CreateFromXmlNode(XmlNode node)
        {
            Skin s = new Skin();

            if(node.SelectSingleNode("/Skin/Name") != null)
                s.Name = node.SelectSingleNode("/Skin/Name").InnerText;

            if(node.SelectSingleNode("/Skin/Author") != null)
                s.Author = node.SelectSingleNode("/Skin/Author").InnerText;

            if(node.SelectSingleNode("/Skin/Version") != null)
                s.Version = node.SelectSingleNode("/Skin/Version").InnerText;

            if(node.SelectSingleNode("/Skin/Description") != null)
                s.Description = node.SelectSingleNode("/Skin/Description").InnerText;

            if (node.SelectSingleNode("/Skin/AllowedRootTemplate") != null)
                s.AllowedRootTemplate = node.SelectSingleNode("/Skin/AllowedRootTemplate").InnerText;

            foreach (XmlNode depNode in node.SelectNodes("/Skin//Dependency"))
            {
                try
                {
                    s.Dependencies.Add(Dependency.CreateFromXmlNode(depNode));
                }
                catch (Exception ex)
                {
	                LogHelper.Error<Skin>("Failed to load dependency type " + (depNode.Attributes["type"] != null ? depNode.Attributes["type"].Value : string.Empty), ex);
                }
            }

            if (node.SelectSingleNode("/Skin/CSS") != null)
                s.Css = EmbeddedCss.CreateFromXmlNode(node.SelectSingleNode("/Skin/CSS"));

            return s;
        }

        public static Skin CreateFromAlias(string alias)
        {
            string manifest = Path.Combine(IO.IOHelper.MapPath( IO.SystemDirectories.Masterpages + "/" + alias), "skin.xml");
            return CreateFromFile(manifest);
        }

        public static Skin CreateFromName(string name)
        {
            foreach (Skin s in Skinning.GetAllSkins())
            {
                if (s.Name == name)
                    return s;
            }

            return null;
        }
        public bool OverridesTemplates()
        {
            return (System.IO.Directory.GetFiles(IO.IOHelper.MapPath(SkinFolder), "*.master").Count() > 0);
        }

        public bool HasBackupFiles()
        {
            return System.IO.Directory.Exists( IO.IOHelper.MapPath(SkinBackupFolder) );
        }

        public void SaveOutput()
        {

            XmlDocument manifest = new XmlDocument();
            manifest.Load(FullFileName);

            int i = 1;
            foreach (Dependency d in Dependencies)
            {
                if (d.DependencyType.Values.Count > 0)
                {
                    XmlNode pNode = manifest.SelectSingleNode(
                        string.Format("/Skin/Dependencies/Dependency[{0}]/Properties", i.ToString()));

                    XmlNode outputNode = pNode.SelectSingleNode("./Output");

                    if (outputNode == null)
                    {
                        outputNode = manifest.CreateElement("Output");
                        outputNode.InnerText = d.DependencyType.Values[0].ToString();
                        pNode.AppendChild(outputNode);
                    }
                    else
                    {
                        outputNode.InnerText = d.DependencyType.Values[0].ToString();
                    }

                }

                i++;
            }

            manifest.Save(FullFileName);
        }

        public string FullFileName { get; set; }

        public string Name { get; set; }

        public string Author { get; set; }
        public string Version { get; set; }
        public string Description { get; set; }

        public string Alias { get; set; }

        public string AllowedRootTemplate { get; set; }

        public List<Dependency> Dependencies { get; set; }

        public EmbeddedCss Css { get; set; }

        public void RollbackDependencies()
        {

            XmlDocument manifest = new XmlDocument();
            manifest.Load(FullFileName);

            //emtpy output tags

            foreach(XmlNode oNode in  manifest.SelectNodes("/Skin/Dependencies/Dependency/Properties/Output"))
            {
                oNode.RemoveAll();
            }

            //execute rollback tasks
            XmlNode hNode = manifest.SelectSingleNode("/Skin/History");

            if (!(hNode == null || hNode.SelectNodes("Task").Count == 0))
            {
                XPathNavigator navigator = manifest.CreateNavigator();
                XPathExpression expression = navigator.Compile("/Skin/History/Task");

                expression.AddSort("@executed", XmlSortOrder.Descending, XmlCaseOrder.UpperFirst,
                        string.Empty, XmlDataType.Text);

                XPathNodeIterator iterator = navigator.Select(expression);

                foreach (XPathNavigator item in iterator)
                {
                    Task t = Task.CreateFromXmlNode(((System.Xml.IHasXmlNode)item).GetNode());
                    t.TaskType.RollBack(((System.Xml.IHasXmlNode)item).GetNode().SelectSingleNode("OriginalValue").InnerText);
                }

                hNode.RemoveAll();

            }

            manifest.Save(FullFileName);
        }

        public void DeployTemplateFiles()
        {
            DeployTemplateFiles(IO.SystemDirectories.Masterpages);
        }

        public void DeployTemplateFiles(string folder)
        {
            string[] masterFiles = System.IO.Directory.GetFiles(IO.IOHelper.MapPath(SkinFolder), "*.master");

            if (masterFiles.Count() > 0)
            {
                if (!System.IO.Directory.Exists(IO.IOHelper.MapPath(SkinBackupFolder)))
                    System.IO.Directory.CreateDirectory(IO.IOHelper.MapPath(SkinBackupFolder));

                foreach (string master in masterFiles)
                {
                    FileInfo fi = new FileInfo(master);
                    string original = Path.Combine(IO.IOHelper.MapPath(IO.SystemDirectories.Masterpages), fi.Name);
                    string backup = Path.Combine(IO.IOHelper.MapPath(SkinBackupFolder), fi.Name);

                    if (System.IO.File.Exists(original))
                        System.IO.File.Copy(original, backup, true);

                    System.IO.File.Copy(master, original, true);
                }
            }
        }

        public void RollbackTemplateFiles(){
            RollbackTemplateFiles(IO.SystemDirectories.Masterpages);
        }

        public void RollbackTemplateFiles(string folder)
        {
            string[] masterFiles = System.IO.Directory.GetFiles(IO.IOHelper.MapPath(SkinFolder), "*.master");

            //1. take the skin files back into skin folder to store the changes made
            if (masterFiles.Count() > 0)
            {
                foreach (string master in masterFiles)
                {
                    FileInfo fi = new FileInfo(master);
                    string inUse = Path.Combine(IO.IOHelper.MapPath(IO.SystemDirectories.Masterpages), fi.Name);

                    if (System.IO.File.Exists(inUse))
                        System.IO.File.Copy(inUse, master, true);
                }
            }

            //2. copy the /backup files back to the masterpages to restore the templates to the way they were before the skin was applied
            string[] backedUpmasterFiles = System.IO.Directory.GetFiles(IO.IOHelper.MapPath(SkinBackupFolder), "*.master");
            foreach (string backup in backedUpmasterFiles)
            {
                FileInfo fi = new FileInfo(backup);
                string inUse = Path.Combine(IO.IOHelper.MapPath(IO.SystemDirectories.Masterpages), fi.Name);

                System.IO.File.Copy(backup, inUse, true);
                System.IO.File.Delete(backup);
            }

            //3. put on some clothes
        }

        public void ExecuteInstallTasks()
        {
            XmlDocument manifest = new XmlDocument();
            manifest.Load(FullFileName);

            foreach (XmlNode tNode in manifest.SelectNodes("/Skin/Install/Task"))
            {
                Task t = Task.CreateFromXmlNode(tNode);
                TaskExecutionDetails details = t.TaskType.Execute(t.Value);

                if (details.TaskExecutionStatus == TaskExecutionStatus.Completed)
                {
                   AddTaskHistoryNode(
                        t.TaskType.ToXml(details.OriginalValue, details.NewValue));
                }

            }
        }

        public void AddTaskHistoryNode(XmlNode taskNode)
        {
            XmlDocument manifest = new XmlDocument();
            manifest.Load(FullFileName);

            XmlNode hNode = manifest.SelectSingleNode("/Skin/History");

            if (hNode == null)
            {
                hNode = manifest.CreateElement("History");
                manifest.SelectSingleNode("/Skin").AppendChild(hNode);
            }

            hNode.AppendChild(manifest.ImportNode(taskNode, true));

            manifest.Save(FullFileName);
        }

        public string SkinFolder
        {
            get
            {
                return IO.SystemDirectories.Masterpages + "/" + Alias;
            }
        }

        public string SkinBackupFolder
        {
            get
            {
                return SkinFolder + "/backup";
            }
        }

    }
}


text:
{% extends "site_base.html" %}

{% load i18n %}
{% load uni_form_tags %}
{% load account_tags %}

{% block head_title %}{% trans "Sign In" %}{% endblock %}

{% block body %}

{% trans "Sign In" %}

    {% if not user.is_authenticated %}
        {% url account_signup as signup_url %}
        {% url socialaccount_login as social_login_url %}

{% blocktrans %}No account? Sign up for an new account, or sign in using an existing 3rd party account.{% endblocktrans %}

    {% endif %}

    <form class="login uniForm" method="POST" action="{% url account_login %}">
        {% csrf_token %}
        <fieldset class="inlineLabels">
            {{ form|as_uni_form }}
            {% if redirect_field_value %}
                <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
            {% endif %}

                {% trans "Forgot Password?" %}

                <button class="primaryAction" type="submit">{% trans "Sign In" %}</button>

        </fieldset>
    </form>

    {% if user.is_authenticated %}
    {% include "account/snippets/already_logged_in.html" %}
    {% endif %}

{% endblock %}


text:
package com.intellij.usages.rules;

import com.intellij.usages.Usage;
import com.intellij.usages.UsageTarget;
import org.jetbrains.annotations.NotNull;

/**
 * @author yole
 */
public interface UsageFilteringRuleEx extends UsageFilteringRule {
  boolean isVisible(@NotNull Usage usage, @NotNull UsageTarget[] targets);
}


text:
<!--
     Copyright (C) 2017 Angel Newton

     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.
 -->
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="nav_header_vertical_spacing">16dp</dimen>
    <dimen name="nav_header_height">160dp</dimen>
    <dimen name="fab_margin">16dp</dimen>
    <dimen name="card_margin">16dp</dimen>

    <!-- verb image original 6width=48dp x 6height=24dp -->
    <dimen name="verb_image_width">288dp</dimen>
    <dimen name="verb_image_height">144dp</dimen>
</resources>


text:
#ifndef _PMON_LIB_H_
#define _PMON_LIB_H_

void PmonEntry(void);
int  InitShell(void);

int  MemoryPuts(char *);
void video_puts(const char *);

void delay(int);

#endif /* _PMON_LIB_H_ */


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

<title>AdvancedPlayer</title>
<meta name="date" content="2012-12-12">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

javazoom.jl.player.advanced

Class AdvancedPlayer

java.lang.Object

javazoom.jl.player.advanced.AdvancedPlayer

public class AdvancedPlayer
extends java.lang.Object

a hybrid of javazoom.jl.player.Player tweeked to include play(startFrame, endFrame)
 hopefully this will be included in the api

Constructor Summary

Constructors

Constructor and Description

AdvancedPlayer(java.io.InputStream stream)

Creates a new Player instance.

AdvancedPlayer(java.io.InputStream stream,
              AudioDevice device)

Method Summary

Methods

Modifier and Type
Method and Description

void
close()

Cloases this player.

PlaybackListener
getPlayBackListener()

gets the PlaybackListener

void
play()

boolean
play(int frames)

Plays a number of MPEG audio frames.

boolean
play(int start,
    int end)

Plays a range of MPEG audio frames

void
setPlayBackListener(PlaybackListener listener)

sets the PlaybackListener

void
stop()

closes the player and notifies PlaybackListener

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

AdvancedPlayer

public AdvancedPlayer(java.io.InputStream stream)
               throws JavaLayerException

Creates a new Player instance.

Throws:

JavaLayerException

AdvancedPlayer

public AdvancedPlayer(java.io.InputStream stream,
              AudioDevice device)
               throws JavaLayerException

Throws:

JavaLayerException

Method Detail

play

public void play()
          throws JavaLayerException

Throws:

JavaLayerException

play

public boolean play(int frames)
             throws JavaLayerException

Plays a number of MPEG audio frames.

Parameters:

frames - The number of frames to play.

Returns:

true if the last frame was played, or false if there are
                        more frames.

Throws:

JavaLayerException

close

public void close()

Cloases this player. Any audio currently playing is stopped
 immediately.

play

public boolean play(int start,
           int end)
             throws JavaLayerException

Plays a range of MPEG audio frames

Parameters:

start - The first frame to play

end - The last frame to play

Returns:

true if the last frame was played, or false if there are more frames.

Throws:

JavaLayerException

setPlayBackListener

public void setPlayBackListener(PlaybackListener listener)

sets the PlaybackListener

getPlayBackListener

public PlaybackListener getPlayBackListener()

gets the PlaybackListener

stop

public void stop()

closes the player and notifies PlaybackListener

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text: module.exports = require('./dist/editor');


text:
bespoke.horizontal.from('article', {
    bullets: 'li, .bullet',
    scale: true,
    hash: true,
    progress: true,
    state: true,
    spotlight: true
});


text:
import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { AuthService } from '../../providers/auth-service';

@Component({
  selector: 'page-register',
  templateUrl: 'register.html'
})
export class RegisterPage {
  createSuccess = false;
  registerCredentials = {
    fullname: '',
    username: '',
    email: '',
    password: '',
    confirmpassword: ''};

  constructor(private nav: NavController, private auth: AuthService,
   private alertCtrl: AlertController) {}

   //Tries to register a new account and sends verification
  public register() {
    if(this.registerCredentials.password === this.registerCredentials.confirmpassword) {

      this.auth.register(this.registerCredentials).subscribe(success => {
        if (success.name === "error") {
          this.showPopup("Error", success.detail);
        } else {
          //if (this.auth.isDebug()) console.log("Registered user: "+success)
          if (this.auth.isDebug()) console.log(success);
          this.createSuccess = true;
          this.auth.sendVerify(this.registerCredentials).subscribe(data => {
            this.showPopup("Verify your Account", "Account created. Please verify your account in the email we sent you at "+this.registerCredentials.email+"");
          });
        }
      },
      error => {
        this.showPopup("Error", error);
      });
    }else{
      this.showPopup("Error", "Passwords must match");
    }
  }

 // Displays a message as a popup
  showPopup(title, text) {
    let alert = this.alertCtrl.create({
      title: title,
      subTitle: text,
      buttons: [
       {
         text: 'OK',
         handler: data => {
           if (this.createSuccess) {
             this.nav.popToRoot();
           }
         }
       }
     ]
    });
    alert.present();
  }
}


text:
<?php

class history_hook {

	/**
	 * Hook the recorder
	 */
	public function __construct() {
		Event::add('system.post_controller', array($this, 'history'));
	}

	/**
	 * Save current url to session
	 */
	public function history() {
		if (Kohana::$instance->history) $_SESSION['history'] = url::current();
	}

}

new history_hook();


text:
* composer
* Git 1.6+
* PHP >=5.5
* php5-intl
* phpunit 3.6+ (optional)

### Clone SevenManager repository
- ``` git clone https://github.com/7rin0/SevenManager.git ```
- ``` cd SevenManager ```

### Get Composer & Project dependencies
-  ``` curl -s http://getcomposer.org/installer | php ```
-  ``` sudo mv composer.phar /usr/local/bin/composer ```
-  ``` composer install --prefer-source -n --profile ```

### Prepare database and generate fixtures and assets
-  ``` php app/console doctrine:database:create ```
-  ``` php app/console doctrine:phpcr:init:dbal --force ```
-  ``` php app/console doctrine:phpcr:repository:init ```
-  ``` php app/console doctrine:schema:update --force ```
-  ``` php app/console doctrine:phpcr:fixtures:load -n ```
-  ``` php app/console fos:user:create admin admin@admin.com admin --super-admin ```
-  ``` php app/console assets:install ```
-  ``` php app/console assetic:dump ```
-  ``` make run_server (optional) ```

### Admin URL
http://{HOST}/admin (ex: http://127.0.0.1:7070/admin)

### Set permissions
 -  ``` chmod -R 777 app web ```
     **or**
 - [Symfony: The Recommended Way!](http://symfony.com/doc/current/book/installation.html#book-installation-permissions)

### Preview
![alt tag](https://github.com/7rin0/SevenManager/raw/master/web/images/preview.gif)


text:
module Rex
module Proto
module SMB
class SimpleClient

class OpenPipe < OpenFile

  # Valid modes are: 'trans' and 'rw'
  attr_accessor :mode

  def initialize(*args)
    super(*args)
    self.mode = 'rw'
    @buff = ''
  end

  def read_buffer(length, offset=0)
    length ||= @buff.length
    @buff.slice!(0, length)
  end

  def read(length = nil, offset = 0)
    case self.mode
    when 'trans'
      read_buffer(length, offset)
    when 'rw'
      super(length, offset)
    else
      raise ArgumentError
    end
  end

  def write(data, offset = 0)
    case self.mode

    when 'trans'
      write_trans(data, offset)
    when 'rw'
      super(data, offset)
    else
      raise ArgumentError
    end
  end

  def write_trans(data, offset=0)
    ack = self.client.trans_named_pipe(self.file_id, data)
    doff = ack['Payload'].v['DataOffset']
    dlen = ack['Payload'].v['DataCount']
    @buff << ack.to_s[4+doff, dlen]
  end
end
end
end
end
end


text:
<?php

namespace common\models;

use Yii;

class ModeBase extends \common\models\db\ModeDB {

}


text:
package com.github.fedorchuck.developers_notification.integrations.telegram;

/**
 *
 Author: Volodymyr Fedorchuk

 * @author Volodymyr Fedorchuk
 * @since 0.2.1
 */
@SuppressWarnings("unused")
class Response {
    private Boolean ok;
//    private Result result; //not using

    public Boolean getOk() {
        return ok;
    }
}


text:
"use strict";

const assert = require("chai").assert;

/**
 * Compare two strings for Array.prototype.sort.  This is a useful
 * building-block for more complex comparison functions.
 */
exports.strcmp = function(a, b) {
   return (a < b) ? -1 : ((a > b) ? 1 : 0);
};

/**
 * Indent a single string
 * @param {String} str
 * @param {Integer} count number of spaces to indent (default 4)
 * @return {String} The string, indented
 */
exports.indent = function(str, count) {
    assert.isString(str);
    if (undefined !== count) {
        assert.isNumber(count);
        assert(count > 0);
    }
    else {
        count = 4;
    }
    return " ".repeat(count) + str;
};

/**
 * Convert a list of strings to a newline-delimited, indented string.
 *
 * @param {Array<String>} The strings
 * @param {Integer} count (default 4)
 * @return {String}
 */
exports.listToIndentedString = function(strings, count) {
    return strings.map(s => exports.indent(s, count)).join("\n");
};

/**
 * Pluralize a noun (if necessary).  This is kind of a hack:
 * it doesn't handle 'children', 'wolves', 'gees', or 'oxen'.
 *
 * @param {String} The noun
 * @param {Integer} the count -- if it's not 1, the noun will be pluralized.
 * @return {String}
 */
exports.pluralize = function(noun, count) {
    if (count === 1) {
        return noun;
    }
    if (noun.match("(?:s|sh|ch|z|x)$")) {
        return noun + "es";
    }
    if (noun.endsWith("y")) {
        return noun.substring(0, noun.length - 1) + "ies";
    }
    return noun + "s";
};