text:
<documentation title="Closure Linter">
    <standard>
        <![CDATA[
    All javascript files should pass basic Closure Linter tests.
    ]]>
    </standard>
    <code_comparison>

            <![CDATA[
var foo = [1, 2];
        ]]>

            <![CDATA[
var foo = [1, 2,];
        ]]>

    </code_comparison>
</documentation>


text:
<?php

namespace San\OffresBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use San\OffresBundle\Entity\Competence;
/**
 * Description of LoadStatuts
 *
 * @author Dev
 */
class LoadCompetences  implements FixtureInterface
{
 // Dans l'argument de la méthode load, l'objet $manager est l'EntityManager
  public function load(ObjectManager $manager)
  {
    // Liste des noms de statut à ajouter
    $names = array(
        'VMWARE',
        'Gestion des ressources systèmes et comptes utilisateurs',
        'Implémentation',
        'Architecture réseau',
        'Active Directory',
        'LAN',
        'WAN',
        'VLAN',
        'Administration systèmes',
        'Linux',
        'Windows',
        'Oracle ',
        'Mac OS',
        'Sauvegarde',
        'Sécurité IT',
        'Méthode EBIOS',
        'Firewall',
        'Cisco',
        'Fortinet',
        'F5 Network',
        'Palo Alto',
        'Varonis',
        'OVM',
        'Tivoli',
        'Citrix',
        'Oracle/SOA',
        'Flux Ficovie',
        'DSN'
    );

    foreach ($names as $name) {

      $competence = new Competence();
      $competence->setNom($name);

      // On la persiste
      $manager->persist($competence);
    }

    // On déclenche l'enregistrement de tous les statuts
    $manager->flush();
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.rtg.report;

import org.apache.velocity.runtime.log.LogChute;

import com.rtg.util.diagnostic.Diagnostic;
import com.rtg.util.io.MemoryPrintStream;

import junit.framework.TestCase;

/**
 */
public class RtgVelocityLogChuteTest extends TestCase {

  public void test() {
    final MemoryPrintStream mps = new MemoryPrintStream();
    Diagnostic.setLogStream(mps.printStream());
    try {
      final RtgVelocityLogChute chute = new RtgVelocityLogChute();
      chute.log(LogChute.TRACE_ID, "not gonna log");
      chute.log(LogChute.DEBUG_ID, "totally logged");
      assertFalse(chute.isLevelEnabled(LogChute.TRACE_ID));
      assertTrue(chute.isLevelEnabled(LogChute.DEBUG_ID));
      assertTrue(chute.isLevelEnabled(LogChute.INFO_ID));
    } finally {
      Diagnostic.setLogStream();
    }
    assertFalse(mps.toString().contains("not gonna log"));
    assertTrue(mps.toString().contains("totally logged"));
  }
}


text:
<?php

namespace SIWOZ\EguardianBundle\Entity;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Event
 *
 * @author Marcin
 */
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation\Type;
use JMS\Serializer\Annotation\Groups;

/**
 * @ORM\Entity(repositoryClass="SIWOZ\EguardianBundle\Repository\EventRepository")
 *
 */
class TestEvent extends Event {

    /**
     *
     * @ORM\ManyToOne(targetEntity="Test",cascade={"persist","remove"})
     * @ORM\JoinColumn(name="test_id", referencedColumnName="id")
     * @Type("SIWOZ\EguardianBundle\Entity\Test")
     * @Groups({"Default", "All","Notification"})
     */
    protected $test;

    /**
     * @var integer
     * @Type("integer")
     * @Groups({"Default", "All"})
     */
    protected $id;

    /**
     * @var \DateTime
     * @Type("DateTime")
     * @Groups({"Default", "All","Notification"})
     */
    protected $startDate;

    /**
     * @var integer
     * @Type("integer")
     * @Groups({"Default", "All","Notification"})
     */
    protected $interval;

    /**
     * @var \SIWOZ\EguardianBundle\Entity\SeniorUser
     * @Type("SIWOZ\EguardianBundle\Entity\SeniorUser")
     * @Groups({"Default", "All"})
     */
    protected $senior;

    /**
     * @var \SIWOZ\EguardianBundle\Entity\GuardianUser
     * @Type("SIWOZ\EguardianBundle\Entity\GuardianUser")
     * @Groups({"Default", "All"})
     */
    protected $guardian;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set startDate
     *
     * @param \DateTime $startDate
     * @return TestEvent
     */
    public function setStartDate($startDate)
    {
        $this->startDate = $startDate;

        return $this;
    }

    /**
     * Get startDate
     *
     * @return \DateTime
     */
    public function getStartDate()
    {
        return $this->startDate;
    }

    /**
     * Set interval
     *
     * @param integer $interval
     * @return TestEvent
     */
    public function setInterval($interval)
    {
        $this->interval = $interval;

        return $this;
    }

    /**
     * Get interval
     *
     * @return integer
     */
    public function getInterval()
    {
        return $this->interval;
    }

    /**
     * Set test
     *
     * @param \SIWOZ\EguardianBundle\Entity\Test $test
     * @return TestEvent
     */
    public function setTest(\SIWOZ\EguardianBundle\Entity\Test $test = null)
    {
        $this->test = $test;

        return $this;
    }

    /**
     * Get test
     *
     * @return \SIWOZ\EguardianBundle\Entity\Test
     */
    public function getTest()
    {
        return $this->test;
    }

    /**
     * Set senior
     *
     * @param \SIWOZ\EguardianBundle\Entity\SeniorUser $senior
     * @return TestEvent
     */
    public function setSenior(\SIWOZ\EguardianBundle\Entity\SeniorUser $senior = null)
    {
        $this->senior = $senior;

        return $this;
    }

    /**
     * Get senior
     *
     * @return \SIWOZ\EguardianBundle\Entity\SeniorUser
     */
    public function getSenior()
    {
        return $this->senior;
    }

    /**
     * Set guardian
     *
     * @param \SIWOZ\EguardianBundle\Entity\GuardianUser $guardian
     * @return TestEvent
     */
    public function setGuardian(\SIWOZ\EguardianBundle\Entity\GuardianUser $guardian = null)
    {
        $this->guardian = $guardian;

        return $this;
    }

    /**
     * Get guardian
     *
     * @return \SIWOZ\EguardianBundle\Entity\GuardianUser
     */
    public function getGuardian()
    {
        return $this->guardian;
    }
    /**
     * @var \DateTime
     * @Type("DateTime")
     * @Groups({"Default", "All","Notification"})
     */
    protected $endDate;

    /**
     * Set endDate
     *
     * @param \DateTime $endDate
     * @return TestEvent
     */
    public function setEndDate($endDate)
    {
        $this->endDate = $endDate;

        return $this;
    }

    /**
     * Get endDate
     *
     * @return \DateTime
     */
    public function getEndDate()
    {
        return $this->endDate;
    }
}


text:
github = Rails.configuration.x.github
repos = github.repos.list :all, org: Rails.application.config.organisation

repos.select { |r| RepoFilters.track? r }.each do |hash|
  Repository.create_or_update hash
end


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

namespace Imagekit
{
    public static class ConnectionHelper
    {
        public static void Initialize(string APIPublic, string APIPrivate, string ImageKitID )
        {
            Secret.Address = "https://upload.imagekit.io/rest/api/image/v2/" + ImageKitID;
            Secret.ApiKey = APIPublic;
            Secret.ApiPrivate = APIPrivate;

        }
    }
}


text:
import sys
import unittest

from libcloud.utils.py3 import httplib

from libcloud.common.types import InvalidCredsError, LibcloudError
from libcloud.dns.types import RecordType, ZoneDoesNotExistError
from libcloud.dns.types import RecordDoesNotExistError
from libcloud.dns.drivers.zerigo import ZerigoDNSDriver, ZerigoError

from libcloud.test import MockHttp
from libcloud.test.file_fixtures import DNSFileFixtures
from libcloud.test.secrets import DNS_PARAMS_ZERIGO

class ZerigoTests(unittest.TestCase):
    def setUp(self):
        ZerigoDNSDriver.connectionCls.conn_class = ZerigoMockHttp
        ZerigoMockHttp.type = None
        self.driver = ZerigoDNSDriver(*DNS_PARAMS_ZERIGO)

    def test_invalid_credentials(self):
        ZerigoMockHttp.type = 'INVALID_CREDS'

        try:
            list(self.driver.list_zones())
        except InvalidCredsError:
            pass
        else:
            self.fail('Exception was not thrown')

    def test_list_record_types(self):
        record_types = self.driver.list_record_types()
        self.assertEqual(len(record_types), 13)
        self.assertTrue(RecordType.A in record_types)

    def test_list_zones_success(self):
        zones = self.driver.list_zones()
        self.assertEqual(len(zones), 1)
        self.assertEqual(zones[0].domain, 'example.com')
        self.assertEqual(zones[0].type, 'master')
        self.assertEqual(zones[0].extra['notes'], 'test foo bar')

    def test_list_zones_no_results(self):
        ZerigoMockHttp.type = 'NO_RESULTS'
        zones = self.driver.list_zones()
        self.assertEqual(len(zones), 0)

    def test_list_records_success(self):
        zone = self.driver.list_zones()[0]
        records = list(self.driver.list_records(zone=zone))

        self.assertEqual(len(records), 4)
        self.assertEqual(records[0].name, 'www')
        self.assertEqual(records[0].type, RecordType.A)
        self.assertEqual(records[0].data, '172.16.16.1')
        self.assertEqual(records[0].extra['fqdn'], 'www.example.com')
        self.assertIsNone(records[0].extra['notes'])
        self.assertIsNone(records[0].extra['priority'])

        self.assertEqual(records[1].name, 'test')
        self.assertEqual(records[1].extra['ttl'], 3600)

    def test_record_with_empty_name(self):
        zone = self.driver.list_zones()[0]
        record1 = list(self.driver.list_records(zone=zone))[-1]
        record2 = list(self.driver.list_records(zone=zone))[-2]

        self.assertIsNone(record1.name)
        self.assertIsNone(record2.name)

    def test_list_records_no_results(self):
        zone = self.driver.list_zones()[0]
        ZerigoMockHttp.type = 'NO_RESULTS'
        records = list(self.driver.list_records(zone=zone))
        self.assertEqual(len(records), 0)

    def test_list_records_zone_does_not_exist(self):
        zone = self.driver.list_zones()[0]

        ZerigoMockHttp.type = 'ZONE_DOES_NOT_EXIST'
        try:
            list(self.driver.list_records(zone=zone))
        except ZoneDoesNotExistError:
            e = sys.exc_info()[1]
            self.assertEqual(e.zone_id, zone.id)
        else:
            self.fail('Exception was not thrown')
        pass

    def test_get_zone_success(self):
        zone = self.driver.get_zone(zone_id=12345678)

        self.assertEqual(zone.id, '12345678')
        self.assertEqual(zone.domain, 'example.com')
        self.assertEqual(zone.extra['hostmaster'], 'dnsadmin@example.com')
        self.assertEqual(zone.type, 'master')

    def test_get_zone_does_not_exist(self):
        ZerigoMockHttp.type = 'DOES_NOT_EXIST'

        try:
            self.driver.get_zone(zone_id='4444')
        except ZoneDoesNotExistError:
            e = sys.exc_info()[1]
            self.assertEqual(e.zone_id, '4444')
        else:
            self.fail('Exception was not thrown')

    def test_get_record_success(self):
        record = self.driver.get_record(zone_id='12345678',
                                        record_id='23456789')
        self.assertEqual(record.id, '23456789')
        self.assertEqual(record.name, 'www')
        self.assertEqual(record.type, RecordType.A)

    def test_get_record_zone_does_not_exist(self):
        ZerigoMockHttp.type = 'ZONE_DOES_NOT_EXIST'

        try:
            self.driver.get_record(zone_id='444', record_id='28536')
        except ZoneDoesNotExistError:
            pass
        else:
            self.fail('Exception was not thrown')

    def test_get_record_record_does_not_exist(self):
        ZerigoMockHttp.type = 'RECORD_DOES_NOT_EXIST'

        try:
            self.driver.get_record(zone_id='12345678',
                                   record_id='28536')
        except RecordDoesNotExistError:
            pass
        else:
            self.fail('Exception was not thrown')

    def test_create_zone_success(self):
        ZerigoMockHttp.type = 'CREATE_ZONE'

        zone = self.driver.create_zone(domain='foo.bar.com', type='master',
                                       ttl=None, extra=None)
        self.assertEqual(zone.id, '12345679')
        self.assertEqual(zone.domain, 'foo.bar.com')

    def test_create_zone_validaton_error(self):
        ZerigoMockHttp.type = 'CREATE_ZONE_VALIDATION_ERROR'

        try:
            self.driver.create_zone(domain='foo.bar.com', type='master',
                                    ttl=10, extra=None)
        except ZerigoError:
            e = sys.exc_info()[1]
            self.assertEqual(len(e.errors), 2)
        else:
            self.fail('Exception was not thrown')

    def test_update_zone_success(self):
        zone = self.driver.list_zones()[0]
        updated_zone = self.driver.update_zone(zone=zone,
                                               ttl=10,
                                               extra={'notes':
                                                      'bar foo'})

        self.assertEqual(zone.extra['notes'], 'test foo bar')

        self.assertEqual(updated_zone.id, zone.id)
        self.assertEqual(updated_zone.domain, 'example.com')
        self.assertEqual(updated_zone.type, zone.type)
        self.assertEqual(updated_zone.ttl, 10)
        self.assertEqual(updated_zone.extra['notes'], 'bar foo')

    def test_update_zone_domain_cannot_be_changed(self):
        zone = self.driver.list_zones()[0]

        try:
            self.driver.update_zone(zone=zone, domain='libcloud.org')
        except LibcloudError:
            pass
        else:
            self.fail('Exception was not thrown')

    def test_create_record_success(self):
        zone = self.driver.list_zones()[0]

        ZerigoMockHttp.type = 'CREATE_RECORD'
        record = self.driver.create_record(name='www', zone=zone,
                                           type=RecordType.A, data='127.0.0.1')

        self.assertEqual(record.id, '23456780')
        self.assertEqual(record.name, 'www')
        self.assertEqual(record.zone, zone)
        self.assertEqual(record.type, RecordType.A)
        self.assertEqual(record.data, '127.0.0.1')

    def test_update_record_success(self):
        zone = self.driver.list_zones()[0]
        record = self.driver.list_records(zone=zone)[0]
        updated_record = self.driver.update_record(record=record, name='www',
                                                   type=RecordType.AAAA,
                                                   data='::1')

        self.assertEqual(record.data, '172.16.16.1')

        self.assertEqual(updated_record.id, record.id)
        self.assertEqual(updated_record.name, 'www')
        self.assertEqual(updated_record.zone, record.zone)
        self.assertEqual(updated_record.type, RecordType.AAAA)
        self.assertEqual(updated_record.data, '::1')

    def test_delete_zone_success(self):
        zone = self.driver.list_zones()[0]
        status = self.driver.delete_zone(zone=zone)
        self.assertTrue(status)

    def test_delete_zone_does_not_exist(self):
        zone = self.driver.list_zones()[0]

        ZerigoMockHttp.type = 'ZONE_DOES_NOT_EXIST'

        try:
            self.driver.delete_zone(zone=zone)
        except ZoneDoesNotExistError:
            e = sys.exc_info()[1]
            self.assertEqual(e.zone_id, zone.id)
        else:
            self.fail('Exception was not thrown')

    def test_delete_record_success(self):
        zone = self.driver.list_zones()[0]
        record = self.driver.list_records(zone=zone)[0]
        status = self.driver.delete_record(record=record)
        self.assertTrue(status)

    def test_delete_record_does_not_exist(self):
        zone = self.driver.list_zones()[0]
        record = self.driver.list_records(zone=zone)[0]

        ZerigoMockHttp.type = 'RECORD_DOES_NOT_EXIST'

        try:
            self.driver.delete_record(record=record)
        except RecordDoesNotExistError:
            e = sys.exc_info()[1]
            self.assertEqual(e.record_id, record.id)
        else:
            self.fail('Exception was not thrown')

class ZerigoMockHttp(MockHttp):
    fixtures = DNSFileFixtures('zerigo')

    def _api_1_1_zones_xml_INVALID_CREDS(self, method, url, body, headers):
        body = 'HTTP Basic: Access denied.\n'
        return (httplib.UNAUTHORIZED, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_xml(self, method, url, body, headers):
        body = self.fixtures.load('list_zones.xml')
        return (httplib.OK, body, {'x-query-count': '1'},
                httplib.responses[httplib.OK])

    def _api_1_1_zones_xml_NO_RESULTS(self, method, url, body, headers):
        body = self.fixtures.load('list_zones_no_results.xml')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_hosts_xml(self, method, url, body, headers):
        body = self.fixtures.load('list_records.xml')
        return (httplib.OK, body, {'x-query-count': '1'},
                httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_hosts_xml_NO_RESULTS(self, method, url, body,
                                                     headers):
        body = self.fixtures.load('list_records_no_results.xml')
        return (httplib.OK, body, {'x-query-count': '0'},
                httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_hosts_xml_ZONE_DOES_NOT_EXIST(self, method,
                                                              url, body,
                                                              headers):
        body = ''
        return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_xml(self, method, url, body, headers):
        body = self.fixtures.load('get_zone.xml')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_4444_xml_DOES_NOT_EXIST(self, method, url, body,
                                               headers):
        body = ''
        return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_hosts_23456789_xml(self, method, url, body, headers):
        body = self.fixtures.load('get_record.xml')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_444_xml_ZONE_DOES_NOT_EXIST(self, method, url, body,
                                                   headers):
        body = ''
        return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_xml_RECORD_DOES_NOT_EXIST(self, method, url,
                                                          body, headers):
        body = self.fixtures.load('get_zone.xml')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_hosts_28536_xml_RECORD_DOES_NOT_EXIST(self, method, url, body,
                                                       headers):
        body = ''
        return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_xml_CREATE_ZONE(self, method, url, body, headers):
        body = self.fixtures.load('create_zone.xml')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_xml_CREATE_ZONE_VALIDATION_ERROR(self, method, url,
                                                        body, headers):
        body = self.fixtures.load('create_zone_validation_error.xml')
        return (httplib.UNPROCESSABLE_ENTITY, body, {},
                httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_hosts_xml_CREATE_RECORD(self, method, url,
                                                        body, headers):
        body = self.fixtures.load('create_record.xml')
        return (httplib.CREATED, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_zones_12345678_xml_ZONE_DOES_NOT_EXIST(self, method, url,
                                                        body, headers):
        body = ''
        return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.OK])

    def _api_1_1_hosts_23456789_xml_RECORD_DOES_NOT_EXIST(self, method, url,
                                                          body, headers):
        body = ''
        return (httplib.NOT_FOUND, body, {}, httplib.responses[httplib.OK])

    """
    def (self, method, url, body, headers):
        body = self.fixtures.load('.xml')
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def (self, method, url, body, headers):
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def (self, method, url, body, headers):
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def (self, method, url, body, headers):
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def (self, method, url, body, headers):
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])

    def (self, method, url, body, headers):
        return (httplib.OK, body, {}, httplib.responses[httplib.OK])
    """

if __name__ == '__main__':
    sys.exit(unittest.main())


text:
package mediabrowser.model.mediainfo;

import mediabrowser.model.dto.*;

public class LiveStreamResponse
{
	private MediaSourceInfo MediaSource;
	public final MediaSourceInfo getMediaSource()
	{
		return MediaSource;
	}
	public final void setMediaSource(MediaSourceInfo value)
	{
		MediaSource = value;
	}
}


text:
package com.roche.sequencing.bioinformatics.common.genome;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.roche.sequencing.bioinformatics.common.sequence.Strand;

public class StrandedGenomicRangedCoordinate extends GenomicRangedCoordinate {

	private static Pattern pattern = Pattern.compile("([a-zA-Z0-9]+[:]\\d+[:]\\d+)[:]([+-])");

	private final Strand strand;

	public StrandedGenomicRangedCoordinate(String locationAsString) {
		super(getNonStrandedString(locationAsString));
		Matcher matcher = pattern.matcher(locationAsString);
		if (matcher.find()) {
			this.strand = Strand.fromString(matcher.group(2));
		} else {
			throw new IllegalArgumentException(
					"The provided locationAsString["
							+ locationAsString
							+ "] does not match the required format [container:startPosition-endPosition:strand] or [container:startPosition:endPosition:strand] for example: [chr1:1:1000:+] or [chr1:1-1000:+]");
		}
	}

	private static String getNonStrandedString(String locationAsString) {
		String nonStrandedString = "";
		Matcher matcher = pattern.matcher(locationAsString);
		if (matcher.find()) {
			nonStrandedString = matcher.group(1);
		} else {
			throw new IllegalArgumentException(
					"The provided locationAsString["
							+ locationAsString
							+ "] does not match the required format [container:startPosition-endPosition:strand] or [container:startPosition:endPosition:strand] for example: [chr1:1:1000:+] or [chr1:1-1000:+]");
		}
		return nonStrandedString;
	}

	public StrandedGenomicRangedCoordinate(String container, Strand strand, long startLocation, long stopLocation) {
		super(container, startLocation, stopLocation);
		this.strand = strand;
	}

	public Strand getStrand() {
		return strand;
	}

	public GenomicRangedCoordinate getGenomicRangedCoordinate() {
		return this;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = super.hashCode();
		result = prime * result + ((strand == null) ? 0 : strand.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (!super.equals(obj))
			return false;
		if (getClass() != obj.getClass())
			return false;
		StrandedGenomicRangedCoordinate other = (StrandedGenomicRangedCoordinate) obj;
		if (strand != other.strand)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return getContainerName() + ":" + getStartLocation() + "-" + getStopLocation() + ":" + strand;
	}

}


text:
import math
import pyprocess as SP
import scipy.stats as stats

#lets create a Wiener process conditioned at an end position (Brownian Bridge)
#Initialize the initial values and parameters
wienerParams = {"mu":0, "sigma":1}
wienerInitial = {"startTime":0, "startPosition":0, "endTime":12, "endPosition": 1 }
Wiener = SP.Wiener_process(wienerParams, wienerInitial)

#Get the mean and variance at time=10
t=10

print Wiener.get_mean_at(t)
print Wiener.get_variance_at(t)
print
#Generate a sample position at time=10
print Wiener.generate_position_at(t)
print
#Generate a sample path at set times in an array:
times = range(10) # = [0,1,2,3,4,5,6,7,8,9]
print Wiener.generate_sample_path(times)
# will print an array of points [(t, W_t) for t in times]

# Lets create a custom diffusion. We specify the drift and diffusion functions in the SDE:
# The functions must have time and space parameters, though they don't need to depend on them.
def drift(x,t):
    return t*x

#the diffusion function must be non-negative in it's domain.
def diffusion(x,t):
    return math.sqrt(abs(x))

customParams={"a":drift, "b":diffusion}
customInitial = {"startTime":0, "startPosition":1}
Custom = SP.Custom_diffusion(customParams, customInitial)

#get the mean and poisiton at t=10.
#As this diffusion is untractable, we use MC methods. You can specify the accuracy in the library.
print Custom.generate_position_at(10)

#Lets create a process which can be seperated into the sum of a CEV diffusion and Compound Poisson jump process.
#First the CEV Process
CEVParams = {"r":0.002, "delta":0.5, "beta":-0.3}
CEVInitial = {"startTime":0, "startPosition":100}
CEV = SP.CEV_process(CEVParams, CEVInitial)

#Next the Compound Process. The jumps are Normal random variables, so lets create a "frozen" scipy.stats random variable.
#Frozen just means that the parameters are fixed upon construction of the random variable.

Nor = stats.norm(-0.2,0.05) #The parameters represent the mean and standard deviation.
rate = 0.1 #This is the jump rate, often denoted lambda in literature.
CPoiParams = {"J":Nor, "rate":rate}
CPoiInitial = {"startTime":0, "startPosition":0}
CPoi = SP.Compound_poisson_process(CPoiParams, CPoiInitial)

#create the custom process:
CustomProcess = SP.Custom_process(GBM, CPoi)

#play around with it?
print CustomProcess.get_mean_at(10)
print CustomProcess.generate_sample_path(range(100))

#Any question please email me at cam.davidson.pilon@gmail.com


text:
package com.example.logging;

// [START logging_write_log_entry_advanced]
import com.google.cloud.MonitoredResource;
import com.google.cloud.logging.HttpRequest;
import com.google.cloud.logging.LogEntry;
import com.google.cloud.logging.Logging;
import com.google.cloud.logging.LoggingOptions;
import com.google.cloud.logging.Payload;
import com.google.cloud.logging.Severity;
import java.util.Collections;

/** Write LogEntry with HTTP request using the Cloud Logging API. */
public class LogEntryWriteHttpRequest {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String logName = "log-name"; // i.e "my-log"
    String payLoad = "payload"; // i.e "Hello world!"
    HttpRequest httpRequest =
        HttpRequest.newBuilder()
            .setRequestUrl("www.example.com")
            .setRequestMethod(HttpRequest.RequestMethod.GET) // Supported method GET,POST,PUT,HEAD
            .setStatus(200)
            .build();
    createLogEntryRequest(logName, payLoad, httpRequest);
  }

  public static void createLogEntryRequest(String logName, String payLoad, HttpRequest httpRequest)
      throws Exception {
    // Instantiates a logging client
    try (Logging logging = LoggingOptions.getDefaultInstance().getService()) {
      // create an instance of LogEntry with HTTP request
      LogEntry logEntry =
          LogEntry.newBuilder(Payload.StringPayload.of(payLoad))
              .setSeverity(Severity.ERROR)
              .setLogName(logName)
              .setHttpRequest(httpRequest)
              .setResource(MonitoredResource.newBuilder("global").build())
              .build();

      // Writes the log entry asynchronously
      logging.write(Collections.singleton(logEntry));
      System.out.printf("Logged: %s", payLoad);
    }
  }
}
// [END logging_write_log_entry_advanced]


text:
// Copyright © 2010-2015 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

using CefSharp.Internals;

namespace CefSharp
{
    internal static class InternalWebBrowserExtensions
    {
        internal static void SetHandlersToNull(this IWebBrowserInternal browser)
        {
            browser.ResourceHandlerFactory = null;
            browser.JsDialogHandler = null;
            browser.DialogHandler = null;
            browser.DownloadHandler = null;
            browser.KeyboardHandler = null;
            browser.LifeSpanHandler = null;
            browser.MenuHandler = null;
            browser.FocusHandler = null;
            browser.RequestHandler = null;
            browser.DragHandler = null;
            browser.GeolocationHandler = null;
        }
    }
}


text:
@interface OMessage : NSObject<MXChatMessage, MXChatTextMessage, MXChatImageMessage, MXChatAudioMessage>

@property (nonatomic, copy) NSString *mid;

@property (nonatomic, assign) MXChatMessageType type;
@property (nonatomic, assign) MXChatMessageState state;
@property (nonatomic, assign) MXChatMessageOwnerType ownerType;
@property (nonatomic, assign) BOOL showTimeLabel;
@property (nonatomic, assign) CGFloat cellHeight;
@property (nonatomic, readonly) NSString *sendTimeString;

//文本
@property (nonatomic, copy) NSString *text;
@property (nonatomic, readonly) NSAttributedString *attributedText;

//图像
@property (nonatomic, copy) NSString *imageURL;

//音频
@property (nonatomic, readonly) NSString *audioTimeString;
@property (nonatomic, copy) NSString *audioURL;

//辅助
@property (nonatomic, copy) NSDate *sendTime;
@property (nonatomic, assign) CGFloat audioTime;
@property (nonatomic, copy) NSString *path;

//扩展
@property (nonatomic, copy) NSString *sender;
@property (nonatomic, copy) NSString *receiver;
//可以是群组名或个人
@property (nonatomic, copy) NSString *owner;
@property (nonatomic, assign) BOOL isGroup;

+ (OMessage *)textMessageWithText:(NSString *)text;
+ (OMessage *)imageMessageWithKey:(NSString *)key path:(NSString *)path;
+ (OMessage *)audioMessageWithKey:(NSString *)key path:(NSString *)path time:(float)time;

@end


text:
    <select fix-ie-select ng-model="selectedModel" ng-change="selectLayer()"
            ng-options="dropDownLayer.id as dropDownLayer.name for dropDownLayer in layersData">
    </select>


text:
#ifndef _NUTI_POPUP_H_
#define _NUTI_POPUP_H_

#include "vectorelements/Billboard.h"
#include "core/ScreenPos.h"

namespace Nuti {
    class Bitmap;
    class PopupDrawData;
    class PopupStyle;

    /**
     * An abstract billboard element that can be displayed on the map. It
     * always faces the camera and has a dynamically drawn bitmap.
     */
    class Popup : public Billboard {
    public:
        /**
        * Constructs an abstract Popup object with the specified style and attaches it to a billboard element.
        * @param baseBillboard The billboard this popup will be attached to.
        * @param style The style that defines what this popup looks like.
        */
        Popup(const std::shared_ptr<Billboard>& baseBillboard, const std::shared_ptr<PopupStyle>& style);
        /**
         * Constructs an abstract Popup object from a geometry object and a style.
         * @param geometry The geometry object that defines the location of this popup.
         * @param style The style that defines what this popup looks like.
         */
        Popup(const std::shared_ptr<Geometry>& geometry, const std::shared_ptr<PopupStyle>& style);
        /**
         * Constructs an abstract Popup object from a map position and a style.
         * @param pos The map position that defines the location of this popup.
         * @param style The style that defines what this popup looks like.
         */
        Popup(const MapPos& pos, const std::shared_ptr<PopupStyle>& style);
        virtual ~Popup();

        /**
         * Draws a custom bitmap for this Popup that will be used for drawing the Popup on the map.
         * The method is called each time the Popup gets reloaded internally.
         * @param anchorScreenPos The screen position of the anchor point of this popup in pixels.
         * @param screenWidth The current screen width in pixels.
         * @param screenHeight The current screen height in pixels.
         * @param dpToPX The value used for converting display independent pixels (dp) to pixels (px).
         * @return The custom Popup bitmap.
         */
        virtual std::shared_ptr<Bitmap> drawBitmap(const ScreenPos& anchorScreenPos,
                                                    float screenWidth, float screenHeight, float dpToPX) = 0;

        /**
         * Returns the horizontal anchor point of this popup.
         * @return The horizontal anchor point of this popup.
         */
        float getAnchorPointX() const;
        /**
         * Returns the vertical anchor point of this popup.
         * @return The vertical anchor point of this popup.
         */
        float getAnchorPointY() const;
        /**
         * Sets the anchor point for the popup. It should only be called from
         * Popup::drawBitmap method, to match the anchor point to the drawn bitmap.
         * Values will be clamped to [-1, 1] range.
         * @param anchorPointX The new horizontal anchor point for the popup. -1 means the left side,
         * 0 the center and 1 the right side of the popup. The default is 0.
         * @param anchorPointY The vertical anchor point for the popup. -1 means the bottom,
         * 0 the center and 1 the top of the popup. The default is -1.
         */
        void setAnchorPoint(float anchorPointX, float anchorPointY);

        /**
         * Returns the style of this Popup.
         * @return The style that defines what this Popup looks like.
         */
        std::shared_ptr<PopupStyle> getStyle() const;
        /**
         * Sets the style for this Popup.
         * @return The new style that defines what this popup looks like.
         */
        void setStyle(const std::shared_ptr<PopupStyle>& style);

    private:
        float _anchorPointX;
        float _anchorPointY;

        std::shared_ptr<PopupStyle> _style;
    };

}

#endif


text:
.class Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;
.super Ljava/lang/Object;
.source "MediaRouteChooserDialogFragment.java"

# interfaces
.implements Landroid/view/View$OnClickListener;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x0
    name = "ExpandGroupListener"
.end annotation

# instance fields
.field position:I

.field final synthetic this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

# direct methods
.method constructor <init>(Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;)V
    .locals 0
    .parameter

    .prologue
    .line 547
    iput-object p1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public onClick(Landroid/view/View;)V
    .locals 4
    .parameter "v"

    .prologue
    .line 554
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    iget v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->position:I

    invoke-virtual {v1, v2}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->getItem(I)Ljava/lang/Object;

    move-result-object v0

    check-cast v0, Landroid/media/MediaRouter$RouteGroup;

    .line 555
    .local v0, group:Landroid/media/MediaRouter$RouteGroup;
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    #setter for: Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->mEditingGroup:Landroid/media/MediaRouter$RouteGroup;
    invoke-static {v1, v0}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->access$502(Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;Landroid/media/MediaRouter$RouteGroup;)Landroid/media/MediaRouter$RouteGroup;

    .line 556
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-virtual {v0}, Landroid/media/MediaRouter$RouteInfo;->getCategory()Landroid/media/MediaRouter$RouteCategory;

    move-result-object v2

    #setter for: Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->mCategoryEditingGroups:Landroid/media/MediaRouter$RouteCategory;
    invoke-static {v1, v2}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->access$602(Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;Landroid/media/MediaRouter$RouteCategory;)Landroid/media/MediaRouter$RouteCategory;

    .line 557
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    iget-object v1, v1, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->this$0:Lcom/android/internal/app/MediaRouteChooserDialogFragment;

    invoke-virtual {v1}, Landroid/app/DialogFragment;->getDialog()Landroid/app/Dialog;

    move-result-object v1

    const/4 v2, 0x0

    invoke-virtual {v1, v2}, Landroid/app/Dialog;->setCanceledOnTouchOutside(Z)V

    .line 558
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    iget-object v1, v1, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->this$0:Lcom/android/internal/app/MediaRouteChooserDialogFragment;

    iget-object v1, v1, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouter:Landroid/media/MediaRouter;

    iget-object v2, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    iget-object v2, v2, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->this$0:Lcom/android/internal/app/MediaRouteChooserDialogFragment;

    #getter for: Lcom/android/internal/app/MediaRouteChooserDialogFragment;->mRouteTypes:I
    invoke-static {v2}, Lcom/android/internal/app/MediaRouteChooserDialogFragment;->access$000(Lcom/android/internal/app/MediaRouteChooserDialogFragment;)I

    move-result v2

    iget-object v3, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    #getter for: Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->mEditingGroup:Landroid/media/MediaRouter$RouteGroup;
    invoke-static {v3}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->access$500(Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;)Landroid/media/MediaRouter$RouteGroup;

    move-result-object v3

    invoke-virtual {v1, v2, v3}, Landroid/media/MediaRouter;->selectRouteInt(ILandroid/media/MediaRouter$RouteInfo;)V

    .line 559
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-virtual {v1}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->update()V

    .line 560
    iget-object v1, p0, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter$ExpandGroupListener;->this$1:Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;

    invoke-virtual {v1}, Lcom/android/internal/app/MediaRouteChooserDialogFragment$RouteAdapter;->scrollToEditingGroup()V

    .line 561
    return-void
.end method


text:
			<?php echo $this->lang->line("sales_suspended_sales"); ?>
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

						<?php echo $this->lang->line('sales_suspended_sale_id'); ?>
						<?php echo $this->lang->line('sales_date'); ?>
						<?php echo $this->lang->line('sales_customer'); ?>
						<?php echo $this->lang->line('sales_comments'); ?>
						<?php echo $this->lang->line('sales_unsuspend_and_delete'); ?>

				<?php
				foreach ($suspended_sales as $suspended_sale)
				{
				?>

						<?php echo $suspended_sale['sale_id'];?>
						<?php echo date($this->config->item('dateformat'),strtotime($suspended_sale['sale_time']));?>

							<?php
							if (isset($suspended_sale['customer_id']))
							{
								$customer = $this->Customer->get_info($suspended_sale['customer_id']);
								echo $customer->first_name. ' '. $customer->last_name;
							}
							else
							{
							?>

							<?php
							}
							?>

						<?php echo $suspended_sale['comment'];?>

							<?php
							echo form_open('sales/unsuspend');
							echo form_hidden('suspended_sale_id', $suspended_sale['sale_id']);
							?>
								<input type="submit" name="submit" value="<?php echo $this->lang->line('sales_unsuspend'); ?>" id="submit" class="btn btn-primary btn-xs pull-right">
							<?php
							echo form_close();
							?>

				<?php
				}

				?>


text:
title: Firefox Slowness with VS.NET on Vista
disqus_identifier: 2007-06-firefox-slowness-with-vsnet-on-vista
comments: true
---

Dan Wahlin is my hero... Ever since I've installed Vista, I've noticed that using Firefox to debug my VS.NET 2005 solutions was painfully slow (like 10-15 seconds per page). I've never bothered to take the time to figure out what was causing it. Instead, I'd just fire up Internet Explorer and go about running the application.

Dan, however, went the extra mile and [figured out what was causing the issue][1]. In short, the slowdown is caused by an IPv6 issue with DNS. The solution is turning off IPv6, which can be done by typing *about:config* in the address bar, finding *network.dns.disableIPv6* and setting it to true.

As it turns out, this is not just a Vista issue, but rather an IPv6 issue. If you have IPv6 installed on XP, you'll like encounter the same issue.</p>

[1]:http://weblogs.asp.net/dwahlin/archive/2007/06/17/fixing-firefox-slowness-with-localhost-on-vista.aspx


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

namespace WasatchNET
{
    ///
    /// Controls the automatic (background) optimization of a spectrometer's integration time
    /// to within 'targetCountThreshold' counts of 'targetCounts' intensity goal.
    ///
    /// <remarks>
    /// This class is similar to the PeakIntegrationOptimizer (PIO) in WPSpecCal,
    /// but simpler, as it only optimizes "full spectra" (uses the maximum height
    /// of the entire spectrum), rather than allowing individual peaks to be optimized
    /// to target levels.
    ///
    /// The typical use-case would be to instantiate the IntegrationOptimizer
    /// with a reference to the spectrometer you want to optimize, then tweak
    /// the values of any public parameters (targetCounts, targetCountThreshold,
    /// maxIterations, maxSaneItegrationTimeMS, startMS etc) you wish.  Then
    /// call start(), and internally poll the object until status no longer reads
    /// PENDING (switches to either SUCCESS or ERROR).  At that time, you can read
    /// the Spectrometer's integration time to obtain the converged value.
    ///
    /// While polling, you can graph the intermediate spectra if you wish, using
    /// Spectrometer.lastSpectrum.  See MultiChannelDemo.Form1.graphIntegrationSpectra
    /// for examples.
    /// </remarks>
    public class IntegrationOptimizer
    {
        public enum Status { PENDING, SUCCESS, ERROR }

        ///
        /// Current (or final) status of the IntegrationOptimizer.  Defaults to
        /// PENDING at construction, and switches to SUCCESS or ERROR only at
        /// completion.
        ///
        public Status status = Status.PENDING;

        /// the intensity you want to reach
        public int targetCounts = 40000;

        /// error margin around the targetCounts intensity
        public int targetCountThreshold = 2500;

        /// how many acquisitions the algorithm can attempt
        public uint maxIterations = 20;

        /// longest integration time you're willing to consider
        public uint maxSaneIntegrationTimeMS = 10000;

        /// initial integration time for first iteration
        public uint startMS = 10;

        /// the Spectrometer being optimized
        public Spectrometer spec;
        Logger logger = Logger.getInstance();

        ///
        /// Instantiate a new IntegrationOptimizer on a particular Spectrometer.
        ///
        /// <param name="spec">the Spectrometer whose integration time should be optimized</param>
        public IntegrationOptimizer(Spectrometer spec)
        {
            this.spec = spec;
        }

        ///
        /// Start the background integration.  Note that this will generate a series of
        /// integrations in a background thread.  Spectrometer communications during an
        /// ongoing optimization may be compromised and parallel activity could yield
        /// unpredictable results.
        ///
        /// <todo>
        /// consider an additional lock, beyond acquisitionLock, to preclude user
        /// commands during internal activities
        /// </todo>
        public async void start()
        {
            spec.dark = null;
            var saveAvg = spec.scanAveraging;
            if (saveAvg > 1)
                spec.scanAveraging = 1;

            var sn = spec.serialNumber;

            logger.debug($"{sn}: starting optimization");
            await Task.Run(() => run());
            logger.debug($"{sn}: optimization done (status = {status}, integrationTimeMS = {spec.integrationTimeMS}");

            if (saveAvg > 1)
                spec.scanAveraging = saveAvg;
        }

        void run()
        {
            double peakCounts = 0;
            int iterations = 0;
            int consecutiveRoundUps = 0;
            int consecutiveRoundDowns = 0;
            int maxConsecutiveRounding = 2;

            status = Status.PENDING;
            spec.integrationTimeMS = startMS;
            var sn = spec.serialNumber;

            while (iterations < maxIterations)
            {
                logger.debug($"{sn}: iteration = {iterations}, ms = {spec.integrationTimeMS})");

                var spectrum = spec.getSpectrum();

                if (spec.shuttingDown || spectrum is null)
                {
                    status = Status.ERROR;
                    return;
                }

                peakCounts = spectrum.Max();
                logger.debug($"{sn}:   max = {peakCounts}");

                ////////////////////////////////////////////////////////////////
                // are we optimal?
                ////////////////////////////////////////////////////////////////

                if (Math.Abs(peakCounts - targetCounts) <= targetCountThreshold)
                {
                    logger.debug($"{sn}:   optimized integration time at {spec.integrationTimeMS}ms (max {peakCounts}, target {targetCounts}, threshold {targetCountThreshold})");
                    status = Status.SUCCESS;
                    return;
                }

                ////////////////////////////////////////////////////////////////
                // not yet optimal, so adjust
                ////////////////////////////////////////////////////////////////

                var ms = spec.integrationTimeMS;
                if (peakCounts > targetCounts)
                    ms /= 2;
                else
                {
                    var tmp = (uint) Math.Round(ms * targetCounts / peakCounts);
                    if (tmp == ms)
                        tmp++;
                    ms = tmp;
                }
                logger.debug($"{sn}:   scaling integration time to {ms}");

                // clamp
                if (ms > maxSaneIntegrationTimeMS)
                {
                    logger.debug($"{sn}:   rounding {ms} down to {maxSaneIntegrationTimeMS}");
                    ms = maxSaneIntegrationTimeMS;
                    consecutiveRoundDowns++;
                    consecutiveRoundUps = 0;
                }
                else if (ms < spec.eeprom.minIntegrationTimeMS)
                {
                    logger.debug($"{sn}:   rounding {ms} up to {spec.eeprom.minIntegrationTimeMS}");
                    ms = spec.eeprom.minIntegrationTimeMS;
                    consecutiveRoundUps++;
                    consecutiveRoundDowns = 0;
                }
                else
                {
                    consecutiveRoundDowns = 0;
                    consecutiveRoundUps = 0;
                }

                // detect head-banging
                if (Math.Max(consecutiveRoundUps, consecutiveRoundDowns) > maxConsecutiveRounding)
                {
                    logger.error($"{sn}:    failing to converge...giving up after {maxConsecutiveRounding} consecutive roundings");
                    status = Status.ERROR;
                    return;
                }

                spec.integrationTimeMS = ms;
                iterations++;
            }

            logger.error($"{sn}: gave up after {iterations} iterations");
            status = Status.ERROR;
        }
    }
}


text:
package org.fiolino.common.processing.sink;

/**
 * Created by micro on 5/30/2016.
 */
public interface StoppableSink<T> extends Sink<T> {
    /**
     * Stops the sink, so that all running threads (if any) are being stopped.
     * <p>
     * This sink won't accept any input thereafter.
     */
    void stop() throws InterruptedException;
}


text:
PACKAGE_NAME=spdx-license-list
#PACKAGE_VERSION is configurable can be passed as an argument.
PACKAGE_VERSION=${1:-v6.4.0}
PACKAGE_URL=https://github.com/sindresorhus/spdx-license-list

yum install -y yum-utils git jq

NODE_VERSION=v12.22.4
#installing nvm
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.35.3/install.sh | bash
source ~/.bashrc
nvm install $NODE_VERSION

OS_NAME=$(cat /etc/os-release | grep ^PRETTY_NAME | cut -d= -f2)

#Check if package exists
if [ -d "$PACKAGE_NAME" ] ; then
  rm -rf $PACKAGE_NAME
  echo "$PACKAGE_NAME  | $PACKAGE_VERSION | $OS_NAME | GitHub | Removed existing package if any"

fi

if ! git clone $PACKAGE_URL $PACKAGE_NAME; then
        echo "------------------$PACKAGE_NAME:clone_fails---------------------------------------"
        echo "$PACKAGE_URL $PACKAGE_NAME"
        echo "$PACKAGE_NAME  |  $PACKAGE_URL |  $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Clone_Fails"
        exit 0
fi

cd  $PACKAGE_NAME
git checkout $PACKAGE_VERSION
PACKAGE_VERSION=$(jq -r ".version" package.json)
# run the test command from test.sh

if ! npm install && npm audit fix && npm audit fix --force; then
    echo "------------------$PACKAGE_NAME:install_fails-------------------------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_Fails"
    exit 1
fi

if ! npm test; then
    echo "------------------$PACKAGE_NAME:install_success_but_test_fails---------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub | Fail |  Install_success_but_test_Fails"
    exit 1
else
    echo "------------------$PACKAGE_NAME:install_&_test_both_success-------------------------"
    echo "$PACKAGE_URL $PACKAGE_NAME"
    echo "$PACKAGE_NAME  |  $PACKAGE_URL | $PACKAGE_VERSION | $OS_NAME | GitHub  | Pass |  Both_Install_and_Test_Success"
    exit 0
fi

# Test is in parity with intel.
  #3 errors
  #full.js:2:26
  #✖  2:26  Unexpected use of file extension "json" for "./spdx-full.json"    import/extensions
  #index.js:2:26
  #✖  2:26  Unexpected use of file extension "json" for "./spdx.json"         import/extensions
  #simple.js:2:34
  #✖  2:34  Unexpected use of file extension "json" for "./spdx-simple.json"  import/extensions


text:
package org.apache.beam.runners.core.construction.renderer;

import com.google.errorprone.annotations.FormatMethod;
import com.google.errorprone.annotations.FormatString;
import java.util.HashMap;
import java.util.Map;
import org.apache.beam.model.pipeline.v1.RunnerApi;
import org.apache.beam.sdk.Pipeline;
import org.apache.beam.sdk.runners.TransformHierarchy;
import org.apache.beam.sdk.values.PValue;

/** A DOT renderer for BEAM {@link Pipeline} DAG. */
@SuppressWarnings({
  "nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class PipelineDotRenderer implements Pipeline.PipelineVisitor {
  public static String toDotString(Pipeline pipeline) {
    final PipelineDotRenderer visitor = new PipelineDotRenderer();
    visitor.begin();
    pipeline.traverseTopologically(visitor);
    visitor.end();
    return visitor.dotBuilder.toString();
  }

  public static String toDotString(RunnerApi.Pipeline pipeline) {
    return PortablePipelineDotRenderer.toDotString(pipeline);
  }

  private final StringBuilder dotBuilder = new StringBuilder();
  private final Map<PValue, Integer> valueToProducerNodeId = new HashMap<>();

  private int indent;
  private int nextNodeId;

  private PipelineDotRenderer() {}

  @Override
  public void enterPipeline(Pipeline p) {}

  @Override
  public void leavePipeline(Pipeline pipeline) {}

  @Override
  public CompositeBehavior enterCompositeTransform(TransformHierarchy.Node node) {
    writeLine("subgraph cluster_%d {", nextNodeId++);
    enterBlock();
    writeLine("label = \"%s\"", escapeString(node.getFullName()));
    return CompositeBehavior.ENTER_TRANSFORM;
  }

  @Override
  public void leaveCompositeTransform(TransformHierarchy.Node node) {
    exitBlock();
    writeLine("}");
  }

  @Override
  public void visitPrimitiveTransform(TransformHierarchy.Node node) {
    final int nodeId = nextNodeId++;
    writeLine("%d [label=\"%s\"]", nodeId, escapeString(node.getTransform().getName()));

    node.getOutputs().values().forEach(x -> valueToProducerNodeId.put(x, nodeId));

    node.getInputs()
        .forEach(
            (key, value) -> {
              final int producerId = valueToProducerNodeId.get(value);
              String style = "solid";
              if (node.getTransform().getAdditionalInputs().containsKey(key)) {
                style = "dashed";
              }
              writeLine("%d -> %d [style=%s label=\"%s\"]", producerId, nodeId, style, "");
            });
  }

  @Override
  public void visitValue(PValue value, TransformHierarchy.Node producer) {}

  private void begin() {
    writeLine("digraph {");
    enterBlock();
    writeLine("rankdir=LR");
  }

  private void end() {
    exitBlock();
    writeLine("}");
  }

  private void enterBlock() {
    indent += 4;
  }

  private void exitBlock() {
    indent -= 4;
  }

  @FormatMethod
  private void writeLine(@FormatString String format, Object... args) {
    if (indent != 0) {
      dotBuilder.append(String.format("%-" + indent + "s", ""));
    }
    dotBuilder.append(String.format(format, args));
    dotBuilder.append(System.lineSeparator());
  }

  private static String escapeString(String x) {
    return x.replace("\"", "\\\"");
  }
}


text:
@interface MyArticleDetailView() <UIAlertViewDelegate>

@end
@implementation MyArticleDetailView

- (instancetype)initWithFrame:(CGRect)frame postWithUrl:(NSString*)postWithUrl param:(NSMutableDictionary*)param modalBlcok:(ModalBlock)modalBlcok
{
    if (self =[super initWithFrame:frame]) {
        self.backgroundColor =[UIColor  whiteColor];
        _postWithUrl = postWithUrl;
        _param = param;
        _modalBlcok = modalBlcok;
        [self addMainView:_param];
    }
    return self;
}
- (void)addMainView:(NSDictionary *)parame
{
    for (UIView *suView in self.subviews) {

        [suView removeFromSuperview];
    }
    __weak MyArticleDetailView *weakSelf =self;
    //    NSLog(@"parame =%@ _postWithUrl=%@",parame,_postWithUrl);
    [[ToolManager shareInstance] showWithStatus];
    [XLDataService postWithUrl:_postWithUrl param:parame modelClass:nil responseBlock:^(id dataObj, NSError *error) {
//        NSLog(@"data =%@",dataObj);
        if (dataObj) {

            modal = [MyArticleDetailModal mj_objectWithKeyValues:dataObj];
            if (_modalBlcok) {
                _modalBlcok(modal);
            }
            weakSelf.webView = allocAndInitWithFrame(IMYWebView, CGRectZero);
            weakSelf.webView.backgroundColor = WhiteColor;
            weakSelf.webView.delegate = self;
            weakSelf.webView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
            weakSelf.webView.scrollView.scrollEnabled = NO;
            [weakSelf.webView setScalesPageToFit:YES];
            [self addSubview:weakSelf.webView];

            if (modal.rtcode ==1) {

                UILabel * _descrip= [UILabel createLabelWithFrame:frame( 10, 10, APPWIDTH - 20, 30) text:@"" fontSize:30*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:self];
                _descrip.numberOfLines = 0;
                _descrip.text = modal.datas.title;

                CGSize size =[_descrip sizeWithMultiLineContent:_descrip.text rowWidth:frameWidth(_descrip) font:[UIFont systemFontOfSize:30*SpacedFonts]];
                _descrip.frame = frame(frameX(_descrip),frameY(_descrip), frameWidth(_descrip), size.height);
                UILabel *time =allocAndInit(UILabel);
                CGSize sizeTime = [time sizeWithContent:@"2015 - 12 - 31" font:[UIFont systemFontOfSize:22*SpacedFonts]];

                NSString *times =modal.datas.createtime;

                BaseButton* _time = [[BaseButton alloc]initWithFrame:frame(frameX(_descrip), size.height + 15 ,  5 + sizeTime.width, sizeTime.height)  setTitle:[times timeformatString:@"yyyy-MM-dd"]titleSize:22*SpacedFonts titleColor:LightBlackTitleColor backgroundImage:nil iconImage:nil highlightImage:nil setTitleOrgin:CGPointMake(0,0) setImageOrgin:CGPointMake(0,0)  inView:self];
                _time.shouldAnmial = NO;

                float height =CGRectGetMaxY(_time.frame)  +10 ;
                if (modal.datas.isaddress) {

                    UIView *bg = allocAndInitWithFrame(UIView, frame(0, height, APPWIDTH, 110));
                    bg.backgroundColor = WhiteColor;
                    bg.userInteractionEnabled = YES;
                    self.userInteractionEnabled = YES;
                    [self addSubview:bg];

                    UIImageView *bg1 = allocAndInitWithFrame(UIImageView, frame(10, 10, APPWIDTH - 20, 90));
                    bg1.userInteractionEnabled = YES;
                    bg1.image = [UIImage imageNamed:@"mingpian_back"];
                    [bg addSubview:bg1];

                    UIImageView *icon = allocAndInitWithFrame(UIImageView, frame(10, 20, 50, 50));
                    icon.userInteractionEnabled = YES;
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(iconTap:)];
                    tap.numberOfTapsRequired = 1;
                    [icon addGestureRecognizer:tap];

                    [[ToolManager shareInstance] imageView:icon setImageWithURL:modal.datas.isaddress_imgurl placeholderType:PlaceholderTypeUserHead];

                    [icon setRadius:frameHeight(icon)/2.0];
                    [bg1 addSubview:icon];

                    UILabel *name = [UILabel createLabelWithFrame:frame(CGRectGetMaxX(icon.frame) +7, 14, 0, 26*SpacedFonts) text:modal.datas.isaddress_name fontSize:26*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:bg1];

                    CGSize sizeName = [name sizeWithContent:name.text font:[UIFont systemFontOfSize:26*SpacedFonts]];
                    name.frame = frame(frameX(name), frameY(name), sizeName.width, frameHeight(name));

                    [UILabel createLabelWithFrame:frame(frameX(name), CGRectGetMaxY(name.frame)+10, 200, 26*SpacedFonts) text:modal.datas.isaddress_add fontSize:22*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentLeft inView:bg1];//公司

                    NSString *industryStr=modal.datas.industry;
                    [UILabel createLabelWithFrame:frame(CGRectGetMaxX(name.frame)+10, frameY(name), 200, 26*SpacedFonts) text:industryStr fontSize:22*SpacedFonts textColor:lightGrayTitleColor textAlignment:NSTextAlignmentLeft inView:bg1];//行业

                    [UILabel createLabelWithFrame:frame(bg1.size.width-110, 14, 100, 26*SpacedFonts) text:modal.datas.isaddress_area fontSize:22*SpacedFonts textColor:BlackTitleColor textAlignment:NSTextAlignmentRight inView:bg1];//地址

                    UIImage *shouji=[UIImage imageNamed:@"shouji(1)"];

                    BaseButton *shoujibtn= [[BaseButton alloc]initWithFrame:frame(frameX(name), CGRectGetMaxY(name.frame) +26*SpacedFonts+20, 100, shouji.size.height+6) setTitle:modal.datas.isaddress_tel titleSize:22*SpacedFonts  titleColor:WhiteColor backgroundImage:nil iconImage:shouji highlightImage:nil setTitleOrgin:CGPointMake(3, 3) setImageOrgin:CGPointMake(3, 3) inView:bg1];
                    shoujibtn.didClickBtnBlock = ^
                    {

                        UIAlertView *alertV=[[UIAlertView alloc]initWithTitle:@"温馨提示" message:[NSString stringWithFormat:@"是否要拨打电话 %@",modal.datas.isaddress_tel] delegate:self cancelButtonTitle:nil otherButtonTitles:@"取消",@"确定", nil];
                        [alertV show];
                    };

                    shoujibtn.backgroundColor=[UIColor orangeColor];
                    shoujibtn.radius=(shouji.size.height+6)/2.0;
                    height += 110;
                }
                else
                {
                    UILabel *line1 = allocAndInitWithFrame(UILabel, frame(10, CGRectGetMaxY(_time.frame)  + 6, APPWIDTH - 20, 1.0));
                    line1.backgroundColor = LineBg;
                    [self addSubview:line1];

                }

                weakSelf.webView.frame= frame(5, height, APPWIDTH -10, APPHEIGHT - height);

                [weakSelf.webView loadHTMLString:modal.datas.content baseURL:nil];

            }
            else
            {
                [weakSelf.webView loadHTMLString:[NSString stringWithFormat:@"<p>%@</p>",modal.rtmsg] baseURL:nil];

            }

        }
        else
        {
            [[ToolManager shareInstance] showInfoWithStatus];
        }

    }];

}
#pragma mark - UIWebview delegete
#pragma mark - UIWebview delegete

- (void)webView:(IMYWebView *)webView didFailLoadWithError:(NSError *)error
{
    [[ToolManager shareInstance] showAlertMessage:error.description];
}
- (void)webViewDidFinishLoad:(IMYWebView *)webView
{
      [[ToolManager shareInstance] dismiss];
    [self webViewFitToScale:webView];

    [webView evaluateJavaScript:@"document.body.scrollHeight" completionHandler:^(id objc, NSError * error) {
        CGFloat height = [objc floatValue];
        if (!error) {

            CGRect frame = webView.frame;
            webView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, height);
            if (modal.datas.isaddress) {
                self.contentSize = CGSizeMake(frameWidth(self), 140 + height);

            }
            else
            {
                self.contentSize = CGSizeMake(frameWidth(self), 70 + height);

            }

            if (modal.datas.productpics&&![modal.datas.productpics isEqualToString:@""]) {

                NSArray *images = [modal.datas.productpics componentsSeparatedByString:@","];

                for (int i = 0; i<images.count; i++) {
                    UIImageView *imageView = allocAndInitWithFrame(UIImageView, frame(5,self.contentSize.height + APPWIDTH *i, (APPWIDTH - 10), (APPWIDTH - 10)));
                    [[ToolManager shareInstance] imageView:imageView setImageWithURL:images[i] placeholderType:PlaceholderTypeImageUnProcessing];
                    [self addSubview:imageView];

                }
                self.contentSize = CGSizeMake(frameWidth(self), self.contentSize.height + APPWIDTH*images.count);
            }

        }
    }];

}
//结合JS解决用webVIew加载图片时图片自动适配屏幕的问题
- (void)webViewFitToScale:(IMYWebView *)webView
{
    NSString *js=@"var script = document.createElement('script');"
    "script.type = 'text/javascript';"
    "script.text = \"function ResizeImages() { "
    "var myimg,oldwidth;"
    "var maxwidth = %f;"
    "for(i=0;i <document.images.length;i++){"
    "myimg = document.images[i];"
    "if(myimg.width > maxwidth){"
    "oldwidth = myimg.width;"
    "myimg.width = %f;"
    "}"
    "}"
    "}\";"
    "document.getElementsByTagName('head')[0].appendChild(script);";
    js=[NSString stringWithFormat:js,[UIScreen mainScreen].bounds.size.width,[UIScreen mainScreen].bounds.size.width-15];
    [webView evaluateJavaScript:js completionHandler:^(id objc, NSError *error) {

    }];
    [webView evaluateJavaScript:@"ResizeImages();" completionHandler:^(id objc, NSError *error) {

    }];

}
#pragma mark
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{

    if (buttonIndex==0) {
        return;
    }else if (buttonIndex==1) {

        NSString *str=[NSString stringWithFormat:@"tel://%@",modal.datas.isaddress_tel];
        NSURL *url=[NSURL URLWithString:str];
        [[UIApplication sharedApplication]openURL:url];

    }

}

#pragma mark
#pragma mark 头像点击
- (void)iconTap:(UITapGestureRecognizer *)sender
{

    MyDetialViewController *myDetialViewCT=allocAndInit(MyDetialViewController);
    if (modal.datas.product_uid) {
        myDetialViewCT.userID=modal.datas.product_uid;

    }

}
@end


text:
using System.IO;
using SharpCompress.Common;

namespace SharpCompress.IO
{
    internal class ListeningStream : Stream
    {
        private long currentEntryTotalReadBytes;
        private readonly IExtractionListener listener;

        public ListeningStream(IExtractionListener listener, Stream stream)
        {
            Stream = stream;
            this.listener = listener;
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Stream.Dispose();
            }
            base.Dispose(disposing);
        }

        public Stream Stream { get; }

        public override bool CanRead => Stream.CanRead;

        public override bool CanSeek => Stream.CanSeek;

        public override bool CanWrite => Stream.CanWrite;

        public override void Flush()
        {
            Stream.Flush();
        }

        public override long Length => Stream.Length;

        public override long Position { get => Stream.Position; set => Stream.Position = value; }

        public override int Read(byte[] buffer, int offset, int count)
        {
            int read = Stream.Read(buffer, offset, count);
            currentEntryTotalReadBytes += read;
            listener.FireCompressedBytesRead(currentEntryTotalReadBytes, currentEntryTotalReadBytes);
            return read;
        }

        public override int ReadByte()
        {
            int value = Stream.ReadByte();
            if (value == -1)
            {
                return -1;
            }

            ++currentEntryTotalReadBytes;
            listener.FireCompressedBytesRead(currentEntryTotalReadBytes, currentEntryTotalReadBytes);
            return value;
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return Stream.Seek(offset, origin);
        }

        public override void SetLength(long value)
        {
            Stream.SetLength(value);
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            Stream.Write(buffer, offset, count);
        }
    }
}