text:
"use strict";

// load olm before the sdk if possible
import './olm-loader';

import sdk from '..';
import testUtils from './test-utils';
import MockHttpBackend from 'matrix-mock-request';
import expect from 'expect';
import Promise from 'bluebird';
import LocalStorageCryptoStore from '../lib/crypto/store/localStorage-crypto-store';

/**
 * Wrapper for a MockStorageApi, MockHttpBackend and MatrixClient
 *
 * @constructor
 * @param {string} userId
 * @param {string} deviceId
 * @param {string} accessToken
 *
 * @param {WebStorage=} sessionStoreBackend a web storage object to use for the
 *     session store. If undefined, we will create a MockStorageApi.
 * @param {object} options additional options to pass to the client
 */
export default function TestClient(
    userId, deviceId, accessToken, sessionStoreBackend, options,
) {
    this.userId = userId;
    this.deviceId = deviceId;

    if (sessionStoreBackend === undefined) {
        sessionStoreBackend = new testUtils.MockStorageApi();
    }
    const sessionStore = new sdk.WebStorageSessionStore(sessionStoreBackend);

    this.httpBackend = new MockHttpBackend();

    options = Object.assign({
        baseUrl: "http://" + userId + ".test.server",
        userId: userId,
        accessToken: accessToken,
        deviceId: deviceId,
        sessionStore: sessionStore,
        request: this.httpBackend.requestFn,
    }, options);
    if (!options.cryptoStore) {
        // expose this so the tests can get to it
        this.cryptoStore = new LocalStorageCryptoStore(sessionStoreBackend);
        options.cryptoStore = this.cryptoStore;
    }
    this.client = sdk.createClient(options);

    this.deviceKeys = null;
    this.oneTimeKeys = {};
}

TestClient.prototype.toString = function() {
    return 'TestClient[' + this.userId + ']';
};

/**
 * start the client, and wait for it to initialise.
 *
 * @return {Promise}
 */
TestClient.prototype.start = function() {
    console.log(this + ': starting');
    this.httpBackend.when("GET", "/pushrules").respond(200, {});
    this.httpBackend.when("POST", "/filter").respond(200, { filter_id: "fid" });
    this.expectDeviceKeyUpload();

    // we let the client do a very basic initial sync, which it needs before
    // it will upload one-time keys.
    this.httpBackend.when("GET", "/sync").respond(200, { next_batch: 1 });

    this.client.startClient({
        // set this so that we can get hold of failed events
        pendingEventOrdering: 'detached',
    });

    return Promise.all([
        this.httpBackend.flushAllExpected(),
        testUtils.syncPromise(this.client),
    ]).then(() => {
        console.log(this + ': started');
    });
};

/**
 * stop the client
 * @return {Promise} Resolves once the mock http backend has finished all pending flushes
 */
TestClient.prototype.stop = function() {
    this.client.stopClient();
    return this.httpBackend.stop();
};

/**
 * Set up expectations that the client will upload device keys.
 */
TestClient.prototype.expectDeviceKeyUpload = function() {
    const self = this;
    this.httpBackend.when("POST", "/keys/upload").respond(200, function(path, content) {
        expect(content.one_time_keys).toBe(undefined);
        expect(content.device_keys).toBeTruthy();

        console.log(self + ': received device keys');
        // we expect this to happen before any one-time keys are uploaded.
        expect(Object.keys(self.oneTimeKeys).length).toEqual(0);

        self.deviceKeys = content.device_keys;
        return {one_time_key_counts: {signed_curve25519: 0}};
    });
};

/**
 * If one-time keys have already been uploaded, return them. Otherwise,
 * set up an expectation that the keys will be uploaded, and wait for
 * that to happen.
 *
 * @returns {Promise} for the one-time keys
 */
TestClient.prototype.awaitOneTimeKeyUpload = function() {
    if (Object.keys(this.oneTimeKeys).length != 0) {
        // already got one-time keys
        return Promise.resolve(this.oneTimeKeys);
    }

    this.httpBackend.when("POST", "/keys/upload")
        .respond(200, (path, content) => {
            expect(content.device_keys).toBe(undefined);
            expect(content.one_time_keys).toBe(undefined);
            return {one_time_key_counts: {
                signed_curve25519: Object.keys(this.oneTimeKeys).length,
            }};
        });

    this.httpBackend.when("POST", "/keys/upload")
          .respond(200, (path, content) => {
              expect(content.device_keys).toBe(undefined);
              expect(content.one_time_keys).toBeTruthy();
              expect(content.one_time_keys).toNotEqual({});
              console.log('%s: received %i one-time keys', this,
                          Object.keys(content.one_time_keys).length);
              this.oneTimeKeys = content.one_time_keys;
              return {one_time_key_counts: {
                  signed_curve25519: Object.keys(this.oneTimeKeys).length,
              }};
          });

    // this can take ages
    return this.httpBackend.flush('/keys/upload', 2, 1000).then((flushed) => {
        expect(flushed).toEqual(2);
        return this.oneTimeKeys;
    });
};

/**
 * Set up expectations that the client will query device keys.
 *
 * We check that the query contains each of the users in `response`.
 *
 * @param {Object} response   response to the query.
 */
TestClient.prototype.expectKeyQuery = function(response) {
    this.httpBackend.when('POST', '/keys/query').respond(
        200, (path, content) => {
            Object.keys(response.device_keys).forEach((userId) => {
                expect(content.device_keys[userId]).toEqual(
                    {},
                    "Expected key query for " + userId + ", got " +
                    Object.keys(content.device_keys),
                );
            });
            return response;
        });
};

/**
 * get the uploaded curve25519 device key
 *
 * @return {string} base64 device key
 */
TestClient.prototype.getDeviceKey = function() {
    const keyId = 'curve25519:' + this.deviceId;
    return this.deviceKeys.keys[keyId];
};

/**
 * get the uploaded ed25519 device key
 *
 * @return {string} base64 device key
 */
TestClient.prototype.getSigningKey = function() {
    const keyId = 'ed25519:' + this.deviceId;
    return this.deviceKeys.keys[keyId];
};

/**
 * flush a single /sync request, and wait for the syncing event
 *
 * @returns {Promise} promise which completes once the sync has been flushed
 */
TestClient.prototype.flushSync = function() {
    console.log(`${this}: flushSync`);
    return Promise.all([
        this.httpBackend.flush('/sync', 1),
        testUtils.syncPromise(this.client),
    ]).then(() => {
        console.log(`${this}: flushSync completed`);
    });
};


text:
Given an array of *n* positive integers and a positive integer *s*, find the minimal length of a subarray of which the sum ≥ *s*. If there isn't one, return 0 instead.

For example, given the array `[2,3,1,2,4,3]` and `s = 7`,

the subarray `[4,3]` has the minimal length under the problem constraint.

**More practice:**

If you have figured out the O(*n*) solution, try coding another solution of which the time complexity is O(*n* log *n*).

redpajama_set_name: RedPajamaGithub


text:
SVGLayout creates an overlay which maps SVG rectangles to HTML elements, providing a drag and drop positioning mechanism right in the browser.  Visual front to back (z-index) positioning and a new architecture for managing resizing events is also included.

Visit the library website for more information: [http://www.svglayout.com](http://www.svglayout.com/)

## Copyright and license

Copyright (c) 2014 Thomas DeMeo
Copyright (c) 2014 Waltham Software Corp. All rights reserved.
Licensed under the MIT (http://www.svglayout.com/mit_license/index.html) license.


text:
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Net;
using System.Configuration;
using Alachisoft.NCache.Config;
using Alachisoft.NCache.Caching;
using Alachisoft.NCache.Runtime.Exceptions;
using Alachisoft.NCache.Common.Util;

namespace Alachisoft.NCache.Config
{
	/// <summary>
	///
	/// </summary>
	internal class ChannelConfigBuilder
	{

		/// <summary>
		///
		/// </summary>
		/// <param name="properties"></param>
		/// <returns></returns>
		public static string BuildTCPConfiguration(IDictionary properties,long opTimeout)
		{
			StringBuilder b = new StringBuilder(2048);
			b.Append(BuildTCP(properties["tcp"] as IDictionary)).Append(":");
			b.Append(BuildTCPPING(properties["tcpping"] as IDictionary)).Append(":");
            b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":");
			b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,false)).Append(":");
			b.Append(BuildTOTAL(properties["total"] as IDictionary,opTimeout)).Append(":");
			b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary));
			return b.ToString();
		}

		public static string BuildTCPConfiguration(IDictionary properties,long opTimeout,bool isPor)
		{
			StringBuilder b = new StringBuilder(2048);
			b.Append(BuildTCP(properties["tcp"] as IDictionary)).Append(":");
            b.Append(BuildTCPPING(properties["tcpping"] as IDictionary)).Append(":");
            b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":");
            b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,isPor)).Append(":");
            b.Append(BuildTOTAL(properties["total"] as IDictionary, opTimeout)).Append(":");
            b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary));

			return b.ToString();
		}

		/// <summary>
		///
		/// </summary>
		/// <param name="properties"></param>
		/// <returns></returns>
		public static string BuildUDPConfiguration(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(2048);
			b.Append(BuildUDP(properties["udp"] as IDictionary)).Append(":");
			b.Append(BuildPING(properties["ping"] as IDictionary)).Append(":");
			b.Append(BuildMERGEFAST(properties["mergefast"] as IDictionary)).Append(":");
			b.Append(BuildFD_SOCK(properties["fd-sock"] as IDictionary)).Append(":");
			b.Append(BuildVERIFY_SUSPECT(properties["verify-suspect"] as IDictionary)).Append(":");
			b.Append(BuildFRAG(properties["frag"] as IDictionary)).Append(":");
			b.Append(BuildUNICAST(properties["unicast"] as IDictionary)).Append(":");
			b.Append(BuildQueue(properties["queue"] as IDictionary)).Append(":");
			b.Append(Buildpbcast_NAKACK(properties["pbcast.nakack"] as IDictionary)).Append(":");
			b.Append(Buildpbcast_STABLE(properties["pbcast.stable"] as IDictionary)).Append(":");
			b.Append(Buildpbcast_GMS(properties["pbcast.gms"] as IDictionary,false)).Append(":");
			b.Append(BuildTOTAL(properties["total"] as IDictionary,5000)).Append(":");
			b.Append(BuildVIEW_ENFORCER(properties["view-enforcer"] as IDictionary));
			return b.ToString();
		}

		private static string BuildUDP(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(256);
			b.Append("UDP(")
				.Append(ConfigHelper.SafeGetPair(properties,"mcast_addr", "239.0.1.10"))
				.Append(ConfigHelper.SafeGetPair(properties,"mcast_port", 10001))
				.Append(ConfigHelper.SafeGetPair(properties,"bind_addr", null))
				.Append(ConfigHelper.SafeGetPair(properties,"bind_port", null))
				.Append(ConfigHelper.SafeGetPair(properties,"port_range", 256))
				.Append(ConfigHelper.SafeGetPair(properties,"ip_mcast", null))				//"false"
				.Append(ConfigHelper.SafeGetPair(properties,"mcast_send_buf_size", null))	//32000
				.Append(ConfigHelper.SafeGetPair(properties,"mcast_recv_buf_size", null))	//64000
				.Append(ConfigHelper.SafeGetPair(properties,"ucast_send_buf_size", null))	//32000
				.Append(ConfigHelper.SafeGetPair(properties,"ucast_recv_buf_size", null))	//64000
				.Append(ConfigHelper.SafeGetPair(properties,"max_bundle_size", null))		//32000
				.Append(ConfigHelper.SafeGetPair(properties,"max_bundle_timeout", null))	//20
				.Append(ConfigHelper.SafeGetPair(properties,"enable_bundling", null))		//"false"
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"use_incoming_packet_handler", null))
				.Append(ConfigHelper.SafeGetPair(properties,"use_outgoing_packet_handler", null))
				.Append("ip_ttl=32;")
				.Append(")");
			return b.ToString();
		}
		private static string BuildPING(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(256);
			b.Append("PING(")
				.Append(ConfigHelper.SafeGetPair(properties,"timeout", null))				//2000
				.Append(ConfigHelper.SafeGetPair(properties,"num_initial_members", null))	//2
				.Append(ConfigHelper.SafeGetPair(properties,"port_range", null))			//1
				.Append(ConfigHelper.SafeGetPair(properties,"initial_hosts", null))
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string BuildMERGEFAST(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(16);
			b.Append("MERGEFAST(")
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string BuildFD_SOCK(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(64);
			b.Append("FD_SOCK(")
				.Append(ConfigHelper.SafeGetPair(properties,"get_cache_timeout", null))		//3000
				.Append(ConfigHelper.SafeGetPair(properties,"start_port", null))			//49152
				.Append(ConfigHelper.SafeGetPair(properties,"num_tries", null))				//3
				.Append(ConfigHelper.SafeGetPair(properties,"suspect_msg_interval", null))	//5000
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string BuildVERIFY_SUSPECT(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(32);
			b.Append("VERIFY_SUSPECT(")
				.Append(ConfigHelper.SafeGetPair(properties,"timeout", 1500))
				.Append(ConfigHelper.SafeGetPair(properties,"num_msgs", null))			// null
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}
		private static string BuildQueue(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(32);
			b.Append("QUEUE(")
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string Buildpbcast_NAKACK(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(128);
			b.Append("pbcast.NAKACK(")
				.Append(ConfigHelper.SafeGetPair(properties,"retransmit_timeout", null))		//"600,1200,2400,4800"
				.Append(ConfigHelper.SafeGetPair(properties,"gc_lag", 40))
				.Append(ConfigHelper.SafeGetPair(properties,"max_xmit_size", null))				// 8192
				.Append(ConfigHelper.SafeGetPair(properties,"use_mcast_xmit", null))			// "false"
				.Append(ConfigHelper.SafeGetPair(properties,"discard_delivered_msgs", null))	// "true"
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string BuildUNICAST(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(64);
			b.Append("UNICAST(")
				.Append(ConfigHelper.SafeGetPair(properties,"timeout", null))		// "800,1600,3200,6400"
				.Append(ConfigHelper.SafeGetPair(properties,"window_size", null))	// -1
				.Append(ConfigHelper.SafeGetPair(properties,"min_threshold", null))	// -1
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string Buildpbcast_STABLE(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(256);
			b.Append("pbcast.STABLE(")
				.Append(ConfigHelper.SafeGetPair(properties,"digest_timeout", null))		// 60000
				.Append(ConfigHelper.SafeGetPair(properties,"desired_avg_gossip", null))	// 20000
				.Append(ConfigHelper.SafeGetPair(properties,"stability_delay", null))		// 6000
				.Append(ConfigHelper.SafeGetPair(properties,"max_gossip_runs", null))		// 3
				.Append(ConfigHelper.SafeGetPair(properties,"max_bytes", null))				// 0
				.Append(ConfigHelper.SafeGetPair(properties,"max_suspend_time", null))		// 600000
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string BuildFRAG(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(32);
			b.Append("FRAG(")
				.Append(ConfigHelper.SafeGetPair(properties,"frag_size", null))
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string Buildpbcast_GMS(IDictionary properties,bool isPor)
		{
			StringBuilder b = new StringBuilder(256);
            if (isPor)
            {
                if (properties == null) properties = new Hashtable();
                properties["is_part_replica"]= "true";
            }
			b.Append("pbcast.GMS(")
				.Append(ConfigHelper.SafeGetPair(properties,"shun", null))					// "true"
				.Append(ConfigHelper.SafeGetPair(properties,"join_timeout", null))			// 5000
				.Append(ConfigHelper.SafeGetPair(properties,"join_retry_timeout", null))	// 2000
                .Append(ConfigHelper.SafeGetPair(properties, "join_retry_count", null))	    // 3
				.Append(ConfigHelper.SafeGetPair(properties,"leave_timeout", null))			// 5000
				.Append(ConfigHelper.SafeGetPair(properties,"merge_timeout", null))			// 10000
				.Append(ConfigHelper.SafeGetPair(properties,"digest_timeout", null))		// 5000
				.Append(ConfigHelper.SafeGetPair(properties,"disable_initial_coord", null))	// false
				.Append(ConfigHelper.SafeGetPair(properties,"num_prev_mbrs", null))			// 50
				.Append(ConfigHelper.SafeGetPair(properties,"print_local_addr", null))		// false
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
                .Append(ConfigHelper.SafeGetPair(properties, "is_part_replica", null))

                .Append(")");
			return b.ToString();
		}

		private static string BuildTOTAL(IDictionary properties,long opTimeout)
		{
			StringBuilder b = new StringBuilder(8);
			b.Append("TOTAL(")
				.Append(ConfigHelper.SafeGetPair(properties,"timeout", null))				//"600,1200,2400,4800"
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
                .Append(ConfigHelper.SafeGetPair(properties, "op_timeout", opTimeout))
				.Append(")");
			return b.ToString();
		}

		private static string BuildVIEW_ENFORCER(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(16);
			b.Append("VIEW_ENFORCER(")
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");
			return b.ToString();
		}

		private static string BuildTCPPING(IDictionary properties)
		{
			StringBuilder b = new StringBuilder(256);
			b.Append("TCPPING(")
				.Append(ConfigHelper.SafeGetPair(properties,"timeout", null))				//3000
                .Append(ConfigHelper.SafeGetPair(properties,"port_range", null))			//5
				.Append(ConfigHelper.SafeGetPair(properties,"static", null))				//false
				.Append(ConfigHelper.SafeGetPair(properties,"num_initial_members", null))	//2
				.Append(ConfigHelper.SafeGetPair(properties,"initial_hosts", null))
				.Append(ConfigHelper.SafeGetPair(properties,"discovery_addr", "228.8.8.8"))		//228.8.8.8
				.Append(ConfigHelper.SafeGetPair(properties,"discovery_port", 7700))			//7700
				.Append(ConfigHelper.SafeGetPair(properties,"down_thread", null))
				.Append(ConfigHelper.SafeGetPair(properties,"up_thread", null))
				.Append(")");

			return b.ToString();
		}

		private static string BuildTCP(IDictionary properties)
		{

            string bindIP = ServiceConfiguration.BindToIP.ToString();

            StringBuilder b = new StringBuilder(256);
            b.Append("TCP(")
                .Append(ConfigHelper.SafeGetPair(properties, "connection_retries", 0))
                .Append(ConfigHelper.SafeGetPair(properties, "connection_retry_interval", 0))
                .Append(ConfigHelper.SafeGetPair(properties, "bind_addr", bindIP))
				.Append(ConfigHelper.SafeGetPair(properties, "start_port", null))
                .Append(ConfigHelper.SafeGetPair(properties, "port_range", null))
                .Append(ConfigHelper.SafeGetPair(properties, "send_buf_size", null))				//32000
				.Append(ConfigHelper.SafeGetPair(properties, "recv_buf_size", null))				//64000
				.Append(ConfigHelper.SafeGetPair(properties, "reaper_interval", null))			//0
				.Append(ConfigHelper.SafeGetPair(properties, "conn_expire_time", null))			//0
				.Append(ConfigHelper.SafeGetPair(properties, "skip_suspected_members", null))	//true
				.Append(ConfigHelper.SafeGetPair(properties, "down_thread", true))
				.Append(ConfigHelper.SafeGetPair(properties, "up_thread", true))
				.Append(")");
			return b.ToString();
		}
	}
}


text:
package net.sandius.rembulan.test.fragments

import net.sandius.rembulan.test.FragmentExecTestSuite
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner

@RunWith(classOf[JUnitRunner])
class BasicLibFragmentsRunSpec extends FragmentExecTestSuite {

  override def bundles = Seq(BasicLibFragments)
  override def expectations = Seq(BasicLibFragments)
  override def contexts = Seq(Basic)

  override def steps = Seq(1, Int.MaxValue)

}


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.compiler.notNullVerification;

import com.intellij.JavaTestUtil;
import com.intellij.codeInsight.AnnotationUtil;
import com.intellij.compiler.instrumentation.FailSafeClassReader;
import com.intellij.compiler.instrumentation.InstrumenterClassWriter;
import com.intellij.compiler.notNullVerification.NotNullVerifyingInstrumenter;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.util.io.IoTestUtil;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.testFramework.IdeaTestUtil;
import com.intellij.testFramework.PlatformTestUtil;
import com.intellij.testFramework.rules.TempDirectory;
import com.intellij.util.ArrayUtil;
import com.intellij.util.ExceptionUtil;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.org.objectweb.asm.ClassWriter;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExternalResource;
import org.junit.rules.TestName;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

import static com.intellij.testFramework.UsefulTestCase.assertInstanceOf;
import static org.junit.Assert.*;

/**
 * @author yole
 */
public abstract class NotNullVerifyingInstrumenterTest {
  @Retention(RetentionPolicy.RUNTIME)
  private @interface TestDirectory { String value(); }

  @TestDirectory("members")
  public static class MembersTargetTest extends NotNullVerifyingInstrumenterTest { }

  @TestDirectory("types")
  public static class TypesTargetTest extends WithTypeUse { }

  @TestDirectory("mixed")
  public static class MixedTargetTest extends WithTypeUse { }

  private static final String TEST_DATA_PATH = "/compiler/notNullVerification/";

  private static class AnnotationCompiler extends ExternalResource {
    File classes;

    @Override
    public Statement apply(Statement base, Description description) {
      TestDirectory annotation = description.getAnnotation(TestDirectory.class);
      if (annotation == null) throw new IllegalArgumentException("Class " + description.getTestClass() + " misses @TestDirectory annotation");
      File source = new File(JavaTestUtil.getJavaTestDataPath() + TEST_DATA_PATH + annotation.value());
      File[] annotations = source.listFiles();
      if (annotations == null || annotations.length == 0) throw new IllegalArgumentException("Cannot find annotations at " + source);
      classes = IoTestUtil.createTestDir("test-notNullInstrumenter-" + annotation.value());
      for (File file : annotations) IdeaTestUtil.compileFile(file, classes);
      return super.apply(base, description);
    }

    @Override
    protected void after() {
      IoTestUtil.delete(classes);
    }
  }

  @ClassRule public static final AnnotationCompiler annotation = new AnnotationCompiler();

  @Rule public TempDirectory tempDir = new TempDirectory();
  @Rule public TestName testName = new TestName();

  @Test
  public void testSimpleReturn() throws Exception {
    Class<?> testClass = prepareTest();
    Object instance = testClass.newInstance();
    Method method = testClass.getMethod("test");
    verifyCallThrowsException("@NotNull method SimpleReturn.test must not return null", instance, method);
  }

  @Test
  public void testSimpleReturnWithMessage() throws Exception {
    Class<?> testClass = prepareTest();
    Object instance = testClass.newInstance();
    Method method = testClass.getMethod("test");
    verifyCallThrowsException("This method cannot return null", instance, method);
  }

  @Test
  public void testMultipleReturns() throws Exception {
    Class<?> testClass = prepareTest();
    Object instance = testClass.newInstance();
    Method method = testClass.getMethod("test", int.class);
    verifyCallThrowsException("@NotNull method MultipleReturns.test must not return null", instance, method, 1);
  }

  @Test
  public void testSimpleParam() throws Exception {
    Class<?> testClass = prepareTest();
    Object instance = testClass.newInstance();
    Method method = testClass.getMethod("test", Object.class);
    verifyCallThrowsException("Argument 0 for @NotNull parameter of SimpleParam.test must not be null", instance, method, (Object)null);
  }

  @Test
  public void testSimpleParamWithMessage() throws Exception {
    Class<?> testClass = prepareTest();
    Object instance = testClass.newInstance();
    Method method = testClass.getMethod("test", Object.class);
    verifyCallThrowsException("SimpleParamWithMessage.test(o) cant be null", instance, method, (Object)null);
  }

  @Test
  public void testConstructorParam() throws Exception {
    Class<?> testClass = prepareTest();
    Constructor<?> method = testClass.getConstructor(Object.class);
    verifyCallThrowsException("Argument 0 for @NotNull parameter of ConstructorParam.<init> must not be null", null, method, (Object)null);
  }

  @Test
  public void testConstructorParamWithMessage() throws Exception {
    Class<?> testClass = prepareTest();
    Constructor<?> method = testClass.getConstructor(Object.class);
    verifyCallThrowsException("ConstructorParam.ConstructorParam.o cant be null", null, method, (Object)null);
  }

  @Test
  public void testUseParameterNames() throws Exception {
    Class<?> testClass = prepareTest(true, AnnotationUtil.NOT_NULL);
    Constructor<?> constructor = testClass.getConstructor(Object.class, Object.class);
    verifyCallThrowsException("Argument for @NotNull parameter 'obj2' of UseParameterNames.<init> must not be null",
                              null, constructor, null, null);

    Method staticMethod = testClass.getMethod("staticMethod", Object.class);
    verifyCallThrowsException("Argument for @NotNull parameter 'y' of UseParameterNames.staticMethod must not be null",
                              null, staticMethod, (Object)null);

    Object instance = constructor.newInstance("", "");
    Method instanceMethod = testClass.getMethod("instanceMethod", Object.class);
    verifyCallThrowsException("Argument for @NotNull parameter 'x' of UseParameterNames.instanceMethod must not be null",
                              instance, instanceMethod, (Object)null);
  }

  @Test
  public void testLongParameter() throws Exception {
    Class<?> testClass = prepareTest(true, AnnotationUtil.NOT_NULL);
    Method staticMethod = testClass.getMethod("foo", long.class, String.class, String.class);
    verifyCallThrowsException("Argument for @NotNull parameter 'c' of LongParameter.foo must not be null",
                              null, staticMethod, new Long(2), "z", null);
  }

  @Test
  public void testDoubleParameter() throws Exception {
    Class<?> testClass = prepareTest(true, AnnotationUtil.NOT_NULL);
    Method staticMethod = testClass.getMethod("foo", double.class, String.class, String.class);
    verifyCallThrowsException("Argument for @NotNull parameter 'c' of DoubleParameter.foo must not be null",
                              null, staticMethod, new Long(2), "z", null);
  }

  @Test
  public void testEnumConstructor() throws Exception {
    Class<?> testClass = prepareTest();
    assertNotNull(testClass.getField("Value").get(null));
  }

  @Test
  public void testCustomExceptionType() throws Exception {
    Class<?> testClass = prepareTest();
    try {
      testClass.getMethod("foo", Object.class, Object.class).invoke(testClass.newInstance(), null, null);
      fail();
    }
    catch (InvocationTargetException e) {
      assertInstanceOf(e.getCause(), NullPointerException.class);
      assertEquals("Argument 1 for @NotNull parameter of CustomExceptionType.foo must not be null", e.getCause().getMessage());
    }
  }

  @Test
  public void testEnumConstructorSecondParam() throws Exception {
    Class<?> testClass = prepareTest();
    assertNotNull(testClass.getField("Value").get(null));
  }

  @Test
  public void testGroovyEnum() throws Exception {
    Class<?> testClass = prepareTest();
    assertNotNull(testClass.getField("Value").get(null));
  }

  @Test
  public void testStaticInnerClass() throws Exception {
    Class<?> aClass = prepareTest();
    assertNotNull(aClass.newInstance());
  }

  @Test
  public void testNonStaticInnerClass() throws Exception {
    Class<?> testClass = prepareTest();
    assertNotNull(testClass.newInstance());
    verifyCallThrowsException(
      "Argument 1 for @NotNull parameter of NonStaticInnerClass$Inner.<init> must not be null", null, testClass.getMethod("fail"));
  }

  @Test
  public void testGroovyInnerClass() throws Exception {
    Class<?> testClass = prepareTest();
    assertNotNull(testClass.newInstance());
    verifyCallThrowsException(
      "Argument for @NotNull parameter 's2' of GroovyInnerClass$Inner.<init> must not be null", null, testClass.getMethod("fail"));
  }

  @Test
  public void testSkipBridgeMethods() throws Exception {
    Class<?> testClass = prepareTest();
    try {
      testClass.getMethod("main").invoke(null);
      fail();
    }
    catch (InvocationTargetException e) {
      assertInstanceOf(e.getCause(), IllegalArgumentException.class);
      String trace = ExceptionUtil.getThrowableText(e.getCause());
      assertEquals("Exception should happen in real, non-bridge method: " + trace,
                   2, StringUtil.getOccurrenceCount(trace, "B.getObject(SkipBridgeMethods"));
    }
  }

  @Test
  public void testMultipleMessages() throws Exception {
    Class<?> test = prepareTest();
    Object instance = test.newInstance();
    verifyCallThrowsException("Argument 0 for @NotNull parameter of MultipleMessages.bar1 must not be null",
                              instance, test.getMethod("bar1", Object.class), (Object)null);
    verifyCallThrowsException("Argument 0 for @NotNull parameter of MultipleMessages.bar2 must not be null",
                              instance, test.getMethod("bar2", Object.class), (Object)null);
    verifyCallThrowsException("@NotNull method MultipleMessages.foo1 must not return null", instance, test.getMethod("foo1"));
    verifyCallThrowsException("@NotNull method MultipleMessages.foo2 must not return null", instance, test.getMethod("foo2"));
  }

  @Test
  public void testMultipleAnnotations() throws Exception {
    Class<?> test = prepareTest(false, "FooAnno", "BarAnno");
    Object instance = test.newInstance();
    verifyCallThrowsException("@FooAnno method MultipleAnnotations.foo1 must not return null", instance, test.getMethod("foo1"));
    verifyCallThrowsException("@BarAnno method MultipleAnnotations.foo2 must not return null", instance, test.getMethod("foo2"));
  }

  @Test
  public void testTypeUseOnlyAnnotations() throws Exception {
    Class<?> test = prepareTest(false, "FooAnno");
    Object instance = test.newInstance();
    verifyCallThrowsException("@FooAnno method TypeUseOnlyAnnotations.foo1 must not return null", instance, test.getMethod("foo1"));
    verifyCallThrowsException("Argument 0 for @FooAnno parameter of TypeUseOnlyAnnotations.foo2 must not be null",
                              instance, test.getMethod("foo2", String.class), (String)null);
    test.getMethod("foo3", List.class).invoke(instance, new Object[]{null});
  }

  @Test
  public void testTypeUseInEnumConstructor() throws Exception {
    Class<?> test = prepareTest(false, "TypeUseNotNull");
    assertEquals(1, test.getEnumConstants().length);
  }

  @Test
  public void testTypeUseAndMemberAnnotations() throws Exception {
    Class<?> test = prepareTest(false, "FooAnno");
    Object instance = test.newInstance();
    verifyCallThrowsException("@FooAnno method TypeUseAndMemberAnnotations.foo1 must not return null", instance, test.getMethod("foo1"));
    verifyCallThrowsException("Argument 0 for @FooAnno parameter of TypeUseAndMemberAnnotations.foo2 must not be null",
                              instance, test.getMethod("foo2", String.class), (String)null);

    Method returnType = test.getMethod("returnType");
    verifyCallThrowsException("@FooAnno method TypeUseAndMemberAnnotations.returnType must not return null", instance, returnType);

    assertEquals(1, returnType.getAnnotations().length);
    assertEquals(1, returnType.getAnnotatedReturnType().getAnnotations().length);
  }

  public static abstract class WithTypeUse extends NotNullVerifyingInstrumenterTest {
    @Test
    public void testTypeUseAndMemberAnnotationsOnArrays() throws Exception {
      Class<?> test = prepareTest();
      Object instance = test.newInstance();

      Object[] singleNullArg = {null};
      verifyCallThrowsException("Argument 0 for @NotNull parameter of TypeUseAndMemberAnnotationsOnArrays.notNullArray must not be null",
                                instance, test.getMethod("notNullArray", String[].class), singleNullArg);
      test.getMethod("nullableArray", String[].class).invoke(instance, singleNullArg);

      verifyCallThrowsException("@NotNull method TypeUseAndMemberAnnotationsOnArrays.notNullReturn must not return null",
                                instance, test.getMethod("notNullReturn"));
      assertNull(test.getMethod("nullableReturn").invoke(instance));
    }
  }

  @Test
  public void testMalformedBytecode() throws Exception {
    Class<?> testClass = prepareTest();
    verifyCallThrowsException("Argument 0 for @NotNull parameter of MalformedBytecode$NullTest2.handle must not be null",
                              null, testClass.getMethod("main"));
  }

  @Test
  public void testEnclosingClass() throws Exception {
    Class<?> testClass = prepareTest();
    Object obj1 = testClass.getMethod("fromStatic").invoke(null);
    assertEquals(testClass, obj1.getClass().getEnclosingClass());
    Object obj2 = testClass.getMethod("fromInstance").invoke(testClass.newInstance());
    assertEquals(testClass, obj2.getClass().getEnclosingClass());
  }

  @Test
  public void testLocalClassImplicitParameters() throws Exception {
    Class<?> test = prepareTest(true, "NotNull");
    Object instance = test.newInstance();
    assertEquals(42, test.getMethod("ok").invoke(instance));
    verifyCallThrowsException("Argument for @NotNull parameter 'test' of LocalClassImplicitParameters$1Test.<init> must not be null",
                              instance, test.getMethod("failLocal"));
    verifyCallThrowsException("Argument for @NotNull parameter 'test' of LocalClassImplicitParameters$1Test2.<init> must not be null",
                              instance, test.getMethod("failLocal2NotNull"));
    verifyCallThrowsException("Argument for @NotNull parameter 'another' of LocalClassImplicitParameters$1Test3.<init> must not be null",
                              instance, test.getMethod("failLocalNullableNotNull"));
    verifyCallThrowsException("Argument for @NotNull parameter 'test' of LocalClassImplicitParameters$1.method must not be null",
                              instance, test.getMethod("failAnonymous"));
    verifyCallThrowsException("Argument for @NotNull parameter 'param' of LocalClassImplicitParameters$Inner.<init> must not be null",
                              instance, test.getMethod("failInner"));
  }

  @Test
  public void testNoCheckForConstant() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForNewObject() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForNewConstructorCall() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForNewArray() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForNewMultiArray() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForPrivateNotNullMethodCall() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForFinalNotNullMethodCall() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testNoCheckForStaticNotNullMethodCall() throws Exception {
    verifyNotInstrumented();
  }

  @Test
  public void testInterfaceStaticMethodParameter() throws Exception {
    Class<?> testClass = prepareTest();
    Method method = testClass.getMethod("test");
    verifyCallThrowsException("Argument 0 for @NotNull parameter of I.test must not be null", null, method);
  }

  @Test
  public void testInterfaceDefaultMethodParameter() throws Exception {
    Class<?> testClass = prepareTest();
    Method method = testClass.getMethod("test");
    verifyCallThrowsException("Argument 0 for @NotNull parameter of I.test must not be null", null, method);
  }

  protected static void verifyCallThrowsException(String expectedError, @Nullable Object instance, Member member, Object... args) throws Exception {
    String exceptionText = null;
    try {
      if (member instanceof Constructor) {
        ((Constructor<?>)member).newInstance(args);
      }
      else {
        ((Method)member).invoke(instance, args);
      }
    }
    catch (InvocationTargetException ex) {
      Throwable cause = ex.getCause();
      if (cause instanceof IllegalStateException || cause instanceof IllegalArgumentException) {
        exceptionText = cause.getMessage();
      }
      else {
        throw ex;
      }
    }
    assertEquals(expectedError, exceptionText);
  }

  protected Class<?> prepareTest() throws IOException {
    return prepareTest(false, AnnotationUtil.NOT_NULL);
  }

  protected Class<?> prepareTest(boolean withDebugInfo, String... notNullAnnotations) throws IOException {
    return prepareTest(withDebugInfo, true, notNullAnnotations);
  }

  protected void verifyNotInstrumented() throws IOException {
    prepareTest(false, false, AnnotationUtil.NOT_NULL);
  }

  protected Class<?> prepareTest(boolean withDebugInfo, boolean expectInstrumented, String... notNullAnnotations) throws IOException {
    String testName = PlatformTestUtil.getTestName(this.testName.getMethodName(), false);
    File testFile = IdeaTestUtil.findSourceFile((JavaTestUtil.getJavaTestDataPath() + TEST_DATA_PATH) + testName);
    File classesDir = tempDir.newFolder("output");
    List<String> args = ContainerUtil.newArrayList("-cp", annotation.classes.getPath());
    if (withDebugInfo) args.add("-g");
    IdeaTestUtil.compileFile(testFile, classesDir, ArrayUtil.toStringArray(args));

    File[] files = classesDir.listFiles();
    assertNotNull(files);
    Arrays.sort(files, (o1, o2) -> o1.getName().compareToIgnoreCase(o2.getName()));
    boolean modified = false;
    MyClassLoader classLoader = new MyClassLoader(getClass().getClassLoader());
    Class<?> mainClass = null;
    for (File file: files) {
      FailSafeClassReader reader = new FailSafeClassReader(FileUtil.loadFileBytes(file));
      int flags = InstrumenterClassWriter.getAsmClassWriterFlags(InstrumenterClassWriter.getClassFileVersion(reader));
      ClassWriter writer = new ClassWriter(reader, flags);
      modified |= NotNullVerifyingInstrumenter.processClassFile(reader, writer, notNullAnnotations);
      String className = FileUtil.getNameWithoutExtension(file.getName());
      Class<?> aClass = classLoader.doDefineClass(className, writer.toByteArray());
      if (className.equals(testName)) {
        mainClass = aClass;
      }
    }
    if (expectInstrumented) {
      assertTrue("Class file not instrumented!", modified);
    }
    else {
      assertFalse("Class file instrumented, but should have not!", modified);
    }
    assertNotNull("Class " + testName + " not found!", mainClass);
    return mainClass;
  }

  private static class MyClassLoader extends ClassLoader {
    MyClassLoader(ClassLoader parent) {
      super(parent);
    }

    public Class<?> doDefineClass(String name, byte[] data) {
      return defineClass(name, data, 0, data.length);
    }
  }
}


text:
module.exports = function(){

  // lets do some fun
  var video = document.getElementById('webcam');
  var canvas = document.getElementById('canvas');
  try {
    var attempts = 0;
    var readyListener = function (event) {
      findVideoSize();
    };
    var findVideoSize = function () {
      if (video.videoWidth > 0 && video.videoHeight > 0) {
        video.removeEventListener('loadeddata', readyListener);
        // onDimensionsReady(video.videoWidth, video.videoHeight);
      } else {
        if (attempts < 10) {
          attempts++;
          setTimeout(findVideoSize, 200);
        } else {
          // onDimensionsReady(640, 480);
        }
      }
    };
    // var onDimensionsReady = function(width, height) {
    //   // demo_app(width, height);
    //   // compatibility.requestAnimationFrame(tick);
    // };

    video.addEventListener('loadeddata', readyListener);

    compatibility.getUserMedia({
      video: true
    }, function (stream) {

      try {
        video.src = compatibility.URL.createObjectURL(stream);
      } catch (error) {
        video.src = stream;
      }

      setTimeout(function () {
        video.play();
      }, 500);

    }, function (error) {
      console.log(error)
    });
  } catch (error) {
    console.log(error)
  }

}


text:
<?php

function endsWith($haystack, $needle)
{
    $length = strlen($needle);
    if ($length == 0) {
        return true;
    }

    return (substr($haystack, -$length) === $needle);
}

$directory = '../objects/';

if(! is_dir($directory))
{
    exit('invalid directory');
}

$objects = array();

//iterate through objects in folder

$files = scandir($directory);

for($i = 0; $i < count($files); $i++)
{
    $objectFile = $directory . $files[$i];

    if($objectFile === '.' || $objectFile === '..' || !endsWith($objectFile, '.json'))
        continue;

    $fileHandle = fopen($objectFile, 'r');

    $objects[] = json_decode(fread($fileHandle, filesize($objectFile)));

    fclose($fileHandle);
}

echo json_encode($objects);

?>


text:
\documentclass[a4paper, 12pt]{article}
\usepackage[slovene]{babel}
\usepackage[utf8]{inputenc}
\usepackage{minted}
\usepackage{nameref}
\usepackage[backend=bibtex]{biblatex}
\usepackage{graphicx}

\graphicspath{{images/}}

\addbibresource{latex/viri.bib}

\begin{document}

    \begin{titlepage}
    	\centering
    	\includegraphics[width=0.3\textwidth]{gimvic_logo.png}\par
    	{\Large Gimnazija vič \par}
    	\vspace{1cm}
        {\huge\bfseries Programiranje v Pythonu\par}
    	\vspace{0.5cm}
        {\scshape\Large Seminarska naloga pri predmetu informatika\par}
    	\vspace{2cm}
        {\Large Mentor: prof. Klemen Bajec\par}
    	{\Large Avtor: Matej Marinko\par}
    	\vfill

    	{\large Ljubljana, marec 2017\par}
    \end{titlepage}

    \thispagestyle{empty}
    \newpage

    \begin{abstract}
    \noindent Namen naloge je izdelati program za steganografijo digitalnih fotografij. V prvem delu seminarske naloge je razloženo, kaj je steganografija in predstavljeni so njeni primeri skozi čas. V nadaljevanju je še ostala teorija, ki je pomembna za razumevanje in izdelavo programa. To so osnove zapisa sliku v računalniku, osnove simetrične enkripcije in nekaj o programskem jeziku Python. Sledi praktični del naloge. Ker je celoten program razmeroma obsežen ter zato ni primerno, da bi bil natančno predstavljen v celoti, so podrobneje razloženi samo nekateri njegovi pomembnejši deli. Namen seminarske naloge je bil dosežen, saj je bil napisan program za steganografijo slik, ki zadovoljivo deluje.
    \\

    \noindent \textbf{Ključne besede:} steganografija, kriptografija, programski jezik Python
    \end{abstract}

    \newpage

    \tableofcontents
    \newpage

    \section{Uvod}
        \input{latex/uvod.tex}

    \newpage

    \section{Steganografija}
        \input{latex/steganografija.tex}

    \section{Zapis slik v računalniku}
        \input{latex/zapis_slik.tex}

    \section{AES kriptiranje}
        \input{latex/aes.tex}

    \section{Python}
        \input{latex/python.tex}

    \section{Izdelava programa}
        \input{latex/programiranje.tex}

    \newpage
    \section{Zaključek}
        \input{latex/zakljucek.tex}

    \newpage
    \printbibliography

\end{document}


text:
package de.flapdoodle.embed.process.runtime;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ThreadLocalRandom;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 */
public class Network {

	private static final Logger logger = LoggerFactory.getLogger(Network.class);

	private static final String NO_LOCALHOST_ERROR_MESSAGE = "We could not detect if localhost is IPv4 or IPv6. " +
			"Sometimes there is no entry for localhost. " +
			"If 'ping localhost' does not work, it could help to add the right entry in your hosts configuration file.";
	private static final int IPV4_LENGTH = 4;

	private Network() {
		throw new IllegalAccessError("singleton");
	}

	public static boolean localhostIsIPv6() throws UnknownHostException {
		try {
			InetAddress addr = getLocalHost();
			byte[] ipAddr = addr.getAddress();
			return ipAddr.length > IPV4_LENGTH;
		} catch (UnknownHostException ux) {
			logger.error(NO_LOCALHOST_ERROR_MESSAGE, ux);
			throw ux;
		}
	}

	public static InetAddress getLocalHost() throws UnknownHostException {
		InetAddress ret = InetAddress.getLocalHost();
		// see https://www.linuxtopia.org/online_books/linux_system_administration/debian_linux_guides/debian_linux_reference_guide/ch-gateway.en_009.html
		// call to getLocalHost() can give 127.0.1.1 which is not the same as localhost and will lead to trouble
		// if used to connect services
		if (!ret.isLoopbackAddress() || ret.getHostAddress().equals("127.0.1.1")) {
			ret = localHostByName();
		}
		return ret;
	}

	private static InetAddress localHostByName() throws UnknownHostException {
		InetAddress ret;
		ret = InetAddress.getByName("localhost");
		if (!ret.isLoopbackAddress()) {
			logger.error("{} is not a loopback address", ret.getHostAddress());
		}
		return ret;
	}

	@Deprecated
	public static int getPreferredFreeServerPort(int preferredPort) throws IOException {
		return getPreferredFreeServerPort(getLocalHost(), preferredPort);
	}

	@Deprecated
	public static int getFreeServerPort() throws IOException {
		return getFreeServerPort(getLocalHost());
	}

	@Deprecated
	public static int getPreferredFreeServerPort(InetAddress hostAddress, int preferredPort) throws IOException {
		try (ServerSocket serverSocket = new ServerSocket(preferredPort, 0, hostAddress)) {
			return preferredPort;
		} catch (IOException e) {
			return getFreeServerPort(hostAddress);
		}
	}

	public static int freeServerPort(InetAddress hostAddress, int preferredPort) throws IOException {
		try {
			try(Socket socket = new Socket(hostAddress, preferredPort)) {
				return freeServerPort(hostAddress);
			}
		} catch (Exception ex) {
			return preferredPort;
		}
	}

	public static int freeServerPort(InetAddress hostAddress) throws IOException {
		try(ServerSocket socket = new ServerSocket(0,0,hostAddress)) {
			return socket.getLocalPort();
		}
	}

	@Deprecated
	public static int getFreeServerPort(InetAddress hostAddress) throws IOException {
		int ports[] = getFreeServerPorts(hostAddress, 10);
		return randomEntryOf(ports);
	}

	@Deprecated
	public static int randomEntryOf(int[] ports) {
		return ports[ThreadLocalRandom.current().nextInt(ports.length)];
	}

	@Deprecated
	public static int[] getFreeServerPorts(InetAddress hostAddress, int poolSize) throws IOException {
		return freeServerPorts(hostAddress, poolSize);
	}

	public static int[] freeServerPorts(InetAddress hostAddress, int poolSize) throws IOException {
		if (poolSize<1) {
			throw new IllegalArgumentException("poolSize < 1: "+poolSize);
		}

		final ServerSocket[] sockets=new ServerSocket[poolSize];
		final int ports[]=new int[poolSize];

		int idx=0;
		try {
			do {
				sockets[idx]=new ServerSocket(0, 0, hostAddress);
				ports[idx]=sockets[idx].getLocalPort();
				idx++;
			} while (idx<poolSize);
			return ports;
		} finally {
			for (int i=0;i<idx;i++) {
				sockets[i].close();
			}
		}
	}

}


text:
---
layout: post
title:  "自定义验证码按钮的实现"
date:   2017-12-21
categories: 技术
---

今天要做的是一个倒计时按钮,也是项目当中经常遇到的一类需求。
最终实现效果如下:
![验证码按钮.png](http://upload-images.jianshu.io/upload_images/1120896-2be99230194bf93f.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

而实现这种验证码,方式很多,有人用NSTimer进行开发的,也有用dispatch_source_t 进行开发的。
但是NSTimer在运用过程中需要注意的地方很多,如果使用不当就会造成内存无法释放,导致内存溢出的可能。
所以,我后来又改用dispatch_source_t 完成了这一需求。
至于dispatch_source_t 的具体详解,有需要的可以去查看相关资料,毕竟今天的主题是利用它其中的一项功能dispatch_source_set_timer。

资料传送门:
https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/GCDWorkQueues/GCDWorkQueues.html

https://www.tuicool.com/articles/nIRJf2e
http://www.dreamingwish.com/article/grand-central-dispatch-basic-3.html

下面开始我们的正题:
```
由于该项目需要用到上一篇中的文本输入框,所以直接在上一篇的项目中进行使用了。
同样是选用Model作为参数的模式
其实关于模式的选用,就是根据自己的工作环境来决定的。
我选用这种模式的原因就是,很长时间没看的代码,需要时间成本去了解.
而这种模式的可读性较强,而且将属性设置和构建分离,方便以后的维护。
```

model的数据也就是常见的属性和一些需要自定义属性设置,当然,以后扩展还会很多,今天的按钮只是其中之一,所以目前属性就这些吧.
```
@interface GWButtonModel : NSObject
//标题
@property (nonatomic,readwrite,copy)NSString *title;
//标题颜色
@property (nonatomic,readwrite,strong)UIColor *titleColor;
//边框颜色
@property (nonatomic,readwrite,strong)UIColor *borderColor;
//边框宽度
@property (nonatomic,readwrite,unsafe_unretained)CGFloat borderWidth;
//刷新计时
@property (nonatomic,readwrite,unsafe_unretained)NSTimeInterval refreshTime;
//字体
@property (nonatomic,readwrite,strong)UIFont *font;
//背景色
@property (nonatomic,readwrite,strong)UIColor *backgroundColor;
//圆角
@property (nonatomic,readwrite,unsafe_unretained)CGFloat cornerRadius;
@end
```

在构建GWButton类之前,我们应该去分析我们的实际应用场景,所以我先来说说我在项目中用的场景:

```
1. 点击按钮
2. 启用代理到控制器中判断用户是否存在(因为是可变的需求,所以不适合放在GWButton类中)
3. 如果用户存在,那么执行获取验证码的网络请求
(我将获取验证码的网络请求放在GWButton当中,因为这是一个公用方法,无论其他需求怎么变,验证码你得获取吧。也减小了控制器中代码的冗余)
4. 获取到验证码之后开始倒计时。否则就是保持原样
5. 倒计时完毕恢复原来的样式
```

分析出了完整的需求之后,事情就简单多了
1. 构建GWButton类

```
@protocol GWSecurityCodeDelegate <NSObject>

/**
 发送验证码
 */
- (void)sendSecurityCode;
@end

@interface GWButton : UIButton

@property (nonatomic,readwrite,weak)id<GWSecurityCodeDelegate>   securityCodeDelegate;

/**
 验证码

 @param frame 布局
 @param buttonModel 按钮数据模型

 */
+ (instancetype)securityCodeButtonWithFrame:(CGRect)frame
                                buttonModel:(GWButtonModel *)buttonModel;

/**
 发送获取验证码请求

 @param type 验证码类型
 @param tel 手机号码
 @param intervalTime 倒计时时间
 */
- (void)securityCodeType:(NSString *)type
           userTelephone:(NSString *)tel
              refresTime:(NSTimeInterval)intervalTime;
@end
```
```
这里的两个说明:
1. 为什么要用securityCodeDelegate命名,不用delegate.因为验证码只是这个按钮的其中一种。
以后还会添加别的按钮类型,它们的代理可能是别的类型。这样命名更加容易识别。就像WKWebview中的两个代理一样。

2. 因为获取验证码的请求,根据不同后台人员,写的可能不同,所以我只能列出个样例,这里需要的是验证码类型和手机号码两个参数。

```
接下来我们就看一下,我们的核心代码了。
其实关于为什么选用dispatch_source,我们可以看一下,官方的介绍:
```
A dispatch source is a fundamental data type that coordinates the processing of specific low-level system events.
Grand Central Dispatch supports the following types of dispatch sources:
Timer dispatch sources generate periodic notifications.
```
好吧。有很多条,我就不展示了,上面有网址自己看了。
那么第一条就是定时器资源的使用。我们都知道dispatch系列存在都是不用我们自主管理线程和内存释放的。这个就要比NSTimer有优势多了。

而且下面这段话也说明了的Dispatch Sources方便之处:
```
Unlike tasks that you submit to a queue manually, dispatch sources provide a continuous source of events for your application.
A dispatch source remains attached to its dispatch queue until you cancel it explicitly.
 While attached, it submits its associated task code to the dispatch queue whenever the corresponding event occurs.
Some events, such as timer events, occur at regular intervals but most occur only sporadically as specific conditions arise.
For this reason, dispatch sources retain their associated dispatch queue to prevent it from being released prematurely while events may still be pending.
```

简单来说就是:
```
Unlike tasks that you submit to a queue manually, dispatch sources provide a continuous source of events for your application.
与您手动提交到队列的任务不同,分派源为您的应用程序提供了一个连续的事件源(有道翻译,你值得拥有)
```
我们只需要设定好参数,结束和需要改变的事件就可以了,其他的它会帮我们做好。

下面来看实际的代码:
```
 __block int timeout = intervalTime; //倒计时时间

//创建dispatch_source源
1. dispatch_source_t   _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,
                                       dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
//间隔时间
uint64_t  interval = 1.0*NSEC_PER_SEC;
//获取开始的时间
dispatch_time_t  start = dispatch_walltime(NULL, 0);
//设置执行的时间
2. dispatch_source_set_timer(_timer, start, interval, 0);

//设置资源回调.
3.dispatch_source_set_event_handler(_timer, ^{
       if(timeout<=0){//倒计时结束,关闭的事件

       }else{  //计时中的事件

            timeout--;
        }
   });

//启动_timer
4. dispatch_resume(_timer);
```

上面代码中的NSEC_PER_SEC嘛意思?
```
#define NSEC_PER_SEC 1000000000ull
#define USEC_PER_SEC 1000000ull
#define NSEC_PER_USEC 1000ull

NSEC:纳秒。
USEC:微秒。
SEC:秒
PER:每
1   NSEC_PER_SEC,每秒有多少纳秒。
2   USEC_PER_SEC,每秒有多少毫秒。(注意是指在纳秒的基础上)
3   NSEC_PER_USEC,每毫秒有多少纳秒。
```

最后就是简单的执行顺序:
执行按钮事件:
```
#pragma mark 验证码刷新事件
- (void)securityCodeButtonAction:(GWButton *)button{

  //这里写的目的是为了防止用户频繁点击按钮造成多次请求的情况
  //网上一些其他的方法例如 分类什么的都试过了还是这个好用。
    button.enabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        button.enabled = YES;
    });

    if([button.securityCodeDelegate respondsToSelector:@selector(sendSecurityCode)]){
        [button.securityCodeDelegate sendSecurityCode];
    }
}
```

然后执行代理:
```
- (void)securityCodeType:(NSString *)type
           userTelephone:(NSString *)tel
              refresTime:(NSTimeInterval)intervalTime{
    //可以将网络请求的方法放在这里,请求成功执行开始计时的方法。
    //还有这个请求只是放在这里给大家看个样例,demo中是没有的。
    kWeakSelf
    [GWVerificationCodeManager GWGetVerifyNUmberRequstWithPhone:[PMBTools convertNullOrNil:tel]
                                                             type:[PMBTools convertNullOrNil:type]
              success:^(id responseobject) {
                  NSDictionary *dict = (NSDictionary *)responseobject;
                  NSLog(@"验证码请求结果:%@",dict);
                  if([dict[@"resCode"] isEqualToString:@"020000"]){
                      [SVProgressHUD showSuccessWithStatus:dict[@"resMsg"]];
                      [weakself beginToCountDownWithRefresTime:intervalTime];
                  }else{
                      [SVProgressHUD showSuccessWithStatus:dict[@"resMsg"]];
                  }
              } failure:^(NSError *error) {

              } progress:^(float progress) {

              }];
}
```

最后就是执行倒计时了

```
- (void)beginToCountDownWithRefresTime:(NSTimeInterval)intervalTime{
    __block int timeout = intervalTime; //倒计时时间
    kWeakSelf
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,  dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));

    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);

    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){//倒计时结束,关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakself setUserInteractionEnabled:YES];
                [weakself setTitle:@"获取验证码" forState:UIControlStateNormal];
                [weakself setBackgroundImage:[PMBTools convertUIColorToUIImage:[PMBTools colorWithHexString:@"#FF9129"]] forState:UIControlStateNormal];
            });
        }else{
            int seconds = (timeout==60?timeout-1:timeout) % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示 根据自己需求设置
                [weakself setBackgroundImage:[PMBTools convertUIColorToUIImage:getColor(207, 204, 207, 1)] forState:UIControlStateNormal];
                [weakself setTitle:[NSString stringWithFormat:@"重新获取(%ds)",seconds]
                          forState:UIControlStateNormal];
                [weakself setUserInteractionEnabled:NO];
            });
            timeout--;
        }
    });

    dispatch_resume(_timer);
}
```

demo地址:
https://github.com/yanggenwei/GWTextField


text:
package com.bjlx.QinShihuang.model.account;

import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotBlank;
import org.mongodb.morphia.annotations.Embedded;

import javax.validation.constraints.NotNull;
import java.util.UUID;

/**
 * Created by xiaozhi on 2016/7/24.
 * 用户的密钥,用于用户操作授权
 */
@Embedded
public class SecretKey {

    /**
     * key的内容
     */
    @NotBlank
    @Length(min = 32, max = 256)
    private String key;

    /**
     * key的生成时间
     */
    @NotNull
    private Long timestamp;

    /**
     * key的过期时间
     */
    private Long expire;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }

    public Long getExpire() {
        return expire;
    }

    public void setExpire(Long expire) {
        this.expire = expire;
    }

    public SecretKey() {
        this.key = org.apache.commons.codec.digest.DigestUtils.sha256Hex(UUID.randomUUID().toString());
        this.timestamp = System.currentTimeMillis();
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Feddes Repert. Spec. Nov. Regni Veg. 92(1-2): 115 (1981)

#### Original name
Puccinia absinthii var. minor U. Braun

### Remarks
null