text:
namespace generator
{
namespace cache
{
class IntermediateDataReader;
}  // namespace cache

class CityAreaCollector : public CollectorInterface
{
public:
  explicit CityAreaCollector(std::string const & filename);

  // CollectorInterface overrides:
  std::shared_ptr<CollectorInterface>
  Clone(std::shared_ptr<cache::IntermediateDataReader> const & = {}) const override;

  void CollectFeature(feature::FeatureBuilder const & feature, OsmElement const &) override;
  void Save() override;

  void Merge(generator::CollectorInterface const & collector) override;
  void MergeInto(CityAreaCollector & collector) const override;

private:
  std::vector<feature::FeatureBuilder> m_boundaries;
};
}  // namespace generator

redpajama_set_name: RedPajamaGithub


text:
namespace riakboost{} namespace boost = riakboost; namespace riakboost{

    template< class T >
    inline bool empty( const T& r )
    {
        return riakboost::begin( r ) == riakboost::end( r );
    }

} // namepace 'boost'

#endif


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class com.smartsheet.api.models.CopyOrMoveRowDirective (Smartsheet Java SDK 2.146.0 API)</title>
<meta name="date" content="2021-11-12">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
com.smartsheet.api.models.CopyOrMoveRowDirective

Packages that use CopyOrMoveRowDirective

Package
Description

com.smartsheet.api

com.smartsheet.api.models

Uses of CopyOrMoveRowDirective in com.smartsheet.api

Methods in com.smartsheet.api with parameters of type CopyOrMoveRowDirective

Modifier and Type
Method and Description

CopyOrMoveRowResult
SheetRowResources.copyRows(Long sheetId,
        EnumSet<RowCopyInclusion> includes,
        Boolean ignoreRowsNotFound,
        CopyOrMoveRowDirective copyParameters)

Copies Row(s) from the Sheet specified in the URL to (the bottom of) another sheet.

CopyOrMoveRowResult
SheetRowResources.moveRows(Long sheetId,
        EnumSet<RowMoveInclusion> includes,
        Boolean ignoreRowsNotFound,
        CopyOrMoveRowDirective moveParameters)

Moves Row(s) from the Sheet specified in the URL to (the bottom of) another sheet.

Uses of CopyOrMoveRowDirective in com.smartsheet.api.models

Methods in com.smartsheet.api.models that return CopyOrMoveRowDirective

Modifier and Type
Method and Description

CopyOrMoveRowDirective
CopyOrMoveRowDirective.InsertCopyOrMoveRowDirectiveBuilder.build()

Builds the CopyOrMoveRowDirective.

CopyOrMoveRowDirective
CopyOrMoveRowDirective.setRowIds(List<Long> rowIds)

Sets the IDs of the rows to move or copy from the source sheet.

CopyOrMoveRowDirective
CopyOrMoveRowDirective.setTo(CopyOrMoveRowDestination to)

Sets the CopyOrMoveRowDestination object that identifies the destination sheet.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2014–2021 Smartsheet. All rights reserved.


text:
'use strict';

angular.module('ruckApp')
  .directive('footer', function () {
    return {
      templateUrl: 'app/components/footer/footer.html',
      restrict: 'E'
    };
  });


text:
body {
  background-color: #777;
  font-size: 16px;
  font-weight: bold;
  color: #fff;
}

.draggable {
  -moz-border-radius: 50%;
  -webkit-border-radius: 50%;
  border-radius: 50%;
  display: inline-block;
  min-width: 40px;
  padding: 0.5em 0.5em;
  color: #555;
  border: solid 4px #fff;
  -webkit-transform: translate(0px, 0px);
          transform: translate(0px, 0px);
  transition: background-color 0.3s;
}

#canvasContainer, #container {
  margin: 0px auto;
  padding-top: 20px;
  padding-bottom: 20px;
  width: 100%;
  text-align: center;
}

.dropzone {
  height: 500px;
  width: 500px;
  background-color: #ccc;
  border: dashed 4px transparent;
  border-radius: 4px;
  display:inline-block;
  transition: background-color 0.3s;
}

.drop-active {
  border-color: #aaa;
}

.drop-target {
  background-color: #ddd;
  border-color: #fff;
  border-style: solid;
}

#endStudyButton {
  color: #555;
  font-size: 16px;
  font-weight: bold;
  background-color: #ccc;
  border: solid 4px #fff;
  border-radius: 4px;
  padding: 0.5em 2em;
}

#endStudyButton:hover {
  color: #333;
  background-color: #999;
}


text:
package ru.stqa.pft.rest;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.jayway.restassured.RestAssured;
import org.apache.http.client.fluent.Request;
import org.testng.SkipException;
import org.testng.annotations.BeforeClass;
import ru.stqa.pft.rest.application.RestHelper;
import ru.stqa.pft.rest.model.Issue;

import java.io.IOException;
import java.util.Set;

/**
 * Created by razgonyaev on 01.12.2016.
 */
public class TestBase {
  RestHelper rest = new RestHelper();

  @BeforeClass
  public void init() {
    RestAssured.authentication = RestAssured.basic("LSGjeU4yP1X493ud1hNniA==", "");
  }

  public void skipIfNotFixed(int issueId) throws IOException {
    if (!isIssueOpen(issueId)) {
      throw new SkipException("Ignored because of issue " + issueId);
    }
  }
  private boolean isIssueOpen(int issueId) throws IOException {
    if (getIssueStatus(issueId).iterator().next().getState_name().equals("Closed")) {
      return true;
    } else {
      return false;
    }
  }

  private Set<Issue> getIssueStatus(int issueId) throws IOException {
    String json = rest.getExecutor().execute(Request.Get(String.format("http://demo.bugify.com/api/issues/%s.json", issueId)))
            .returnContent().asString();
    JsonElement parsed = new JsonParser().parse(json);
    JsonElement issues = parsed.getAsJsonObject().get("issues");
    return new Gson().fromJson(issues, new TypeToken<Set<Issue>>(){}.getType());
  }

}


text:
<?php namespace CodeIgniter\Test;

class ReflectionHelperTest extends \CIUnitTestCase
{
	public function testGetPrivatePropertyWithObject()
	{
		$obj    = new __TestForReflectionHelper();
		$actual = $this->getPrivateProperty($obj, 'private');
		$this->assertEquals('secret', $actual);
	}

	public function testGetPrivatePropertyWithObjectStaticCall()
	{
		$obj    = new __TestForReflectionHelper();
		$actual = \CIUnitTestCase::getPrivateProperty($obj, 'private');
		$this->assertEquals('secret', $actual);
	}

	public function testGetPrivatePropertyWithStatic()
	{
		$actual = $this->getPrivateProperty(
			__TestForReflectionHelper::class, 'static_private'
		);
		$this->assertEquals('xyz', $actual);
	}

	public function testSetPrivatePropertyWithObject()
	{
		$obj = new __TestForReflectionHelper();
		$this->setPrivateProperty(
			$obj, 'private', 'open'
		);
		$this->assertEquals('open', $obj->getPrivate());
	}

	public function testSetPrivatePropertyWithStatic()
	{
		$this->setPrivateProperty(
			__TestForReflectionHelper::class, 'static_private', 'abc'
		);
		$this->assertEquals(
			'abc', __TestForReflectionHelper::getStaticPrivate()
		);
	}

	public function testGetPrivateMethodInvokerWithObject()
	{
		$obj    = new __TestForReflectionHelper();
		$method = $this->getPrivateMethodInvoker(
			$obj, 'privateMethod'
		);
		$this->assertEquals(
			'private param1param2', $method('param1', 'param2')
		);
	}

	public function testGetPrivateMethodInvokerWithStatic()
	{
		$method = $this->getPrivateMethodInvoker(
			__TestForReflectionHelper::class, 'privateStaticMethod'
		);
		$this->assertEquals(
			'private_static param1param2', $method('param1', 'param2')
		);
	}
}

class __TestForReflectionHelper
{
	private $private               = 'secret';
	private static $static_private = 'xyz';

	public function getPrivate()
	{
		return $this->private;
	}

	public static function getStaticPrivate()
	{
		return self::$static_private;
	}

	private function privateMethod($param1, $param2)
	{
		return 'private ' . $param1 . $param2;
	}

	private static function privateStaticMethod($param1, $param2)
	{
		return 'private_static ' . $param1 . $param2;
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Platygrapha occulta f. occulta

### Remarks
null


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/DynamoDBKeySchemaElement.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/DynamoDBKeySchemaElement</TokenIdentifier>
			<Abstract type="html">Key Schema Element</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/setAttributeName:</TokenIdentifier>
			<Abstract type="html">The name of a key attribute.

Constraints:

Length: 1 - 255
</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *attributeName</Declaration>

			<Anchor>//api/name/attributeName</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/attributeName</TokenIdentifier>
			<Abstract type="html">The name of a key attribute.

Constraints:

Length: 1 - 255
</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *attributeName</Declaration>

			<Anchor>//api/name/attributeName</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/DynamoDBKeySchemaElement/attributeName</TokenIdentifier>
			<Abstract type="html">The name of a key attribute.

Constraints:

Length: 1 - 255
</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *attributeName</Declaration>

			<Anchor>//api/name/attributeName</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/setKeyType:</TokenIdentifier>
			<Abstract type="html">The attribute data, consisting of the data type and the attribute
value itself.

Constraints:

Allowed Values: HASH, RANGE</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *keyType</Declaration>

			<Anchor>//api/name/keyType</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/keyType</TokenIdentifier>
			<Abstract type="html">The attribute data, consisting of the data type and the attribute
value itself.

Constraints:

Allowed Values: HASH, RANGE</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *keyType</Declaration>

			<Anchor>//api/name/keyType</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/DynamoDBKeySchemaElement/keyType</TokenIdentifier>
			<Abstract type="html">The attribute data, consisting of the data type and the attribute
value itself.

Constraints:

Allowed Values: HASH, RANGE</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>@property (nonatomic, retain) NSString *keyType</Declaration>

			<Anchor>//api/name/keyType</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/init</TokenIdentifier>
			<Abstract type="html">Default constructor for a new KeySchemaElement object.  Callers should use the
property methods to initialize this object after creating it.</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>- (id)init</Declaration>

			<Anchor>//api/name/init</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/initWithAttributeName:andKeyType:</TokenIdentifier>
			<Abstract type="html">Constructs a new KeySchemaElement object.
Callers should use properties to initialize any additional object members.</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>- (id)initWithAttributeName:(NSString *)theAttributeName andKeyType:(NSString *)theKeyType</Declaration>
			<Parameters>
				<Parameter>
					<Name>theAttributeName</Name>
					<Abstract type="html">The name of a key attribute.</Abstract>
				</Parameter><Parameter>
					<Name>theKeyType</Name>
					<Abstract type="html">The attribute data, consisting of the data type and
the attribute value itself.</Abstract>
				</Parameter>
			</Parameters>

			<Anchor>//api/name/initWithAttributeName:andKeyType:</Anchor>
            <NodeRef refid="196"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/DynamoDBKeySchemaElement/description</TokenIdentifier>
			<Abstract type="html">Returns a string representation of this object; useful for testing and
debugging.</Abstract>
			<DeclaredIn>DynamoDBKeySchemaElement.h</DeclaredIn>

			<Declaration>- (NSString *)description</Declaration>

			<ReturnValue><Abstract type="html">A string representation of this object.</Abstract></ReturnValue>
			<Anchor>//api/name/description</Anchor>
            <NodeRef refid="196"/>
		</Token>

	</File>
</Tokens>


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

import com.facebook.presto.metadata.Table.TableMapper;
import com.facebook.presto.spi.ColumnMetadata;
import com.facebook.presto.spi.SchemaTableName;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.GetGeneratedKeys;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.SqlUpdate;
import org.skife.jdbi.v2.sqlobject.customizers.Mapper;

import java.util.List;

public interface MetadataDao
{
    @SqlUpdate("CREATE TABLE IF NOT EXISTS tables (\n" +
            "  table_id BIGINT PRIMARY KEY AUTO_INCREMENT,\n" +
            "  catalog_name VARCHAR(255) NOT NULL,\n" +
            "  schema_name VARCHAR(255) NOT NULL,\n" +
            "  table_name VARCHAR(255) NOT NULL,\n" +
            "  UNIQUE (catalog_name, schema_name, table_name)\n" +
            ")")
    void createTablesTable();

    @SqlUpdate("CREATE TABLE IF NOT EXISTS columns (\n" +
            "  table_id BIGINT NOT NULL,\n" +
            "  column_id BIGINT NOT NULL,\n" +
            "  column_name VARCHAR(255) NOT NULL,\n" +
            "  ordinal_position INT NOT NULL,\n" +
            "  data_type VARCHAR(255) NOT NULL,\n" +
            "  PRIMARY KEY (table_id, column_id),\n" +
            "  UNIQUE (table_id, column_name),\n" +
            "  UNIQUE (table_id, ordinal_position),\n" +
            "  FOREIGN KEY (table_id) REFERENCES tables (table_id)\n" +
            ")")
    void createColumnsTable();

    @SqlQuery("SELECT table_id FROM tables\n" +
            "WHERE catalog_name = :catalogName\n" +
            "  AND schema_name = :schemaName\n" +
            "  AND table_name = :tableName")
    @Mapper(TableMapper.class)
    Table getTableInformation(
            @Bind("catalogName") String catalogName,
            @Bind("schemaName") String schemaName,
            @Bind("tableName") String tableName);

    @SqlQuery("SELECT catalog_name, schema_name, table_name\n" +
            "FROM tables\n" +
            "WHERE table_id = :tableId")
    @Mapper(QualifiedTableNameMapper.class)
    QualifiedTableName getTableName(@Bind("tableId") long tableId);

    @SqlQuery("SELECT column_name, data_type, ordinal_position\n" +
            "FROM columns\n" +
            "WHERE table_id = :tableId\n" +
            "  AND column_id = :columnId")
    ColumnMetadata getColumnMetadata(
            @Bind("tableId") long tableId,
            @Bind("columnId") long columnId);

    @SqlQuery("SELECT column_name, data_type, ordinal_position\n" +
            "FROM columns\n" +
            "WHERE table_id = :tableId\n" +
            "ORDER BY ordinal_position")
    List<ColumnMetadata> getTableColumnMetaData(@Bind("tableId") long tableId);

    @SqlQuery("SELECT column_id\n" +
            "FROM columns\n" +
            "WHERE table_id = :tableId AND column_name = :columnName")
    Long getColumnId(@Bind("tableId") long tableId, @Bind("columnName") String columnName);

    @SqlQuery("SELECT catalog_name, schema_name, table_name\n" +
            "FROM tables\n" +
            "WHERE (catalog_name = :catalogName OR :catalogName IS NULL)\n" +
            "  AND (schema_name = :schemaName OR :schemaName IS NULL)")
    @Mapper(SchemaTableNameMapper.class)
    List<SchemaTableName> listTables(
            @Bind("catalogName") String catalogName,
            @Bind("schemaName") String schemaName);

    @SqlQuery("SELECT DISTINCT schema_name FROM tables\n" +
            "WHERE catalog_name = :catalogName\n")
    List<String> listSchemaNames(@Bind("catalogName") String catalogName);

    @SqlQuery("SELECT t.catalog_name, t.schema_name, t.table_name,\n" +
            "  c.column_id, c.column_name, c.ordinal_position, c.data_type\n" +
            "FROM tables t\n" +
            "JOIN columns c ON (t.table_id = c.table_id)\n" +
            "WHERE (catalog_name = :catalogName OR :catalogName IS NULL)\n" +
            "  AND (schema_name = :schemaName OR :schemaName IS NULL)\n" +
            "  AND (table_name = :tableName OR :tableName IS NULL)\n" +
            "ORDER BY schema_name, table_name, ordinal_position")
    List<TableColumn> listTableColumns(
            @Bind("catalogName") String catalogName,
            @Bind("schemaName") String schemaName,
            @Bind("tableName") String tableName);

    @SqlQuery("SELECT t.catalog_name, t.schema_name, t.table_name,\n" +
            "  c.column_id, c.column_name, c.ordinal_position, c.data_type\n" +
            "FROM tables t\n" +
            "JOIN columns c ON (t.table_id = c.table_id)\n" +
            "WHERE t.table_id = :tableId")
    List<TableColumn> listTableColumns(@Bind("tableId") long tableId);

    @SqlUpdate("INSERT INTO tables (catalog_name, schema_name, table_name)\n" +
            "VALUES (:catalogName, :schemaName, :tableName)")
    @GetGeneratedKeys
    long insertTable(
            @Bind("catalogName") String catalogName,
            @Bind("schemaName") String schemaName,
            @Bind("tableName") String tableName);

    @SqlUpdate("INSERT INTO columns (table_id, column_id, column_name, ordinal_position, data_type)\n" +
            "VALUES (:tableId, :columnId, :columnName, :ordinalPosition, :dataType)")
    void insertColumn(
            @Bind("tableId") long tableId,
            @Bind("columnId") long columnId,
            @Bind("columnName") String columnName,
            @Bind("ordinalPosition") int ordinalPosition,
            @Bind("dataType") String dataType);

    @SqlUpdate("DELETE FROM tables WHERE table_id = :tableId")
    int dropTable(@Bind("tableId") long tableId);

    @SqlUpdate("DELETE FROM columns WHERE table_id = :tableId")
    int dropColumns(@Bind("tableId") long tableId);
}


text:
#include "TcpSocketThread.h"
#include "./../radarStationPrototype/rscontroller/tcpsocket.h"

Receiver::Receiver(QObject *parent)
	: QTcpSocket(parent)
{
	//qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
	//connect(tcpSocket, SIGNAL(connected()), this, SIGNAL(connected()));
	//connect(tcpSocket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    connect(this, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
	connect(this, SIGNAL(readyRead()), this, SLOT(readData()));
}

Receiver::~Receiver()
{
    abort();
    //waitForDisconnected();
}

void Receiver::displayError(QAbstractSocket::SocketError err)
{
    QAbstractSocket::SocketState st = state();
    int i = 0;
}

void Receiver::connect2Host(const QString& _host, quint16 _port)
{
	abort();
	host = _host;
	port = _port;
	connectToHost(host, port);
}

void Receiver::disconnect()
{
	abort();
}

void Receiver::readData()
{
	QDataStream in(this);
    in.setVersion(QDataStream::Qt_5_4);

	if(bytesAvailable() <= 0)
		return;

	int sz = bytesAvailable();
	char* packet = new char[sz + 1];
	memset(packet, 0, sz + 1);
	in.readRawData(packet, sz);
	emit packetReceived(packet, sz);
}

void  Receiver::writePacket(QString packet)
{
	write(packet.toStdString().c_str(), packet.toStdString().size());
}

void Receiver::writePacket(QByteArray packet)
{
    write(packet.data(), packet.size());
    emit logMessage(
                QString("write to %1 socket %2 bytes")
                .arg(port).arg(packet.size())
                );
}

//--------------------------------------------------------------------------------------
/*
Sender::Sender(QObject *parent)
    : QTcpServer(parent)
{
    //qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
    //connect(tcpSocket, SIGNAL(connected()), this, SIGNAL(connected()));
    //connect(tcpSocket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
    //connect(tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(displayError(QAbstractSocket::SocketError)));
    connect(this, SIGNAL(readyRead()), this, SLOT(readData()));
}

Sender::~Sender()
{
    abort();
    //waitForDisconnected();
}
*/

TcpSocketThread::TcpSocketThread(QObject *parent)
    : QThread(parent)
	, restart(false)
	, abort(false)
    //, receiver(NULL)
{
}

TcpSocketThread::~TcpSocketThread()
{
	abort = true;
	deleteReceiver();
}

void TcpSocketThread::deleteReceiver()
{
    /*
	if(receiver)
	{
        delete receiver;
        receiver = NULL;
	}
    */
}

void TcpSocketThread::connect2Device(const QString& host, quint16 port)
{
	emit connectToHost(host, port);
}

void TcpSocketThread::disconnect()
{
	emit disconnectFromHost();
}

void TcpSocketThread::run()
{
    // Receiver* receiver = new Receiver();

    TcpSocket* receiver = new TcpSocket();

	connect(this, SIGNAL(connectToHost(const QString&, quint16)), receiver, SLOT(connect2Host(const QString&, quint16)));
	connect(this, SIGNAL(disconnectFromHost()), receiver, SLOT(disconnect()));
	connect(this, SIGNAL(writeData(QString)), receiver, SLOT(writePacket(QString)));
    connect(this, SIGNAL(writePacket(QByteArray*)), receiver, SLOT(writePacket(QByteArray*)));

	connect(receiver, SIGNAL(connected()), this, SIGNAL(connected()));
	connect(receiver, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
//	connect(receiver, SIGNAL(displayError(QAbstractSocket::SocketError)), this, SIGNAL(displayError(QAbstractSocket::SocketError)));
	connect(receiver, SIGNAL(packetReceived(char*, int)), this, SLOT(packetReceived(char*, int)));
	connect(receiver, SIGNAL(logMessage(const QString&)), this, SIGNAL(logMessage(const QString&)));

	exec();

    //deleteReceiver();
    delete receiver;
}

void TcpSocketThread::packetReceived(char* packet, int sz)
{
	QString msg = packet;
	emit logMessage(msg);
}


text:
@interface AWFAdvisoryStyle : AWFCascadingStyle

@end


text:
package org.codehaus.enunciate.util;

import org.codehaus.enunciate.contract.Facet;
import org.codehaus.enunciate.contract.HasFacets;

import java.util.*;

/**
 * @author Ryan Heaton
 */
public class FacetFilter {

  private final Set<String> includes;
  private final Set<String> excludes;
  private static final ThreadLocal<FacetFilter> FACET_FILTER = new ThreadLocal<FacetFilter>();

  private FacetFilter(Set<String> includes, Set<String> excludes) {
    this.includes = includes;
    this.excludes = excludes;
  }

  public static void set(Set<String> includes, Set<String> excludes) {
    if ((includes != null && !includes.isEmpty()) || (excludes != null && !excludes.isEmpty())) {
      FACET_FILTER.set(new FacetFilter(includes, excludes));
    }
  }

  public static FacetFilter get() {
    return FACET_FILTER.get();
  }

  public static void clear() {
    FACET_FILTER.remove();
  }

  public static boolean accept(HasFacets item) {
    return FACET_FILTER.get() == null || FACET_FILTER.get().acceptInternal(item);
  }

  protected boolean acceptInternal(HasFacets item) {
    if (item == null) {
      return false;
    }

    if ((includes == null || includes.isEmpty()) && (excludes == null || excludes.isEmpty())) {
      return true;
    }

    boolean accept = true;
    if (includes != null && !includes.isEmpty()) {
      boolean included = false;
      for (Facet facet : item.getFacets()) {
        if (includes.contains(facet.getName())) {
          included = true;
          break;
        }
      }
      accept = included;
    }

    //then remove the items that are explicitly excluded.
    if (excludes != null && !excludes.isEmpty()) {
      for (Facet facet : item.getFacets()) {
        if (excludes.contains(facet.getName())) {
          accept = false;
          break;
        }
      }
    }

    return accept;
  }

  public static <T extends HasFacets> Collection<T> filteredCollection(Collection<T> list) {
    FacetFilter filter = FACET_FILTER.get();
    if (filter == null) {
      return list;
    }

    ArrayList<T> filtered = new ArrayList<T>(list);
    Iterator<T> iterator = filtered.iterator();
    while (iterator.hasNext()) {
      T item = iterator.next();
      if (item != null && !filter.accept(item)) {
        iterator.remove();
      }
    }

    return filtered;
  }

  public static <K,V> Map<K,V> filteredMap(Map<K, V> map) {
    FacetFilter filter = FACET_FILTER.get();
    if (filter == null) {
      return map;
    }

    LinkedHashMap<K, V> filtered = new LinkedHashMap<K, V>(map);
    Iterator<Map.Entry<K, V>> iterator = filtered.entrySet().iterator();
    while (iterator.hasNext()) {
      Map.Entry entry = iterator.next();
      HasFacets item = entry.getKey() instanceof HasFacets ? (HasFacets) entry.getKey() : entry.getValue() instanceof HasFacets ? (HasFacets) entry.getValue() : null;
      if (item != null && !filter.accept(item)) {
        iterator.remove();
      }
    }

    return filtered;
  }

}


text:
IS_NOT_NULL = 'is_not_null'
IS_NOT_BOOL = 'is_not_bool'
IS_NOT_CONVERTIBLE_TO_BOOL = 'is_not_convertible_to_bool'

NOTHING_MATCH = 'nothing_match'

# String
IS_NOT_A_STRING = 'is_not_a_string'
IS_NOT_A_BYTES_STRING = 'is_not_a_bytes_string'
EMPTY_STRING = 'empty_string'
SHORT_STRING = 'short_string'
LONG_STRING = 'long_string'
# Regexp
DOES_NOT_MATCH_RE = 'does_not_match_re'

WRONG_TYPE = 'wrong_type'
IS_NOT_A_NUMBER = 'is_not_a_number'
DOES_NOT_MATCH_ANY = 'does_not_match_any'

TOO_BIG = 'too_big'
TOO_SMALL = 'too_small'

IS_NOT_INT = 'is_not_int'
INVALID_DECIMAL = 'invalid_decimal'

IS_NOT_EXACTLY = 'is_not_exactly'
TRAFARET_IS_NOT_SET = 'trafaret_is_not_set'
IS_NOT_CALLABLE = 'is_not_callable'

IS_NOT_BYTES = 'is_not_bytes'
CANNOT_BE_DECODED = 'cannot_be_decoded'
CANNOT_BE_ENCODED = 'cannot_be_encoded'

IS_NOT_A_LIST = 'is_not_a_list'
TOO_SHORT = 'too_short'
TOO_LONG = 'too_long'

TUPLE_LIKE = 'tuple_like'
LOT_ELEMENTS = 'lot_elements'

PAIR_MEMBERS_DID_NOT_MATCH = 'pair_members_did_not_match'
SOME_ELEMENTS_DID_NOT_MATCH = 'some_elements_did_not_match'

# Keys and dict
IS_NOT_A_DICT = 'is_not_a_dict'
REQUIRED = 'required'
SHADOWED = 'shadowed'
NOT_ALLOWED = 'not_allowed'
MAPPING_FAILED = 'mapping_failed'
# extra keys
MUST_BE_EQUAL = 'must_be_equal'
ONLY_ONE_MUST_BE_DEFINED = 'only_one_must_be_defined'
ONE_IS_REQUIRED = 'one_is_required'

# Internet
IS_NOT_VALID_EMAIL = 'is_not_valid_email'
IS_NOT_VALID_URL = 'is_not_valid_url'
IS_NOT_IPv4 = 'is_not_ipv4'
IS_NOT_IPv6 = 'is_not_ipv6'
IS_NOT_IP = 'is_not_ip'

# Date & DateTime
DOES_NOT_MATCH_FORMAT = 'does_not_match_format'
IS_NOT_CONVERTIBLE_TO_DATE = 'is_not_convertible_to_date'
IS_NOT_CONVERTIBLE_TO_DATETIME = 'is_not_convertible_to_datetime'

# Contrib
NOT_DATETIME = 'not_datetime'
NOT_DATE = 'not_date'


text:
package com.github.leeyazhou.scf.server.exception;

import com.github.leeyazhou.scf.core.entity.ErrorState;
import com.github.leeyazhou.scf.core.entity.KeyValuePair;
import com.github.leeyazhou.scf.protocol.sdp.RequestProtocol;

/**
 * service frame exception use in proxy and proxyhandle
 *
 */
public class RPCException extends RuntimeException {
	private static final long serialVersionUID = 1L;

	private ErrorState state;

	private String errorMsg;

	private String fromIP;

	private String toIP;

	private Object sdp;

	/**
	 * create exception
	 *
	 * @param errorMsg
	 * @param fromIP
	 * @param toIP
	 * @param mb
	 * @param state
	 * @param cause
	 */
	public RPCException(String errorMsg, String fromIP, String toIP, Object sdp, ErrorState state,
			Throwable cause) {
		super(errorMsg, cause);
		this.setState(state);
		this.setErrorMsg(errorMsg);
		this.setFromIP(fromIP);
		this.setToIP(toIP);
		this.setSdp(sdp);
	}

	public RPCException(String errorMsg, ErrorState state, Throwable cause) {
		this(errorMsg, "", "", null, state, cause);
	}

	public RPCException(String errorMsg, ErrorState state) {
		this(errorMsg, "", "", null, state, null);
	}

	public RPCException(ErrorState state, Throwable cause) {
		this("", "", "", null, state, cause);
	}

	public RPCException(ErrorState state) {
		this("", "", "", null, state, null);
	}

	@Override
	public void printStackTrace() {
		System.out.println("-------------------------begin-----------------------------");
		System.out.println("fromIP:" + this.getFromIP());
		System.out.println("toIP:" + this.getToIP());
		System.out.println("state:" + this.getState().toString());
		System.out.println("errorMsg:" + this.getErrorMsg());
		System.out.println("MessageBodyBase:");

		if (sdp.getClass() == RequestProtocol.class) {
			RequestProtocol request = (RequestProtocol) this.sdp;
			System.out.println("Server.Lookup:" + request.getLookup());
			System.out.println("Server.MethodName:" + request.getMethodName());
			System.out.println("Server.ParaKVList:");
			for (KeyValuePair kv : request.getParaKVList()) {
				System.out.println("key:" + kv.getKey() + "---value:" + kv.getValue());
			}
		}
		super.printStackTrace();
		System.out.println("--------------------------end------------------------------");
	}

	public void setState(ErrorState state) {
		this.state = state;
	}

	public ErrorState getState() {
		return state;
	}

	public String getFromIP() {
		return fromIP;
	}

	public void setFromIP(String fromIP) {
		this.fromIP = fromIP;
	}

	public String getToIP() {
		return toIP;
	}

	public void setToIP(String toIP) {
		this.toIP = toIP;
	}

	public void setErrorMsg(String errorMsg) {
		this.errorMsg = errorMsg;
	}

	public String getErrorMsg() {
		return errorMsg;
	}

	public Object getSdp() {
		return sdp;
	}

	public void setSdp(Object sdp) {
		this.sdp = sdp;
	}
}


text:
require 'bh/helpers/alert_box_helper'
require 'bh/helpers/button_helper'
require 'bh/helpers/cdn_helper'
require 'bh/helpers/dropdown_helper'
require 'bh/helpers/glyphicon_helper'
require 'bh/helpers/icon_helper'
require 'bh/helpers/modal_helper'
require 'bh/helpers/nav_helper'
require 'bh/helpers/navbar_helper'
require 'bh/helpers/panel_helper'
require 'bh/helpers/panel_row_helper'
require 'bh/helpers/progress_bar_helper'

module Bh
  module Extensions
    class MiddlemanExtension < Middleman::Extension
      helpers do
        include AlertBoxHelper
        include ButtonHelper
        include CdnHelper
        include DropdownHelper
        include GlyphiconHelper
        include IconHelper
        include ModalHelper
        include NavHelper
        include NavbarHelper
        include PanelHelper
        include PanelRowHelper
        include ProgressBarHelper
      end
    end
  end
end

::Middleman::Extensions.register(:bh, Bh::Extensions::MiddlemanExtension)


text:
    {{ request.current_signup.bigger_profile_image }}
    {{ request.current_signup.capital_amount_format }}

    {{ request.current_signup.name_or_email }}

      {% if site.show_public_profiles? == false %}
      {% elsif request.current_signup.is_profile_published? %}
      Public profile
      {% else %}
      No public profile
      {% endif %}
      (Sign out)

      {% if request.current_signup.has_membership_level_badge %}
      {% if site.has_membership_page? %}
      {{ request.current_signup.membership_level_badge }}
      {% else %}
      {{ request.current_signup.membership_level_badge }}
      {% endif %}
      {% endif %}
      {% if request.current_signup.is_banned? %}
      Banned
      {% elsif request.current_signup.rule_violations_count == 1 %}
       {{ "fugue-flag-yellow" | icon }} Warning
      {% elsif request.current_signup.rule_violations_count == 2 %}
       {{ "fugue-flag" | icon }} 1 violation
      {% elsif request.current_signup.rule_violations_count == 3 %}
       {{ "fugue-flag-gray" | icon }} 2 violations
      {% endif %}

{% if request.current_user.is_intern? %}

  {% if request.current_user.can_publish? %}
  {% if page_type == 'Blog' %}

 New blog post

 Edit this page

  {% elsif page_type == 'Suggestion Box' %}

 New suggestion

 Edit this page

  {% elsif page_type == 'Calendar' %}

 New event

 Edit this page

  {% elsif page_type == 'Blog Post' %}

 Edit this blog post

  {% elsif page_type == 'Question' %}

 Edit this question

  {% elsif page_type == 'FAQ' %}

 Edit questions

  {% elsif page_type == 'Suggestion' %}

 Edit this suggestion

  {% elsif page_type == 'Event' %}

 Edit this event

  {% elsif page_type == 'Profile' %}

 Edit this person

  {% elsif page %}

 Edit this page

  {% endif %}
  {% endif %}

 Control panel

{% endif %}

  {% for child in site.supporter_pages %}

{{ child.icon | icon }} {{ child.name }}

  {% endfor %}

  {% if page_type == 'User Page' %}

 Your pages

  {% else %}

 Your pages

  {% endif %}
  {% if page_type == 'User Settings' %}

 Settings

  {% else %}

 Settings

  {% endif %}

  {% if page and page.is_editing_available? %}

 Edit this page

  {% endif %}

{% if request.logged_in? and request.current_signup.has_email? %}
{% elsif request.sorta_logged_in? and request.current_signup.has_email? %}
{% else %}
  {% if site.has_button1? %}
  {{ site.button1_text }}
  {% endif %}
{% endif %}

{% if site.has_button2? %}
{{ site.button2_text }}
{% endif %}

{% if site.has_button3? %}
{{ site.button3_text }}
{% endif %}

{% if request.current_signup.has_parent? %}

    {{ request.current_signup.parent.profile_image }}

      Point person: {{ request.current_signup.parent.published_name_linked }}

    {% if request.current_signup.parent.has_twitter_info? %}

    {% endif %}
    {% if request.current_signup.parent.has_facebook_info? %}

    {% endif %}
    {% if request.current_signup.parent.has_email? %}

    {% endif %}

{% endif %}

    {% if site.has_facebook_page? %}

    {% else %}
    <fb:like href="{{ site.full_url }}" colorscheme="{{ site.facebook_colorscheme }}" width="240"></fb:like>
    {% endif %}

    {% if site.has_twitter? %}

      Follow @{{ site.broadcaster.twitter_login }} on Twitter

    {% endif %}
    {% if page and page.has_rss? %}

       Subscribe with RSS

    {% elsif page and page.has_parent? and page.parent.has_rss? %}

      Subscribe with RSS

    {% endif %}


text:
package build

import (
	"github.com/m3db/m3em/os/fs"
)

type svcBuild struct {
	id         string
	sourcePath string
}

func (b *svcBuild) ID() string {
	return b.id
}

func (b *svcBuild) Iter(bufferSize int) (fs.FileReaderIter, error) {
	return fs.NewSizedFileReaderIter(b.sourcePath, bufferSize)
}

func (b *svcBuild) SourcePath() string {
	return b.sourcePath
}

// NewServiceBuild constructs a new ServiceBuild representing a Service build
func NewServiceBuild(id string, sourcePath string) ServiceBuild {
	return &svcBuild{
		id:         id,
		sourcePath: sourcePath,
	}
}

type svcConfig struct {
	id    string
	bytes []byte
}

func (c *svcConfig) ID() string {
	return c.id
}

func (c *svcConfig) Iter(_ int) (fs.FileReaderIter, error) {
	bytes, err := c.Bytes()
	if err != nil {
		return nil, err
	}
	return fs.NewBytesReaderIter(bytes), nil
}

func (c *svcConfig) Bytes() ([]byte, error) {
	return c.bytes, nil
}

// NewServiceConfig returns a new Service Configuration
func NewServiceConfig(id string, marshalledBytes []byte) ServiceConfiguration {
	return &svcConfig{
		id:    id,
		bytes: marshalledBytes,
	}
}


text:
package org.springframework.security.web.server;

import java.util.Arrays;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import org.springframework.core.log.LogMessage;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher;
import org.springframework.security.web.server.util.matcher.ServerWebExchangeMatcher.MatchResult;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;

/**
 * A {@link ServerAuthenticationEntryPoint} which delegates to multiple
 * {@link ServerAuthenticationEntryPoint} based on a {@link ServerWebExchangeMatcher}
 *
 * @author Rob Winch
 * @author Mathieu Ouellet
 * @since 5.0
 */
public class DelegatingServerAuthenticationEntryPoint implements ServerAuthenticationEntryPoint {

	private static final Log logger = LogFactory.getLog(DelegatingServerAuthenticationEntryPoint.class);

	private final List<DelegateEntry> entryPoints;

	private ServerAuthenticationEntryPoint defaultEntryPoint = (exchange, ex) -> {
		exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
		return exchange.getResponse().setComplete();
	};

	public DelegatingServerAuthenticationEntryPoint(DelegateEntry... entryPoints) {
		this(Arrays.asList(entryPoints));
	}

	public DelegatingServerAuthenticationEntryPoint(List<DelegateEntry> entryPoints) {
		Assert.notEmpty(entryPoints, "entryPoints cannot be null");
		this.entryPoints = entryPoints;
	}

	@Override
	public Mono<Void> commence(ServerWebExchange exchange, AuthenticationException ex) {
		return Flux.fromIterable(this.entryPoints).filterWhen((entry) -> isMatch(exchange, entry)).next()
				.map((entry) -> entry.getEntryPoint())
				.doOnNext((entryPoint) -> logger.debug(LogMessage.format("Match found! Executing %s", entryPoint)))
				.switchIfEmpty(Mono.just(this.defaultEntryPoint)
						.doOnNext((entryPoint) -> logger.debug(LogMessage
								.format("No match found. Using default entry point %s", this.defaultEntryPoint))))
				.flatMap((entryPoint) -> entryPoint.commence(exchange, ex));
	}

	private Mono<Boolean> isMatch(ServerWebExchange exchange, DelegateEntry entry) {
		ServerWebExchangeMatcher matcher = entry.getMatcher();
		logger.debug(LogMessage.format("Trying to match using %s", matcher));
		return matcher.matches(exchange).map(MatchResult::isMatch);
	}

	/**
	 * EntryPoint which is used when no RequestMatcher returned true
	 */
	public void setDefaultEntryPoint(ServerAuthenticationEntryPoint defaultEntryPoint) {
		this.defaultEntryPoint = defaultEntryPoint;
	}

	public static class DelegateEntry {

		private final ServerWebExchangeMatcher matcher;

		private final ServerAuthenticationEntryPoint entryPoint;

		public DelegateEntry(ServerWebExchangeMatcher matcher, ServerAuthenticationEntryPoint entryPoint) {
			this.matcher = matcher;
			this.entryPoint = entryPoint;
		}

		public ServerWebExchangeMatcher getMatcher() {
			return this.matcher;
		}

		public ServerAuthenticationEntryPoint getEntryPoint() {
			return this.entryPoint;
		}

	}

}


text:
import openmdao.api as om

from pycycle.maps.ncp01 import NCP01

import numpy as np

class StallCalcs(om.ExplicitComponent):
    """Component to compute the stall margins at constant speed (SMN) and constant flow (SMW)"""

    def setup(self):

        self.add_input('PR_SMN', val=1.0, units=None, desc='SMN pressure ratio')
        self.add_input('PR_SMW', val=1.0, units=None, desc='SMW pressure ratio')
        self.add_input('PR_actual', val=1.0, units=None, desc='Actual pressure ratio')

        self.add_input('Wc_SMN', val=1.0, units='lbm/s', desc='SMN corrected flow')
        self.add_input('Wc_actual', val=1.0, units='lbm/s', desc='Actual corrected flow')

        self.add_output('SMN', val=0.0, units=None, desc='Stall margin at constant speed')
        self.add_output('SMW', val=0.0, units=None, desc='Stall margin at constant flow')

        self.declare_partials('SMN', ['PR_SMN','PR_actual','Wc_SMN','Wc_actual'])
        self.declare_partials('SMW', ['PR_SMW','PR_actual'])

    def compute(self, inputs, outputs):

        outputs['SMN'] = ((inputs['Wc_actual']/inputs['Wc_SMN'])/(inputs['PR_actual']/inputs['PR_SMN'])-1)*100.
        outputs['SMW'] = (inputs['PR_SMW']-inputs['PR_actual'])/inputs['PR_actual'] * 100

    def compute_partials(self, inputs, J):

        PR_actual = inputs['PR_actual']
        PR_SMN = inputs['PR_SMN']
        PR_SMW = inputs['PR_SMW']

        Wc_actual = inputs['Wc_actual']
        Wc_SMN = inputs['Wc_SMN']

        wc_ratio = 100*Wc_actual/Wc_SMN
        J['SMN', 'PR_SMN'] = wc_ratio / PR_actual
        J['SMN', 'PR_actual'] = -wc_ratio * PR_SMN/PR_actual**2

        PR_ratio = 100*PR_SMN/PR_actual
        J['SMN', 'Wc_SMN'] = -Wc_actual/Wc_SMN**2 * PR_ratio
        J['SMN', 'Wc_actual'] = PR_ratio /Wc_SMN

        J['SMW', 'PR_SMW'] = 100 / PR_actual
        J['SMW', 'PR_actual'] = - 100 * PR_SMW/PR_actual**2

class MapScalars(om.ExplicitComponent):
    """Compute map scalars in design mode"""

    def setup(self):

        self.add_input('Nc', val=2.0, units='rpm',
                       desc='Computed design corrected shaft speed')
        self.add_input('NcMap', val=2.0, units='rpm',
                       desc='Design corrected shaft speed of map')
        self.add_input('PR', val=2.0,
                       desc='User input design pressure ratio')
        self.add_input('PRmap', val=2.0,
                       desc='Design pressure ratio of map')
        self.add_input('eff', val=1.0,
                       desc='User input design adiabatic efficiency')
        self.add_input('effMap', val=1.0,
                       desc='Design adiabatic efficiency of map')
        self.add_input('Wc', val=2.0, units='lbm/s',
                       desc='Computed design corrected mass flow rate')
        self.add_input('WcMap', val=2.0, units='lbm/s',
                       desc='Design corrected mass flow rate of map')

        self.add_output('s_Nc', shape=1,
                        desc='Scalar for design corrected shaft speed')
        self.add_output('s_PR', shape=1,
                        desc='Scalar for design pressure ratio')
        self.add_output('s_eff', shape=1,
                        desc='Scalar for design adiabatic efficiency')
        self.add_output('s_Wc', shape=1,
                        desc='Scalar for design corrected mass flow rate')

        self.declare_partials('s_Nc', ['Nc', 'NcMap'])
        self.declare_partials('s_PR', ['PR', 'PRmap'])
        self.declare_partials('s_eff', ['eff', 'effMap'])
        self.declare_partials('s_Wc', ['Wc', 'WcMap'])

    def compute(self, inputs, outputs):
        outputs['s_Nc'] = inputs['Nc'] / inputs['NcMap']
        outputs['s_PR'] = (inputs['PR'] - 1) / (inputs['PRmap'] - 1)
        outputs['s_eff'] = inputs['eff'] / inputs['effMap']
        outputs['s_Wc'] = inputs['Wc'] / inputs['WcMap']

    def compute_partials(self, inputs, J):
        J['s_Nc', 'Nc'] = 1. / inputs['NcMap']
        J['s_Nc', 'NcMap'] = -inputs['Nc'] / inputs['NcMap']**2
        J['s_PR', 'PR'] = 1. / (inputs['PRmap'] - 1)
        J['s_PR', 'PRmap'] = -(inputs['PR'] - 1.) / (inputs['PRmap'] - 1.)**2
        J['s_eff', 'eff'] = 1. / inputs['effMap']
        J['s_eff', 'effMap'] = -inputs['eff'] * inputs['effMap']**(-2)
        J['s_Wc', 'Wc'] = 1. / inputs['WcMap']
        J['s_Wc', 'WcMap'] = -inputs['Wc'] * inputs['WcMap']**(-2)

class ScaledMapValues(om.ExplicitComponent):
    """Computes scaled map values for off-design mode"""

    def setup(self):

        self.add_input('effMap', val=2.0, desc='Efficiency from unscaled map')
        self.add_input('PRmap', val=2.0,
                       desc='Pressure ratio from unscaled map')
        self.add_input('WcMap', val=2.0, units='lbm/s',
                       desc='Corrected mass flow rate from unscaled map')
        self.add_input('NcMap', val=2.0, units='rpm',
                       desc='Corrected shaft speed from unscaled map')
        self.add_input('s_PR', val=2.0,
                       desc='Scalar for design corrected pressure ratio')
        self.add_input('s_eff', val=2.0,
                       desc='Scalar for design corrected adiabatic efficiency')
        self.add_input('s_Wc', val=2.0,
                       desc='Scalar for design corrected mass flow rate')
        self.add_input('s_Nc', val=2.0,
                       desc='Scalar for design corrected speed')

        self.add_output('PR', shape=1, desc='Pressure ratio', lower=1.00001)
        self.add_output('eff', shape=1, desc='Adiabatic efficiency')
        self.add_output('Wc', shape=1,
                        desc='Corrected mass flow rate', units='lbm/s')
        self.add_output('Nc', shape=1,
                        desc='Corrected shaft speed', units='rpm')

        self.declare_partials('PR', ['PRmap', 's_PR'])
        self.declare_partials('eff', ['effMap', 's_eff'])
        self.declare_partials('Wc', ['WcMap', 's_Wc'])
        self.declare_partials('Nc', ['NcMap', 's_Nc'])

    def compute(self, inputs, outputs):
        outputs['PR'] = (inputs['PRmap'] - 1.) * inputs['s_PR'] + 1.
        outputs['eff'] = inputs['effMap'] * inputs['s_eff']
        outputs['Wc'] = inputs['WcMap'] * inputs['s_Wc']
        outputs['Nc'] = inputs['NcMap'] * inputs['s_Nc']

    def compute_partials(self, inputs, J):
        J['PR', 'PRmap'] = inputs['s_PR']
        J['PR', 's_PR'] = inputs['PRmap'] - 1.
        J['eff', 'effMap'] = inputs['s_eff']
        J['eff', 's_eff'] = inputs['effMap']
        J['Wc', 'WcMap'] = inputs['s_Wc']
        J['Wc', 's_Wc'] = inputs['WcMap']
        J['Nc', 'NcMap'] = inputs['s_Nc']
        J['Nc', 's_Nc'] = inputs['NcMap']

class CompressorMap(om.Group):
    """Runs design and off-design mode compressor map calculations"""

    def initialize(self):
        self.options.declare('map_data', default=NCP01)
        self.options.declare('design', default=True)
        self.options.declare('interp_method', default='slinear')
        self.options.declare('extrap', default=False)

    def setup(self):

        map_data = self.options['map_data']
        design = self.options['design']
        method = self.options['interp_method']
        extrap = self.options['extrap']

        params = map_data.param_data
        outputs = map_data.output_data

        # Define map which will be used
        readmap = om.MetaModelStructuredComp(method=method, extrapolate=extrap)
        for p in params:
            readmap.add_input(p['name'], val=p['default'], units=p['units'], training_data=p['values'])
        for o in outputs:
            readmap.add_output(o['name'], val=o['default'], units=o['units'], training_data=o['values'])

        # Create instance of map for evaluating actual operating point
        if design:
            # In design mode, operating point specified by default values for RlineMap, NcMap and alphaMap
            mapDesPt = om.IndepVarComp()
            mapDesPt.add_output('NcMap', val=map_data.defaults['NcMap'], units='rpm')
            mapDesPt.add_output('RlineMap', val=map_data.defaults['RlineMap'], units=None)
            self.add_subsystem('mapDesPt', subsys=mapDesPt, promotes=['*'])

            # Evaluate map using design point values
            self.add_subsystem('map', readmap, promotes_inputs=['RlineMap', 'NcMap', 'alphaMap'],
                                promotes_outputs=['effMap', 'PRmap', 'WcMap'])

            # Compute map scalars based on input PR, eff, Nc and Wc as well as unscaled map values
            self.add_subsystem('scalars', MapScalars(),
                                promotes_inputs=['PR', 'eff', 'Nc', 'Wc', 'NcMap', 'effMap', 'PRmap', 'WcMap'],
                                promotes_outputs=['s_Nc', 's_PR', 's_eff', 's_Wc'])

        else:
            # In off-design mode, RlineMap, NcMap and alphaMap are input to map
            self.add_subsystem('map', readmap, promotes_inputs=['RlineMap', 'NcMap', 'alphaMap'],
                                promotes_outputs=['effMap', 'PRmap', 'WcMap'])

            # Compute scaled map outputs base on input scalars and unscaled map values
            self.add_subsystem('scaledOutput', ScaledMapValues(),
                                promotes_inputs=['s_PR', 's_eff', 's_Wc', 's_Nc', 'NcMap', 'effMap', 'PRmap', 'WcMap'],
                                promotes_outputs=['PR', 'eff'])

            # Use balance component to vary NcMap and RlineMap to match incoming corrected flow and speed
            map_bal = om.BalanceComp()
            map_bal.add_balance('NcMap', val=map_data.defaults['NcMap'], units='rpm', eq_units='rpm')
            map_bal.add_balance('RlineMap', val=map_data.defaults['RlineMap'], units=None,
                                eq_units='lbm/s', lower=map_data.RlineStall)
            self.add_subsystem(name='map_bal', subsys=map_bal,
                                promotes_inputs=[('lhs:NcMap','Nc'),('lhs:RlineMap','Wc')],
                                promotes_outputs=['NcMap', 'RlineMap'])
            self.connect('scaledOutput.Nc','map_bal.rhs:NcMap')
            self.connect('scaledOutput.Wc','map_bal.rhs:RlineMap')

        # Define the Rline corresponding to stall
        RlineStall = om.IndepVarComp()
        RlineStall.add_output('RlineStall', val=map_data.RlineStall, units=None)
        self.add_subsystem('stall_R', subsys=RlineStall)

        # Evaluate map for the constant speed stall margin (SMN)
        SMN_map = om.MetaModelStructuredComp(method=method, extrapolate=extrap)
        for p in params:
            SMN_map.add_input(p['name'], val=p['default'], units=p['units'], training_data=p['values'])
        for o in outputs:
            SMN_map.add_output(o['name'], val=o['default'], units=o['units'], training_data=o['values'])

        self.add_subsystem('SMN_map', SMN_map, promotes_inputs=['NcMap', 'alphaMap'])
        self.connect('stall_R.RlineStall', 'SMN_map.RlineMap')

        # Evaluate map for the constant speed stall margin (SMN)
        SMW_map = om.MetaModelStructuredComp(method=method, extrapolate=extrap)
        for p in params:
            SMW_map.add_input(p['name'], val=p['default'], units=p['units'], training_data=p['values'])
        for o in outputs:
            SMW_map.add_output(o['name'], val=o['default'], units=o['units'], training_data=o['values'])
        self.add_subsystem('SMW_map', SMW_map, promotes_inputs=['alphaMap'])
        self.connect('stall_R.RlineStall', 'SMW_map.RlineMap')

        # Use balance to vary NcMap on SMW map to hold corrected flow constant
        SMW_bal = om.BalanceComp()
        SMW_bal.add_balance('NcMap', val=map_data.defaults['NcMap'], units='rpm', eq_units='lbm/s')
        self.add_subsystem(name='SMW_bal', subsys=SMW_bal)
        self.connect('SMW_bal.NcMap', 'SMW_map.NcMap')
        self.connect('WcMap','SMW_bal.lhs:NcMap')
        self.connect('SMW_map.WcMap','SMW_bal.rhs:NcMap')

        # Compute the stall margins
        self.add_subsystem('stall_margins', StallCalcs(),
                                promotes_inputs=[('PR_actual','PRmap'),('Wc_actual','WcMap')],
                                promotes_outputs=['SMN','SMW'])
        self.connect('SMN_map.PRmap', 'stall_margins.PR_SMN')
        self.connect('SMW_map.PRmap', 'stall_margins.PR_SMW')
        self.connect('SMN_map.WcMap', 'stall_margins.Wc_SMN')

if __name__ == "__main__":
    from pycycle.maps.ncp01 import NCP01

    p1 = om.Problem()
    ivc = p1.model.add_subsystem(
        'ivc', om.IndepVarComp(), promotes=['*'])
    # Design variables
    ivc.add_output('alphaMap', 0.0)
    ivc.add_output('PR', 2.0)
    ivc.add_output('Nc', 1000.0, units='rpm')
    ivc.add_output('eff', .9)
    ivc.add_output('Wc', 3000., units='lbm/s')

    # Off-design variables
    # ivc.add_output('alphaMap', 0.0)
    # ivc.add_output('Nc', 1000.0, units='rpm')
    # ivc.add_output('Wc', 3000., units='lbm/s')
    # ivc.add_output('s_Nc', 1.0)
    # ivc.add_output('s_Wc', 1.0)
    # ivc.add_output('s_PR', 1.0)
    # ivc.add_output('s_eff', 1.0)

    p1.model.add_subsystem('map', CompressorMap(
        map_data=NCP01, design=True), promotes=['*'])
    p1.setup()

    # exit()

    p1.run_model()
    p1.check_partials()

    # print('s_PRdes: ', p1['s_PRdes'])
    # print('s_effDes: ', p1['s_effDes'])
    # print('s_NcDes: ', p1['s_NcDes'])
    # print('s_WcDes: ', p1['s_WcDes'])
    # print(p1['shaftNc.NcMap'])
    # print(p1['readMap.PRmap'])
    # print(p1['readMap.effMap'])
    # print(p1['readMap.WcMap'])

    # print('Eff: ', p1['eff'])
    # print('PR: ', p1['PR'])
    # print('Wc: ', p1['Wc'])

    # p2 = Problem()
    # p2.model = CompressorMap(map_data=NCP01, design=False)
    # p2.setup()

    # p2['s_PRdes'] = 2.0
    # p2['s_NcDes'] = 1000.0
    # p2['s_effDes'] = 0.983606557377
    # p2['s_WcDes'] = 0.937500146484
    # p2['Nc'] = 900.0
    # p2['RlineMap'] = 2.0
    # p2['alphaMap'] = 0.0

    # p2.run_model()

    # print('s_PRdes: ', p2['s_PRdes'])
    # print('s_effDes: ', p2['s_effDes'])
    # print('s_NcDes: ', p2['s_NcDes'])
    # print('s_WcDes: ', p2['s_WcDes'])
    # print(p2['shaftNc.NcMap'])
    # print(p2['readMap.PRmap'])
    # print(p2['readMap.effMap'])
    # print(p2['readMap.WcMap'])

    # print('Eff: ', p2['eff'])
    # print('PR: ', p2['PR'])
    # print('Wc: ', p2['Wc'])


text:
<?php

namespace FOS\FacebookBundle\Twig\Extension;

use FOS\FacebookBundle\Templating\Helper\FacebookHelper;
use Symfony\Component\DependencyInjection\ContainerInterface;

class FacebookExtension extends \Twig_Extension
{
    protected $container;

    /**
     * Constructor.
     *
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * Returns a list of global functions to add to the existing list.
     *
     * @return array An array of global functions
     */
    public function getFunctions()
    {
        return array(
            'facebook_initialize' => new \Twig_Function_Method($this, 'renderInitialize', array('is_safe' => array('html'))),
            'facebook_login_button' => new \Twig_Function_Method($this, 'renderLoginButton', array('is_safe' => array('html'))),
            'facebook_logout_url' => new \Twig_Function_Method($this, 'renderLogoutUrl', array('is_safe' => array('html'))),
        );
    }

    /**
     * Returns the name of the extension.
     *
     * @return string The extension name
     */
    public function getName()
    {
        return 'facebook';
    }

    /**
     * @see FacebookHelper::initialize()
     */
    public function renderInitialize($parameters = array(), $name = null)
    {
        return $this->container->get('fos_facebook.helper')->initialize($parameters, $name ?: 'FOSFacebookBundle::initialize.html.twig');
    }

    /**
     * @see FacebookHelper::loginButton()
     */
    public function renderLoginButton($parameters = array(), $name = null)
    {
        return $this->container->get('fos_facebook.helper')->loginButton($parameters, $name ?: 'FOSFacebookBundle::loginButton.html.twig');
    }

    /**
     * @see FacebookHelper::logoutUrl()
     */
    public function renderLogoutUrl($parameters = array(), $name = null)
    {
        return $this->container->get('fos_facebook.helper')->logoutUrl($parameters);
    }
}


text:
import Description from '../index';

import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';

describe('<Description />', () => {
  it('should render a prop', () => {
    const id = 'testId';
    const renderedComponent = shallow(
      <Description id={id} />
    );
    expect(renderedComponent.prop('id')).toEqual(id);
  });

  it('should render its text', () => {
    const children = 'Text';
    const renderedComponent = shallow(
      <Description>{children}</Description>
    );
    expect(renderedComponent.contains(children)).toEqual(true);
  });
});


text: /* starter app.css */


text:
from __future__ import division
import pywikibot
import re
from pywikibot import textlib
from pywikibot.page import Page

site = pywikibot.getSite()
yes_all = False
for arg in pywikibot.handleArgs():
  if arg in ["--all", "-a"]:
    yes_all = True

def get_name(page):
  if page.title().startswith("File:"):
    return page.title(withNamespace = False)
  else:
    return source.title()

def replace(source_name, target_name):
  source = Page(site, "")
  target = Page(site, "")
  old = get_name(source)
  new = get_name(target)

  # Move all references
  for reference in source.getReferences(follow_redirects=False):
    old_text = reference.text
    reference.text = old_text.replace(old, new)
    pywikibot.showDiff(old_text, reference.text)

def peek(l):
  return l[len(l) - 1] if len(l) > 0 else None

from collections import namedtuple
def split_sections(content):
  """
  This method splits the text given in the parameter into sections. Currently it doesn't detect

 blocks or using headers in templates.

  The result is a list of all sections. Each section is a 5-tuple with the following values:
  0. The header which is the part between the equal signs. Is None for the first section if the page doesn't start with a header.
  1. The content following after it until the next header. Is never None.
  2. The parent section. None if there is none.
  3. The child sections as a list of sections. The resulting list also contains them.
  4. The depth as the number of equals signs. So there might be gaps, but the parent section has always a lower depth value and the children sections a higher depth value. Later sibling sections might have higher depth values than the current section. Previous sibling sections have always the same depth value. If there is no header defaults to zero.

  @param content: The content as a string
  @return: a list with all sections
  """
  Section = namedtuple('Section', 'title content parent children depth')

  section_regex = re.compile(r"(?:\A|^(?P<es>=+) *(?P<title>[^\n\r]+?) *(?P=es))(?P<content>[^=].*?)(?=(?:^=+ *[^=]+ *=+|\Z))", re.M | re.S)
  super_sections = [] # use as stack
  sections = []
  for match in section_regex.finditer(content):
    depth = 0 if match.group('es') is None else len(match.group('es'))
    while len(super_sections) > 0 and peek(super_sections).depth > depth:
      super_section.pop()
    super_section = peek(super_sections)
    section = Section(match.group('title'), match.group('content'), super_section, [], depth)
    if super_section is not None:
      super_section.parent += [section]
    sections += [section]
  return sections

# Automatically read the requests
requests = Page(site, "Project:Request Move#Requests")
#TODO: More general regex? Or manuall reading?
row_regex = re.compile(r"(?:\|\||\n\|)[ \t]*((?:\[\[.*\]\]|(?:\[\[.*\]\]|[^-}])(?:\[\[.*\]\]|[^|\n])*(?:\[\[.*\]\]|[^|\n ])))?")
sections = split_sections(requests.text)
print sections
for tested_section in sections:
  if tested_section.title == "Completed":
    section = tested_section.content
# Get line by line
for row in section.split("|-"):
  elements = [match.group(1) for match in row_regex.finditer(row)]
  if len(elements) == 2:
    elements += ['No reason given.']
  if len(elements) == 3:
    if pywikibot.inputChoice("Move '{}' to '{}'? Reason: {}".format(*elements), ['Yes', 'No'], ['y', 'n'], 'n', y):
      reason = raw_input("What is the reason for moving the page? Input nothing to use current reason.")
      if len(reason) > 0:
        elements[2] = reason
      Page(site, elements[0]).move(newtitle=elements[1], reason=elements[2], movetalkpage=True)

images_total = 0
if images_total == 0:
  print("No images found.")
else:
  print("Statistics: {} images, {} ({:.0%}) already marked, {} ({:.0%}) detected, {} ({:.0%}) edited.".format(images_total, images_marked, images_marked / images_total, images_detected, images_detected / images_total, images_edited, images_edited / images_total))


text:
import boto
from boto.s3.key import Key
from os import environ as env

conn = boto.connect_s3()
bucket = conn.get_bucket(env['AWS_BUCKET'])
k = bucket.get_key('record', validate=False)
k.set_contents_from_filename('tests/record.json')
k.set_acl('public-read')
k.close(fast=True)


text:
package main

import (
	"crypto/hmac"
	"crypto/sha1"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"strings"
	"time"
)

type rtcConfigResponse struct {
	LifetimeDuration   string              `json:"lifetimeDuration"`
	IceServers         []iceServerResponse `json:"iceServers"`
	BlockStatus        string              `json:"blockStatus"`
	IceTransportPolicy string              `json:"iceTransportPolicy"`
}

type iceServerResponse struct {
	URLs       []string `json:"urls"`
	Username   string   `json:"username,omitempty"`
	Credential string   `json:"credential,omitempty"`
}

func main() {
	externalIP := popVarFromEnv("EXTERNAL_IP", true, "")
	turnPort := popVarFromEnv("TURN_PORT", false, "3478")
	sharedSecret := popVarFromEnv("TURN_SHARED_SECRET", true, "")
	listenPort := popVarFromEnv("PORT", false, "8080")
	authHeaderName := popVarFromEnv("AUTH_HEADER_NAME", false, "x-auth-user")

	// Env vars for running in aggregator mode.
	discoveryDNSName := popVarFromEnv("DISCOVERY_DNS_NAME", false, "")
	discoveryPortName := popVarFromEnv("DISCOVERY_PORT_NAME", false, "turn")

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

		// Get user from auth header.
		user := r.Header.Get(authHeaderName)
		if len(user) == 0 {
			writeStatusResponse(w, http.StatusUnauthorized, fmt.Sprintf("Missing or invalid %s header", authHeaderName))
			return
		}
		// IAP uses a prefix of accounts.google.com:email, remove this to just get the email
		userToks := strings.Split(user, ":")
		user = userToks[len(userToks)-1]
		ips := make([]string, 0)

		if len(discoveryDNSName) == 0 {
			// Standard mode, use external IP to return single server.
			ips = []string{externalIP}
			resp, err := makeRTCConfig(ips, turnPort, user, sharedSecret)
			if err != nil {
				writeStatusResponse(w, http.StatusInternalServerError, "Internal server error")
				return
			}

			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			json.NewEncoder(w).Encode(resp)
		} else {
			// Aggregator mode, use DNS SRV records to build RTC config.
			// Fetch all service host and ports using SRV record of headless discovery service.
			// NOTE: The SRV record returns resolvable aliases to the endpoints, so do another lookup should return the IP.
			_, srvs, err := net.LookupSRV(discoveryPortName, "tcp", discoveryDNSName)
			if err != nil {
				log.Printf("ERROR: failed to query SRV record from %v %v: %v", discoveryDNSName, discoveryPortName, err)
				writeStatusResponse(w, http.StatusInternalServerError, "Internal server error")
				return
			}
			for _, srv := range srvs {
				addrs, err := net.LookupHost(srv.Target)
				if err != nil {
					log.Printf("ERROR: failed to query A record from %v: %v", srv.Target, err)
					writeStatusResponse(w, http.StatusInternalServerError, "Internal server error")
					return
				}
				ips = append(ips, addrs[0])
			}
		}

		resp, err := makeRTCConfig(ips, turnPort, user, sharedSecret)
		if err != nil {
			log.Printf("ERROR: failed to make RTC config: %v", err)
			writeStatusResponse(w, http.StatusInternalServerError, "Internal server error")
			return
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(resp)
	})

	log.Println(fmt.Sprintf("Listening on port %s", listenPort))
	http.ListenAndServe(fmt.Sprintf("0.0.0.0:%s", listenPort), nil)
}

func makeRTCConfig(ips []string, port, user, secret string) (rtcConfigResponse, error) {
	var resp rtcConfigResponse
	var err error

	username, credential := makeCredential(secret, user)

	stunURLs := []string{}
	turnURLs := []string{}

	for _, ip := range ips {
		stunURLs = append(stunURLs, fmt.Sprintf("stun:%s:%s", ip, port))
		turnURLs = append(turnURLs, fmt.Sprintf("turn:%s:%s?transport=udp", ip, port))
	}

	resp.LifetimeDuration = "86400s"
	resp.BlockStatus = "NOT_BLOCKED"
	resp.IceTransportPolicy = "all"
	resp.IceServers = []iceServerResponse{
		iceServerResponse{
			URLs: stunURLs,
		},
		iceServerResponse{
			URLs:       turnURLs,
			Username:   username,
			Credential: credential,
		},
	}

	return resp, err
}

// Creates credential per coturn REST API docs
// https://github.com/coturn/coturn/wiki/turnserver#turn-rest-api
// [START makeCredential]
func makeCredential(secret, user string) (string, string) {
	var username string
	var credential string

	ttlOneDay := 24 * 3600 * time.Second
	nowPlusTTL := time.Now().Add(ttlOneDay).Unix()
	// Make sure to set --rest-api-separator="-" in the coturn config.
	username = fmt.Sprintf("%d-%s", nowPlusTTL, user)

	mac := hmac.New(sha1.New, []byte(secret))
	mac.Write([]byte(username))
	credential = base64.StdEncoding.EncodeToString(mac.Sum(nil))

	return username, credential
}

// [END makeCredential]

func writeStatusResponse(w http.ResponseWriter, statusCode int, message string) {
	type statusResponse struct {
		Status string
	}
	status := statusResponse{
		Status: message,
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	json.NewEncoder(w).Encode(status)
}

func popVarFromEnv(envName string, isRequired bool, defaultValue string) string {
	value := os.Getenv(envName)
	if isRequired && len(value) == 0 {
		log.Fatalf("Missing environment variable: %s", envName)
	} else if len(value) == 0 {
		value = defaultValue
	}
	return value
}