text:
# Restme.Dapper (RESTme Dapper Wrapper)

This is a set of Dapper .Net wrappers and helpers aims to simplify data manipulations in large scaled applications without compromise of using ORM.

### Features
* Implemented based on the latest .NET Core 1.0
* Simple methods and flexible calls

### Usage

#### 1. (Optional, but good practice) Apply Db Attributes to Entities
```csharp
    [RestmeTable("Users", DefaultOrderByClauseInQuery = "Id desc")]
    public class OEliteUser : IRestmeDbEntity
    {
        [RestmeDbColumn("UserName", RestmeDbColumnType.NormalColumn)]
        public string UserName { get; set; }

        [RestmeDbColumn("Id", RestmeDbColumnType.PrimaryKey)]
        public int Id { get; set; }

        [RestmeDbColumn]
        public bool IsActive { get; set; }
    }

    //class below is a useful collection wrapper, representing a set of OEliteUser when expecting multiple records to be returned
    public class OEliteUserCollection : List<OEliteUser>, IRestmeDbEntityCollection<OEliteUser>
    {
        //particuarly useful when the returned results are paginated - this will return the total count
        public int TotalRecordsCount {get;set;}
    }
```

* **[RestmeTable()]** => *RestmeTableAttribute* is used to to define an entity class mapping with a data table/view
* **[RestmeDbColumn()]** => *RestmeDbColumnAttribute* is used to map an entity property with a data table/view column
  - You can simply add [ResmeDbColumn] without any value, in which case the Property's name will be automatically mapped as the data table's column name.

#### 2. (Optional, but best practice) Define your DbContext
It'll be nice to have a DbContext similar like the Entity Framework does, although we certainly don't want same level of complexity which affects performance!

Our DbContext concept here is to provie a Schema structure of the database so when we do the entity-related queries, we can focus on the "primary" entity table, and expand the query accordingly. The RESTmd Dapper Wrapper will take care of the SQL query, compose them accordingly and then pass into the ADO.NET connection which then quickly returns the expected results.

An example of the DbContext can be like this:
```csharp
    public partial class DbCentre : RestmeDb
    {
        private const string _connectionString = "YOUR CONNECTION STRING";

        public DbCentre():base(_connectionString) {}

        //Representation of the Users table (and map with User class in your code)
        public OEliteUserQuery Users => DbQuery<OEliteUser, OEliteUserQuery>();

        //Representation of the Logins table (and map with UserLogin class in your code)
        public UserLoginQuery UserLogins => DbQuery<UserLogin, UserLoginQuery>();

    }
```

NOTE, here I mentioned *OEliteUserQuery*, which is a class defined based on RestmeDbQuery, this is optional, however by inheriting from RestmeDbQuery it will allow you to customize the Db Execution queries such as custom select/insert/update/delete based on your particular needs

```csharp
public class OEliteUserDbQuery : RestmeDbQuery<OEliteUser>
{
    public OEliteUserDbQuery(RestmeDb dbCentre) : base(dbCentre)
    {
    }

    //example: we provided a custom table source for SELECT query, which instead of using the normal "Users" table, we query against a view called "vw_Users".
    public override string CustomSelectTableSource => "vw_Users";

    //most other actions/methods are customizable by overriding them, enjoy
}
```

#### 3. Query and CRUD from database
```csharp
//example 1.  passing bespoke parameters (most popular use case)
public async Task<OEliteUser> GetUserAsync(int userId)
{
    //Use a custom DbContext class (e.g. DbCentre) as below, or use RestmeDb(connStr)  directly if you didn't create custom DbContext as shown above
    using(var dbCentre = new DbCentre())
    {
        //e.g. get an user by query against Users.Id column
        var user = await dbCentre.Users.Query("Id=@Id").Params(new {Id = userId}).FetchAsync<OSite>();
    }
}

//example 2. passing exsting object (Same type) which has multiple parameters preset and defined in custom DbQuery (such as OEliteUserQuery defined in example above)
public async Task<OEliteUser> GetUserAsync(OEliteUser user)
{
    using(var dbCentre = new DbCentre())
    {
        var user = await dbCentre.Users.Query("Id=@Id").FetchAsync<OSite>();
    }
}

```
In example 2, RestmeDb will feed all found property values of object "user" to your query (here, only property "Id" will be used because there's only "@Id" parameter in the SQL query)

```csharp

//example 3. paginated set of search results
public async Task<List<OEliteUser>> FindUsersAsync(int pageIndex, int pageSize, string keyword, bool isActive)
{
    using (var dbCentre = new DbCentre())
    {
        var query = "username like '%@keyword%' and isActive = @isActive";

        result = await dbCentre.Users.Query(query)
                .Params(new {keyword = keyword, isActive = isActive})
                .Paginated(pageIndex, pageSize, "id desc")
                .FetchAsync<OEliteUser, OEliteUserCollection>();
    }
}
```

```csharp

//example 4. updated entire object
public async Task<bool> UpdateUserAsync(OEliteUser user)
{
    var affectedRowCount = await dbCentre.Users.Update(user, "Id=@Id").ExecuteAsync();
    return affectedRowCount > 0;
}
```
NOTE: there are more where clause control and parameters in the Update() method, enjoy.

```csharp

//example 5. delete record using entity object
public async Task<bool> DeleteUserAsync(OEliteUser user)
{
    var affectedRowCount = await dbCentre.Users.Delete(user, "Id=@Id").ExecuteAsync();
    return affectedRowCount > 0;
}

//example 6. delete record using parameters
public async Task<bool> DeleteUserAsync(int userId)
{
    var affectedRowCount = await dbCentre.Users.Delete("Id=@Id", new {Id = userId}).ExecuteAsync();
    return affectedRowCount > 0;
}
```

### Contributions

This is a simple library just recently created, your contribution is welcomed.

### License
Released under [MIT License](http://choosealicense.com/licenses/mit).


text:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<RootFolder xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ESMoL.xsd">

  <DesignFolder name="Imported Models">
    <ModelsFolder name="Newdiscretezeropole00000000">
      <Dataflow name="Dataflow">
        <Subsystem BlockType="Model" Deadline="0" Description="" Name="discretezeropole" Period="0" Priority="0" SampleTime="0" Tag="" UserData="" name="discretezeropole">
          <Line Name="" _id="idC" dstLine_end_="idD" srcLine_end_="idB"/>
          <Line Name="" _id="idF" dstLine_end_="id4" srcLine_end_="ide"/>
          <Line Name="" _id="id11" dstLine_end_="id12" srcLine_end_="idB"/>
          <Line Name="" _id="id14" dstLine_end_="id5" srcLine_end_="id13"/>
          <Line Name="" _id="id16" dstLine_end_="id17" srcLine_end_="idB"/>
          <Line Name="" _id="id19" dstLine_end_="id7" srcLine_end_="id18"/>
          <Line Name="" _id="id1B" dstLine_end_="id1C" srcLine_end_="idB"/>
          <Line Name="" _id="id1e" dstLine_end_="id6" srcLine_end_="id1D"/>
          <Line Name="" _id="id20" dstLine_end_="id21" srcLine_end_="idB"/>
          <Line Name="" _id="id23" dstLine_end_="id8" srcLine_end_="id22"/>
          <OutputPort Number="1" _id="id4" name="Out1" srcLine="idF">
            <TypeBaseRef MemberIndex="0" _id="id27" name="double" ref="id25"/>
          </OutputPort>
          <OutputPort Number="2" _id="id5" name="Out2" srcLine="id14">
            <TypeBaseRef MemberIndex="0" _id="id29" name="double" ref="id25"/>
          </OutputPort>
          <OutputPort Number="3" _id="id6" name="Out3" srcLine="id1e">
            <TypeBaseRef MemberIndex="0" _id="id2B" name="double" ref="id25"/>
          </OutputPort>
          <OutputPort Number="4" _id="id7" name="Out7" srcLine="id19">
            <TypeBaseRef MemberIndex="0" _id="id2D" name="double" ref="id25"/>
          </OutputPort>
          <OutputPort Number="5" _id="id8" name="Out8" srcLine="id23">
            <TypeBaseRef MemberIndex="0" _id="id2F" name="double" ref="id25"/>
          </OutputPort>
          <Primitive BlockType="Constant" Description="" Name="Constant1" Priority="0" SampleTime="0" Tag="" UserData="" name="Constant1">
            <OutputPort Number="1" _id="idB" dstLine="idC id11 id16 id1B id20" name="Out_1">
              <TypeBaseRef MemberIndex="0" _id="id30" name="double" ref="id25"/>
            </OutputPort>
            <Parameter Value="inf" name="FramePeriod"/>
            <Parameter Value="off" name="LockScale"/>
            <Parameter Value="double" name="OutDataTypeStr"/>
            <Parameter Value="[]" name="OutMax"/>
            <Parameter Value="[]" name="OutMin"/>
            <Parameter Value="Sample based" name="SamplingMode"/>
            <Parameter Value="6" name="Value"/>
            <Parameter Value="on" name="VectorParams1D"/>
            <Parameter Value="double" name="ParamDataTypeStr"/>
          </Primitive>
          <Primitive BlockType="DiscreteZeroPole" Description="" Name="Discrete
Zero-Pole" Priority="0" SampleTime="1" Tag="" UserData="" name="Discrete
Zero-Pole">
            <InputPort Number="1" _id="idD" name="In_1" srcLine="idC">
              <TypeBaseRef MemberIndex="0" _id="id32" name="double" ref="id25"/>
            </InputPort>
            <OutputPort Number="1" _id="ide" dstLine="idF" name="Out_1">
              <TypeBaseRef MemberIndex="0" _id="id34" name="double" ref="id25"/>
            </OutputPort>
            <Parameter Value="2" name="Gain"/>
            <Parameter Value="[]" name="Poles"/>
            <Parameter Value="Auto" name="RTWStateStorageClass"/>
            <Parameter Value="" name="RTWStateStorageTypeQualifier"/>
            <Parameter Value="" name="StateIdentifier"/>
            <Parameter Value="off" name="StateMustResolveToSignalObject"/>
            <Parameter Value="[]" name="Zeros"/>
            <Parameter Value="double" name="ParamDataTypeStr"/>
          </Primitive>
          <Primitive BlockType="DiscreteZeroPole" Description="" Name="Discrete
Zero-Pole1" Priority="0" SampleTime="1" Tag="" UserData="" name="Discrete
Zero-Pole1">
            <InputPort Number="1" _id="id12" name="In_1" srcLine="id11">
              <TypeBaseRef MemberIndex="0" _id="id36" name="double" ref="id25"/>
            </InputPort>
            <OutputPort Number="1" _id="id13" dstLine="id14" name="Out_1">
              <TypeBaseRef MemberIndex="0" _id="id38" name="double" ref="id25"/>
            </OutputPort>
            <Parameter Value="1" name="Gain"/>
            <Parameter Value="[0.05317]" name="Poles"/>
            <Parameter Value="Auto" name="RTWStateStorageClass"/>
            <Parameter Value="" name="RTWStateStorageTypeQualifier"/>
            <Parameter Value="" name="StateIdentifier"/>
            <Parameter Value="off" name="StateMustResolveToSignalObject"/>
            <Parameter Value="[]" name="Zeros"/>
            <Parameter Value="double" name="ParamDataTypeStr"/>
          </Primitive>
          <Primitive BlockType="DiscreteZeroPole" Description="" Name="Discrete
Zero-Pole2" Priority="0" SampleTime="1" Tag="" UserData="" name="Discrete
Zero-Pole2">
            <InputPort Number="1" _id="id17" name="In_1" srcLine="id16">
              <TypeBaseRef MemberIndex="0" _id="id3A" name="double" ref="id25"/>
            </InputPort>
            <OutputPort Number="1" _id="id18" dstLine="id19" name="Out_1">
              <TypeBaseRef MemberIndex="0" _id="id3C" name="double" ref="id25"/>
            </OutputPort>
            <Parameter Value="0.20000000000000001" name="Gain"/>
            <Parameter Value="[-0.5]" name="Poles"/>
            <Parameter Value="Auto" name="RTWStateStorageClass"/>
            <Parameter Value="" name="RTWStateStorageTypeQualifier"/>
            <Parameter Value="" name="StateIdentifier"/>
            <Parameter Value="off" name="StateMustResolveToSignalObject"/>
            <Parameter Value="[-5]" name="Zeros"/>
            <Parameter Value="double" name="ParamDataTypeStr"/>
          </Primitive>
          <Primitive BlockType="DiscreteZeroPole" Description="" Name="Discrete
Zero-Pole3" Priority="0" SampleTime="1" Tag="" UserData="" name="Discrete
Zero-Pole3">
            <InputPort Number="1" _id="id1C" name="In_1" srcLine="id1B">
              <TypeBaseRef MemberIndex="0" _id="id3e" name="double" ref="id25"/>
            </InputPort>
            <OutputPort Number="1" _id="id1D" dstLine="id1e" name="Out_1">
              <TypeBaseRef MemberIndex="0" _id="id40" name="double" ref="id25"/>
            </OutputPort>
            <Parameter Value="1" name="Gain"/>
            <Parameter Value="[2.482002 0.332997]" name="Poles"/>
            <Parameter Value="Auto" name="RTWStateStorageClass"/>
            <Parameter Value="" name="RTWStateStorageTypeQualifier"/>
            <Parameter Value="" name="StateIdentifier"/>
            <Parameter Value="off" name="StateMustResolveToSignalObject"/>
            <Parameter Value="[]" name="Zeros"/>
            <Parameter Value="double" name="ParamDataTypeStr"/>
          </Primitive>
          <Primitive BlockType="DiscreteZeroPole" Description="" Name="Discrete
Zero-Pole4" Priority="0" SampleTime="1" Tag="" UserData="" name="Discrete
Zero-Pole4">
            <InputPort Number="1" _id="id21" name="In_1" srcLine="id20">
              <TypeBaseRef MemberIndex="0" _id="id42" name="double" ref="id25"/>
            </InputPort>
            <OutputPort Number="1" _id="id22" dstLine="id23" name="Out_1">
              <TypeBaseRef MemberIndex="0" _id="id44" name="double" ref="id25"/>
            </OutputPort>
            <Parameter Value="0.20000000000000001" name="Gain"/>
            <Parameter Value="[2.482002 0.332997]" name="Poles"/>
            <Parameter Value="Auto" name="RTWStateStorageClass"/>
            <Parameter Value="" name="RTWStateStorageTypeQualifier"/>
            <Parameter Value="" name="StateIdentifier"/>
            <Parameter Value="off" name="StateMustResolveToSignalObject"/>
            <Parameter Value="[-5]" name="Zeros"/>
            <Parameter Value="double" name="ParamDataTypeStr"/>
          </Primitive>
        </Subsystem>
      </Dataflow>
      <Stateflow name="Stateflow"/>
    </ModelsFolder>
  </DesignFolder>

  <Types name="Types">
    <Matrix Type="double" _id="id25" columns="1" name="double" referedbyTypeStructRef="id27 id29 id2B id2D id2F id30 id32 id34 id36 id38 id3A id3C id3e id40 id42 id44" rows="1"/>
  </Types>

</RootFolder>

redpajama_set_name: RedPajamaGithub


text:
#pragma once

#if ENABLE(SVG_FONTS)

#include "CachedFontClient.h"
#include "CachedResourceHandle.h"
#include "SVGElement.h"

namespace WebCore {

class CSSFontFaceSrcValue;

class SVGFontFaceUriElement final : public SVGElement, public CachedFontClient {
public:
    static Ref<SVGFontFaceUriElement> create(const QualifiedName&, Document&);

    virtual ~SVGFontFaceUriElement();

    Ref<CSSFontFaceSrcValue> srcValue() const;

private:
    SVGFontFaceUriElement(const QualifiedName&, Document&);

    void parseAttribute(const QualifiedName&, const AtomicString&) final;
    void childrenChanged(const ChildChange&) final;
    InsertedIntoAncestorResult insertedIntoAncestor(InsertionType, ContainerNode&) final;
    bool rendererIsNeeded(const RenderStyle&) final { return false; }

    void loadFont();

    CachedResourceHandle<CachedFont> m_cachedFont;
};

} // namespace WebCore

#endif // ENABLE(SVG_FONTS)


text:
<?php

namespace Oro\Bundle\EntityExtendBundle\Tests\Unit\Tools\DumperExtensions;

use Oro\Bundle\EntityConfigBundle\Config\Config;
use Oro\Bundle\EntityConfigBundle\Config\Id\EntityConfigId;
use Oro\Bundle\EntityExtendBundle\Tools\DumperExtensions\MultipleAssociationEntityConfigDumperExtension;
use Oro\Bundle\EntityExtendBundle\Tools\ExtendConfigDumper;

class MultipleAssociationEntityConfigDumperExtensionTest extends \PHPUnit_Framework_TestCase
{
    const ASSOCIATION_SCOPE = 'test_scope';
    const ATTR_NAME         = 'items';

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $configManager;

    /** @var \PHPUnit_Framework_MockObject_MockObject */
    protected $associationBuilder;

    public function setUp()
    {
        $this->configManager = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Config\ConfigManager')
            ->disableOriginalConstructor()
            ->getMock();
        $this->associationBuilder = $this->getMockBuilder('Oro\Bundle\EntityExtendBundle\Tools\AssociationBuilder')
            ->disableOriginalConstructor()
            ->getMock();
    }

    public function testSupportsPostUpdate()
    {
        $extension = $this->getExtensionMock();

        $this->configManager->expects($this->never())
            ->method('getProvider');

        $this->assertFalse(
            $extension->supports(ExtendConfigDumper::ACTION_POST_UPDATE)
        );
    }

    public function testSupportsPreUpdate()
    {
        $extension = $this->getExtensionMock(
            ['getAssociationScope', 'getAssociationAttributeName']
        );

        $extension->expects($this->once())
            ->method('getAssociationScope')
            ->will($this->returnValue(self::ASSOCIATION_SCOPE));
        $extension->expects($this->exactly(2))
            ->method('getAssociationAttributeName')
            ->will($this->returnValue(self::ATTR_NAME));

        $config1 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity1'));
        $config1->set(self::ATTR_NAME, ['Test\SourceEntity']);
        $config2 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity2'));

        $this->setTargetEntityConfigsExpectations([$config1, $config2]);

        $this->assertTrue(
            $extension->supports(ExtendConfigDumper::ACTION_PRE_UPDATE)
        );
    }

    public function testSupportsPreUpdateNoApplicableTargetEntities()
    {
        $extension = $this->getExtensionMock(
            ['getAssociationScope', 'getAssociationAttributeName']
        );

        $extension->expects($this->once())
            ->method('getAssociationScope')
            ->will($this->returnValue(self::ASSOCIATION_SCOPE));
        $extension->expects($this->once())
            ->method('getAssociationAttributeName')
            ->will($this->returnValue(self::ATTR_NAME));

        $config1 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity1'));

        $this->setTargetEntityConfigsExpectations([$config1]);

        $this->assertFalse(
            $extension->supports(ExtendConfigDumper::ACTION_PRE_UPDATE)
        );
    }

    public function testPreUpdate()
    {
        $extension = $this->getExtensionMock(
            ['getAssociationScope', 'getAssociationAttributeName', 'getAssociationKind']
        );

        $extension->expects($this->once())
            ->method('getAssociationScope')
            ->will($this->returnValue(self::ASSOCIATION_SCOPE));
        $extension->expects($this->exactly(3))
            ->method('getAssociationAttributeName')
            ->will($this->returnValue(self::ATTR_NAME));
        $extension->expects($this->once())
            ->method('getAssociationKind')
            ->will($this->returnValue('test'));

        $config1 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity1'));
        $config1->set(self::ATTR_NAME, ['Test\SourceEntity']);
        $config2 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity2'));

        $this->setTargetEntityConfigsExpectations([$config1, $config2]);

        $this->associationBuilder->expects($this->once())
            ->method('createManyToManyAssociation')
            ->with('Test\SourceEntity', 'Test\Entity1', 'test');

        $extension->preUpdate();
    }

    public function testPreUpdateForManyToOne()
    {
        $extension = $this->getExtensionMock(
            ['getAssociationScope', 'getAssociationAttributeName', 'getAssociationKind', 'getAssociationType']
        );

        $extension->expects($this->once())
            ->method('getAssociationScope')
            ->will($this->returnValue(self::ASSOCIATION_SCOPE));
        $extension->expects($this->exactly(3))
            ->method('getAssociationAttributeName')
            ->will($this->returnValue(self::ATTR_NAME));
        $extension->expects($this->once())
            ->method('getAssociationKind')
            ->will($this->returnValue('test'));
        $extension->expects($this->once())
            ->method('getAssociationType')
            ->will($this->returnValue('manyToOne'));

        $config1 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity1'));
        $config1->set(self::ATTR_NAME, ['Test\SourceEntity']);
        $config2 = new Config(new EntityConfigId(self::ASSOCIATION_SCOPE, 'Test\Entity2'));

        $this->setTargetEntityConfigsExpectations([$config1, $config2]);

        $this->associationBuilder->expects($this->once())
            ->method('createManyToOneAssociation')
            ->with('Test\SourceEntity', 'Test\Entity1', 'test');

        $extension->preUpdate();
    }

    /**
     * @param string[] $methods
     *
     * @return MultipleAssociationEntityConfigDumperExtension|\PHPUnit_Framework_MockObject_MockObject
     */
    protected function getExtensionMock(array $methods = [])
    {
        return $this->getMockForAbstractClass(
            'Oro\Bundle\EntityExtendBundle\Tools\DumperExtensions\MultipleAssociationEntityConfigDumperExtension',
            [$this->configManager, $this->associationBuilder],
            '',
            true,
            true,
            true,
            $methods
        );
    }

    protected function setTargetEntityConfigsExpectations(array $configs = [])
    {
        $configProvider = $this->getMockBuilder('Oro\Bundle\EntityConfigBundle\Provider\ConfigProvider')
            ->disableOriginalConstructor()
            ->getMock();
        $configProvider->expects($this->once())
            ->method('getConfigs')
            ->will($this->returnValue($configs));
        $this->configManager->expects($this->once())
            ->method('getProvider')
            ->with(self::ASSOCIATION_SCOPE)
            ->will($this->returnValue($configProvider));
    }
}


text:
package org.elasticsearch.action.percolate;

import com.google.common.collect.Lists;
import org.elasticsearch.ElasticsearchGenerationException;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.CompositeIndicesRequest;
import org.elasticsearch.action.IndicesRequest;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.support.broadcast.BroadcastOperationRequest;
import org.elasticsearch.client.Requests;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static org.elasticsearch.action.ValidateActions.addValidationError;

/**
 *
 */
public class PercolateRequest extends BroadcastOperationRequest<PercolateRequest> implements CompositeIndicesRequest {

    private String documentType;
    private String routing;
    private String preference;
    private GetRequest getRequest;
    private boolean onlyCount;

    private BytesReference source;
    private boolean unsafe;

    private BytesReference docSource;

    // Used internally in order to compute tookInMillis, TransportBroadcastOperationAction itself doesn't allow
    // to hold it temporarily in an easy way
    long startTime;

    public PercolateRequest() {
    }

    public PercolateRequest(PercolateRequest request, BytesReference docSource) {
        super(request.indices());
        this.documentType = request.documentType();
        this.routing = request.routing();
        this.preference = request.preference();
        this.source = request.source;
        this.docSource = docSource;
        this.onlyCount = request.onlyCount;
        this.startTime = request.startTime;
    }

    @Override
    public List<? extends IndicesRequest> subRequests() {
        List<IndicesRequest> requests = Lists.newArrayList();
        requests.add(this);
        if (getRequest != null) {
            requests.add(getRequest);
        }
        return requests;
    }

    public String documentType() {
        return documentType;
    }

    public void documentType(String type) {
        this.documentType = type;
    }

    public String routing() {
        return routing;
    }

    public PercolateRequest routing(String routing) {
        this.routing = routing;
        return this;
    }

    public String preference() {
        return preference;
    }

    public PercolateRequest preference(String preference) {
        this.preference = preference;
        return this;
    }

    public GetRequest getRequest() {
        return getRequest;
    }

    public void getRequest(GetRequest getRequest) {
        this.getRequest = getRequest;
    }

    /**
     * Before we fork on a local thread, make sure we copy over the bytes if they are unsafe
     */
    @Override
    public void beforeLocalFork() {
        if (unsafe) {
            source = source.copyBytesArray();
            unsafe = false;
        }
    }

    public BytesReference source() {
        return source;
    }

    public PercolateRequest source(Map document) throws ElasticsearchGenerationException {
        return source(document, Requests.CONTENT_TYPE);
    }

    public PercolateRequest source(Map document, XContentType contentType) throws ElasticsearchGenerationException {
        try {
            XContentBuilder builder = XContentFactory.contentBuilder(contentType);
            builder.map(document);
            return source(builder);
        } catch (IOException e) {
            throw new ElasticsearchGenerationException("Failed to generate [" + document + "]", e);
        }
    }

    public PercolateRequest source(String document) {
        this.source = new BytesArray(document);
        this.unsafe = false;
        return this;
    }

    public PercolateRequest source(XContentBuilder documentBuilder) {
        source = documentBuilder.bytes();
        unsafe = false;
        return this;
    }

    public PercolateRequest source(byte[] document) {
        return source(document, 0, document.length);
    }

    public PercolateRequest source(byte[] source, int offset, int length) {
        return source(source, offset, length, false);
    }

    public PercolateRequest source(byte[] source, int offset, int length, boolean unsafe) {
        return source(new BytesArray(source, offset, length), unsafe);
    }

    public PercolateRequest source(BytesReference source, boolean unsafe) {
        this.source = source;
        this.unsafe = unsafe;
        return this;
    }

    public PercolateRequest source(PercolateSourceBuilder sourceBuilder) {
        this.source = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
        this.unsafe = false;
        return this;
    }

    public boolean onlyCount() {
        return onlyCount;
    }

    public void onlyCount(boolean onlyCount) {
        this.onlyCount = onlyCount;
    }

    BytesReference docSource() {
        return docSource;
    }

    @Override
    public ActionRequestValidationException validate() {
        ActionRequestValidationException validationException = super.validate();
        if (documentType == null) {
            validationException = addValidationError("type is missing", validationException);
        }
        if (source == null && getRequest == null) {
            validationException = addValidationError("source or get is missing", validationException);
        }
        if (getRequest != null && getRequest.fields() != null) {
            validationException = addValidationError("get fields option isn't supported via percolate request", validationException);
        }
        return validationException;
    }

    @Override
    public void readFrom(StreamInput in) throws IOException {
        super.readFrom(in);
        startTime = in.readVLong();
        documentType = in.readString();
        routing = in.readOptionalString();
        preference = in.readOptionalString();
        unsafe = false;
        source = in.readBytesReference();
        docSource = in.readBytesReference();
        if (in.readBoolean()) {
            getRequest = new GetRequest(null);
            getRequest.readFrom(in);
        }
        onlyCount = in.readBoolean();
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeVLong(startTime);
        out.writeString(documentType);
        out.writeOptionalString(routing);
        out.writeOptionalString(preference);
        out.writeBytesReference(source);
        out.writeBytesReference(docSource);
        if (getRequest != null) {
            out.writeBoolean(true);
            getRequest.writeTo(out);
        } else {
            out.writeBoolean(false);
        }
        out.writeBoolean(onlyCount);
    }
}


text:
<?php
// src/finalProjectBundle/Entity/Message.php

namespace finalProjectBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;
use FOS\MessageBundle\Entity\Message as BaseMessage;

/**
 * @ORM\Entity
 */
class Message extends BaseMessage
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(
     *   targetEntity="finalProjectBundle\Entity\Thread",
     *   inversedBy="messages"
     * )
     * @var \FOS\MessageBundle\Model\ThreadInterface
     */
    protected $thread;

    /**
     * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
     * @var \FOS\MessageBundle\Model\ParticipantInterface
     */
    protected $sender;

    /**
     * @ORM\OneToMany(
     *   targetEntity="finalProjectBundle\Entity\MessageMetadata",
     *   mappedBy="message",
     *   cascade={"all"}
     * )
     * @var MessageMetadata[]|Collection
     */
    protected $metadata;
}


text:
- Read [this article](https://chris.beams.io/posts/git-commit/) before writing commit messages
- `detekt` itself should not report any new errors
- This repo uses tabs!
- Use idea-code-style.xml for coding style
- Run `detektFormat` before commiting
- Make sure `when {` or `object : MyType { ... ` is on the same line as `=` eg.
```kotlin
    fun stuff(x: Int) = when(x) {
        1..10 -> ...
        else -> ...
    }
```

### When implementing new rules ...

- ... do not forget to add the new rule to a `RuleSetProvider`.
- ... do not forget to add the new rule to the `default-detekt-config.yml` in the `detekt-cli-resources`.
- ... do not forget to write a description for the issue of the new rule.
- be aware that your PR will stay open for at least two days so that other users can give feedback.
- make sure to set the new rule `active: false` in the default config. Brave users can test it on demand.
After some time and testing there is a chance this rule will become active on default.

### Release checklist

- new features? -> Update README.md / from `1.x.x` Wiki
- add changes in CHANGELOG.md -> `groovy github-milestone-report.groovy arturbosch/detekt [milestone-number]`
- migrations expected? -> Update MIGRATION_GUIDE.md
- all new contributors mentioned? -> README.md>Contributors, Update `all contributors`-Badge
- new gradle-plugin release? -> Update gradle-version badge


text:
FROM php:fpm

WORKDIR /home/project

RUN apt-get update && apt-get upgrade -y && apt-get install -y git libssl-dev wget && \
    docker-php-ext-install zip mbstring && \
	pecl install xdebug-beta && docker-php-ext-enable xdebug

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer


text:
JAVA project

# Presentado por
* Sanchez Aguilar, Cristian Antonio
* Rivas Trejo, Marvin Leonel
* Hernandez Abrego, Francisco Salvador
* Villalta Villalta, Luis David

# Pasos a seguir
1. Crear la conexion a la base de datos usando como ejemplo el archivo GTRacing_Project/example-conf.json y guardarlo en GTRacing_Project/conf.json para el modulo escritorio y en la clase com.gtracing.conexion.Conexion para el modulo web en el proyecto GTRacing_Web
2. Para ver la cuenta de la empresa en sandbox.paypal.com:
username: owner@gtracing.com
password: D@nB@$c04
3. Como ciente se puede logear al momento de pagar con la cuenta:
username: cliente@gtracing.com
password: D@nB@$c04


text:
module Wisper
  module Mongoid
    module Publisher
      extend ActiveSupport::Concern
      included do
        include Wisper::Publisher

        after_validation :after_validation_broadcast
        after_create :after_create_broadcast,  on: :create
        after_update :after_update_broadcast,  on: :update
        after_destroy :after_destroy_broadcast, on: :destroy
      end

      private

      def after_validation_broadcast
        action = new_record? ? 'create' : 'update'
        broadcast("#{action}_#{broadcast_model_name_key}_failed", self) unless errors.empty?
      end

      def after_create_broadcast
        broadcast(:after_create, self)
        broadcast("create_#{broadcast_model_name_key}_successful", self)
      end

      def after_update_broadcast
        broadcast(:after_update, self)
        broadcast("update_#{broadcast_model_name_key}_successful", self)
      end

      def after_destroy_broadcast
        broadcast(:after_destroy, self)
        broadcast("destroy_#{broadcast_model_name_key}_successful", self)
      end

      def broadcast_model_name_key
        self.class.model_name.param_key
      end
    end
  end
end


text:
package com.galois.qrstream.qrpipe;

import java.util.Random;

public class TestUtils {
  public static int nextNatural(Random r) {
    return Math.abs(r.nextInt());
  }
}


text:
using namespace llvm;

static std::pair<MCSymbol *, unsigned> &
getEntry(AsmPrinter &Asm,
         StringMap<std::pair<MCSymbol *, unsigned>, BumpPtrAllocator &> &Pool,
         StringRef Prefix, StringRef Str) {
  std::pair<MCSymbol *, unsigned> &Entry = Pool[Str];
  if (!Entry.first) {
    Entry.second = Pool.size() - 1;
    Entry.first = Asm.GetTempSymbol(Prefix, Entry.second);
  }
  return Entry;
}

MCSymbol *DwarfStringPool::getSymbol(AsmPrinter &Asm, StringRef Str) {
  return getEntry(Asm, Pool, Prefix, Str).first;
}

unsigned DwarfStringPool::getIndex(AsmPrinter &Asm, StringRef Str) {
  return getEntry(Asm, Pool, Prefix, Str).second;
}

void DwarfStringPool::emit(AsmPrinter &Asm, const MCSection *StrSection,
                           const MCSection *OffsetSection) {
  if (Pool.empty())
    return;

  // Start the dwarf str section.
  Asm.OutStreamer.SwitchSection(StrSection);

  // Get all of the string pool entries and put them in an array by their ID so
  // we can sort them.
  SmallVector<const StringMapEntry<std::pair<MCSymbol *, unsigned>> *, 64>
  Entries(Pool.size());

  for (const auto &E : Pool)
    Entries[E.getValue().second] = &E;

  for (const auto &Entry : Entries) {
    // Emit a label for reference from debug information entries.
    Asm.OutStreamer.EmitLabel(Entry->getValue().first);

    // Emit the string itself with a terminating null byte.
    Asm.OutStreamer.EmitBytes(
        StringRef(Entry->getKeyData(), Entry->getKeyLength() + 1));
  }

  // If we've got an offset section go ahead and emit that now as well.
  if (OffsetSection) {
    Asm.OutStreamer.SwitchSection(OffsetSection);
    unsigned offset = 0;
    unsigned size = 4; // FIXME: DWARF64 is 8.
    for (const auto &Entry : Entries) {
      Asm.OutStreamer.EmitIntValue(offset, size);
      offset += Entry->getKeyLength() + 1;
    }
  }
}


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.
 */
#include "presto_cpp/main/PrestoServer.h"
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/lexical_cast.hpp>
#include <glog/logging.h>
#include "presto_cpp/main/Announcer.h"
#include "presto_cpp/main/PeriodicTaskManager.h"
#include "presto_cpp/main/PrestoExchangeSource.h"
#include "presto_cpp/main/SignalHandler.h"
#include "presto_cpp/main/TaskResource.h"
#include "presto_cpp/main/common/ConfigReader.h"
#include "presto_cpp/main/common/Configs.h"
#include "presto_cpp/main/common/Counters.h"
#include "presto_cpp/main/connectors/hive/storage_adapters/FileSystems.h"
#include "presto_cpp/main/http/HttpServer.h"
#include "presto_cpp/presto_protocol/Connectors.h"
#include "presto_cpp/presto_protocol/WriteProtocol.h"
#include "presto_cpp/presto_protocol/presto_protocol.h"
#include "velox/common/base/StatsReporter.h"
#include "velox/common/caching/SsdCache.h"
#include "velox/common/file/FileSystems.h"
#include "velox/common/memory/MmapAllocator.h"
#include "velox/connectors/Connector.h"
#include "velox/core/Context.h"
#include "velox/dwio/dwrf/reader/DwrfReader.h"
#include "velox/exec/Driver.h"
#include "velox/exec/PartitionedOutputBufferManager.h"
#include "velox/functions/prestosql/aggregates/RegisterAggregateFunctions.h"
#include "velox/functions/prestosql/registration/RegistrationFunctions.h"
#include "velox/functions/prestosql/window/WindowFunctionsRegistration.h"
#include "velox/serializers/PrestoSerializer.h"

#ifdef PRESTO_ENABLE_PARQUET
#include "velox/dwio/parquet/RegisterParquetReader.h" // @manual
#endif

namespace facebook::presto {
using namespace facebook::velox;

namespace {

constexpr char const* kHttp = "http";
constexpr char const* kBaseUriFormat = "http://{}:{}";
constexpr char const* kConnectorName = "connector.name";
constexpr char const* kCacheEnabled = "cache.enabled";
constexpr char const* kCacheMaxCacheSize = "cache.max-cache-size";

protocol::NodeState convertNodeState(presto::NodeState nodeState) {
  switch (nodeState) {
    case presto::NodeState::ACTIVE:
      return protocol::NodeState::ACTIVE;
    case presto::NodeState::INACTIVE:
      return protocol::NodeState::INACTIVE;
    case presto::NodeState::SHUTTING_DOWN:
      return protocol::NodeState::SHUTTING_DOWN;
  }
  return protocol::NodeState::ACTIVE; // For gcc build.
}

void sendOkResponse(proxygen::ResponseHandler* downstream, const json& body) {
  proxygen::ResponseBuilder(downstream)
      .status(http::kHttpOk, "OK")
      .header(
          proxygen::HTTP_HEADER_CONTENT_TYPE, http::kMimeTypeApplicationJson)
      .body(body.dump())
      .sendWithEOM();
}

std::string getLocalIp() {
  using boost::asio::ip::tcp;
  boost::asio::io_service io_service;
  tcp::resolver resolver(io_service);
  tcp::resolver::query query(boost::asio::ip::host_name(), kHttp);
  tcp::resolver::iterator it = resolver.resolve(query);
  while (it != tcp::resolver::iterator()) {
    boost::asio::ip::address addr = (it++)->endpoint().address();
    // simple check to see if the address is not ::
    if (addr.to_string().length() > 4) {
      return fmt::format("{}", addr.to_string());
    }
  }
  VELOX_FAIL(
      "Could not infer Node IP. Please specify node.ip in the node.properties file.");
}

void enableChecksum() {
  velox::exec::PartitionedOutputBufferManager::getInstance()
      .lock()
      ->setListenerFactory([]() {
        return std::make_unique<
            serializer::presto::PrestoOutputStreamListener>();
      });
}

} // namespace

PrestoServer::PrestoServer(const std::string& configDirectoryPath)
    : configDirectoryPath_(configDirectoryPath),
      signalHandler_(std::make_unique<SignalHandler>(this)),
      start_(std::chrono::steady_clock::now()),
      memoryInfo_(std::make_unique<protocol::MemoryInfo>()) {}

PrestoServer::~PrestoServer() {}

void PrestoServer::run() {
  auto systemConfig = SystemConfig::instance();
  auto nodeConfig = NodeConfig::instance();
  int servicePort{0};
  int httpExecThreads{0};
  try {
    systemConfig->initialize(
        fmt::format("{}/config.properties", configDirectoryPath_));
    nodeConfig->initialize(
        fmt::format("{}/node.properties", configDirectoryPath_));
    servicePort = systemConfig->httpServerHttpPort();
    nodeVersion_ = systemConfig->prestoVersion();
    httpExecThreads = systemConfig->httpExecThreads();
    environment_ = nodeConfig->nodeEnvironment();
    nodeId_ = nodeConfig->nodeId();
    address_ = nodeConfig->nodeIp(getLocalIp);
    // Add [] to an ipv6 address.
    if (address_.find(':') != std::string::npos && address_.front() != '[') {
      address_ = fmt::format("[{}]", address_);
    }
    nodeLocation_ = nodeConfig->nodeLocation();
  } catch (const VeloxUserError& e) {
    // VeloxUserError is always logged as an error.
    // Avoid logging again.
    exit(EXIT_FAILURE);
  }

  registerPrestoCppCounters();
  registerFileSystems();
  registerOptionalHiveStorageAdapters();
  protocol::registerHiveConnectors();
  protocol::registerTpchConnector();
  protocol::HiveNoCommitWriteProtocol::registerProtocol();
  protocol::HiveTaskCommitWriteProtocol::registerProtocol();

  auto executor = std::make_shared<folly::IOThreadPoolExecutor>(
      systemConfig->numIoThreads(),
      std::make_shared<folly::NamedThreadFactory>("PrestoWorkerNetwork"));
  folly::setUnsafeMutableGlobalIOExecutor(executor);

  initializeAsyncCache();

  auto catalogNames = registerConnectors(fs::path(configDirectoryPath_));

  folly::SocketAddress socketAddress;
  socketAddress.setFromLocalPort(servicePort);
  LOG(INFO) << fmt::format(
      "STARTUP: Starting server at {}:{} ({})",
      socketAddress.getIPAddress().str(),
      servicePort,
      address_);

  Announcer announcer(
      address_,
      servicePort,
      discoveryAddressLookup(),
      nodeVersion_,
      environment_,
      nodeId_,
      nodeLocation_,
      catalogNames,
      30'000 /*milliseconds*/);
  announcer.start();

  httpServer_ =
      std::make_unique<http::HttpServer>(socketAddress, httpExecThreads);

  httpServer_->registerPost(
      "/v1/memory",
      [server = this](
          proxygen::HTTPMessage* /*message*/,
          const std::vector<std::unique_ptr<folly::IOBuf>>& /*body*/,
          proxygen::ResponseHandler* downstream) {
        server->reportMemoryInfo(downstream);
      });
  httpServer_->registerGet(
      "/v1/info",
      [server = this](
          proxygen::HTTPMessage* /*message*/,
          const std::vector<std::unique_ptr<folly::IOBuf>>& /*body*/,
          proxygen::ResponseHandler* downstream) {
        server->reportServerInfo(downstream);
      });
  httpServer_->registerGet(
      "/v1/info/state",
      [server = this](
          proxygen::HTTPMessage* /*message*/,
          const std::vector<std::unique_ptr<folly::IOBuf>>& /*body*/,
          proxygen::ResponseHandler* downstream) {
        json infoStateJson = convertNodeState(server->nodeState());
        sendOkResponse(downstream, infoStateJson);
      });
  httpServer_->registerGet(
      "/v1/status",
      [server = this](
          proxygen::HTTPMessage* /*message*/,
          const std::vector<std::unique_ptr<folly::IOBuf>>& /*body*/,
          proxygen::ResponseHandler* downstream) {
        server->reportNodeStatus(downstream);
      });
  httpServer_->registerHead(
      "/v1/status",
      [server = this](
          proxygen::HTTPMessage* /*message*/,
          const std::vector<std::unique_ptr<folly::IOBuf>>& /*body*/,
          proxygen::ResponseHandler* downstream) {
        proxygen::ResponseBuilder(downstream)
            .status(http::kHttpOk, "OK")
            .header(
                proxygen::HTTP_HEADER_CONTENT_TYPE,
                http::kMimeTypeApplicationJson)
            .sendWithEOM();
      });

  velox::functions::prestosql::registerAllScalarFunctions();
  velox::aggregate::prestosql::registerAllAggregateFunctions();
  velox::window::prestosql::registerAllWindowFunctions();
  if (!velox::isRegisteredVectorSerde()) {
    velox::serializer::presto::PrestoVectorSerde::registerVectorSerde();
  }

  facebook::velox::exec::ExchangeSource::registerFactory(
      PrestoExchangeSource::createExchangeSource);

  velox::dwrf::registerDwrfReaderFactory();
#ifdef PRESTO_ENABLE_PARQUET
  velox::parquet::registerParquetReaderFactory();
#endif

  taskManager_ = std::make_unique<TaskManager>(
      systemConfig->values(), nodeConfig->values());
  taskManager_->setBaseUri(fmt::format(kBaseUriFormat, address_, servicePort));
  taskResource_ = std::make_unique<TaskResource>(*taskManager_);
  taskResource_->registerUris(*httpServer_);
  if (systemConfig->enableSerializedPageChecksum()) {
    enableChecksum();
  }

  if (systemConfig->enableVeloxTaskLogging()) {
    if (auto listener = getTaskListiner()) {
      exec::registerTaskListener(listener);
    }
  }

  if (systemConfig->enableVeloxExprSetLogging()) {
    if (auto listener = getExprSetListener()) {
      exec::registerExprSetListener(listener);
    }
  }

  LOG(INFO) << "STARTUP: Starting all periodic tasks...";
  PeriodicTaskManager periodicTaskManager(
      driverCPUExecutor(), httpServer_->getExecutor(), taskManager_.get());
  periodicTaskManager.addTask(
      [server = this]() { server->populateMemAndCPUInfo(); },
      1'000'000, // 1 second
      "populate_mem_cpu_info");
  periodicTaskManager.start();

  // Start everything. After the return from the following call we are shutting
  // down.
  httpServer_->start();

  LOG(INFO) << "SHUTDOWN: Stopping all periodic tasks...";
  periodicTaskManager.stop();

  // Destroy entities here to ensure we won't get any messages after Server
  // object is gone and to have nice log in case shutdown gets stuck.
  LOG(INFO) << "SHUTDOWN: Destroying Task Resource...";
  taskResource_.reset();
  LOG(INFO) << "SHUTDOWN: Destroying Task Manager...";
  taskManager_.reset();
  LOG(INFO) << "SHUTDOWN: Destroying HTTP Server...";
  httpServer_.reset();

  auto cpuExecutor = driverCPUExecutor();
  LOG(INFO) << "SHUTDOWN: Joining Driver CPU Executor '"
            << cpuExecutor->getName()
            << "': threads: " << cpuExecutor->numActiveThreads() << "/"
            << cpuExecutor->numThreads()
            << ", task queue: " << cpuExecutor->getTaskQueueSize();
  cpuExecutor->join();

  LOG(INFO) << "SHUTDOWN: Joining IO Executor '"
            << connectorIoExecutor_->getName()
            << "': threads: " << connectorIoExecutor_->numActiveThreads() << "/"
            << connectorIoExecutor_->numThreads();
  connectorIoExecutor_->join();

  LOG(INFO) << "SHUTDOWN: Done joining our executors.";

  auto globalCPUKeepAliveExec = folly::getGlobalCPUExecutor();
  if (auto* pGlobalCPUExecutor = dynamic_cast<folly::CPUThreadPoolExecutor*>(
          globalCPUKeepAliveExec.get())) {
    LOG(INFO) << "SHUTDOWN: Global CPU Executor '"
              << pGlobalCPUExecutor->getName()
              << "': threads: " << pGlobalCPUExecutor->numActiveThreads() << "/"
              << pGlobalCPUExecutor->numThreads()
              << ", task queue: " << pGlobalCPUExecutor->getTaskQueueSize();
  }

  auto globalIOKeepAliveExec = folly::getGlobalIOExecutor();
  if (auto* pGlobalIOExecutor = dynamic_cast<folly::IOThreadPoolExecutor*>(
          globalIOKeepAliveExec.get())) {
    LOG(INFO) << "SHUTDOWN: Global IO Executor '"
              << pGlobalIOExecutor->getName()
              << "': threads: " << pGlobalIOExecutor->numActiveThreads() << "/"
              << pGlobalIOExecutor->numThreads();
  }
}

void PrestoServer::initializeAsyncCache() {
  auto nodeConfig = NodeConfig::instance();
  auto systemConfig = SystemConfig::instance();
  uint64_t memoryGb = nodeConfig->nodeMemoryGb(
      [&]() { return systemConfig->systemMemoryGb(); });
  LOG(INFO) << "Starting with node memory " << memoryGb << "GB";
  std::unique_ptr<cache::SsdCache> ssd;
  auto asyncCacheSsdGb = systemConfig->asyncCacheSsdGb();
  if (asyncCacheSsdGb) {
    constexpr int32_t kNumSsdShards = 16;
    cacheExecutor_ =
        std::make_unique<folly::IOThreadPoolExecutor>(kNumSsdShards);
    ssd = std::make_unique<cache::SsdCache>(
        systemConfig->asyncCacheSsdPath(),
        asyncCacheSsdGb << 30,
        kNumSsdShards,
        cacheExecutor_.get());
  }
  auto memoryBytes = memoryGb << 30;

  memory::MmapAllocatorOptions options;
  options.capacity = memoryBytes;
  options.useMmapArena = systemConfig->useMmapArena();
  options.mmapArenaCapacityRatio = systemConfig->mmapArenaCapacityRatio();

  auto allocator = std::make_shared<memory::MmapAllocator>(options);
  mappedMemory_ = std::make_shared<cache::AsyncDataCache>(
      allocator, memoryBytes, std::move(ssd));

  memory::MappedMemory::setDefaultInstance(mappedMemory_.get());
}

void PrestoServer::stop() {
  // Make sure we only go here once.
  auto shutdownOnsetSec = SystemConfig::instance()->shutdownOnsetSec();
  if (not shuttingDown_.exchange(true)) {
    LOG(INFO) << "SHUTDOWN: Initiating shutdown. Will wait for "
              << shutdownOnsetSec << " seconds.";
    this->setNodeState(NodeState::SHUTTING_DOWN);

    // Give coordinator some time to receive our new node state and stop sending
    // any tasks.
    std::this_thread::sleep_for(std::chrono::seconds(shutdownOnsetSec));

    size_t numTasks{0};
    auto taskNumbers = taskManager_->getTaskNumbers(numTasks);
    size_t seconds = 0;
    while (taskNumbers[velox::exec::TaskState::kRunning] > 0) {
      LOG(INFO) << "SHUTDOWN: Waiting (" << seconds
                << " seconds so far) for 'Running' tasks to complete. "
                << numTasks << " tasks left: "
                << PrestoTask::taskNumbersToString(taskNumbers);
      std::this_thread::sleep_for(std::chrono::seconds(1));
      taskNumbers = taskManager_->getTaskNumbers(numTasks);
      ++seconds;
    }

    // Give coordinator some time to request tasks stats for completed or failed
    // tasks.
    std::this_thread::sleep_for(std::chrono::seconds(shutdownOnsetSec));

    if (httpServer_) {
      LOG(INFO) << "SHUTDOWN: All tasks are completed. Stopping HTTP Server...";
      httpServer_->stop();
      LOG(INFO) << "SHUTDOWN: HTTP Server stopped.";
    }
  }
}

std::function<folly::SocketAddress()> PrestoServer::discoveryAddressLookup() {
  try {
    auto uri = folly::Uri(SystemConfig::instance()->discoveryUri());

    return [uri]() {
      return folly::SocketAddress(uri.hostname(), uri.port(), true);
    };
  } catch (const VeloxUserError& e) {
    // VeloxUserError is always logged as an error.
    // Avoid logging again.
    exit(EXIT_FAILURE);
  }
}

std::shared_ptr<velox::exec::TaskListener> PrestoServer::getTaskListiner() {
  return nullptr;
}

std::shared_ptr<velox::exec::ExprSetListener>
PrestoServer::getExprSetListener() {
  return nullptr;
}

std::vector<std::string> PrestoServer::registerConnectors(
    const fs::path& configDirectoryPath) {
  static const std::string kPropertiesExtension = ".properties";

  auto numIoThreads = SystemConfig::instance()->numIoThreads();
  if (numIoThreads) {
    connectorIoExecutor_ =
        std::make_unique<folly::IOThreadPoolExecutor>(numIoThreads);
  }
  std::vector<std::string> catalogNames;

  for (const auto& entry :
       fs::directory_iterator(configDirectoryPath / "catalog")) {
    if (entry.path().extension() == kPropertiesExtension) {
      auto fileName = entry.path().filename().string();
      auto catalogName =
          fileName.substr(0, fileName.size() - kPropertiesExtension.size());

      auto connectorConf = util::readConfig(entry.path());
      std::shared_ptr<const velox::Config> properties =
          std::make_shared<const velox::core::MemConfig>(
              std::move(connectorConf));

      auto connectorName = util::requiredProperty(*properties, kConnectorName);
      const bool cacheEnabled = properties->get(kCacheEnabled, false);
      const size_t cacheSize = properties->get(kCacheMaxCacheSize, 0);

      catalogNames.emplace_back(catalogName);

      LOG(INFO) << "STARTUP: Registering catalog " << catalogName
                << " using connector " << connectorName
                << ", cache enabled: " << cacheEnabled
                << ", cache size: " << cacheSize;

      std::shared_ptr<velox::connector::Connector> connector;
      if (cacheEnabled && cacheSize > 0) {
        connector = connectorWithCache(connectorName, catalogName, properties);
        cacheRamCapacityGb_ += cacheSize / 1024; // cacheSize is in Mb.
      } else {
        connector =
            facebook::velox::connector::getConnectorFactory(connectorName)
                ->newConnector(catalogName, std::move(properties));
      }
      velox::connector::registerConnector(connector);
    }
  }
  return catalogNames;
}

void PrestoServer::registerFileSystems() {
  velox::filesystems::registerLocalFileSystem();
}

std::shared_ptr<velox::connector::Connector> PrestoServer::connectorWithCache(
    const std::string& connectorName,
    const std::string& catalogName,
    std::shared_ptr<const velox::Config> properties) {
  VELOX_CHECK_NOT_NULL(
      dynamic_cast<cache::AsyncDataCache*>(mappedMemory_.get()));
  LOG(INFO) << "STARTUP: Using AsyncDataCache";
  return facebook::velox::connector::getConnectorFactory(connectorName)
      ->newConnector(
          catalogName, std::move(properties), connectorIoExecutor_.get());
}

void PrestoServer::populateMemAndCPUInfo() {
  auto systemConfig = SystemConfig::instance();
  const int64_t nodeMemoryGb =
      systemConfig->systemMemoryGb() - cacheRamCapacityGb_;
  protocol::MemoryInfo memoryInfo{
      {double(nodeMemoryGb), protocol::DataUnit::GIGABYTE}};

  // Fill the only memory pool info (general)
  auto& poolInfo = memoryInfo.pools["general"];
  auto* pool = taskResource_->getPool();

  // Fill global pool fields.
  poolInfo.maxBytes = nodeMemoryGb * 1024 * 1024 * 1204;
  // TODO(sperhsin): If 'current bytes' is the same as we get by summing up all
  // child contexts below, then use the one we sum up, rather than call
  // 'getCurrentBytes'.
  poolInfo.reservedBytes = pool->getCurrentBytes();
  poolInfo.reservedRevocableBytes = 0;

  // Fill basic per-query fields.
  const auto* queryCtxMgr = taskManager_->getQueryContextManager();
  size_t numContexts{0};
  queryCtxMgr->visitAllContexts([&](const protocol::QueryId& queryId,
                                    const velox::core::QueryCtx* queryCtx) {
    const protocol::Long bytes = queryCtx->pool()->getCurrentBytes();
    poolInfo.queryMemoryReservations.insert({queryId, bytes});
    // TODO(spershin): Might want to see what Java exports and export similar
    // info (like child memory pools).
    poolInfo.queryMemoryAllocations.insert(
        {queryId, {protocol::MemoryAllocation{"total", bytes}}});
    ++numContexts;
  });
  REPORT_ADD_STAT_VALUE(kCounterNumQueryContexts, numContexts);
  cpuMon_.update();
  **memoryInfo_.wlock() = std::move(memoryInfo);
}

static protocol::Duration getUptime(
    std::chrono::steady_clock::time_point& start) {
  auto seconds = std::chrono::duration_cast<std::chrono::seconds>(
                     std::chrono::steady_clock::now() - start)
                     .count();
  if (seconds >= 86400) {
    return protocol::Duration(seconds / 86400.0, protocol::TimeUnit::DAYS);
  }
  if (seconds >= 3600) {
    return protocol::Duration(seconds / 3600.0, protocol::TimeUnit::HOURS);
  }
  if (seconds >= 60) {
    return protocol::Duration(seconds / 60.0, protocol::TimeUnit::MINUTES);
  }

  return protocol::Duration(seconds, protocol::TimeUnit::SECONDS);
}

void PrestoServer::reportMemoryInfo(proxygen::ResponseHandler* downstream) {
  sendOkResponse(downstream, json(**memoryInfo_.rlock()));
}

void PrestoServer::reportServerInfo(proxygen::ResponseHandler* downstream) {
  const protocol::ServerInfo serverInfo{
      {nodeVersion_},
      environment_,
      false,
      false,
      std::make_shared<protocol::Duration>(getUptime(start_))};
  sendOkResponse(downstream, json(serverInfo));
}

void PrestoServer::reportNodeStatus(proxygen::ResponseHandler* downstream) {
  auto systemConfig = SystemConfig::instance();
  const int64_t nodeMemoryGb =
      systemConfig->systemMemoryGb() - cacheRamCapacityGb_;

  const double cpuLoadPct{cpuMon_.getCPULoadPct()};

  // TODO(spershin): As 'nonHeapUsed' we could export the cache memory.
  const int64_t nonHeapUsed{0};

  protocol::NodeStatus nodeStatus{
      nodeId_,
      {nodeVersion_},
      environment_,
      false,
      getUptime(start_),
      address_,
      address_,
      **memoryInfo_.rlock(),
      (int)std::thread::hardware_concurrency(),
      cpuLoadPct,
      cpuLoadPct,
      taskResource_->getPool()->getCurrentBytes(),
      nodeMemoryGb * 1024 * 1024 * 1024,
      nonHeapUsed};

  sendOkResponse(downstream, json(nodeStatus));
}

} // namespace facebook::presto


text:
package org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.get;

import java.io.StringReader;
import java.util.concurrent.BlockingQueue;

import org.apache.log4j.Logger;
import org.buddycloud.channelserver.Configuration;
import org.buddycloud.channelserver.channel.ChannelManager;
import org.buddycloud.channelserver.db.CloseableIterator;
import org.buddycloud.channelserver.db.exception.NodeStoreException;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.JabberPubsub;
import org.buddycloud.channelserver.packetprocessor.iq.namespace.pubsub.PubSubElementProcessorAbstract;
import org.buddycloud.channelserver.pubsub.model.NodeItem;
import org.buddycloud.channelserver.utils.XMLConstants;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;

public class RepliesGet extends PubSubElementProcessorAbstract {

    private Element pubsub;
    private SAXReader xmlReader;

    // RSM details
    private String firstItemId = null;
    private String lastItemId = null;

    public static final Logger LOGGER = Logger.getLogger(RecentItemsGet.class);

    public RepliesGet(BlockingQueue<Packet> outQueue, ChannelManager channelManager) {
        setChannelManager(channelManager);
        setOutQueue(outQueue);

        xmlReader = new SAXReader();

        acceptedElementName = XMLConstants.REPLIES;
    }

    @Override
    public void process(Element elm, JID actorJID, IQ reqIQ, Element rsm) throws Exception {
        response = IQ.createResultIQ(reqIQ);
        request = reqIQ;
        actor = actorJID;
        resultSetManagement = rsm;

        if (null == actor) {
            actor = request.getFrom();
        }

        if (!isValidStanza()) {
            outQueue.put(response);
            return;
        }

        try {
            if (!Configuration.getInstance().isLocalJID(request.getFrom())) {
                response.getElement().addAttribute(XMLConstants.REMOTE_SERVER_DISCOVER_ATTR, Boolean.FALSE.toString());
            }
            pubsub = response.getElement().addElement(XMLConstants.PUBSUB_ELEM, JabberPubsub.NAMESPACE_URI);
            if ((!userCanViewNode()) || (!itemExists())) {
                outQueue.put(response);
                return;
            }
            parseRsmElement();
            addReplies();
            addRsmElement();
            outQueue.put(response);
        } catch (NodeStoreException e) {
            LOGGER.error(e);
            response.getElement().remove(pubsub);
            setErrorCondition(PacketError.Type.wait, PacketError.Condition.internal_server_error);
        }
        outQueue.put(response);

    }

    private boolean itemExists() throws NodeStoreException {
        if (null != channelManager.getNodeItem(node, parentId)) {
            return true;
        }
        setErrorCondition(PacketError.Type.modify, PacketError.Condition.bad_request);
        return false;
    }

    protected void addRsmElement() throws NodeStoreException {

        Element rsm = pubsub.addElement(XMLConstants.SET_ELEM);
        rsm.addNamespace("", NS_RSM);
        if (null != firstItemId) {
            rsm.addElement("first").setText(firstItemId);
            rsm.addElement("last").setText(lastItemId);
        }
        rsm.addElement("count").setText(
            String.valueOf(channelManager.getCountNodeItemReplies(node, parentId)));
    }

    private void addReplies() throws NodeStoreException {

        String rsmItem = afterItemId;
        boolean after = true;
        if (null != beforeItemId) {
          rsmItem = beforeItemId;
          after = false;
        }

        CloseableIterator<NodeItem> items = channelManager.getNodeItemReplies(node, parentId, rsmItem, after, maxResults);
        NodeItem item;
        Element entry;
        Element itemElement;
        Element itemsElement = pubsub.addElement(XMLConstants.ITEMS_ELEM);
        itemsElement.addAttribute(XMLConstants.NODE_ATTR, node);

        while (items.hasNext()) {
            item = items.next();

            try {
                entry = xmlReader.read(new StringReader(item.getPayload())).getRootElement();
                itemElement = itemsElement.addElement(XMLConstants.ITEM_ELEM);
                itemElement.addAttribute(XMLConstants.ID_ATTR, item.getId());
                if (null == firstItemId) {
                    firstItemId = item.getId();
                }
                lastItemId = item.getId();
                itemElement.add(entry);
            } catch (DocumentException e) {
                LOGGER.error("Error parsing a node entry, ignoring. " + item.getId());

            }
        }
    }
}


text:
<?php

namespace common\models\base;

use Yii;

/**
 * This is the model class for table "{{%currency}}".
 *
 * @property string $id
 * @property string $classify
 * @property string $language
 * @property string $name
 * @property string $code
 * @property string $course
 *
 * @property Language $language0
 */
class Currency extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%currency}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['language', 'name', 'code'], 'required'],
            [['language'], 'integer'],
            [['course'], 'number'],
            [['classify', 'name'], 'string', 'max' => 255],
            [['code'], 'string', 'max' => 20],
            [['name'], 'unique'],
            [['language', 'name'], 'unique', 'targetAttribute' => ['language', 'name'], 'message' => 'The combination of Language and Name has already been taken.'],
            [['language'], 'exist', 'skipOnError' => true, 'targetClass' => Language::className(), 'targetAttribute' => ['language' => 'id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'classify' => Yii::t('app', 'Classify'),
            'language' => Yii::t('app', 'Language'),
            'name' => Yii::t('app', 'Name'),
            'code' => Yii::t('app', 'Code'),
            'course' => Yii::t('app', 'Course'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getLanguage0()
    {
        return $this->hasOne(Language::className(), ['id' => 'language']);
    }
}


text:
using Autofac;
using ChatterBox.Core.Infrastructure;

namespace ChatterBox.Core.AutofacModules
{
    public class CoreModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            base.Load(builder);

            builder.RegisterType<SystemClock>()
                .AsImplementedInterfaces()
                .SingleInstance();
        }
    }
}


text:
using System;
using System.Linq;
using Cirrious.MvvmCross.Droid.Fragging.Fragments;
using Cirrious.MvvmCross.Views;

namespace RegionEx.Droid
{
    /// <summary>
    /// Attribute for tagging views with the region in which they should displayed when shown with IMultiRegionPresenter.
    /// </summary>
    public class RegionAttribute : Attribute
    {
        public RegionAttribute(int id)
        {
            Id = id;
        }

        /// <summary>
        /// The Android resource ID of the region.
        /// </summary>
        public int Id { get; private set; }
    }
}


text:
export WORKON_HOME='~/.virtualenvs'
source /usr/share/virtualenvwrapper/virtualenvwrapper.sh
mkvirtualenv --no-site-packages scion

source ~/.bash_profile

# Create virtualenv
workon scion
pip install setuptools --upgrade

# Get code
mkdir -p code
cd code
mkdir -p logs

git clone https://github.com/scionrep/scioncc
cd scioncc
git checkout ${GIT_REV:-master}


text:
package com.carlosbecker;

import com.carlosbecker.spotify.Profile;
import com.carlosbecker.spotify.oauth.Token;
import com.google.common.net.HttpHeaders;
import com.jcabi.aspects.Immutable;
import com.jcabi.http.Request;
import com.jcabi.http.request.JdkRequest;
import lombok.RequiredArgsConstructor;

@Immutable
@RequiredArgsConstructor
public final class Spotify {
    private final transient Token token;

    public Request entry() {
        return new JdkRequest("https://api.spotify.com/v1/")
            .header(HttpHeaders.AUTHORIZATION, this.token.value())
            .header(HttpHeaders.ACCEPT, "application/json")
            .header(HttpHeaders.CONTENT_TYPE, "application/json; charset=utf-8")
            .header(HttpHeaders.USER_AGENT, "caarlos0/spotify-api");
    }

    public Profile me() {
        return new Profile.Me(this.entry());
    }
}


text:
import os
import sys
import socket
from optparse import OptionParser
import time
import struct
import math

# protocol commands
MESSAGE_TYPE_JPEG_IMAGE = 1
MESSAGE_TYPE_IMAGE_REPONSE = 2

def get_local_ipaddress():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("gmail.com",80))
    ipaddress = (s.getsockname()[0])
    s.close()
    return ipaddress

def process_command_line(argv):
    global operation_mode

    parser = OptionParser(usage="usage: %prog [option]", version="Face Recognition Desktop Client")
    parser.add_option(
            '-d', '--dir', action='store', type='string', dest='input_dir',
            help='Set Input image directory')
    parser.add_option(
            '-s', '--server', action='store', type='string', dest='server_address', default="localhost",
            help='Set Input image directory')
    parser.add_option(
            '-p', '--port', action='store', type='int', dest='server_port', default=9876,
            help='Set Input image directory')
    settings, args = parser.parse_args(argv)
    if not len(args) == 0:
        parser.error('program takes no command-line arguments; "%s" ignored.' % (args,))

    if not settings.input_dir:
        parser.error("input directory does no exists at :%s" % (settings.input_dir))
    if not os.path.isdir(settings.input_dir):
        parser.error("input directory does no exists at :%s" % (settings.input_dir))

    return settings, args

def send_request(address, port, inputs):
    # connection
    try:
        print "Connecting to (%s, %d).." % (address, port)
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.setblocking(True)
        sock.connect((address, port))
    except socket.error, msg:
        sys.stderr.write("Connection error\n")
        sys.exit(1)

    # send requests
    current_duration = -1
    print "image\tstart\tend\tduration\tjitter"
    for each_input in inputs:
        start_time_request = time.time() * 1000.0
        binary = open(each_input, 'rb').read();

        ret_data = face_request(sock, binary)

        # print result
        end_time_request = time.time() * 1000.0
        prev_duration = current_duration
        current_duration = end_time_request-start_time_request

        if prev_duration == -1: # fisrt response
            print "%s\t%014.2f\t%014.2f\t%014.2f\t0" % (each_input, start_time_request,\
                    end_time_request, \
                    end_time_request-start_time_request)
        else:
            print "%s\t%014.2f\t%014.2f\t%014.2f\t%014.2f" % (each_input, round(start_time_request, 3), \
                    end_time_request, \
                    current_duration, \
                    math.fabs(current_duration-prev_duration))

def face_request(sock, data):
    if len(data) > 100*1000: # 100k
        sys.stderr.write("Error, Server cannot support image bigger than 100KB\n")
        return 'Server cannot support > 100 KB iamges', (0,0,0,0)

    # send
    sock.sendall(struct.pack("!I", MESSAGE_TYPE_JPEG_IMAGE))
    sock.sendall(struct.pack("!I", len(data)))
    sock.sendall(data)

    #recv
    message_type = struct.unpack("!I", sock.recv(4))[0]
    message_size = struct.unpack("!I", sock.recv(4))[0]
    recvedData = struct.unpack("!IIIIIIIIf", sock.recv(4*9))
    detectTimeinMs = recvedData[0]
    objectsFound = recvedData[1]
    drawRect = recvedData[2]
    havePerson = recvedData[3]
    rect_x = recvedData[4]
    rect_y = recvedData[5]
    rect_width = recvedData[6]
    rect_height = recvedData[7]
    #confidence = recvedData[8]

    #print "detectTime(%d), objectFound(%d), drawRect(%d), havePerson(%d)" % \
    #        (detectTimeinMs, objectsFound, drawRect, havePerson)
    found_name = ''
    recv_size = message_size-36 # 36=9*4
    if not recv_size == 0:
        found_name = sock.recv(recv_size)

    return str(found_name), (rect_x, rect_y, rect_width, rect_height)

def main(argv=None):
    global LOCAL_IPADDRESS
    settings, args = process_command_line(sys.argv[1:])

    files = [os.path.join(settings.input_dir, file) for file in os.listdir(settings.input_dir) if file[-3:] == "jpg" or file[-3:] == "JPG"]
    send_request(settings.server_address, settings.server_port, files)

    return 0

if __name__ == "__main__":
    status = main()
    sys.exit(status)


text:
#ifndef GEOMETRYOBJECT_H
#define GEOMETRYOBJECT_H

/* These are very similiar to SceneObjects. It just simplifies the
 material settings, since primitives have a single material with a fixed name */

#include "nau/scene/sceneObject.h"
#include "nau/scene/sceneObjectFactory.h"

namespace nau
{
	namespace scene
	{
		class GeometricObject : public nau::scene::SceneObject
		{
		public:
			friend class nau::scene::SceneObjectFactory;

			~GeometricObject(void);

			static unsigned int PrimitiveCounter;

			unsigned int m_PrimitiveID;
			void setRenderable(std::shared_ptr<IRenderable> &renderable);
			void setMaterial(const std::string &name);

			std::string getType (void);

		protected:
			GeometricObject();
			void eventReceived(const std::string & sender, const std::string & eventType,
				const std::shared_ptr<IEventData>& evt);
		};
	};
};
#endif