text:
<?php

/**
 * @namespace
 */
namespace ZendTest\Tag\Cloud;
use Zend\Tag;
use Zend\Tag\Cloud;
use Zend\Loader\PluginLoader;
use ZendTest\Tag\Cloud\TestAsset;

/**
 * @category   Zend
 * @package    Zend_Tag
 * @subpackage UnitTests
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 * @group      Zend_Tag
 * @group      Zend_Tag_Cloud
 */
class CloudTest extends \PHPUnit_Framework_TestCase
{

    public function testGetAndSetItemList()
    {
        $cloud = $this->_getCloud();
        $this->assertTrue($cloud->getItemList() instanceof Tag\ItemList);

        $cloud->setItemList(new ItemListDummy);
        $this->assertTrue($cloud->getItemList() instanceof ItemListDummy);
    }

    public function testSetCloudDecoratorViaArray()
    {
        $cloud = $this->_getCloud();

        $cloud->setCloudDecorator(array('decorator' => 'CloudDummy', 'options' => array('foo' => 'bar')));
        $this->assertTrue($cloud->getCloudDecorator() instanceof TestAsset\CloudDummy);
        $this->assertEquals('bar', $cloud->getCloudDecorator()->getFoo());
    }

    public function testGetAndSetCloudDecorator()
    {
        $cloud = $this->_getCloud();
        $this->assertTrue($cloud->getCloudDecorator() instanceof \Zend\Tag\Cloud\Decorator\HTMLCloud);

        $cloud->setCloudDecorator(new TestAsset\CloudDummy());
        $this->assertTrue($cloud->getCloudDecorator() instanceof TestAsset\CloudDummy);
    }

    public function testSetInvalidCloudDecorator()
    {
        $cloud = $this->_getCloud();

        try {
            $cloud->setCloudDecorator(new \stdClass());
            $this->fail('An expected Zend_Tag_Cloud_Exception was not raised');
        } catch (Cloud\Exception $e) {
            $this->assertEquals('Decorator is no instance of Zend_Tag_Cloud_Decorator_Cloud', $e->getMessage());
        }
    }

    public function testSetTagDecoratorViaArray()
    {
        $cloud = $this->_getCloud();

        $cloud->setTagDecorator(array('decorator' => 'TagDummy', 'options' => array('foo' => 'bar')));
        $this->assertTrue($cloud->getTagDecorator() instanceof TestAsset\TagDummy);
        $this->assertEquals('bar', $cloud->getTagDecorator()->getFoo());
    }

    public function testGetAndSetTagDecorator()
    {
        $cloud = $this->_getCloud();
        $this->assertTrue($cloud->getTagDecorator() instanceof \Zend\Tag\Cloud\Decorator\HTMLTag);

        $cloud->setTagDecorator(new TestAsset\TagDummy());
        $this->assertTrue($cloud->getTagDecorator() instanceof TestAsset\TagDummy);
    }

    public function testSetInvalidTagDecorator()
    {
        $cloud = $this->_getCloud();

        try {
            $cloud->setTagDecorator(new \stdClass());
            $this->fail('An expected Zend_Tag_Cloud_Exception was not raised');
        } catch (Cloud\Exception $e) {
            $this->assertEquals('Decorator is no instance of Zend_Tag_Cloud_Decorator_Tag', $e->getMessage());
        }
    }

    public function testSetPrefixPathViaOptions()
    {
        $cloud = $this->_getCloud(array(
            'prefixPath' => array(
                'prefix' => 'ZendTest\Tag\Cloud\TestAsset',
                'path' => __DIR__ . '/TestAsset'
            ),
            'cloudDecorator' => array(
                'decorator' => 'CloudDummy1',
                'options'   => array(
                    'foo' => 'bar'
                )
            )
        ), false);

        $this->assertTrue($cloud->getCloudDecorator() instanceof TestAsset\CloudDummy1);
        $this->assertEquals('bar', $cloud->getCloudDecorator()->getFoo());
    }

    public function testSetPrefixPathsViaOptions()
    {
        $cloud = $this->_getCloud(array(
            'prefixPath' => array(
                array(
                    'prefix' => 'ZendTest\Tag\Cloud\TestAsset',
                    'path' => __DIR__ . '/TestAsset'
                )
            ),
            'cloudDecorator' => array(
                'decorator' => 'CloudDummy2',
                'options'   => array(
                    'foo' => 'bar'
                )
            )
        ), false);

        $this->assertTrue($cloud->getCloudDecorator() instanceof TestAsset\CloudDummy2);
        $this->assertEquals('bar', $cloud->getCloudDecorator()->getFoo());
    }

    public function testSetPrefixPathsSkip()
    {
        $cloud = $this->_getCloud(array(
            'prefixPath' => array(
                array(
                    'prefix' => 'foobar',
                )
            ),
        ), false);

        $this->assertEquals(1, count($cloud->getPluginLoader()->getPaths()));
    }

    public function testSetPluginLoader()
    {
        $loader = new PluginLoader(array('foo_' => 'bar/'));
        $cloud  = $this->_getCloud(array(), null);
        $cloud->setPluginLoader($loader);
        $paths  = $cloud->getPluginLoader()->getPaths();

        $this->assertEquals('bar/', $paths['foo_\\'][0]); // this might be an issue
    }

    public function testSetPluginLoaderViaOptions()
    {
        $loader = new PluginLoader(array('foo_' => 'bar/'));
        $cloud  = $this->_getCloud(array('pluginLoader' => $loader), null);
        $paths  = $cloud->getPluginLoader()->getPaths();

        $this->assertEquals('bar/', $paths['foo_\\'][0]); // this might be an issue
    }

    public function testAppendTagAsArray()
    {
        $cloud = $this->_getCloud();
        $list  = $cloud->getItemList();

        $cloud->appendTag(array('title' => 'foo', 'weight' => 1));

        $this->assertEquals('foo', $list[0]->getTitle());
    }

    public function testAppendTagAsItem()
    {
        $cloud = $this->_getCloud();
        $list  = $cloud->getItemList();

        $cloud->appendTag(new Tag\Item(array('title' => 'foo', 'weight' => 1)));

        $this->assertEquals('foo', $list[0]->getTitle());
    }

    public function testAppendInvalidTag()
    {
        $cloud = $this->_getCloud();

        try {
            $cloud->appendTag('foo');
            $this->fail('An expected Zend_Tag_Cloud_Exception was not raised');
        } catch (Cloud\Exception $e) {
            $this->assertEquals('Tag must be an instance of Zend_Tag_Taggable or an array', $e->getMessage());
        }
    }

    public function testSetTagsAsArray()
    {
        $cloud = $this->_getCloud();
        $list  = $cloud->getItemList();

        $cloud->setTags(array(array('title' => 'foo', 'weight' => 1),
                              array('title' => 'bar', 'weight' => 2)));

        $this->assertEquals('foo', $list[0]->getTitle());
        $this->assertEquals('bar', $list[1]->getTitle());
    }

    public function testSetTagsAsItem()
    {
        $cloud = $this->_getCloud();
        $list  = $cloud->getItemList();

        $cloud->setTags(array(new Tag\Item(array('title' => 'foo', 'weight' => 1)),
                              new Tag\Item(array('title' => 'bar', 'weight' => 2))));

        $this->assertEquals('foo', $list[0]->getTitle());
        $this->assertEquals('bar', $list[1]->getTitle());
    }

    public function testSetTagsMixed()
    {
        $cloud = $this->_getCloud();
        $list  = $cloud->getItemList();

        $cloud->setTags(array(array('title' => 'foo', 'weight' => 1),
                              new Tag\Item(array('title' => 'bar', 'weight' => 2))));

        $this->assertEquals('foo', $list[0]->getTitle());
        $this->assertEquals('bar', $list[1]->getTitle());
    }

    public function testSetInvalidTags()
    {
        $cloud = $this->_getCloud();

        try {
            $cloud->setTags(array('foo'));
            $this->fail('An expected Zend_Tag_Cloud_Exception was not raised');
        } catch (Cloud\Exception $e) {
            $this->assertEquals('Tag must be an instance of Zend_Tag_Taggable or an array', $e->getMessage());
        }
    }

    public function testConstructorWithArray()
    {
        $cloud = $this->_getCloud(array('tags' => array(array('title' => 'foo', 'weight' => 1))));
        $list  = $cloud->getItemList();

        $this->assertEquals('foo', $list[0]->getTitle());
    }

    public function testConstructorWithConfig()
    {
        $cloud = $this->_getCloud(new \Zend\Config\Config(array('tags' => array(array('title' => 'foo', 'weight' => 1)))));
        $list  = $cloud->getItemList();

        $this->assertEquals('foo', $list[0]->getTitle());
    }

    public function testSetOptions()
    {
        $cloud = $this->_getCloud();
        $cloud->setOptions(array('tags' => array(array('title' => 'foo', 'weight' => 1))));
        $list  = $cloud->getItemList();

        $this->assertEquals('foo', $list[0]->getTitle());
    }

    public function testSkipOptions()
    {
        $cloud = $this->_getCloud(array('options' => 'foobar'));
        // In case would fail due to an error
    }

    public function testRender()
    {
        $cloud    = $this->_getCloud(array('tags' => array(array('title' => 'foo', 'weight' => 1), array('title' => 'bar', 'weight' => 3))));
        $expected = '
'
                  . '
foo
 '
                  . '
bar
'
                  . '
';
        $this->assertEquals($expected, $cloud->render());
    }

    public function testRenderEmptyCloud()
    {
        $cloud = $this->_getCloud();
        $this->assertEquals('', $cloud->render());
    }

    public function testRenderViaToString()
    {
        $cloud = $this->_getCloud(array('tags' => array(array('title' => 'foo', 'weight' => 1), array('title' => 'bar', 'weight' => 3))));
        $expected = '
'
                  . '
foo
 '
                  . '
bar
'
                  . '
';
        $this->assertEquals($expected, (string) $cloud);
    }

    protected function _getCloud($options = null, $setPluginLoader = true)
    {
        $cloud = new Tag\Cloud($options);

        if ($setPluginLoader) {
            $cloud->getPluginLoader()->addPrefixPath('ZendTest\Tag\Cloud\TestAsset', __DIR__ . '/TestAsset');
        }

        return $cloud;
    }
}

class ItemListDummy extends Tag\ItemList {}


text:
namespace _09.Threeuple
{
    using System;

    public class StartUp
    {
        public static void Main()
        {
            for (int i = 0; i < 3; i++)
            {
                string[] input = Console.ReadLine()
                    .Split(' ');

                if (i == 0)
                {
                    string name = input[0] + " " + input[1];
                    string adress = input[2];
                    string town = input[3];
                    Threeuple<string, string, string> tuple = new Threeuple<string, string, string>(name, adress, town);

                    Console.WriteLine(tuple.ToString());
                }
                else if (i == 1)
                {
                    string name = input[0];
                    int beer = int.Parse(input[1]);
                    string drunkState = input[2];
                    bool isDrunk = drunkState == "drunk";
                    Threeuple<string, int, bool> tuple = new Threeuple<string, int, bool>(name, beer, isDrunk);

                    Console.WriteLine(tuple.ToString());
                }
                else
                {
                    string name = input[0];
                    double floatingNum = double.Parse(input[1]);
                    string bankName = input[2];
                    Threeuple<string, double, string> tuple = new Threeuple<string, double, string>(name, floatingNum, bankName);

                    Console.WriteLine(tuple.ToString());
                }
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
The Paratest task will run your PHPUnit tests in parallel.

***Composer***

```
composer require --dev brianium/paratest
```

***Config***

The task lives under the `paratest` namespace and has following configurable parameters:

```yaml
# grumphp.yml
parameters:
    tasks:
        paratest:
            processes: ~
            functional: ~
            group: []
            always_execute: false
            phpunit: null
            configuration: null
            runner: null
            debugger: null
            coverage-xml: null
            coverage-html: null
            log-junit: null
            testsuite: null
```

**processes**

*Default: null*

The number of test processes to run. (Default: auto)
 Possible values:
 - Integer (>= 1): Number of processes to run.
 - auto (default): Number of processes is automatically set to the number of logical CPU cores.
 - half: Number of processes is automatically set to half the number of logical CPU cores.

**functional**

*Default: null*

Run test methods instead of classes in separate processes.

**group**

*Default: array()*

If you wish to only run tests from a certain Group.
`group: [fast,quick,small]`

**always_execute**

*Default: false*

Always run the whole test suite, even if no PHP files were changed.

**phpunit**

*Default: null*

The PHPUnit binary to execute. (Default: vendor/bin/phpunit)

**configuration**

*Default: null*

The PHPUnit configuration file to use.

**runner**

*Default: null*

Runner, WrapperRunner or SqliteRunner. (Default: Runner)

**coverage-xml**

*Default: null*

Generate code coverage report in Clover XML format.

**coverage-html**

*Default: null*

Generate code coverage report in HTML format.

**log-junit**

*Default: null*

Log test execution in JUnit XML format to file.

**testsuite**

*Default: null*

Filter which testsuite to run. Run multiple suits by separating them with ",". Example:  --testsuite suite1,suite2


text:
This plugin (try) to get the hostname of the visitor and write it into the `log_visitor` table.

There are currently ***no reports or any views available***, to see a result. ***You need to directly query the table!***
I currently dont have the time and need of such a view, and therefor maybe you'll never see one...if nobody else create oen :-)

NOTE:
***I use it currently only in an intranet enviroment*** to detect computers which have old enviroment, because the IP might change i log the hostname.

I never tried it and probably wont use it for internet...


text:
package org.apache.http.impl.client;

@com.francetelecom.rd.stubs.annotation.ClassDone(0)
public class DefaultRedirectHandler
  implements org.apache.http.client.RedirectHandler
{
  // Constructors

  public DefaultRedirectHandler(){
  }
  // Methods

  public boolean isRedirectRequested(org.apache.http.HttpResponse arg1, org.apache.http.protocol.HttpContext arg2){
    return false;
  }
  public java.net.URI getLocationURI(org.apache.http.HttpResponse arg1, org.apache.http.protocol.HttpContext arg2) throws org.apache.http.ProtocolException{
    return (java.net.URI) null;
  }
}


text:
package org.ml4j.wit.api.impl.json;

import java.util.ArrayList;

public class EntityNameListResponse extends ArrayList<String> {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

}


text:
using System;
using System.Collections.Generic;
using System.Text;

class Solution
{
    static List<string> ReorderWordPositions(List<string> words, int n)
    {
        for (int pos = 0; pos < words.Count; pos++)
        {
            string word = words[pos];
            int newPos = words[pos].Length % (words.Count + 1);
            words[pos] = null; // Mark the word for deleting
            words.Insert(newPos, word);
            words.Remove(null);
        }

        return words;
    }

    static int GetMaxLengthOfWordInArray(List<string> words, int wordsLength)
    {
        int max = 0;

        int currentLength = words[0].Length;
        for (int i = 1; i < wordsLength; i++)
        {
            max = Math.Max(currentLength, max);
            currentLength = words[i].Length;
        }

        return max;
    }

    static void PrintOperation(List<string> words)
    {
        var result = new StringBuilder();

        int currentLetterPos = 0;
        int maxLength = GetMaxLengthOfWordInArray(words, words.Count);

        for (int i = 0; i < maxLength; i++)
        {
            foreach (var word in words)
            {
                if (word.Length > currentLetterPos)
                {
                    result.Append(word[currentLetterPos]);
                }
                else
                {
                    continue;
                }
            }

            currentLetterPos++;
        }
        Console.WriteLine(result.ToString());
    }

    static void Main()
    {
        //using (var reader = new StreamReader(@"..\..\input.txt"))
        //{
        var n = int.Parse(Console.ReadLine());
        var words = new List<string>(n);

        for (int i = 0; i < n; i++)
        {
            words.Add(Console.ReadLine());
        }

        if (words.Count > 1)
        {
            words = ReorderWordPositions(words, n);

            PrintOperation(words);
        }
        else
        {
            Console.WriteLine(words[0]);
        }
        //}
    }
}


text:
<?php

namespace Magento\Checkout\Test\Unit\Block\Cart\Item\Renderer\Actions;

use Magento\Catalog\Model\Product;
use Magento\Checkout\Block\Cart\Item\Renderer\Actions\Generic;
use Magento\Quote\Model\Quote\Item;

class GenericTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var Generic
     */
    protected $model;

    protected function setUp()
    {
        $objectManagerHelper = new \Magento\Framework\TestFramework\Unit\Helper\ObjectManager($this);

        $this->model = $objectManagerHelper->getObject(
            'Magento\Checkout\Block\Cart\Item\Renderer\Actions\Generic',
            []
        );
    }

    public function testGetItem()
    {
        /**
         * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock
         */
        $itemMock = $this->getMockBuilder('Magento\Quote\Model\Quote\Item')
            ->disableOriginalConstructor()
            ->getMock();

        $this->assertEquals($this->model, $this->model->setItem($itemMock));
        $this->assertEquals($itemMock, $this->model->getItem());
    }

    public function testIsProductVisibleInSiteVisibility()
    {
        /**
         * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock
         */
        $itemMock = $this->getMockBuilder('Magento\Quote\Model\Quote\Item')
            ->disableOriginalConstructor()
            ->getMock();

        /**
         * @var Product|\PHPUnit_Framework_MockObject_MockObject $productMock
         */
        $productMock = $this->getMockBuilder('Magento\Catalog\Model\Product')
            ->disableOriginalConstructor()
            ->getMock();

        $itemMock->expects($this->once())
            ->method('getProduct')
            ->willReturn($productMock);

        $productMock->expects($this->once())
            ->method('isVisibleInSiteVisibility')
            ->willReturn(true);

        $this->assertEquals($this->model, $this->model->setItem($itemMock));
        $this->assertTrue($this->model->isProductVisibleInSiteVisibility());
    }

    public function testIsVirtual()
    {
        /**
         * @var Item|\PHPUnit_Framework_MockObject_MockObject $itemMock
         */
        $itemMock = $this->getMockBuilder('Magento\Quote\Model\Quote\Item')
            ->disableOriginalConstructor()
            ->setMethods(['getIsVirtual'])
            ->getMock();

        $itemMock->expects($this->once())
            ->method('getIsVirtual')
            ->willReturn(true);

        $this->assertEquals($this->model, $this->model->setItem($itemMock));
        $this->assertTrue($this->model->isVirtual());
    }
}


text:
'''
testing module for the worker and dns discovery library
'''

from dns import resolver
from mock import patch, Mock
from odin.worker import Worker

IP = '192.168.0.1'

@patch('dns.resolver.Resolver')
class TestWoker:
    """ test worker obj"""

    def test_resolve_no_timeout(self, m_dns):
        worker = Worker(IP)
        assert worker._resolver.timeout == 1
        assert worker.resolve() == (True, True)

    def test_resolve_with_timeout(self, m_dns):
        worker = Worker(IP)
        assert worker._resolver.timeout == 1
        assert worker.resolve(timeout=2) == (True, True)
        assert worker._resolver.timeout == 2

    def test_resolve_NoAnswer(self, m_dns):
        m_dns().query.side_effect = resolver.NoAnswer('foo')
        worker = Worker(IP)
        assert worker.resolve() == (True, False)

    def test_resolve_NoNameservers(self, m_dns):
        m_dns().query.side_effect = resolver.NoNameservers('foo')
        worker = Worker(IP)
        assert worker.resolve() == (True, False)

    def test_resolve_Timeout(self, m_dns):
        m_dns().query.side_effect = resolver.Timeout('foo')
        worker = Worker(IP)
        assert worker.resolve() == (False, False)

    def test_dns_version_no_timeout(self, m_dns):
        answers = []
        record = Mock
        record.strings = ['some', 'other stuff']
        answers.append(record)
        m_dns().query.return_value = answers
        worker = Worker(IP)
        assert worker._resolver.timeout == 1
        assert worker.dns_version() == answers[0].strings[0]

    def test_dns_version_with_timeout(self, m_dns):
        answers = []
        record = Mock
        record.strings = ['some', 'other stuff']
        answers.append(record)
        m_dns().query.return_value = answers
        worker = Worker(IP)
        assert worker._resolver.timeout == 1
        assert worker.dns_version(timeout=2) == answers[0].strings[0]
        assert worker._resolver.timeout == 2

    def test_dns_version_NoNameservers(self, m_dns):
        m_dns().query.side_effect = resolver.NoNameservers('foo')
        worker = Worker(IP)
        assert worker.dns_version() is None

    def test_dns_version_Timeout(self, m_dns):
        m_dns().query.side_effect = resolver.Timeout('foo')
        worker = Worker(IP)
        assert worker.dns_version() is None

    def test_dns_scan(self, m_dns):
        answers = []
        record = Mock
        record.strings = ['some version', 'other stuff']
        answers.append(record)
        m_dns().query.side_effect = [True, answers]
        worker = Worker(IP)
        assert worker.dns_scan() is True
        assert worker.is_dns is True
        assert worker.is_resolver is True
        assert worker.version == 'some version'

    def test_dns_scan_without_version(self, m_dns):
        m_dns().query.return_value = 'whatever'
        worker = Worker(IP)
        assert worker.dns_scan(version=False) is True
        assert worker.is_dns is True
        assert worker.is_resolver is True
        assert worker.version is None


text:
"""Functional test for GradientDescent."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np
import tensorflow as tf

class GradientDescentOptimizerTest(tf.test.TestCase):

  def testBasic(self):
    for dtype in [tf.half, tf.float32]:
      with self.test_session():
        var0 = tf.Variable([1.0, 2.0], dtype=dtype)
        var1 = tf.Variable([3.0, 4.0], dtype=dtype)
        grads0 = tf.constant([0.1, 0.1], dtype=dtype)
        grads1 = tf.constant([0.01, 0.01], dtype=dtype)
        sgd_op = tf.train.GradientDescentOptimizer(3.0).apply_gradients(zip(
            [grads0, grads1], [var0, var1]))
        tf.initialize_all_variables().run()
        # Fetch params to validate initial values
        self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval())
        self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval())
        # Run 1 step of sgd
        sgd_op.run()
        # Validate updated params
        self.assertAllCloseAccordingToType(
            [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval())
        self.assertAllCloseAccordingToType(
            [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval())

  def testTensorLearningRate(self):
    for dtype in [tf.half, tf.float32]:
      with self.test_session():
        var0 = tf.Variable([1.0, 2.0], dtype=dtype)
        var1 = tf.Variable([3.0, 4.0], dtype=dtype)
        grads0 = tf.constant([0.1, 0.1], dtype=dtype)
        grads1 = tf.constant([0.01, 0.01], dtype=dtype)
        lrate = tf.constant(3.0)
        sgd_op = tf.train.GradientDescentOptimizer(lrate).apply_gradients(zip(
            [grads0, grads1], [var0, var1]))
        tf.initialize_all_variables().run()
        # Fetch params to validate initial values
        self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval())
        self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval())
        # Run 1 step of sgd
        sgd_op.run()
        # Validate updated params
        self.assertAllCloseAccordingToType(
            [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval())
        self.assertAllCloseAccordingToType(
            [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval())

  def testFloat64(self):
    with self.test_session():
      opt = tf.train.GradientDescentOptimizer(3.0)

      # compute_gradients.
      values = [1.0, 3.0]
      good_vars = [tf.Variable([v]) for v in values]
      bad_loss = tf.constant(2.0, tf.float64, name="bad_loss")
      self.assertRaisesRegexp(
          ValueError, r"Invalid type.*float64.*bad_loss.*expected.*float32",
          opt.compute_gradients, bad_loss, good_vars)
      bad_vars = [
          tf.Variable(np.array([v], np.float64), name="bad_var")
          for v in values
      ]
      self.assertRaisesRegexp(
          ValueError, r"Invalid type.*float64.*bad_var.*expected.*float32",
          opt.compute_gradients, tf.cast(bad_vars[0] + bad_vars[1], tf.float32),
          bad_vars)
      opt.compute_gradients(good_vars[0] + good_vars[1], good_vars)

      # apply_gradients.
      bad_grads = [
          tf.constant([0.1], dtype=np.float64, name="bad_grad"),
          tf.constant([0.01])
      ]
      self.assertRaisesRegexp(
          ValueError, r"Invalid type.*float64.*bad_grad.*expected.*float32",
          opt.apply_gradients, zip(bad_grads, good_vars))
      good_grads = [tf.constant([0.01]), tf.constant([0.02])]
      self.assertRaisesRegexp(
          ValueError, r"Invalid type.*float64.*bad_var.*expected.*float32",
          opt.apply_gradients, zip(good_grads, bad_vars))
      opt.apply_gradients(zip(good_grads, good_vars))

  def testGradWrtRef(self):
    for dtype in [tf.half, tf.float32]:
      with self.test_session():
        opt = tf.train.GradientDescentOptimizer(3.0)
        values = [1.0, 3.0]
        vars_ = [tf.Variable([v], dtype=dtype) for v in values]
        grads_and_vars = opt.compute_gradients(vars_[0].ref() + vars_[1], vars_)
        tf.initialize_all_variables().run()
        for grad, _ in grads_and_vars:
          self.assertAllCloseAccordingToType([1.0], grad.eval())

  def testWithGlobalStep(self):
    for dtype in [tf.half, tf.float32]:
      with self.test_session():
        global_step = tf.Variable(0, trainable=False)
        var0 = tf.Variable([1.0, 2.0], dtype=dtype)
        var1 = tf.Variable([3.0, 4.0], dtype=dtype)
        grads0 = tf.constant([0.1, 0.1], dtype=dtype)
        grads1 = tf.constant([0.01, 0.01], dtype=dtype)
        sgd_op = tf.train.GradientDescentOptimizer(3.0).apply_gradients(
            zip([grads0, grads1], [var0, var1]),
            global_step=global_step)
        tf.initialize_all_variables().run()
        # Fetch params to validate initial values
        self.assertAllCloseAccordingToType([1.0, 2.0], var0.eval())
        self.assertAllCloseAccordingToType([3.0, 4.0], var1.eval())
        # Run 1 step of sgd
        sgd_op.run()
        # Validate updated params and global_step
        self.assertAllCloseAccordingToType(
            [1.0 - 3.0 * 0.1, 2.0 - 3.0 * 0.1], var0.eval())
        self.assertAllCloseAccordingToType(
            [3.0 - 3.0 * 0.01, 4.0 - 3.0 * 0.01], var1.eval())
        self.assertAllCloseAccordingToType(1, global_step.eval())

  def testSparseBasic(self):
    for dtype in [tf.half, tf.float32]:
      with self.test_session():
        var0 = tf.Variable([[1.0], [2.0]], dtype=dtype)
        var1 = tf.Variable([[3.0], [4.0]], dtype=dtype)
        grads0 = tf.IndexedSlices(
            tf.constant([0.1], shape=[1, 1], dtype=dtype),
            tf.constant([0]),
            tf.constant([2, 1]))
        grads1 = tf.IndexedSlices(
            tf.constant([0.01], shape=[1, 1], dtype=dtype),
            tf.constant([1]),
            tf.constant([2, 1]))
        sgd_op = tf.train.GradientDescentOptimizer(3.0).apply_gradients(
            zip([grads0, grads1], [var0, var1]))
        tf.initialize_all_variables().run()
        # Fetch params to validate initial values
        self.assertAllCloseAccordingToType([[1.0], [2.0]], var0.eval())
        self.assertAllCloseAccordingToType([[3.0], [4.0]], var1.eval())
        # Run 1 step of sgd
        sgd_op.run()
        # Validate updated params
        self.assertAllCloseAccordingToType(
            [[1.0 - 3.0 * 0.1], [2.0]], var0.eval())
        self.assertAllCloseAccordingToType(
            [[3.0], [4.0 - 3.0 * 0.01]], var1.eval())

if __name__ == "__main__":
  tf.test.main()


text:
<!doctype html>

    <title>CodeMirror 2: C-like mode</title>
    <link rel="stylesheet" href="../../lib/codemirror.css">

    <link rel="stylesheet" href="../../theme/default.css">
    <link rel="stylesheet" href="../../css/docs.css">

CodeMirror 2: C-like mode

<form><textarea id="code" name="code">
/* C demo code */

#include <zmq.h>
#include <pthread.h>
#include <semaphore.h>
#include <time.h>
#include <stdio.h>
#include <fcntl.h>
#include <malloc.h>

typedef struct {
  void* arg_socket;
  zmq_msg_t* arg_msg;
  char* arg_string;
  unsigned long arg_len;
  int arg_int, arg_command;

  int signal_fd;
  int pad;
  void* context;
  sem_t sem;
} acl_zmq_context;

#define p(X) (context->arg_##X)

void* zmq_thread(void* context_pointer) {
  acl_zmq_context* context = (acl_zmq_context*)context_pointer;
  char ok = 'K', err = 'X';
  int res;

  while (1) {
    while ((res = sem_wait(&context->sem)) == EINTR);
    if (res) {write(context->signal_fd, &err, 1); goto cleanup;}
    switch(p(command)) {
    case 0: goto cleanup;
    case 1: p(socket) = zmq_socket(context->context, p(int)); break;
    case 2: p(int) = zmq_close(p(socket)); break;
    case 3: p(int) = zmq_bind(p(socket), p(string)); break;
    case 4: p(int) = zmq_connect(p(socket), p(string)); break;
    case 5: p(int) = zmq_getsockopt(p(socket), p(int), (void*)p(string), &p(len)); break;
    case 6: p(int) = zmq_setsockopt(p(socket), p(int), (void*)p(string), p(len)); break;
    case 7: p(int) = zmq_send(p(socket), p(msg), p(int)); break;
    case 8: p(int) = zmq_recv(p(socket), p(msg), p(int)); break;
    case 9: p(int) = zmq_poll(p(socket), p(int), p(len)); break;
    }
    p(command) = errno;
    write(context->signal_fd, &ok, 1);
  }
 cleanup:
  close(context->signal_fd);
  free(context_pointer);
  return 0;
}

void* zmq_thread_init(void* zmq_context, int signal_fd) {
  acl_zmq_context* context = malloc(sizeof(acl_zmq_context));
  pthread_t thread;

  context->context = zmq_context;
  context->signal_fd = signal_fd;
  sem_init(&context->sem, 1, 0);
  pthread_create(&thread, 0, &zmq_thread, context);
  pthread_detach(thread);
  return context;
}
</textarea></form>

Simple mode that tries to handle C-like languages as well as it
    can. Takes two configuration parameters: keywords, an
    object whose property names are the keywords in the language,
    and useCPP, which determines whether C preprocessor
    directives are recognized.

MIME types defined: text/x-csrc
    (C code), text/x-c++src (C++
    code), text/x-java (Java
    code), text/x-groovy (Groovy code).


text:
<?php

class Product
{
	public $Code;
	public $Quantity;

	/**
	 * @todounit when passing an invalid data type for quantity then throw exception
	 */
	public function __construct($ProductCode = "", $Quantity = 1)
	{
		$this->Code = $ProductCode;
		$this->Quantity = (int)$Quantity;
	}
}


text:
    <meta name="viewport" content="width=device-width initial-scale=1" charset="UTF-8">
    <title>Last Array Element</title>


text: © <?php echo date('Y'); ?> Netscout Technology Solutions. The Netscout Name and Logo are registered trademarks


text:
package com.greensnow25.NetworkFileManager.Client;

import com.greensnow25.NetworkFileManager.LIbrery.Interfaces.Action;

import java.io.*;
import java.net.Socket;

/**
 * public class clientBase.
 *
 * @author greensnow25.
 * @version 1.
 * @since 16.03.17
 */
public class ClientBaseActions {
    /**
     * inputStream.
     */
    private InputStream input;
    /**
     * outputStream.
     */
    private OutputStream output;
    /**
     * write to server.
     */
    private PrintWriter printWriter;
    /**
     * read from client.
     */
    private BufferedReader brFromServer;
    /**
     * Action base.
     */
    private Action[] actions = new Action[6];
    /**
     * sout.
     */
    private PrintWriter println;
    /**
     * keyboard entered.
     */
    private BufferedReader fromKeyboard;

    /**
     * class constructor.
     *
     * @param input  from client.
     * @param output to client.
     */
    public ClientBaseActions(InputStream input, OutputStream output) {
        this.input = input;
        this.output = output;
        this.brFromServer = new BufferedReader(new InputStreamReader(input));
        this.printWriter = new PrintWriter(output, true);
        this.println = new PrintWriter(System.out, true);
        this.fromKeyboard = new BufferedReader(new InputStreamReader(System.in));

    }

    public void filing() {
        int position = 0;
        actions[position++] = this.new ShowDirectory("show", "Show directory");
        actions[position++] = this.new ToParentDirectory("goParent", "Go up to the directory above");
        actions[position++] = this.new ToChildDirectory("goChild", "Move to the directory level below");
        actions[position++] = this.new DownloadFileFromClientToServer("dFile", "Download file from client to serer");
        actions[position++] = this.new DownloadFileFromServerToClient("uFile", "Download file from server to client");
        actions[position++] = this.new Help("help", "Displays the user action menu");
    }

    /**
     * choise action.
     *
     * @param line what the client wants to do.
     * @throws IOException ex.
     */
    public void select(String line) throws IOException {
        boolean bad = false;
        for (int i = 0; i != actions.length; i++) {
            if (line.equals(actions[i].key())) {
                actions[i].makeAction();
                bad = true;
            }
        }
        if (!bad) {
            println.println(brFromServer.readLine());

        }

    }

    /**
     * inner class move to parent directory.
     */
    public class ToParentDirectory extends Action {

        /**
         * constructor.
         *
         * @param key  key.
         * @param info info.
         */
        public ToParentDirectory(String key, String info) {
            super(key, info);
        }

        /**
         * Method moves to the directory one level higher.
         */
        @Override
        public void makeAction() {
            try {
                println.println(brFromServer.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * inner class move to child directory.
     */
    public class ToChildDirectory extends Action {

        /**
         * constructor.
         *
         * @param key  key.
         * @param info info.
         */
        public ToChildDirectory(String key, String info) {
            super(key, info);
        }

        @Override
        public void makeAction() {

            try {
                println.println("enter child dir");
                printWriter.println(fromKeyboard.readLine());
                println.println(brFromServer.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * inner class download file from server.
     */
    public class DownloadFileFromServerToClient extends Action {

        /**
         * constructor.
         *
         * @param key  key.
         * @param info info.
         */
        public DownloadFileFromServerToClient(String key, String info) {
            super(key, info);
        }

        @Override
        public void makeAction() throws IOException {
            println.println("Exemple : D:\\doc.txt  ");
            println.println("Enter full file name for downloading to server: ");
            String answer = fromKeyboard.readLine();

            File file = new File(answer);
            printWriter.println(file.getName());
            // brFromServer.readLine();
            try (FileInputStream fileIn = new FileInputStream(file)) {

                long l = file.length();
                printWriter.println(l);
                output.flush();
                int len;
                byte[] buffer = new byte[1024 * 100];

                while ((len = fileIn.read(buffer)) != -1) {
                    output.write(buffer, 0, len);
                    output.flush();

                }
                println.println(brFromServer.readLine());

            } catch (FileNotFoundException e) {
                e.printStackTrace();
                System.out.println("File does not exist.");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * inner class upload file to server.
     */
    public class DownloadFileFromClientToServer extends Action {

        /**
         * constructor.
         *
         * @param key  key.
         * @param info info.
         */
        public DownloadFileFromClientToServer(String key, String info) {
            super(key, info);
        }

        @Override
        public void makeAction() throws IOException {
            println.println("Exemple : doc.txt  ");
            println.println("Enter full file name for downloading to client: ");
            String answer = fromKeyboard.readLine();
            printWriter.println(answer);
            println.println("Enter the full path directory in which you want to save the file");
            println.println("For exemple : D:\\temp\\");
            String saveDir = fromKeyboard.readLine();
            printWriter.println("ok");
            File file = new File(saveDir + answer);

            try (FileOutputStream fw = new FileOutputStream(file)) {

                String lenght = brFromServer.readLine();
                long lengh = Long.parseLong(lenght);
                boolean exit = true;

                int len;
                long totalLenght = 0;
                byte[] buffer = new byte[1024 * 100];
                while (exit) {
                    len = input.read(buffer);
                    fw.write(buffer, 0, len);
                    totalLenght += len;
                    if (totalLenght == lengh) {
                        exit = false;
                    }

                }
                System.out.println("File successfully downloaded.");
            }
        }
    }

    /**
     * inner class show directory.
     */
    public class ShowDirectory extends Action {

        /**
         * constructor.
         *
         * @param key  key.
         * @param info info.
         */
        public ShowDirectory(String key, String info) {
            super(key, info);
        }

        /**
         * The method sends the client a list of files contained in the directory.
         */
        @Override
        public void makeAction() throws IOException {
            String answer = brFromServer.readLine();
            int len = Integer.parseInt(answer);
            for (int i = 0; i != len; i++) {
                println.println(brFromServer.readLine());
            }
        }
    }

    /**
     * inner class displays a prompt.
     */
    public class Help extends Action {

        /**
         * constructor.
         *
         * @param key  key.
         * @param info info.
         */
        public Help(String key, String info) {
            super(key, info);
        }

        @Override
        public void makeAction() throws IOException {
            String answer = brFromServer.readLine();
            int len = Integer.parseInt(answer);
            for (int i = 0; i != len; i++) {
                println.println(brFromServer.readLine());
            }
        }
    }
}


text:
package org.apache.accumulo.test.functional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.IOException;
import java.time.Duration;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.apache.accumulo.core.client.Accumulo;
import org.apache.accumulo.core.client.AccumuloClient;
import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.client.admin.NewTableConfiguration;
import org.apache.accumulo.core.clientImpl.ClientContext;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.TableId;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.IteratorUtil;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.accumulo.harness.AccumuloClusterHarness;
import org.apache.hadoop.io.Text;
import org.junit.jupiter.api.Test;

import com.google.common.collect.Iterables;

/**
 * Tests that Accumulo will flush but not create a file that has 0 entries.
 */
public class FlushNoFileIT extends AccumuloClusterHarness {

  @Override
  protected Duration defaultTimeout() {
    return Duration.ofMinutes(1);
  }

  @Test
  public void test() throws Exception {
    try (AccumuloClient c = Accumulo.newClient().from(getClientProps()).build()) {

      String tableName = getUniqueNames(1)[0];

      NewTableConfiguration ntc = new NewTableConfiguration();
      IteratorSetting iteratorSetting = new IteratorSetting(20, NullIterator.class);
      ntc.attachIterator(iteratorSetting, EnumSet.of(IteratorUtil.IteratorScope.minc));
      ntc.withSplits(new TreeSet<>(Set.of(new Text("a"), new Text("s"))));

      c.tableOperations().create(tableName, ntc);
      TableId tableId = TableId.of(c.tableOperations().tableIdMap().get(tableName));

      try (BatchWriter bw = c.createBatchWriter(tableName)) {
        Mutation m = new Mutation(new Text("r1"));
        m.put("acf", tableName, "1");
        bw.addMutation(m);
      }

      FunctionalTestUtils.checkRFiles(c, tableName, 3, 3, 0, 0);

      c.tableOperations().flush(tableName, null, null, true);

      FunctionalTestUtils.checkRFiles(c, tableName, 3, 3, 0, 0);

      long flushId = FunctionalTestUtils.checkFlushId((ClientContext) c, tableId, 0);

      try (BatchWriter bw = c.createBatchWriter(tableName)) {
        Mutation m = new Mutation(new Text("r2"));
        m.put("acf", tableName, "1");
        bw.addMutation(m);
      }

      c.tableOperations().flush(tableName, null, null, true);

      FunctionalTestUtils.checkRFiles(c, tableName, 3, 3, 0, 0);

      long secondFlushId = FunctionalTestUtils.checkFlushId((ClientContext) c, tableId, flushId);
      assertTrue(secondFlushId > flushId, "Flush ID did not change");

      try (Scanner scanner = c.createScanner(tableName)) {
        assertEquals(0, Iterables.size(scanner), "Expected 0 Entries in table");
      }
    }
  }

  public static class NullIterator implements SortedKeyValueIterator<Key,Value> {

    @Override
    public void init(SortedKeyValueIterator<Key,Value> source, Map<String,String> options,
        IteratorEnvironment env) {}

    @Override
    public boolean hasTop() {
      return false;
    }

    @Override
    public void next() throws IOException {}

    @Override
    public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive) {}

    @Override
    public Key getTopKey() {
      return null;
    }

    @Override
    public Value getTopValue() {
      return null;
    }

    @Override
    public SortedKeyValueIterator<Key,Value> deepCopy(IteratorEnvironment env) {
      return null;
    }
  }
}


text:
// flow-typed signature: 6c27d849c3bc76c4b99b4bb42146bc0f
// flow-typed version: <<STUB>>/d3-dsv_v^1.0.5/flow_v0.50.0

/**
 * This is an autogenerated libdef stub for:
 *
 *   'd3-dsv'
 *
 * Fill this stub out by replacing all the `any` types.
 *
 * Once filled out, we encourage you to share your work with the
 * community by sending a pull request to:
 * https://github.com/flowtype/flow-typed
 */

declare module "d3-dsv" {
  declare module.exports: any;
}

/**
 * We include stubs for each file inside this npm package in case you need to
 * require those files directly. Feel free to delete any files that aren't
 * needed.
 */
declare module "d3-dsv/build/d3-dsv" {
  declare module.exports: any;
}

declare module "d3-dsv/build/d3-dsv.min" {
  declare module.exports: any;
}

declare module "d3-dsv/src/csv" {
  declare module.exports: any;
}

declare module "d3-dsv/src/dsv" {
  declare module.exports: any;
}

declare module "d3-dsv/src/tsv" {
  declare module.exports: any;
}

// Filename aliases
declare module "d3-dsv/build/d3-dsv.js" {
  declare module.exports: $Exports<"d3-dsv/build/d3-dsv">;
}
declare module "d3-dsv/build/d3-dsv.min.js" {
  declare module.exports: $Exports<"d3-dsv/build/d3-dsv.min">;
}
declare module "d3-dsv/index" {
  declare module.exports: $Exports<"d3-dsv">;
}
declare module "d3-dsv/index.js" {
  declare module.exports: $Exports<"d3-dsv">;
}
declare module "d3-dsv/src/csv.js" {
  declare module.exports: $Exports<"d3-dsv/src/csv">;
}
declare module "d3-dsv/src/dsv.js" {
  declare module.exports: $Exports<"d3-dsv/src/dsv">;
}
declare module "d3-dsv/src/tsv.js" {
  declare module.exports: $Exports<"d3-dsv/src/tsv">;
}


text:
package com.seleniumtests.it.driver;

import org.openqa.selenium.NoSuchElementException;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import com.seleniumtests.core.SeleniumTestsContextManager;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.it.driver.support.GenericMultiBrowserTest;
import com.seleniumtests.it.driver.support.pages.DriverTestPageSalesforceLightning;

public class TestSalesforceLightning extends GenericMultiBrowserTest {

	public TestSalesforceLightning() throws Exception {
		super(BrowserType.CHROME, "DriverTestPageSalesforceLightning");
	}

	public TestSalesforceLightning(BrowserType browserType) throws Exception {
		super(browserType, "DriverTestPageSalesforceLightning");
	}

	@BeforeMethod(groups= {"it"})
	public void init() {
		SeleniumTestsContextManager.getThreadContext().setReplayTimeout(1);
	}

	@AfterMethod(groups={"it"}, alwaysRun=true)
	public void reset() {
		if (driver != null) {
			driver.navigate().refresh();
		}
	}

	@Test(groups = "it")
	public void testSelectByText() {
		DriverTestPageSalesforceLightning.combobox.selectByText("New");
		Assert.assertEquals(DriverTestPageSalesforceLightning.combobox.getSelectedText(), "New");
	}

	@Test(groups = "it")
	public void testSelectByIndex() {
		DriverTestPageSalesforceLightning.combobox.selectByIndex(2);
		Assert.assertEquals(DriverTestPageSalesforceLightning.combobox.getSelectedText(), "Finished");
	}

	@Test(groups = "it", expectedExceptions = UnsupportedOperationException.class)
	public void testSelectByValue() {
		DriverTestPageSalesforceLightning.combobox.selectByValue("New");
	}

	@Test(groups = "it")
	public void testSelectByCorrespondingText() {
		DriverTestPageSalesforceLightning.combobox.selectByCorrespondingText("Ne");
		Assert.assertEquals(DriverTestPageSalesforceLightning.combobox.getSelectedText(), "New");
	}

	@Test(groups = "it", expectedExceptions = UnsupportedOperationException.class)
	public void testDeselectByText() {
		DriverTestPageSalesforceLightning.combobox.deselectByText("New");
	}

	@Test(groups = "it", expectedExceptions = UnsupportedOperationException.class)
	public void testDeselectByIndex() {
		DriverTestPageSalesforceLightning.combobox.deselectByIndex(2);
	}

	@Test(groups = "it", expectedExceptions = UnsupportedOperationException.class)
	public void testDeselectByValue() {
		DriverTestPageSalesforceLightning.combobox.deselectByValue("In Progress");
	}

	@Test(groups = "it")
	public void testSelectNotMultiple() {
		Assert.assertFalse(DriverTestPageSalesforceLightning.combobox.isMultiple());
	}

	/**
	 * Check trying to select an element which does not exist raises an error
	 */
	@Test(groups = "it", expectedExceptions=NoSuchElementException.class)
	public void testSelectByInvalidText() {
		DriverTestPageSalesforceLightning.combobox.selectByText("Option 12");
	}

	@Test(groups = "it", expectedExceptions=NoSuchElementException.class)
	public void testSelectByInvalidTexts() {
		DriverTestPageSalesforceLightning.combobox.selectByText(new String[] {"Option 12"});
	}

	@Test(groups = "it", expectedExceptions=NoSuchElementException.class)
	public void testSelectInvalidIndex() {
		DriverTestPageSalesforceLightning.combobox.selectByIndex(20);
	}

	@Test(groups = "it", expectedExceptions=NoSuchElementException.class)
	public void testSelectInvalidIndexes() {
		DriverTestPageSalesforceLightning.combobox.selectByIndex(new int[] {10, 20});
	}

	@Test(groups = "it", expectedExceptions = UnsupportedOperationException.class)
	public void testSelectByInvalidValue() {
		DriverTestPageSalesforceLightning.combobox.selectByValue("option30");
	}

	@Test(groups = "it", expectedExceptions = UnsupportedOperationException.class)
	public void testSelectByInvalidValues() {
		DriverTestPageSalesforceLightning.combobox.selectByValue(new String[] {"option30"});
	}

}


text:
package gov.sandia.cognition.learning.function.categorization;

import gov.sandia.cognition.util.AbstractCloneableSerializable;
import java.util.LinkedHashSet;
import java.util.Set;

/**
 * An abstract implementation of the {@code Categorizer} interface. Keeps track
 * of the set of categories.
 *
 * @param  <InputType> The type of the input the categorizer can use.
 * @param  <CategoryType> The type of category output by the categorizer.
 * @author  Justin Basilico
 * @since   3.0
 */
public abstract class AbstractCategorizer<InputType, CategoryType>
    extends AbstractCloneableSerializable
    implements Categorizer<InputType, CategoryType>
{
    /** The set of categories that are the possible output values of the
     *  categorizer. */
    protected Set<CategoryType> categories;

    /**
     * Creates a new {@code AbstractCategorizer} with an empty category set.
     */
    public AbstractCategorizer()
    {
        this(new LinkedHashSet<CategoryType>());
    }

    /**
     * Creates a new {@code AbstractCategorizer} with the given category set.
     *
     * @param   categories
     *      The categories.
     */
    public AbstractCategorizer(
        final Set<CategoryType> categories)
    {
        super();

        this.setCategories(categories);
    }

    @Override
    public AbstractCategorizer<InputType, CategoryType> clone()
    {
        @SuppressWarnings("unchecked")
        AbstractCategorizer<InputType, CategoryType> clone =
            (AbstractCategorizer<InputType, CategoryType>) super.clone();
        clone.setCategories( new LinkedHashSet<CategoryType>( this.getCategories() ) );
        return clone;
    }

    public Set<CategoryType> getCategories()
    {
        return this.categories;
    }

    /**
     * Sets the Set of possible categories, which are the output values.
     *
     * @param   categories The list of possible output categories.
     */
    protected void setCategories(
        final Set<CategoryType> categories)
    {
        this.categories = categories;
    }
}


text:
// Code generated by protoc-gen-liverpc v0.1, DO NOT EDIT.
// source: v1/Guard.proto

/*
Package v1 is a generated liverpc stub package.
This code was generated with go-common/app/tool/liverpc/protoc-gen-liverpc v0.1.

It is generated from these files:
	v1/Guard.proto
	v1/Note.proto
	v1/RoomAdmin.proto
	v1/UserSetting.proto
*/
package v1

import context "context"

import proto "github.com/golang/protobuf/proto"
import "go-common/library/net/rpc/liverpc"

var _ proto.Message // generate to suppress unused imports
// Imports only used by utility functions:

// ===============
// Guard Interface
// ===============

type Guard interface {
	// * 根据uid获取大航海信息
	//
	GetByUidTargetId(context.Context, *GuardGetByUidTargetIdReq) (*GuardGetByUidTargetIdResp, error)

	// * 根据uid获取大航海信息
	//
	GetByUid(context.Context, *GuardGetByUidReq) (*GuardGetByUidResp, error)
}

// =====================
// Guard Live Rpc Client
// =====================

type guardRpcClient struct {
	client *liverpc.Client
}

// NewGuardRpcClient creates a Rpc client that implements the Guard interface.
// It communicates using Rpc and can be configured with a custom HTTPClient.
func NewGuardRpcClient(client *liverpc.Client) Guard {
	return &guardRpcClient{
		client: client,
	}
}

func (c *guardRpcClient) GetByUidTargetId(ctx context.Context, in *GuardGetByUidTargetIdReq) (*GuardGetByUidTargetIdResp, error) {
	out := new(GuardGetByUidTargetIdResp)
	err := doRpcRequest(ctx, c.client, 1, "Guard.getByUidTargetId", in, out)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *guardRpcClient) GetByUid(ctx context.Context, in *GuardGetByUidReq) (*GuardGetByUidResp, error) {
	out := new(GuardGetByUidResp)
	err := doRpcRequest(ctx, c.client, 1, "Guard.getByUid", in, out)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// =====
// Utils
// =====

func doRpcRequest(ctx context.Context, client *liverpc.Client, version int, method string, in, out proto.Message) (err error) {
	err = client.Call(ctx, version, method, in, out)
	return
}


text:
#ifndef DYNET_C_SOFTMAX_BUILDER_H_
#define DYNET_C_SOFTMAX_BUILDER_H_

#include <dynet_c/define.h>
#include <dynet_c/expr.h>
#include <dynet_c/graph.h>
#include <dynet_c/model.h>

/**
 * Opaque type of SoftmaxBuilder.
 */
typedef struct dynetSoftmaxBuilder dynetSoftmaxBuilder_t;

/**
 * Deletes the SoftmaxBuilder object.
 * @param builder Pointer of a handler.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetDeleteSoftmaxBuilder(
    dynetSoftmaxBuilder_t *builder);

/**
 * Initializes the parameters in the computation graph.
 * @param builder Pointer of a handler.
 * @param h_0 Vector to initialize hidden layers at timestep 0.
 * @param n The number of `h_0` elements.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetResetSoftmaxBuilderGraph(
    dynetSoftmaxBuilder_t *builder, dynetComputationGraph_t *cg,
    DYNET_C_BOOL update);

/**
 * Computes negative log probability of a class.
 * @param builder Pointer of a handler.
 * @param rep Vector expression.
 * @param classidx Class.
 * @param newobj Pointer to receive an Expression.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetApplySoftmaxBuilderNegLogSoftmaxOne(
    dynetSoftmaxBuilder_t *builder, const dynetExpression_t *rep,
    uint32_t classidx, dynetExpression_t **newobj);

/**
 * Computes batched negative log probability of a class.
 * @param builder Pointer of a handler.
 * @param rep Vector expression (batched).
 * @param classidxs List of classes, one per batch element.
 * @param n Number of indices.
 * @param newobj Pointer to receive an Expression.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetApplySoftmaxBuilderNegLogSoftmax(
    dynetSoftmaxBuilder_t *builder, const dynetExpression_t *rep,
    const uint32_t *classidxs, size_t n, dynetExpression_t **newobj);

/**
 * Samples from the softmax distribution.
 * @param builder Pointer of a handler.
 * @param rep Vector expression parametrizing the distribution.
 * @param retval Pointer to receive a sampled class.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetSampleFromSoftmaxBuilder(
    dynetSoftmaxBuilder_t *builder, const dynetExpression_t *rep,
    uint32_t *retval);

/**
 * Returns an Expression representing a vector the size of the number of
 * classes.
 * @param rep Vector expression parametrizing the distribution.
 * @param newobj Pointer to receive an Expression.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetGetSoftmaxBuilderFullLogDistribution(
    dynetSoftmaxBuilder_t *builder, const dynetExpression_t *rep,
    dynetExpression_t **newobj);

/**
 * Returns the logits (before application of the softmax).
 * @param rep Vector expression parametrizing the distribution.
 * @param newobj Pointer to receive an Expression.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetGetSoftmaxBuilderFullLogits(
    dynetSoftmaxBuilder_t *builder, const dynetExpression_t *rep,
    dynetExpression_t **newobj);

/**
 * Gets the ParameterCollection containing the softmax parameters.
 * @param builder Pointer of a handler.
 * @param newobj Pointer to receive the parameter collection.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetGetSoftmaxBuilderParameterCollection(
    dynetSoftmaxBuilder_t *builder, dynetParameterCollection_t **newobj);

/**
 * Creates a new StandardSoftmaxBuilder object.
 * @param rep_dim Dimension of the input vectors.
 * @param num_classes Number of classes.
 * @param pc Parameter collection.
 * @param bias Whether to use a bias vector or not.
 * @param newobj Pointer to receive a handler.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetCreateStandardSoftmaxBuilder(
    uint32_t rep_dim, uint32_t num_classes, dynetParameterCollection_t *pc,
    DYNET_C_BOOL bias, dynetSoftmaxBuilder_t **newobj);

/**
 * Creates a new StandardSoftmaxBuilder object with pre-existing parameters.
 * @param p_w Weight matrix.
 * @param p_b Bias vector (no bias is used if `p_b` is nullptr).
 * @param newobj Pointer to receive a handler.
 * @return Status code.
 */
DYNET_C_API DYNET_C_STATUS dynetCreateStandardSoftmaxBuilderFromParameters(
    dynetParameter_t *p_w, dynetParameter_t *p_b,
    dynetSoftmaxBuilder_t **newobj);

#endif  // DYNET_C_SOFTMAX_BUILDER_H_


text:
package com.fasterxml.jackson.databind;

import com.fasterxml.jackson.databind.cfg.MapperConfig;
import com.fasterxml.jackson.databind.introspect.AnnotatedField;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.AnnotatedParameter;
import java.io.Serializable;

public abstract class PropertyNamingStrategy
  implements Serializable
{
  public static final PropertyNamingStrategy CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES = new LowerCaseWithUnderscoresStrategy();
  public static final PropertyNamingStrategy PASCAL_CASE_TO_CAMEL_CASE = new PascalCaseStrategy();

  public String nameForConstructorParameter(MapperConfig<?> paramMapperConfig, AnnotatedParameter paramAnnotatedParameter, String paramString)
  {
    return paramString;
  }

  public String nameForField(MapperConfig<?> paramMapperConfig, AnnotatedField paramAnnotatedField, String paramString)
  {
    return paramString;
  }

  public String nameForGetterMethod(MapperConfig<?> paramMapperConfig, AnnotatedMethod paramAnnotatedMethod, String paramString)
  {
    return paramString;
  }

  public String nameForSetterMethod(MapperConfig<?> paramMapperConfig, AnnotatedMethod paramAnnotatedMethod, String paramString)
  {
    return paramString;
  }

  public static class LowerCaseWithUnderscoresStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase
  {
    public String translate(String paramString)
    {
      if (paramString == null)
        return paramString;
      int i = paramString.length();
      StringBuilder localStringBuilder = new StringBuilder(i << 1);
      int j = 0;
      int k = 0;
      for (int m = 0; m < i; m++)
      {
        char c = paramString.charAt(m);
        if ((m > 0) || (c != '_'))
        {
          if (Character.isUpperCase(c))
          {
            if ((k == 0) && (j > 0) && (localStringBuilder.charAt(j - 1) != '_'))
            {
              localStringBuilder.append('_');
              j++;
            }
            c = Character.toLowerCase(c);
            k = 1;
          }
          else
          {
            k = 0;
          }
          localStringBuilder.append(c);
          j++;
        }
      }
      if (j > 0)
        return localStringBuilder.toString();
      return paramString;
    }
  }

  public static class PascalCaseStrategy extends PropertyNamingStrategy.PropertyNamingStrategyBase
  {
    public String translate(String paramString)
    {
      if ((paramString == null) || (paramString.length() == 0))
        return paramString;
      char c = paramString.charAt(0);
      if (Character.isUpperCase(c))
        return paramString;
      StringBuilder localStringBuilder = new StringBuilder(paramString);
      localStringBuilder.setCharAt(0, Character.toUpperCase(c));
      return localStringBuilder.toString();
    }
  }

  public static abstract class PropertyNamingStrategyBase extends PropertyNamingStrategy
  {
    public String nameForConstructorParameter(MapperConfig<?> paramMapperConfig, AnnotatedParameter paramAnnotatedParameter, String paramString)
    {
      return translate(paramString);
    }

    public String nameForField(MapperConfig<?> paramMapperConfig, AnnotatedField paramAnnotatedField, String paramString)
    {
      return translate(paramString);
    }

    public String nameForGetterMethod(MapperConfig<?> paramMapperConfig, AnnotatedMethod paramAnnotatedMethod, String paramString)
    {
      return translate(paramString);
    }

    public String nameForSetterMethod(MapperConfig<?> paramMapperConfig, AnnotatedMethod paramAnnotatedMethod, String paramString)
    {
      return translate(paramString);
    }

    public abstract String translate(String paramString);
  }
}

/* Location:           /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar
 * Qualified Name:     com.fasterxml.jackson.databind.PropertyNamingStrategy
 * JD-Core Version:    0.6.2
 */


text:
<!DOCTYPE html>

    <title>BigInt Structure Reference</title>
    <link rel="stylesheet" type="text/css" href="../css/jazzy.css" />
    <link rel="stylesheet" type="text/css" href="../css/highlight.css" />
    <meta charset="utf-8">

          BigInt Docs

         (92% documented)

        <form role="search" action="../search.json">
          <input type="text" placeholder="Search documentation" data-typeahead>
        </form>

            View on GitHub

            Install in Dash

      BigInt Reference

      BigInt Structure Reference

            Extensions

                BinaryFloatingPoint

                String

            Structures

                BigInt

                – Sign

                – Words

                BigUInt

                – Words

BigInt

public struct BigInt: SignedInteger

An arbitary precision signed integer type, also known as a <q>big integer</q>.

Operations on big integers never overflow, but they might take a long time to execute.
The amount of memory (and address space) available is the only constraint to the magnitude of these numbers.

This particular big integer type uses base-2^64 digits to represent integers.

BigInt is essentially a tiny wrapper that extends BigUInt with a sign bit and provides signed integer
operations. Both the underlying absolute value and the negative/positive flag are available as read-write
properties.

Not all algorithms of BigUInt are available for BigInt values; for example, there is no square root or
primality test for signed integers. When you need to call one of these, just extract the absolute value:

BigInt(255).abs.isPrime()   // Returns false

                    Sign

Undocumented

                        See more

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    Word

The type representing a digit in BigInt‘s underlying number system.

Declaration

Swift

public typealias Word = BigUInt.Word

                        Show on GitHub

                    isSigned

Declaration

Swift

public static var isSigned: Bool

                        Show on GitHub

                    magnitude

The absolute value of this integer.

Declaration

Swift

public var magnitude: BigUInt

                        Show on GitHub

                    sign

True iff the value of this integer is negative.

Declaration

Swift

public var sign: Sign

                        Show on GitHub

                    init(sign:magnitude:)

Initializes a new big integer with the provided absolute number and sign flag.

Declaration

Swift

public init(sign: Sign, magnitude: BigUInt)

                        Show on GitHub

                    isZero

Return true iff this integer is zero.

Complexity

    O(1)

Declaration

Swift

public var isZero: Bool

                        Show on GitHub

                    signum()

Returns -1 if this value is negative and 1 if it's positive; otherwise, 0.

Declaration

Swift

public func signum() -> BigInt

Return Value

The sign of this number, expressed as an integer of the same type.

                        Show on GitHub

                    ~(_:)

Declaration

Swift

public static prefix func ~(x: BigInt) -> BigInt

                        Show on GitHub

                    &(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    |(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    ^(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    &=(_:_:)

Declaration

Swift

public static func &=(lhs: inout BigInt, rhs: BigInt)

                        Show on GitHub

                    |=(_:_:)

Declaration

Swift

public static func |=(lhs: inout BigInt, rhs: BigInt)

                        Show on GitHub

                    ^=(_:_:)

Declaration

Swift

public static func ^=(lhs: inout BigInt, rhs: BigInt)

                        Show on GitHub

Primality Testing

                    isStrongProbablePrime(_:)

Returns true iff this integer passes the strong probable prime test for the specified base.

Declaration

Swift

public func isStrongProbablePrime(_ base: BigInt) -> Bool

                        Show on GitHub

                    isPrime(rounds:)

Returns true if this integer is probably prime. Returns false if this integer is definitely not prime.

This function performs a probabilistic Miller-Rabin Primality Test, consisting of rounds iterations,
each calculating the strong probable prime test for a random base. The number of rounds is 10 by default,
but you may specify your own choice.

To speed things up, the function checks if self is divisible by the first few prime numbers before
diving into (slower) Miller-Rabin testing.

Also, when self is less than 82 bits wide, isPrime does a deterministic test that is guaranteed to
return a correct result.

Declaration

Swift

public func isPrime(rounds: Int = 10) -> Bool

                        Show on GitHub

                    bitWidth

Declaration

Swift

public var bitWidth: Int

                        Show on GitHub

                    trailingZeroBitCount

Declaration

Swift

public var trailingZeroBitCount: Int

                        Show on GitHub

                    Words

                        See more

Declaration

Swift

public struct Words: RandomAccessCollection

                        Show on GitHub

                    words

Declaration

Swift

public var words: Words

                        Show on GitHub

                    init(words:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    appendHashes(to:)

Append this BigInt to the specified hasher.

Declaration

Swift

public func appendHashes(to hasher: inout SipHasher)

                        Show on GitHub

                    init(exactly:)

Declaration

Swift

public init?<T: BinaryFloatingPoint>(exactly source: T)

                        Show on GitHub

                    init(_:)

Declaration

Swift

public init<T: BinaryFloatingPoint>(_ source: T)

                        Show on GitHub

                    negate()

Declaration

Swift

public mutating func negate()

                        Show on GitHub

                    -(_:_:)

Subtract b from a and return the result.

Declaration

Swift

public static func -(a: BigInt, b: BigInt) -> BigInt

                        Show on GitHub

                    -=(_:_:)

Subtract b from a in place.

Declaration

Swift

public static func -=(a: inout BigInt, b: BigInt)

                        Show on GitHub

                    quotientAndRemainder(dividingBy:)

Divide this integer by y and return the resulting quotient and remainder.

Requires

    y > 0

Complexity

    O(count^2)

Declaration

Swift

public func quotientAndRemainder(dividingBy y: BigInt) -> (quotient: BigInt, remainder: BigInt)

Return Value

(quotient, remainder) where quotient = floor(self/y), remainder = self - quotient * y

                        Show on GitHub

                    /(_:_:)

Divide a by b and return the quotient. Traps if b is zero.

Declaration

Swift

public static func /(a: BigInt, b: BigInt) -> BigInt

                        Show on GitHub

                    %(_:_:)

Divide a by b and return the remainder. The result has the same sign as a.

Declaration

Swift

public static func %(a: BigInt, b: BigInt) -> BigInt

                        Show on GitHub

                    modulus(_:)

Return the result of a mod b. The result is always a nonnegative integer that is less than the absolute value of b.

Declaration

Swift

public func modulus(_ mod: BigInt) -> BigInt

                        Show on GitHub

                    /=(_:_:)

Divide a by b storing the quotient in a.

Declaration

Swift

public static func /=(a: inout BigInt, b: BigInt)

                        Show on GitHub

                    %=(_:_:)

Divide a by b storing the remainder in a.

Declaration

Swift

public static func %=(a: inout BigInt, b: BigInt)

                        Show on GitHub

                    init()

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    init(_:)

Initializes a new signed big integer with the same value as the specified unsigned big integer.

Declaration

Swift

public init(_ integer: BigUInt)

                        Show on GitHub

                    init(_:)

Declaration

Swift

public init<T>(_ source: T) where T : BinaryInteger

                        Show on GitHub

                    init(exactly:)

Declaration

Swift

public init?<T>(exactly source: T) where T : BinaryInteger

                        Show on GitHub

                    init(clamping:)

Declaration

Swift

public init<T>(clamping source: T) where T : BinaryInteger

                        Show on GitHub

                    init(truncatingIfNeeded:)

Declaration

Swift

public init<T>(truncatingIfNeeded source: T) where T : BinaryInteger

                        Show on GitHub

                    init(integerLiteral:)

Initialize a new big integer from an integer literal.

Declaration

Swift

public init(integerLiteral value: Int64)

                        Show on GitHub

                    ==(_:_:)

Return true iff a is equal to b.

Declaration

Swift

public static func ==(a: BigInt, b: BigInt) -> Bool

                        Show on GitHub

                    <(_:_:)

Return true iff a is less than b.

Declaration

Swift

public static func <(a: BigInt, b: BigInt) -> Bool

                        Show on GitHub

                    init(_:radix:)

Initialize a big integer from an ASCII representation in a given radix. Numerals above 9 are represented by
letters from the English alphabet.

Requires

    radix > 1 && radix < 36

Declaration

Swift

public init?<S: StringProtocol>(_ text: S, radix: Int = 10)

Return Value

The integer represented by text, or nil if text contains a character that does not represent a numeral in radix.

                        Show on GitHub

                    init(unicodeScalarLiteral:)

Initialize a new big integer from a Unicode scalar.
The scalar must represent a decimal digit.

Declaration

Swift

public init(unicodeScalarLiteral value: UnicodeScalar)

                        Show on GitHub

                    init(extendedGraphemeClusterLiteral:)

Initialize a new big integer from an extended grapheme cluster.
The cluster must consist of a decimal digit.

Declaration

Swift

public init(extendedGraphemeClusterLiteral value: String)

                        Show on GitHub

                    init(stringLiteral:)

Initialize a new big integer from a decimal number represented by a string literal of arbitrary length.
The string must contain only decimal digits.

Declaration

Swift

public init(stringLiteral value: StringLiteralType)

                        Show on GitHub

                    description

Return the decimal representation of this integer.

Declaration

Swift

public var description: String

                        Show on GitHub

                    customPlaygroundQuickLook

Return the playground quick look representation of this integer.

Declaration

Swift

public var customPlaygroundQuickLook: PlaygroundQuickLook

                        Show on GitHub

                    *(_:_:)

Multiply a with b and return the result.

Declaration

Swift

public static func *(a: BigInt, b: BigInt) -> BigInt

                        Show on GitHub

                    *=(_:_:)

Multiply a with b in place.

Declaration

Swift

public static func *=(a: inout BigInt, b: BigInt)

                        Show on GitHub

                    advanced(by:)

Returns self + n.

Declaration

Swift

public func advanced(by n: Stride) -> BigInt

                        Show on GitHub

                    distance(to:)

Returns other - self.

Declaration

Swift

public func distance(to other: BigInt) -> Stride

                        Show on GitHub

                    &<<(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    &<<=(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    &>>(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    &>>=(_:_:)

Undocumented

Declaration

Swift

public struct BigInt: SignedInteger

                        Show on GitHub

                    <<(_:_:)

Declaration

Swift

public static func <<<Other: BinaryInteger>(lhs: BigInt, rhs: Other) -> BigInt

                        Show on GitHub

                    <<=(_:_:)

Declaration

Swift

public static func <<=<Other: BinaryInteger>(lhs: inout BigInt, rhs: Other)

                        Show on GitHub

                    >>(_:_:)

Declaration

Swift

public static func >><Other: BinaryInteger>(lhs: BigInt, rhs: Other) -> BigInt

                        Show on GitHub

                    >>=(_:_:)

Declaration

Swift

public static func >>=<Other: BinaryInteger>(lhs: inout BigInt, rhs: Other)

                        Show on GitHub

                    greatestCommonDivisor(with:)

Returns the greatest common divisor of a and b.

Complexity

    O(count^2) where count = max(a.count, b.count)

Declaration

Swift

public func greatestCommonDivisor(with b: BigInt) -> BigInt

                        Show on GitHub

                    inverse(_:)

Returns the multiplicative inverse of this integer in modulo modulus arithmetic,
or nil if there is no such number.

Requires

    modulus.magnitude > 1

Complexity

    O(count^3)

Declaration

Swift

public func inverse(_ modulus: BigInt) -> BigInt?

Return Value

If gcd(self, modulus) == 1, the value returned is an integer a < modulus such that (a * self) % modulus == 1. If self and modulus aren’t coprime, the return value is nil.

                        Show on GitHub

                    squareRoot()

Returns the integer square root of a big integer; i.e., the largest integer whose square isn’t greater than value.

Requires

    self >= 0

Declaration

Swift

public func squareRoot() -> BigInt

Return Value

floor(sqrt(self))

                        Show on GitHub

                    init(from:)

Declaration

Swift

public init(from decoder: Decoder) throws

                        Show on GitHub

                    encode(to:)

Declaration

Swift

public func encode(to encoder: Encoder) throws

                        Show on GitHub

                    power(_:)

Returns this integer raised to the power exponent.

This function calculates the result by successively squaring the base while halving the exponent.

Note

    This function can be unreasonably expensive for large exponents, which is why exponent is
    a simple integer value. If you want to calculate big exponents, you’ll probably need to use
    the modulo arithmetic variant.

See also

    BigUInt.power(_:, modulus:)

Complexity

    O((exponent * self.count)^log2(3)) or somesuch. The result may require a large amount of memory, too.

Declaration

Swift

public func power(_ exponent: Int) -> BigInt

Return Value

1 if exponent == 0, otherwise self raised to exponent. (This implies that 0.power(0) == 1.)

                        Show on GitHub

                    power(_:modulus:)

Returns the remainder of this integer raised to the power exponent in modulo arithmetic under modulus.

Uses the right-to-left binary method.

Complexity

    O(exponent.count * modulus.count^log2(3)) or somesuch

Declaration

Swift

public func power(_ exponent: BigInt, modulus: BigInt) -> BigInt

                        Show on GitHub

                    +(_:_:)

Add a to b and return the result.

Declaration

Swift

public static func +(a: BigInt, b: BigInt) -> BigInt

                        Show on GitHub

                    +=(_:_:)

Add b to a in place.

Declaration

Swift

public static func +=(a: inout BigInt, b: BigInt)

                        Show on GitHub

© 2016 Károly Lőrentey. (Last updated: 2017-10-10)

Generated by jazzy ♪♫ v0.8.4, a Realm project.


text:
function warmUp() {
    Components.utils.import("resource://hatenabookmark/modules/10-event.jsm");
}

function setUp() {
    EventService.resetListeners();
}

function testEventService() {
    var result = false;
    function f() { result = true; }
    EventService.createListener("EventDispatched", f);
    EventService.dispatch("EventDispatched");
    assert.equals(result, true);
}

function testMultipleListener() {
    var result = [];
    EventService.createListener("AnEvent", function () result.push(1));
    EventService.createListener("AnotherEvent", function () result.push(2));
    EventService.createListener("AnEvent", function () result.push(3));
    EventService.dispatch("AnEvent");
    assert.equals(result, [1, 3]);
}

function testListenerMethods() {
    var result = false;
    function f() result = true;
    var listener = EventService.createListener("EventDispatched", f);

    listener.unlisten();
    EventService.dispatch("EventDispatched");
    assert.equals(result, false);

    result = false;
    listener.listen();
    EventService.dispatch("EventDispatched");
    assert.equals(result, true);
}

function testDOMEventListenerInterface() {
    var result = false;
    var listenerOjbect = { handleEvent: function () result = true };
    EventService.createListener("EventDispatched", listenerOjbect);
    EventService.dispatch("EventDispatched");
    assert.equals(result, true);
}

function testEventData() {
    var result = false;
    EventService.createListener("EventDispatched", function (event) {
        result = event.data;
    });
    EventService.dispatch("EventDispatched", true);
    assert.equals(result, true);
}

function testPreventDefault() {
    EventService.createListener("EventDispatched", function (event) {
        event.preventDefault();
    });
    var result = EventService.dispatch("EventDispatched");
    assert.equals(result, false);
}

function testStopPropagation() {
    var result = [];
    EventService.createListener("EventDispatched", function () result.push(1));
    EventService.createListener("EventDispatched", function (event) {
        result.push(2);
        event.stopPropagation();
    });
    EventService.createListener("EventDispatched", function () result.push(3));
    EventService.dispatch("EventDispatched");
    assert.equals(result, [1, 2]);
}

function testLockKey() {
    var result = [];
    var listeners = [
        EventService.createListener("Event", function () result.push(1), "foo"),
        EventService.createListener("Event", function () result.push(2), null),
        EventService.createListener("Event", function () result.push(3), "foo"),
        EventService.createListener("Event", function () result.push(4), "bar"),
    ];
    EventService.dispatch("Event");
    assert.equals(result, [1, 2, 4]);
    listeners.forEach(function (l) l.unlisten());
}

function testPriority() {
    var result = [];
    EventService.createListener("AnEvent", function () result.push(1));
    EventService.createListener("AnEvent", function () result.push(2), null, 0);
    EventService.createListener("AnEvent", function () result.push(3), null, 2);
    EventService.createListener("AnEvent", function () result.push(4), null, 1);
    EventService.createListener("AnEvent", function () result.push(5), null, 2);
    EventService.createListener("AnEvent", function () result.push(6), null, 1);
    EventService.dispatch("AnEvent");
    assert.equals(result, [3, 5, 4, 6, 1, 2]);
}

function testMultipleListenerMethodCall() {
    var result = [];
    var listener = EventService.createListener("AnEvent", function () result.push(1));
    listener.listen();
    listener.listen();
    EventService.dispatch("AnEvent");
    assert.equals(result, [1]);

    listener.unlisten();
    EventService.dispatch("AnEvent");
    assert.equals(result, [1]);
}

//// XXX getTestWindow()の返り値がnullになる。
//testDisposable.priority = "never";
//function testDisposable() {
//    const EXTENSION_ID = "bookmark@hatena.ne.jp";
//    const em = Cc["@mozilla.org/extensions/manager;1"]
//               .getService(Ci.nsIExtensionManager);
//    let location = em.getInstallLocation(EXTENSION_ID);
//    let srcFile = location.getItemFile(EXTENSION_ID, "tests/javascripts/event-service-test.xul");
//    let destDir = location.getItemFile(EXTENSION_ID, "chrome/content");
//    let copiedFile = utils.cosmeticClone(srcFile, destDir, srcFile.leafName);
//    yield 200;
//
//    let result, win;
//
//    yield utils.setUpTestWindow(function () {}, {
//        uri: "chrome://hatenabookmark/content/event-service-test.xul"
//    });
//    result = false;
//    win = utils.getTestWindow();
//    win.callback = function () result = true;
//    win.createDisposableListener();
//    EventService.dispatch("AnEvent");
//    assert.equals(result, true);
//
//    utils.closeTestWindow();
//    result = false;
//    EventService.dispatch("AnEvent");
//    assert.equals(result, false);
//
//    let listener;
//
//    yield utils.setUpTestWindow(function () {}, {
//        uri: "chrome://hatenabookmark/content/event-service-test.xul"
//    });
//    result = false;
//    win = utils.getTestWindow();
//    win.callback = function () result = true;
//    listener = win.createNonDisposableListener();
//    EventService.dispatch("AnEvent");
//    assert.equals(result, true);
//
//    utils.closeTestWindow();
//    result = false;
//    EventService.dispatch("AnEvent");
//    assert.equals(result, true);
//
//    listener.unlisten();
//    result = false;
//    EventService.dispatch("AnEvent");
//    assert.equals(result, false);
//
//    utils.scheduleToRemove(copiedFile);
//}

function testImplement() {
    var dispatcher = {};
    var ret = EventService.implement(dispatcher);
    assert.isTrue(ret === dispatcher);
    assert.isFunction(dispatcher.createListener);
    result = false;
    dispatcher.createListener("AnEvent", function () result = true);
    EventService.dispatch("AnEvent");
    assert.equals(result, false);
    dispatcher.dispatch("AnEvent");
    assert.equals(result, true);
}


text:
use std::fs::{remove_file, rename, create_dir_all, set_permissions};
use std::fs::{Permissions};
use std::os::unix::fs::PermissionsExt;
use std::path::{Path, PathBuf};

use shaman::digest::Digest;
use shaman::sha2::Sha256;
use unshare::{Command, Stdio};

use super::capsule;
use super::context::BuildContext;
use path_util::PathExt;

pub fn download_file(ctx: &mut BuildContext, url: &str)
    -> Result<PathBuf, String>
{
    let https = url.starts_with("https:");
    if https {
        try!(capsule::ensure_features(ctx, &[capsule::Https]));
    }
    let mut hash = Sha256::new();
    hash.input_str(url);
    let urlpath = Path::new(url);
    let name = match urlpath.file_name().and_then(|x| x.to_str()) {
        Some(name) => name,
        None => "file.bin",
    };
    let name = hash.result_str()[..8].to_string() + "-" + name;
    let dir = Path::new("/vagga/cache/downloads");
    if !dir.exists() {
        try!(create_dir_all(&dir)
            .map_err(|e| format!("Error moving file: {}", e)));
        try!(set_permissions(&dir, Permissions::from_mode(0o755))
            .map_err(|e| format!("Can't chmod file: {}", e)));
    }
    let filename = dir.join(&name);
    if filename.exists() {
        return Ok(filename);
    }
    info!("Downloading image {} -> {}", url, filename.display());
    let tmpfilename = filename.with_file_name(name + ".part");
    let mut cmd = Command::new(
        if https { "/usr/bin/wget" } else { "/vagga/bin/busybox" });
    cmd.stdin(Stdio::null());
    if !https {
        cmd.arg("wget");
    }
    cmd.arg("-O");
    cmd.arg(&tmpfilename);
    cmd.arg(url);

    debug!("Running: {:?}", cmd);
    match cmd.status() {
        Ok(st) if st.success() => {
            try!(rename(&tmpfilename, &filename)
                .map_err(|e| format!("Error moving file: {}", e)));
            Ok(filename)
        }
        Ok(val) => {
            remove_file(&tmpfilename)
                .map_err(|e| error!("Error unlinking cache file: {}", e)).ok();
            Err(format!("Wget exited with status: {}", val))
        }
        Err(x) => {
            remove_file(&tmpfilename)
                .map_err(|e| error!("Error unlinking cache file: {}", e)).ok();
            Err(format!("Error starting wget: {}", x))
        }
    }
}


text:
import {
    skip,
    skipNode,
    importNode,
    currentElement,
    currentPointer,
    elementOpen,
    elementOpenStart,
    elementOpenEnd,
    elementClose,
    elementVoid,
    attr,
    text,
    applyAttr,
    applyProp,
    patch,
    patchOuter,
    symbols,
    attributes,
    notifications,
} from 'incremental-dom/index.js';

const CALLBACKS = {
    beforeOpen: [],
    afterOpen: [],
    beforeClose: [],
    afterClose: [],
    beforeText: [],
    afterText: [],
    beforeAttr: [],
    afterAttr: [],
};

function trigger(clb, ...args) {
    for (let i = 0, len = CALLBACKS[clb].length; i < len; i++) {
        let res = CALLBACKS[clb][i].call(IDOM, ...args);
        if (res === false) {
            return false;
        }
    }
    return true;
}

/**
 * IncrementalDOM wrapper.
 */
export class IDOM {
    /**
     * @private
     */
    static close(...args) { return close(...args); }
    /**
     * @private
     */
    static skip(...args) { return skip(...args); }
    /**
     * @private
     */
    static skipNode(...args) { return skipNode(...args); }
    /**
     * @private
     */
    static importNode(...args) { return importNode(...args); }
    /**
     * @private
     */
    static currentElement(...args) { return currentElement(...args); }
    /**
     * @private
     */
    static currentPointer(...args) { return currentPointer(...args); }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/elementOpen IncrementalDOM.elementOpen}
     */
    static elementOpen(...args) {
        if (trigger('beforeOpen', ...args)) {
            let res = elementOpen(...args);
            let clb = trigger('afterOpen', res);
            if (clb === false) {
                this.elementClose(args[0]);
                return false;
            }
            return res;
        }
    }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/elementOpenStart IncrementalDOM.elementOpenStart}
     */
    static elementOpenStart(...args) {
        if (trigger('beforeOpen', ...args)) {
            let res = elementOpenStart(...args);
            return res || true;
        }
    }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/elementOpenEnd IncrementalDOM.elementOpenEnd}
     */
    static elementOpenEnd(...args) {
        let res = elementOpenEnd(...args);
        let clb = trigger('afterOpen', res);
        if (clb === false) {
            this.elementClose(args[0]);
            return false;
        }
        return res;
    }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/elementClose IncrementalDOM.elementClose}
     */
    static elementClose(...args) {
        if (trigger('beforeClose', ...args)) {
            let res = elementClose(...args);
            return trigger('afterClose', res) || res;
        }
    }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/elementVoid IncrementalDOM.elementVoid}
     */
    static elementVoid(...args) {
        if (trigger('beforeOpen', ...args)) {
            let res = elementVoid(...args);
            return trigger('afterOpen', res) || res;
        }
    }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/attr IncrementalDOM.attr}
     */
    static attr(...args) {
        if (trigger('beforeAttr', ...args)) {
            let res = attr(...args);
            return trigger('afterAttr', res) || res;
        }
    }
    /**
     * Wrap the IncrementalDOM.text function with some arguments checks.
     * @see {@link http://google.github.io/incremental-dom/#api/text IncrementalDOM.text}
     * @param {String} str The text to render.
     */
    static text(str) {
        if (trigger('beforeText', str)) {
            if (typeof str === 'undefined') {
                str = '';
            }
            let res = text(str);
            return trigger('afterText', res) || res;
        }
    }
    /**
     * @private
     */
    static applyAttr(...args) { return applyAttr(...args); }
    /**
     * @private
     */
    static applyProp(...args) { return applyProp(...args); }
    /**
     * @see {@link http://google.github.io/incremental-dom/#api/patch IncrementalDOM.patch}
     */
    static patch(...args) { return patch(...args); }
    /**
     * @private
     */
    static patchOuter(...args) { return patchOuter(...args); }
    /**
     * @private
     */
    static get symbols() { return symbols; }
    /**
     * @private
     */
    static get attributes() { return attributes; }
    /**
     * @private
     */
    static get notifications() { return notifications; }

    static beforeElementOpen(cb) {
        CALLBACKS.beforeOpen.push(cb);
    }

    static afterElementOpen(cb) {
        CALLBACKS.afterOpen.push(cb);
    }

    static beforeElementClose(cb) {
        CALLBACKS.beforeClose.push(cb);
    }

    static afterElementClose(cb) {
        CALLBACKS.afterClose.push(cb);
    }

    static beforeText(cb) {
        CALLBACKS.beforeText.push(cb);
    }

    static afterText(cb) {
        CALLBACKS.afterText.push(cb);
    }

    static beforeAttr(cb) {
        CALLBACKS.beforeAttr.push(cb);
    }

    static afterAttr(cb) {
        CALLBACKS.afterAttr.push(cb);
    }
}


text:
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

namespace Microsoft.Azure.Management.TrafficManager.Fluent
{
    /// <summary>
    /// Possible endpoint types supported in a Traffic manager profile.
    /// </summary>
    public class EndpointType : ExpandableStringEnum<EndpointType>
    {
        public static readonly EndpointType Azure = Parse("Microsoft.Network/trafficManagerProfiles/azureEndpoints");
        public static readonly EndpointType External = Parse("Microsoft.Network/trafficManagerProfiles/externalEndpoints");
        public static readonly EndpointType NestedProfile = Parse("Microsoft.Network/trafficManagerProfiles/nestedEndpoints");

        /// <summary>
        /// Gets the local name of the endpoint type.
        /// </summary>
        public string LocalName
        {
            get
            {
                if (Value != null)
                {
                    return Value.Substring(Value.LastIndexOf('/') + 1);
                }
                return null;
            }
        }
    }
}


text:
@implementation RACSignal (Mantle)

#pragma mark - Public API

- (RACSignal *)parseResponseAtKey:(id)key forClass:(Class)klass {
  return [self parseResponseWithMapping:@{ key : klass }];
}

- (RACSignal *)parseResponseForClass:(Class)klass {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    [self subscribeNext:^(id response) {
      NSError *error;

      id object = [self objectForResponse:response andKlass:klass error:&error];
      if (error) { [subscriber sendError:error]; }

      [subscriber sendNext:object];
    }];

    [self subscribeError:^(NSError *error) {
      [subscriber sendError:error];
    }];

    [self subscribeCompleted:^{
      [subscriber sendCompleted];
    }];

    return nil;
  }];
}

- (RACSignal *)parseResponseWithMapping:(NSDictionary *)mapping {
  return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    [self subscribeNext:^(id response) {

      NSMutableDictionary *objects = [NSMutableDictionary dictionary];

      for (NSString *key in [mapping allKeys]) {
        Class klass = mapping[key];

        NSError *error;
        id object = [self objectForResponse:response[key] andKlass:klass error:&error];
        if (error) { [subscriber sendError:error]; }

        objects[key] = object;
      }

      [subscriber sendNext:objects];
    }];

    [self subscribeError:^(NSError *error) {
      [subscriber sendError:error];
    }];

    [self subscribeCompleted:^{
      [subscriber sendCompleted];
    }];

    return nil;
  }];
}

#pragma mark - Helpers

- (id)objectForResponse:(id)response andKlass:(Class)klass error:(NSError **)error {
  id object = [response isKindOfClass:[NSArray class]] ?
  [MTLJSONAdapter modelsOfClass:klass fromJSONArray:response error:error] :
  [MTLJSONAdapter modelOfClass:klass fromJSONDictionary:response error:error];

  return object;
}

@end