text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.apache.hadoop</groupId>
  <artifactId>hadoop-core</artifactId>
  <packaging>jar</packaging>
  <version>@version</version>
  <dependencies>
   <dependency>
      <groupId>commons-cli</groupId>
      <artifactId>commons-cli</artifactId>
      <version>1.2</version>
    </dependency>
   <dependency>
      <groupId>xmlenc</groupId>
      <artifactId>xmlenc</artifactId>
      <version>0.52</version>
    </dependency>
    <dependency>
      <groupId>commons-httpclient</groupId>
      <artifactId>commons-httpclient</artifactId>
      <version>3.0.1</version>
    </dependency>
    <dependency>
      <groupId>commons-codec</groupId>
      <artifactId>commons-codec</artifactId>
      <version>1.3</version>
    </dependency>
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>1.4.1</version>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jetty</artifactId>
      <version>6.1.14</version>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jetty-util</artifactId>
      <version>6.1.14</version>
    </dependency>
    <dependency>
      <groupId>tomcat</groupId>
      <artifactId>jasper-runtime</artifactId>
      <version>5.5.12</version>
    </dependency>
    <dependency>
      <groupId>tomcat</groupId>
      <artifactId>jasper-compiler</artifactId>
      <version>5.5.12</version>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jsp-api-2.1</artifactId>
      <version>6.1.14</version>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>jsp-2.1</artifactId>
      <version>6.1.14</version>
    </dependency>
    <dependency>
      <groupId>commons-el</groupId>
      <artifactId>commons-el</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>net.java.dev.jets3t</groupId>
      <artifactId>jets3t</artifactId>
      <version>0.7.1</version>
    </dependency>
    <dependency>
      <groupId>commons-net</groupId>
      <artifactId>commons-net</artifactId>
      <version>1.4.1</version>
    </dependency>
    <dependency>
      <groupId>org.mortbay.jetty</groupId>
      <artifactId>servlet-api-2.5</artifactId>
      <version>6.1.14</version>
    </dependency>
    <dependency>
      <groupId>net.sf.kosmosfs</groupId>
      <artifactId>kfs</artifactId>
      <version>0.3</version>
    </dependency>
    <dependency>
      <groupId>hsqldb</groupId>
      <artifactId>hsqldb</artifactId>
      <version>1.8.0.10</version>
    </dependency>
    <dependency>
      <groupId>oro</groupId>
      <artifactId>oro</artifactId>
      <version>2.0.8</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.jdt</groupId>
      <artifactId>core</artifactId>
      <version>3.1.1</version>
    </dependency>
  </dependencies>
</project>


text:
class CreateExchangeRateEurRate < ActiveRecord::Migration
  def self.up
    create_table :exchange_rate_eur_rate do |t|
      t.integer :currency_id
      t.float :rate
      t.date :rate_date
      t.timestamps
    end
  end

  def self.down
    drop_table :exchange_rate_eur_rate
  end
end

redpajama_set_name: RedPajamaGithub


text:
package edu.irabank.dao.impl;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import antlr.collections.Stack;
import edu.irabank.dao.AccountDetailsDAO;
import edu.irabank.dao.UserDAO;
import edu.irabank.dto.AccountDetailsDTO;
import edu.irabank.dto.UserDTO;

/**
 * @author Abha Upadhyay
 *
 */

@Repository
public class AccountDetailsDAOImpl implements AccountDetailsDAO
{
	@Autowired
	private SessionFactory sessionFactory;
	@Autowired
	HttpSession sessionID;
	@Autowired
	UserDAO userDAO;

	@Override
	public boolean getAccountNum(String accountNO)
	{
		Session session = sessionFactory.getCurrentSession();
		Query query = session.getNamedQuery("AccountDetailsDTO.findByAccountNumber"); //using NamedQuery
		System.out.println("AccountNo here: " + accountNO);
		query.setParameter("accountNumber", accountNO);
		System.out.println("query : " + query);

		try{
			String accountno = ((AccountDetailsDTO) query.uniqueResult()).getAccountNumber();
			System.out.println("query : " + query);
			System.out.println("Retrieved Accountnumber = " + accountno);
			return true;
			}
			catch(Exception e){
			System.out.println("41 : the exception is " + e);
			e.printStackTrace();
			return false;

			}

	}

	@Override
	public Double getBalance(String accntno)
	{
		Session session = sessionFactory.getCurrentSession();
		Query query = session.getNamedQuery("AccountDetailsDTO.findByAccountNumber"); //using NamedQuery
		System.out.println("AccountNo here: " + accntno);
		query.setParameter("accountNumber", accntno);
		System.out.println("query : " + query);
		Double Balance = ((AccountDetailsDTO) query.uniqueResult()).getBalance();
		return Balance;
	}

	@Override
	//Used in Credit and Debit to Update Balance
	public boolean updateBalance(String accountno, Double balance)
	{
		Session session = sessionFactory.getCurrentSession();
		Query query = session.getNamedQuery("AccountDetailsDTO.findByAccountNumber"); //using NamedQuery
		System.out.println("Balance here: " + balance);
		query.setParameter("accountNumber", accountno);
		System.out.println("query : " + query);
		((AccountDetailsDTO) query.uniqueResult()).setBalance(balance);
		return true;
	}

	@Override
	public String getAccountNumbyUserID(Integer Userid)
	{
		try{
		System.out.println("Entered Try Loop for DAO" + Userid);

		//get UserDTO to pass it to AccountDetails
		UserDTO userDTO = new UserDTO();
		userDTO = userDAO.getUserDTOByUserId(Userid);

		Query query = getSession().createQuery("SELECT a FROM AccountDetailsDTO a WHERE a.uId = :uId");
		System.out.println("userID here: " + Userid);

		query.setParameter("uId", userDTO);
		AccountDetailsDTO DTO = (AccountDetailsDTO) query.uniqueResult();
		String Accountnum = DTO.getAccountNumber();
		System.out.println("Account Number: "+ Accountnum);

		return Accountnum;
		}
		catch(Exception e){
			System.out.println("Exception: "+ e);
			return null;

		}
	}

	private Session getSession() {
		Session sessionobj = getSessionFactory().getCurrentSession();
		if (sessionobj == null) {
			sessionobj = getSessionFactory().openSession();
		}
		return sessionobj;
	}
	private SessionFactory getSessionFactory() {

		return sessionFactory;
	}

}


text:
#ifndef ContentSelectorQuery_h
#define ContentSelectorQuery_h

#include "core/css/CSSSelectorList.h"
#include "wtf/Forward.h"
#include "wtf/Vector.h"

namespace WebCore {

class Document;
class Node;
class InsertionPoint;

class ContentSelectorDataList {
public:
    void initialize(const CSSSelectorList&);
    bool matches(const Vector<RefPtr<Node> >& siblings, int nthNode) const;

private:
    static bool checkContentSelector(const CSSSelector*, const Vector<RefPtr<Node> >& siblings, int nthNode);

    Vector<const CSSSelector*> m_selectors;
};

class ContentSelectorQuery {
    WTF_MAKE_NONCOPYABLE(ContentSelectorQuery);
public:
    explicit ContentSelectorQuery(InsertionPoint*);

    bool matches(const Vector<RefPtr<Node> >& siblings, int nthNode) const;

private:
    InsertionPoint* m_insertionPoint;
    ContentSelectorDataList m_selectors;
};

}

#endif


text: Dimuons analysis for HEP SWC 2015-16


text:
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('todo', '0010_attachment'),
    ]

    operations = [
        migrations.AlterField(
            model_name='task',
            name='created_by',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='todo_created_by', to=settings.AUTH_USER_MODEL),
        ),
    ]


text:
package util

import (
	"syscall"
	"time"
)

var (
	lastInspectUnixNano int64
	lastCPUUsageTime    int64
)

// GetCPUPercentage calculates CPU usage and returns percentage in float64(e.g. 2.5 means 2.5%).
// http://man7.org/linux/man-pages/man2/getrusage.2.html
func GetCPUPercentage() float64 {
	var ru syscall.Rusage
	_ = syscall.Getrusage(syscall.RUSAGE_SELF, &ru)
	usageTime := ru.Utime.Nano() + ru.Stime.Nano()
	nowTime := time.Now().UnixNano()
	perc := float64(usageTime-lastCPUUsageTime) / float64(nowTime-lastInspectUnixNano) * 100.0
	lastInspectUnixNano = nowTime
	lastCPUUsageTime = usageTime
	return perc
}


text:
package x509

import (
	"io/fs"
	"os"
	"path/filepath"
	"strings"
)

const (
	// certFileEnv is the environment variable which identifies where to locate
	// the SSL certificate file. If set this overrides the system default.
	certFileEnv = "SSL_CERT_FILE"

	// certDirEnv is the environment variable which identifies which directory
	// to check for SSL certificate files. If set this overrides the system default.
	// It is a colon separated list of directories.
	// See https://www.openssl.org/docs/man1.0.2/man1/c_rehash.html.
	certDirEnv = "SSL_CERT_DIR"
)

func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) {
	return nil, nil
}

func loadSystemRoots() (*CertPool, error) {
	roots := NewCertPool()

	files := certFiles
	if f := os.Getenv(certFileEnv); f != "" {
		files = []string{f}
	}

	var firstErr error
	for _, file := range files {
		data, err := os.ReadFile(file)
		if err == nil {
			roots.AppendCertsFromPEM(data)
			break
		}
		if firstErr == nil && !os.IsNotExist(err) {
			firstErr = err
		}
	}

	dirs := certDirectories
	if d := os.Getenv(certDirEnv); d != "" {
		// OpenSSL and BoringSSL both use ":" as the SSL_CERT_DIR separator.
		// See:
		//  * https://golang.org/issue/35325
		//  * https://www.openssl.org/docs/man1.0.2/man1/c_rehash.html
		dirs = strings.Split(d, ":")
	}

	for _, directory := range dirs {
		fis, err := readUniqueDirectoryEntries(directory)
		if err != nil {
			if firstErr == nil && !os.IsNotExist(err) {
				firstErr = err
			}
			continue
		}
		for _, fi := range fis {
			data, err := os.ReadFile(directory + "/" + fi.Name())
			if err == nil {
				roots.AppendCertsFromPEM(data)
			}
		}
	}

	if roots.len() > 0 || firstErr == nil {
		return roots, nil
	}

	return nil, firstErr
}

// readUniqueDirectoryEntries is like os.ReadDir but omits
// symlinks that point within the directory.
func readUniqueDirectoryEntries(dir string) ([]fs.DirEntry, error) {
	files, err := os.ReadDir(dir)
	if err != nil {
		return nil, err
	}
	uniq := files[:0]
	for _, f := range files {
		if !isSameDirSymlink(f, dir) {
			uniq = append(uniq, f)
		}
	}
	return uniq, nil
}

// isSameDirSymlink reports whether fi in dir is a symlink with a
// target not containing a slash.
func isSameDirSymlink(f fs.DirEntry, dir string) bool {
	if f.Type()&fs.ModeSymlink == 0 {
		return false
	}
	target, err := os.Readlink(filepath.Join(dir, f.Name()))
	return err == nil && !strings.Contains(target, "/")
}


text:
@interface HouseModel : NSObject

@property (copy, nonatomic) NSString *address;
@property (assign, nonatomic) CGFloat area;
@property (strong, nonatomic) NSArray *tags;

@end


text:
package warehouse.products;

import lombok.ToString;
import lombok.Value;
import warehouse.PaletteLabel;

import java.util.List;

/**
 * Created by michal on 12.12.2016.
 */
public interface ProductStockEventStore {
    EventId persist(PaletteLabel storageUnit, Object event);

    List<Object> readEventsInStock(String refNo);
    List<Object> readEventsSince(String refNo, EventId since);

    @Value
    @ToString(of = "id")
    class EventId {
        Object id;
    }
}


text:
@class FSNConnection;

// block types
typedef id(^FSNParseBlock)(FSNConnection *, NSError **);
typedef void(^FSNCompletionBlock)(FSNConnection *);
typedef void(^FSNProgressBlock)(FSNConnection *);

// http methods
// add additional http methods as necessary
// non-http request methods could also go here
typedef enum {
    FSNRequestMethodGET = 0, // default
    FSNRequestMethodPOST,
} FSNRequestMethod;

// NSNotification names
extern NSString * const FSNConnectionActivityBegan;
extern NSString * const FSNConnectionActivityEnded;

// string function for request enum
NSString* stringForRequestMethod(FSNRequestMethod method);

@interface FSNConnection : NSObject <NSURLConnectionDelegate>

// NOTE: object property declarations in header are explicity 'strong' so that non-arc code may include the header.

@property (nonatomic, strong) NSURL *url;
@property (nonatomic) FSNRequestMethod method;

#if TARGET_OS_IPHONE
@property (nonatomic) BOOL shouldRunInBackground; // defaults to YES for POST method
#endif

@property (nonatomic, strong) NSDictionary *headers;    // optional custom http headers
@property (nonatomic, strong) NSDictionary *parameters; // GET or POST parameters, including POST form data

@property (nonatomic, copy) FSNParseBlock parseBlock;           // executed in background thread
@property (nonatomic, copy) FSNCompletionBlock completionBlock; // executed in main thread
@property (nonatomic, copy) FSNProgressBlock progressBlock;     // executed in main thread

@property (nonatomic, strong, readonly) NSURLResponse *response;        // response from NSURLConnection
@property (nonatomic, strong, readonly) NSHTTPURLResponse *httpResponse; // response or nil if not an http response
@property (nonatomic, strong, readonly) NSData *responseData;           // populated with data unless responseStream is set.
@property (nonatomic, strong) NSOutputStream *responseStream;           // if this is set then responseData will be nil

@property (nonatomic, strong, readonly) id<NSObject> parseResult;       // result of parseBlock; may be nil on success
@property (nonatomic, strong, readonly) NSError *error;                 // if set then the request or parse failed

@property (nonatomic, readonly) BOOL didStart;          // start was called
@property (nonatomic, readonly) BOOL didFinishLoading;  // underlying connection finished loading
@property (nonatomic, readonly) BOOL didComplete;       // underlying connection either finished or failed
@property (nonatomic, readonly) BOOL didSucceed;        // finished with no error

@property (nonatomic, readonly) long long uploadProgressBytes;
@property (nonatomic, readonly) long long uploadExpectedBytes;
@property (nonatomic, readonly) long long downloadProgressBytes;
@property (nonatomic, readonly) long long downloadExpectedBytes;
@property (nonatomic, readonly) float uploadProgress;
@property (nonatomic, readonly) float downloadProgress;

@property (nonatomic, readonly) NSUInteger concurrencyCountAtStart;
@property (nonatomic, readonly) NSTimeInterval startTime;
@property (nonatomic, readonly) NSTimeInterval challengeInterval;
@property (nonatomic, readonly) NSTimeInterval responseInterval;
@property (nonatomic, readonly) NSTimeInterval finishOrFailInterval;
@property (nonatomic, readonly) NSTimeInterval parseInterval;

+ (id)withUrl:(NSURL *)url
       method:(FSNRequestMethod)method
      headers:(NSDictionary *)headers
   parameters:(NSDictionary *)parameters
   parseBlock:(FSNParseBlock)parseBlock
completionBlock:(FSNCompletionBlock)completionBlock
progressBlock:(FSNProgressBlock)progressBlock;

+ (NSSet *)connections;
+ (void)cancelAllConnections;

// call this method to allow the request to complete but ignore the response.
- (void)clearBlocks;

- (FSNConnection *)start; // returns self for chaining convenience, or nil if start fails.

- (void)cancel; // no blocks will be called after request is cancelled, unless a call to finish is already scheduled.

@end


text:
<?php

namespace CRTX\Curl;

use CRTX\AbstractFactory\AbstractFactory;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;

/**
 * @author Christian Ruiz <ruiz.d.christian@gmail.com>
 */
class MultiCurlFactory extends AbstractFactory
{
    public function build($className, array $arguments = array())
    {
        $ReflectedClass = $this->getClassReflection($className);

        $parameterBagList = array();

        $CurlFactory = new CurlFactory();

        foreach($arguments as & $parameterList) {
            $parameterList['curlhandle'] = curl_init($parameterList['url']);
            $parameterList['curl'] = $CurlFactory->build('Curl', array(
                    $parameterList['curlhandle'],
                    $parameterList['optionList']
                )
            );
            array_push($parameterBagList, new ParameterBag($parameterList));
        }

        return $ReflectedClass->newInstance($parameterBagList);
    }
}


text:
__version__ = '$Revision: 1.5 $'[11:-2]

from StringIO import StringIO
from twisted.trial import unittest
from twisted.protocols import pcp

# Goal:

# Take a Protocol instance.  Own all outgoing data - anything that
# would go to p.transport.write.  Own all incoming data - anything
# that comes to p.dataReceived.

# I need:
# Something with the AbstractFileDescriptor interface.
# That is:
#  - acts as a Transport
#    - has a method write()
#    - which buffers
#  - acts as a Consumer
#    - has a registerProducer, unRegisterProducer
#    - tells the Producer to back off (pauseProducing) when its buffer is full.
#    - tells the Producer to resumeProducing when its buffer is not so full.
#  - acts as a Producer
#    - calls registerProducer
#    - calls write() on consumers
#    - honors requests to pause/resume producing
#    - honors stopProducing, and passes it along to upstream Producers

class DummyTransport:
    """A dumb transport to wrap around."""

    def __init__(self):
        self._writes = []

    def write(self, data):
        self._writes.append(data)

    def getvalue(self):
        return ''.join(self._writes)

class DummyProducer:
    resumed = False
    stopped = False
    paused = False

    def __init__(self, consumer):
        self.consumer = consumer

    def resumeProducing(self):
        self.resumed = True
        self.paused = False

    def pauseProducing(self):
        self.paused = True

    def stopProducing(self):
        self.stopped = True

class DummyConsumer(DummyTransport):
    producer = None
    finished = False
    unregistered = True

    def registerProducer(self, producer, streaming):
        self.producer = (producer, streaming)

    def unregisterProducer(self):
        self.unregistered = True

    def finish(self):
        self.finished = True

class TransportInterfaceTest(unittest.TestCase):
    proxyClass = pcp.BasicProducerConsumerProxy

    def setUp(self):
        self.underlying = DummyConsumer()
        self.transport = self.proxyClass(self.underlying)

    def testWrite(self):
        self.transport.write("some bytes")

class ConsumerInterfaceTest:
    """Test ProducerConsumerProxy as a Consumer.

    Normally we have ProducingServer -> ConsumingTransport.

    If I am to go between (Server -> Shaper -> Transport), I have to
    play the role of Consumer convincingly for the ProducingServer.
    """

    def setUp(self):
        self.underlying = DummyConsumer()
        self.consumer = self.proxyClass(self.underlying)
        self.producer = DummyProducer(self.consumer)

    def testRegisterPush(self):
        self.consumer.registerProducer(self.producer, True)
        ## Consumer should NOT have called PushProducer.resumeProducing
        self.failIf(self.producer.resumed)

    ## I'm I'm just a proxy, should I only do resumeProducing when
    ## I get poked myself?
    #def testRegisterPull(self):
    #    self.consumer.registerProducer(self.producer, False)
    #    ## Consumer SHOULD have called PushProducer.resumeProducing
    #    self.failUnless(self.producer.resumed)

    def testUnregister(self):
        self.consumer.registerProducer(self.producer, False)
        self.consumer.unregisterProducer()
        # Now when the consumer would ordinarily want more data, it
        # shouldn't ask producer for it.
        # The most succinct way to trigger "want more data" is to proxy for
        # a PullProducer and have someone ask me for data.
        self.producer.resumed = False
        self.consumer.resumeProducing()
        self.failIf(self.producer.resumed)

    def testFinish(self):
        self.consumer.registerProducer(self.producer, False)
        self.consumer.finish()
        # I guess finish should behave like unregister?
        self.producer.resumed = False
        self.consumer.resumeProducing()
        self.failIf(self.producer.resumed)

class ProducerInterfaceTest:
    """Test ProducerConsumerProxy as a Producer.

    Normally we have ProducingServer -> ConsumingTransport.

    If I am to go between (Server -> Shaper -> Transport), I have to
    play the role of Producer convincingly for the ConsumingTransport.
    """

    def setUp(self):
        self.consumer = DummyConsumer()
        self.producer = self.proxyClass(self.consumer)

    def testRegistersProducer(self):
        self.failUnlessEqual(self.consumer.producer[0], self.producer)

    def testPause(self):
        self.producer.pauseProducing()
        self.producer.write("yakkity yak")
        self.failIf(self.consumer.getvalue(),
                    "Paused producer should not have sent data.")

    def testResume(self):
        self.producer.pauseProducing()
        self.producer.resumeProducing()
        self.producer.write("yakkity yak")
        self.failUnlessEqual(self.consumer.getvalue(), "yakkity yak")

    def testResumeNoEmptyWrite(self):
        self.producer.pauseProducing()
        self.producer.resumeProducing()
        self.failUnlessEqual(len(self.consumer._writes), 0,
                             "Resume triggered an empty write.")

    def testResumeBuffer(self):
        self.producer.pauseProducing()
        self.producer.write("buffer this")
        self.producer.resumeProducing()
        self.failUnlessEqual(self.consumer.getvalue(), "buffer this")

    def testStop(self):
        self.producer.stopProducing()
        self.producer.write("yakkity yak")
        self.failIf(self.consumer.getvalue(),
                    "Stopped producer should not have sent data.")

class PCP_ConsumerInterfaceTest(ConsumerInterfaceTest, unittest.TestCase):
    proxyClass = pcp.BasicProducerConsumerProxy

class PCPII_ConsumerInterfaceTest(ConsumerInterfaceTest, unittest.TestCase):
    proxyClass = pcp.ProducerConsumerProxy

class PCP_ProducerInterfaceTest(ProducerInterfaceTest, unittest.TestCase):
    proxyClass = pcp.BasicProducerConsumerProxy

class PCPII_ProducerInterfaceTest(ProducerInterfaceTest, unittest.TestCase):
    proxyClass = pcp.ProducerConsumerProxy

class ProducerProxyTest(unittest.TestCase):
    """Producer methods on me should be relayed to the Producer I proxy.
    """
    proxyClass = pcp.BasicProducerConsumerProxy

    def setUp(self):
        self.proxy = self.proxyClass(None)
        self.parentProducer = DummyProducer(self.proxy)
        self.proxy.registerProducer(self.parentProducer, True)

    def testStop(self):
        self.proxy.stopProducing()
        self.failUnless(self.parentProducer.stopped)

class ConsumerProxyTest(unittest.TestCase):
    """Consumer methods on me should be relayed to the Consumer I proxy.
    """
    proxyClass = pcp.BasicProducerConsumerProxy

    def setUp(self):
        self.underlying = DummyConsumer()
        self.consumer = self.proxyClass(self.underlying)

    def testWrite(self):
        # NOTE: This test only valid for streaming (Push) systems.
        self.consumer.write("some bytes")
        self.failUnlessEqual(self.underlying.getvalue(), "some bytes")

    def testFinish(self):
        self.consumer.finish()
        self.failUnless(self.underlying.finished)

    def testUnregister(self):
        self.consumer.unregisterProducer()
        self.failUnless(self.underlying.unregistered)

class PullProducerTest:
    def setUp(self):
        self.underlying = DummyConsumer()
        self.proxy = self.proxyClass(self.underlying)
        self.parentProducer = DummyProducer(self.proxy)
        self.proxy.registerProducer(self.parentProducer, True)

    def testHoldWrites(self):
        self.proxy.write("hello")
        # Consumer should get no data before it says resumeProducing.
        self.failIf(self.underlying.getvalue(),
                    "Pulling Consumer got data before it pulled.")

    def testPull(self):
        self.proxy.write("hello")
        self.proxy.resumeProducing()
        self.failUnlessEqual(self.underlying.getvalue(), "hello")

    def testMergeWrites(self):
        self.proxy.write("hello ")
        self.proxy.write("sunshine")
        self.proxy.resumeProducing()
        nwrites = len(self.underlying._writes)
        self.failUnlessEqual(nwrites, 1, "Pull resulted in %d writes instead "
                             "of 1." % (nwrites,))
        self.failUnlessEqual(self.underlying.getvalue(), "hello sunshine")

    def testLateWrite(self):
        # consumer sends its initial pull before we have data
        self.proxy.resumeProducing()
        self.proxy.write("data")
        # This data should answer that pull request.
        self.failUnlessEqual(self.underlying.getvalue(), "data")

class PCP_PullProducerTest(PullProducerTest, unittest.TestCase):
    class proxyClass(pcp.BasicProducerConsumerProxy):
        iAmStreaming = False

class PCPII_PullProducerTest(PullProducerTest, unittest.TestCase):
    class proxyClass(pcp.ProducerConsumerProxy):
        iAmStreaming = False

# Buffering!

class BufferedConsumerTest(unittest.TestCase):
    """As a consumer, ask the producer to pause after too much data."""

    proxyClass = pcp.ProducerConsumerProxy

    def setUp(self):
        self.underlying = DummyConsumer()
        self.proxy = self.proxyClass(self.underlying)
        self.proxy.bufferSize = 100

        self.parentProducer = DummyProducer(self.proxy)
        self.proxy.registerProducer(self.parentProducer, True)

    def testRegisterPull(self):
        self.proxy.registerProducer(self.parentProducer, False)
        ## Consumer SHOULD have called PushProducer.resumeProducing
        self.failUnless(self.parentProducer.resumed)

    def testPauseIntercept(self):
        self.proxy.pauseProducing()
        self.failIf(self.parentProducer.paused)

    def testResumeIntercept(self):
        self.proxy.pauseProducing()
        self.proxy.resumeProducing()
        # With a streaming producer, just because the proxy was resumed is
        # not necessarily a reason to resume the parent producer.  The state
        # of the buffer should decide that.
        self.failIf(self.parentProducer.resumed)

    def testTriggerPause(self):
        """Make sure I say \"when.\""""

        # Pause the proxy so data sent to it builds up in its buffer.
        self.proxy.pauseProducing()
        self.failIf(self.parentProducer.paused, "don't pause yet")
        self.proxy.write("x" * 51)
        self.failIf(self.parentProducer.paused, "don't pause yet")
        self.proxy.write("x" * 51)
        self.failUnless(self.parentProducer.paused)

    def testTriggerResume(self):
        """Make sure I resumeProducing when my buffer empties."""
        self.proxy.pauseProducing()
        self.proxy.write("x" * 102)
        self.failUnless(self.parentProducer.paused, "should be paused")
        self.proxy.resumeProducing()
        # Resuming should have emptied my buffer, so I should tell my
        # parent to resume too.
        self.failIf(self.parentProducer.paused,
                    "Producer should have resumed.")
        self.failIf(self.proxy.producerPaused)

class BufferedPullTests(unittest.TestCase):
    class proxyClass(pcp.ProducerConsumerProxy):
        iAmStreaming = False

        def _writeSomeData(self, data):
            pcp.ProducerConsumerProxy._writeSomeData(self, data[:100])
            return min(len(data), 100)

    def setUp(self):
        self.underlying = DummyConsumer()
        self.proxy = self.proxyClass(self.underlying)
        self.proxy.bufferSize = 100

        self.parentProducer = DummyProducer(self.proxy)
        self.proxy.registerProducer(self.parentProducer, False)

    def testResumePull(self):
        # If proxy has no data to send on resumeProducing, it had better pull
        # some from its PullProducer.
        self.parentProducer.resumed = False
        self.proxy.resumeProducing()
        self.failUnless(self.parentProducer.resumed)

    def testLateWriteBuffering(self):
        # consumer sends its initial pull before we have data
        self.proxy.resumeProducing()
        self.proxy.write("datum" * 21)
        # This data should answer that pull request.
        self.failUnlessEqual(self.underlying.getvalue(), "datum" * 20)
        # but there should be some left over
        self.failUnlessEqual(self.proxy._buffer, ["datum"])

# TODO:
#  test that web request finishing bug (when we weren't proxying
#    unregisterProducer but were proxying finish, web file transfers
#    would hang on the last block.)
#  test what happens if writeSomeBytes decided to write zero bytes.


text:
title: commaSeparatedPattern - detekt-api
---

[detekt-api](../../index.html) / [io.gitlab.arturbosch.detekt.api](../index.html) / [kotlin.String](index.html) / [commaSeparatedPattern](./comma-separated-pattern.html)

# commaSeparatedPattern

`fun `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`.commaSeparatedPattern(vararg delimiters: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)` = arrayOf(",")): `[`Sequence`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/-sequence/index.html)`<`[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`>`

Splits given String into a sequence of strings splited by the provided delimiters ("," by default).

It also trims the strings and removes the empty ones


text:
setxkbmap -layout nada
# xcape -e 'Hyper_R=backslash;ISO_Level3_Shift=Escape'
xcape -e 'Hyper_L=Tab;Hyper_R=backslash;ISO_Level3_Shift=Escape' # OLD way with Tab bug


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Joshua Miller -- Portfolio</title>
	<link rel="stylesheet" type="text/css" href="assets/css/reset.css">
	<link rel="stylesheet" type="text/css" href="assets/css/style.css">

Joshua Miller

About

|

Portfolio

|

Contact

Portfolio

Hangman

RPG Game

Trivia Game

Rutgers Info Widget

Rock Paper Scissors

Connect with Me

		© Copyright 2017 Joshua Miller


text:
namespace rxcpp {

namespace subjects {

namespace detail {

template<class T>
class multicast_observer
{
    typedef subscriber<T> observer_type;
    typedef std::vector<observer_type> list_type;

    struct mode
    {
        enum type {
            Invalid = 0,
            Casting,
            Disposed,
            Completed,
            Errored
        };
    };

    struct state_type
        : public std::enable_shared_from_this<state_type>
    {
        explicit state_type(composite_subscription cs)
            : generation(0)
            , current(mode::Casting)
            , lifetime(cs)
        {
        }
        std::atomic<int> generation;
        std::mutex lock;
        typename mode::type current;
        std::exception_ptr error;
        composite_subscription lifetime;
    };

    struct completer_type
        : public std::enable_shared_from_this<completer_type>
    {
        ~completer_type()
        {
        }
        completer_type(std::shared_ptr<state_type> s, const std::shared_ptr<completer_type>& old, observer_type o)
            : state(s)
        {
            if (old) {
                observers.reserve(old->observers.size() + 1);
                std::copy_if(
                    old->observers.begin(), old->observers.end(),
                    std::inserter(observers, observers.end()),
                    [](const observer_type& o){
                        return o.is_subscribed();
                    });
            }
            observers.push_back(o);
        }
        std::shared_ptr<state_type> state;
        list_type observers;
    };

    // this type prevents a circular ref between state and completer
    struct binder_type
        : public std::enable_shared_from_this<binder_type>
    {
        explicit binder_type(composite_subscription cs)
            : state(std::make_shared<state_type>(cs))
            , id(trace_id::make_next_id_subscriber())
            , current_generation(0)
        {
        }

        std::shared_ptr<state_type> state;

        trace_id id;

        // used to avoid taking lock in on_next
        mutable int current_generation;
        mutable std::shared_ptr<completer_type> current_completer;

        // must only be accessed under state->lock
        mutable std::shared_ptr<completer_type> completer;
    };

    std::shared_ptr<binder_type> b;

public:
    typedef subscriber<T, observer<T, detail::multicast_observer<T>>> input_subscriber_type;

    explicit multicast_observer(composite_subscription cs)
        : b(std::make_shared<binder_type>(cs))
    {
        auto keepAlive = b;
        b->state->lifetime.add([keepAlive](){
            if (keepAlive->state->current == mode::Casting){
                keepAlive->state->current = mode::Disposed;
                keepAlive->current_completer.reset();
                keepAlive->completer.reset();
                ++keepAlive->state->generation;
            }
        });
    }
    trace_id get_id() const {
        return b->id;
    }
    composite_subscription get_subscription() const {
        return b->state->lifetime;
    }
    input_subscriber_type get_subscriber() const {
        return make_subscriber<T>(get_id(), get_subscription(), observer<T, detail::multicast_observer<T>>(*this));
    }
    bool has_observers() const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        return b->current_completer && !b->current_completer->observers.empty();
    }
    template<class SubscriberFrom>
    void add(const SubscriberFrom& sf, observer_type o) const {
        trace_activity().connect(sf, o);
        std::unique_lock<std::mutex> guard(b->state->lock);
        switch (b->state->current) {
        case mode::Casting:
            {
                if (o.is_subscribed()) {
                    b->completer = std::make_shared<completer_type>(b->state, b->completer, o);
                    ++b->state->generation;
                }
            }
            break;
        case mode::Completed:
            {
                guard.unlock();
                o.on_completed();
                return;
            }
            break;
        case mode::Errored:
            {
                auto e = b->state->error;
                guard.unlock();
                o.on_error(e);
                return;
            }
            break;
        case mode::Disposed:
            {
                guard.unlock();
                o.unsubscribe();
                return;
            }
            break;
        default:
            abort();
        }
    }
    template<class V>
    void on_next(V v) const {
        if (b->current_generation != b->state->generation) {
            std::unique_lock<std::mutex> guard(b->state->lock);
            b->current_generation = b->state->generation;
            b->current_completer = b->completer;
        }

        auto current_completer = b->current_completer;
        if (!current_completer || current_completer->observers.empty()) {
            return;
        }
        for (auto& o : current_completer->observers) {
            if (o.is_subscribed()) {
                o.on_next(v);
            }
        }
    }
    void on_error(std::exception_ptr e) const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        if (b->state->current == mode::Casting) {
            b->state->error = e;
            b->state->current = mode::Errored;
            auto s = b->state->lifetime;
            auto c = std::move(b->completer);
            b->current_completer.reset();
            ++b->state->generation;
            guard.unlock();
            if (c) {
                for (auto& o : c->observers) {
                    if (o.is_subscribed()) {
                        o.on_error(e);
                    }
                }
            }
            s.unsubscribe();
        }
    }
    void on_completed() const {
        std::unique_lock<std::mutex> guard(b->state->lock);
        if (b->state->current == mode::Casting) {
            b->state->current = mode::Completed;
            auto s = b->state->lifetime;
            auto c = std::move(b->completer);
            b->current_completer.reset();
            ++b->state->generation;
            guard.unlock();
            if (c) {
                for (auto& o : c->observers) {
                    if (o.is_subscribed()) {
                        o.on_completed();
                    }
                }
            }
            s.unsubscribe();
        }
    }
};

}

template<class T>
class subject
{
    detail::multicast_observer<T> s;

public:
    typedef subscriber<T, observer<T, detail::multicast_observer<T>>> subscriber_type;
    typedef observable<T> observable_type;
    subject()
        : s(composite_subscription())
    {
    }
    explicit subject(composite_subscription cs)
        : s(cs)
    {
    }

    bool has_observers() const {
        return s.has_observers();
    }

    subscriber_type get_subscriber() const {
        return s.get_subscriber();
    }

    observable<T> get_observable() const {
        auto keepAlive = s;
        return make_observable_dynamic<T>([=](subscriber<T> o){
            keepAlive.add(keepAlive.get_subscriber(), std::move(o));
        });
    }
};

}

}

#endif


text:
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution

import json

class FindPlacesByName(Choreography):

    def __init__(self, temboo_session):
        """
        Create a new instance of the FindPlacesByName Choreo. A TembooSession object, containing a valid
        set of Temboo credentials, must be supplied.
        """
        super(FindPlacesByName, self).__init__(temboo_session, '/Library/Factual/FindPlacesByName')

    def new_input_set(self):
        return FindPlacesByNameInputSet()

    def _make_result_set(self, result, path):
        return FindPlacesByNameResultSet(result, path)

    def _make_execution(self, session, exec_id, path):
        return FindPlacesByNameChoreographyExecution(session, exec_id, path)

class FindPlacesByNameInputSet(InputSet):
    """
    An InputSet with methods appropriate for specifying the inputs to the FindPlacesByName
    Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
    """
    def set_APIKey(self, value):
        """
        Set the value of the APIKey input for this Choreo. ((optional, string) The API Key provided by Factual (AKA the OAuth Consumer Key).)
        """
        super(FindPlacesByNameInputSet, self)._set_input('APIKey', value)
    def set_APISecret(self, value):
        """
        Set the value of the APISecret input for this Choreo. ((optional, string) The API Secret provided by Factual (AKA the OAuth Consumer Secret).)
        """
        super(FindPlacesByNameInputSet, self)._set_input('APISecret', value)
    def set_Query(self, value):
        """
        Set the value of the Query input for this Choreo. ((required, string) A search string (i.e. Starbucks))
        """
        super(FindPlacesByNameInputSet, self)._set_input('Query', value)

class FindPlacesByNameResultSet(ResultSet):
    """
    A ResultSet with methods tailored to the values returned by the FindPlacesByName Choreo.
    The ResultSet object is used to retrieve the results of a Choreo execution.
    """

    def getJSONFromString(self, str):
        return json.loads(str)

    def get_Response(self):
        """
        Retrieve the value for the "Response" output from this Choreo execution. ((json) The response from Factual.)
        """
        return self._output.get('Response', None)

class FindPlacesByNameChoreographyExecution(ChoreographyExecution):

    def _make_result_set(self, response, path):
        return FindPlacesByNameResultSet(response, path)


text:
<!DOCTYPE html>

  <meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Helper for publish_object. Reformat the filName in system metadata. — reformat_file_name • arcticdatautils</title>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha256-bZLfwXAP04zRMK2BjiO8iu9pf4FbLqX6zitd+tIvLhE=" crossorigin="anonymous" />

<link rel="stylesheet" href="../bootstrap-toc.css">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/all.min.css" integrity="sha256-mmgLkCYLUQbXn0B1SRqzHar6dCnv9oZFPEC1g1cwlkk=" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.12.1/css/v4-shims.min.css" integrity="sha256-wZjR52fzng1pJHwx4aV2AO3yyTOXrcDW7jBpJtTwVxw=" crossorigin="anonymous" />

<link href="../pkgdown.css" rel="stylesheet">

<meta property="og:title" content="Helper for publish_object. Reformat the filName in system metadata. — reformat_file_name" />
<meta property="og:description" content="Reformat the fileName field in an object's system metadata to follow Arctic Data Center
system metdata naming conventions.  Publish_object calls this function to rename
the fileName field in system metadata." />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
        Toggle navigation

      </button>

        arcticdatautils
        0.7.0

  Reference

    Articles

      Overview

      Basic Usage

Helper for publish_object. Reformat the filName in system metadata.

    Source: R/editing.R

reformat_file_name.Rd

Reformat the fileName field in an object's system metadata to follow Arctic Data Center
system metdata naming conventions.  Publish_object calls this function to rename
the fileName field in system metadata.

reformat_file_name(path, sysmeta)

Arguments

    <colgroup><col class="name" /><col class="desc" /></colgroup>

      path

(character) full file path

      sysmeta

(S4) A system metadata object

Contents

Developed by Bryce Mecum.

Site built with pkgdown 1.6.1.


text:
"""Support to embed Sonos."""
from __future__ import annotations

import asyncio
from collections import OrderedDict
from dataclasses import dataclass, field
import datetime
from functools import partial
import logging
import socket
from typing import TYPE_CHECKING, Any, Optional, cast
from urllib.parse import urlparse

from soco import events_asyncio
import soco.config as soco_config
from soco.core import SoCo
from soco.exceptions import SoCoException
import voluptuous as vol

from homeassistant import config_entries
from homeassistant.components import ssdp
from homeassistant.components.media_player import DOMAIN as MP_DOMAIN
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_HOSTS, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import CALLBACK_TYPE, Event, HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.dispatcher import async_dispatcher_send, dispatcher_send
from homeassistant.helpers.event import async_track_time_interval, call_later
from homeassistant.helpers.typing import ConfigType

from .alarms import SonosAlarms
from .const import (
    AVAILABILITY_CHECK_INTERVAL,
    DATA_SONOS,
    DATA_SONOS_DISCOVERY_MANAGER,
    DISCOVERY_INTERVAL,
    DOMAIN,
    PLATFORMS,
    SONOS_CHECK_ACTIVITY,
    SONOS_REBOOTED,
    SONOS_SPEAKER_ACTIVITY,
    SONOS_VANISHED,
    UPNP_ST,
)
from .exception import SonosUpdateError
from .favorites import SonosFavorites
from .speaker import SonosSpeaker

_LOGGER = logging.getLogger(__name__)

CONF_ADVERTISE_ADDR = "advertise_addr"
CONF_INTERFACE_ADDR = "interface_addr"
DISCOVERY_IGNORED_MODELS = ["Sonos Boost"]

CONFIG_SCHEMA = vol.Schema(
    {
        DOMAIN: vol.Schema(
            {
                MP_DOMAIN: vol.All(
                    cv.deprecated(CONF_INTERFACE_ADDR),
                    vol.Schema(
                        {
                            vol.Optional(CONF_ADVERTISE_ADDR): cv.string,
                            vol.Optional(CONF_INTERFACE_ADDR): cv.string,
                            vol.Optional(CONF_HOSTS): vol.All(
                                cv.ensure_list_csv, [cv.string]
                            ),
                        }
                    ),
                )
            }
        )
    },
    extra=vol.ALLOW_EXTRA,
)

@dataclass
class UnjoinData:
    """Class to track data necessary for unjoin coalescing."""

    speakers: list[SonosSpeaker]
    event: asyncio.Event = field(default_factory=asyncio.Event)

class SonosData:
    """Storage class for platform global data."""

    def __init__(self) -> None:
        """Initialize the data."""
        # OrderedDict behavior used by SonosAlarms and SonosFavorites
        self.discovered: OrderedDict[str, SonosSpeaker] = OrderedDict()
        self.favorites: dict[str, SonosFavorites] = {}
        self.alarms: dict[str, SonosAlarms] = {}
        self.topology_condition = asyncio.Condition()
        self.hosts_heartbeat: CALLBACK_TYPE | None = None
        self.discovery_known: set[str] = set()
        self.boot_counts: dict[str, int] = {}
        self.mdns_names: dict[str, str] = {}
        self.entity_id_mappings: dict[str, SonosSpeaker] = {}
        self.unjoin_data: dict[str, UnjoinData] = {}

async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
    """Set up the Sonos component."""
    conf = config.get(DOMAIN)

    hass.data[DOMAIN] = conf or {}

    if conf is not None:
        hass.async_create_task(
            hass.config_entries.flow.async_init(
                DOMAIN, context={"source": config_entries.SOURCE_IMPORT}
            )
        )

    return True

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Sonos from a config entry."""
    soco_config.EVENTS_MODULE = events_asyncio
    soco_config.REQUEST_TIMEOUT = 9.5

    if DATA_SONOS not in hass.data:
        hass.data[DATA_SONOS] = SonosData()

    data = hass.data[DATA_SONOS]
    config = hass.data[DOMAIN].get("media_player", {})
    hosts = config.get(CONF_HOSTS, [])
    _LOGGER.debug("Reached async_setup_entry, config=%s", config)

    if advertise_addr := config.get(CONF_ADVERTISE_ADDR):
        soco_config.EVENT_ADVERTISE_IP = advertise_addr

    if deprecated_address := config.get(CONF_INTERFACE_ADDR):
        _LOGGER.warning(
            "'%s' is deprecated, enable %s in the Network integration (https://www.home-assistant.io/integrations/network/)",
            CONF_INTERFACE_ADDR,
            deprecated_address,
        )

    manager = hass.data[DATA_SONOS_DISCOVERY_MANAGER] = SonosDiscoveryManager(
        hass, entry, data, hosts
    )
    await manager.setup_platforms_and_discovery()
    return True

async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Unload a Sonos config entry."""
    unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
    await hass.data[DATA_SONOS_DISCOVERY_MANAGER].async_shutdown()
    hass.data.pop(DATA_SONOS)
    hass.data.pop(DATA_SONOS_DISCOVERY_MANAGER)
    return unload_ok

class SonosDiscoveryManager:
    """Manage sonos discovery."""

    def __init__(
        self, hass: HomeAssistant, entry: ConfigEntry, data: SonosData, hosts: list[str]
    ) -> None:
        """Init discovery manager."""
        self.hass = hass
        self.entry = entry
        self.data = data
        self.hosts = set(hosts)
        self.discovery_lock = asyncio.Lock()
        self._known_invisible: set[SoCo] = set()
        self._manual_config_required = bool(hosts)

    async def async_shutdown(self) -> None:
        """Stop all running tasks."""
        await self._async_stop_event_listener()
        self._stop_manual_heartbeat()

    def is_device_invisible(self, ip_address: str) -> bool:
        """Check if device at provided IP is known to be invisible."""
        return any(x for x in self._known_invisible if x.ip_address == ip_address)

    def _create_visible_speakers(self, ip_address: str) -> None:
        """Create all visible SonosSpeaker instances with the provided seed IP."""
        try:
            soco = SoCo(ip_address)
            visible_zones = soco.visible_zones
            self._known_invisible = soco.all_zones - visible_zones
        except (OSError, SoCoException) as ex:
            _LOGGER.warning(
                "Failed to request visible zones from %s: %s", ip_address, ex
            )
            return

        for zone in visible_zones:
            if zone.uid not in self.data.discovered:
                self._add_speaker(zone)

    async def _async_stop_event_listener(self, event: Event | None = None) -> None:
        for speaker in self.data.discovered.values():
            speaker.activity_stats.log_report()
            speaker.event_stats.log_report()
        if zgs := next(
            (
                speaker.soco.zone_group_state
                for speaker in self.data.discovered.values()
            ),
            None,
        ):
            _LOGGER.debug(
                "ZoneGroupState stats: (%s/%s) processed",
                zgs.processed_count,
                zgs.total_requests,
            )
        await asyncio.gather(
            *(speaker.async_offline() for speaker in self.data.discovered.values())
        )
        if events_asyncio.event_listener:
            await events_asyncio.event_listener.async_stop()

    def _stop_manual_heartbeat(self, event: Event | None = None) -> None:
        if self.data.hosts_heartbeat:
            self.data.hosts_heartbeat()
            self.data.hosts_heartbeat = None

    def _add_speaker(self, soco: SoCo) -> None:
        """Create and set up a new SonosSpeaker instance."""
        try:
            speaker_info = soco.get_speaker_info(True, timeout=7)
            if soco.uid not in self.data.boot_counts:
                self.data.boot_counts[soco.uid] = soco.boot_seqnum
            _LOGGER.debug("Adding new speaker: %s", speaker_info)
            speaker = SonosSpeaker(self.hass, soco, speaker_info)
            self.data.discovered[soco.uid] = speaker
            for coordinator, coord_dict in (
                (SonosAlarms, self.data.alarms),
                (SonosFavorites, self.data.favorites),
            ):
                if TYPE_CHECKING:
                    coord_dict = cast(dict[str, Any], coord_dict)
                if soco.household_id not in coord_dict:
                    new_coordinator = coordinator(self.hass, soco.household_id)
                    new_coordinator.setup(soco)
                    coord_dict[soco.household_id] = new_coordinator
            speaker.setup(self.entry)
        except (OSError, SoCoException):
            _LOGGER.warning("Failed to add SonosSpeaker using %s", soco, exc_info=True)

    def _poll_manual_hosts(self, now: datetime.datetime | None = None) -> None:
        """Add and maintain Sonos devices from a manual configuration."""
        for host in self.hosts:
            ip_addr = socket.gethostbyname(host)
            soco = SoCo(ip_addr)
            try:
                visible_zones = soco.visible_zones
            except OSError:
                _LOGGER.warning("Could not get visible Sonos devices from %s", ip_addr)
            else:
                if new_hosts := {
                    x.ip_address
                    for x in visible_zones
                    if x.ip_address not in self.hosts
                }:
                    _LOGGER.debug("Adding to manual hosts: %s", new_hosts)
                    self.hosts.update(new_hosts)
                dispatcher_send(
                    self.hass,
                    f"{SONOS_SPEAKER_ACTIVITY}-{soco.uid}",
                    "manual zone scan",
                )
                break

        for host in self.hosts.copy():
            ip_addr = socket.gethostbyname(host)
            if self.is_device_invisible(ip_addr):
                _LOGGER.debug("Discarding %s from manual hosts", ip_addr)
                self.hosts.discard(ip_addr)
                continue

            known_speaker = next(
                (
                    speaker
                    for speaker in self.data.discovered.values()
                    if speaker.soco.ip_address == ip_addr
                ),
                None,
            )
            if not known_speaker:
                self._create_visible_speakers(ip_addr)
            elif not known_speaker.available:
                try:
                    known_speaker.ping()
                except SonosUpdateError:
                    _LOGGER.debug(
                        "Manual poll to %s failed, keeping unavailable", ip_addr
                    )

        self.data.hosts_heartbeat = call_later(
            self.hass, DISCOVERY_INTERVAL.total_seconds(), self._poll_manual_hosts
        )

    async def _async_handle_discovery_message(
        self, uid: str, discovered_ip: str, boot_seqnum: int | None
    ) -> None:
        """Handle discovered player creation and activity."""
        async with self.discovery_lock:
            if not self.data.discovered:
                # Initial discovery, attempt to add all visible zones
                await self.hass.async_add_executor_job(
                    self._create_visible_speakers,
                    discovered_ip,
                )
            elif uid not in self.data.discovered:
                if self.is_device_invisible(discovered_ip):
                    return
                await self.hass.async_add_executor_job(
                    self._add_speaker, SoCo(discovered_ip)
                )
            elif boot_seqnum and boot_seqnum > self.data.boot_counts[uid]:
                self.data.boot_counts[uid] = boot_seqnum
                async_dispatcher_send(self.hass, f"{SONOS_REBOOTED}-{uid}")
            else:
                async_dispatcher_send(
                    self.hass, f"{SONOS_SPEAKER_ACTIVITY}-{uid}", "discovery"
                )

    async def _async_ssdp_discovered_player(
        self, info: ssdp.SsdpServiceInfo, change: ssdp.SsdpChange
    ) -> None:
        uid = info.upnp[ssdp.ATTR_UPNP_UDN]
        if not uid.startswith("uuid:RINCON_"):
            return
        uid = uid[5:]

        if change == ssdp.SsdpChange.BYEBYE:
            _LOGGER.debug(
                "ssdp:byebye received from %s", info.upnp.get("friendlyName", uid)
            )
            reason = info.ssdp_headers.get("X-RINCON-REASON", "ssdp:byebye")
            async_dispatcher_send(self.hass, f"{SONOS_VANISHED}-{uid}", reason)
            return

        self.async_discovered_player(
            "SSDP",
            info,
            cast(str, urlparse(info.ssdp_location).hostname),
            uid,
            info.ssdp_headers.get("X-RINCON-BOOTSEQ"),
            cast(str, info.upnp.get(ssdp.ATTR_UPNP_MODEL_NAME)),
            None,
        )

    @callback
    def async_discovered_player(
        self,
        source: str,
        info: ssdp.SsdpServiceInfo,
        discovered_ip: str,
        uid: str,
        boot_seqnum: str | int | None,
        model: str,
        mdns_name: str | None,
    ) -> None:
        """Handle discovery via ssdp or zeroconf."""
        if self._manual_config_required:
            _LOGGER.warning(
                "Automatic discovery is working, Sonos hosts in configuration.yaml are not needed"
            )
            self._manual_config_required = False
        if model in DISCOVERY_IGNORED_MODELS:
            _LOGGER.debug("Ignoring device: %s", info)
            return
        if self.is_device_invisible(discovered_ip):
            return

        if boot_seqnum:
            boot_seqnum = int(boot_seqnum)
            self.data.boot_counts.setdefault(uid, boot_seqnum)
        if mdns_name:
            self.data.mdns_names[uid] = mdns_name

        if uid not in self.data.discovery_known:
            _LOGGER.debug("New %s discovery uid=%s: %s", source, uid, info)
            self.data.discovery_known.add(uid)
        asyncio.create_task(
            self._async_handle_discovery_message(
                uid, discovered_ip, cast(Optional[int], boot_seqnum)
            )
        )

    async def setup_platforms_and_discovery(self) -> None:
        """Set up platforms and discovery."""
        await self.hass.config_entries.async_forward_entry_setups(self.entry, PLATFORMS)
        self.entry.async_on_unload(
            self.hass.bus.async_listen_once(
                EVENT_HOMEASSISTANT_STOP, self._async_stop_event_listener
            )
        )
        _LOGGER.debug("Adding discovery job")
        if self.hosts:
            self.entry.async_on_unload(
                self.hass.bus.async_listen_once(
                    EVENT_HOMEASSISTANT_STOP, self._stop_manual_heartbeat
                )
            )
            await self.hass.async_add_executor_job(self._poll_manual_hosts)

        self.entry.async_on_unload(
            await ssdp.async_register_callback(
                self.hass, self._async_ssdp_discovered_player, {"st": UPNP_ST}
            )
        )

        self.entry.async_on_unload(
            async_track_time_interval(
                self.hass,
                partial(
                    async_dispatcher_send,
                    self.hass,
                    SONOS_CHECK_ACTIVITY,
                ),
                AVAILABILITY_CHECK_INTERVAL,
            )
        )

async def async_remove_config_entry_device(
    hass: HomeAssistant, config_entry: ConfigEntry, device_entry: dr.DeviceEntry
) -> bool:
    """Remove Sonos config entry from a device."""
    known_devices = hass.data[DATA_SONOS].discovered.keys()
    for identifier in device_entry.identifiers:
        if identifier[0] != DOMAIN:
            continue
        uid = identifier[1]
        if uid not in known_devices:
            return True
    return False


text:
require 'spec_helper'

describe RubyLint::FileList do
  before :all do
    @list = RubyLint::FileList.new
  end

  example 'list a set of files' do
    path = fixture_path('valid.rb')

    @list.process([path]).should == [path]
  end

  example 'list a set of directories' do
    @list.process([fixture_path('deeply')]).should == [
      fixture_path('deeply/nested/file.rb')
    ]
  end

  example 'raise for non existing files' do
    block = lambda { @list.process(['yeah-right']) }

    block.should raise_error(Errno::ENOENT)
  end
end


text:
package com.laytonsmith.core.constructs;

import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.core.FullyQualifiedClassName;
import com.laytonsmith.core.natives.interfaces.Mixed;
import com.laytonsmith.core.objects.ObjectModifier;
import com.laytonsmith.core.objects.ObjectType;
import com.laytonsmith.testing.StaticTest;

import static org.junit.Assert.fail;

import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
import org.junit.Before;
import org.junit.Test;

/**
 *
 * @author cailin
 */
public class ClassInfoTest {

	@Before
	public void before() {
		StaticTest.InstallFakeServerFrontend();
	}

	@Test
	public void testAllInterfacesReturnNothingForGetInterfaces() throws Exception {
		List<String> failures = new ArrayList<>();
		for(FullyQualifiedClassName t : NativeTypeList.getNativeTypeList()) {
			Mixed m = NativeTypeList.getInvalidInstanceForUse(t);
			if(m.getObjectType() == ObjectType.INTERFACE) {
				try {
					if(m.getInterfaces() != null && m.getInterfaces().length > 0) {
						failures.add(m.getClass().getName() + " is an interface, but getInterfaces() has returned a non-zero list");
					}
				} catch (UnsupportedOperationException ex) {
					failures.add(m.getClass().getName() + " cannot throw an exception for getInterfaces()");
				}
			}
		}
		if(!failures.isEmpty()) {
			fail("One or more failures has occured:\n" + StringUtils.Join(failures, "\n"));
		}
	}

	@Test
	public void testOnlyContainedClassesHaveVariousModifiers() throws Exception {
		List<String> failures = new ArrayList<>();
		Set<ObjectModifier> allowed = EnumSet.of(ObjectModifier.FINAL, ObjectModifier.ABSTRACT);
		for(FullyQualifiedClassName t : NativeTypeList.getNativeTypeList()) {
			Mixed m = NativeTypeList.getInvalidInstanceForUse(t);
			if(m.getContainingClass() == null) {
				for(ObjectModifier i : m.getObjectModifiers()) {
					if(!allowed.contains(i)) {
						failures.add(m.getClass().getName() + " contains an illegal modifier (" + i + "), because it is an outer"
								+ " class, but the only allowed modifiers are: " + allowed.toString());
					}
				}
			}
		}
		if(!failures.isEmpty()) {
			fail("One or more failures has occured:\n" + StringUtils.Join(failures, "\n"));
		}
	}

	@Test
	public void testAllTypeofClassesDoNotThrowUnsupportedOperationException() throws Exception {
		List<String> failures = new ArrayList<>();
		for(FullyQualifiedClassName fqcn : NativeTypeList.getNativeTypeList()) {
			if(CVoid.TYPE.getFQCN().equals(fqcn) || CNull.TYPE.getFQCN().equals(fqcn)) {
				continue;
			}
			Mixed m = NativeTypeList.getInvalidInstanceForUse(fqcn);
			try {
				m.getSuperclasses();
			} catch (UnsupportedOperationException e) {
				failures.add("getSuperclasses in " + m.getClass() + " throws an UnsupportedOperationException. This"
						+ " is only allowed in phantom classes.");
			}
			try {
				m.getInterfaces();
			} catch (UnsupportedOperationException e) {
				failures.add("getInterfaces in " + m.getClass() + " throws an UnsupportedOperationException. This"
						+ " is only allowed in phantom classes.");
			}
		}

		if(!failures.isEmpty()) {
			fail("One or more failures has occured:\n" + StringUtils.Join(failures, "\n"));
		}
	}
}


text:
import * as React from 'react';
import { SimpleInput } from '../SimpleInput';
import { ButtonsOrientation, ConfirmAdder } from '../Confirm/ConfirmAdder';

interface ConfirmStringAdderProps {
  label?: string;
  validator?: (input?: string) => string | undefined;
  forceInputValue?: boolean;
  onAccept: (value?: string) => void;
  placeholder?: string;
  orientation?: ButtonsOrientation;
}

export function ConfirmStringAdder({
  label,
  validator,
  forceInputValue,
  onAccept,
  placeholder,
  orientation,
}: ConfirmStringAdderProps) {
  return (
    <ConfirmAdder
      label={label}
      validator={validator}
      accept={value =>
        forceInputValue &&
        (value == null || (typeof value === 'string' && value === ''))
          ? 'You have to enter a value'
          : undefined
      }
      onAccept={onAccept}
      orientation={orientation}
    >
      {onNewValue => (
        <SimpleInput
          placeholder={placeholder}
          onChange={v => onNewValue(() => String(v))}
        />
      )}
    </ConfirmAdder>
  );
}


text:
//===--- CSStep.h - Constraint Solver Steps -------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the \c SolverStep class and its related types,
// which is used by constraint solver to do iterative solving.
//
//===----------------------------------------------------------------------===//

#ifndef SWIFT_SEMA_CSSTEP_H
#define SWIFT_SEMA_CSSTEP_H

#include "Constraint.h"
#include "ConstraintSystem.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>

using namespace llvm;

namespace swift {
namespace constraints {

class SolverStep;
class ComponentStep;

/// Represents available states which every
/// given step could be in during it's lifetime.
enum class StepState { Setup, Ready, Running, Suspended, Done };

/// Represents result of the step execution,
/// and can only be constructed by `SolverStep`.
struct StepResult {
  using Kind = ConstraintSystem::SolutionKind;

  friend class SolverStep;

private:
  Kind ResultKind;
  SmallVector<std::unique_ptr<SolverStep>, 4> NextSteps;

  StepResult(Kind kind) : ResultKind(kind) {}

  StepResult(Kind kind, std::unique_ptr<SolverStep> step) : ResultKind(kind) {
    NextSteps.push_back(std::move(step));
  }

  StepResult(Kind kind, SmallVectorImpl<std::unique_ptr<SolverStep>> &followup)
      : ResultKind(kind), NextSteps(std::move(followup)) {}

public:
  StepResult() = delete;

  Kind getKind() const { return ResultKind; }

  void transfer(SmallVectorImpl<std::unique_ptr<SolverStep>> &workList) {
    workList.reserve(NextSteps.size());
    for (auto &step : NextSteps)
      workList.push_back(std::move(step));
  }

private:
  static StepResult success() { return StepResult(Kind::Solved); }
  static StepResult failure() { return StepResult(Kind::Error); }

  static StepResult unsolved(std::unique_ptr<SolverStep> singleStep) {
    return StepResult(Kind::Unsolved, std::move(singleStep));
  }

  static StepResult
  unsolved(SmallVectorImpl<std::unique_ptr<SolverStep>> &followup) {
    return StepResult(Kind::Unsolved, followup);
  }
};

/// Represents a single independently solvable part of
/// the constraint system. And is a base class for all
/// different types of steps there are.
class SolverStep {
  friend class ConstraintSystem;

protected:
  ConstraintSystem &CS;

  StepState State = StepState::Setup;

  /// Once step is complete this is a container to hold finalized solutions.
  SmallVectorImpl<Solution> &Solutions;

public:
  explicit SolverStep(ConstraintSystem &cs,
                      SmallVectorImpl<Solution> &solutions)
      : CS(cs), Solutions(solutions) {}

  virtual ~SolverStep() {}

  /// \returns The current state of this step.
  StepState getState() const { return State; }

  /// Run preliminary setup (if needed) right
  /// before taking this step for the first time.
  virtual void setup() {}

  /// Try to move solver forward by simplifying constraints if possible.
  /// Such simplication might lead to either producing a solution, or
  /// creating a set of "follow-up" more granular steps to execute.
  ///
  /// \param prevFailed Indicate whether previous step
  ///        has failed (returned StepResult::Kind = Error),
  ///        this is useful to propagate failures when
  ///        unsolved steps are re-taken.
  ///
  /// \returns status and any follow-up steps to take before considering
  ///          this step solved or failed.
  virtual StepResult take(bool prevFailed) = 0;

  /// Try to resume previously suspended step.
  ///
  /// This happens after "follow-up" steps are done
  /// and all of the required information should be
  /// available to re-take this step.
  ///
  /// \param prevFailed Indicate whether previous step
  ///        has failed (returned StepResult::Kind = Error),
  ///        this is useful to propagate failures when
  ///        unsolved steps are re-taken.
  ///
  /// \returns status and any follow-up steps to take before considering
  ///          this step solved or failed.
  virtual StepResult resume(bool prevFailed) = 0;

  virtual void print(llvm::raw_ostream &Out) = 0;

protected:
  /// Transition this step into one of the available states.
  ///
  /// This is primarily driven by execution of the step itself and
  /// the solver, while it executes the work list.
  ///
  /// \param newState The new state this step should be in.
  void transitionTo(StepState newState) {
#ifndef NDEBUG
    // Make sure that ordering of the state transitions is correct,
    // because `setup -> ready -> running [-> suspended]* -> done`
    // is the only reasonable state transition path.
    switch (State) {
    case StepState::Setup:
      assert(newState == StepState::Ready);
      break;

    case StepState::Ready:
      assert(newState == StepState::Running);
      break;

    case StepState::Running:
      assert(newState == StepState::Suspended || newState == StepState::Done);
      break;

    case StepState::Suspended:
      assert(newState == StepState::Running);
      break;

    case StepState::Done:
      llvm_unreachable("step is already done.");
    }
#endif

    State = newState;
  }

  StepResult done(bool isSuccess) {
    transitionTo(StepState::Done);
    return isSuccess ? StepResult::success() : StepResult::failure();
  }

  StepResult replaceWith(std::unique_ptr<SolverStep> replacement) {
    transitionTo(StepState::Done);
    return StepResult(StepResult::Kind::Solved, std::move(replacement));
  }

  StepResult suspend(std::unique_ptr<SolverStep> followup) {
    transitionTo(StepState::Suspended);
    return StepResult::unsolved(std::move(followup));
  }

  StepResult suspend(SmallVectorImpl<std::unique_ptr<SolverStep>> &followup) {
    transitionTo(StepState::Suspended);
    return StepResult::unsolved(followup);
  }

  /// Erase constraint from the constraint system (include constraint graph)
  /// and return the constraint which follows it.
  ConstraintList::iterator erase(Constraint *constraint) {
    CS.CG.removeConstraint(constraint);
    return CS.InactiveConstraints.erase(constraint);
  }

  void restore(ConstraintList::iterator &iterator, Constraint *constraint) {
    CS.InactiveConstraints.insert(iterator, constraint);
    CS.CG.addConstraint(constraint);
  }

  ResolvedOverloadSetListItem *getResolvedOverloads() const {
    return CS.resolvedOverloadSets;
  }

  void recordDisjunctionChoice(ConstraintLocator *disjunctionLocator,
                               unsigned index) const {
    CS.recordDisjunctionChoice(disjunctionLocator, index);
  }

  Score getCurrentScore() const { return CS.CurrentScore; }

  Optional<Score> getBestScore() const { return CS.solverState->BestScore; }

  void filterSolutions(SmallVectorImpl<Solution> &solutions, bool minimize) {
    if (!CS.retainAllSolutions())
      CS.filterSolutions(solutions, minimize);
  }

  /// Check whether constraint solver is running in "debug" mode,
  /// which should output diagnostic information.
  bool isDebugMode() const { return CS.TC.getLangOpts().DebugConstraintSolver; }

  llvm::raw_ostream &getDebugLogger(bool indent = true) const {
    auto &log = CS.getASTContext().TypeCheckerDebug->getStream();
    return indent ? log.indent(CS.solverState->depth * 2) : log;
  }
};

/// `SplitterStep` is responsible for running connected components
/// algorithm to determine how many independent sub-systems there are.
/// Once that's done it would create one `ComponentStep` per such
/// sub-system, and move to try to solve each and then merge partial
/// solutions produced by components into complete solution(s).
class SplitterStep final : public SolverStep {
  // Set of constraints associated with each component, after
  // component steps are complete, all of the constraints are
  // returned back to the work-list in their original order.
  SmallVector<ConstraintList, 4> Components;
  // Partial solutions associated with given step, each element
  // of the array presents a disjoint component (or follow-up step)
  // that current step has been split into.
  std::unique_ptr<SmallVector<Solution, 4>[]> PartialSolutions = nullptr;

  SmallVector<Constraint *, 4> OrphanedConstraints;

public:
  SplitterStep(ConstraintSystem &cs, SmallVectorImpl<Solution> &solutions)
      : SolverStep(cs, solutions) {}

  StepResult take(bool prevFailed) override;
  StepResult resume(bool prevFailed) override;

  void print(llvm::raw_ostream &Out) override {
    Out << "SplitterStep with #" << Components.size() << " components\n";
  }

private:
  /// If current step needs follow-up steps to get completely solved,
  /// let's compute them using connected components algorithm.
  void computeFollowupSteps(
      SmallVectorImpl<std::unique_ptr<ComponentStep>> &componentSteps);

  /// Once all of the follow-up steps are complete, let's try
  /// to merge resulting solutions together, to form final solution(s)
  /// for this step.
  ///
  /// \returns true if there are any solutions, false otherwise.
  bool mergePartialSolutions() const;
};

/// `ComponentStep` represents a set of type variables and related
/// constraints which could be solved independently. It's further
/// simplified into "binding" steps which attempt type variable and
/// disjunction choices.
class ComponentStep final : public SolverStep {
  class Scope {
    ConstraintSystem &CS;
    ConstraintSystem::SolverScope *SolverScope;

    std::vector<TypeVariableType *> TypeVars;
    ConstraintSystem::SolverScope *PrevPartialScope = nullptr;

    // The component this scope is associated with.
    ComponentStep &Component;

  public:
    Scope(ComponentStep &component);

    ~Scope() {
      delete SolverScope; // rewind back all of the changes.
      CS.solverState->PartialSolutionScope = PrevPartialScope;

      // return all of the saved type variables back to the system.
      CS.TypeVariables = std::move(TypeVars);
      // return all of the saved constraints back to the component.
      auto &constraints = *Component.Constraints;
      constraints.splice(constraints.end(), CS.InactiveConstraints);
    }
  };

  /// The position of the component in the set of
  /// components produced by "split" step.
  unsigned Index;

  /// Indicates whether this is only component produced
  /// by "split" step. This information opens optimization
  /// opportunity, because if there are no other components,
  /// constraint system doesn't have to pruned from
  /// unrelated type variables and their constraints.
  bool IsSingle;

  /// The score associated with constraint system before
  /// the component step is taken.
  Score OriginalScore;

  /// The original best score computed before any of the
  /// component steps belonging to the same "split" are taken.
  Optional<Score> OriginalBestScore;

  /// If this step depends on other smaller steps to be solved first
  /// we need to keep active scope until all of the work is done.
  std::unique_ptr<Scope> ComponentScope = nullptr;

  /// Type variables and constraints "in scope" of this step.
  std::vector<TypeVariableType *> TypeVars;
  /// Constraints "in scope" of this step.
  ConstraintList *Constraints;

  /// Number of disjunction constraints associated with this step,
  /// used to aid in ordering of the components.
  unsigned NumDisjunctions = 0;

  /// Constraint which doesn't have any free type variables associated
  /// with it, which makes it disconnected in the graph.
  Constraint *OrphanedConstraint = nullptr;

public:
  ComponentStep(ConstraintSystem &cs, unsigned index, bool single,
                ConstraintList *constraints,
                SmallVectorImpl<Solution> &solutions)
      : SolverStep(cs, solutions), Index(index), IsSingle(single),
        OriginalScore(getCurrentScore()), OriginalBestScore(getBestScore()),
        Constraints(constraints) {}

  /// Record a type variable as associated with this step.
  void record(TypeVariableType *typeVar) { TypeVars.push_back(typeVar); }

  /// Record a constraint as associated with this step.
  void record(Constraint *constraint) {
    Constraints->push_back(constraint);
    if (constraint->getKind() == ConstraintKind::Disjunction)
      ++NumDisjunctions;
  }

  /// Record a constraint as associated with this step but which doesn't
  /// have any free type variables associated with it.
  void recordOrphan(Constraint *constraint) {
    assert(!OrphanedConstraint);
    OrphanedConstraint = constraint;
  }

  StepResult take(bool prevFailed) override;
  StepResult resume(bool prevFailed) override;

  // The number of disjunction constraints associated with this component.
  unsigned disjunctionCount() const { return NumDisjunctions; }

  void print(llvm::raw_ostream &Out) override {
    Out << "ComponentStep with at #" << Index << '\n';
  }

private:
  void setupScope() {
    // If this is a single component, there is no need
    // to preliminary modify constraint system or log anything.
    if (IsSingle)
      return;

    if (isDebugMode())
      getDebugLogger() << "(solving component #" << Index << '\n';

    ComponentScope = llvm::make_unique<Scope>(*this);
    // If this component has oprhaned constraint attached,
    // let's return it to the graph.
    CS.CG.setOrphanedConstraint(OrphanedConstraint);
  }
};

template <typename P> class BindingStep : public SolverStep {
  using Scope = ConstraintSystem::SolverScope;

  P Producer;

protected:
  /// Indicates whether any of the attempted bindings
  /// produced a solution.
  bool AnySolved = false;

  /// Active binding (scope + choice) which is currently
  /// being attempted, helps to rewind state of the
  /// constraint system back to original before attempting
  /// next binding, if any.
  Optional<std::pair<std::unique_ptr<Scope>, typename P::Element>> ActiveChoice;

  BindingStep(ConstraintSystem &cs, P producer,
              SmallVectorImpl<Solution> &solutions)
      : SolverStep(cs, solutions), Producer(std::move(producer)) {}

public:
  StepResult take(bool prevFailed) override {
    while (auto choice = Producer()) {
      if (shouldSkip(*choice))
        continue;

      if (shouldStopAt(*choice))
        break;

      if (isDebugMode()) {
        auto &log = getDebugLogger();
        log << "(attempting ";
        choice->print(log, &CS.getASTContext().SourceMgr);
        log << '\n';
      }

      {
        auto scope = llvm::make_unique<Scope>(CS);
        if (attempt(*choice)) {
          ActiveChoice.emplace(std::move(scope), *choice);
          return suspend(llvm::make_unique<SplitterStep>(CS, Solutions));
        }
      }

      if (isDebugMode())
        getDebugLogger() << ")\n";

      // If this binding didn't match, let's check if we've attempted
      // enough bindings to stop, because some producers might need
      // to compute next step of bindings to try, which we'd want to avoid.
      if (shouldStopAfter(*choice))
        break;
    }

    return done(/*isSuccess=*/AnySolved);
  }

protected:
  /// Attempt to apply given binding choice to constraint system.
  /// This action is going to establish "active choice" of this step
  /// to point to a given choice.
  ///
  /// \param choice The choice to attempt.
  ///
  /// \return true if the choice has been accepted and system can be
  /// simplified further, false otherwise.
  virtual bool attempt(const typename P::Element &choice) = 0;

  /// Check whether attempting this choice could be avoided,
  /// which could speed-up solving.
  virtual bool shouldSkip(const typename P::Element &choice) const = 0;

  /// Check whether attempting binding choices should be stopped,
  /// because optimal solution has already been found.
  virtual bool shouldStopAt(const typename P::Element &choice) const = 0;

  /// Check whether attempting binding choices should be stopped,
  /// after current choice has been attempted, because optimal
  /// solution has already been found,
  virtual bool shouldStopAfter(const typename P::Element &choice) const {
    return false;
  }

  bool needsToComputeNext() const { return Producer.needsToComputeNext(); }

  ConstraintLocator *getLocator() const { return Producer.getLocator(); }
};

class TypeVariableStep final : public BindingStep<TypeVarBindingProducer> {
  using BindingContainer = ConstraintSystem::PotentialBindings;
  using Binding = ConstraintSystem::PotentialBinding;

  TypeVariableType *TypeVar;
  // A set of the initial bindings to consider, which is
  // also a source of follow-up "computed" bindings such
  // as supertypes, defaults etc.
  SmallVector<Binding, 4> InitialBindings;

  /// Indicates whether source of one of the previously
  /// attempted bindings was a literal constraint. This
  /// is useful for a performance optimization to stop
  /// attempting other bindings in certain conditions.
  bool SawFirstLiteralConstraint = false;

public:
  TypeVariableStep(ConstraintSystem &cs, BindingContainer &bindings,
                   SmallVectorImpl<Solution> &solutions)
      : BindingStep(cs, {cs, bindings}, solutions), TypeVar(bindings.TypeVar),
        InitialBindings(bindings.Bindings.begin(), bindings.Bindings.end()) {}

  void setup() override;

  StepResult resume(bool prevFailed) override;

  void print(llvm::raw_ostream &Out) override {
    Out << "TypeVariableStep for " << TypeVar->getString() << " with #"
        << InitialBindings.size() << " initial bindings\n";
  }

protected:
  bool attempt(const TypeVariableBinding &choice) override;

  bool shouldSkip(const TypeVariableBinding &choice) const override {
    // If this is a defaultable binding and we have found solutions,
    // don't explore the default binding.
    return AnySolved && choice.isDefaultable();
  }

  /// Check whether attempting type variable binding choices should
  /// be stopped, because optimal solution has already been found.
  bool shouldStopAt(const TypeVariableBinding &choice) const override {
    // If we were able to solve this without considering
    // default literals, don't bother looking at default literals.
    return AnySolved && choice.hasDefaultedProtocol() &&
           !SawFirstLiteralConstraint;
  }

  bool shouldStopAfter(const TypeVariableBinding &choice) const override {
    // If there has been at least one solution so far
    // at a current batch of bindings is done it's a
    // success because each new batch would be less
    // and less precise.
    return AnySolved && needsToComputeNext();
  }
};

class DisjunctionStep final : public BindingStep<DisjunctionChoiceProducer> {
  Constraint *Disjunction;
  SmallVector<Constraint *, 4> DisabledChoices;
  ConstraintList::iterator AfterDisjunction;

  Optional<Score> BestNonGenericScore;
  Optional<std::pair<Constraint *, Score>> LastSolvedChoice;

public:
  DisjunctionStep(ConstraintSystem &cs, Constraint *disjunction,
                  SmallVectorImpl<Solution> &solutions)
      : BindingStep(cs, {cs, disjunction}, solutions), Disjunction(disjunction),
        AfterDisjunction(erase(disjunction)) {
    assert(Disjunction->getKind() == ConstraintKind::Disjunction);
    pruneOverloadSet(Disjunction);
    ++cs.solverState->NumDisjunctions;
  }

  ~DisjunctionStep() override {
    // Rewind back any changes left after attempting last choice.
    ActiveChoice.reset();
    // Return disjunction constraint back to the system.
    restore(AfterDisjunction, Disjunction);
    // Re-enable previously disabled overload choices.
    for (auto *choice : DisabledChoices)
      choice->setEnabled();
  }

  StepResult resume(bool prevFailed) override;

  void print(llvm::raw_ostream &Out) override {
    Out << "DisjunctionStep for ";
    Disjunction->print(Out, &CS.getASTContext().SourceMgr);
    Out << '\n';
  }

private:
  bool shouldSkip(const DisjunctionChoice &choice) const override;

  /// Whether we should short-circuit a disjunction that already has a
  /// solution when we encounter the given choice.
  ///
  /// FIXME: This is performance hack, which should go away.
  ///
  /// \params choice The disjunction choice we are about to attempt.
  ///
  /// \returns true if disjunction step should be considered complete,
  ///          false otherwise.
  bool shouldStopAt(const DisjunctionChoice &choice) const override;
  bool shortCircuitDisjunctionAt(Constraint *currentChoice,
                                 Constraint *lastSuccessfulChoice) const;

  /// Attempt to apply given disjunction choice to constraint system.
  /// This action is going to establish "active choice" of this disjunction
  /// to point to a given choice.
  ///
  /// \param choice The choice to attempt.
  ///
  /// \return true if the choice has been accepted and system can be
  /// simplified further, false otherwise.
  bool attempt(const DisjunctionChoice &choice) override;

  // Check if selected disjunction has a representative
  // this might happen when there are multiple binary operators
  // chained together. If so, disable choices which differ
  // from currently selected representative.
  void pruneOverloadSet(Constraint *disjunction) {
    auto *choice = disjunction->getNestedConstraints().front();
    auto *typeVar = choice->getFirstType()->getAs<TypeVariableType>();
    if (!typeVar)
      return;

    auto *repr = typeVar->getImpl().getRepresentative(nullptr);
    if (!repr || repr == typeVar)
      return;

    for (auto *resolved = getResolvedOverloads(); resolved;
         resolved = resolved->Previous) {
      if (!resolved->BoundType->isEqual(repr))
        continue;

      auto &representative = resolved->Choice;
      if (!representative.isDecl())
        return;

      // Disable all of the overload choices which are different from
      // the one which is currently picked for representative.
      for (auto *constraint : disjunction->getNestedConstraints()) {
        auto choice = constraint->getOverloadChoice();
        if (!choice.isDecl() || choice.getDecl() == representative.getDecl())
          continue;

        constraint->setDisabled();
        DisabledChoices.push_back(constraint);
      }
      break;
    }
  };

  // Figure out which of the solutions has the smallest score.
  static Optional<Score> getBestScore(SmallVectorImpl<Solution> &solutions) {
    assert(!solutions.empty());
    Score bestScore = solutions.front().getFixedScore();
    if (solutions.size() == 1)
      return bestScore;

    for (unsigned i = 1, n = solutions.size(); i != n; ++i) {
      auto &score = solutions[i].getFixedScore();
      if (score < bestScore)
        bestScore = score;
    }
    return bestScore;
  }
};

} // end namespace constraints
} // end namespace swift

#endif // SWIFT_SEMA_CSSTEP_H


text:
package cn.iam007.app.mall.base;

import org.apache.log4j.Logger;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import cn.iam007.app.common.config.AppConstants;
import cn.iam007.app.common.utils.logging.LogUtil;
import cn.iam007.app.mall.R;
import cn.iam007.app.mall.widget.WaitingProgressDialog;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuItem.OnMenuItemClickListener;
import com.baidu.mobstat.StatService;

public abstract class BaseActivity extends SherlockFragmentActivity {
    protected final static String TAG = "activity";

    protected Dialog mWaitingDialog = null;

    private GestureDetector mGestureDetector;

    /**
     * 显示等待的dialog
     */
    protected void showWaitingDialog() {
        final Context context = this;
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                mWaitingDialog = new WaitingProgressDialog(context);
                mWaitingDialog.setCanceledOnTouchOutside(false);
                mWaitingDialog.show();
            }
        });
    }

    /**
     * 销毁等待的dialog
     */
    protected void dismissWaitingDialog() {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                try {
                    if (mWaitingDialog != null) {
                        mWaitingDialog.dismiss();
                    }
                } catch (Exception e) {
                }
            }
        });

    }

    /**
     * 不显示搜索view
     */
    protected final static int FLAG_SEARCH_VIEW = 0x01;
    protected final static int FLAG_DISABLE_HOME_AS_UP = 0x02;

    protected int getFlag() {
        return 0;
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        if ((getFlag() & FLAG_DISABLE_HOME_AS_UP) != FLAG_DISABLE_HOME_AS_UP) {
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
        }

        //GestureDetector
        mGestureDetector = new GestureDetector(this,
                new GestureDetector.SimpleOnGestureListener() {
                    @Override
                    public boolean onFling(MotionEvent e1, MotionEvent e2,
                            float velocityX, float velocityY) {
                        if (mGestureDetectorState) {
                            float absVelocityX = Math.abs(velocityX);
                            float absVelocityY = Math.abs(velocityY);
                            if (absVelocityX >= absVelocityY) {
                                // 横向滑动
                                if (absVelocityX > 150) {
                                    if (velocityX > 0) {
                                        onFlingRight();
                                    } else {
                                        onFlingLeft();
                                    }
                                }
                            } else {
                                // 竖形滑动
                                if (absVelocityY > 150) {
                                    if (velocityY > 0) {
                                        onFlingBottom();
                                    } else {
                                        onFlingTop();
                                    }
                                }
                            }
                        }

                        return false;
                    }
                });
    }

    /**
     * 手势向上滑动
     */
    protected void onFlingTop() {
    }

    /**
     * 手势向下滑动
     */
    protected void onFlingBottom() {
    }

    /**
     * 手势向右滑动
     */
    protected void onFlingLeft() {
    }

    /**
     * 手势向右滑动
     */
    protected void onFlingRight() {
    }

    @Override
    protected void onResume() {
        super.onResume();

        StatService.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();

        StatService.onPause(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if ((getFlag() & FLAG_SEARCH_VIEW) == FLAG_SEARCH_VIEW) {
            MenuItem menuItem = menu.add("delete");
            menuItem.setIcon(R.drawable.activity_action_bar_search_btn_bg)
                    .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM
                            | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
            menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {

                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    //                    Intent intent = new Intent();
                    //                    intent.setClass(BaseActivity.this,
                    //                            SearchActivity.class);
                    //                    startActivity(intent);
                    return true;
                }
            });
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case android.R.id.home:
            finish();
            break;

        default:
            break;
        }
        return true;
    }

    private Logger mLogger = LogUtil.getLogger();

    public final void debug(String msg) {
        if (AppConstants.LOGGER_ENABLE) {
            mLogger.debug(msg);
        }
    }

    public final void info(String msg) {
        if (AppConstants.LOGGER_ENABLE) {
            mLogger.info(msg);
        }
    }

    public boolean dispatchTouchEvent(MotionEvent ev) {
        mGestureDetector.onTouchEvent(ev);
        //        boolean consume = super.dispatchTouchEvent(ev);
        //        if (consume) {
        //            LogUtil.d(TAG, "dispatchTouchEvent:" + ev.getAction() + " "
        //                    + consume);
        //        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean mGestureDetectorState = true;

    /**
     * 将手势失效
     */
    public void disableGestureDetector() {
        mGestureDetectorState = false;
    }

    /**
     * 开启手势识别
     */
    public void enableGestureDetector() {
        mGestureDetectorState = true;
    }

    //    @Override
    //    public boolean onTouchEvent(MotionEvent event) {
    //        mGestureDetector.onTouchEvent(event);
    //        return super.onTouchEvent(event);
    //    }

    //    public void next(View view) {
    //        showNext();
    //    }
    //
    //    public void pre(View view) {
    //        showPre();
    //    }
    //
    //    public void showNext() {
    //
    //    }
    //
    //    public void showPre() {
    //
    //    }
}


text:
package tf.ownnote.ui.notes;

import java.time.DateTimeException;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
import tf.ownnote.ui.main.OwnNoteEditor;

/**
 *
 * @author thomas
 */
public class NoteVersion {
    private static final String DATA_SEP = "@";

    private String versionAuthor;
    private LocalDateTime versionDate;

    private NoteVersion() {
    }

    public NoteVersion(final String author, final LocalDateTime date) {
        versionAuthor = author;
        versionDate = date;
    }

    public String getAuthor() {
        return versionAuthor;
    }

    public void setAuthor(final String author) {
        versionAuthor = author;
    }

    public LocalDateTime getDate() {
        return versionDate;
    }

    public void setDate(final LocalDateTime date) {
       versionDate = date;
    }

    public static NoteVersion fromHtmlString(final String htmlString) {
        final NoteVersion result = new NoteVersion("", LocalDateTime.now());

        String [] data = htmlString.split(DATA_SEP);
        if (data.length == 2) {
            result.setAuthor(data[0]);

            try {
                result.setDate(LocalDateTime.parse(data[1], OwnNoteEditor.DATE_TIME_FORMATTER));
            } catch (DateTimeException ex) {
                Logger.getLogger(NoteVersion.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return result;
    }

    public static String toHtmlString(final NoteVersion data) {
        if (data == null) {
            return "";
        }

        return data.getAuthor() + DATA_SEP + OwnNoteEditor.DATE_TIME_FORMATTER.format(data.getDate());
    }
}


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

    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Frequently Asked Question — statsmodels 0.9.0 documentation</title>
    <link rel="stylesheet" href="_static/nature.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="shortcut icon" href="_static/statsmodels_hybi_favico.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="stylesheet" href="_static/examples.css" type="text/css" />
<link rel="stylesheet" href="_static/facebox.css" type="text/css" />

Navigation

          index

          modules |

Install
  |

Support
  |

Bugs
  |

Develop
  |

Examples
  |

FAQ
  |

Frequently Asked Question¶

What do endog and exog mean?¶

These are shorthand for endogenous and exogenous variables. You might be more comfortable with the common y and X notation in linear models. Sometimes the endogenous variable y is called a dependent variable. Likewise, sometimes the exogenous variables X are called the independent variables. You can read about this in greater detail at endog, exog, what's that?

How does statsmodels handle missing data?¶

Missing data can be handled via the missing keyword argument. Every model takes this keyword. You can find more information in the docstring of statsmodels.base.Model.

Why won't statsmodels build?¶

If you're on Python 3.4, you must use Cython 0.20.1. If you're still having problems, try running

python setup.py clean

What if my question isn't answered here?¶

You may find answers for questions that have not yet been added here on GitHub under the FAQ issues tag. If not, please ask your question on stackoverflow using the statsmodels tag or on the mailing list.

Table Of Contents

Frequently Asked Question

What do endog and exog mean?

How does statsmodels handle missing data?

Why won't statsmodels build?

What if my question isn't answered here?

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

        © Copyright 2009-2017, Josef Perktold, Skipper Seabold, Jonathan Taylor, statsmodels-developers.
      Created using Sphinx 1.7.4.


text:
FactoryGirl.define do
  factory :entry do
    project
    category
    description ""
    hours 1
    date "2014-02-26 22:06:47"
    user

    factory :entry_with_client do
      project { create(:project, client: create(:client)) }
    end
  end
end


text:
<?php
$mysqli = new mysqli("localhost", "USERNAME", "PASSWROD", "DB_NAME");
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
} else {

}
?>