text:
package com.hazelcast.spi.impl;

import com.hazelcast.spi.impl.AbstractInvocationFuture.WaitNode;
import com.hazelcast.test.AssertTask;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

import static com.hazelcast.spi.impl.AbstractInvocationFuture.VOID;
import static java.util.concurrent.TimeUnit.DAYS;
import static java.util.concurrent.TimeUnit.HOURS;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelTest.class})
public class AbstractInvocationFuture_GetWithTimeoutTest extends AbstractInvocationFuture_AbstractTest {

    @Test(expected = NullPointerException.class)
    public void whenNullTimeunit() throws Exception {
        future.get(1, null);
    }

    @Test
    public void whenZeroTimeout_butResponseAvailable() throws Exception {
        future.complete(value);
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return future.get(0, SECONDS);
            }
        });
        assertCompletesEventually(getFuture);
        assertSame(value, getFuture.get());
    }

    @Test
    public void whenZeroTimeout_andNoResponseAvailable() throws Exception {
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return future.get(0, SECONDS);
            }
        });

        assertCompletesEventually(getFuture);

        try {
            getFuture.get();
            fail();
        } catch (ExecutionException e) {
            assertInstanceOf(TimeoutException.class, e.getCause());
        }

        // we need to make sure the thread is removed from the waiters.
        assertSame(VOID, future.getState());
    }

    @Test
    public void whenResponseAvailable() throws Exception {
        future.complete(value);
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return future.get(10, SECONDS);
            }
        });
        assertCompletesEventually(getFuture);
        assertSame(value, getFuture.get());
    }

    @Test
    public void whenResultAlreadyAvailable_andInterruptFlagSet() throws Exception {
        future.complete(value);

        final AtomicBoolean interrupted = new AtomicBoolean();
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                // we set the interrupt flag.
                Thread.currentThread().interrupt();
                Object value = future.get(1, SECONDS);
                // and then we check if the interrupt flag is still set
                interrupted.set(Thread.currentThread().isInterrupted());
                return value;
            }
        });

        assertCompletesEventually(getFuture);
        assertSame(value, future.get());
        assertTrue(interrupted.get());
    }

    @Test
    public void whenResponseAvailableAfterSomeDelay() throws Exception {
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return future.get(60, SECONDS);
            }
        });

        // wait till the thread is registered.
        assertTrueEventually(new AssertTask() {
            @Override
            public void run() throws Exception {
                assertNotSame(VOID, future.getState());
            }
        });

        future.complete(value);

        assertCompletesEventually(getFuture);
        assertSame(value, getFuture.get());
    }

    @Test
    public void whenTimeout() throws ExecutionException, InterruptedException {
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                return future.get(1, SECONDS);
            }
        });

        assertCompletesEventually(getFuture);

        try {
            getFuture.get();
            fail();
        } catch (ExecutionException e) {
            assertInstanceOf(TimeoutException.class, e.getCause());
        }

        // we need to make sure the thread is removed from the waiters.
        assertSame(VOID, future.getState());
    }

    @Test
    public void whenInterruptedWhileWaiting() throws Exception {
        final AtomicReference<Thread> thread = new AtomicReference<Thread>();
        final AtomicBoolean interrupted = new AtomicBoolean();
        Future getFuture = spawn(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                thread.set(Thread.currentThread());
                try {
                    return future.get(1, HOURS);
                } finally {
                    interrupted.set(Thread.currentThread().isInterrupted());
                }
            }
        });

        assertTrueEventually(new AssertTask() {
            @Override
            public void run() throws Exception {
                assertNotSame(VOID, future.getState());
            }
        });

        sleepSeconds(5);
        thread.get().interrupt();

        assertCompletesEventually(getFuture);
        assertTrue(interrupted.get());

        try {
            future.get();
            fail();
        } catch (InterruptedException e) {
        }
    }

    @Test
    public void whenMultipleGetters() throws Exception {
        List<Future> getFutures = new LinkedList<Future>();
        for (int k = 0; k < 10; k++) {
            getFutures.add(spawn(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    return future.get(1, DAYS);
                }
            }));
        }

        assertTrueEventually(new AssertTask() {
            @Override
            public void run() throws Exception {
                assertNotSame(VOID, future.getState());
            }
        });

        sleepSeconds(5);
        future.complete(value);

        for (Future getFuture : getFutures) {
            assertCompletesEventually(getFuture);
            assertSame(value, future.get());
        }

        assertSame(value, future.getState());
    }

    @Test
    public void unregister() {
        for (int length = 1; length <= 5; length++) {
            for (int position = 0; position < length; position++) {
                unregister(length, position);
            }
        }
    }

    private void unregister(int length, int position) {
        TestFuture future = new TestFuture();
        Thread[] threads = createThread(length);
        for (int k = 0; k < length; k++) {
            if (k == 0) {
                future.compareAndSetState(VOID, threads[k]);
            } else {
                WaitNode node = new WaitNode(threads[k], null);
                node.next = future.getState();
                future.compareAndSetState(future.getState(), node);
            }
        }

        future.unregisterWaiter(threads[position]);

        for (int k = 0; k < length; k++) {
            assertContains(future.getState(), threads[k], k != position);
        }
    }

    private void assertContains(Object state, Thread waiter, boolean contains) {
        boolean found = false;

        Object current = state;
        while (current != null) {
            Object currentWaiter = current.getClass() == WaitNode.class ? ((WaitNode) current).waiter : current;
            Object next = current.getClass() == WaitNode.class ? ((WaitNode) current).next : null;

            if (currentWaiter == waiter) {
                found = true;
                current = null;
            } else {
                current = next;
            }
        }

        assertEquals(contains, found);
    }

    private Thread[] createThread(int length) {
        Thread[] threads = new Thread[length];
        for (int k = 0; k < threads.length; k++) {
            threads[k] = new Thread();
        }
        return threads;
    }
}


text:
run.sh is a way to generate a simple bash script for running Java apps,
like the `elasticsearch` script. It uses the [replacer](http://mvnrepository.com/artifact/com.google.code.maven-replacer-plugin/replacer) plugin to configure a custom script based on your `pom.xml` file.

## Usage

You can find an example of the [replacer](http://mvnrepository.com/artifact/com.google.code.maven-replacer-plugin/replacer) configuration in the `pom.xml` file included. After copying this configuration, move the `run` script to a dir named `bin` in the root of your project and rename it as your project, remember to edit the file where it says `<your project name>` with the value of `${project.name}`. Next time you run

	$ mvn clean package

Your script will be ready to run with a couple of basic options.

	$ ./bin/app --help

    Usage: ./bin/app [options]

	Options:
  	  -d, --daemon
  	  -v, --version
  	  -h, --help

More options can be added just by modifying the `USAGE` variable, you can add a new option by adding `-p, --pid` or `-p, --pid <p>`, if the option takes a value . All those options will be pass to your app as system properties, using your app name as prefix. They can be accessed like this

```java
  package com.example.bootstrap.App;

  public class App {
  	public static void main(String[] args) {
    	System.out.println(System.getProperty("app.pid"));
    }
  }
```

The script needs an enviroment variable with the path of your classes dir. This var needs to be named after your project, an example is `APP_CLASSPATH`.

run.sh also tries to include a file, which can be used to add variables to the script. The file should be named after your project and finish with `in.sh`, and will be looked in `/usr/share/${project.name}/`, `/usr/local/share/${project.name}/`, `/opt/${project.name}/` and `~/.${project.name}.in.sh`. There's an example file available in the repo.

## Contributing
Feel free to open a pull request with a nice feature or a fix for some bug.

## License

See the `LICENSE` file.

redpajama_set_name: RedPajamaGithub


text:
package org.eidos.kingchallenge.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;

public class KingSimpleFormatter extends Formatter {
	Date dat = new Date();
	private final static String format = "{0,date} {0,time}";
	private MessageFormat formatter;
	// Line separator string. This is the value of the line.separator
	// property at the moment that the SimpleFormatter was created.
	private String lineSeparator = System.getProperty("line.separator");
	private Object args[] = new Object[1];

	public synchronized String format(LogRecord record) {
		StringBuffer sb = new StringBuffer();
		sb.append("[");
		// Minimize memory allocations here.
		dat.setTime(record.getMillis());
		args[0] = dat;
		StringBuffer text = new StringBuffer();
		if (formatter == null) {
			formatter = new MessageFormat(format);
		}
		formatter.format(args, text, null);
		sb.append(text);
		sb.append("] ");

		sb.append(" -");
		sb .append(Thread.currentThread().getName() );
		sb.append(" -");
		if (record.getSourceClassName() != null) {
			sb.append(record.getSourceClassName());
		} else {
			sb.append(record.getLoggerName());
		}

		if (record.getSourceMethodName() != null) {
			sb.append(".");
			sb.append(record.getSourceMethodName());
		}
		sb.append(": ");
		String message = formatMessage(record);
		sb.append(record.getLevel().getLocalizedName());
		sb.append(":  ");
		sb.append(message);
		sb.append(lineSeparator);
		if (record.getThrown() != null) {
			try {
				StringWriter sw = new StringWriter();
				PrintWriter pw = new PrintWriter(sw);
				record.getThrown().printStackTrace(pw);
				pw.close();
				sb.append(sw.toString());
			} catch (Exception ex) {
			}
		}
		return sb.toString();
	}
}


text:
layout: doc
title: "Advanced Features: Overview"
description:
modified:
excerpt:
tags: []
image:
  feature:
  teaser:
  thumb:
toc: true
share: false
---

{% include doc/AdvancedFeaturesIndex.md %}


text:
package io.fabric8.kubernetes.client;

import io.fabric8.kubernetes.api.model.authorization.v1.LocalSubjectAccessReview;
import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectAccessReview;
import io.fabric8.kubernetes.api.model.authorization.v1.SelfSubjectRulesReview;
import io.fabric8.kubernetes.api.model.authorization.v1.SubjectAccessReview;
import io.fabric8.kubernetes.client.dsl.InOutCreateable;
import io.fabric8.kubernetes.client.dsl.NamespacedInOutCreateable;

public interface V1AuthorizationAPIGroupDSL extends Client{
  InOutCreateable<SelfSubjectAccessReview, SelfSubjectAccessReview> selfSubjectAccessReview();
  InOutCreateable<SubjectAccessReview, SubjectAccessReview> subjectAccessReview();
  NamespacedInOutCreateable<LocalSubjectAccessReview, LocalSubjectAccessReview> localSubjectAccessReview();
  InOutCreateable<SelfSubjectRulesReview, SelfSubjectRulesReview> selfSubjectRulesReview();
}


text:
cask "cyberduck" do
  version "7.7.2.33862"
  sha256 "3becbea9d43261e8b8ddc139164c5744bb5535602bf994d400aedf8767fc1f44"

  url "https://update.cyberduck.io/Cyberduck-#{version}.zip"
  appcast "https://version.cyberduck.io/changelog.rss"
  name "Cyberduck"
  desc "Server and cloud storage browser"
  homepage "https://cyberduck.io/"

  auto_updates true

  app "Cyberduck.app"

  zap trash: [
    "~/Library/Application Support/Cyberduck",
    "~/Library/Caches/ch.sudo.cyberduck",
    "~/Library/Group Containers/G69SCX94XU.duck",
    "~/Library/Preferences/ch.sudo.cyberduck.plist",
    "~/Library/Saved Application State/ch.sudo.cyberduck.savedState",
  ]
end


text:
var cec2ation = require('../lib/cec2ation.js'),
	assert = require('assert'),
	mocha = require('mocha'),
	sinon = require('sinon');

describe('when configure called', function() {
	var startInstanceJobStub = sinon.stub();
	var stopInstanceJobStub = sinon.stub();
	var config;

	beforeEach(function() {
		config = {
			start: 'START',
			stop: 'STOP',
			instances: []
		};

		startInstanceJobStub.start = sinon.stub();
		stopInstanceJobStub.start = sinon.stub();
		sinon.stub(cec2ation, 'startInstanceJob').returns(startInstanceJobStub);
		sinon.stub(cec2ation, 'stopInstanceJob').returns(stopInstanceJobStub);
		cec2ation.configure(config);
	});

	afterEach(function() {
		cec2ation.startInstanceJob.restore();
		cec2ation.stopInstanceJob.restore();
	});

	it('should start startInstanceJob', function() {
		assert(cec2ation.startInstanceJob.calledWithExactly(config));
		assert(cec2ation.startInstanceJob.calledOnce);
		assert(startInstanceJobStub.start.calledOnce);
	});

	it('should start stopInstanceJob', function() {
		assert(cec2ation.stopInstanceJob.calledWithExactly(config));
		assert(cec2ation.stopInstanceJob.calledOnce);
		assert(stopInstanceJobStub.start.calledOnce);
	});
});

describe('when calling startInstanceJob', function() {
	var job;
	var config;
	beforeEach(function() {
		config = {
			start : '0 0 0 0 0 0'
		}

		sinon.stub(cec2ation, 'startInstance');
		job = cec2ation.startInstanceJob(config);
	});

	afterEach(function() {
		cec2ation.startInstance.restore();
	})

	it('should set time correctly', function() {
		assert.equal('0 0 0 0 0 0', job.cronTime.source);
	});

	it('should set callback correctly', function() {
		assert.equal(1, job._callbacks.length);
		job._callbacks[0]();
		assert(cec2ation.startInstance.calledOnce);
		assert(cec2ation.startInstance.calledWithExactly(config));
	});
});

describe('when calling stopInstanceJob', function() {
	var job;
	var config;

	beforeEach(function() {
		config = {
			stop: '0 0 0 0 0 0'
		};

		sinon.stub(cec2ation, 'stopInstance');
		job = cec2ation.stopInstanceJob(config);
	});

	afterEach(function() {
		cec2ation.stopInstance.restore();
	})

	it('should set time correctly', function() {
		assert.equal('0 0 0 0 0 0', job.cronTime.source);
	});

	it('should set callback correctly', function() {
		assert.equal(1, job._callbacks.length);
		job._callbacks[0]();
		assert(cec2ation.stopInstance.calledOnce);
		assert(cec2ation.stopInstance.calledWithExactly(config));
	});
});

describe('when calling getEC2Client', function() {
	var config;
	var client;

	beforeEach(function() {
		config = {
			accessKeyId: 'ACCESSKEYID',
			secretAccessKey: 'SECRETACCESSKEY',
			region: 'REGION'
		};

		client = cec2ation.getEC2Client(config);
	});

	it('should set accesskey', function() {
		assert.equal(config.accessKeyId, client.config.credentials.accessKeyId);
	});

	it('should set secretAccessKey', function() {
		assert.equal(config.secretAccessKey, client.config.credentials.secretAccessKey);
	});

	it('should set region', function() {
		assert.equal(config.region, client.config.region);
	});
});

describe('when calling stopInstance', function() {

	var client;
	var config;
	var instances;

	beforeEach(function() {
		client = sinon.stub();
		client.stopInstances = sinon.stub();

		sinon.stub(cec2ation, 'getEC2Client').returns(client);
		sinon.stub(cec2ation, 'getInstances').yields(null, instances);
		cec2ation.stopInstance(config);
	});

	afterEach(function() {
		cec2ation.getEC2Client.restore();
		cec2ation.getInstances.restore();
	});

	it('should call getInstances', function() {
		assert(cec2ation.getInstances.calledOnce);
		assert(cec2ation.getInstances.calledWith(config));
	});

	it('should call stopInstances', function() {
		assert(client.stopInstances.calledOnce);
		assert(client.stopInstances.calledWith({InstanceIds : instances}));
	});
});

describe('when calling getInstances', function() {
	var client;
	var config;

	beforeEach(function() {
		config = {
			instances: "INSTANCES"
		};

		client = sinon.stub();
		client.describeInstances = sinon.stub();

		sinon.stub(cec2ation, 'getEC2Client').returns(client);
		client.describeInstances.yields(null, {
			Reservations : [ {
				Instances : [ {
					InstanceId: 'A'
				},{
					InstanceId: 'B'
				}]
			}]
		});
	});

	it('should return expected', function(done) {
		cec2ation.getInstances(config, function(e, instances) {
			assert.deepEqual(['A', 'B'], instances);
			done(e, instances);
		});
	});
});


text:
package com.morgan.server.account;

import java.util.Set;

import com.google.common.collect.ImmutableMap;
import com.morgan.server.auth.UserInformation;
import com.morgan.shared.common.BackendException;

/**
 * Helper that can look up user accounts.
 *
 * @author mark@mark-morgan.net (Mark Morgan)
 */
public interface AccountLookupHelper {

  /**
   * Look's up a set of users.
   */
  ImmutableMap<Long, UserInformation> lookUpAccounts(Set<Long> ids) throws BackendException;
}


text:
package checkSyntaxLC;

import java.util.*;

public class WordLadderII {
  /**
   * @param start, a string
   * @param end, a string
   * @param dict, a set of string
   * @return a list of lists of string
   */
  public List<List<String>> findLadders(String start, String end,
      Set<String> dict) {
    // write your code here

    dict.add(start); // why this? Ans: because this DFS need trace back
    dict.add(end); // this is general trick

    Map<String, List<String>> wordMap = new HashMap<String, List<String>>();
    Map<String, Integer> distance = new HashMap<String, Integer>();
    for (String word : dict) {
      wordMap.put(word, new ArrayList<String>());
    }
    // BFS to build the wordMap(WHOLE!)
    bfs(wordMap, distance, start, end, dict);
    System.out.println(distance);
    System.out.println(wordMap);

    List<String> path = new ArrayList<>();
    // List<List<String>> result = new ArrayList<ArrayList<String>>();
    List<List<String>> result = new ArrayList<List<String>>();
    // DFS then use the wordMap and minimum Level to find all solution
    dfs(result, path, wordMap, distance, end, start, dict);
    System.out.println(result);
    return result;
  }

  private static void bfs(Map<String, List<String>> wordMap,
      Map<String, Integer> distance, String start, String end, Set<String> dict) {
    if (dict == null || dict.size() == 0) {
      return;
    }
    Queue<String> bfsQ = new LinkedList<String>();
    bfsQ.offer(start);
    wordMap.put(start, new ArrayList<>());
    distance.put(start, 1); // start is level 1, the same condition as WordLadder I

    int level = 1;
    while (!bfsQ.isEmpty()) {
      int Qsize = bfsQ.size();
      level++;
      for (int i = 0; i < Qsize; i++) {
        String cur = bfsQ.poll();
//        wordMap.put(cur, new ArrayList<>()); // WRONG!WRONG!WRONG!
        for (String neighbor : getNeighbors(cur, dict)) {
          wordMap.get(neighbor).add(cur); // KEY, why get(neighbor) instead of get(cur)? why don't
                                          // check distance? because I need whole Map!
          if (!distance.containsKey(neighbor)) {
            // wordMap.get(neighbor).add(cur); // KEY, why get(neighbor) instead of get(cur)?
            distance.put(neighbor, level);
            bfsQ.offer(neighbor);
          }
        }
      }
    }

    return; // safety
  }

  private static void dfs(List<List<String>> result, List<String> path,
      Map<String, List<String>> wordMap, Map<String, Integer> distance,
      String cur, String start, Set<String> dict) {
    path.add(cur);
    if (cur.equals(start)) {
      Collections.reverse(path);
      result.add(new ArrayList<String>(path));
      Collections.reverse(path);
    } else {
      for (String next : wordMap.get(cur)) {
        if (distance.get(next) + 1 == distance.get(cur)) {
          dfs(result, path, wordMap, distance, next, start, dict);
        }
      }
    }
    path.remove(path.size() - 1);
  }

  private static String replaceChar(String src, int idx, char ch) {
    if (idx >= src.length()) {
      return src;
    }
    char[] charArr = src.toCharArray();
    charArr[idx] = ch;
    return new String(charArr);
  }

  // dummy dict, not much checking
  private static List<String> getNeighbors(String str, Set<String> dict) {
    List<String> neighbors = new ArrayList<>();
    for (char ch = 'a'; ch <= 'z'; ++ch) {
      for (int i = 0; i < str.length(); ++i) {
        String newWord = replaceChar(str, i, ch);
        if (!str.equals(newWord)) {
          if (dict.contains(newWord)) {
            neighbors.add(newWord);
          }
        }
      }
    }

    return neighbors;
  }

  private void test() {
    Set<String> dict = new HashSet<>();
    // dict.add("hot");
    // dict.add("dot");
    // dict.add("dog");
    // dict.add("lot");
    // dict.add("log");
    // dict.add("dit");
    // dict.add("dig");
    // dict.add("sit");
    // dict.add("set");
    // dict.add("seg");
    // dict.add("sog");

    // dict.add("hot");
    // dict.add("dot");
    // dict.add("dog");
    // dict.add("git");
    // dict.add("got");
    // dict.add("god");
    // dict.add("zit");
    // dict.add("zot");
    // dict.add("zog");

    // dict.add("hot");
    // dict.add("cot");
    // dict.add("bit");
    // dict.add("biz");
    // dict.add("boz");
    // dict.add("bog");
    //
    // String start = "hit";
    // String end = "cog";

    dict.add("a");
    dict.add("b");
    dict.add("c");
    String start = "a", end = "c";

    List<List<String>> ans = findLadders(start, end, dict);
    for (List<String> list : ans) {
      for (String num : list) {
        System.out.print(num + " ");
      }
      System.out.println();
    }
  }

  public static void main(String[] args) {
    WordLadderII wli = new WordLadderII();
    wli.test();
  }
}


text:
<?php
namespace inklabs\kommerce\ActionHandler\Product;

use inklabs\kommerce\Action\Product\UpdateProductCommand;
use inklabs\kommerce\EntityDTO\Builder\ProductDTOBuilder;
use inklabs\kommerce\EntityRepository\ProductRepositoryInterface;
use inklabs\kommerce\Lib\Authorization\AuthorizationContextInterface;
use inklabs\kommerce\Lib\Command\CommandHandlerInterface;

final class UpdateProductHandler implements CommandHandlerInterface
{
    /** @var UpdateProductCommand */
    private $command;

    /** @var ProductRepositoryInterface */
    private $productRepository;

    public function __construct(UpdateProductCommand $command, ProductRepositoryInterface $productRepository)
    {
        $this->command = $command;
        $this->productRepository = $productRepository;
    }

    public function verifyAuthorization(AuthorizationContextInterface $authorizationContext): void
    {
        $authorizationContext->verifyIsAdmin();
    }

    public function handle()
    {
        $productDTO = $this->command->getProductDTO();
        $product = $this->productRepository->findOneById($productDTO->id);
        ProductDTOBuilder::setFromDTO($product, $productDTO);

        $this->productRepository->update($product);
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**error** | **String** | Unprocessable entity message |  [optional]


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
  <title>angle= (Imlib2::Context)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />
</head>
<body class="standalone-code">
  <pre>/*
 * Set the text drawing angle.
 *
 * Example:
 *   ctx.angle = 76.8
 *
 */
static VALUE ctx_set_angle(VALUE self, VALUE val) {
</pre>
</body>
</html>


text:
package com.orientechnologies.orient.core.storage.fs;

import java.io.IOException;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.orientechnologies.common.io.OFileUtils;
import com.orientechnologies.common.io.OIOException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.profiler.OProfiler.OProfilerHookValue;
import com.orientechnologies.common.util.OByteBufferUtils;
import com.orientechnologies.orient.core.Orient;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.serialization.OBinaryProtocol;

/**
 * OFile implementation that use the Memory Mapping techniques to get faster access on read/write. The Memory Mapping is handled by
 * {@link OMMapManager} class. If the Memory Mapping buffer pools is full and a new segment is requested, then read/write are
 * executed against the channel directly without Memory Mapping.

 * Header structure:

 *

 * +-----------+--------------+---------------+---------------+

 * | FILE SIZE | FILLED UP TO | SOFTLY CLOSED | SECURITY CODE |

 * | 8 bytes . | 8 bytes .... | 1 byte ...... | 32 bytes .... |

 * +-----------+--------------+---------------+---------------+

 * = 1024 bytes

 *

 */
public class OFileMMap extends OAbstractFile {
  public final static String                 NAME                      = "mmap";
  protected int                              filledUpTo;                                                         // PART OF HEADER
                                                                                // (4
                                                                                // bytes)
  protected MappedByteBuffer                 headerBuffer;
  protected static final Queue<ByteBuffer>   bufferPool                = new ConcurrentLinkedQueue<ByteBuffer>();

  private static int                         BYTEBUFFER_POOLABLE_SIZE;
  private static OMMapManager.ALLOC_STRATEGY strategy;

  private static long                        metricPooledBufferCreated = 0;
  private static long                        metricPooledBufferUsed    = 0;
  private static long                        metricNonPooledBufferUsed = 0;

  static {
    Orient.instance().getProfiler().registerHookValue("system.file.mmap.pooledBufferCreated", new OProfilerHookValue() {
      public Object getValue() {
        return metricPooledBufferCreated;
      }
    });
    Orient.instance().getProfiler().registerHookValue("system.file.mmap.pooledBufferUsed", new OProfilerHookValue() {
      public Object getValue() {
        return metricPooledBufferUsed;
      }
    });
    Orient.instance().getProfiler().registerHookValue("system.file.mmap.nonPooledBufferUsed", new OProfilerHookValue() {
      public Object getValue() {
        return metricNonPooledBufferUsed;
      }
    });
  }

  @Override
  public void delete() throws IOException {
    OMMapManagerLocator.getInstance().removeFile(this);
    super.delete();
  }

  @Override
  public OFileMMap init(String iFileName, String iMode) {
    super.init(iFileName, iMode);
    BYTEBUFFER_POOLABLE_SIZE = OGlobalConfiguration.FILE_MMAP_BUFFER_SIZE.getValueAsInteger();
    strategy = OMMapManager.ALLOC_STRATEGY.values()[OGlobalConfiguration.FILE_MMAP_STRATEGY.getValueAsInteger()];
    return this;
  }

  public int getFileSize() {
    return size;
  }

  public int getFilledUpTo() {
    return filledUpTo;
  }

  public void read(long iOffset, byte[] iData, int iLength, int iArrayOffset) throws IOException {
    byte[] source = new byte[iLength];
    read(iOffset, source, iLength);
    System.arraycopy(source, 0, iData, iArrayOffset, iLength);
  }

  public void write(long iOffset, byte[] iData, int iSize, int iArrayOffset) throws IOException {
    if (iData == null || iData.length == 0 || iSize == 0)
      return;

    assert iOffset > -1;
    assert iArrayOffset > -1;

    iOffset = checkRegions(iOffset, iSize);

    try {
      final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, iSize,
          OMMapManager.OPERATION_TYPE.WRITE, strategy);
      if (entries != null) {
        // MMAP WRITE
        try {

          int position = (int) (iOffset - entries[0].beginOffset);

          int remaining;
          final int iLength = iSize;
          int remainingLength = iLength;
          for (OMMapBufferEntry entry : entries) {
            entry.buffer.position(position);
            remaining = entry.buffer.remaining();
            int toWrite = Math.min(remaining, remainingLength);
            entry.buffer.put(iData, iArrayOffset + iLength - remainingLength, toWrite);
            position = 0;
            remainingLength -= toWrite;
          }
        } finally {
          OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.WRITE);
        }
      } else {
        // DIRECT WRITE
        final ByteBuffer buffer = acquireByteBuffer(iSize);
        buffer.put(iData, iArrayOffset, iSize);
        buffer.rewind();
        channel.write(buffer, iOffset + HEADER_SIZE);
        releaseByteBuffer(buffer);
      }
    } catch (BufferOverflowException e) {
      OLogManager.instance().error(this, "Error on write in the range " + iOffset + "-" + (iOffset + iSize) + "." + toString(), e,
          OIOException.class);
    }
  }

  @Override
  public void read(long iOffset, final byte[] iDestBuffer, final int iLenght) throws IOException {
    iOffset = checkRegions(iOffset, iLenght);

    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, iLenght,
        OMMapManager.OPERATION_TYPE.READ, strategy);
    if (entries != null) {
      // MMAP READ
      try {
        int position = (int) (iOffset - entries[0].beginOffset);

        int remaining;
        int remainingLength = iLenght;
        for (OMMapBufferEntry entry : entries) {
          entry.buffer.position(position);
          remaining = entry.buffer.remaining();
          int toRead = Math.min(remaining, remainingLength);
          entry.buffer.get(iDestBuffer, iLenght - remainingLength, toRead);
          position = 0;
          remainingLength -= toRead;
        }
      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.READ);
      }
    } else {
      // DIRECT READ
      final ByteBuffer buffer = acquireByteBuffer(iLenght);
      channel.read(buffer, iOffset + HEADER_SIZE);
      buffer.rewind();
      buffer.get(iDestBuffer);
      releaseByteBuffer(buffer);
    }
  }

  @Override
  public int readInt(long iOffset) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_INT);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_INT,
        OMMapManager.OPERATION_TYPE.READ, strategy);
    if (entries != null) {
      // MMAP READ
      try {

        if (entries.length == 1)
          return entries[0].buffer.getInt((int) (iOffset - entries[0].beginOffset));
        else {
          entries[0].buffer.position((int) (iOffset - entries[0].beginOffset));
          entries[1].buffer.position(0);
          return OByteBufferUtils.mergeIntFromBuffers(entries[0].buffer, entries[1].buffer);
        }

      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.READ);
      }
    } else {
      // DIRECT READ
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_INT);
      channel.read(buffer, iOffset + HEADER_SIZE);
      buffer.rewind();
      final int value = buffer.getInt();
      releaseByteBuffer(buffer);
      return value;
    }
  }

  @Override
  public long readLong(long iOffset) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_LONG);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_LONG,
        OMMapManager.OPERATION_TYPE.READ, strategy);
    if (entries != null) {
      // MMAP READ
      try {
        if (entries.length == 1)
          return entries[0].buffer.getLong((int) (iOffset - entries[0].beginOffset));
        else {
          entries[0].buffer.position((int) (iOffset - entries[0].beginOffset));
          entries[1].buffer.position(0);
          return OByteBufferUtils.mergeLongFromBuffers(entries[0].buffer, entries[1].buffer);
        }

      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.READ);
      }
    } else {
      // DIRECT READ
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_LONG);
      channel.read(buffer, iOffset + HEADER_SIZE);
      buffer.rewind();
      final long value = buffer.getLong();
      releaseByteBuffer(buffer);
      return value;
    }
  }

  @Override
  public short readShort(long iOffset) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_SHORT);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_SHORT,
        OMMapManager.OPERATION_TYPE.READ, strategy);
    if (entries != null) {
      // MMAP READ
      try {
        if (entries.length == 1) {
          return entries[0].buffer.getShort((int) (iOffset - entries[0].beginOffset));
        } else {
          entries[0].buffer.position((int) (iOffset - entries[0].beginOffset));
          entries[1].buffer.position(0);

          return OByteBufferUtils.mergeShortFromBuffers(entries[0].buffer, entries[1].buffer);
        }

      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.READ);
      }
    } else {
      // DIRECT READ
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_SHORT);
      channel.read(buffer, iOffset + HEADER_SIZE);
      buffer.rewind();
      final short value = buffer.getShort();
      releaseByteBuffer(buffer);
      return value;
    }
  }

  @Override
  public byte readByte(long iOffset) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_BYTE);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_BYTE,
        OMMapManager.OPERATION_TYPE.READ, strategy);
    if (entries != null) {
      // MMAP READ
      try {
        return entries[0].buffer.get((int) (iOffset - entries[0].beginOffset));
      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.READ);
      }
    } else {
      // DIRECT READ
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_BYTE);
      channel.read(buffer, iOffset + HEADER_SIZE);
      buffer.rewind();
      final byte value = buffer.get();
      releaseByteBuffer(buffer);
      return value;
    }
  }

  @Override
  public void writeInt(long iOffset, final int iValue) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_INT);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_INT,
        OMMapManager.OPERATION_TYPE.WRITE, strategy);
    if (entries != null) {
      // MMAP WRITE
      try {
        if (entries.length == 1)
          entries[0].buffer.putInt((int) (iOffset - entries[0].beginOffset), iValue);
        else {
          entries[0].buffer.position((int) (iOffset - entries[0].beginOffset));
          entries[1].buffer.position(0);

          OByteBufferUtils.splitIntToBuffers(entries[0].buffer, entries[1].buffer, iValue);
        }
      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.WRITE);
      }
    } else {
      // DIRECT WRITE
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_INT);
      buffer.putInt(iValue);
      buffer.rewind();
      channel.write(buffer, iOffset + HEADER_SIZE);
      releaseByteBuffer(buffer);
    }
  }

  @Override
  public void writeLong(long iOffset, final long iValue) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_LONG);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_LONG,
        OMMapManager.OPERATION_TYPE.WRITE, strategy);
    if (entries != null) {
      // MMAP WRITE
      try {
        if (entries.length == 1)
          entries[0].buffer.putLong((int) (iOffset - entries[0].beginOffset), iValue);
        else {
          entries[0].buffer.position((int) (iOffset - entries[0].beginOffset));
          entries[1].buffer.position(0);

          OByteBufferUtils.splitLongToBuffers(entries[0].buffer, entries[1].buffer, iValue);
        }
      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.WRITE);
      }
    } else {
      // DIRECT WRITE
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_LONG);
      buffer.putLong(iValue);
      buffer.rewind();
      channel.write(buffer, iOffset + HEADER_SIZE);
      releaseByteBuffer(buffer);
    }
  }

  @Override
  public void writeShort(long iOffset, final short iValue) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_SHORT);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_SHORT,
        OMMapManager.OPERATION_TYPE.WRITE, strategy);
    if (entries != null) {
      // MMAP WRITE
      try {
        if (entries.length == 1)
          entries[0].buffer.putShort((int) (iOffset - entries[0].beginOffset), iValue);
        else {
          entries[0].buffer.position((int) (iOffset - entries[0].beginOffset));
          entries[1].buffer.position(0);

          OByteBufferUtils.splitShortToBuffers(entries[0].buffer, entries[1].buffer, iValue);
        }
      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.WRITE);
      }
    } else {
      // DIRECT WRITE
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_SHORT);
      buffer.putShort(iValue);
      buffer.rewind();
      channel.write(buffer, iOffset + HEADER_SIZE);
      releaseByteBuffer(buffer);
    }
  }

  @Override
  public void writeByte(long iOffset, final byte iValue) throws IOException {
    iOffset = checkRegions(iOffset, OBinaryProtocol.SIZE_BYTE);
    final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, OBinaryProtocol.SIZE_BYTE,
        OMMapManager.OPERATION_TYPE.WRITE, strategy);
    if (entries != null) {
      // MMAP WRITE
      try {
        entries[0].buffer.put((int) (iOffset - entries[0].beginOffset), iValue);
      } finally {
        OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.WRITE);
      }
    } else {
      // DIRECT WRITE
      final ByteBuffer buffer = acquireByteBuffer(OBinaryProtocol.SIZE_BYTE);
      buffer.put(iValue);
      buffer.rewind();
      channel.write(buffer, iOffset + HEADER_SIZE);
      releaseByteBuffer(buffer);
    }
  }

  @Override
  public void write(long iOffset, final byte[] iSourceBuffer) throws IOException {
    if (iSourceBuffer == null || iSourceBuffer.length == 0)
      return;

    iOffset = checkRegions(iOffset, iSourceBuffer.length);

    try {
      final OMMapBufferEntry[] entries = OMMapManagerLocator.getInstance().acquire(this, iOffset, iSourceBuffer.length,
          OMMapManager.OPERATION_TYPE.WRITE, strategy);
      if (entries != null) {
        // MMAP WRITE
        try {

          int position = (int) (iOffset - entries[0].beginOffset);

          int remaining;
          final int iLenght = iSourceBuffer.length;
          int remainingLength = iLenght;
          for (OMMapBufferEntry entry : entries) {
            entry.buffer.position(position);
            remaining = entry.buffer.remaining();
            int toWrite = Math.min(remaining, remainingLength);
            entry.buffer.put(iSourceBuffer, iLenght - remainingLength, toWrite);
            position = 0;
            remainingLength -= toWrite;
          }
        } finally {
          OMMapManagerLocator.getInstance().release(entries, OMMapManager.OPERATION_TYPE.WRITE);
        }
      } else {
        // DIRECT WRITE
        final ByteBuffer buffer = acquireByteBuffer(iSourceBuffer.length);
        buffer.put(iSourceBuffer);
        buffer.rewind();
        channel.write(buffer, iOffset + HEADER_SIZE);
        releaseByteBuffer(buffer);
      }
    } catch (BufferOverflowException e) {
      OLogManager.instance().error(this,
          "Error on write in the range " + iOffset + "-" + (iOffset + iSourceBuffer.length) + "." + toString(), e,
          OIOException.class);
    }
  }

  /**
   * Synchronizes buffered changes to the file.
   *
   */
  @Override
  public void synch() {
    OMMapManagerLocator.getInstance().flushFile(this);
    flushHeader();
  }

  @Override
  public void writeHeaderLong(final int iPosition, final long iValue) {
    if (headerBuffer != null) {
      headerBuffer.putLong(HEADER_DATA_OFFSET + iPosition, iValue);
      setHeaderDirty();
    }
  }

  @Override
  public long readHeaderLong(final int iPosition) {
    return headerBuffer.getLong(HEADER_DATA_OFFSET + iPosition);
  }

  @Override
  public void close() throws IOException {
    super.close();

    OMMapManagerLocator.getInstance().flush();
    if (headerBuffer != null) {
      setSoftlyClosed(true);
      headerBuffer = null;
    }
  }

  public boolean isSoftlyClosed() {
    return headerBuffer.get(SOFTLY_CLOSED_OFFSET) == 1;
  }

  public void setSoftlyClosed(final boolean iValue) {
    if (headerBuffer == null)
      return;

    headerBuffer.put(SOFTLY_CLOSED_OFFSET, (byte) (iValue ? 1 : 0));
    setHeaderDirty();
    flushHeader();
  }

  MappedByteBuffer map(final long iBeginOffset, final int iSize) throws IOException {
    return channel.map(mode.equals("r") ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, iBeginOffset
        + HEADER_SIZE, iSize);
  }

  @Override
  protected void openChannel(final int iNewSize) throws IOException {
    super.openChannel(iNewSize);
    headerBuffer = channel.map(mode.equals("r") ? FileChannel.MapMode.READ_ONLY : FileChannel.MapMode.READ_WRITE, 0, HEADER_SIZE);
  }

  public boolean isClosed() {
    return headerBuffer == null;
  }

  /**
   * Acquires a byte buffer to use in read/write operations. If the requested size is minor-equals to BYTEBUFFER_POOLABLE_SIZE
   * bytes, then is returned from the bufferPool if any. Buffer bigger than BYTEBUFFER_POOLABLE_SIZE bytes.
   *
   * @param iSize
   *          The requested size
   * @return A buffer in the pool if any and if size is compatible, otherwise a new one
   */
  protected ByteBuffer acquireByteBuffer(final int iSize) {
    if (iSize > BYTEBUFFER_POOLABLE_SIZE) {
      try {
        metricNonPooledBufferUsed++;
        // CREATE A BUFFER AT THE FLY. IT WILL BE DISCARDED WHEN FINISHED
        return ByteBuffer.allocate(iSize);
      } catch (OutOfMemoryError e) {
        // LOG THE EXCEPTION AND RE-THROW IT
        OLogManager.instance().error(this, "Error on allocating direct buffer of size %d bytes", e, iSize);
        throw e;
      }
    }

    // POP THE FIRST AVAILABLE
    ByteBuffer buffer = bufferPool.poll();
    if (buffer != null)
      metricPooledBufferUsed++;
    else {
      metricPooledBufferCreated++;
      buffer = ByteBuffer.allocateDirect(BYTEBUFFER_POOLABLE_SIZE);
    }

    buffer.limit(iSize);

    return buffer;
  }

  protected void releaseByteBuffer(final ByteBuffer iBuffer) {
    if (iBuffer.limit() > BYTEBUFFER_POOLABLE_SIZE)
      // DISCARD: IT'S TOO BIG TO KEEP IT IN MEMORY
      return;

    iBuffer.rewind();

    // PUSH INTO THE POOL
    bufferPool.add(iBuffer);
  }

  @Override
  protected void init() {
    size = headerBuffer.getInt(SIZE_OFFSET);
    filledUpTo = headerBuffer.getInt(FILLEDUPTO_OFFSET);
  }

  @Override
  protected void setFilledUpTo(final int iHow) {
    if (iHow != filledUpTo) {
      filledUpTo = iHow;
      headerBuffer.putInt(FILLEDUPTO_OFFSET, filledUpTo);
      setHeaderDirty();
    }
  }

  @Override
  public void setSize(final int iSize) throws IOException {
    if (maxSize > 0 && iSize > maxSize)
      throw new IllegalArgumentException("Cannot extend the file to " + OFileUtils.getSizeAsString(iSize) + " because the max is "
          + OFileUtils.getSizeAsString(maxSize));
    if (iSize != size) {
      checkSize(iSize);
      size = iSize;
      headerBuffer.putInt(SIZE_OFFSET, size);
      setHeaderDirty();
    }
  }

  protected void flushHeader() {
    if (headerDirty) {
      headerBuffer.force();
      headerDirty = false;
    }
  }
}


text:
Simple iOS image asset maker for macOS

## Usage
1. Select a png file (the program assumes that the selected file is @3x resolution)
2. Services->AssetMaker
3. Grab your fresh asset images from the Assets folder.

## Install

1. Download and unzip the project
2. Open a Terminal
3. ```cd $Projetc_Path```
4. ```./install.bash```

## Uninstall

``` bash
rm -rf ~/Library/Services/AssetMaker.workflow
rm -rf ~/Library/Application\ Support/AssetMaker
```


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ReflectionHelper.Property.cs" company="OBeautifulCode">
//   Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
//   Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Math source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------

namespace OBeautifulCode.Reflection.Recipes
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;

    using OBeautifulCode.Validation.Recipes;

    ///
    /// Provides useful methods related to reflection.
    ///
#if !OBeautifulCodeReflectionRecipesProject
    internal
#else
    public
#endif
    static partial class ReflectionHelper
    {
        ///
        /// Determines if an object has a given property.
        ///
        /// <param name="item">Object for which to check for the given property.</param>
        /// <param name="propertyName">The name of the property to check for.</param>
        /// <param name="bindingFlags">Optional binding flags to use during reflection operations.</param>
        /// <returns>
        /// true if the object has the specified property, false if not.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="item"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="propertyName"/> is whitespace.</exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Correct name.")]
        public static bool HasProperty(
            this object item,
            string propertyName,
            BindingFlags bindingFlags = DefaultBindingFlags) =>
            GetPropertyInfo(item?.GetType(), propertyName, bindingFlags) != null;

        ///
        /// Gets the names of all properties.
        ///
        /// <param name="type">The type.</param>
        /// <param name="bindingFlags">The binding flags to use.</param>
        /// <returns>Collection of property names.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Correct name.")]
        public static IReadOnlyCollection<string> GetPropertyNames(
            this Type type,
            BindingFlags bindingFlags = DefaultBindingFlags)
        {
            new { type }.Must().NotBeNull();
            var allProperties = type.GetProperties(bindingFlags);
            var ret = allProperties.Select(_ => _.Name).ToList();
            return ret;
        }

        ///
        /// Retrieves a property value from a given object.
        ///
        /// <typeparam name="T">Type of the property.</typeparam>
        /// <param name="type">Type to get property value on (will only get static properties).</param>
        /// <param name="propertyName">The name of the property.</param>
        /// <param name="bindingFlags">Optional binding flags to use during reflection operations.</param>
        /// <returns>
        /// The value of the property.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="type"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="propertyName"/> is whitespace.</exception>
        /// <exception cref="InvalidOperationException">The property was not found.</exception>
        /// <exception cref="InvalidCastException">The property is not of the specified type.</exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Justification = "This is a developer-facing string, not a user-facing string.")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Correct name.")]
        public static T GetPropertyValue<T>(
            this Type type,
            string propertyName,
            BindingFlags bindingFlags = DefaultBindingFlags)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var pi = type.GetPropertyInfo(propertyName, bindingFlags);
            if (pi == null)
            {
                throw new InvalidOperationException($"Property {propertyName} was not found on type {type.FullName}");
            }

            var ret = pi.GetPropertyValue<T>(null);
            return ret;
        }

        ///
        /// Retrieves a property value from a given object.
        ///
        /// <typeparam name="T">Type of the property.</typeparam>
        /// <param name="item">Object from which the property value is returned.</param>
        /// <param name="propertyName">The name of the property.</param>
        /// <param name="bindingFlags">Optional binding flags to use during reflection operations.</param>
        /// <returns>
        /// The value of the property.
        /// </returns>
        /// <exception cref="ArgumentNullException"><paramref name="item"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="propertyName"/> is whitespace.</exception>
        /// <exception cref="InvalidOperationException">The property was not found.</exception>
        /// <exception cref="InvalidCastException">The property is not of the specified type.</exception>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Justification = "This is a developer-facing string, not a user-facing string.")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Correct name.")]
        public static T GetPropertyValue<T>(
            this object item,
            string propertyName,
            BindingFlags bindingFlags = DefaultBindingFlags)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            var pi = item.GetType().GetPropertyInfo(propertyName, bindingFlags);
            if (pi == null)
            {
                throw new InvalidOperationException($"Property {propertyName} was not found on type {item.GetType().FullName}");
            }

            var ret = pi.GetPropertyValue<T>(item);
            return ret;
        }

        ///
        /// Sets a property value in a given Object.
        ///
        /// <typeparam name="T">Type of the property.</typeparam>
        /// <param name="type">Type to set property value on (will only set static properties).</param>
        /// <param name="propertyName">The name of the property to set.</param>
        /// <param name="value">Value to set.</param>
        /// <param name="bindingFlags">Optional binding flags to use during reflection operations.</param>
        /// <exception cref="ArgumentNullException"><paramref name="type"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="propertyName"/> is whitespace.</exception>
        /// <exception cref="InvalidOperationException">The property was not found.</exception>
        /// <exception cref="InvalidCastException">The property is not of type T.</exception>
        /// <remarks>
        /// adapted from: .
        /// </remarks>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Justification = "This is a developer-facing string, not a user-facing string.")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Correct name.")]
        public static void SetPropertyValue<T>(
            this Type type,
            string propertyName,
            T value,
            BindingFlags bindingFlags = DefaultBindingFlags)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var pi = type.GetPropertyInfo(propertyName, bindingFlags);
            if (pi == null)
            {
                throw new InvalidOperationException($"Property {propertyName} was not found on type {type.FullName}");
            }

            pi.SetPropertyValue(null, value);
        }

        ///
        /// Sets a property value in a given Object.
        ///
        /// <typeparam name="T">Type of the property.</typeparam>
        /// <param name="item">Object containing property to set.</param>
        /// <param name="propertyName">The name of the property to set.</param>
        /// <param name="value">Value to set.</param>
        /// <param name="bindingFlags">Optional binding flags to use during reflection operations.</param>
        /// <exception cref="ArgumentNullException"><paramref name="item"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="propertyName"/> is null.</exception>
        /// <exception cref="ArgumentException"><paramref name="propertyName"/> is whitespace.</exception>
        /// <exception cref="InvalidOperationException">The property was not found.</exception>
        /// <exception cref="InvalidCastException">The property is not of type T.</exception>
        /// <remarks>
        /// adapted from: .
        /// </remarks>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Justification = "This is a developer-facing string, not a user-facing string.")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "Correct name.")]
        public static void SetPropertyValue<T>(
            this object item,
            string propertyName,
            T value,
            BindingFlags bindingFlags = DefaultBindingFlags)
        {
            if (item == null)
            {
                throw new ArgumentNullException(nameof(item));
            }

            var pi = item.GetType().GetPropertyInfo(propertyName, bindingFlags);
            if (pi == null)
            {
                throw new InvalidOperationException($"Property {propertyName} was not found in Type {item.GetType().FullName}");
            }

            pi.SetPropertyValue(item, value);
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Justification = "This is a developer-facing string, not a user-facing string.")]
        private static T GetPropertyValue<T>(
            this PropertyInfo pi,
            object item)
        {
            if (pi == null)
            {
                throw new ArgumentException(nameof(PropertyInfo) + " must not be null", nameof(pi));
            }

            Type t = typeof(T);
            try
            {
                // can't solely rely on the ( T ) cast - if pi.GetValue returns null, then null can be casted to any reference type.
                if (!pi.PropertyType.IsAssignableFrom(t))
                {
                    throw new InvalidCastException($"Unable to cast object of type '{pi.PropertyType.FullName}' to type '{t.FullName}'.");
                }

                return (T)pi.GetValue(item, null);
            }
            catch (NullReferenceException)
            {
                // if result the value is null, then attempt to cast to value type will result in NullReferenceException
                throw new InvalidCastException($"Unable to cast object of type '{pi.PropertyType.FullName}' to type '{t.FullName}'.");
            }
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider", MessageId = "System.String.Format(System.String,System.Object,System.Object)", Justification = "This is a developer-facing string, not a user-facing string.")]
        private static void SetPropertyValue<T>(
            this PropertyInfo pi,
            object item,
            T value)
        {
            if (pi == null)
            {
                throw new ArgumentException(nameof(PropertyInfo) + " must not be null", nameof(pi));
            }

            try
            {
                pi.SetValue(item, value, null);
            }
            catch (ArgumentException ex)
            {
                throw new InvalidCastException(ex.Message);
            }
        }

        private static PropertyInfo GetPropertyInfo(
            this Type type,
            string propertyName,
            BindingFlags bindingFlags)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            if (propertyName == null)
            {
                throw new ArgumentNullException(nameof(propertyName));
            }

            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentException("The name of the property is whitespace.", nameof(propertyName));
            }

            PropertyInfo pi = null;

            while ((pi == null) && (type != null))
            {
                pi = type.GetProperty(propertyName, bindingFlags);
                type = type.BaseType;
            }

            return pi;
        }
    }
}


text:
package org.wso2.developerstudio.eclipse.esb.core.internal.impl;

import org.wso2.developerstudio.eclipse.esb.core.interfaces.ISequenceProvider;
import org.wso2.developerstudio.eclipse.esb.core.interfaces.ISequenceProviderData;

public class SequenceProviderDataImpl implements ISequenceProviderData{
	private String id;
	private String name;
	private ISequenceProvider provider;

	public String getText() {
		return getName();
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setProvider(ISequenceProvider provider) {
		this.provider = provider;
	}

	public ISequenceProvider getProvider() {
		return provider;
	}

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias alias="Person" type="com.github.rbuck.retry.samples.pojo.Person"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/github/rbuck/retry/samples/mybatis/mapper/Person.xml"/>
    </mappers>
</configuration>


text:
<?php
namespace Oro\Bundle\DistributionBundle\Command;

use Composer\Package\PackageInterface;
use Oro\Bundle\DistributionBundle\Console\Grid;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class ListAvailablePackagesCommand extends ContainerAwareCommand
{
    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this
            ->setName('oro:package:available')
            ->setDescription('List of available packages');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var PackageInterface[] $availablePackages */
        $availablePackages = $this->getContainer()->get('oro_distribution.package_manager')->getAvailable();

        $grid = new Grid(2, [':']);
        foreach ($availablePackages as $package) {
            $grid->addRow([$package->getName(), $package->getPrettyVersion()]);
        }

        $output->writeln($grid->render());
    }
}


text:
ImagesEngine::Engine.routes.draw do root to: 'dashboard#index'

  get "dashboard/index"

end


text:
<!DOCTYPE html>

		<meta charset="utf-8">
		<title>{% block title %}{% endblock %}</title>
		<link
			type="text/css"
			href="{{ROOT}}css/obscure.css"
			rel="stylesheet">
		<link
			href="https://fonts.googleapis.com/css?family=Inconsolata"
			rel="stylesheet">
		<link
			type="text/css"
			href="{{ROOT}}css/syntax.css"
			rel="stylesheet">
			<link rel="icon" href="{{ROOT}}img/favicon.ico">

			django-zeropass

				About

				License

				Source Code

				Build Status

				Installation

				Configuration

				Signals & Receivers

				Customising Emails

				Directional Logins

				Clearing Up Expired Tokens

				Email Deliverability

				Bugs & Errors

{% block content %}

{% endblock %}


text:
package by.post.control.ui.dialogs;

import by.post.control.db.TableType;
import by.post.control.events.RootEventTarget;
import by.post.control.events.TableSelectionEvent;
import by.post.control.search.Search;
import by.post.data.Table;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.util.Duration;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author Dmitriy V.Yefremov
 */
public class SearchToolDialogController {

    @FXML
    private TextField searchField;
    @FXML
    private ProgressBar progress;
    @FXML
    private Label progressLabel;
    @FXML
    private DialogPane dialogPane;
    @FXML
    private ListView listView;
    @FXML
    private Label timeValueLabel;
    @FXML
    private Label timeLabel;
    @FXML
    private ButtonType cancelButton;
    @FXML
    private ButtonType searchButton;
    @FXML
    private ComboBox<String> comboBox;

    private boolean searchRunning;
    private Search search;
    //It is used to display the time spent on search
    private Timeline timeline;
    private long startSearchTime;
    private Map<String, Table> tables;

    public SearchToolDialogController() {

    }

    /**
     * Action for close dialog request or cancel button
     */
    public void onCloseRequest() {
        setProgressVisible(false);
        search.cancel();
    }

    /**
     * Action for Enter key
     */
    @FXML
    private void onKeyReleased(KeyEvent event) {

        if (event.getCode() == KeyCode.ENTER) {
            search();
        }
    }

    /**
     * ListView actions for found tables
     *
     * @param event
     */
    @FXML
    private void onListMouseClick(MouseEvent event) throws IOException {

        if (event.getClickCount() == 2) {
            selectItem();
        }
    }

    @FXML
    private void onListKeyReleased(KeyEvent event) throws IOException {

        if (event.getCode() == KeyCode.ENTER) {
            selectItem();
        }
    }

    @FXML
    private void onComboBoxAction() {
        Platform.runLater(() -> {
            if (comboBox.getValue() != null) {
                searchField.setText(comboBox.getValue());
            }
            comboBox.getSelectionModel().clearSelection();
        });
    }

    @FXML
    private void initialize() {

        tables = new HashMap<>();
        search = ServiceLoader.load(Search.class).iterator().next();
        dialogPane.setExpandableContent(null);

        timeline = new Timeline(new KeyFrame(Duration.seconds(0), event -> {
            if (searchRunning) {
                timeValueLabel.setText((System.currentTimeMillis() - startSearchTime) / 1000 + "s");
            }
        }), new KeyFrame(Duration.seconds(1)));

        timeline.setCycleCount(Animation.INDEFINITE);
        //Adding filter on cancel button click
        dialogPane.lookupButton(cancelButton).addEventFilter(ActionEvent.ACTION, event -> {
            onCloseRequest();
            event.consume();
        });

        dialogPane.lookupButton(searchButton).addEventFilter(ActionEvent.ACTION, event -> {
            search();
            event.consume();
        });
    }

    private void search() {

        String searchText = searchField.getText();

        if (searchRunning || searchText.isEmpty()) {
            String error = searchRunning ? "Search is already running!" : "Blank query";
            new Alert(Alert.AlertType.ERROR, error).showAndWait();
            return;
        }

        updateComboBox(searchText);
        search.cancel();
        setProgressVisible(true);
        dialogPane.setExpanded(false);
        dialogPane.setExpandableContent(null);

        Task<Boolean> task = new Task<Boolean>() {
            @Override
            protected Boolean call() throws Exception {
                Collection<Table> founded = search.search(searchText);
                tables.clear();
                Platform.runLater(() -> {
                    listView.getItems().clear();
                    founded.forEach(t -> {
                        listView.getItems().add(t.getName());
                        tables.put(t.getName(), t);
                    });
                });

                return !tables.isEmpty();
            }
        };

        task.setOnSucceeded(event -> {
            dialogPane.setExpandableContent(listView);
            dialogPane.setExpanded(true);
            setProgressVisible(false);
            timeline.stop();
        });

        Thread thread = new Thread(task);
        thread.setDaemon(true);
        thread.start();

        startSearchTime = System.currentTimeMillis();
        timeline.playFromStart();
    }

    /**
     * Updating and storing search requests in combobox
     *
     * @param searchText
     */
    private void updateComboBox(String searchText) {

        if (!comboBox.getItems().contains(searchText)) {
            Platform.runLater(() -> comboBox.getItems().add(searchText));
        }
    }

    /**
     * @param visible
     */
    private void setProgressVisible(boolean visible) {

        progress.setVisible(visible);
        progress.setDisable(!visible);
        progressLabel.setVisible(visible);
        searchRunning = visible;
        //For first run
        timeLabel.setVisible(visible);
        timeValueLabel.setVisible(visible);
    }

    /**
     * Select item in table tree by table name
     */
    private void selectItem() throws IOException {

        Table table = tables.get(String.valueOf(listView.getSelectionModel().getSelectedItem()));

        if (table != null) {
            table.setType(TableType.TABLE);
            Event.fireEvent(RootEventTarget.TARGET, new TableSelectionEvent(table));
        }
    }
}


text:
/**
 * Package for test task chapter_009.
 *
 * @author apermyakov
 * @version 1.0
 * @since 19.12.2017
 */
package ru.apermyakov.servlets.testtask;


text:
<?xml version="1.0"?>
<!DOCTYPE display PUBLIC "-//Liferay//DTD Display 6.1.0//EN" "http://www.liferay.com/dtd/liferay-display_6_1_0.dtd">

<display>
	<category name="category.verce">
		<portlet id="dispel-client" />
	</category>
</display>


text:
/* This is always re-included to allow for prefixing the symbol names. */
#include <ironbee/module_sym.h>

#ifndef _IB_MODULE_H_
#define _IB_MODULE_H_

/**
 * @file
 * @brief IronBee --- Module
 *
 * @author Brian Rectanus <brectanus@qualys.com>
 * @author Christopher Alfeld <calfeld@qualys.com>
 */

#include <ironbee/action.h>
#include <ironbee/build.h>
#include <ironbee/config.h>
#include <ironbee/operator.h>
#include <ironbee/types.h>

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup IronBeeModule Module
 * @ingroup IronBee
 *
 * Modules add functionality to IronBee.
 *
 * @{
 */

/**
 * Initialize values for dynamic modules created with ib_module_create().
 *
 * @param[in] m                   Module
 * @param[in] xfilename           Module code filename
 * @param[in] xdata               Module data
 * @param[in] xib                 Engine handle
 * @param[in] xname               Module name
 * @param[in] xgcdata             Global config data
 * @param[in] xgclen              Global config data length
 * @param[in] xfn_cfg_copy        Config copy function
 * @param[in] xcbdata_cfg_copy    Config copy function callback data
 * @param[in] xcm_init            Configuration field map
 * @param[in] xdm_init            Config directive map
 * @param[in] xfn_init            Initialize function
 * @param[in] xcbdata_init        Initialize function callback data
 * @param[in] xfn_fini            Finish function
 * @param[in] xcbdata_fini        Finish function callback data
 */
#define IB_MODULE_INIT_DYNAMIC(m, xfilename, xdata, xib, xname, xgcdata, xgclen, xfn_cfg_copy, xcbdata_cfg_copy, xcm_init, xdm_init, xfn_init, xcbdata_init, xfn_fini, xcbdata_fini) \
    do { \
        (m)->vernum             = IB_VERNUM; \
        (m)->abinum             = IB_ABINUM; \
        (m)->version            = IB_VERSION; \
        (m)->filename           = xfilename; \
        (m)->data               = xdata; \
        (m)->ib                 = xib; \
        (m)->idx                = 0; \
        (m)->name               = xname; \
        (m)->gcdata             = xgcdata; \
        (m)->gclen              = xgclen; \
        (m)->fn_cfg_copy        = xfn_cfg_copy; \
        (m)->cbdata_cfg_copy    = xcbdata_cfg_copy; \
        (m)->cm_init            = xcm_init; \
        (m)->dm_init            = xdm_init; \
        (m)->fn_init            = xfn_init; \
        (m)->cbdata_init        = xcbdata_init; \
        (m)->fn_fini            = xfn_fini; \
        (m)->cbdata_fini        = xcbdata_fini; \
    } while (0)

/** Defaults for all module structure headers */
#define IB_MODULE_HEADER_DEFAULTS     IB_VERNUM, \
                                      IB_ABINUM, \
                                      IB_VERSION, \
                                      __FILE__, \
                                      NULL, \
                                      NULL, \
                                      0

/** Module config structure, size, and default handlers */
#define IB_MODULE_CONFIG(ptr)         (ptr), (sizeof(*(ptr))), NULL, NULL

/** Used to signify that there is no config structure for the module. */
#define IB_MODULE_CONFIG_NULL         NULL, 0, NULL, NULL

/**
 * Function which is exported in an IronBee module to return the address
 * to the module structure used to load the module.
 *
 * This module function is declared by IB_MODULE_DECLARE and defined
 * by IB_MODULE_INIT. The address of this function is looked up by
 * name (IB_MODULE_SYM) when the module is loaded and called to fetch
 * the address of the module structure built with IB_MODULE_INIT.
 *
 * @param ib Engine handle
 * @returns Address of the module structure
 */
typedef const ib_module_t *(*ib_module_sym_fn)(ib_engine_t* ib);

/**
 * Function to handle copying configuration data.
 *
 * This is called when configuration data needs to be copied from a parent
 * context to a child context.  If NULL, it defaults to memcpy.
 *
 * @param[in] ib     Engine handle
 * @param[in] m      Module
 * @param[in] dst    Destination of data.
 * @param[in] src    Source of data.
 * @param[in] length Length of data.
 * @param[in] cbdata Callback data
 *
 * @returns Status code
 */
typedef ib_status_t (*ib_module_fn_cfg_copy_t)(
    ib_engine_t *ib,
    ib_module_t *m,
    void        *dst,
    const void  *src,
    size_t       length,
    void        *cbdata
);

/**
 * Function to initialize a module.
 *
 * This is called when the module is loaded.
 *
 * @param[in] ib     Engine handle
 * @param[in] m      Module
 * @param[in] cbdata Callback data
 *
 * @returns Status code
 */
typedef ib_status_t (*ib_module_fn_init_t)(
    ib_engine_t *ib,
    ib_module_t *m,
    void        *cbdata
);

/**
 * Function to finish a module.
 *
 * This is called when the module is unloaded.
 *
 * @param[in] ib     Engine handle
 * @param[in] m      Module
 * @param[in] cbdata Callback data
 *
 * @returns Status code
 */
typedef ib_status_t (*ib_module_fn_fini_t)(
    ib_engine_t *ib,
    ib_module_t *m,
    void        *cbdata
);

/**
 * Additional functionality for IronBee.
 *
 * A module provides additional functionality to IronBee.  It can register
 * configuration values and directives, hook into events, and provide
 * functions for other modules.
 */
struct ib_module_t {
    /* Header */
    uint32_t     vernum;      /**< Engine version number */
    uint32_t     abinum;      /**< Engine ABI Number */
    const char  *version;     /**< Engine version string */
    const char  *filename;    /**< Module code filename */
    void        *data;        /**< Module data */
    ib_engine_t *ib;          /**< Engine */
    size_t       idx;         /**< Module index */

    /* Module Config */
    const char *name; /**< Module name */

    void                    *gcdata;          /**< Global config data */
    size_t                   gclen;           /**< Global config data length */
    ib_module_fn_cfg_copy_t  fn_cfg_copy;     /**< Config copy handler */
    void                    *cbdata_cfg_copy; /**< Config copy data */
    const ib_cfgmap_init_t  *cm_init;         /**< Module config mapping */

    const ib_dirmap_init_t *dm_init; /**< Module directive mapping */

    /* Functions */
    ib_module_fn_init_t         fn_init;         /**< Module init */
    void                       *cbdata_init;     /**< fn_init callback data */
    ib_module_fn_fini_t         fn_fini;         /**< Module finish */
    void                       *cbdata_fini;     /**< fn_init callback data */
};

/**
 * Duplicate and add a module handle to the given engine.
 *
 * @param[in] m  Loaded module handle.
 * @param[in] ib Engine handle
 *
 * @returns Status code
 */
ib_status_t DLL_PUBLIC ib_module_register(
    const ib_module_t *m,
    ib_engine_t       *ib
);

/**
 * Create a module structure.
 *
 * Use this to dynamically build modules.
 *
 * @param[out] pm Address which module structure will be written
 * @param[in]  ib Engine handle
 *
 * @returns Status code
 */
ib_status_t DLL_PUBLIC ib_module_create(
    ib_module_t **pm,
    ib_engine_t  *ib
);

/**
 * Load and initialize an engine module.
 *
 * This causes the module init() function to be called.
 *
 * @param[in]  ib   Engine handle
 * @param[in]  file Filename of the module
 *
 * @returns Status code
 */
ib_status_t DLL_PUBLIC ib_module_load(
    ib_engine_t *ib,
    const char  *file
);

/**
 * Load a module DSO but do not initialize; instead return symbol.
 *
 * @param[out] psym Address to which module symbol is written
 * @param[in]  ib   Engine handle
 * @param[in]  file Filename of the module
 *
 * @returns Status code
 */
ib_status_t DLL_PUBLIC ib_module_file_to_sym(
    ib_module_sym_fn *psym,
    ib_engine_t      *ib,
    const char       *file
);

/**
 * Initialize an engine module from a symbol.
 *
 * This causes the module init() function to be called.
 *
 * @param[in]  ib  Engine handle
 * @param[in]  sym Module symbol.
 *
 * @returns Status code
 */
ib_status_t DLL_PUBLIC ib_module_load_from_sym(
    ib_engine_t       *ib,
    ib_module_sym_fn   sym
);

/**
 * Initialize module configuration for main context.
 *
 * This routine is an alternative to setting an initial structure in the
 * module declaration.  It allows modules to setup their initial configuration
 * data in their initialization functions.
 *
 * @param module Module to initialize configuration data for.
 * @param cfg Configuration data.
 * @param cfg_length Length of configuration data.
 *
 * @returns
 * - IB_OK on success.
 * - IB_EINVAL if @a m already has configuration data.
 */
ib_status_t DLL_PUBLIC ib_module_config_initialize(
    ib_module_t *module,
    void *cfg,
    size_t cfg_length);

/**
 * @} IronBeeModule
 */

#ifdef __cplusplus
}
#endif

#endif /* _IB_MODULE_H_ */


text:
const _send = require('./send');

module.exports = function (request, response) {
  response.send = _send;
};


text:
package org.wso2.carbon.identity.mgt.policy.password;

import junit.framework.TestCase;

/* Policy to check using username as password. */
public class DefaultPasswordNamePolicyTest extends TestCase {

	DefaultPasswordNamePolicy policy = new DefaultPasswordNamePolicy();

	public void testUsernameSameasPassword(){

		assertFalse("username same as password failed", policy.enforce("password", "password"));
	}

	public void testDifferentUsername() {

		assertTrue("username different than password failed", policy.enforce("password","username"));
	}

	public void testNullInput() {

		assertTrue("null input failed", policy.enforce(null));
	}
}


text:
'use strict';

exports.__esModule = true;

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _2 = require('./util/_');

var _3 = _interopRequireDefault(_2);

var _classnames = require('classnames');

var _classnames2 = _interopRequireDefault(_classnames);

var _propTypes = require('./util/propTypes');

var _propTypes2 = _interopRequireDefault(_propTypes);

var _widgetHelpers = require('./util/widgetHelpers');

var _dataHelpers = require('./util/dataHelpers');

var _interaction = require('./util/interaction');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var optionId = function optionId(id, idx) {
  return id + '__option__' + idx;
};

exports.default = _react2.default.createClass({
  displayName: 'MultiselectTagList',

  mixins: [require('./mixins/PureRenderMixin'), require('./mixins/AriaDescendantMixin')()],

  propTypes: {
    value: _react2.default.PropTypes.array,
    focused: _react2.default.PropTypes.number,

    valueField: _react2.default.PropTypes.string,
    textField: _propTypes2.default.accessor,

    onDelete: _react2.default.PropTypes.func.isRequired,
    valueComponent: _react2.default.PropTypes.func,

    disabled: _propTypes2.default.disabled.acceptsArray,
    readOnly: _propTypes2.default.readOnly.acceptsArray
  },

  getDefaultProps: function getDefaultProps() {
    return {
      ariaActiveDescendantKey: 'taglist'
    };
  },
  componentDidUpdate: function componentDidUpdate() {
    var focused = this.props.focused,
        activeId = optionId((0, _widgetHelpers.instanceId)(this), focused);

    this.ariaActiveDescendant(focused == null || (0, _interaction.isDisabledItem)(focused, this.props) ? null : activeId);
  },
  render: function render() {
    var _this = this;

    var _props = this.props,
        focused = _props.focused,
        value = _props.value,
        textField = _props.textField,
        ValueComponent = _props.valueComponent;

    var id = (0, _widgetHelpers.instanceId)(this);
    var props = _3.default.omitOwnProps(this);

    return _react2.default.createElement(
      'ul',
      _extends({}, props, {
        role: 'listbox',
        tabIndex: '-1',
        className: 'rw-multiselect-taglist'
      }),
      value.map(function (item, i) {
        var isDisabled = (0, _interaction.isDisabledItem)(item, _this.props),
            isReadonly = (0, _interaction.isReadOnlyItem)(item, _this.props),
            isFocused = !isDisabled && focused === i,
            currentID = optionId(id, i);

        return _react2.default.createElement(
          'li',
          {
            key: i,
            id: currentID,
            tabIndex: '-1',
            role: 'option',
            className: (0, _classnames2.default)({
              'rw-state-focus': isFocused,
              'rw-state-disabled': isDisabled,
              'rw-state-readonly': isReadonly
            })
          },
          ValueComponent ? _react2.default.createElement(ValueComponent, { item: item }) : (0, _dataHelpers.dataText)(item, textField),
          _react2.default.createElement(
            'span',
            {
              tabIndex: '-1',
              onClick: !(isDisabled || isReadonly) ? _this._delete.bind(null, item) : undefined,
              'aria-disabled': isDisabled,
              'aria-label': 'Unselect',
              disabled: isDisabled
            },
            _react2.default.createElement(
              'span',
              { className: 'rw-tag-btn', 'aria-hidden': 'true' },
              '\xD7'
            )
          )
        );
      })
    );
  },
  _delete: function _delete(val) {
    this.props.onDelete(val);
  },
  remove: function remove(idx) {
    var val = this.props.value[idx];

    if (val && !((0, _interaction.isDisabledItem)(val, this.props) || (0, _interaction.isReadOnlyItem)(val, this.props))) this.props.onDelete(val);
  },
  removeNext: function removeNext() {
    var val = this.props.value[this.props.value.length - 1];

    if (val && !((0, _interaction.isDisabledItem)(val, this.props) || (0, _interaction.isReadOnlyItem)(val, this.props))) this.props.onDelete(val);
  },
  clear: function clear() {
    this.setState({ focused: null });
  },
  first: function first() {
    var idx = 0,
        value = this.props.value,
        l = value.length;

    while (idx < l && (0, _interaction.isDisabledItem)(value[idx], this.props)) {
      idx++;
    }return idx !== l ? idx : null;
  },
  last: function last() {
    var value = this.props.value,
        idx = value.length - 1;

    while (idx > -1 && (0, _interaction.isDisabledItem)(value[idx], this.props)) {
      idx--;
    }return idx >= 0 ? idx : null;
  },
  next: function next(current) {
    var nextIdx = current + 1,
        value = this.props.value,
        l = value.length;

    while (nextIdx < l && (0, _interaction.isDisabledItem)(nextIdx, this.props)) {
      nextIdx++;
    }if (current === null || nextIdx >= l) return null;

    return nextIdx;
  },
  prev: function prev(current) {
    var nextIdx = current,
        value = this.props.value;

    if (nextIdx === null || nextIdx === 0) nextIdx = value.length;

    nextIdx--;

    while (nextIdx > -1 && (0, _interaction.isDisabledItem)(value[nextIdx], this.props)) {
      nextIdx--;
    }return nextIdx >= 0 ? nextIdx : null;
  }
});
module.exports = exports['default'];


text:
package org.keycloak.services.clientregistration.policy.impl;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

import org.keycloak.component.ComponentModel;
import org.keycloak.models.ClientScopeModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.ProviderConfigProperty;
import org.keycloak.services.clientregistration.policy.AbstractClientRegistrationPolicyFactory;
import org.keycloak.services.clientregistration.policy.ClientRegistrationPolicy;

/**
 * @author Marek Posolda
 */
public class ClientScopesClientRegistrationPolicyFactory extends AbstractClientRegistrationPolicyFactory {

    private List<ProviderConfigProperty> configProperties;

    // Keeping the name for backwards compatibility
    public static final String PROVIDER_ID = "allowed-client-templates";

    public static final String ALLOWED_CLIENT_SCOPES = "allowed-client-scopes";

    public static final String ALLOW_DEFAULT_SCOPES = "allow-default-scopes";

    @Override
    public ClientRegistrationPolicy create(KeycloakSession session, ComponentModel model) {
        return new ClientScopesClientRegistrationPolicy(session, model);
    }

    @Override
    public String getHelpText() {
        return "When present, it allows to specify whitelist of client scopes, which will be allowed in representation of registered (or updated) client";
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties(KeycloakSession session) {
        List<ProviderConfigProperty> configProps = new LinkedList<>();

        ProviderConfigProperty property;
        property = new ProviderConfigProperty();
        property.setName(ALLOWED_CLIENT_SCOPES);
        property.setLabel("allowed-client-scopes.label");
        property.setHelpText("allowed-client-scopes.tooltip");
        property.setType(ProviderConfigProperty.MULTIVALUED_LIST_TYPE);

        if (session != null) {
            property.setOptions(getClientScopes(session));
        }
        configProps.add(property);

        property = new ProviderConfigProperty();
        property.setName(ALLOW_DEFAULT_SCOPES);
        property.setLabel("allow-default-scopes.label");
        property.setHelpText("allow-default-scopes.tooltip");
        property.setType(ProviderConfigProperty.BOOLEAN_TYPE);
        property.setDefaultValue(true);
        configProps.add(property);

        configProperties = configProps;
        return configProperties;
    }

    private List<String> getClientScopes(KeycloakSession session) {
        RealmModel realm = session.getContext().getRealm();
        if (realm == null) {
            return Collections.emptyList();
        } else {
            return realm.getClientScopesStream().map(ClientScopeModel::getName).collect(Collectors.toList());
        }
    }

    @Override
    public List<ProviderConfigProperty> getConfigProperties() {
        return getConfigProperties(null);
    }

    @Override
    public String getId() {
        return PROVIDER_ID;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Student Travel Support for NuFact09 Workshop; Chicago, IL</AwardTitle>
    <AwardEffectiveDate>09/01/2009</AwardEffectiveDate>
    <AwardExpirationDate>08/31/2010</AwardExpirationDate>
    <AwardAmount>5000</AwardAmount>
    <AwardInstrument>
      <Value>Standard Grant</Value>
    </AwardInstrument>
    <Organization>
      03010000
      <Directorate>
        <LongName>Direct For Mathematical & Physical Scien</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Physics</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>James Joseph Reidy</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>This award provides partial support for five students and postdocs to participate in the International Workshops on Neutrino Factories, Superbeams and Beta Beams (NuFact09), Chicago, Illinois, July 20-25, 2009. The NuFact workshop series is the only conference series dedicated to the future of the field of neutrino oscillations and presents a unique opportunity for young scientists to participate in discussions with world experts in this cutting edge research.</AbstractNarration>
    <MinAmdLetterDate>08/30/2009</MinAmdLetterDate>
    <MaxAmdLetterDate>08/30/2009</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0935306</AwardID>
    <Investigator>
      <FirstName>Daniel</FirstName>
      <LastName>Kaplan</LastName>
      <EmailAddress>kaplan@iit.edu</EmailAddress>
      <StartDate>08/30/2009</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Yagmur</FirstName>
      <LastName>Torun</LastName>
      <EmailAddress>torun@iit.edu</EmailAddress>
      <StartDate>08/30/2009</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Investigator>
      <FirstName>Zack</FirstName>
      <LastName>Sullivan</LastName>
      <EmailAddress>zack.sullivan@iit.edu</EmailAddress>
      <StartDate>08/30/2009</StartDate>
      <EndDate/>
      <RoleCode>Co-Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Illinois Institute of Technology</Name>
      <CityName>Chicago</CityName>
      <ZipCode>606163717</ZipCode>
      <PhoneNumber>3125673035</PhoneNumber>
      <StreetAddress>10 West 35th Street</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>Illinois</StateName>
      <StateCode>IL</StateCode>
    </Institution>
    <FoaInformation>
      0000099
      <Name>Other Applications NEC</Name>
    </FoaInformation>
  </Award>
</rootTag>


text:
<?php

namespace AlchemyAPI\Test;

use AlchemyAPI\AlchemyAPI;

class AlchemyAPITest extends \PHPUnit_Framework_TestCase
{
    public function setUp()
    {
        parent::setUp();
        $this->alchemy = $this->getMock('AlchemyAPI\AlchemyAPI', ['query'], ['nokey']);
        $this->response = $this->getMock('GuzzleHttp\Message\Response', [], [200]);
        $this->endpoint = 'https://access.alchemyapi.com/calls/';
    }

    public function tearDown()
    {
        parent::tearDown();
        unset(
            $this->alchemy,
            $this->response,
            $this->endpoint
        );
    }

    public function testUrlKeywords()
    {
        $url = $this->endpoint . 'url/URLGetRankedKeywords';

        $params = [
            'apikey' => 'nokey',
            'outputMode' => 'json',
            'keywordExtractMode' => 'normal',
            'maxRetrieve' => 50,
            'sentiment' => false,
            'showSourceText' => false,
            'url' => 'http://example.com'
        ];

        $this->alchemy->expects($this->once())
            ->method('query')
            ->with($url, $params)
            ->will($this->returnValue($this->response));

        $this->alchemy->keywords('url', 'http://example.com');
    }

    public function testHtmlKeywords()
    {
        $url = $this->endpoint . 'html/HTMLGetRankedKeywords';

        $params = [
            'apikey' => 'nokey',
            'outputMode' => 'json',
            'keywordExtractMode' => 'normal',
            'maxRetrieve' => 50,
            'sentiment' => false,
            'showSourceText' => false,
            'html' => ''
        ];

        $this->alchemy->expects($this->once())
            ->method('query')
            ->with($url, $params)
            ->will($this->returnValue($this->response));

        $this->alchemy->keywords('html', '');
    }

    public function testTextKeywords()
    {
        $url = $this->endpoint . 'text/TextGetRankedKeywords';

        $params = [
            'apikey' => 'nokey',
            'outputMode' => 'json',
            'keywordExtractMode' => 'normal',
            'maxRetrieve' => 50,
            'sentiment' => false,
            'showSourceText' => false,
            'text' => 'lorem ipsum'
        ];

        $this->alchemy->expects($this->once())
            ->method('query')
            ->with($url, $params)
            ->will($this->returnValue($this->response));

        $this->alchemy->keywords('text', 'lorem ipsum');
    }

    public function testImageImageKeywords()
    {
        $url = $this->endpoint . 'image/ImageGetRankedImageKeywords';
        $url .= '?' . http_build_query([
            'apikey' => 'nokey',
            'outputMode' => 'json',
            'extractMode' => 'trust-metadata'
        ]);

        $params = 'test.png';

        $this->alchemy->expects($this->once())
            ->method('query')
            ->with($url, $params)
            ->will($this->returnValue($this->response));

        $this->alchemy->image_keywords('image', 'test.png');
    }

}


text:
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
	[ActionCategory(ActionCategory.StateMachine)]
    [ActionTarget(typeof(PlayMakerFSM), "gameObject,fsmName")]
	[Tooltip("Set the value of a Vector3 Variable in another FSM.")]
	public class SetFsmVector3 : FsmStateAction
	{
		[RequiredField]
        [Tooltip("The GameObject that owns the FSM.")]
		public FsmOwnerDefault gameObject;

		[UIHint(UIHint.FsmName)]
		[Tooltip("Optional name of FSM on Game Object")]
		public FsmString fsmName;

		[RequiredField]
		[UIHint(UIHint.FsmVector3)]
        [Tooltip("The name of the FSM variable.")]
		public FsmString variableName;

		[RequiredField]
        [Tooltip("Set the value of the variable.")]
		public FsmVector3 setValue;

        [Tooltip("Repeat every frame. Useful if the value is changing.")]
        public bool everyFrame;

		GameObject goLastFrame;
		string fsmNameLastFrame;

		PlayMakerFSM fsm;

		public override void Reset()
		{
			gameObject = null;
			fsmName = "";
			setValue = null;
		}

		public override void OnEnter()
		{
			DoSetFsmVector3();

			if (!everyFrame)
				Finish();
		}

		void DoSetFsmVector3()
		{
			if (setValue == null)
			{
			    return;
			}

			var go = Fsm.GetOwnerDefaultTarget(gameObject);
			if (go == null)
			{
			    return;
			}

			// FIX: must check as well that the fsm name is different.
			if (go != goLastFrame || fsmName.Value != fsmNameLastFrame)
			{
				goLastFrame = go;
				fsmNameLastFrame = fsmName.Value;
				// only get the fsm component if go or fsm name has changed

				fsm = ActionHelpers.GetGameObjectFsm(go, fsmName.Value);
			}

			if (fsm == null)
			{
                LogWarning("Could not find FSM: " + fsmName.Value);
			    return;
			}

			var fsmVector3 = fsm.FsmVariables.GetFsmVector3(variableName.Value);

			if (fsmVector3 != null)
			{
                fsmVector3.Value = setValue.Value;
			}
            else
            {
                LogWarning("Could not find variable: " + variableName.Value);
            }
		}

		public override void OnUpdate()
		{
			DoSetFsmVector3();
		}

	}
}


text:
module Fog
  module Volume
    class OpenStack
      class Real
        def get_quota_defaults(tenant_id)
          request(
            :expects  => 200,
            :method   => 'GET',
            :path     => "/os-quota-sets/#{tenant_id}/defaults"
          )
        end
      end

      class Mock
        def get_quota_defaults(tenant_id)
          response = Excon::Response.new
          response.status = 200
          response.body = {
            'quota_set' => self.data[:quota].merge({'id' => tenant_id})
          }
          response
        end
      end
    end
  end
end


text:
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-comp-2686',
  templateUrl: './comp-2686.component.html',
  styleUrls: ['./comp-2686.component.css']
})
export class Comp2686Component implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}