text:
package org.apache.hadoop.security.token.delegation;

import java.io.ByteArrayInputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import junit.framework.Assert;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.security.AccessControlException;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hadoop.security.UserGroupInformation.AuthenticationMethod;
import org.apache.hadoop.security.token.SecretManager;
import org.apache.hadoop.security.token.Token;
import org.apache.hadoop.security.token.SecretManager.InvalidToken;
import org.apache.hadoop.security.token.delegation.AbstractDelegationTokenSecretManager.DelegationTokenInformation;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.Time;
import org.junit.Test;

import static org.junit.Assert.*;

public class TestDelegationToken {
  private static final Log LOG = LogFactory.getLog(TestDelegationToken.class);
  private static final Text KIND = new Text("MY KIND");

  public static class TestDelegationTokenIdentifier
  extends AbstractDelegationTokenIdentifier
  implements Writable {

    public TestDelegationTokenIdentifier() {
    }

    public TestDelegationTokenIdentifier(Text owner, Text renewer, Text realUser) {
      super(owner, renewer, realUser);
    }

    @Override
    public Text getKind() {
      return KIND;
    }

    @Override
    public void write(DataOutput out) throws IOException {
      super.write(out);
    }
    @Override
    public void readFields(DataInput in) throws IOException {
      super.readFields(in);
    }
  }

  public static class TestDelegationTokenSecretManager
  extends AbstractDelegationTokenSecretManager<TestDelegationTokenIdentifier> {

    public boolean isStoreNewMasterKeyCalled = false;
    public boolean isRemoveStoredMasterKeyCalled = false;
    public boolean isStoreNewTokenCalled = false;
    public boolean isRemoveStoredTokenCalled = false;
    public boolean isUpdateStoredTokenCalled = false;
    public TestDelegationTokenSecretManager(long delegationKeyUpdateInterval,
                         long delegationTokenMaxLifetime,
                         long delegationTokenRenewInterval,
                         long delegationTokenRemoverScanInterval) {
      super(delegationKeyUpdateInterval, delegationTokenMaxLifetime,
            delegationTokenRenewInterval, delegationTokenRemoverScanInterval);
    }

    @Override
    public TestDelegationTokenIdentifier createIdentifier() {
      return new TestDelegationTokenIdentifier();
    }

    @Override
    protected byte[] createPassword(TestDelegationTokenIdentifier t) {
      return super.createPassword(t);
    }

    @Override
    protected void storeNewMasterKey(DelegationKey key) throws IOException {
      isStoreNewMasterKeyCalled = true;
      super.storeNewMasterKey(key);
    }

    @Override
    protected void removeStoredMasterKey(DelegationKey key) {
      isRemoveStoredMasterKeyCalled = true;
      Assert.assertFalse(key.equals(allKeys.get(currentId)));
    }

    @Override
    protected void storeNewToken(TestDelegationTokenIdentifier ident,
        long renewDate) {
      super.storeNewToken(ident, renewDate);
      isStoreNewTokenCalled = true;
    }

    @Override
    protected void removeStoredToken(TestDelegationTokenIdentifier ident)
        throws IOException {
      super.removeStoredToken(ident);
      isRemoveStoredTokenCalled = true;
    }

    @Override
    protected void updateStoredToken(TestDelegationTokenIdentifier ident,
        long renewDate) {
      super.updateStoredToken(ident, renewDate);
      isUpdateStoredTokenCalled = true;
    }

    public byte[] createPassword(TestDelegationTokenIdentifier t, DelegationKey key) {
      return SecretManager.createPassword(t.getBytes(), key.getKey());
    }

    public Map<TestDelegationTokenIdentifier, DelegationTokenInformation> getAllTokens() {
      return currentTokens;
    }

    public DelegationKey getKey(TestDelegationTokenIdentifier id) {
      return allKeys.get(id.getMasterKeyId());
    }
  }

  public static class TokenSelector extends
  AbstractDelegationTokenSelector<TestDelegationTokenIdentifier>{

    protected TokenSelector() {
      super(KIND);
    }
  }

  @Test
  public void testSerialization() throws Exception {
    TestDelegationTokenIdentifier origToken = new
                        TestDelegationTokenIdentifier(new Text("alice"),
                                          new Text("bob"),
                                          new Text("colin"));
    TestDelegationTokenIdentifier newToken = new TestDelegationTokenIdentifier();
    origToken.setIssueDate(123);
    origToken.setMasterKeyId(321);
    origToken.setMaxDate(314);
    origToken.setSequenceNumber(12345);

    // clone origToken into newToken
    DataInputBuffer inBuf = new DataInputBuffer();
    DataOutputBuffer outBuf = new DataOutputBuffer();
    origToken.write(outBuf);
    inBuf.reset(outBuf.getData(), 0, outBuf.getLength());
    newToken.readFields(inBuf);

    // now test the fields
    assertEquals("alice", newToken.getUser().getUserName());
    assertEquals(new Text("bob"), newToken.getRenewer());
    assertEquals("colin", newToken.getUser().getRealUser().getUserName());
    assertEquals(123, newToken.getIssueDate());
    assertEquals(321, newToken.getMasterKeyId());
    assertEquals(314, newToken.getMaxDate());
    assertEquals(12345, newToken.getSequenceNumber());
    assertEquals(origToken, newToken);
  }

  private Token<TestDelegationTokenIdentifier> generateDelegationToken(
      TestDelegationTokenSecretManager dtSecretManager,
      String owner, String renewer) {
    TestDelegationTokenIdentifier dtId =
      new TestDelegationTokenIdentifier(new Text(
        owner), new Text(renewer), null);
    return new Token<TestDelegationTokenIdentifier>(dtId, dtSecretManager);
  }

  private void shouldThrow(PrivilegedExceptionAction<Object> action,
                           Class<? extends Throwable> except) {
    try {
      action.run();
      Assert.fail("action did not throw " + except);
    } catch (Throwable th) {
      LOG.info("Caught an exception: ", th);
      assertEquals("action threw wrong exception", except, th.getClass());
    }
  }

  @Test
  public void testGetUserNullOwner() {
    TestDelegationTokenIdentifier ident =
        new TestDelegationTokenIdentifier(null, null, null);
    UserGroupInformation ugi = ident.getUser();
    assertNull(ugi);
  }

  @Test
  public void testGetUserWithOwner() {
    TestDelegationTokenIdentifier ident =
        new TestDelegationTokenIdentifier(new Text("owner"), null, null);
    UserGroupInformation ugi = ident.getUser();
    assertNull(ugi.getRealUser());
    assertEquals("owner", ugi.getUserName());
    assertEquals(AuthenticationMethod.TOKEN, ugi.getAuthenticationMethod());
  }

  @Test
  public void testGetUserWithOwnerEqualsReal() {
    Text owner = new Text("owner");
    TestDelegationTokenIdentifier ident =
        new TestDelegationTokenIdentifier(owner, null, owner);
    UserGroupInformation ugi = ident.getUser();
    assertNull(ugi.getRealUser());
    assertEquals("owner", ugi.getUserName());
    assertEquals(AuthenticationMethod.TOKEN, ugi.getAuthenticationMethod());
  }

  @Test
  public void testGetUserWithOwnerAndReal() {
    Text owner = new Text("owner");
    Text realUser = new Text("realUser");
    TestDelegationTokenIdentifier ident =
        new TestDelegationTokenIdentifier(owner, null, realUser);
    UserGroupInformation ugi = ident.getUser();
    assertNotNull(ugi.getRealUser());
    assertNull(ugi.getRealUser().getRealUser());
    assertEquals("owner", ugi.getUserName());
    assertEquals("realUser", ugi.getRealUser().getUserName());
    assertEquals(AuthenticationMethod.PROXY,
                 ugi.getAuthenticationMethod());
    assertEquals(AuthenticationMethod.TOKEN,
                 ugi.getRealUser().getAuthenticationMethod());
  }

  @Test
  public void testDelegationTokenSecretManager() throws Exception {
    final TestDelegationTokenSecretManager dtSecretManager =
      new TestDelegationTokenSecretManager(24*60*60*1000,
          3*1000,1*1000,3600000);
    try {
      dtSecretManager.startThreads();
      final Token<TestDelegationTokenIdentifier> token =
        generateDelegationToken(
          dtSecretManager, "SomeUser", "JobTracker");
      Assert.assertTrue(dtSecretManager.isStoreNewTokenCalled);
      // Fake renewer should not be able to renew
      shouldThrow(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          dtSecretManager.renewToken(token, "FakeRenewer");
          return null;
        }
      }, AccessControlException.class);
      long time = dtSecretManager.renewToken(token, "JobTracker");
      Assert.assertTrue(dtSecretManager.isUpdateStoredTokenCalled);
      assertTrue("renew time is in future", time > Time.now());
      TestDelegationTokenIdentifier identifier =
        new TestDelegationTokenIdentifier();
      byte[] tokenId = token.getIdentifier();
      identifier.readFields(new DataInputStream(
          new ByteArrayInputStream(tokenId)));
      Assert.assertTrue(null != dtSecretManager.retrievePassword(identifier));
      LOG.info("Sleep to expire the token");
      Thread.sleep(2000);
      //Token should be expired
      try {
        dtSecretManager.retrievePassword(identifier);
        //Should not come here
        Assert.fail("Token should have expired");
      } catch (InvalidToken e) {
        //Success
      }
      dtSecretManager.renewToken(token, "JobTracker");
      LOG.info("Sleep beyond the max lifetime");
      Thread.sleep(2000);

      shouldThrow(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          dtSecretManager.renewToken(token, "JobTracker");
          return null;
        }
      }, InvalidToken.class);
    } finally {
      dtSecretManager.stopThreads();
    }
  }

  @Test
  public void testCancelDelegationToken() throws Exception {
    final TestDelegationTokenSecretManager dtSecretManager =
      new TestDelegationTokenSecretManager(24*60*60*1000,
        10*1000,1*1000,3600000);
    try {
      dtSecretManager.startThreads();
      final Token<TestDelegationTokenIdentifier> token =
        generateDelegationToken(dtSecretManager, "SomeUser", "JobTracker");
      //Fake renewer should not be able to renew
      shouldThrow(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          dtSecretManager.renewToken(token, "FakeCanceller");
          return null;
        }
      }, AccessControlException.class);
      dtSecretManager.cancelToken(token, "JobTracker");
      Assert.assertTrue(dtSecretManager.isRemoveStoredTokenCalled);
      shouldThrow(new PrivilegedExceptionAction<Object>() {
        @Override
        public Object run() throws Exception {
          dtSecretManager.renewToken(token, "JobTracker");
          return null;
        }
      }, InvalidToken.class);
    } finally {
      dtSecretManager.stopThreads();
    }
  }

  @Test(timeout = 10000)
  public void testRollMasterKey() throws Exception {
    TestDelegationTokenSecretManager dtSecretManager =
      new TestDelegationTokenSecretManager(800,
        800,1*1000,3600000);
    try {
      dtSecretManager.startThreads();
      //generate a token and store the password
      Token<TestDelegationTokenIdentifier> token = generateDelegationToken(
          dtSecretManager, "SomeUser", "JobTracker");
      byte[] oldPasswd = token.getPassword();
      //store the length of the keys list
      int prevNumKeys = dtSecretManager.getAllKeys().length;

      dtSecretManager.rollMasterKey();
      Assert.assertTrue(dtSecretManager.isStoreNewMasterKeyCalled);

      //after rolling, the length of the keys list must increase
      int currNumKeys = dtSecretManager.getAllKeys().length;
      Assert.assertEquals((currNumKeys - prevNumKeys) >= 1, true);

      //after rolling, the token that was generated earlier must
      //still be valid (retrievePassword will fail if the token
      //is not valid)
      ByteArrayInputStream bi =
        new ByteArrayInputStream(token.getIdentifier());
      TestDelegationTokenIdentifier identifier =
        dtSecretManager.createIdentifier();
      identifier.readFields(new DataInputStream(bi));
      byte[] newPasswd =
        dtSecretManager.retrievePassword(identifier);
      //compare the passwords
      Assert.assertEquals(oldPasswd, newPasswd);
      // wait for keys to expire
      while(!dtSecretManager.isRemoveStoredMasterKeyCalled) {
        Thread.sleep(200);
      }
    } finally {
      dtSecretManager.stopThreads();
    }
  }

  @Test
  @SuppressWarnings("unchecked")
  public void testDelegationTokenSelector() throws Exception {
    TestDelegationTokenSecretManager dtSecretManager =
      new TestDelegationTokenSecretManager(24*60*60*1000,
        10*1000,1*1000,3600000);
    try {
      dtSecretManager.startThreads();
      AbstractDelegationTokenSelector ds =
      new AbstractDelegationTokenSelector<TestDelegationTokenIdentifier>(KIND);

      //Creates a collection of tokens
      Token<TestDelegationTokenIdentifier> token1 = generateDelegationToken(
          dtSecretManager, "SomeUser1", "JobTracker");
      token1.setService(new Text("MY-SERVICE1"));

      Token<TestDelegationTokenIdentifier> token2 = generateDelegationToken(
          dtSecretManager, "SomeUser2", "JobTracker");
      token2.setService(new Text("MY-SERVICE2"));

      List<Token<TestDelegationTokenIdentifier>> tokens =
        new ArrayList<Token<TestDelegationTokenIdentifier>>();
      tokens.add(token1);
      tokens.add(token2);

      //try to select a token with a given service name (created earlier)
      Token<TestDelegationTokenIdentifier> t =
        ds.selectToken(new Text("MY-SERVICE1"), tokens);
      Assert.assertEquals(t, token1);
    } finally {
      dtSecretManager.stopThreads();
    }
  }

  @Test
  public void testParallelDelegationTokenCreation() throws Exception {
    final TestDelegationTokenSecretManager dtSecretManager =
        new TestDelegationTokenSecretManager(2000, 24 * 60 * 60 * 1000,
            7 * 24 * 60 * 60 * 1000, 2000);
    try {
      dtSecretManager.startThreads();
      int numThreads = 100;
      final int numTokensPerThread = 100;
      class tokenIssuerThread implements Runnable {

        @Override
        public void run() {
          for(int i =0;i <numTokensPerThread; i++) {
            generateDelegationToken(dtSecretManager, "auser", "arenewer");
            try {
              Thread.sleep(250);
            } catch (Exception e) {
            }
          }
        }
      }
      Thread[] issuers = new Thread[numThreads];
      for (int i =0; i <numThreads; i++) {
        issuers[i] = new Daemon(new tokenIssuerThread());
        issuers[i].start();
      }
      for (int i =0; i <numThreads; i++) {
        issuers[i].join();
      }
      Map<TestDelegationTokenIdentifier, DelegationTokenInformation> tokenCache = dtSecretManager
          .getAllTokens();
      Assert.assertEquals(numTokensPerThread*numThreads, tokenCache.size());
      Iterator<TestDelegationTokenIdentifier> iter = tokenCache.keySet().iterator();
      while (iter.hasNext()) {
        TestDelegationTokenIdentifier id = iter.next();
        DelegationTokenInformation info = tokenCache.get(id);
        Assert.assertTrue(info != null);
        DelegationKey key = dtSecretManager.getKey(id);
        Assert.assertTrue(key != null);
        byte[] storedPassword = dtSecretManager.retrievePassword(id);
        byte[] password = dtSecretManager.createPassword(id, key);
        Assert.assertTrue(Arrays.equals(password, storedPassword));
        //verify by secret manager api
        dtSecretManager.verifyToken(id, password);
      }
    } finally {
      dtSecretManager.stopThreads();
    }
  }

  @Test
  public void testDelegationTokenNullRenewer() throws Exception {
    TestDelegationTokenSecretManager dtSecretManager =
      new TestDelegationTokenSecretManager(24*60*60*1000,
        10*1000,1*1000,3600000);
    dtSecretManager.startThreads();
    TestDelegationTokenIdentifier dtId = new TestDelegationTokenIdentifier(new Text(
        "theuser"), null, null);
    Token<TestDelegationTokenIdentifier> token = new Token<TestDelegationTokenIdentifier>(
        dtId, dtSecretManager);
    Assert.assertTrue(token != null);
    try {
      dtSecretManager.renewToken(token, "");
      Assert.fail("Renewal must not succeed");
    } catch (IOException e) {
      //PASS
    }
  }

  private boolean testDelegationTokenIdentiferSerializationRoundTrip(Text owner,
      Text renewer, Text realUser) throws IOException {
    TestDelegationTokenIdentifier dtid = new TestDelegationTokenIdentifier(
        owner, renewer, realUser);
    DataOutputBuffer out = new DataOutputBuffer();
    dtid.writeImpl(out);
    DataInputBuffer in = new DataInputBuffer();
    in.reset(out.getData(), out.getLength());
    try {
      TestDelegationTokenIdentifier dtid2 =
          new TestDelegationTokenIdentifier();
      dtid2.readFields(in);
      assertTrue(dtid.equals(dtid2));
      return true;
    } catch(IOException e){
      return false;
    }
  }

  @Test
  public void testSimpleDtidSerialization() throws IOException {
    assertTrue(testDelegationTokenIdentiferSerializationRoundTrip(
        new Text("owner"), new Text("renewer"), new Text("realUser")));
    assertTrue(testDelegationTokenIdentiferSerializationRoundTrip(
        new Text(""), new Text(""), new Text("")));
    assertTrue(testDelegationTokenIdentiferSerializationRoundTrip(
        new Text(""), new Text("b"), new Text("")));
  }

  @Test
  public void testOverlongDtidSerialization() throws IOException {
    byte[] bigBuf = new byte[Text.DEFAULT_MAX_LEN + 1];
    for (int i = 0; i < bigBuf.length; i++) {
      bigBuf[i] = 0;
    }
    assertFalse(testDelegationTokenIdentiferSerializationRoundTrip(
        new Text(bigBuf), new Text("renewer"), new Text("realUser")));
    assertFalse(testDelegationTokenIdentiferSerializationRoundTrip(
        new Text("owner"), new Text(bigBuf), new Text("realUser")));
    assertFalse(testDelegationTokenIdentiferSerializationRoundTrip(
        new Text("owner"), new Text("renewer"), new Text(bigBuf)));
  }

  @Test
  public void testDelegationKeyEqualAndHash() {
    DelegationKey key1 = new DelegationKey(1111, 2222, "keyBytes".getBytes());
    DelegationKey key2 = new DelegationKey(1111, 2222, "keyBytes".getBytes());
    DelegationKey key3 = new DelegationKey(3333, 2222, "keyBytes".getBytes());
    Assert.assertEquals(key1, key2);
    Assert.assertFalse(key2.equals(key3));
  }
}


text:
package com.tonescribe.song.linker;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedList;

import com.tonescribe.ToneScribe;
import com.tonescribe.song.RestEvent;
import com.tonescribe.song.Song;
import com.tonescribe.song.SongEvent;
import com.tonescribe.song.ToneEvent;

public class PreciseSongLinker implements SongLinker {

	private static String templateStart, templateEnd;
	static {
		templateStart = loadFile("templateStart.txt");
		templateEnd = loadFile("templateEnd.txt");
	}

	private static String loadFile(String string) {
		StringBuffer sb = new StringBuffer();
		BufferedReader in = new BufferedReader(new InputStreamReader(
				PreciseSongLinker.class.getResourceAsStream(string)));
		try {
			String lineIn = in.readLine();
			while (lineIn != null) {
				sb.append(lineIn).append("\n");
				lineIn = in.readLine();
			}
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}

	@Override
	public String link(Song song) {
		// Prepare beep statements
		HashSet<Integer> freqsUsed = new HashSet<Integer>();
		StringBuilder bodyBuilder = new StringBuilder();
		// Add beep statements
		for (SongEvent e : song.getTones()) {
			if (e.getTimeSeconds() < song.getSelectionStartTimeSec()
					|| e.getTimeSeconds() > song.getSelectionEndTimeSec()) {
				continue;
			}

			if (e instanceof ToneEvent) {
				int freq = (int) ((ToneEvent) e).getPitch();
				freqsUsed.add(freq);
				bodyBuilder.append("\tbeep(").append(freq).append(", ")
						.append((int) (e.getDurationSeconds() * 1000.0))
						.append(");")
						.append(System.getProperty("line.separator"));
			} else if (e instanceof RestEvent) {
				bodyBuilder.append("\t__delay_cycles(")
						.append((int) (e.getDurationSeconds() * 1000000.0))
						.append(");")
						.append(System.getProperty("line.separator"));
			}
		}

		// Create frequency delays switch statement. List with highest
		// frequencies first; these are most sensitive to extra cycles consumed
		// by switch statement
		StringBuilder freqSwitchBuilder = new StringBuilder();
		freqSwitchBuilder.append("switch (freq) {\n");
		LinkedList<Integer> freqsUsedSorted = new LinkedList<Integer>(freqsUsed);
		Collections.sort(freqsUsedSorted, new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				return o2 - o1;
			}
		});
		for (Integer freq : freqsUsedSorted) {
			// Delay for 1M cycles divided by frequency
			// Cut in half again to delay a semiperiod
			int delayCycles = (1000000 / freq) / 2;

			freqSwitchBuilder.append("\t\tcase ").append(freq).append(": \n");
			freqSwitchBuilder.append("\t\t\t__delay_cycles(")
					.append(delayCycles).append(");\n");
			freqSwitchBuilder.append("\t\t\tbreak;\n");
		}
		freqSwitchBuilder.append("\t\t}\n");

		// Prepare beginning of script
		StringBuilder builder = new StringBuilder();
		builder.append(templateStart.replace("<FREQSWITCH>",
				freqSwitchBuilder.toString()).replace("<VERSION>",
				ToneScribe.CURRENT_VERSION));
		// add beeps into script
		builder.append(bodyBuilder);
		// Prepare end of script
		builder.append(templateEnd);
		return builder.toString();
	}

}

redpajama_set_name: RedPajamaGithub


text:
module KnowledgeGraphJs
  class ApplicationController < ActionController::Base
    layout "knowledge_graph_js/application"

    if defined? PlayAuth
      helper PlayAuth::SessionsHelper
    end
  end
end


text:
<phpunit bootstrap="./tests/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="unit">
            <directory>./tests/unit</directory>
        </testsuite>
    </testsuites>
    <filter>
        <blacklist>
            <directory>./protected/vendor/*</directory>
        </blacklist>
    </filter>
    <logging>
        <log type="coverage-clover" target="build/logs/clover.xml"/>
    </logging>
</phpunit>


text:
<?php

namespace VideoHoster\Models;

class LevelModel extends AbstractModel
{
    public $levelId;
    public $name;

    public function exchangeArray($data)
    {
        $this->levelId = (isset($data['levelId'])) ? $data['levelId'] : null;
        $this->name = (isset($data['name'])) ? $data['name'] : null;
    }
}


text:
module Observr
  module EventHandler
    class Portable
      include Base

      def initialize
        @reference_mtime = @reference_atime = @reference_ctime = Time.now
      end

      # Enters listening loop.
      #
      # Will block control flow until application is explicitly stopped/killed.
      #
      # @param [Array<Pathname>] monitored_paths
      #   list of paths the application is currently monitoring.
      #
      # @return [undefined]
      #
      def listen(monitored_paths)
        @monitored_paths = monitored_paths
        loop { trigger; sleep(1) }
      end

      # See if an event occured, and if so notify observers.
      #
      # @return [undefined]
      #
      # @private
      def trigger
        path, type = detect_event
        notify(path, type) unless path.nil?
      end

      # Update list of monitored paths.
      #
      # @param [Array<Pathname>] monitored_paths
      #   list of paths the application is currently monitoring.
      #
      # @return [undefined]
      #
      def refresh(monitored_paths)
        @monitored_paths = monitored_paths
      end

      private

      # Verify mtimes of monitored files.
      #
      # If the latest mtime is more recent than the reference mtime, return
      # that file's path.
      #
      # @return [[Pathname, Symbol]]
      #   path and type of event if event occured, nil otherwise
      #
      # @todo improve ENOENT error handling
      #
      def detect_event # OPTIMIZE, REFACTOR
        @monitored_paths.each do |path|
          return [path, :deleted] unless path.exist?
        end

        mtime_path = @monitored_paths.max {|a,b| a.mtime <=> b.mtime }
        atime_path = @monitored_paths.max {|a,b| a.atime <=> b.atime }
        ctime_path = @monitored_paths.max {|a,b| a.ctime <=> b.ctime }

        if    mtime_path.mtime > @reference_mtime then @reference_mtime = mtime_path.mtime; [mtime_path, :modified]
        elsif atime_path.atime > @reference_atime then @reference_atime = atime_path.atime; [atime_path, :accessed]
        elsif ctime_path.ctime > @reference_ctime then @reference_ctime = ctime_path.ctime; [ctime_path, :changed ]
        else; nil; end
      rescue Errno::ENOENT
        retry
      end
    end
  end
end


text:
#pragma once

// External

// Internal
#include <lfant/Component.h>

namespace lfant {

class Rigidbody;
class Collision;

namespace galaga {

class Projectile : public lfant::Component
{
	DECLARE_TYPE(lfant::Component, Projectile)
public:
	Projectile();
	~Projectile();

	void Init();

	void OnCollideEnter(Rigidbody* rb, Collision* col);

protected:

private:

};

}
}


text:
using Avalonia.Controls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            AppBuilder.Configure<App>()
                .UsePlatformDetect()
                .Start<MainWindow>();
        }
    }
}


text:
;$(function(){
    //*subscribe start*/
    $('.subscribe input').click(function(){
        dao.ajax(
            '/subscribe',
            {
                channel:$(this).attr('name'),
                status:$(this).is(':checked')
            },
            function(){alert('Изменения подписки сохранены.')}
        )
    });
    // end subscribe
    $('.nav [lang_id] ').on( 'click', function (){
        console.log('ksdfhsdk');
        var lang_id = $(this).attr('lang_id');
        $.ajax({
            type: "POST",
            url: '/switch_lang',
            data: { lang_id: lang_id },
            dataType: "json",
            success: function(data){
                if (data.result == 'ok'){
    //								 setTimeout(function () {window.location.reload()}, 5000);
                     setTimeout(function () {window.location.reload()}, 250);
                }
            }
        });
    });
});

function show_d(text){
    var dialog =$(
    "
" +
        "
"+
            "
"+
                "
" +
                    "<button type='button' class='close' data-dismiss='modal' aria-label='Close'>×</button>"+
                    "
 "+text+"
" +
                "
" +
            "
"+
        "
"+
    "
").appendTo('body');
    dialog.modal('show');
}

function reset_ang(){
    var customInterpolationApp = angular.module('customInterpolationApp', []);
    customInterpolationApp.config(function($interpolateProvider) {
        $interpolateProvider.startSymbol('//');
        $interpolateProvider.endSymbol('//');
    });
}

function scroll_top(){
    $('

').appendTo( $('body') );
    $(window).scroll(function() {
        if($(this).scrollTop() != 0) $('#toTop').fadeIn();
        else $('#toTop').fadeOut();
    });
    $('#toTop').on('click', function() {
        $('body,html').animate({scrollTop:0},800);
    });
}

function spam(doc_id){
    // sending and complaints admin
    var toolbar = $('.in-toolbar');
    $('

 ')
        .prependTo(toolbar);

    toolbar.on('click', '.rb.spam', spam_);
    $('body').on('click', '.btn.send_spam', spam_send);

    function spam_(){
        var dialog = $(
            '
'+
                '
'+
                    '
'+
                        '
'+
                            '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>'+
                            '
Сообщить о нарушении
'+
                        '
'+
                        '

' +
                        '
'+
                            'Отправить жалобу'+
                            'Отмена'+
                        '
'+
                   '
'+
                '
'+
            '
'
        ).appendTo('body');
        var tube = $('Описание проблемы
<textarea class="form-control" name="spam" style="height:150px; width:520px;"></textarea>' +
            '').appendTo(dialog.find('.modal-body'));
        dialog.modal();
    }
    function spam_send(){
        var comm_id = $(this).closest('[id_comm]');
        if(comm_id.length){ comm_id = comm_id.attr('id_comm');}
        else{ comm_id = '';}
        $.ajax({
            type: "POST", dataType: "json", url:'/spam',
            data: {
                doc_id:doc_id,
                data:JSON.stringify({
                    user_id:current_user.id,
                    doc_id:doc_id,
                    com_id:comm_id,
                    is_doc:'doc',
                    link:location.protocol+'//'+location.hostname+'/news/'+doc_id+(comm_id ? '#comm_'+comm_id : ''),
                    title:$('.single_object').find('h1 a').text(),
                    body:$('.modal-body').find('[name=spam]').val()
                })
            },
            success: function (data) {
                if (data.result == 'ok') alert('Сообщение успешно отправлено!')
            }
        });
    }
}

function comments_proc(doc_id, comm_id, text_help, mode, id){
    mode = mode || 'strict';
    var click_answer = function(){
        move_editor($(this).closest('[id_comm]').attr('id_comm'));
        $('.container').focus();
        $('.hide_inp:last').focus();
        $('.hide_inp:first').focus();
        $('.container iframe').focus();
        return false;
    };
    var init_f = function() {
        $('li[id_comm]').each(function(){
            var id_comm = $(this).attr('id_comm');
            if(id_comm=='_')return;
            var user_id = $(this).attr('user_id');
            var toolbar = $(this).find('.in-toolbar:first');
            var children = $(this).find('li[id_comm]');
            if (current_user.is_admin ){
                $('
 ban
' +
                    ' ').appendTo(toolbar);
            }
            if (current_user.is_admin || current_user.moderator_comm ||
                current_user.id == user_id && current_user.is_logged_in && !children.length || current_user.edit_comm){
                $('
 ' +
                    '
 ').appendTo(toolbar);
            }
            if (current_user.is_admin || current_user.moderator_comm ||
                current_user.id == user_id && current_user.is_logged_in && !children.length || current_user.del_comm){
                $('
' +
                    '
').appendTo(toolbar);
            }
            toolbar.find('.comm_edit').click(edit_comm);
            toolbar.find('.comm_del').click(del_comm);
        });

        $('.comm_editor').find('[data=name]').text(current_user.name);
        if(!text_help){text_help='';}
        if(mode=="strict"){
            if (current_user.can_comment || current_user.is_admin){
                $('.comment_button').html('

' +
                    ' Добавить комментарий

');
            }else {
                var mess = !current_user.is_logged_in
                    ? text_help
                    : 'У вас нет прав слишком часто добавлять коментарии, в связи с низкой кармой';
                $('.comment_button').html(
                    '
' +
                        '
 Добавить комментарий
' +
                        '

'+
                        '
'+
                        '
 ' + mess + '
');
                $('.comm_answer').hide();
            }
            $('.add_comm_b').click(function(){
                if (current_user.can_comment) click_answer.call(this);
                else if( typeof fb_login == 'function' ) fb_login();
            });
        }else{

            setTimeout(function(){move_editor('_')}, 500);
            $('.add_comm_b').click(function(){
                click_answer.call(this);
            });
            if (current_user.is_logged_in){
                var user_comm = ""+current_user.name+""
            }else{
                var user_comm ='<input class="form-control input-sm" type="text" style="display: inline-block; width: 300px; margin: 10px 0 0 10px;" placeholder="Введите свое имя"/>'
            }
            $('.comm_editor .comm_title').append(user_comm);
        }
    };

    current_user.ready(function() { init_f() });

    function del_comm(){
        console.warn('del_comm');
        var comm_id = $(this).attr('id_comm');
        if (confirm(dao.ct('Вы действительно хотите удалить комментарий?'))) {
            var new_body = $('.t_rich_edit1[name="body1"]').val();
            $.ajax({
                type: "POST", url: '/comm/del', dataType: "json",
                data: { comm_id: comm_id},
                success: function(data){
                    if(data.result=="ok"){
                        if(data.action=="del_dom"){
                            $("li[id_comm="+comm_id+"]").remove();
                        }else{
                            $(".comm_comment[id_comm="+comm_id+"]").text('Коментарий удален.');
                            $(".un[id_comm="+comm_id+"]").text('');
                        }
                    }else{ alert(data.error); }
                }
            });
        } else { /* Do nothing!*/ }
    }

    function edit_comm(){
        var comm_id = $(this).attr('id_comm');
        var parent = $('div.comm_comment[id_comm="'+comm_id+'"]');
        var text_comm =parent.html();
        parent.html('
<textarea class="form-control" style="width:98%; height:100px; border: 1px solid #ccc;"> </textarea>
'+
            '
' +
            '
'+ dao.ct('Отправить')+'
'+
        '
'+ dao.ct( 'Отмена')+'
'+
        '
');
        parent.find('.edit_comm, .cancel_comm').button();
        parent.find('textarea').val(text_comm);
        parent.find('.cancel_comm').click(function(){
            parent.html(text_comm);
        });
        parent.find('.edit_comm').click(function(){
            var new_body = parent.find('textarea').val();
            $.ajax({
                type: "POST", url: '/comm/edit', dataType: "json",
                data: {
                    comm_id: comm_id,
                    user: current_user.id,
                    body: new_body
                },
                success: function(data){
                    if(data.result=="ok"){
                        parent.html(new_body);
                    }else{ dao.user_mess(data.error, 'error'); }
                }
            });
        });
    }

    //    $('.comm_ban1').click(function(){
    $('.ul_comments').on('click', '.comm_ban', function(){
        var branch_id = $(this).attr('id_comm');
        $.ajax({
            url: '/comm/ban', type: 'POST', dataType: 'json',
            data: {
                proc_id: comm_id,
                branch_id: branch_id,
                parent_id: id_comm,
                doc_id: '', link: ''
            },
            beforeSend: function(){ },
            success: function(data){
                if(data.result == 'ok'){
                    alert('Пользователь '+data.user+' забанен.')
                }else dao.user_mess(data.error, 'error');
            }
        });
    });

//    var doc_id = "{{doc['id']}}";
    var id_comm = '_';
    var comm_editor = $('.comm_editor');
    var easewig = $('.easewig').css({'margin':'0px 5px 0px 5px'});

    $('.hide_inp').css({'position':'absolute', 'left':'-5000px'});

    window.move_editor = move_editor;
    function move_editor(_id_comm) {

        id_comm = _id_comm;
        $('[comm_cont="'+id_comm+'"]:first').get(0).appendChild(comm_editor.get(0));
        easewig = $('.easewig');
        name = $('.comm_title input');
        input = easewig.find('textarea');
        if (!input.length)
            input = $('<textarea class="form-control" style="width:99%; height:100px; border:1px solid #ccc;" class="ggg"/>').appendTo(easewig);
    }

    $('.comm_answer').click(click_answer);

    $('.ggg').css({'height': '440px', 'height': '220px'  });
    $('.comm_create').on('click', function(){

        var aa = $('.easewig textarea').val();
        var name = $('.comm_title input').val();
        var comm_id = $(this).attr('id_comm');

        $.ajax({
            url: '/comm/add', type: 'POST', dataType: 'json',
            data: {
                id:id, // id - this is the document ID of the article
                // proc_id: comm_id,
                comm_id: comm_id,
                doc_id: doc_id,
                // proc_id: doc_id,
                // doc_id: comm_id,
                parent: id_comm,
                title: name,
                descr: aa
            },
            beforeSend: function(){ },
            success: function(data){
                if(data.result == 'ok'){
                    draw_comm(data.content);
//                    if(mode=="strict")move_editor('__');
                    move_editor('_');
                    input.val('');
                    input.change();
                }else if(data.result == 'fail') dao.user_mess(data.error+' result.fail', 'error');
                else dao.user_mess(data.error+' error', 'error');

                $('input[name=captcha]').val('');
                $('input[name=hash]').val(data.hash);
                $('img[name=captcha]').attr('src', '/captcha?hash='+data.hash);
            }
        });
    });

    var comm_reversed = false;
    function draw_comm(content){
        var place = $('li[id_comm='+content.parent+'] >ul');
        var aaa = $('

'+
            '
'+
            '
'+(content.our == "true" ? ''+dao.ct(content.name)+'' : content.title)+'
'+
            '
'+content.date+'
'+

            ( current_user.is_admin || 'user:'+content.title ==current_user.id ?
                '
'+
                    '

  '+
                    '

'+
                    '
' :'')+
            '
'+
            '
'+content.body+'
'+
            '
 '+dao.ct('Ответить')+'
'+
            '

' +
        '
')[(comm_reversed ? 'prepend' : 'append')+'To'](place);
        if(!current_user.is_admin ) place.closest('[id_comm]').find('.in-toolbar:first').remove();
        aaa.append('

');
        $('.comm_answer', aaa).click(click_answer);
        if ( current_user.is_admin || 'user:'+content.title ==current_user.id){
            $('.comm_edit', aaa ).on('click', edit_comm);
            $('.comm_del', aaa  ).on('click', del_comm );
        }
        aaa[0].scrollIntoView();
        window.scrollBy(0, -160);
        //aaa.css({'margin-top':'130px'});
    }

}

//*end comments*/
function make_lf2(){
    var lfnid = 0;
    var lfcycle = 25000;
    var lfactive = false;

    var target = $('.nr');
    var nl = target.find('.news-list');
    var ph = target.find('.news-image');

    $('.news-list').on('mouseover', 'a.item', function( event ) {
//        $('a.item').removeClass('active');
        $('a.item').parent().removeClass('active');
        $(this).parent().toggleClass('active');
        ph.find('.main-img').hide();
        ph.find('.news_title').hide();
        target.find('.news_descr').hide();
        $('#news_title'+$(this).attr('var')).show();
        $('#news_descr'+$(this).attr('var')).show();
        $('#news-image-'+$(this).attr('var')).show();
        console.log('img', $('#news-image-'+$(this).attr('var')).length);
        lfactive = true;
        return false;
    });
    $('.news-list').on('mouseout', 'a.item', function( event ) {
        lfnid = 1 * $(this).attr('var');
        lfactive = false;
        return false;
    });
    target.show();
    ph.find('.news_title').hide();
    ph.find('.main_img').hide();
    target.find('.news_descr').hide();
    $('#news-image-0').fadeIn("slow");
    $('#news_title0').fadeIn("slow");
    $('#news_descr0').fadeIn("slow");
    nl.find("a.item").parent().eq(0).toggleClass('active');
    setInterval(NewsRotate, lfcycle);

    function NewsRotate() {
        var lfnidb = lfnid;
        if(!lfactive) {
            nl.find("a.item").parent().removeClass('active');
            lfnid = (lfnid + 1) % nl.find("a.item").length;
            nl.find("a.item").parent().eq(lfnid).toggleClass('active');
            $('#news-image-'+lfnidb).fadeOut("slow",function() {
                $('#news-image-'+lfnid).fadeIn("slow");
            });
            $('#news_title'+lfnidb).fadeOut("slow",function() {
                $('#news_title'+lfnid).fadeIn("slow");
            });
            $('#news_descr'+lfnidb).fadeOut("slow",function() {
                $('#news_descr'+lfnid).fadeIn("slow");
            });
        }
    }
}
function make_lf3(){
    var lfnid = 0;
    var lfcycle = 25000;
    var lfactive = false;

    var target = $('.nr');
    var nl = target.find('.news-list');
    var ph = target.find('.news-image');

    $('.news-list').on('mouseover', 'a.item', function( event ) {
//        $('a.item').removeClass('active');
        $('a.item').parent().removeClass('active');
        $(this).parent().toggleClass('active');
        ph.find('.main-img').hide();
        ph.find('.news_title').hide();
        target.find('.news_descr').hide();
        $('#news_title'+$(this).attr('var')).show();
        $('#news_descr'+$(this).attr('var')).show();
        $('#news-image-'+$(this).attr('var')).show();
        console.log('img', $('#news-image-'+$(this).attr('var')).length);
        lfactive = true;
        return false;
    });
    $('.news-list').on('mouseout', 'a.item', function( event ) {
        lfnid = 1 * $(this).attr('var');
        lfactive = false;
        return false;
    });
    target.show();
    ph.find('.news_title').hide();
    ph.find('.main_img').hide();
    target.find('.news_descr').hide();
    $('#news-image-0').fadeIn("slow");
    $('#news_title0').fadeIn("slow");
    $('#news_descr0').fadeIn("slow");
    nl.find("a.item").parent().eq(0).toggleClass('active');
    setInterval(NewsRotate, lfcycle);

    function NewsRotate() {
        var lfnidb = lfnid;
        if(!lfactive) {
            nl.find("a.item").parent().removeClass('active');
            lfnid = (lfnid + 1) % nl.find("a.item").length;
            nl.find("a.item").parent().eq(lfnid).toggleClass('active');
            $('#news-image-'+lfnidb).fadeOut("slow",function() {
                $('#news-image-'+lfnid).fadeIn("slow");
            });
            $('#news_title'+lfnidb).fadeOut("slow",function() {
                $('#news_title'+lfnid).fadeIn("slow");
            });
            $('#news_descr'+lfnidb).fadeOut("slow",function() {
                $('#news_descr'+lfnid).fadeIn("slow");
            });
        }
    }
}

function make_lf(){
    var lfnid = 0;
    var lfcycle = 25000;
    var lfactive = false;

    target = $('.nr');
    var nl = target.find('.news-list');
    var ph = target.find('.news-image-placeholder');

    $('.news-list').on('mouseover', 'a.item', function( event ) {
        $('a.item').removeClass('active');
        $(this).toggleClass('active');
        ph.find('.news_title').hide();
        ph.find('> img').hide();
        $('#news_title'+$(this).attr('var')).show();
        $('#news-image-'+$(this).attr('var')).show();
        lfactive = true;
        return false;
    });
    $('.news-list').on('mouseout', 'a.item', function( event ) {
        lfnid = 1 * $(this).attr('var');
        lfactive = false;
        return false;
    });
    target.show();
    ph.find('.news_title').hide();
    $('#news-image-0').fadeIn("slow");
    $('#news_title0').fadeIn("slow");
    nl.find("a.item").eq(0).toggleClass('active');
    setInterval(NewsRotate, lfcycle);

    function NewsRotate() {
        var lfnidb = lfnid;
        if(!lfactive) {
            nl.find("a.item").removeClass('active');
            lfnid = (lfnid + 1) % nl.find("a.item").length;
            nl.find("a.item").eq(lfnid).toggleClass('active');
            $('#news-image-'+lfnidb).fadeOut("slow",function() {
                $('#news-image-'+lfnid).fadeIn("slow");
            });
            $('#news_title'+lfnidb).fadeOut("slow",function() {
                $('#news_title'+lfnid).fadeIn("slow");
            });
        }
    }
}

var current_user = function() {
    var on_ready = [];
    init();
    return make_user({});

    // -------------------------------------------------------------------------

    function ready(callback) {
        if (current_user.name) {
            callback();
        } else {
            on_ready.push(callback);
        }
    }

    function make_user(user) {
        user.ready = ready;
        return user;
    }

    function init() {
        $.ajax({
            type:"POST", dataType:"json", url:'/user_status', data: {},
            success:function (data) {
                if (data.result == 'ok') {
                    // current user
                    current_user = make_user(data.user);
                    // panel
                    $('#header .placeholder').parent().append($(data.panel));
                    init_panel();
                }
            }
        });
    }
}();

function init_panel() {
    if( typeof fb_login == 'function' ) $('[name=facebook]'     ).click(fb_login);
    if( typeof tw_login == 'function' ) $('[name=twitter]'      ).click(tw_login);
    if( typeof vk_login == 'function' ) $('[name=vk]'           ).click(vk_login);
    if( typeof vk_login == 'function' ) $('[name=odnoklassniki]').click(ok_login);
    if( typeof gl_login == 'function' ) $('[name=google]'       ).click(gl_login);
    if( typeof ya_login == 'function' ) $('[name=ya]'           ).click(ya_login);
}

function ok_login(){
//    encodeURIComponent
    var redirect = 'http://'+window.location.host+'/oauth_ok';
    var scope = 'email,useroffline';
    var scope = 'VALUABLE_ACCESS;PHOTO_CONTENT';
    var loc = 'http://www.odnoklassniki.ru/oauth/authorize?client_id='+window.ok_id+'&scope='+scope+'&redirect_uri='+redirect+'&response_type=code';

    window.location = loc;
    return false;
}

function vk_login(){
    var redirect = 'http://'+window.location.host+'/oauth_vk';
    var scope = 'email,useroffline';
    var loc = 'http://api.vk.com/oauth/authorize?client_id='+window.vk_id+'&scope='+scope+'&redirect_uri='+redirect+'&response_type=code';
    window.location = loc;
    return false;
}
auth_options = {
    fb: {
        scope: 'email,user_birthday,user_about_me,user_photos,publish_actions,user_checkins,user_actions.music,manage_pages'
    }
};
function fb_login(){
    var scope = auth_options.fb.scope;
    //var redirect = 'http://'+window.location.host+'/oauth_fb?wwww='+dao.base64_encode(window.location.toString());
    var redirect = 'http://'+window.location.host+'/oauth_fb';
    var loc = 'http://graph.facebook.com/oauth/authorize?display=page&client_id='+window.fb_id+'&type=web_server&scope='+scope+'&redirect_uri='+redirect+'&response_type=token';
    window.location = loc;
    return false;
}

function tw_login(){
    var loc = 'http://'+window.location.host+'/oauth_tw_login';
    window.location = loc;
    return false;
}
function ya_login(){
    var loc = 'http://'+window.location.host+'/oauth_ya_login';
    window.location = loc;
    return false;
}

function gl_login(){
    var loc = 'http://'+window.location.host+'/oauth_gl_login';
    window.location = loc;
    return false;
}

function auto_loader(){
    $(window).on('scroll', function(){
        $('.loader').each(function(){
            var $this = $(this);
            var base_skip = $this.attr('skip') || 0;
            base_skip = parseInt(base_skip);

            var aaa = $this.offset().top + $this.height() - $(window).scrollTop() - $('html')[0].offsetHeight;
            if(aaa < 0 && !$this.data('is_loading')){
                $this.data('is_loading', true);
                var waiter = $('
Загрузка
').appendTo($this);
                load($this.attr('slot'), $this.find('.cell').length + base_skip, function(data) {
                    waiter.remove();
                    $this.append(data.content);
                    if (data.len_dv) $this.data('is_loading', false);
                });

            }
        });
    });
    function load(slot, skip, cb){
        var url ='/loader/slot'+window.location.search;
        $.ajax({
            type: "POST", dataType: "json", url: url,
            data: { slot:slot, skip:skip },
            success: function (data) {
                if (data.result == 'ok') {
                    cb(data);
                }
            }
        });
    }
}


text:
<?php defined('C5_EXECUTE') or die(_("Access Denied."));

class ResourceLibraryPackage extends Package {

	protected $pkgHandle = 'resource_library';
	protected $appVersionRequired = '5.3.0';
	protected $pkgVersion = '1.0';

	public function getPackageName() {
		return t("Resource Library");
	}

	public function getPackageDescription() {
		return t("Manage a library of audio, visual and document resources. Great for lectures or sermons and their corresponding documents.");
	}

	public function install() {
		$pkg = parent::install();

        Loader::model('collection_types');
		Loader::model('single_page');

		// install blocks
		BlockType::installBlockTypeFromPackage('resource_library_search', $pkg);

		// install page types
        $pdt = CollectionType::getByHandle('resource_library');
        if( !$pdt || !intval($pdt->getCollectionTypeID()) ){
            $data['ctHandle'] = 'resource_library';
            $data['ctName'] = t('Resource Library');
            $pdt = CollectionType::add($data, $pkg);
        }

		// install single pages
		SinglePage::add('/resources', $pkg);
		$rl = SinglePage::add('/dashboard/resource_library', $pkg);
		SinglePage::add('/dashboard/resource_library/add', $pkg);
		SinglePage::add('/dashboard/resource_library/manage', $pkg);
		SinglePage::add('/dashboard/resource_library/manage/list', $pkg);
		SinglePage::add('/dashboard/resource_library/manage/edit', $pkg);
      	$rl->update(array('cName'=>t('Resource Library'), 'cDescription'=>t('Manage audio, documents, etc.')));
	}

}


text: Rails.application.config.session_store :cookie_store, key: '_test_lock_session'


text:
    <form class="form-vertical" role="form">

                    <input class="form-control" type="text" name="searchText" placeholder="标题,作者"
                            [(ngModel)]="searchText"
                            (keyup)="search($event)" (change)="search($event)">

                        <button class="btn btn-default" type="button"> 搜索</button>

                    <button class="btn btn-success" type="button" (click)="goToWrite()">发表文章</button>

    </form>

                            序号
                            标题
                            作者
                            日期
                            操作

                            {{post.postId}}
                            {{post.title}}
                            {{post.userName}}
                            {{post.postTime}}

            <pagination [totalItems]="totalItems" [maxSize]="maxSize"
            [itemsPerPage]="itemsPerPage" [(ngModel)]="currentPage"
            firstText="{{'firstPage' | translate}}" lastText="{{'lastPage' | translate}}"
            previousText="{{'previousPage' | translate}}" nextText="{{'nextPage' | translate}}"
            [boundaryLinks]="true" [rotate]="false"
            (numPages)="numPages = $event" (pageChanged)="pageChanged($event)" class="pagination-sm"></pagination>


text:
define(
({
	"pasteFromWord": "Вставити з Word",
	"instructions": "Вставка вмісту з Word до текстового поля.  Після вибору вмісту для вставки натисніть кнопку Вставити.  Для скасування вставки тексту натисніть кнопку Скасувати."
})
);


text:
<?php

namespace Dunglas\ApiBundle\Tests\Behat\TestBundle\EventListener;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\Serializer\SerializerInterface;

/**
 * Serializes data in XML then builds the response object.
 *
 * @author Kévin Dunglas <dunglas@gmail.com>
 */
class XmlResponderViewListener
{
    const FORMAT = 'xml';

    /**
     * @var SerializerInterface
     */
    private $serializer;

    public function __construct(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    /**
     * In an API context, converts any data to a XML response.
     *
     * @param GetResponseForControllerResultEvent $event
     *
     * @return Response|mixed
     */
    public function onKernelView(GetResponseForControllerResultEvent $event)
    {
        $controllerResult = $event->getControllerResult();

        if ($controllerResult instanceof Response) {
            return $controllerResult;
        }

        $request = $event->getRequest();

        $format = $request->attributes->get('_api_format');
        if (self::FORMAT !== $format) {
            return $controllerResult;
        }

        switch ($request->getMethod()) {
            case Request::METHOD_POST:
                $status = 201;
                break;

            case Request::METHOD_DELETE:
                $status = 204;
                break;

            default:
                $status = 200;
                break;
        }

        $resourceType = $request->attributes->get('_resource_type');
        $response = new Response(
            $this->serializer->serialize($controllerResult, self::FORMAT, $resourceType->getNormalizationContext()),
            $status,
            ['Content-Type' => 'application/xml']
        );

        $event->setResponse($response);
    }
}


text:
import Options from '../../src/helpers/yargs-options';

describe('options', () => {
    let options: any;

    beforeEach(() => {
        options = new Options();
    });

    afterEach(() => {
        options = null;
    });

    test('should return a defined object', () => {
        expect(options).toBeDefined();
    });

    describe('-> buildOption', () => {
        test('should build an option', () => {
            options.options = {
                config: () => ({
                    alias: 'conf',
                    describe: 'Config file',
                    default: 'test.json'
                }),
            };
            expect(options.buildOption('config').alias).toBe('conf');
        });
    });

    describe('-> buildPositional', () => {
        test('should build a positional string', () => {
            options.positionals = {
                config: () => ({
                    alias: 'conf',
                    describe: 'Config file',
                    default: 'test.json'
                }),
            };
            expect(options.buildPositional('config').alias).toBe('conf');
        });
    });

    describe('-> buildCoerce', () => {
        test('should build a coerce function', () => {
            options.coerce = {
                testc: (newValue: string) => newValue.toUpperCase(),
            };
            expect(options.buildCoerce('testc')).toBeDefined();
        });
    });
});


text:
class ReconstructData : public VideoPostData
{
public:
	static NodeData* Alloc() { return NewObjClear(ReconstructData); }
	virtual RENDERRESULT Execute(BaseVideoPost* node, VideoPostStruct* vps);
	virtual VIDEOPOSTINFO GetRenderInfo(BaseVideoPost* node) { return VIDEOPOSTINFO_STOREFRAGMENTS; }
	virtual Bool RenderEngineCheck(BaseVideoPost* node, Int32 id);
};

RENDERRESULT ReconstructData::Execute(BaseVideoPost* node, VideoPostStruct* vps)
{
	if (vps->vp != VIDEOPOSTCALL_RENDER || vps->open || *vps->error != RENDERRESULT_OK || vps->thread->TestBreak())
		return RENDERRESULT_OK;

	VPBuffer*			rgba = vps->render->GetBuffer(VPBUFFER_RGBA, NOTOK);
	const RayParameter* ray	 = vps->vd->GetRayParameter();	// only in VP_INNER & VIDEOPOSTCALL_RENDER
	if (!ray)
		return RENDERRESULT_OUTOFMEMORY;
	if (!rgba)
		return RENDERRESULT_OUTOFMEMORY;

	Int32 x1, y1, x2, y2, x, y, cnt;

	// example functions
	Int32 cpp = rgba->GetInfo(VPGETINFO_CPP);

	x1	= ray->left;
	y1	= ray->top;
	x2	= ray->right;
	y2	= ray->bottom;
	cnt = x2 - x1 + 1;

	Int			 bufferSize = cpp * cnt;
	Float32* b, *buffer = nullptr;

	if (bufferSize > 0)
		buffer = NewMemClear(Float32, bufferSize);
	if (!buffer)
		return RENDERRESULT_OUTOFMEMORY;

	for (y = y1; y <= y2; y++)
	{
		rgba->GetLine(x1, y, cnt, buffer, 32, true);

		const VPFragment** frag = vps->vd->GetFragments(x1, y, cnt, VPGETFRAGMENTS_Z_P | VPGETFRAGMENTS_N), ** ind = frag;
		if (!frag)
			continue;

		for (b = buffer, x = x1; x <= x2; x++, b += cpp, ind++)
		{
			Vector32		col = Vector32(0.0);
			const VPFragment* f;
			for (f = (*ind); f; f = f->next)
				col += f->weight * f->color;

			if (!(*ind))
				continue;		// unchanged background pixel
			col /= (Float32) 256.0;
			b[0] = col.x;
			b[1] = col.y;
			b[2] = col.z;
		}

		DeleteMem(frag);

		vps->render->IccConvert(buffer, cnt, cpp, false);
		rgba->SetLine(x1, y, cnt, buffer, 32, true);
	}
	DeleteMem(buffer);

	return RENDERRESULT_OK;
}

Bool ReconstructData::RenderEngineCheck(BaseVideoPost* node, Int32 id)
{
	// the following render engines are not supported by this effect
	if (id == RDATA_RENDERENGINE_PREVIEWSOFTWARE ||
			id == RDATA_RENDERENGINE_PREVIEWHARDWARE ||
			id == RDATA_RENDERENGINE_CINEMAN)
		return false;

	return true;
}

// be sure to use a unique ID obtained from www.plugincafe.com
#define ID_VPRECONSTRUCT 1001054

Bool RegisterVPReconstruct()
{
	return RegisterVideoPostPlugin(ID_VPRECONSTRUCT, GeLoadString(IDS_VPRECONSTRUCT), 0, ReconstructData::Alloc, "", 0, 0);
}


text:
package <%= appPackage %>.di.scope;

import java.lang.annotation.Retention;

import javax.inject.Scope;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author xiaobailong24
 * @date 2017/6/16
 * Dagger ActivityScope
 */
@Scope
@Retention(RUNTIME)
public @interface ActivityScope {
}


text:
layout: default
title: Home
---

Programming Made Dead Simple

{% include welcome_msg.html %}

  {% for post in paginator.posts %}

        {{ post.title }}

    {{ post.date | date_to_string }}
    {% if post.tldr != null %}

tl;dr - {{ post.tldr }}

    {% endif %}
    {{ post.content | strip_html | truncatewords: 50 }}

  {% endfor %}

  {% if paginator.next_page %}
    Older
  {% else %}
    Older
  {% endif %}
  {% if paginator.previous_page %}
    {% if paginator.page == 2 %}
      Newer
    {% else %}
      Newer
    {% endif %}
  {% else %}
    Newer
  {% endif %}


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>Documentation: CompHotspot.ino</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Documentation

For Arduino users

Main Page

Related Pages

Modules

Classes

Files

Examples

CompHotspot.ino

How to Use

This example shows that ,when the hot component on the Nextion screen is pressed or released, the debug serial will output the debug information every time.

Author

Wu Pengfei (email:pengf.nosp@m.ei.w.nosp@m.u@ite.nosp@m.ad.c.nosp@m.c)

Date

2015/7/10  2016/12/25 bring HMI up to v0.32 to avoid too old issues  by Patrick Martin, no other changes made

Copyright

Copyright (C) 2014-2015 ITEAD Intelligent Systems Co., Ltd.

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

Generated on Fri Jan 6 2017 14:00:35 for Documentation by

     1.8.7


text:
import OrchestraModel from 'OpenOrchestra/Application/Model/OrchestraModel'
import Fields         from 'OpenOrchestra/Application/Model/Content/Fields'
import Status         from 'OpenOrchestra/Application/Model/Status/Status'

/**
 * @class Content
 */
class Content extends OrchestraModel
{
    /**
     * Parse server response to create nested object
     * @param response
     *
     * @returns {Object}
     */
    parse(response) {
        if (response.hasOwnProperty('attributes')) {
            response.fields = new Fields(response.attributes);
        }
        if (response.hasOwnProperty('status')) {
            response.status = new Status(response.status);
        }

        return response;
    }

    /**
     * @inheritdoc
     */
    _getSyncUrl(method, options) {
        let urlParameter = options.urlParameter || {};
        switch (method) {
            case "read":
                urlParameter.contentId = this.get('id');
                return Routing.generate('open_orchestra_api_content_show', urlParameter);
            case "create":
                return this._getSyncCreateUrl(options, urlParameter);
            case "update":
                return this._getSyncUpdateUrl(options);
            case "delete":
                urlParameter.contentId = this.get('id');
                return Routing.generate('open_orchestra_api_content_delete', urlParameter);
        }
    }

    /**
     * @param {Object} options
     *
     * @returns {string}
     * @private
     */
    _getSyncUpdateUrl(options) {
        let apiContext = options.apiContext || null;
        switch (apiContext) {
            case "update_status_with_save_published":
                return Routing.generate('open_orchestra_api_content_update_status_with_save_published');
            case "update_status":
                return Routing.generate('open_orchestra_api_content_update_status');
        }
    }

    /**
     * @param {Object} options
     * @param {Object} urlParameter
     *
     * @returns {string}
     * @private
     */
    _getSyncCreateUrl(options, urlParameter) {
        let apiContext = options.apiContext || null;
        switch (apiContext) {
            case "new-version":
                return Routing.generate('open_orchestra_api_content_new_version', urlParameter);
            case "new-language":
                return Routing.generate('open_orchestra_api_content_new_language', urlParameter);
            default:
                return Routing.generate('open_orchestra_api_content_duplicate', urlParameter);
        }
    }
}

export default Content


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:background="@color/colorAccent"
    android:gravity="center"
    android:text="it is a simple dialog"
    android:textSize="18sp" />


text:
static_assert(__has_feature(objc_arc), "Djinni requires ARC to be enabled for this file");

@protocol NativeApiPostsResponse;

namespace djinni_generated {

class ApiPostsResponse
{
public:
    using CppType = std::shared_ptr<::djinni_rest_gen::ApiPostsResponse>;
    using CppOptType = std::shared_ptr<::djinni_rest_gen::ApiPostsResponse>;
    using ObjcType = id<NativeApiPostsResponse>;

    using Boxed = ApiPostsResponse;

    static CppType toCpp(ObjcType objc);
    static ObjcType fromCppOpt(const CppOptType& cpp);
    static ObjcType fromCpp(const CppType& cpp) { return fromCppOpt(cpp); }

private:
    class ObjcProxy;
};

}  // namespace djinni_generated


text:
package io.datalayer.cache.guava;

import static org.junit.Assert.fail;
import io.datalayer.cache.guava.AosGuava;

import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.cache.RemovalListener;
import com.google.common.cache.RemovalNotification;
import com.google.common.collect.Sets;

public class AosGuavaTest {
    private static final String KEY_1 = "key1";
    private static final String VALUE_1 = "value1";
    private static final String KEY_2 = "key2";
    private static final String VALUE_2 = "value2";

    private Map<String, Set<String>> cacheToEmit;
    private LoadingCache<String, Set<String>> cache;

    @Test
    public void test1() throws ExecutionException {
        AosGuava aosGuava = new AosGuava();
        try {
            aosGuava.get(KEY_1);
            fail();
        } catch (ExecutionException e) {

        }
        aosGuava.put(KEY_1, VALUE_1);
        aosGuava.get(KEY_1);
        aosGuava.put(KEY_2, VALUE_2);
        aosGuava.get(KEY_2);
    }

    @Test
    public void test2() throws InterruptedException {

        cacheToEmit = new ConcurrentHashMap<String, Set<String>>();

        cache = CacheBuilder.newBuilder() //
                .maximumSize(10) //
                .expireAfterWrite(1, TimeUnit.SECONDS) //
                .removalListener(new RemovalListener<String, Set<String>>() {

                    @Override
                    public void onRemoval(RemovalNotification<String, Set<String>> removalNotification) {

                        System.out.println("Removed key: " + removalNotification.getKey());

                    }
                }).build(new CacheLoader<String, Set<String>>() {

                    public Set<String> load(String visitorId) {

                        return Collections.synchronizedSet(new HashSet<String>());
                    }
                });

        ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();

        ScheduledFuture<Void> task = executorService.schedule(new Callable<Void>() {
            @Override
            public Void call() {
                cache.cleanUp();
                return null;
            }
        }, 1, TimeUnit.SECONDS);

        String[] keys = new String[] { "visitorId1", "visitorId2", "visitorId3" };

        Set<String> value0 = Sets.newHashSet("value0");
        cache.put(keys[0], value0);
        Set<String> pingSet0 = null;
        try {
            pingSet0 = cache.get(keys[0]);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(keys[0] + ": " + pingSet0);

        Set<String> pingSet1 = null;
        try {
            pingSet1 = cache.get(keys[1], new Callable<Set<String>>() {

                @Override
                public Set<String> call() throws Exception {

                    return Collections.synchronizedSet(new HashSet<String>());
                }
            });
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(keys[1] + ": " + pingSet1);

        Set<String> pingSet2 = null;
        try {
            pingSet2 = cache.get(keys[2], new Callable<Set<String>>() {

                @Override
                public Set<String> call() throws Exception {

                    return Collections.synchronizedSet(new HashSet<String>());
                }
            });
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        System.out.println(keys[2] + ": " + pingSet2);

        while (cache.asMap().size() > 0) {
            TimeUnit.SECONDS.sleep(1);
            cache.cleanUp();
        }

    }
}


text:
package com.stulsoft.pkafka.scala.stream

import org.apache.kafka.streams.KeyValue

/**
  * Implicit conversions that provide us with some syntactic sugar when writing stream transformations.
  *
  * @see [[https://github.com/confluentinc/examples/blob/3.2.x/kafka-streams/src/main/scala/io/confluent/examples/streams/KeyValueImplicits.scala original code]]
  * @author Yuriy Stul
  */
object KeyValueImplicits {
  implicit def Tuple2ToKeyValue[K, V](tuple: (K, V)): KeyValue[K, V] = new KeyValue(tuple._1, tuple._2)
}


text:
<?php

use Scalar\String;

class StringTest extends PHPUnit_Framework_TestCase
{

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage Scalar\String expects a string as a parameter
     */
    public function testStringWithInvalidParameter()
    {
        new String(32);
    }

    public function testString()
    {
        new String('Foo');
    }

    /**
     * @expectedException InvalidArgumentException
     * @expectedExceptionMessage Scalar\String expects a string as a parameter
     */
    public function testStringSetInvalidParameter()
    {
        $string = new String('Foo');

        $string->setValue(32);
    }

    public function testStringGetValue()
    {
        $string = new String("Foo");

        $this->assertSame("Foo", $string->getValue());
    }

    public function testStringSetNewValue()
    {
        $string = new String('Foo');

        $string->setValue('Bar');

        $this->assertSame('Bar', $string->getValue());
    }

    public function testStringCastObjectToString()
    {
        $string = new String("Foo");

        $this->assertSame("Foo", (string) $string);
    }
}


text:
typedef struct PointVertex {
    GLKVector2 p;
    GLKVector2 uv;
    float      alpha;
} PointVertex;

#endif


text:
CINDER_WAIT=20 # Seconds to wait before cleaning up Cinder (varies per provider)

microbosh_ip="$1"
primary_ip="$2"
meta_ip="$3"

if [ -z "$1" -o -z "$2" -o -z "$3" ] ; then
	echo 'usage: bbosh_cleanup.sh <microbosh-IP> <primary-IP> <meta-IP>'
	exit 1
fi

# deletes the instances and all left over BOSH files, including logs
rm -rf ~/.ssh/known_hosts bosh-deployments.yml *log ~/.bosh_*
nova delete `nova list | grep 10.10.10.10 | awk 'BEGIN{FS="|"}{print $2}'`
nova delete `nova list | grep 10.10.10.16 | awk 'BEGIN{FS="|"}{print $2}'`
nova delete `nova list | grep 10.10.10.17 | awk 'BEGIN{FS="|"}{print $2}'`

sleep $CINDER_WAIT

# Delete volumes and stemcells
for i in  `cinder list | grep available | awk 'BEGIN{FS="|"}{print $2}'`; do cinder delete $i; done
for i in  `glance image-list | grep BOSH | awk 'BEGIN{FS="|"}{print $2}'`; do glance image-delete $i; done