text:
from ackward import (Class,
                     ClassProperty,
                     Constructor,
                     InlineFunction,
                     Namespace,
                     Property,
                     TranslationUnit)

eq_operator='''
bool operator==(const TimeDelta& td) const
{ return obj() == td.obj(); }
'''

ne_operator='''
bool operator!=(const TimeDelta& td) const
{ return obj() != td.obj(); }
'''

lt_operator='''
bool operator<(const TimeDelta& td) const
{ return obj() < td.obj(); }
'''

le_operator='''
bool operator<=(const TimeDelta& td) const
{ return obj() <= td.obj(); }
'''

gt_operator='''
bool operator>(const TimeDelta& td) const
{ return obj() > td.obj(); }
'''

ge_operator='''
bool operator>=(const TimeDelta& td) const
{ return obj() >= td.obj(); }
'''

add_operator='''
inline TimeDelta operator+(const TimeDelta& lhs, const TimeDelta& rhs)
{ return lhs.obj() + rhs.obj(); }
'''

sub_operator='''
inline TimeDelta operator-(const TimeDelta& lhs, const TimeDelta& rhs)
{ return lhs.obj() - rhs.obj(); }
'''

mul_operator='''
inline TimeDelta operator*(const TimeDelta& lhs, unsigned long d)
{ return lhs.obj() * d; }
'''

div_operator='''
inline TimeDelta operator/(const TimeDelta& lhs, long rhs)
{ return lhs.obj() / rhs; }
'''

neg_operator='''
inline TimeDelta operator-(const TimeDelta& td)
{ return td.obj().attr("__neg__")(); }
'''

abs_function='''
inline TimeDelta abs(const TimeDelta& td)
{ return td.obj().attr("__abs__")(); }
'''

def tunit():
    return TranslationUnit(
        impl_includes=[
            ('ackward', 'datetime', 'TimeDelta.hpp')
            ])

def timedelta_class(parent):
    cls = Class(name='TimeDelta',
                wrapped_class='datetime.timedelta',
                parent=parent)

    Constructor(
        signature=[('double', 'days', '0'),
                   ('double', 'seconds', '0'),
                   ('double', 'microseconds', '0'),
                   ('double', 'milliseconds', '0'),
                   ('double', 'minutes', '0'),
                   ('double', 'hours', '0'),
                   ('double', 'weeks', '0')],
        parent=cls)

    Property(
        type='int',
        name='days',
        read_only=True,
        parent=cls)

    Property(
        type='unsigned int',
        name='seconds',
        read_only=True,
        parent=cls)

    Property(
        type='unsigned int',
        name='microseconds',
        read_only=True,
        parent=cls)

    ClassProperty(
        type='TimeDelta',
        name='min',
        read_only=True,
        parent=cls)

    ClassProperty(
        type='TimeDelta',
        name='max',
        read_only=True,
        parent=cls)

    ClassProperty(
        type='TimeDelta',
        name='resolution',
        read_only=True,
        parent=cls)

    InlineFunction(code=eq_operator, parent=cls)
    InlineFunction(code=ne_operator, parent=cls)
    InlineFunction(code=lt_operator, parent=cls)
    InlineFunction(code=le_operator, parent=cls)
    InlineFunction(code=gt_operator, parent=cls)
    InlineFunction(code=ge_operator, parent=cls)

def definition(env):
    t = tunit()
    n = Namespace('ackward', 'datetime', parent=t)
    timedelta_class(parent=n)

    InlineFunction(code=add_operator, parent=n)
    InlineFunction(code=sub_operator, parent=n)
    InlineFunction(code=mul_operator, parent=n)
    InlineFunction(code=div_operator, parent=n)
    InlineFunction(code=neg_operator, parent=n)
    InlineFunction(code=abs_function, parent=n)

    return t


text:
package April2021PrepLeetcode;

import java.util.PriorityQueue;

public class _0703KthLargestElementInAStream {

	public static void main(String[] args) {
		KthLargest kthLargest = new KthLargest(3, new int[] { 4, 5, 8, 2 });
		System.out.println(kthLargest.add(3)); // return 4
		System.out.println(kthLargest.add(5)); // return 5
		System.out.println(kthLargest.add(10)); // return 5
		System.out.println(kthLargest.add(9)); // return 8
		System.out.println(kthLargest.add(4)); // return 8
	}

	static class KthLargest {
		PriorityQueue<Integer> pq;
		int size;

		public KthLargest(int k, int[] nums) {
			pq = new PriorityQueue<Integer>();
			size = k;

			for (int i = 0; i < nums.length; i++) {
				pq.offer(nums[i]);
				if (pq.size() > k)
					pq.poll();
			}
		}

		public int add(int val) {
			pq.offer(val);
			if (pq.size() > size)
				pq.poll();
			return pq.peek();
		}
	}

}

redpajama_set_name: RedPajamaGithub


text:
'''

Do snapshot on VM root volume and do some vm ops with expunge

This case is coming from a bug.

@author: Youyk
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.zstack_test.zstack_test_snapshot as zstack_sp_header
import zstackwoodpecker.zstack_test.zstack_test_volume as zstack_vol_header
import zstackwoodpecker.header.volume as vol_header
import zstackwoodpecker.operations.config_operations as conf_ops

import os
import time

test_stub = test_lib.lib_get_test_stub()
test_obj_dict = test_state.TestStateDict()

def test():
    if conf_ops.get_global_config_value('vm', 'deletionPolicy') == 'Direct' :
        test_util.test_skip('vm delete_policy is Direct, skip test.')
        return
    test_util.test_dsc('Create original vm')
    vm = test_stub.create_vm(vm_name = 'basic-test-vm')
    test_obj_dict.add_vm(vm)

    root_volume_uuid = test_lib.lib_get_root_volume_uuid(vm.get_vm())
    test_util.test_dsc('Stop vm before create snapshot.')
    vm.stop()

    test_util.test_dsc('create snapshot and check')
    snapshots = test_obj_dict.get_volume_snapshot(root_volume_uuid)

    snapshots.set_utility_vm(vm)
    snapshots.create_snapshot('create_root_snapshot1')
    test_util.test_dsc('start vm')
    vm.destroy()
    vm.recover()
    vm.start()
    vm.destroy()
    vm.expunge()
    test_obj_dict.rm_vm(vm)
    test_lib.lib_robot_cleanup(test_obj_dict)
    test_util.test_pass('Do snapshot ops on VM root volume with VM ops successfully')

#Will be called only if exception happens in test().
def error_cleanup():
    test_lib.lib_error_cleanup(test_obj_dict)


text:
package org.springframework.security.messaging.access.expression;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.expression.Expression;

import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Mockito.when;

@RunWith(MockitoJUnitRunner.class)
public class MessageExpressionConfigAttributeTests {
	@Mock
	Expression expression;

	MessageExpressionConfigAttribute attribute;

	@Before
	public void setup() {
		attribute = new MessageExpressionConfigAttribute(expression);
	}

	@Test(expected = IllegalArgumentException.class)
	public void constructorNullExpression() {
		new MessageExpressionConfigAttribute(null);
	}

	@Test
	public void getAuthorizeExpression() {
		assertThat(attribute.getAuthorizeExpression()).isSameAs(expression);
	}

	@Test
	public void getAttribute() {
		assertThat(attribute.getAttribute()).isNull();
	}

	@Test
	public void toStringUsesExpressionString() {
		when(expression.getExpressionString()).thenReturn("toString");

		assertThat(attribute.toString()).isEqualTo(expression.getExpressionString());
	}
}


text:
<?php

namespace Earls\LionBiBundle\Tests\FunctionalTests\Model;

use Doctrine\Common\DataFixtures\Executor\ORMExecutor;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\DataFixtures\Purger\ORMPurger;
use Symfony\Bridge\Doctrine\DataFixtures\ContainerAwareLoader;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\StringInput;
use Symfony\Component\Console\Output\StreamOutput;

/**
 * Earls\LionBiBundle\Tests\FunctionalTests\Model\FixtureAwareTestCase
 **/
abstract class FixtureAwareTestCase extends WebTestCase
{
    /**
     * @var ORMExecutor
     */
    private $fixtureExecutor;

    /**
     * @var ContainerAwareLoader
     */
    private $fixtureLoader;

    public function setUp()
    {
        self::bootKernel();
    }

    /**
     * Adds a new fixture to be loaded.
     *
     * @param FixtureInterface $fixture
     */
    protected function addFixture(FixtureInterface $fixture)
    {
        $this->getFixtureLoader()->addFixture($fixture);
    }

    protected function initTestDatabase()
    {
        $this->runCommand('doctrine:database:drop --force');
        $this->runCommand('doctrine:database:create');
        $this->runCommand('doctrine:schema:create');
    }

    /**
     * Executes all the fixtures that have been loaded so far.
     */
    protected function executeFixtures()
    {
        $this->initTestDatabase();
        $this->getFixtureExecutor()->execute($this->getFixtureLoader()->getFixtures(), true);
    }

    /**
     * @return ORMExecutor
     */
    private function getFixtureExecutor()
    {
        if (!$this->fixtureExecutor) {
            /** @var \Doctrine\ORM\EntityManager $entityManager */
            $entityManager = self::$kernel->getContainer()->get('doctrine')->getManager();
            $this->fixtureExecutor = new ORMExecutor($entityManager, new ORMPurger($entityManager));
        }

        return $this->fixtureExecutor;
    }

    /**
     * @return ContainerAwareLoader
     */
    private function getFixtureLoader()
    {
        if (!$this->fixtureLoader) {
            $this->fixtureLoader = new ContainerAwareLoader(self::$kernel->getContainer());
        }

        return $this->fixtureLoader;
    }

    public function runCommand($command)
    {
        $client = self::createClient();
        $application = new Application($client->getKernel());
        $application->setAutoExit(false);

        $fp = tmpfile();
        $input = new StringInput($command);
        $output = new StreamOutput($fp);

        $application->run($input, $output);

        fseek($fp, 0);
        $output = '';
        while (!feof($fp)) {
            $output = fread($fp, 4096);
        }
        fclose($fp);

        return $output;
    }

    protected function getContainer()
    {
        self::bootKernel();
        return self::$kernel->getContainer();
    }
}


text:
<?php

/**
 * @see PHPUnit_Framework_TestSuite
 */
require_once 'PHPUnit/Framework/TestSuite.php';

/**
 * Zym testsuite
 *
 * @author Geoffrey Tran
 * @license http://www.zym-project.com/license New BSD License
 * @category Zym
 * @package Zym_PhpUnit
 * @subpackage Framework
 * @copyright Copyright (c) 2008 Zym. (http://www.zym-project.com/)
 */
class Zym_PhpUnit_Framework_TestSuite extends PHPUnit_Framework_TestSuite
{
    /**
     * Construct
     *
     * @return void
     */
    public function __construct($currentFile)
    {
        $this->setName($this->_createName());

        $name  = substr($this->getName(), 0, -5);
        $path  = dirname($currentFile);
        $tests = array();

        $componentFile = $path . "/{$name}Test.php";
        if (file_exists($componentFile)) {
            $tests[] = $componentFile;
        }

        $componentDir = $path . '/' . $name;
        if (file_exists($componentDir)) {
            $iterator = new RecursiveDirectoryIterator($componentDir);
            foreach(new RecursiveIteratorIterator($iterator) as $file) {
                if ($file->isFile() && substr($file, -8) == 'Test.php') {
                    $tests[] = (string) $file;
                }
            }
        }

        $this->addTestFiles($tests);
    }

    /**
     * Get suite
     *
     * @return Zym_PhpUnit_Framework_TestSuite
     */
    public static function suite()
    {
        return new self(__FILE__);
    }

    /**
     * Create name
     *
     * @return string
     */
    protected function _createName()
    {
        $parts = explode('_', get_class($this));
        $name  = $parts[count($parts) - 1];

        return $name;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;

// Test types used to make proxies.
public interface TestType_IHelloService
{
    string Hello(string message);
}

public interface TestType_IGoodbyeService
{
    string Goodbye(string message);
}

// Demonstrates interface implementing multiple other interfaces
public interface TestType_IHelloAndGoodbyeService : TestType_IHelloService, TestType_IGoodbyeService
{
}

// Deliberately contains method with same signature of TestType_IHelloService (see TestType_IHelloService1And2).
public interface TestType_IHelloService2
{
    string Hello(string message);
}

// Demonstrates 2 interfaces containing same method name dispatches to the right one
public interface TestType_IHelloService1And2 : TestType_IHelloService, TestType_IHelloService2
{
}

// Demonstrates methods taking multiple parameters as well as a params parameter
public interface TestType_IMultipleParameterService
{
    double TestMethod(int i, string s, double d);
    object ParamsMethod(params object[] parameters);
}

// Demonstrate a void-returning method and parameterless method
public interface TestType_IOneWay
{
    void OneWay();
}

// Demonstrates proxies can be made for properties.
public interface TestType_IPropertyService
{
    string ReadWrite { get; set; }
}

// Demonstrates proxies can be made for internal types
internal interface TestType_InternalInterfaceService
{
    string Echo(string message);
}

// Demonstrates proxies can be made for public types implementing internal interfaces
internal interface TestType_PublicInterfaceService_Implements_Internal : TestType_InternalInterfaceService
{
    string Echo2(string message);
}

// Negative -- demonstrates trying to use a class for the interface type for the proxy
public class TestType_ConcreteClass
{
    public string Echo(string s) { return null; }
}

// Negative -- demonstrates base type that is sealed and should generate exception
public sealed class Sealed_TestDispatchProxy : DispatchProxy
{
    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        throw new InvalidOperationException();
    }
}

// This test double creates a proxy instance for the requested 'ProxyT' type.
// When methods are invoked on that proxy, it will call a registered callback.
public class TestDispatchProxy : DispatchProxy
{
    // Gets or sets the Action to invoke when clients call methods on the proxy.
    public Func<MethodInfo, object[], object> CallOnInvoke { get; set; }

    // Gets the proxy itself (which is always 'this')
    public object GetProxy()
    {
        return this;
    }

    // Implementation of DispatchProxy.Invoke() just calls back to given Action
    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        return CallOnInvoke(targetMethod, args);
    }
}

public class TestDispatchProxy2 : TestDispatchProxy
{
}

// Negative test -- demonstrates base type that is abstract
public abstract class Abstract_TestDispatchProxy : DispatchProxy
{
    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        throw new InvalidOperationException();
    }
}

// Negative -- demonstrates base type that has no public default ctor
public class NoDefaultCtor_TestDispatchProxy : DispatchProxy
{
    private NoDefaultCtor_TestDispatchProxy()
    {
    }
    protected override object Invoke(MethodInfo targetMethod, object[] args)
    {
        throw new InvalidOperationException();
    }
}


text:
#!/usr/bin/env node

'use strict';

const {loadAndParseRcFile, resolveRcFilePath} = require('../packages/utils/src/lighthouserc.js');
const ApiClient = require('../packages/utils/src/api-client.js');
const {writeSeedDataToApi} = require('../packages/utils/src/seed-data/seed-data.js');
const {createActualTestDataset} = require('../packages/server/test/test-utils.js');
const {
  createDefaultDataset,
  createLoadTestDataset,
} = require('../packages/utils/src/seed-data/dataset-generator.js');

if (process.argv.length !== 3 && process.argv.length !== 4) {
  process.stderr.write(`Usage ./scripts/seed-database.js <path to rc file> [--load]`);
  process.exit(1);
}

async function run() {
  const {serverBaseUrl} = loadAndParseRcFile(resolveRcFilePath(process.argv[2]));
  if (!serverBaseUrl) throw new Error('RC file did not set the serverBaseUrl');

  const api = new ApiClient({rootURL: serverBaseUrl});
  await writeSeedDataToApi(
    api,
    process.argv.includes('--load')
      ? createLoadTestDataset()
      : process.argv.includes('--actual')
      ? createActualTestDataset()
      : createDefaultDataset()
  );
}

run();


text:
    width: 80%;
    height: 80%;
    border: 1px solid gray;
    position: absolute;
}

#position {
    width: 80%;
    height: 10%;
    border: 1px solid gray;
    position: absolute;
    background-color: #cacfd2;
    margin-top: 517px;
}


text:
package views.sicandcompliance

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import views.VatRegViewSpec
import views.html.sicandcompliance.about_to_confirm_sic

class AboutToConfirmSicViewSpec extends VatRegViewSpec {

  val view: about_to_confirm_sic = app.injector.instanceOf[about_to_confirm_sic]

  val heading = "You are about to confirm the business's Standard Industry Classification (SIC) codes for VAT"
  val title = s"$heading - Register for VAT - GOV.UK"
  val para1 = "A SIC code describes a business activity."
  val para2 = "Every business has one or more SIC codes. If the business registered with Companies House, it had to provide at least one."
  val para3 = "You must:"
  val para4 = "We will guide you through this process."
  val bullet1 = "check the SIC codes for this business are still correct."
  val bullet2 = "add any more SIC codes that are relevant to the business's activity."
  val continue = "Continue"

  implicit val doc: Document = Jsoup.parse(view().body)

  "The Join FRS page" must {
    "have a back link" in new ViewSetup {
      doc.hasBackLink mustBe true
    }

    "have the correct heading" in new ViewSetup {
      doc.heading mustBe Some(heading)
    }

    "have the correct page title" in new ViewSetup {
      doc.title mustBe title
    }

    "have correct text" in new ViewSetup {
      doc.para(1) mustBe Some(para1)
      doc.para(2) mustBe Some(para2)
      doc.para(3) mustBe Some(para3)
      doc.para(4) mustBe Some(para4)
    }

    "have correct bullets" in new ViewSetup {
      doc.unorderedList(1) mustBe List(
        bullet1,
        bullet2
      )
    }

    "have a save and continue button" in new ViewSetup {
      doc.submitButton mustBe Some(continue)
    }
  }

}


text:
package org.teavm.flavour.expr.ast;

import java.util.ArrayList;
import java.util.List;

public class ExprCopier implements ExprVisitor<Expr> {
    @Override
    public Expr visit(BinaryExpr expr) {
        Expr firstOperand = expr.getFirstOperand().acceptVisitor(this);
        Expr secondOperand = expr.getSecondOperand().acceptVisitor(this);
        return copyLocation(new BinaryExpr(firstOperand, secondOperand, expr.getOperation()), expr);
    }

    @Override
    public Expr visit(CastExpr expr) {
        Expr operand = expr.getValue().acceptVisitor(this);
        return copyLocation(new CastExpr(operand, expr.getTargetType()), expr);
    }

    @Override
    public Expr visit(InstanceOfExpr expr) {
        Expr operand = expr.getValue().acceptVisitor(this);
        return copyLocation(new InstanceOfExpr(operand, expr.getCheckedType()), expr);
    }

    @Override
    public Expr visit(InvocationExpr expr) {
        Expr instance = expr.getInstance() != null ? expr.getInstance().acceptVisitor(this) : null;
        List<Expr> arguments = new ArrayList<>();
        for (Expr arg : expr.getArguments()) {
            arguments.add(arg.acceptVisitor(this));
        }
        return copyLocation(new InvocationExpr(instance, expr.getMethodName(), arguments), expr);
    }

    @Override
    public Expr visit(StaticInvocationExpr expr) {
        List<Expr> arguments = new ArrayList<>();
        for (Expr arg : expr.getArguments()) {
            arguments.add(arg.acceptVisitor(this));
        }
        return copyLocation(new StaticInvocationExpr(expr.getClassName(), expr.getMethodName(), arguments), expr);
    }

    @Override
    public Expr visit(PropertyExpr expr) {
        Expr instance = expr.getInstance().acceptVisitor(this);
        return copyLocation(new PropertyExpr(instance, expr.getPropertyName()), expr);
    }

    @Override
    public Expr visit(StaticPropertyExpr expr) {
        return copyLocation(new StaticPropertyExpr(expr.getClassName(), expr.getPropertyName()), expr);
    }

    @Override
    public Expr visit(UnaryExpr expr) {
        Expr operand = expr.getOperand().acceptVisitor(this);
        return copyLocation(new UnaryExpr(operand, expr.getOperation()), expr);
    }

    @Override
    public Expr visit(VariableExpr expr) {
        return copyLocation(new VariableExpr(expr.getName()), expr);
    }

    @Override
    public Expr visit(ConstantExpr expr) {
        return copyLocation(new ConstantExpr(expr.getValue()), expr);
    }

    @Override
    public Expr visit(TernaryConditionExpr expr) {
        Expr condition = expr.getCondition().acceptVisitor(this);
        Expr consequent = expr.getConsequent().acceptVisitor(this);
        Expr alternative = expr.getAlternative().acceptVisitor(this);
        return copyLocation(new TernaryConditionExpr(condition, consequent, alternative), expr);
    }

    @Override
    public Expr visit(ThisExpr expr) {
        return copyLocation(new ThisExpr(), expr);
    }

    @Override
    public Expr visit(LambdaExpr expr) {
        Expr body = expr.getBody().acceptVisitor(this);
        return copyLocation(new LambdaExpr(body, expr.getBoundVariables()), expr);
    }

    @Override
    public Expr visit(AssignmentExpr expr) {
        Expr target = expr.getTarget().acceptVisitor(this);
        Expr value = expr.getValue().acceptVisitor(this);
        return copyLocation(new AssignmentExpr(target, value), expr);
    }

    private Expr copyLocation(Expr expr, Expr from) {
        expr.setStart(from.getStart());
        expr.setEnd(from.getEnd());
        return expr;
    }
}


text:
angular.module('futurism')
    .controller('navBarCtrl', function($scope, $rootScope, me, $, messager, session, $location, unread, socket, modals, websites, sound) {
        'use strict';

        $scope.path = '/';
        $scope.me = me;
        $scope.messager = messager;
        $scope.unread = unread;
        $scope.sound = sound;

        $rootScope.$on('$routeChangeSuccess', function() {
            $scope.path = $location.url();
        });

        $scope.atDeckBuilder = function() {
            return $scope.path.indexOf('/deck-builder') !== -1 || $scope.path.indexOf('/deck-selector') !== -1;
        };

        $scope.atCardBuilder = function() {
            return $scope.path.indexOf('/card-builder') !== -1 || $scope.path.indexOf('/card-selector') !== -1;
        };

        $scope.atLobby = function() {
            return $scope.path === '/lobby';
        };

        $scope.atStore = function() {
            return $scope.path === '/t-machine';
        };

        $scope.atGuild = function() {
            return $scope.path === '/guild' || $scope.path === '/guild-joiner' || $scope.path === '/guild-list';
        };

        $scope.atGame = function() {
            return $scope.path.indexOf('/game') !== -1;
        };

        $scope.clickStats = function() {
            modals.openUser(me.user._id);
        };

        $scope.clickInvites = function() {
            modals.openInvites();
        };

        $scope.clickApplicants = function() {
            modals.openApplicants();
        };

        $scope.shouldShow = function() {
            return $scope.path !== '/title' && $scope.path !== '/';
        };

        $scope.logout = function() {
            socket.disconnect();
            session.destroy();
            websites.logout();
            $location.url('/');
        };

        /**
         * Close the responsive navbar when a link is clicked
         */
        $(document).on('click','.navbar-collapse.in',function(e) {
            if( $(e.target).is('a') ) {
                $(this).collapse('hide');
            }
        });
    });


text:
groovylib
=========

GroovyLib


text:
<?php

namespace Kuborgh\LogentriesBundle\Transport;

/**
 * Send logentries via Guzzle HTTP
 */
interface TransportInterface
{
    /**
     * Transport constructor
     *
     * @param array $params Service parameters
     */
    public function __construct(array $params);

    /**
     * Send a custom message to a custom logentries channel
     *
     * @param string $json Data in JSON format
     */
    public function send($json);
}


text:
@class SBAddress4LevelModelProvince;
@class SBAddress4LevelModelCity;
@class SBAddress4LevelModelCounty;
@class SBAddress4LevelModelStreet;

/// 四级地址 model
@interface SBAddress4LevelModel : NSObject

@property (nonatomic , strong) SBAddress4LevelModelProvince * modelProvince;
@property (nonatomic , strong) SBAddress4LevelModelCity     * modelCity;
@property (nonatomic , strong) SBAddress4LevelModelCounty   * modelCounty;
@property (nonatomic , strong) SBAddress4LevelModelStreet   * modelStreet;

@property (nonatomic , strong) NSString * aName;
@property (nonatomic , assign) NSInteger  aId;

@property (nonatomic , assign) NSInteger  afromId;

@property (nonatomic , assign) BOOL isSelected;

@end

/// 省级model
@interface SBAddress4LevelModelProvince : SBAddress4LevelModel

///// 省id
//@property (nonatomic , assign) NSInteger    provinceId;
///// 省名
//@property (nonatomic , strong) NSString *   strProvinceName;

@end

/// 市级model
@interface SBAddress4LevelModelCity : SBAddress4LevelModel

///// 市id
//@property (nonatomic , assign) NSInteger    cityId;
///// 市名
//@property (nonatomic , strong) NSString *   strCityName;
/// 城市所在省级id
//@property (nonatomic , assign) NSInteger    cityAtProvinceId;

@end

/// 区级model
@interface SBAddress4LevelModelCounty : SBAddress4LevelModel

///// 区id
//@property (nonatomic , assign) NSInteger    countyId;
///// 区名
//@property (nonatomic , strong) NSString *   strCountyName;
/// 地区所在城市级id
//@property (nonatomic , assign) NSInteger    countyAtCityId;

@end

/// 街道model
@interface SBAddress4LevelModelStreet : SBAddress4LevelModel

///// 街道id
//@property (nonatomic , assign) NSInteger    streetId;
///// 街道名
//@property (nonatomic , strong) NSString *   strStreetName;
/// 街道所在城地区id
//@property (nonatomic , assign) NSInteger    streetAtCountyId;

@end


text:
<!DOCTYPE html>

		<title>three.js PMREM directional light test</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
		<link type="text/css" rel="stylesheet" href="main.css">

				three.js -
				PMREM directional light test Emmett Lalish

Top row is white metal

Middle row is white dielectric

Bottom row is black dielectric.

Mouse-out is a standard Directional Light.

Mouse-over is a PMREM of the skybox: a single bright pixel representing the same directional light source.

The difference between these renders indicates the error in the PMREM approximations.


text:
<?php

namespace Spatie\Activitylog\Facades;

use Illuminate\Support\Facades\Facade;
use Spatie\Activitylog\LogBatch as ActivityLogBatch;

/**
 * @method static string getUuid()
 * @method static mixed withinBatch(\Closure $callback)
 * @method static void startBatch()
 * @method static void setBatch(string $uuid): void
 * @method static bool isOpen()
 * @method static void endBatch()
 *
 * @see \Spatie\Activitylog\LogBatch
 */
class LogBatch extends Facade
{
    protected static function getFacadeAccessor(): string
    {
        return ActivityLogBatch::class;
    }
}


text:
namespace Microsoft.Azure.Management.DataLake.Analytics.Models
{
    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using Microsoft.Rest.Serialization;
    using Microsoft.Rest.Azure;

    /// <summary>
    /// The response body contains the status of the specified asynchronous
    /// operation, indicating whether it has succeeded, is inprogress, or has
    /// failed. Note that this status is distinct from the HTTP status code
    /// returned for the Get Operation Status operation itself. If the
    /// asynchronous operation succeeded, the response body includes the HTTP
    /// status code for the successful request. If the asynchronous operation
    /// failed, the response body includes the HTTP status code for the
    /// failed request and error information regarding the failure.
    /// </summary>
    public partial class AzureAsyncOperationResult
    {
        /// <summary>
        /// Initializes a new instance of the AzureAsyncOperationResult class.
        /// </summary>
        public AzureAsyncOperationResult() { }

        /// <summary>
        /// Initializes a new instance of the AzureAsyncOperationResult class.
        /// </summary>
        /// <param name="status">the status of the AzureAsuncOperation. Possible values include: 'InProgress', 'Succeeded', 'Failed'</param>
        public AzureAsyncOperationResult(OperationStatus? status = default(OperationStatus?), Error error = default(Error))
        {
            Status = status;
            Error = error;
        }

        /// <summary>
        /// Gets the status of the AzureAsuncOperation. Possible values
        /// include: 'InProgress', 'Succeeded', 'Failed'
        /// </summary>
        [JsonProperty(PropertyName = "status")]
        public OperationStatus? Status { get; private set; }

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "error")]
        public Error Error { get; private set; }

    }
}


text:
import os
import tempfile
import zipfile

def _read_file(path):
    with open(path, "rb") as f:
        return f.read()

def create_predictable_zip(path):
    """
    Create a zip file with predictable sort order and metadata so that MD5 will
    stay consistent if zipping the same content twice.
    Args:
        path (str): absolute path either to a directory to zip up, or an existing zip file to convert.
    Returns: path (str) to the output zip file
    """
    # if path is a directory, recursively enumerate all the files under the directory
    if os.path.isdir(path):
        paths = []
        for root, directories, filenames in os.walk(path):
            paths += [os.path.join(root, filename)[len(path)+1:] for filename in filenames]
        reader = lambda x: _read_file(os.path.join(path, x))
    # otherwise, if it's a zip file, open it up and pull out the list of names
    elif os.path.isfile(path) and os.path.splitext(path)[1] == ".zip":
        inputzip = zipfile.ZipFile(path)
        paths = inputzip.namelist()
        reader = lambda x: inputzip.read(x)
    else:
        raise Exception("The `path` must either point to a directory or to a zip file.")

    # create a temporary zip file path to write the output into
    zippathfd, zippath = tempfile.mkstemp(suffix=".zip")

    with zipfile.ZipFile(zippath, "w") as outputzip:
        # loop over the file paths in sorted order, to ensure a predictable zip
        for filepath in sorted(paths):
            write_file_to_zip_with_neutral_metadata(outputzip, filepath, reader(filepath))
        os.fdopen(zippathfd).close()
    return zippath

def write_file_to_zip_with_neutral_metadata(zfile, filename, content):
    """
    Write the string `content` to `filename` in the open ZipFile `zfile`.
    Args:
        zfile (ZipFile): open ZipFile to write the content into
        filename (str): the file path within the zip file to write into
        content (str): the content to write into the zip
    Returns: None
    """
    info = zipfile.ZipInfo(filename, date_time=(2015, 10, 21, 7, 28, 0))
    info.compress_type = zipfile.ZIP_DEFLATED
    info.comment = "".encode()
    info.create_system = 0
    zfile.writestr(info, content)


text:
namespace operations_research {
FileLineReader::FileLineReader(const char* const filename)
    : filename_(filename),
      line_callback_(nullptr),
      loaded_successfully_(false) {}

FileLineReader::~FileLineReader() {}

void FileLineReader::set_line_callback(Callback1<char*>* const callback) {
  line_callback_.reset(callback);
}

void FileLineReader::Reload() {
  const int kMaxLineLength = 60 * 1024;
  File* const data_file = File::Open(filename_, "r");
  if (data_file == NULL) {
    loaded_successfully_ = false;
    return;
  }

  std::unique_ptr<char[]> line(new char[kMaxLineLength]);
  for (;;) {
    char* const result = data_file->ReadLine(line.get(), kMaxLineLength);
    if (result == NULL) {
      data_file->Close();
      loaded_successfully_ = true;
      return;
    }
    // Chop the last linefeed if present.
    int len = strlen(result);
    if (len > 0 && result[len - 1] == '\n') {  // Linefeed.
      result[--len] = '\0';
    }
    if (len > 0 && result[len - 1] == '\r') {  // Carriage return.
      result[--len] = '\0';
    }
    if (line_callback_.get() != NULL) {
      line_callback_->Run(result);
    }
  }
  data_file->Close();
}

bool FileLineReader::loaded_successfully() const {
  return loaded_successfully_;
}
}  // namespace operations_research


text:
'use strict';

var get = function(url, options) {
  var request = new XMLHttpRequest();
  request.open('GET', encodeURI(url));
  request.onload = function() {
    if (request.status < 400) {
      options.success(request.responseText);
    }
  };
  request.send();
};

var param = function(object) {
  var encodedString = '';
  for (var prop in object) {
    if (object.hasOwnProperty(prop)) {
      if (encodedString.length > 0) {
        encodedString += '&';
      }
      encodedString += encodeURI(prop + '=' + object[prop]);
    }
  }
  return encodedString;
}

var post = function(url, options) {
  var request = new XMLHttpRequest();
  request.open('POST', encodeURI(url), true);
  request.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
  request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
  request.onload = function() {
    if (request.status < 400) {
      options.success();
    }
  };

  request.send(param(options.data));
};

module.exports = {
  get: get,
  post: post
};


text:
if [ -z "$1" ]; then
    echo "Specify app bundle as first parameter"
    exit 1
fi

if [ -z "$APPLE_ID_USER" ] || [ -z "$APPLE_ID_PASSWORD" ]; then
    echo "You need to set your Apple ID credentials with \$APPLE_ID_USER and \$APPLE_ID_PASSWORD."
    exit 1
fi

APP_BUNDLE=$(basename "$1")
APP_BUNDLE_DIR=$(dirname "$1")

cd "$APP_BUNDLE_DIR" || exit 1

# Package app for submission
echo "Generating ZIP archive ${APP_BUNDLE}.zip..."
ditto -c -k --rsrc --keepParent "$APP_BUNDLE" "${APP_BUNDLE}.zip"

# Submit for notarization
echo "Submitting $APP_BUNDLE for notarization..."
RESULT=$(xcrun altool --notarize-app --type osx \
    --file "${APP_BUNDLE}.zip" \
    --primary-bundle-id org.electrum-ltc.electrum-ltc \
    --username $APPLE_ID_USER \
    --password @env:APPLE_ID_PASSWORD \
    --output-format xml
)

if [ $? -ne 0 ]; then
    echo "Submitting $APP_BUNDLE failed:"
    echo "$RESULT"
    exit 1
fi

REQUEST_UUID=$(echo "$RESULT" | xpath \
    "//key[normalize-space(text()) = 'RequestUUID']/following-sibling::string[1]/text()" 2>/dev/null
)

if [ -z "$REQUEST_UUID" ]; then
    echo "Submitting $APP_BUNDLE failed:"
    echo "$RESULT"
    exit 1
fi

echo "$(echo "$RESULT" | xpath \
    "//key[normalize-space(text()) = 'success-message']/following-sibling::string[1]/text()" 2> /dev/null)"

# Poll for notarization status
echo "Submitted notarization request $REQUEST_UUID, waiting for response..."
sleep 60
while :
do
    RESULT=$(xcrun altool --notarization-info "$REQUEST_UUID" \
        --username "$APPLE_ID_USER" \
        --password @env:APPLE_ID_PASSWORD \
        --output-format xml
    )
    STATUS=$(echo "$RESULT" | xpath \
        "//key[normalize-space(text()) = 'Status']/following-sibling::string[1]/text()" 2>/dev/null
    )

    if [ "$STATUS" = "success" ]; then
        echo "Notarization of $APP_BUNDLE succeeded!"
        break
    elif [ "$STATUS" = "in progress" ]; then
        echo "Notarization in progress..."
        sleep 20
    else
        echo "Notarization of $APP_BUNDLE failed:"
        echo "$RESULT"
        exit 1
    fi
done

# Staple the notary ticket
xcrun stapler staple "$APP_BUNDLE"

# rm zip
rm "${APP_BUNDLE}.zip"


text:
using SocialServicesManager.Interfaces;
using System;

namespace SocialServicesManager.ConsoleUI.Providers
{
    public class ConsoleReader : IReader
    {
        public string ReadLine()
        {
            string result = Console.ReadLine();
            return result;
        }
    }
}


text:
module ApplicationHelper
  include UserStylesHelper

  def get_relative_asset_path
    return "#{controller_name}/#{action_name}"
  end

  def favicon_resolutions_link_tag
    sizes = [16, 32, 96, 160, 192]

    html = [favicon_link_tag()]

    favicon_sizes_link_tag("favicon", sizes, "png", {
      rel: "icon",
      type: "image/png"
    }, html)
  end

  def apple_touch_icon_link_tag
    rel = "apple-touch-icon"
    sizes = [57, 60, 72, 76, 114, 120, 144, 152, 180]

    html = [tag(:meta, {
      name: "apple-mobile-web-app-title",
      content: Rails.configuration.app_name
    })]

    favicon_sizes_link_tag(rel, sizes, "png", {
      rel: rel
    }, html)
  end

  def windows_icon_link_tag
    attributes = [
      { name: "application-name", content: Rails.configuration.app_name },
      { name: "msapplication-TileColor", content: Rails.configuration.windows_tile_color },
      { name: "msapplication-TileImage", content: "/images/mstile-144x144.png" },
      { name: "msapplication-config", content: "/images/browserconfig.xml" }
    ]

    raw(attributes.map { |attribute|
      tag(:meta, attribute)
    }.join())
  end

  private

  def favicon_sizes_link_tag(href_prefix, sizes, format="png", attributes={}, html=[])
    html << sizes.map { |size|
      tag(:link, attributes.merge({
        href: "/images/#{href_prefix}-#{size}x#{size}.#{format}",
        sizes: "#{size}x#{size}"
      }))
    }
    raw(html.join())
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Extensions.Contacts;
using Takenet.MessagingHub.Client.Extensions.Directory;
using Lime.Messaging.Resources;
using Lime.Protocol.Network;
using CooperativeGasPriceBot.Extensions;
using Takenet.MessagingHub.Client.Sender;
using Takenet.MessagingHub.Client;
using CooperativeGasPriceBot.Services;
using Takenet.MessagingHub.Client.Extensions.Resource;
using Lime.Messaging.Contents;
using Takenet.MessagingHub.Client.Extensions.EventTracker;

namespace CooperativeGasPriceBot.Receivers
{
    public abstract class BaseMessageReceiver : IMessageReceiver
    {
        protected readonly IMessagingHubSender _sender;
        protected readonly IContactService _contactService;
        protected readonly IResourceExtension _resource;
        protected readonly IUserContextService _context;
        protected readonly IEventTrackExtension _track;
        protected readonly Settings _settings;

        public BaseMessageReceiver(
            IMessagingHubSender sender,
            IContactService contactService,
            IResourceExtension resource,
            IUserContextService context,
            IEventTrackExtension track,
            Settings settings
            )
        {
            _sender = sender;
            _contactService = contactService;
            _resource = resource;
            _settings = settings;
            _context = context;
            _track = track;
        }

        public async Task ReceiveAsync(Message envelope, CancellationToken cancellationToken = default(CancellationToken))
        {
            var userNode = envelope.From.ToIdentity();
            var contact = await GetContact(userNode, cancellationToken);
            var context = await _context.GetContextAsync(userNode, cancellationToken);
            if (context == null)
            {
                context = new Models.UserContext();
                await _context.SetContextAsync(context, userNode, cancellationToken);
            }

            if (_contactService.IsContactFirstTime(contact))
            {
                await _track.AddAsync("Métricas de Usuários", "Novos usuários", cancellationToken: cancellationToken, identity: userNode);
                var welcomeMessageResource = await _resource.GetAsync<Document>(_settings.Resources.Welcome, cancellationToken);
                await _sender.SendMessageAsync(welcomeMessageResource, userNode, cancellationToken);
            }

            await ProcessAsync(envelope, cancellationToken);

        }

        public abstract Task ProcessAsync(Message envelope, CancellationToken cancellationToken = default(CancellationToken));

        private async Task<Contact> GetContact(Identity userNode, CancellationToken cancellationToken)
        {
            return await _contactService.GetContactAsync(userNode, cancellationToken);
        }
    }
}


text:
package jsettlers.common.map;

/**
 * This enum defines the possible definitions of walkable areas.
 *
 * @author Andreas Eberle
 *
 */
public enum EWalkableTypes {
	SETTLER,
	PLAYER_SETTLER
}


text:
package compute

import "fmt"

type HttpsHealthCheck struct {
	client httpsHealthChecksClient
	name   string
}

func NewHttpsHealthCheck(client httpsHealthChecksClient, name string) HttpsHealthCheck {
	return HttpsHealthCheck{
		client: client,
		name:   name,
	}
}

func (h HttpsHealthCheck) Delete() error {
	err := h.client.DeleteHttpsHealthCheck(h.name)

	if err != nil {
		return fmt.Errorf("Delete: %s", err)
	}

	return nil
}

func (h HttpsHealthCheck) Name() string {
	return h.name
}

func (h HttpsHealthCheck) Type() string {
	return "Https Health Check"
}


text:
"""Background thread handler.

Provides a way to create new threads which are not bound to the creator's
request context and do not need to end before the creator request completes.
"""

import logging
import sys
import thread
import threading
import traceback

from google.appengine.api.logservice import logservice
from google.appengine.runtime import request_environment

BACKGROUND_REQUEST_ID = 'HTTP_X_APPENGINE_BACKGROUNDREQUEST'

class _BackgroundRequest(object):
  """A class for coordinating between a background thread and its creator.

  This facilitates swapping target, args and kwargs for thread_id between the
  background thread creator and the background thread.
  """

  def __init__(self):
    self._ready_condition = threading.Condition()
    self._callable_ready = False
    self._thread_id_ready = False

  def ProvideCallable(self, target, args, kwargs):
    """Sets the target and the args to be provided to this background request.

    Args:
      target: A callable for the background thread to execute.
      args: A tuple of positional args to be passed to target.
      kwargs: A dict of keyword args to be passed to target.

    Returns:
      The thread ID of the thread servicing this background request.
    """
    with self._ready_condition:
      self._target = target
      self._args = args
      self._kwargs = kwargs
      self._callable_ready = True
      self._ready_condition.notify()
      while not self._thread_id_ready:
        self._ready_condition.wait()
      return self._thread_id

  def WaitForCallable(self):
    """Sets the thread ID and returns the callable and args for this request.

    This will block until the request details have been set.

    Returns:
      A tuple (target, args, kwargs) where
        target: A callable for the background thread to execute.
        args: A tuple of positional args to be passed to target.
        kwargs: A dict of keyword args to be passed to target.
    """
    with self._ready_condition:
      self._thread_id = thread.get_ident()
      self._thread_id_ready = True
      self._ready_condition.notify()
      while not self._callable_ready:
        self._ready_condition.wait()
      return self._target, self._args, self._kwargs

class _BackgroundRequestsContainer(object):
  """A container for storing pending background thread requests."""

  def __init__(self):
    self._requests = {}
    self._lock = threading.Lock()

  def _GetOrAddRequest(self, request_id):
    with self._lock:
      if request_id in self._requests:
        return self._requests[request_id]
      else:
        request = _BackgroundRequest()
        self._requests[request_id] = request
        return request

  def _RemoveRequest(self, request_id):
    with self._lock:
      del self._requests[request_id]

  def EnqueueBackgroundThread(self, request_id, target, args, kwargs):
    """Enqueues a new background thread request for a certain request ID.

    Args:
      request_id: A str containing the request ID for this background thread.
      target: A callable for the background thread to execute.
      args: A tuple of positional args to be passed to target.
      kwargs: A dict of keyword args to be passed to target.

    Returns:
      The thread_id of the background thread.
    """
    request = self._GetOrAddRequest(request_id)
    return request.ProvideCallable(target, args, kwargs)

  def RunBackgroundThread(self, request_id):
    """Runs the callable enqueued for the specified request ID."""
    request = self._GetOrAddRequest(request_id)
    target, args, kwargs = request.WaitForCallable()
    self._RemoveRequest(request_id)
    target(*args, **kwargs)

_pending_background_threads = _BackgroundRequestsContainer()

def EnqueueBackgroundThread(request_id, target, args, kwargs):
  """Enqueues a new background thread request for a certain request ID.

  Args:
    request_id: A str containing the request ID for this background thread.
    target: A callable for the background thread to execute.
    args: A tuple of positional args to be passed to target.
    kwargs: A dict of keyword args to be passed to target.

  Returns:
    The thread_id of the background thread.
  """
  return _pending_background_threads.EnqueueBackgroundThread(
      request_id, target, args, kwargs)

def Handle(environ):
  """Handles a background request.

  This function is called by the runtime in response to an /_ah/background
  request.

  Args:
    environ: A dict containing the environ for this request (i.e. for
        os.environ).

  Returns:
    A dict containing:
      error: App Engine error code. 0 if completed successfully, 1 otherwise.
      response_code: The HTTP response code. 200 if completed successfully, 500
          otherwise.
      logs: A list of tuples (timestamp_usec, severity, message) of log
          entries.  timestamp_usec is a long, severity is int and message is
          str.  Severity levels are 0..4 for Debug, Info, Warning, Error,
          Critical.
  """
  error = logservice.LogsBuffer()
  request_environment.current_request.Init(error, environ)
  response = {'error': 0, 'response_code': 200}
  try:
    request_id = environ[BACKGROUND_REQUEST_ID]
    _pending_background_threads.RunBackgroundThread(request_id)
    return response

  except:
    exception = sys.exc_info()

    tb = exception[2].tb_next
    if tb:
      tb = tb.tb_next
    message = ''.join(traceback.format_exception(exception[0], exception[1],
                                                 tb))
    logging.error(message)
    response['response_code'] = 500
    response['error'] = 1
    return response
  finally:
    request_environment.current_request.Clear()
    response['logs'] = error.parse_logs()


text:
```php
require 'vendor/autoload.php';

use mikemix\Wiziq;

$auth    = new Wiziq\API\Auth('your-secret-access-key', 'public-access-key');
$gateway = new Wiziq\API\Gateway($auth);
$api     = new Wiziq\API\ClassroomApi($gateway);

try {
    $classroom = Wiziq\Entity\Classroom::build('Class title', new \DateTime('now'))
        ->withPresenter(100, 'Presenter Name');

    $response  = $api->create($classroom);

    printf('Class %s created: %s', $classroom, var_export($response, true));
} catch (Wiziq\Common\Api\Exception\CallException $e) {
    die($e->getMessage());
} catch (Wiziq\Common\Http\Exception\InvalidResponseException $e) {
    die($e->getMessage());
}
```

### Modify a class

```php
require 'vendor/autoload.php';

use mikemix\Wiziq;

$auth    = new Wiziq\API\Auth('your-secret-access-key', 'public-access-key');
$gateway = new Wiziq\API\Gateway($auth);
$api     = new Wiziq\API\ClassroomApi($gateway);

try {
    $classroomId = 12345;
    $classroom = Wiziq\Entity\Classroom::build('Class title', new \DateTime('now'))
        ->withPresenter(100, 'Presenter Name');

    $response  = $api->modify($classroomId, $classroom);

    printf('Class %s created: %s', $classroom, var_export($response, true));
} catch (Wiziq\Common\Api\Exception\CallException $e) {
    die($e->getMessage());
} catch (Wiziq\Common\Http\Exception\InvalidResponseException $e) {
    die($e->getMessage());
}
```

### Add attendees to the class (not permament one)

```php
require 'vendor/autoload.php';

use mikemix\Wiziq;

$auth    = new Wiziq\API\Auth('your-secret-access-key', 'public-access-key');
$gateway = new Wiziq\API\Gateway($auth);
$api     = new Wiziq\API\ClassroomApi($gateway);

try {
    $classroomId = 12345;
    $attendees   = Wiziq\Entity\Attendees::build()
        ->add(100, 'Mike', 'en-US')
        ->add(101, 'Susan', 'pl-PL');
        // add more if needed

    $response = $api->addAttendeesToClass($classroomId, $attendees);

    printf('Attendees to class %d added: %s', $classroomId, var_export($response, true));
} catch (Wiziq\Common\Api\Exception\CallException $e) {
    die($e->getMessage());
} catch (Wiziq\Common\Http\Exception\InvalidResponseException $e) {
    die($e->getMessage());
}
```

### Create the permanent class

```php
require 'vendor/autoload.php';

use mikemix\Wiziq;

$auth    = new Wiziq\API\Auth('your-secret-access-key', 'public-access-key');
$gateway = new Wiziq\API\Gateway($auth);
$api     = new Wiziq\API\ClassroomApi($gateway);

try {
    $classroom = Wiziq\Entity\PermaClassroom::build('Class title')
        ->withPresenter(100, 'Presenter Name');

    $response  = $api->createPermaClass($classroom);

    printf('Perma class %s created: %s', $classroom, var_export($response, true));
} catch (Wiziq\Common\Api\Exception\CallException $e) {
    die($e->getMessage());
} catch (Wiziq\Common\Http\Exception\InvalidResponseException $e) {
    die($e->getMessage());
}
```


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

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>
  Class: Aceroute::Order

    — Documentation by YARD 0.8.7.6

</title>

  <link rel="stylesheet" href="../css/style.css" type="text/css" charset="utf-8" />

  <link rel="stylesheet" href="../css/common.css" type="text/css" charset="utf-8" />

    Index (O) »
    Aceroute
     »
    Order

(no frames)

      Class List

      Method List

      File List

Class: Aceroute::Order

Inherits:

      Base

Object

Base

Aceroute::Order

        show all

Defined in:

lib/aceroute/order.rb

Instance Attribute Summary (collapse)

      - (Object) cid

Returns the value of attribute cid.

      - (Object) customer

in msec (not sec) since epoch.

      - (Object) description

any freeform text here.

      - (Object) duration

any freeform text here.

      - (Object) id

Returns the value of attribute id.

      - (Object) location

in msec (not sec) since epoch.

      - (Object) purchase_order

any freeform text here.

      - (Object) scheduled

any freeform text here.

      - (Object) start_time

in msec (not sec) since epoch.

      - (Object) summary

any freeform text here.

      - (Object) worker

any freeform text here.

      Class Method Summary
      (collapse)

      + (Object) delete(id)

Deletes Aceroute::Location of given id from Aceroute.

      Instance Method Summary
      (collapse)

      - (Aceroute::Order) create!

Persists Aceroute::Order object to Aceroute API.

      - (Object) destroy!(id = nil)

Deletes this Aceroute::Order object (self) from Aceroute.

      - (Aceroute::Order) initialize(customer, location, start_time, description = nil, duration = 10, scheduled = true, worker = nil, summary = nil, purchase_order = nil)

    constructor

Creates a new Aceroute::Order object.

Constructor Details

    - (<tt>Aceroute::Order</tt>) initialize(customer, location, start_time, description = nil, duration = 10, scheduled = true, worker = nil, summary = nil, purchase_order = nil)

Creates a new Aceroute::Order object. Note this does not persist the
Location to Aceroute, that can be done by calling the create! method on the
new object.

Parameters:

        customer

        (<tt>Aceroute::Customer</tt>)

        —

recipient of this Order

        location

        (<tt>Aceroute::Location</tt>)

        —

location of this Order (delivery destination)

        start_time

        (<tt>Integer</tt>)

        —

start time of Order, in msec since epoch (note: msec not sec)

        description

        (<tt>String</tt>)

        (defaults to: <tt>nil</tt>)

        —

description of Order (e.g., contents of order)

        duration

        (<tt>Integer</tt>)

        (defaults to: <tt>10</tt>)

        —

duration of Order in minutes (time to service customer); used to aid in
route optimization. Defaults to 10 minutes

        scheduled

        (<tt>Boolean</tt>)

        (defaults to: <tt>true</tt>)

        —

whether this Order is scheduled or not; defaults to true

        worker

        (<tt>Integer</tt>)

        (defaults to: <tt>nil</tt>)

        —

Worker ID of aceroute worker to assign this Order to; defaults to nil (not
implemented)

        summary

        (<tt>String</tt>)

        (defaults to: <tt>nil</tt>)

        —

Summary of order, to be displated in app. Defaults to none.

        purchase_order

        (<tt>String</tt>)

        (defaults to: <tt>nil</tt>)

        —

arbitrary string to indicate PO or other note, if needed

24
25
26
27
28
29
30
31
32
33
34
35
36
37

# File 'lib/aceroute/order.rb', line 24

def initialize(customer, location, start_time, description = nil, duration = 10,
  scheduled = true, worker = nil, summary = nil, purchase_order = nil)
  self.customer = customer
  self.location = location
  self.start_time = start_time
  #FIXME: taking a DateTime argument is friendlier
  #self.start_time = start_time.to_i * 1000 #DateTime object
  self.description = description
  self.duration = duration
  self.scheduled = scheduled
  self.worker = worker
  self.summary = summary
  self.purchase_order = purchase_order
end

Instance Attribute Details

    - (<tt>Object</tt>) cid

Returns the value of attribute cid

5
6
7

# File 'lib/aceroute/order.rb', line 5

def cid
  @cid
end

    - (<tt>Object</tt>) customer

in msec (not sec) since epoch

3
4
5

# File 'lib/aceroute/order.rb', line 3

def customer
  @customer
end

    - (<tt>Object</tt>) description

any freeform text here

4
5
6

# File 'lib/aceroute/order.rb', line 4

def description
  @description
end

    - (<tt>Object</tt>) duration

any freeform text here

4
5
6

# File 'lib/aceroute/order.rb', line 4

def duration
  @duration
end

    - (<tt>Object</tt>) id

Returns the value of attribute id

5
6
7

# File 'lib/aceroute/order.rb', line 5

def id
  @id
end

    - (<tt>Object</tt>) location

in msec (not sec) since epoch

3
4
5

# File 'lib/aceroute/order.rb', line 3

def location
  @location
end

    - (<tt>Object</tt>) purchase_order

any freeform text here

4
5
6

# File 'lib/aceroute/order.rb', line 4

def purchase_order
  @purchase_order
end

    - (<tt>Object</tt>) scheduled

any freeform text here

4
5
6

# File 'lib/aceroute/order.rb', line 4

def scheduled
  @scheduled
end

    - (<tt>Object</tt>) start_time

in msec (not sec) since epoch

3
4
5

# File 'lib/aceroute/order.rb', line 3

def start_time
  @start_time
end

    - (<tt>Object</tt>) summary

any freeform text here

4
5
6

# File 'lib/aceroute/order.rb', line 4

def summary
  @summary
end

    - (<tt>Object</tt>) worker

any freeform text here

4
5
6

# File 'lib/aceroute/order.rb', line 4

def worker
  @worker
end

Class Method Details

    + (<tt>Object</tt>) delete(id)

Deletes Aceroute::Location of given id from Aceroute

Parameters:

        id

        (<tt>Integer</tt>)

73
74
75
76
77

# File 'lib/aceroute/order.rb', line 73

def self.delete(id)
  req = "<data><del><id>#{id}</id></del></data>"
  ret = Aceroute::call_api("order.delete", req)
  ret.success == "true" ? true : false  #maybe raise error here instead
end

Instance Method Details

    - (<tt>Aceroute::Order</tt>) create!

Persists Aceroute::Order object to Aceroute API.

Returns:

        (<tt>Aceroute::Order</tt>)

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

# File 'lib/aceroute/order.rb', line 43

def create!
  recs = "<data>
        <event>
          <cid>#{self.customer.cid}</cid>
          <nm>#{self.description}</nm>
          <dur>#{self.duration}</dur>
          <schd>#{self.scheduled ? 1 : 0}</schd>
          <start_epoch>#{self.start_time}</start_epoch>
          <lid>#{self.location.id}</lid>
          <cntid>#{0}</cntid>
          <rid>#{self.worker}</rid>
          <dtl>#{self.summary}</dtl>
          <po>#{self.purchase_order}</po>
        </event>
      </data>"
  data = Aceroute::call_api("order.create", recs)
  order = data.event
  update_attrs(order)
  return self
end

    - (<tt>Object</tt>) destroy!(id = nil)

Deletes this Aceroute::Order object (self) from Aceroute

66
67
68

# File 'lib/aceroute/order.rb', line 66

def destroy!(id = nil)
  Order.delete(id ? id : self.id)
end

  Generated on Sun Dec  4 11:17:52 2016 by
  yard
  0.8.7.6 (ruby-2.3.1).


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <meta name="viewport" content="width=device-width,initial-scale=1">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <meta name="lang:clipboard.copy" content="Copy to clipboard">
  <meta name="lang:clipboard.copied" content="Copied to clipboard">
  <meta name="lang:search.language" content="en">
  <meta name="lang:search.pipeline.stopwords" content="True">
  <meta name="lang:search.pipeline.trimmer" content="True">
  <meta name="lang:search.result.none" content="No matching documents">
  <meta name="lang:search.result.one" content="1 matching document">
  <meta name="lang:search.result.other" content="# matching documents">
  <meta name="lang:search.tokenizer" content="[\s\-]+">

    <link href="https://fonts.gstatic.com/" rel="preconnect" crossorigin>
    <link href="https://fonts.googleapis.com/css?family=Roboto+Mono:400,500,700|Roboto:300,400,400i,700&display=fallback" rel="stylesheet">

  <link rel="stylesheet" href="../_static/stylesheets/application.css"/>
  <link rel="stylesheet" href="../_static/stylesheets/application-palette.css"/>
  <link rel="stylesheet" href="../_static/stylesheets/application-fixes.css"/>

  <link rel="stylesheet" href="../_static/fonts/material-icons.css"/>

  <meta name="theme-color" content="#3f51b5">

    <title>statsmodels.regression.linear_model.OLSResults.get_robustcov_results — statsmodels</title>
  <link rel="icon" type="image/png" sizes="32x32" href="../_static/icons/favicon-32x32.png">
  <link rel="icon" type="image/png" sizes="16x16" href="../_static/icons/favicon-16x16.png">
  <link rel="manifest" href="../_static/icons/site.webmanifest">
  <link rel="mask-icon" href="../_static/icons/safari-pinned-tab.svg" color="#919191">
  <meta name="msapplication-TileColor" content="#2b5797">
  <meta name="msapplication-config" content="../_static/icons/browserconfig.xml">
  <link rel="stylesheet" href="../_static/stylesheets/examples.css">
  <link rel="stylesheet" href="../_static/stylesheets/deprecation.css">
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/material.css" type="text/css" />
    <link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />

    <link rel="shortcut icon" href="../_static/favicon.ico"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="index" title="Index" href="../genindex.html" />
    <link rel="search" title="Search" href="../search.html" />
    <link rel="next" title="statsmodels.regression.linear_model.OLSResults.initialize" href="statsmodels.regression.linear_model.OLSResults.initialize.html" />
    <link rel="prev" title="statsmodels.regression.linear_model.OLSResults.get_prediction" href="statsmodels.regression.linear_model.OLSResults.get_prediction.html" />

  <svg class="md-svg">
    <defs data-children-count="0">

      <svg xmlns="http://www.w3.org/2000/svg" width="416" height="448" viewBox="0 0 416 448" id="__github"><path fill="currentColor" d="M160 304q0 10-3.125 20.5t-10.75 19T128 352t-18.125-8.5-10.75-19T96 304t3.125-20.5 10.75-19T128 256t18.125 8.5 10.75 19T160 304zm160 0q0 10-3.125 20.5t-10.75 19T288 352t-18.125-8.5-10.75-19T256 304t3.125-20.5 10.75-19T288 256t18.125 8.5 10.75 19T320 304zm40 0q0-30-17.25-51T296 232q-10.25 0-48.75 5.25Q229.5 240 208 240t-39.25-2.75Q130.75 232 120 232q-29.5 0-46.75 21T56 304q0 22 8 38.375t20.25 25.75 30.5 15 35 7.375 37.25 1.75h42q20.5 0 37.25-1.75t35-7.375 30.5-15 20.25-25.75T360 304zm56-44q0 51.75-15.25 82.75-9.5 19.25-26.375 33.25t-35.25 21.5-42.5 11.875-42.875 5.5T212 416q-19.5 0-35.5-.75t-36.875-3.125-38.125-7.5-34.25-12.875T37 371.5t-21.5-28.75Q0 312 0 260q0-59.25 34-99-6.75-20.5-6.75-42.5 0-29 12.75-54.5 27 0 47.5 9.875t47.25 30.875Q171.5 96 212 96q37 0 70 8 26.25-20.5 46.75-30.25T376 64q12.75 25.5 12.75 54.5 0 21.75-6.75 42 34 40 34 99.5z"/></svg>

    </defs>
  </svg>

  <input class="md-toggle" data-md-toggle="drawer" type="checkbox" id="__drawer">
  <input class="md-toggle" data-md-toggle="search" type="checkbox" id="__search">

   Skip to content

          statsmodels v0.12.2
           statsmodels.regression.linear_model.OLSResults.get_robustcov_results

    <form class="md-search__form" action="../search.html" method="GET" name="search">
      <input type="text" class="md-search__input" name="q" placeholder="Search"
             autocapitalize="off" autocomplete="off" spellcheck="false"
             data-md-component="query" data-md-state="active">

      <button type="reset" class="md-icon md-search__icon" data-md-component="reset" tabindex="-1">
        
      </button>
    </form>

            Type to start searching

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

User Guide

Linear Regression

statsmodels.regression.linear_model.OLSResults

    statsmodels v0.12.2

      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 24 24" width="28" height="28">
        <use xlink:href="#__github" width="24" height="24"></use>
      </svg>

    statsmodels

      Installing statsmodels

      Getting started

      User Guide

      Background

      Regression and Linear Models

      Linear Regression

      Generalized Linear Models

      Generalized Estimating Equations

      Generalized Additive Models (GAM)

      Robust Linear Models

      Linear Mixed Effects Models

      Regression with Discrete Dependent Variable

      Generalized Linear Mixed Effects Models

      ANOVA

      Time Series Analysis

      Other Models

      Statistics and Tools

      Data Sets

      Sandbox

      Examples

      API Reference

      About statsmodels

      Developer Page

      Release Notes

Show Source

statsmodels.regression.linear_model.OLSResults.get_robustcov_results¶

OLSResults.get_robustcov_results(cov_type='HC1', use_t=None, **kwargs)¶

Create new results instance with robust covariance as default.

Parameters

cov_typestr

The type of robust sandwich estimator to use. See Notes below.

use_tbool

If true, then the t distribution is used for inference.
If false, then the normal distribution is used.
If use_t is None, then an appropriate default is used, which is
True if the cov_type is nonrobust, and False in all other
cases.

**kwargs

Required or optional arguments for robust covariance calculation.
See Notes below.

Returns

RegressionResults

This method creates a new results instance with the
requested robust covariance as the default covariance of
the parameters.  Inferential statistics like p-values and
hypothesis tests will be based on this covariance matrix.

Notes

The following covariance types and required or optional arguments are
currently available:

'fixed scale' and optional keyword argument 'scale' which uses

a predefined scale estimate with default equal to one.

'HC0', 'HC1', 'HC2', 'HC3' and no keyword arguments:

heteroscedasticity robust covariance

'HAC' and keywords

maxlag integer (required) : number of lags to use

kernel callable or str (optional)kernel

currently available kernels are ['bartlett', 'uniform'],
default is Bartlett

use_correction bool (optional)If true, use small sample

correction

'cluster' and required keyword groups, integer group indicator

groups array_like, integer (required) :

index of clusters or groups

use_correction bool (optional) :

If True the sandwich covariance is calculated with a small
sample correction.
If False the sandwich covariance is calculated without
small sample correction.

df_correction bool (optional)

If True (default), then the degrees of freedom for the
inferential statistics and hypothesis tests, such as
pvalues, f_pvalue, conf_int, and t_test and f_test, are
based on the number of groups minus one instead of the
total number of observations minus the number of explanatory
variables. df_resid of the results instance is also
adjusted. When use_t is also True, then pvalues are
computed using the Student's t distribution using the
corrected values. These may differ substantially from
p-values based on the normal is the number of groups is
sma…
If False, then df_resid of the results instance is not
adjusted.

'hac-groupsum' Driscoll and Kraay, heteroscedasticity and

autocorrelation robust standard errors in panel data
keywords

time array_like (required) : index of time periods

maxlag integer (required) : number of lags to use

kernel callable or str (optional). The available kernels
are ['bartlett', 'uniform']. The default is Bartlett.

use_correction False or string in ['hac', 'cluster'] (optional).
If False the the sandwich covariance is calculated without small
sample correction. If use_correction = 'cluster' (default),
then the same small sample correction as in the case of
covtype='cluster' is used.

df_correction bool (optional) The adjustment to df_resid, see
cov_type 'cluster' above
# TODO: we need more options here

'hac-panel' heteroscedasticity and autocorrelation robust standard

errors in panel data.
The data needs to be sorted in this case, the time series
for each panel unit or cluster need to be stacked. The
membership to a timeseries of an individual or group can
be either specified by group indicators or by increasing
time periods.

keywords

either groups or time : array_like (required)
groups : indicator for groups
time : index of time periods

maxlag integer (required) : number of lags to use

kernel callable or str (optional)

currently available kernels are ['bartlett', 'uniform'],
default is Bartlett

use_correction False or string in ['hac', 'cluster'] (optional)

If False the sandwich covariance is calculated without
small sample correction.

df_correction bool (optional)

adjustment to df_resid, see cov_type 'cluster' above
# TODO: we need more options here

Reminder:
use_correction in "hac-groupsum" and "hac-panel" is not bool,
needs to be in [False, 'hac', 'cluster']

TODO: Currently there is no check for extra or misspelled keywords,
except in the case of cov_type HCx

                   Previous  statsmodels.regression.linear_model.OLSResults.get_prediction

  Next  statsmodels.regression.linear_model.OLSResults.initialize

              © Copyright 2009-2019, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.

            Last updated on
              Feb 02, 2021.

            Created using
            Sphinx 3.4.3.
             and
            Material for
              Sphinx


text:
import json

from django.test import TestCase
from django.contrib.auth.models import User, Permission

from Snack.models import Profil

class TestPurchase(TestCase):

    def setUp(self):
        self.user = User.objects.create(username='user', password='test')
        self.user.set_password('test')
        treasurer = Permission.objects.get(codename='treasurer_account')
        self.user.user_permissions.add(treasurer)
        self.user.save()
        self.profil = Profil(user=self.user)
        self.profil.save()
        self.client.force_login(self.user)

    def test_set_debt(self):
        response = self.client.post(
            '/debt/',
            {'id': 1, 'debt': 5}
        )
        self.assertEqual(response.status_code, 200)
        self.assertEqual(5, Profil.objects.get(id=1).debt)
        self.assertEqual(True, json.loads(response.content)['res'])

    def test_get_all_user(self):
        response = self.client.get('/debt/')
        self.assertEqual(response.status_code, 200)
        self.assertIn(self.profil, response.context['profils'])


text:
'use strict';

'use strict';

angular.module('issueTracker.issues.issue.issueController', [])
    .controller('IssueCtrl', [
        '$scope',
        '$route',
        '$routeParams',
        '$location',
        '$window',
        'Issues',
        'Projects',
        'Identity',
        'Users',
        'toastr',
        function ($scope, $route, $routeParams, $location, $window, issues, projects, identity, users, toastr) {

            $scope.issueId = $routeParams.issueId;
            $scope.user = identity.getUser;
            $scope.relatedUsers = [];
            $scope.isUserRelated = false;
            $scope.inputAddComment = {};
            $scope.search = {user: ''};

            $scope.issue = {};

            $scope.loadUsersByFilter = function () {
                if($scope.search.user.length < 2){
                    return;
                }
                users.getUsersByFilter($scope.search.user)
                    .then(function (data) {
                        $scope.users = data;
                    });
            };

            $scope.loadAllUsers = function () {
                users.getAllUsers()
                    .then(function (data) {
                        $scope.users = data;
                    });
            };

            $scope.editIssue = function () {
                delete $scope.issue.Id;
                delete $scope.issue.Author;
                delete $scope.issue.IssueKey;
                delete $scope.issue.AvailableStatuses;
                delete $scope.issue.Project;
                delete $scope.issue.Status;

                var assigneeId = $scope.issue.Assignee.Id;
                delete $scope.issue.Assignee;
                $scope.issue.AssigneeId = assigneeId

                var priorityId = $scope.issue.Priority.Id;
                delete $scope.issue.Priority;
                $scope.issue.PriorityId = priorityId;

                issues.editIssue($scope.issueId, $scope.issue)
                    .then(function (success) {
                        $window.history.back();
                        toastr.success($scope.issue.Title + ' was edited successfully.')
                    });
            };

            issues.getIssueById($scope.issueId)
                .then(function (data) {
                    $scope.issue = data;
                    console.log(data);

                    $scope.search.user = $scope.issue.Assignee.Username;
                    $scope.loadUsersByFilter();

                    issues.getCommentsByIssueId($scope.issueId)
                        .then(function (data) {
                            if(data.length > 0){
                                $scope.issue.comments = data;
                            }
                        });

                    projects.getProjectById($scope.issue.Project.Id)
                        .then(function (data) {
                            $scope.issue.Project = data;

                            issues.getIssuesByProjectId($scope.issue.Project.Id)
                                .then(function (data) {
                                    $scope.issue.Project.Issues = data;
                                    $scope.relatedUsers.push($scope.issue.Project.Lead);
                                    if($scope.issue.Project.Lead.Id === identity.getUser().Id){
                                        $scope.isUserRelated = true;
                                    }

                                    for(var i = 0; i < $scope.issue.Project.Issues.length; i+=1){
                                        $scope.relatedUsers.push($scope.issue.Project.Issues[i].Assignee);
                                        if($scope.issue.Project.Issues[i].Assignee.Id === identity.getUser().Id){
                                            $scope.isUserRelated = true;
                                        }
                                    }
                                });
                        });
                });

                $scope.changeStatus = function (statusId) {
                    issues.changeIssueStatus($scope.issueId ,statusId)
                        .then(function (success) {
                            $route.reload();
                        });
                };

            $scope.addComment = function () {

                issues.addComment($scope.issueId, $scope.inputAddComment.Text)
                    .then(function (data) {
                        $scope.issue.comments = data;
                    });
            };

        }
    ]);


text:
IPCZ_MSG_BEGIN_INTERFACE(Test)

IPCZ_MSG_BEGIN(BasicTestMessage, IPCZ_MSG_ID(0), IPCZ_MSG_VERSION(0))
  IPCZ_MSG_PARAM(uint32_t, foo)
  IPCZ_MSG_PARAM(uint32_t, bar)
IPCZ_MSG_END()

IPCZ_MSG_BEGIN(MessageWithDataArray, IPCZ_MSG_ID(1), IPCZ_MSG_VERSION(0))
  IPCZ_MSG_PARAM_ARRAY(uint64_t, values)
IPCZ_MSG_END()

IPCZ_MSG_BEGIN(MessageWithDriverObject, IPCZ_MSG_ID(2), IPCZ_MSG_VERSION(0))
  IPCZ_MSG_PARAM_DRIVER_OBJECT(object)
IPCZ_MSG_END()

IPCZ_MSG_BEGIN(MessageWithDriverObjectArray,
               IPCZ_MSG_ID(3),
               IPCZ_MSG_VERSION(0))
  IPCZ_MSG_PARAM_DRIVER_OBJECT_ARRAY(objects)
IPCZ_MSG_END()

IPCZ_MSG_BEGIN(MessageWithDriverArrayAndExtraObject,
               IPCZ_MSG_ID(4),
               IPCZ_MSG_VERSION(0))
  IPCZ_MSG_PARAM_DRIVER_OBJECT_ARRAY(objects)
  IPCZ_MSG_PARAM_DRIVER_OBJECT(extra_object)
IPCZ_MSG_END()

IPCZ_MSG_END_INTERFACE()


text:
import assign from 'object-assign';
import * as Scheduler from 'scheduler';
import * as SchedulerTracing from 'scheduler/tracing';
import ReactCurrentDispatcher from './ReactCurrentDispatcher';
import ReactCurrentOwner from './ReactCurrentOwner';
import ReactDebugCurrentFrame from './ReactDebugCurrentFrame';

const ReactSharedInternals = {
  ReactCurrentDispatcher,
  ReactCurrentOwner,
  // Used by renderers to avoid bundling object-assign twice in UMD bundles:
  assign,
};

if (__UMD__) {
  // Re-export the schedule API(s) for UMD bundles.
  // This avoids introducing a dependency on a new UMD global in a minor update,
  // Since that would be a breaking change (e.g. for all existing CodeSandboxes).
  // This re-export is only required for UMD bundles;
  // CJS bundles use the shared NPM package.
  Object.assign(ReactSharedInternals, {
    Scheduler,
    SchedulerTracing,
  });
}

if (__DEV__) {
  Object.assign(ReactSharedInternals, {
    // These should not be included in production.
    ReactDebugCurrentFrame,
    // Shim for React DOM 16.0.0 which still destructured (but not used) this.
    // TODO: remove in React 17.0.
    ReactComponentTreeHook: {},
  });
}

export default ReactSharedInternals;


text:
<?php

declare(strict_types=1);

namespace Psi\Component\ContentType\Standard\Field;

use Psi\Component\ContentType\FieldInterface;
use Psi\Component\ContentType\OptionsResolver\FieldOptionsResolver;
use Psi\Component\ContentType\Standard\Storage as Storage;
use Psi\Component\ContentType\Standard\View as View;
use Symfony\Component\Form\Extension\Core\Type as Form;

class UrlField implements FieldInterface
{
    public function getViewType(): string
    {
        return View\UrlType::class;
    }

    public function getFormType(): string
    {
        return Form\UrlType::class;
    }

    public function getStorageType(): string
    {
        return Storage\StringType::class;
    }

    public function configureOptions(FieldOptionsResolver $options)
    {
    }
}


text:
require.config({
	paths:{
		"jquery":"lib/jquery"
	}
});
define(['jquery'],function ($) {
	function SetDataFunction(){
		var ncpu = 0;
		this.changeNcpu= function(obj_ncpu){
			return ncpu=obj_ncpu;
		};
		this.setData = function(obj_array_url) {  //获得db的数据,根据url数组,得到数组数据
		//	var keys = [];
			var values = [];
			//var getDataOfValues = function() {
					for (var i = obj_array_url.length - 1; i >= 0; i--) {
						$.ajax({
							url: obj_array_url[i],
							method: "get",
							async: false,
							dataType: "json",
							success: function(result, status, xhr) {
								values.push(result[0]);
							},
							error: function(XMLHttpRequest, status, jqXHR, textStatus, e) {
								console.error("getDataOfValues 状态 ="+status);
							}
						});
					}
			//	};
			//getDataOfValues();
			return values;
		};
		this.changeData =function(obj_array_values,obj_int_datagrid,obj_time){
			var values = [];
			var sys_values = [],
				db_values = [],
				after_values = {},
				//after_values = null,
				ncpu=0,
				time=999;
			for (var i = 0; i < obj_array_values.length; i++) {
				var endTime = obj_array_values[i].sys.time;
				endTime = endTime.replace(/\-/g, '/');
				var date_values = new Date(endTime);
				var time_values = (date_values).getTime();
				if (obj_int_datagrid == 0) {  //判断是否是第一次建表
					var after_time = globalObject.getDate(endTime);
					obj_array_values[i].sys.time = after_time;
					obj_array_values[i].db.time = after_time;
					// after_values = $.extend({}, obj_array_values[i].sys, obj_array_values[i].db);
					// ncpu = obj_array_values[i].sys.ncpu;
					sys_values = $.extend({}, obj_array_values[i].sys, obj_array_values[i].db);
					ncpu = obj_array_values[i].sys.ncpu;
					//db_values.push(obj_array_values[i].db);
					//db_values.push(obj_array_values[i].db);
					time = time_values;
				} else {
					if (time_values > obj_time) {
						var after_time = globalObject.getDate(endTime);
						obj_array_values[i].sys.time = after_time;
						obj_array_values[i].db.time = after_time;
						// after_values = $.extend({}, obj_array_values[i].sys, obj_array_values[i].db);
						// ncpu = obj_array_values[i].sys.ncpu;
						sys_values = $.extend({}, obj_array_values[i].sys, obj_array_values[i].db);
						ncpu = obj_array_values[i].sys.ncpu;
						//db_values.push(obj_array_values[i].db);
					//	db_values.push(obj_array_values[i].db);
						time = time_values;
					}else{
						time=time_values;
					}
				}
			}
			after_values = sys_values;
			//after_values.db = db_values;
			after_object = {};
			after_object["after_values"]= after_values;
			after_object["time"]=time;
			after_object["ncpu"]=ncpu;
			return	after_object;
		};
		this.formatter_system_time_color=function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
		this.formatter_system_one_color = function(cellvalue, options, rowObject) {
					if (rowObject.one_m > ncpu) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_two_color = function(cellvalue, options, rowObject) {
					if (rowObject.five_m > ncpu) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_three_color = function(cellvalue, options, rowObject) {
					if (rowObject.fifteen_m > ncpu) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_usr_color = function(cellvalue, options, rowObject) {
					if (rowObject.usr > 10) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_sys_color = function(cellvalue, options, rowObject) {
					if (rowObject.sys > 10) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_iow_color = function(cellvalue, options, rowObject) {
					if (rowObject.iow > 10) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_si_color = function(cellvalue, options, rowObject) {
					if (rowObject.si > 0) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_so_color = function(cellvalue, options, rowObject) {
					if (rowObject.so > 0) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_recv_color = function(cellvalue, options, rowObject) {
					if (rowObject.recv.indexOf("MB") != -1) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_send_color = function(cellvalue, options, rowObject) {
					if (rowObject.send.indexOf("MB") != -1) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_rkb_color = function(cellvalue, options, rowObject) {
					if (rowObject.rkB_s > 1024) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_wkb_color = function(cellvalue, options, rowObject) {
					if (rowObject.wkB_s > 1024) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_await_color = function(cellvalue, options, rowObject) {
					if (rowObject.await > 5) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_svctm_color = function(cellvalue, options, rowObject) {
					if (rowObject.svctm > 5) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_util_color = function(cellvalue, options, rowObject) {
					if (rowObject.util > 80) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_qps_color = function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
		this.formatter_system_tps_color = function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
		this.formatter_system_hit_color = function(cellvalue, options, rowObject) {
					if (rowObject.hit > 99) {
						return '' + cellvalue + "";
					} else {
						return '' + cellvalue + "";
					}
		};
		this.formatter_system_run_color = function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
		this.formatter_system_con_color = function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
		this.formatter_system_cre_color = function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
		this.formatter_system_cac_color = function(cellvalue, options, rowObject) {
					return '' + cellvalue + "";
		};
	}
	return {
		SetDataFunction : SetDataFunction
	};
});


text:
.payment-buttons {
  display: block;
}

.bank-payment-image {
  position: relative;
  top: 0;
  height: 70px;
  text-align: center;
}

.bank-payment-name {
  position: relative;
  bottom: 0;
  line-height: 1.5em;
  text-align: center;
}

.payment-button {
  display: block;
  float: left;
  padding: 0.8em;
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.trino.connector;

import java.util.function.Function;

import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;

public class ConnectorCatalogServiceProvider<T>
        implements CatalogServiceProvider<T>
{
    private final String name;
    private final ConnectorServicesProvider connectorServicesProvider;
    private final Function<ConnectorServices, T> serviceGetter;

    public ConnectorCatalogServiceProvider(String name, ConnectorServicesProvider connectorServicesProvider, Function<ConnectorServices, T> serviceGetter)
    {
        this.name = requireNonNull(name, "name is null");
        this.connectorServicesProvider = requireNonNull(connectorServicesProvider, "connectorServicesProvider is null");
        this.serviceGetter = requireNonNull(serviceGetter, "serviceGetter is null");
    }

    @Override
    public T getService(CatalogHandle catalogHandle)
    {
        ConnectorServices connectorServices = connectorServicesProvider.getConnectorServices(catalogHandle);
        T result = serviceGetter.apply(connectorServices);
        checkArgument(result != null, "Catalog '%s' does not have a %s", catalogHandle, name);
        return result;
    }
}


text:
'use strict';

const Promise = require('bluebird');
const request = Promise.promisify(require('request'));
const baseUrl = 'https://www.f-list.net/json/';
//years months weeks days hours minutes
const dateRegex = /(?:(\d+)y(?:,\s)?)?(?:(\d+)mo(?:,\s)?)?(?:(\d+)w(?:,\s)?)?(?:(\d+)d(?:,\s)?)?(?:(\d+)h(?:,\s)?)?(?:(\d+)m(?:,\s)?)?(?:(\d+)s)?/i;//eslint-disable-line max-len

function isObject(o) {
	return typeof o === 'object' && o !== null && !Array.isArray(o);
}

/**
 * @see https://wiki.f-list.net/Json_endpoints#API_Version_1
 */
module.exports = class FListApiClient {

	/**
	 * Parses an f-list format date, which only specifies rough time frame of the last interaction.
	 * @private
	 * @param  {string} str String in for format of Xy, Xmo, Yw, Xd, Xh, Xm, Xs where each group is optional.
	 * @return {Date} The returned date is not always perfectly accurate, but as accurate as F-List allows it to be.
	 */
	static parseDate(str) {
		const date = new Date();
		const match = str.match(dateRegex);
		const years = parseInt(match[1], 10);
		const months = parseInt(match[2], 10);
		const weeks = parseInt(match[3], 10);
		const days = parseInt(match[4], 10);
		const hours = parseInt(match[5], 10);
		const minutes = parseInt(match[6], 10);
		const seconds = parseInt(match[7], 10);
		if (years) {
			date.setUTCFullYear(date.getUTCFullYear() - years);
		}
		if (months) {
			date.setUTCMonth(date.getUTCMonth() - months);
		}
		if (weeks) {
			date.setUTCDate(date.getUTCDate() - weeks * 7);
		}
		if (days) {
			date.setUTCDate(date.getUTCDate() - days);
		}
		if (hours) {
			date.setUTCHours(date.getUTCHours() - hours);
		}
		if (minutes) {
			date.setUTCMinutes(date.getUTCMinutes() - minutes);
		}
		if (seconds) {
			date.setUTCSeconds(date.getUTCSeconds() - seconds);
		}

		return date;
	}

	/**
	 * Modifies the passed object.
	 * Deep deplaces f-list date format strings with {Date} objects.
	 * @private
	 * @param  {Object} obj The object to be modified.
	 */
	static fixupContent(obj) {
		for (const key in obj) {
			if (!obj.hasOwnProperty(key)) {
				continue;
			}
			const data = obj[key];
			if (typeof data === 'string') {
				if (key.includes('datetime_')) {
					obj[key] = this.parseDate(data);
					continue;
				}
			}
			if (isObject(data)) {
				this.fixupContent(data);
			}
		}
	}

	/**
	 * @param  {string} username The username.
	 * @param  {string} password The password.
	 */
	constructor(username, password) {
		this.credentials = {
			username,
			password
		};
	}

	/**
	 * Sends a request to the given endpoint.
	 * @public
	 * @param  {string} endPoint The endpoint to use.
	 * @param  {{params: Object, skipAuth: boolean, forceAuth: boolean, doNotUseApi: boolean}} options The request options.
	 * @return {Promise.<Object>} Resolves the API response.
	 */
	request(endPoint, options) {
		const params = options.params || {};
		params.account = this.credentials.username;

		let returnPromise = Promise.resolve();
		if (this.shouldAuth() && !this.isAuthenticated() && !options.skipAuth || options.forceAuth) {
			returnPromise = this.authenticate();
		}
		return returnPromise
		.then(() => {
			if (this.credentials.ticket) {
				params.ticket = this.credentials.ticket;
			}
			return request({
				url: baseUrl + (options.doNotUseApi ? '' : 'api/') + endPoint + '.php',
				json: true,
				form: params,
				method: 'POST'
			})
			.then(response => {
				if (response.body.error) {
					throw new Error(response.body.error);
				}
				FListApiClient.fixupContent(response.body);
				return response.body;
			});
		});
	}

	/**
	 * Utility mehtod that checks if an auth should happen internally.
	 * @private
	 * @return {boolean} Should the client auth.
	 */
	shouldAuth() {
		return Boolean(this.credentials.username);
	}

	/**
	 * Utility method to check whether the client is authenticated.
	 * @public
	 * @return {Boolean} Is authenticated.
	 */
	isAuthenticated() {
		return this.validUntil && this.validUntil > Date.now();
	}

	/**
	 * This method is intended for internal use, but can also be used externally
	 * as it exposes some (rarely used) client data.
	 * @public
	 * @return {Promise.<Object>} Resolves the authentication api response.
	 */
	authenticate() {
		if (this.authPromise && this.authPromise.isPending()) {
			return this.authPromise;
		}
		this.authPromise = this.request('getApiTicket', {
			params: {
				password: this.credentials.password
			},
			skipAuth: true,
			doNotUseApi: true
		})
		.then(response => {
			this.validUntil = Date.now() + 24 * 60 * 60 * 1000;
			this.authResponse = response;
			this.credentials.ticket = response.ticket;
			return response;
		});
		return this.authPromise;
	}
};


text:
package com.hazelcast.impl.base;

import com.hazelcast.nio.DataSerializable;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Pairs implements DataSerializable {
    private List<KeyValue> lsKeyValues = null;

    public Pairs() {
    }

    public Pairs(int size) {
        lsKeyValues = new ArrayList<KeyValue>(size);
    }

    public void addKeyValue(KeyValue keyValue) {
        if (getKeyValues() == null) {
            setKeyValues(new ArrayList<KeyValue>());
        }
        getKeyValues().add(keyValue);
    }

    public void writeData(DataOutput out) throws IOException {
        int size = (getKeyValues() == null) ? 0 : getKeyValues().size();
        out.writeInt(size);
        for (int i = 0; i < size; i++) {
            getKeyValues().get(i).writeData(out);
        }
    }

    public void readData(DataInput in) throws IOException {
        int size = in.readInt();
        for (int i = 0; i < size; i++) {
            if (getKeyValues() == null) {
                setKeyValues(new ArrayList<KeyValue>());
            }
            KeyValue kv = new KeyValue();
            kv.readData(in);
            getKeyValues().add(kv);
        }
    }

    public int size() {
        return (getKeyValues() == null) ? 0 : getKeyValues().size();
    }

    public KeyValue getEntry(int i) {
        return (getKeyValues() == null) ? null : getKeyValues().get(i);
    }

    /**
     * @param lsKeyValues the lsKeyValues to set
     */
    public void setKeyValues(List<KeyValue> lsKeyValues) {
        this.lsKeyValues = lsKeyValues;
    }

    /**
     * @return the lsKeyValues
     */
    public List<KeyValue> getKeyValues() {
        return lsKeyValues;
    }

    @Override
    public String toString() {
        return "Pairs{" +
                "lsKeyValues=" + ((lsKeyValues == null) ? 0 : lsKeyValues.size()) +
                '}';
    }
}


text:
html {
  position: relative;
  min-height: 100%; }

body {
  background: url(../img/background1.png) repeat;
  color: white; }

.modal-dialog {
  color: black; }

.logo {
  display: block;
  font-family: 'Open Sans', sans-serif;
  font-size: 100px;
  text-align: center;
  color: white; }

.input2::-webkit-input-placeholder {
  text-indent: 0px;
  transition: text-indent 1.9s ease; }

.input2::-moz-placeholder {
  text-indent: 0px;
  transition: text-indent 1.9s ease; }

.input2:-moz-placeholder {
  text-indent: 0px;
  transition: text-indent 1.9s ease; }

.input2:-ms-input-placeholder {
  text-indent: 0px;
  transition: text-indent 1.9s ease; }

.input2:focus::-webkit-input-placeholder {
  text-indent: 2000px;
  transition: text-indent 1.9s ease; }

.input2:focus::-moz-placeholder {
  text-indent: 2000px;
  transition: text-indent 1.9s ease; }

.input2:focus:-moz-placeholder {
  text-indent: 2000px;
  transition: text-indent 1.9s ease; }

.input2:focus:-ms-input-placeholder {
  text-indent: 2000px;
  transition: text-indent 1.9s ease; }

.footer {
  position: absolute;
  display: block !important;
  bottom: 0;
  width: 100%;
  height: 60px;
  margin-top: 60px;
  background-color: #e3e3e3;
}

body > .container {
  padding-top: 60px;
}
.container .text-muted {
  margin: 20px 0;
  text-align:justify;
}

.footer > .container {
  padding-right: 15px;
  padding-left: 15px;
}


text:
package com.hazelcast.client.impl.protocol.task.dynamicconfig;

import com.hazelcast.client.impl.protocol.ClientMessage;
import com.hazelcast.client.impl.protocol.codec.DynamicConfigAddReplicatedMapConfigCodec;
import com.hazelcast.config.EntryListenerConfig;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.config.ListenerConfig;
import com.hazelcast.config.MergePolicyConfig;
import com.hazelcast.config.ReplicatedMapConfig;
import com.hazelcast.instance.Node;
import com.hazelcast.nio.Connection;
import com.hazelcast.nio.serialization.IdentifiedDataSerializable;
import com.hazelcast.version.Version;

import java.util.ArrayList;

import static com.hazelcast.internal.cluster.Versions.V3_10;

public class AddReplicatedMapConfigMessageTask
        extends AbstractAddConfigMessageTask<DynamicConfigAddReplicatedMapConfigCodec.RequestParameters> {

    public AddReplicatedMapConfigMessageTask(ClientMessage clientMessage, Node node, Connection connection) {
        super(clientMessage, node, connection);
    }

    @Override
    protected DynamicConfigAddReplicatedMapConfigCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) {
        return DynamicConfigAddReplicatedMapConfigCodec.decodeRequest(clientMessage);
    }

    @Override
    protected ClientMessage encodeResponse(Object response) {
        return DynamicConfigAddReplicatedMapConfigCodec.encodeResponse();
    }

    @Override
    protected IdentifiedDataSerializable getConfig() {
        ReplicatedMapConfig config = new ReplicatedMapConfig(parameters.name);
        config.setAsyncFillup(parameters.asyncFillup);
        config.setInMemoryFormat(InMemoryFormat.valueOf(parameters.inMemoryFormat));
        Version clusterVersion = nodeEngine.getClusterService().getClusterVersion();
        if (clusterVersion.isGreaterOrEqual(V3_10) && parameters.mergeBatchSizeExist) {
            MergePolicyConfig mergePolicyConfig = mergePolicyConfig(true, parameters.mergePolicy,
                    parameters.mergeBatchSize);
            config.setMergePolicyConfig(mergePolicyConfig);
        } else {
            // RU_COMPAT_3_9
            config.setMergePolicy(parameters.mergePolicy);
        }
        config.setStatisticsEnabled(parameters.statisticsEnabled);
        if (parameters.listenerConfigs != null && !parameters.listenerConfigs.isEmpty()) {
            for (ListenerConfigHolder holder : parameters.listenerConfigs) {
                config.addEntryListenerConfig((EntryListenerConfig) holder.asListenerConfig(serializationService));
            }
        } else {
            config.setListenerConfigs(new ArrayList<ListenerConfig>());
        }
        return config;
    }

    @Override
    public String getMethodName() {
        return "addReplicatedMapConfig";
    }
}