text:
external help file: Microsoft.Azure.Commands.KeyVault.dll-Help.xml
ms.assetid: 28BC1B99-946C-4A8D-9581-4D5CC0BCEF8B
online version:
schema: 2.0.0
---

# Set-AzureKeyVaultCertificatePolicy

## SYNOPSIS
Creates or updates the policy for a certificate in a key vault.

## SYNTAX

### Expanded (Default)
```
Set-AzureKeyVaultCertificatePolicy [-VaultName] <String> [-Name] <String> [-SecretContentType <String>]
 [-ReuseKeyOnRenewal <Boolean>] [-Disabled] [-SubjectName <String>]
 [-DnsNames <System.Collections.Generic.List`1[System.String]>]
 [-KeyUsage <System.Collections.Generic.List`1[System.String]>]
 [-Ekus <System.Collections.Generic.List`1[System.String]>] [-ValidityInMonths <Int32>] [-IssuerName <String>]
 [-CertificateType <String>] [-RenewAtNumberOfDaysBeforeExpiry <Int32>] [-RenewAtPercentageLifetime <Int32>]
 [-EmailAtNumberOfDaysBeforeExpiry <Int32>] [-EmailAtPercentageLifetime <Int32>] [-KeyType <String>]
 [-KeyNotExportable] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>]
```

### ByValue
```
Set-AzureKeyVaultCertificatePolicy [-VaultName] <String> [-Name] <String>
 [-EmailAtNumberOfDaysBeforeExpiry <Int32>] [-EmailAtPercentageLifetime <Int32>] [-KeyType <String>]
 [[-CertificatePolicy] <KeyVaultCertificatePolicy>] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>]
```

## DESCRIPTION
The **Set-AzureKeyVaultCertificatePolicy** cmdlet creates or updates the policy for a certificate in a key vault.

## EXAMPLES

### Example 1: Set a certificate policy
```
PS C:\>Set-AzureKeyVaultCertificatePolicy -VaultName "ContosoKV01" -Name "TestCert01" -SecretContentType "application/x-pkcs12" -SubjectName "CN=contoso.com" -IssuerName "Self" -ValidityInMonths 6 -ReuseKeyOnRenewal $True
```

This command sets the policy for the TestCert01 certificate in the ContosoKV01 key vault.

## PARAMETERS

### -CertificatePolicy
Specifies the certificate policy.

```yaml
Type: KeyVaultCertificatePolicy
Parameter Sets: ByValue
Aliases:

Required: False
Position: 2
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -CertificateType
Specifies the type of certificate to the issuer.

```yaml
Type: String
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Disabled
Indicates that the certificate policy is disabled.

```yaml
Type: SwitchParameter
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -DnsNames
Specifies the DNS names in the certificate.

```yaml
Type: System.Collections.Generic.List`1[System.String]
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Ekus
Specifies the enhanced key usages (EKUs) in the certificate.

```yaml
Type: System.Collections.Generic.List`1[System.String]
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -EmailAtNumberOfDaysBeforeExpiry
Specifies how many days before expiry the automatic notification process begins.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -EmailAtPercentageLifetime
Specifies the percentage of the lifetime after which the automatic process for the notification begins.

```yaml
Type: Int32
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -IssuerName
Specifies the name of the issuer for this certificate.

```yaml
Type: String
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -KeyNotExportable
Indicates that the key is not exportable.

```yaml
Type: SwitchParameter
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -KeyType
Specifies the key type of the key that backs the certificate.
The acceptable values for this parameter are:

- RSA
- RSA-HSM

```yaml
Type: String
Parameter Sets: (All)
Aliases:
Accepted values: RSA, RSA-HSM

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -KeyUsage
Specifies the key usages in the certificate.

```yaml
Type: System.Collections.Generic.List`1[System.String]
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Name
Specifies the name of the certificate.

```yaml
Type: String
Parameter Sets: (All)
Aliases: CertificateName

Required: True
Position: 1
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -PassThru
Returns an object representing the item with which you are working.
By default, this cmdlet does not generate any output.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -RenewAtNumberOfDaysBeforeExpiry
Specifies the number of days before expiry after which the automatic process for certificate renewal begins.

```yaml
Type: Int32
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -RenewAtPercentageLifetime
Specifies the percentage of the lifetime after which the automatic process for certificate renewal begins.

```yaml
Type: Int32
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ReuseKeyOnRenewal
Indicates that the certificate reuse the key during renewal.

```yaml
Type: Boolean
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -SecretContentType
Specifies the content type of the new key vault secret.
The acceptable values for this parameter are:

- application/x-pkcs12
- application/x-pem-file

```yaml
Type: String
Parameter Sets: Expanded
Aliases:
Accepted values: application/x-pkcs12, application/x-pem-file

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -SubjectName
Specifies the subject name of the certificate.

```yaml
Type: String
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -ValidityInMonths
Specifies the number of months the certificate is valid.

```yaml
Type: Int32
Parameter Sets: Expanded
Aliases:

Required: False
Position: Named
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -VaultName
Specifies the name of a key vault.

```yaml
Type: String
Parameter Sets: (All)
Aliases:

Required: True
Position: 0
Default value: None
Accept pipeline input: True (ByPropertyName)
Accept wildcard characters: False
```

### -Confirm
Prompts you for confirmation before running the cmdlet.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: cf

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -WhatIf
Shows what would happen if the cmdlet runs.
The cmdlet is not run.

```yaml
Type: SwitchParameter
Parameter Sets: (All)
Aliases: wi

Required: False
Position: Named
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Microsoft.Azure.Commands.KeyVault.Models.KeyVaultCertificatePolicy

## NOTES

## RELATED LINKS

[Get-AzureKeyVaultCertificatePolicy](./Get-AzureKeyVaultCertificatePolicy.md)

[New-AzureKeyVaultCertificatePolicy](./New-AzureKeyVaultCertificatePolicy.md)


text:
import graphene
from graphene_django.debug import DjangoDebug

import apps.users.schema

class Query(apps.users.schema.Query, graphene.ObjectType):
    debug = graphene.Field(DjangoDebug, name='__debug')

class Mutation(apps.users.schema.Mutation, graphene.ObjectType):
    ...

schema = graphene.Schema(query=Query, mutation=Mutation)

redpajama_set_name: RedPajamaGithub


text:
package edu.pitt.dbmi.deepphe.summarization.orm.i2b2data;

// Generated Apr 15, 2015 4:30:25 PM by Hibernate Tools 4.3.1

import java.math.BigDecimal;
import java.sql.Clob;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

/**
 * PatientDimension generated by hbm2java
 */
@Entity
@Table(name = "PATIENT_DIMENSION", schema = "I2B2DEMODATA")
public class PatientDimension implements java.io.Serializable {

	private static final long serialVersionUID = 1L;

	private BigDecimal patientNum;
	private String vitalStatusCd;
	private Date birthDate;
	private Date deathDate;
	private String sexCd;
	private BigDecimal ageInYearsNum;
	private String languageCd;
	private String raceCd;
	private String maritalStatusCd;
	private String religionCd;
	private String zipCd;
	private String statecityzipPath;
	private String incomeCd;
	private Clob patientBlob;
	private Date updateDate;
	private Date downloadDate;
	private Date importDate;
	private String sourcesystemCd;
	private BigDecimal uploadId;

	public PatientDimension() {
	}

	public PatientDimension(BigDecimal patientNum) {
		this.patientNum = patientNum;
	}

	public PatientDimension(BigDecimal patientNum, String vitalStatusCd,
			Date birthDate, Date deathDate, String sexCd,
			BigDecimal ageInYearsNum, String languageCd, String raceCd,
			String maritalStatusCd, String religionCd, String zipCd,
			String statecityzipPath, String incomeCd, Clob patientBlob,
			Date updateDate, Date downloadDate, Date importDate,
			String sourcesystemCd, BigDecimal uploadId) {
		this.patientNum = patientNum;
		this.vitalStatusCd = vitalStatusCd;
		this.birthDate = birthDate;
		this.deathDate = deathDate;
		this.sexCd = sexCd;
		this.ageInYearsNum = ageInYearsNum;
		this.languageCd = languageCd;
		this.raceCd = raceCd;
		this.maritalStatusCd = maritalStatusCd;
		this.religionCd = religionCd;
		this.zipCd = zipCd;
		this.statecityzipPath = statecityzipPath;
		this.incomeCd = incomeCd;
		this.patientBlob = patientBlob;
		this.updateDate = updateDate;
		this.downloadDate = downloadDate;
		this.importDate = importDate;
		this.sourcesystemCd = sourcesystemCd;
		this.uploadId = uploadId;
	}

	@Id
	@Column(name = "PATIENT_NUM", unique = true, nullable = false, precision = 38, scale = 0)
	public BigDecimal getPatientNum() {
		return this.patientNum;
	}

	public void setPatientNum(BigDecimal patientNum) {
		this.patientNum = patientNum;
	}

	@Column(name = "VITAL_STATUS_CD", length = 50)
	public String getVitalStatusCd() {
		return this.vitalStatusCd;
	}

	public void setVitalStatusCd(String vitalStatusCd) {
		this.vitalStatusCd = vitalStatusCd;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "BIRTH_DATE", length = 7)
	public Date getBirthDate() {
		return this.birthDate;
	}

	public void setBirthDate(Date birthDate) {
		this.birthDate = birthDate;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "DEATH_DATE", length = 7)
	public Date getDeathDate() {
		return this.deathDate;
	}

	public void setDeathDate(Date deathDate) {
		this.deathDate = deathDate;
	}

	@Column(name = "SEX_CD", length = 50)
	public String getSexCd() {
		return this.sexCd;
	}

	public void setSexCd(String sexCd) {
		this.sexCd = sexCd;
	}

	@Column(name = "AGE_IN_YEARS_NUM", precision = 38, scale = 0)
	public BigDecimal getAgeInYearsNum() {
		return this.ageInYearsNum;
	}

	public void setAgeInYearsNum(BigDecimal ageInYearsNum) {
		this.ageInYearsNum = ageInYearsNum;
	}

	@Column(name = "LANGUAGE_CD", length = 50)
	public String getLanguageCd() {
		return this.languageCd;
	}

	public void setLanguageCd(String languageCd) {
		this.languageCd = languageCd;
	}

	@Column(name = "RACE_CD", length = 50)
	public String getRaceCd() {
		return this.raceCd;
	}

	public void setRaceCd(String raceCd) {
		this.raceCd = raceCd;
	}

	@Column(name = "MARITAL_STATUS_CD", length = 50)
	public String getMaritalStatusCd() {
		return this.maritalStatusCd;
	}

	public void setMaritalStatusCd(String maritalStatusCd) {
		this.maritalStatusCd = maritalStatusCd;
	}

	@Column(name = "RELIGION_CD", length = 50)
	public String getReligionCd() {
		return this.religionCd;
	}

	public void setReligionCd(String religionCd) {
		this.religionCd = religionCd;
	}

	@Column(name = "ZIP_CD", length = 10)
	public String getZipCd() {
		return this.zipCd;
	}

	public void setZipCd(String zipCd) {
		this.zipCd = zipCd;
	}

	@Column(name = "STATECITYZIP_PATH", length = 700)
	public String getStatecityzipPath() {
		return this.statecityzipPath;
	}

	public void setStatecityzipPath(String statecityzipPath) {
		this.statecityzipPath = statecityzipPath;
	}

	@Column(name = "INCOME_CD", length = 50)
	public String getIncomeCd() {
		return this.incomeCd;
	}

	public void setIncomeCd(String incomeCd) {
		this.incomeCd = incomeCd;
	}

	@Column(name = "PATIENT_BLOB")
	public Clob getPatientBlob() {
		return this.patientBlob;
	}

	public void setPatientBlob(Clob patientBlob) {
		this.patientBlob = patientBlob;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "UPDATE_DATE", length = 7)
	public Date getUpdateDate() {
		return this.updateDate;
	}

	public void setUpdateDate(Date updateDate) {
		this.updateDate = updateDate;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "DOWNLOAD_DATE", length = 7)
	public Date getDownloadDate() {
		return this.downloadDate;
	}

	public void setDownloadDate(Date downloadDate) {
		this.downloadDate = downloadDate;
	}

	@Temporal(TemporalType.DATE)
	@Column(name = "IMPORT_DATE", length = 7)
	public Date getImportDate() {
		return this.importDate;
	}

	public void setImportDate(Date importDate) {
		this.importDate = importDate;
	}

	@Column(name = "SOURCESYSTEM_CD", length = 50)
	public String getSourcesystemCd() {
		return this.sourcesystemCd;
	}

	public void setSourcesystemCd(String sourcesystemCd) {
		this.sourcesystemCd = sourcesystemCd;
	}

	@Column(name = "UPLOAD_ID", precision = 38, scale = 0)
	public BigDecimal getUploadId() {
		return this.uploadId;
	}

	public void setUploadId(BigDecimal uploadId) {
		this.uploadId = uploadId;
	}

}


text:
<node text="Object (java.lang)">
  <node text="SecondClass ()">
    <node text="KotlinClass ()">
      <node text="MyClass ()" base="true"/>
    </node>
  </node>
</node>


text:
namespace djinni_generated {

class NativeListenerCaller final : ::djinni::JniInterface<::testsuite::ListenerCaller, NativeListenerCaller> {
public:
    using CppType = std::shared_ptr<::testsuite::ListenerCaller>;
    using CppOptType = std::shared_ptr<::testsuite::ListenerCaller>;
    using JniType = jobject;

    using Boxed = NativeListenerCaller;

    ~NativeListenerCaller();

    static CppType toCpp(JNIEnv* jniEnv, JniType j) { return ::djinni::JniClass<NativeListenerCaller>::get()._fromJava(jniEnv, j); }
    static ::djinni::LocalRef<JniType> fromCppOpt(JNIEnv* jniEnv, const CppOptType& c) { return {jniEnv, ::djinni::JniClass<NativeListenerCaller>::get()._toJava(jniEnv, c)}; }
    static ::djinni::LocalRef<JniType> fromCpp(JNIEnv* jniEnv, const CppType& c) { return fromCppOpt(jniEnv, c); }

private:
    NativeListenerCaller();
    friend ::djinni::JniClass<NativeListenerCaller>;
    friend ::djinni::JniInterface<::testsuite::ListenerCaller, NativeListenerCaller>;

};

}  // namespace djinni_generated


text:
{% extends "base.html" %}
{% block title %}Index{% endblock %}
{% block lessFilename %}main{% endblock %}
{% block jsFilename %}main-page.js{% endblock %}
{% block content %}

            <button type="button" class="navbar-toggle" data-toggle="collapse"
                    data-target=".navbar-collapse">
                Toggle navigation
            </button>
            Social Health Observatory

                    Import/Export

Export configuration file

Import configuration file

Layers

Datasets

{% endblock %}


text:
namespace bdm {

/// AgentUidMap is an associative container that exploits the properties of
/// AgentUid to store data in contigous arrays. Inserting elements and reading
/// elements at the same time is thread-safe as long as the keys are different.
/// These operations with distinct keys are lock-free and atomic free, and thus
/// offer high-performance.
template <typename TValue>
class AgentUidMap {
  struct Iterator {
    AgentUidMap* map_;
    uint64_t idx_;
  };

 public:
  AgentUidMap() = default;

  AgentUidMap(const AgentUidMap& other)
      : data_(other.data_), agent_uid_reused_(other.agent_uid_reused_) {}

  explicit AgentUidMap(uint64_t initial_size) {
    data_.resize(initial_size);
    agent_uid_reused_.resize(initial_size, AgentUid::kReusedMax);
  }

  void resize(uint64_t new_size) {  // NOLINT
    data_.resize(new_size);
    agent_uid_reused_.resize(new_size, AgentUid::kReusedMax);
  }

  void clear() {  // NOLINT
    for (auto& el : agent_uid_reused_) {
      el = AgentUid::kReusedMax;
    }
  }

  void ParallelClear() {
#pragma omp parallel for
    for (uint64_t i = 0; i < data_.size(); ++i) {
      agent_uid_reused_[i] = AgentUid::kReusedMax;
    }
  }

  uint64_t size() const {  // NOLINT
    return data_.size();
  }

  void Remove(const AgentUid& key) {
    if (key.GetIndex() >= data_.size()) {
      return;
    }
    agent_uid_reused_[key.GetIndex()] = AgentUid::kReusedMax;
  }

  bool Contains(const AgentUid& uid) const {
    auto idx = uid.GetIndex();
    if (idx >= data_.size()) {
      return false;
    }
    return uid.GetReused() == agent_uid_reused_[idx];
  }

  void Insert(const AgentUid& uid, const TValue& value) {
    auto idx = uid.GetIndex();
    data_[idx] = value;
    agent_uid_reused_[idx] = uid.GetReused();
  }

  const TValue& operator[](const AgentUid& key) const {
    return data_[key.GetIndex()];
  }

  typename AgentUid::Reused_t GetReused(uint64_t index) const {
    return agent_uid_reused_[index];
  }

 private:
  std::vector<TValue> data_;
  std::vector<typename AgentUid::Reused_t> agent_uid_reused_;
};

}  // namespace bdm

#endif  // CORE_CONTAINER_AGENT_UID_MAP_H_


text:
<?php
namespace BnetTest\Warcraft;

use BnetTest\TestClient;
use Bnet\Warcraft\Quests\QuestRequest;

class QuestRequestTest extends \PHPUnit_Framework_TestCase
{
    public function testFind()
    {
        $request  = new QuestRequest(new TestClient('wow'));
        $response = $request->find(13146);

        $this->assertInstanceOf('\Bnet\Warcraft\Quests\QuestEntity', $response);
        $this->assertSame(13146, $response->id);
    }

    public function testFindInvalidId()
    {
        $request  = new QuestRequest(new TestClient('wow'));
        $response = $request->find('invalid');

        $this->assertNull($response);
    }
}


text:
namespace AdminPanel.Server.Api.Controllers;

public partial class AppControllerBase : ControllerBase
{
    [AutoInject] protected IOptionsSnapshot<AppSettings> AppSettings = default!;

    [AutoInject] protected IMapper Mapper = default!;

    [AutoInject] protected AppDbContext DbContext = default!;

    [AutoInject] protected IStringLocalizer<AppStrings> Localizer = default!;
}


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 org.flowable.idm.engine.test.api.identity;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.flowable.engine.common.api.FlowableException;
import org.flowable.engine.common.api.FlowableIllegalArgumentException;
import org.flowable.idm.api.Token;
import org.flowable.idm.api.TokenQuery;
import org.flowable.idm.engine.impl.persistence.entity.TokenEntity;
import org.flowable.idm.engine.test.PluggableFlowableIdmTestCase;

/**
 * @author Tijs Rademakers
 */
public class TokenQueryTest extends PluggableFlowableIdmTestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();

        Calendar tokenCal = new GregorianCalendar();
        tokenCal.set(2015, 1, 1, 0, 0, 0);
        createToken("1111", "aaaa", tokenCal.getTime(), "127.0.0.1", "chrome", "user1", null);

        tokenCal.set(2016, 1, 1, 0, 0, 0);
        createToken("2222", "bbbb", tokenCal.getTime(), "128.0.0.2", "firefox", "user2", null);

        tokenCal.set(2017, 1, 1, 0, 0, 0);
        createToken("3333", "cccc", tokenCal.getTime(), "129.0.0.1", "firefox2", "bla3", "test");
    }

    private Token createToken(String id, String tokenValue, Date tokenDate, String ipAddress,
            String userAgent, String userId, String tokenData) {

        Token token = idmIdentityService.newToken(id);
        token.setTokenValue(tokenValue);
        token.setTokenDate(tokenDate);
        token.setIpAddress(ipAddress);
        token.setUserAgent(userAgent);
        token.setUserId(userId);
        token.setTokenData(tokenData);
        idmIdentityService.saveToken(token);
        return token;
    }

    @Override
    protected void tearDown() throws Exception {
        idmIdentityService.deleteToken("1111");
        idmIdentityService.deleteToken("2222");
        idmIdentityService.deleteToken("3333");

        super.tearDown();
    }

    public void testQueryByNoCriteria() {
        TokenQuery query = idmIdentityService.createTokenQuery();
        verifyQueryResults(query, 3);
    }

    public void testQueryById() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenId("1111");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidId() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenId("invalid");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().tokenId(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByTokenValue() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenValue("aaaa");
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        assertEquals("aaaa", result.getTokenValue());
    }

    public void testQueryByInvalidTokenValue() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenValue("invalid");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().tokenValue(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByTokenDateBefore() {
        Calendar queryCal = new GregorianCalendar(2015, 6, 1, 0, 0, 0);
        TokenQuery query = idmIdentityService.createTokenQuery().tokenDateBefore(queryCal.getTime());
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        Calendar tokenCal = new GregorianCalendar();
        tokenCal.setTime(result.getTokenDate());
        assertEquals(2015, tokenCal.get(Calendar.YEAR));
        assertEquals(1, tokenCal.get(Calendar.MONTH));
    }

    public void testQueryByTokenDateAfter() {
        Calendar queryCal = new GregorianCalendar(2016, 6, 1, 0, 0, 0);
        TokenQuery query = idmIdentityService.createTokenQuery().tokenDateAfter(queryCal.getTime());
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        Calendar tokenCal = new GregorianCalendar();
        tokenCal.setTime(result.getTokenDate());
        assertEquals(2017, tokenCal.get(Calendar.YEAR));
        assertEquals(1, tokenCal.get(Calendar.MONTH));
    }

    public void testQueryByIpAddress() {
        TokenQuery query = idmIdentityService.createTokenQuery().ipAddress("127.0.0.1");
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        assertEquals("127.0.0.1", result.getIpAddress());
    }

    public void testQueryByInvalidIpAddress() {
        TokenQuery query = idmIdentityService.createTokenQuery().ipAddress("invalid");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().ipAddress(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByIpAddressLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().ipAddressLike("%0.0.1%");
        verifyQueryResults(query, 2);

        query = idmIdentityService.createTokenQuery().ipAddressLike("129.%");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidIpAddressLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().ipAddressLike("%invalid%");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().ipAddressLike(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByUserAgent() {
        TokenQuery query = idmIdentityService.createTokenQuery().userAgent("chrome");
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        assertEquals("chrome", result.getUserAgent());
    }

    public void testQueryByInvalidUserAgent() {
        TokenQuery query = idmIdentityService.createTokenQuery().userAgent("invalid");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().userAgent(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByUserAgentLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().userAgentLike("%fire%");
        verifyQueryResults(query, 2);

        query = idmIdentityService.createTokenQuery().userAgentLike("ch%");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidUserAgentLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().userAgentLike("%invalid%");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().userAgentLike(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByUserId() {
        TokenQuery query = idmIdentityService.createTokenQuery().userId("user1");
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        assertEquals("user1", result.getUserId());
    }

    public void testQueryByInvalidUserId() {
        TokenQuery query = idmIdentityService.createTokenQuery().userId("invalid");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().userId(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByUserIdLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().userIdLike("%user%");
        verifyQueryResults(query, 2);

        query = idmIdentityService.createTokenQuery().userIdLike("bla%");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidUserIdLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().userIdLike("%invalid%");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().userIdLike(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByTokenData() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenData("test");
        verifyQueryResults(query, 1);

        Token result = query.singleResult();
        assertEquals("test", result.getTokenData());
    }

    public void testQueryByInvalidTokenData() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenData("invalid");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().tokenData(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQueryByTokenDataLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenDataLike("%test%");
        verifyQueryResults(query, 1);
    }

    public void testQueryByInvalidTokenDataLike() {
        TokenQuery query = idmIdentityService.createTokenQuery().tokenDataLike("%invalid%");
        verifyQueryResults(query, 0);

        try {
            idmIdentityService.createTokenQuery().tokenDataLike(null).singleResult();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    public void testQuerySorting() {
        // asc
        assertEquals(3, idmIdentityService.createTokenQuery().orderByTokenId().asc().count());
        assertEquals(3, idmIdentityService.createTokenQuery().orderByTokenDate().asc().count());

        // desc
        assertEquals(3, idmIdentityService.createTokenQuery().orderByTokenId().desc().count());
        assertEquals(3, idmIdentityService.createTokenQuery().orderByTokenDate().desc().count());

        // Combined with criteria
        TokenQuery query = idmIdentityService.createTokenQuery().userAgentLike("%firefox%").orderByTokenDate().asc();
        List<Token> tokens = query.list();
        assertEquals(2, tokens.size());
        assertEquals("firefox", tokens.get(0).getUserAgent());
        assertEquals("firefox2", tokens.get(1).getUserAgent());
    }

    public void testQueryInvalidSortingUsage() {
        try {
            idmIdentityService.createTokenQuery().orderByTokenId().list();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }

        try {
            idmIdentityService.createTokenQuery().orderByTokenId().orderByTokenDate().list();
            fail();
        } catch (FlowableIllegalArgumentException e) {
        }
    }

    private void verifyQueryResults(TokenQuery query, int countExpected) {
        assertEquals(countExpected, query.list().size());
        assertEquals(countExpected, query.count());

        if (countExpected == 1) {
            assertNotNull(query.singleResult());
        } else if (countExpected > 1) {
            verifySingleResultFails(query);
        } else if (countExpected == 0) {
            assertNull(query.singleResult());
        }
    }

    private void verifySingleResultFails(TokenQuery query) {
        try {
            query.singleResult();
            fail();
        } catch (FlowableException e) {
        }
    }

    public void testNativeQuery() {
        assertEquals("ACT_ID_TOKEN", idmManagementService.getTableName(Token.class));
        assertEquals("ACT_ID_TOKEN", idmManagementService.getTableName(TokenEntity.class));
        String tableName = idmManagementService.getTableName(Token.class);
        String baseQuerySql = "SELECT * FROM " + tableName;

        assertEquals(3, idmIdentityService.createNativeUserQuery().sql(baseQuerySql).list().size());

        assertEquals(1, idmIdentityService.createNativeUserQuery().sql(baseQuerySql + " where ID_ = #{id}").parameter("id", "1111").list().size());

        // paging
        assertEquals(2, idmIdentityService.createNativeUserQuery().sql(baseQuerySql).listPage(0, 2).size());
        assertEquals(2, idmIdentityService.createNativeUserQuery().sql(baseQuerySql).listPage(1, 3).size());
        assertEquals(1, idmIdentityService.createNativeUserQuery().sql(baseQuerySql + " where ID_ = #{id}").parameter("id", "1111").listPage(0, 1).size());
    }

}


text:
using System;
using System.IO;
using System.Text;
using YaR.Clouds.Extensions;

namespace YaR.Clouds.Base.Repos.MailRuCloud.Mobile.Requests.Types
{
    class ResponseBodyStream : IDisposable
    {
        private readonly Stream _stream;

        public ResponseBodyStream(Stream stream)
        {
            _stream = stream;
            OperationResult = (OperationResult)ReadShort();
        }
        public short ReadShort()
        {
            return (short)(ReadInt() & 255);
        }

        public OperationResult OperationResult { get; }

        public int ReadIntSpl()
        {
            //Debug.Write($"{nameof(ReadIntSpl)}() = ");

            int res = (ReadInt() & 255) | ((ReadInt() & 255) << 8);

            //Debug.WriteLine($" = {res}");
            return res;
        }

        public byte[] ReadNBytes(long count)
        {
            int total = (int)count;
            byte[] bytes = new byte[total];

            int bytesRead = 0;
            int read;
            while ((read = _stream.Read(bytes, bytesRead, total - bytesRead)) > 0)
                bytesRead += read;

            if (bytesRead < total)
                throw new Exception($"End of stream {nameof(ReadNBytes)}");

            return bytes;
        }

        public int ReadInt()
        {
            int b = _stream.ReadByte();

            //Debug.Write($"{b:X} ");

            if (b == -1)
                throw new Exception("End of stream");
            return b;
        }

        public ulong ReadULong()
        {
            //Debug.Write($"{nameof(ReadULong)}() = ");

            int i = 0;
            byte[] bytes = new byte[8];
            int val;
            do
            {
                val = ReadInt();
                int high = val & 127;
                int rem = 7 - i / 8;
                int div = i % 8;
                bytes[rem] = (byte) (bytes[rem] | ((high << div) & 255));
                high >>= 8 - div;
                if (high == 0 || rem != 0)
                {
                    if (high != 0 && div > 0)
                    {
                        rem--;
                        bytes[rem] = (byte)(high | bytes[rem]);
                    }
                    i = (byte) (i + 7);
                }
                else
                    throw new Exception("Pu64 error");
            } while ((val & 128) != 0);

            Array.Reverse(bytes);
            UInt64 res = BitConverter.ToUInt64(bytes, 0);
            //Debug.WriteLine($" = {res}");
            return res;
        }

        public long ReadPu32()
        {
            //Debug.Write($"(");
            long j = 0;
            int shift = 0;
            int b;
            do
            {
                b = ReadInt();
                j |= (long) (b & 127) << shift;
                shift = (byte) (shift + 7);
            } while ((b & 128) != 0);

            //Debug.Write($" = {j}) ");
            return j;
        }

        public byte[] ReadBytesByLength()
        {
            var len = ReadPu32();
            return ReadNBytes((int)len);
        }

        public string ReadNBytesAsString(long bytesCount)
        {
            var data = ReadNBytes(bytesCount);
            string res = Encoding.UTF8.GetString(data);
            //Debug.WriteLine($"string = {res}");
            return res;
        }

        public string ReadString()
        {
            string str = ReadNBytesAsString(ReadPu32() - 1);

            if (ReadInt() != 0)
                throw new FormatException("String does not ends with zero");

            return str;
        }

        public byte[] ReadAllBytes()
        {
            const int bufferSize = 4096;
            using var ms = new MemoryStream();

            byte[] buffer = new byte[bufferSize];
            int count;
            while ((count = _stream.Read(buffer, 0, buffer.Length)) != 0)
                ms.Write(buffer, 0, count);
            return ms.ToArray();
        }

        public TreeId ReadTreeId()
        {
            return TreeId.FromStream(this);
        }

        public DateTime ReadDate()
        {
            var res = ReadULong().ToDateTime();

            //Debug.WriteLine($"datetime = {res}");

            return res;
        }

        public void Dispose()
        {
            //_stream?.Dispose();
        }
    }
}


text:
/******************************************************************************
Includes   <System Includes> , "Project Includes"
******************************************************************************/
#include <stdint.h>
#include "iodefine.h"
#include "cgc.h"
#include "rskrx630def.h"

/******************************************************************************
Typedef definitions
******************************************************************************/

/******************************************************************************
Macro definitions
******************************************************************************/

/******************************************************************************
Imported global variables and functions (from other files)
******************************************************************************/

/******************************************************************************
Exported global variables and functions (to be accessed by other files)
******************************************************************************/

/******************************************************************************
Private global variables and functions
******************************************************************************/
void io_set_cpg(void);
void ConfigurePortPins(void);
void EnablePeripheralModules(void);

/******************************************************************************
* Function Name: HardwareSetup
* Description  : This function does initial setting for CPG port pins used in
*              : the Demo including the MII pins of the Ethernet PHY connection.
* Arguments    : none
* Return Value : none
******************************************************************************/
void HardwareSetup(void)
{
	/* Gain access to the System control registers                           */
    /* Refer to section 13 of the Hardware User Manual for further details   */
    SYSTEM.PRCR.WORD = 0xA503;

    /* Gain access to the Port Function Select Registers                     */
	/* Refer to section 21 of the Hardware User Manual for further details   */
    MPC.PWPR.BIT.B0WI = 0;
	MPC.PWPR.BIT.PFSWE = 1;

    /* CPG setting */
    /* User defined values for XTAL, Clock Divders etc are set in cgc.h      */
    InitCGC();

	/* Setup the port pins */
	ConfigurePortPins();

    /* Enables peripherals */
    EnablePeripheralModules();

#if INCLUDE_LCD == 1
    /* Initialize display */
    InitialiseDisplay();
#endif
}

/******************************************************************************
* Function Name: EnablePeripheralModules
* Description  : Enables Peripheral Modules before use
* Arguments    : none
* Return Value : none
******************************************************************************/
void EnablePeripheralModules(void)
{
	/*  Module standby clear */
    SYSTEM.MSTPCRA.BIT.MSTPA15 = 0;             /* CMT0 */
}

/******************************************************************************
* Function Name: ConfigurePortPins
* Description  : Configures port pins.
* Arguments    : none
* Return Value : none
******************************************************************************/
void ConfigurePortPins(void)
{
/* Port pins default to inputs. To ensure safe initialisation set the pin states
before changing the data direction registers. This will avoid any unintentional
state changes on the external ports.
Many peripheral modules will override the setting of the port registers. Ensure
that the state is safe for external devices if the internal peripheral module is
disabled or powered down. */

    /* Set initial LED pin state to off */
    LED0     = 1;
    LED1     = 1;
    LED2     = 1;
    LED3     = 1;
    /* Configure LED 0-3 pin settings */
    LED0_PDR = 1;
    LED1_PDR = 1;
    LED2_PDR = 1;
    LED3_PDR = 1;

    /* Configure SW 1-3 pin settings */
    /* No need to configure inputs as they are inputs by default */

#if INCLUDE_LCD == 1
    /* Set LCD pins as outputs */
    /* LCD-RS */
    LCD_RS_PDR = 1;
    /* LCD-EN */
    LCD_EN = 1;
    /*LCD-data */
    LCD_DATA_PDR = 0xF0;
#endif
}


text:
package org.archive.resource.html;

import org.archive.resource.MetaData;
import org.htmlparser.nodes.TextNode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import junit.framework.TestCase;

public class ExtractingParseObserverTest extends TestCase {

	public void testHandleStyleNodeExceptions() throws Exception {
		String[] tests = {
				"some css",
				"url()",
				"url () ",
				"url ('')",
				"url (' ')",
				"url('\")",
				"url(')",
				"url('\"')"
		};
		boolean except = false;
		HTMLMetaData md = new HTMLMetaData(new MetaData());
		ExtractingParseObserver epo = new ExtractingParseObserver(md);
		for(String css : tests) {
			try {
				TextNode tn = new TextNode(css);
				epo.handleStyleNode(tn);
			} catch(Exception e) {
				System.err.format("And the winner is....(%s)\n", css);
				e.printStackTrace();
				except = true;
				throw e;
			}
			assertFalse(except);
		}
	}
	public void testHandleStyleNode() throws Exception {
		String[][] tests = {
				{""},
				{"url(foo.gif)","foo.gif"},
				{"url('foo.gif')","foo.gif"},
				{"url(\"foo.gif\")","foo.gif"},
				{"url(\\\"foo.gif\\\")","foo.gif"},
				{"url(\\'foo.gif\\')","foo.gif"},

		};
		for(String[] testa : tests) {
			checkExtract(testa);
		}
		//		boolean except = false;
//		HTMLMetaData md = new HTMLMetaData(new MetaData());
//		ExtractingParseObserver epo = new ExtractingParseObserver(md);
//		for(String css : tests) {
//			try {
//				TextNode tn = new TextNode(css);
//				epo.handleStyleNode(tn);
//			} catch(Exception e) {
//				System.err.format("And the winner is....(%s)\n", css);
//				e.printStackTrace();
//				except = true;
//				throw e;
//			}
//			assertFalse(except);
//		}
	}
	private void checkExtract(String[] data) throws JSONException {
//		System.err.format("CSS(%s) want[0](%s)\n",css,want[0]);
		String css = data[0];
		boolean except = false;
		HTMLMetaData md = new HTMLMetaData(new MetaData());
		ExtractingParseObserver epo = new ExtractingParseObserver(md);
		try {
			TextNode tn = new TextNode(css);
			epo.handleStyleNode(tn);
		} catch(Exception e) {
			fail("Exception with CSS:" + css);
		}
		JSONArray a = md.optJSONArray("Links");
		if(data.length > 1) {
			assertNotNull(a);
			assertEquals(data.length-1,a.length());
			for(int i = 1; i < data.length; i++) {
				Object o = a.optJSONObject(i-1);

				assertTrue(o instanceof JSONObject);
				JSONObject jo = (JSONObject) o;
				assertEquals(data[i],jo.getString("href"));
			}
		} else {
			assertNull(a);
		}
	}

}


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

<TITLE>
soot.jimple.toolkits.reflection (Soot API)
</TITLE>

<META NAME="date" CONTENT="2012-01-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

soot.jimple.toolkits.reflection

Classes

ReflectionTraceInfo

ReflectiveCallsInliner

ReflInliner

Enums

ReflectionTraceInfo.Kind


text:
namespace ash {

SuggestedContentInfoView::SuggestedContentInfoView(
    AppListViewDelegate* view_delegate,
    PrivacyContainerView* container)
    : PrivacyInfoView(IDS_APP_LIST_SUGGESTED_CONTENT_INFO,
                      IDS_APP_LIST_MANAGE_SETTINGS),
      view_delegate_(view_delegate),
      container_(container) {}

SuggestedContentInfoView::~SuggestedContentInfoView() = default;

void SuggestedContentInfoView::CloseButtonPressed() {
  view_delegate_->MarkSuggestedContentInfoDismissed();
  container_->Update();
}

void SuggestedContentInfoView::LinkClicked() {
  view_delegate_->MarkSuggestedContentInfoDismissed();
  constexpr char url[] = "chrome://os-settings/osPrivacy";
  NewWindowDelegate::GetInstance()->OpenUrl(
      GURL(url), NewWindowDelegate::OpenUrlFrom::kUserInteraction);
}

}  // namespace ash


text:
<?php
// src/Common/DataBundle/Entity/Product.php
namespace Common\DataBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 *
 */
class BaseTimePrice
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var decimal $local_price
     *
     * @ORM\Column(name="local_price", type="decimal", scale=2)
     */
    protected $local_price;

    /**
     * @var decimal $currency_price
     *
     * @ORM\Column(name="currency_price", type="decimal", scale=2)
     */
    protected $currency_price;

    /**
     * @var decimal $currency_rate
     *
     * @ORM\Column(name="currency_rate", type="decimal", scale=2)
     */
    protected $currency_rate;

    /**
     * @var string $price_date
     *
     * @ORM\Column(name="price_date", type="datetime")
     */
    protected $price_date;

    /**
     * @var string $created_at
     *
     * @ORM\Column(name="created_at", type="datetime")
     */
    protected $created_at;

    /**
     * @var string $updated_at
     *
     * @ORM\Column(name="updated_at", type="datetime")
     */
    protected $updated_at;

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

    /**
     * Set local_price
     *
     * @param float $localPrice
     * @return BaseTimePrice
     */
    public function setLocalPrice($localPrice)
    {
        $this->local_price = $localPrice;

        return $this;
    }

    /**
     * Get local_price
     *
     * @return float
     */
    public function getLocalPrice()
    {
        return $this->local_price;
    }

    /**
     * Set currency_price
     *
     * @param float $currencyPrice
     * @return BaseTimePrice
     */
    public function setCurrencyPrice($currencyPrice)
    {
        $this->currency_price = $currencyPrice;

        return $this;
    }

    /**
     * Get currency_price
     *
     * @return float
     */
    public function getCurrencyPrice()
    {
        return $this->currency_price;
    }

    /**
     * Set currency_rate
     *
     * @param float $currencyRate
     * @return BaseTimePrice
     */
    public function setCurrencyRate($currencyRate)
    {
        $this->currency_rate = $currencyRate;

        return $this;
    }

    /**
     * Get currency_rate
     *
     * @return float
     */
    public function getCurrencyRate()
    {
        return $this->currency_rate;
    }

    /**
     * Set price_date
     *
     * @param \DateTime $priceDate
     * @return BaseTimePrice
     */
    public function setPriceDate($priceDate)
    {
        $this->price_date = $priceDate;

        return $this;
    }

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

    /**
     * Set created_at
     *
     * @param \DateTime $createdAt
     * @return BaseTimePrice
     */
    public function setCreatedAt($createdAt)
    {
        $this->created_at = $createdAt;

        return $this;
    }

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

    /**
     * Set updated_at
     *
     * @param \DateTime $updatedAt
     * @return BaseTimePrice
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updated_at = $updatedAt;

        return $this;
    }

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


text:
export default {
  // ids of the items that should be currently displayed based on
  // current list type and current pagination
  activeIds (state) {
    const { activeType, itemsPerPage, lists } = state

    if (!activeType) {
      return []
    }

    const page = Number(state.route.params.page) || 1
    const start = (page - 1) * itemsPerPage
    const end = page * itemsPerPage

    return lists[activeType].slice(start, end)
  },

  // items that should be currently displayed.
  // this Array may not be fully fetched.
  activeItems (state, getters) {
    return getters.activeIds.map(id => state.items[id]).filter(_ => _)
  }
}


text:
@interface PayRecodeController : QPTBaseViewController

@end


text:
import {Component} from 'angular2/core';
import {ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
  selector: 'gt-footer',
  templateUrl: 'app/components/footer.component.html',
  styleUrls: ['app/components/footer.component.less'],
  directives: [ROUTER_DIRECTIVES]
})
export class FooterComponent {}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/.idea/laravel-montesquieu.iml" filepath="$PROJECT_DIR$/.idea/laravel-montesquieu.iml" />
    </modules>
  </component>
</project>


text:
#pragma once

#include <folly/dynamic.h>

#include <react/core/ReactPrimitives.h>
#include <react/core/Sealable.h>
#include <react/debug/DebugStringConvertible.h>

namespace facebook {
namespace react {

class Props;

using SharedProps = std::shared_ptr<Props const>;

/*
 * Represents the most generic props object.
 */
class Props : public virtual Sealable, public virtual DebugStringConvertible {
 public:
  using Shared = std::shared_ptr<Props const>;

  Props() = default;
  Props(Props const &sourceProps, RawProps const &rawProps);
  virtual ~Props() = default;

  std::string nativeId;

  /*
   * Special value that represents generation number of `Props` object, which
   * increases when the object was constructed with some source `Props` object.
   * Default props objects (that was constructed using default constructor) have
   * revision equals `0`.
   * The value might be used for optimization purposes.
   */
  int const revision{0};

#ifdef ANDROID
  folly::dynamic const rawProps = folly::dynamic::object();
#endif
};

} // namespace react
} // namespace facebook


text:
class CarEngine;

class Vehicle : public vtTransform
{
public:
	Vehicle();
	~Vehicle();

	void ShowBounds(bool bShow);

	vtGeode	*m_pHighlight;	// The wireframe highlight

	vtTransform *m_pFrontLeft;
	vtTransform *m_pFrontRight;
	vtTransform *m_pRearLeft;
	vtTransform *m_pRearRight;

	float GetWheelRadius() { return 0.25f; }	// TODO: get real value
};

class VehicleManager
{
public:
	VehicleManager();
	~VehicleManager();

	Vehicle *CreateVehicle(const char *szType, const RGBf &cColor);

protected:
	Vehicle *CreateVehicleFromNode(osg::Node *node, const RGBf &cColor);
};

class VehicleSet
{
public:
	VehicleSet();

	void AddEngine(CarEngine *e);
	int FindClosestVehicle(const FPoint3 &point, double &closest);
	void VisualSelect(int vehicle);
	void VisualDeselectAll();
	int GetSelected() { return m_iSelected; }
	void SetVehicleSpeed(int vehicle, float fMetersPerSec);

	CarEngine *GetSelectedCarEngine();
	void SetSelectedRotation(float fRot);

	std::vector<CarEngine*> m_Engines;
	int m_iSelected;
};

#endif	// VEHICLEH


text:
using System;
using System.Collections.Generic;
using Discord;
using Discord.Commands;

namespace Kohaku
{
    public class GuildPrefixService
    {
        private readonly Dictionary<ulong, string> _prefixes = new Dictionary<ulong, string>();

        public bool HasGuildSpecificPrefix(IUserMessage message, ref int pos)
        {
            if (message.Channel is IGuildChannel guildChannel && _prefixes.TryGetValue(guildChannel.GuildId, out var prefix))
            {
                return message.HasStringPrefix(prefix, ref pos);
            }
            else
            {
                return false;
            }
        }
    }

    public class ModuleGuildPrefixService
    {
        private readonly CommandService _commands;

        //(Guild.Id, ModuleName) => ModulePrefix
        private readonly Dictionary<(ulong, string), string> _prefixes = new Dictionary<(ulong, string), string>();

        public ModuleGuildPrefixService(CommandService commands)
        {
            _commands = commands;
        }

        public SearchResult Search(ICommandContext context, int argPos)
        {
            if (context.Guild != null)
            {
                foreach (var module in _commands.Modules)
                {
                    if (_prefixes.TryGetValue((context.Guild.Id, module.Name), out var prefix))
                    {
                        int prefixAdd = 0;
                        if (context.Message.HasStringPrefix(prefix, ref prefixAdd))
                        {
                            return _commands.Search(context, argPos + prefixAdd);
                        }
                    }
                }
            }

            return _commands.Search(context, argPos);
        }
    }
}


text:
<?php

namespace Google\Service\Storage;

class BucketAutoclass extends \Google\Model
{
  /**
   * @var bool
   */
  public $enabled;
  /**
   * @var string
   */
  public $toggleTime;

  /**
   * @param bool
   */
  public function setEnabled($enabled)
  {
    $this->enabled = $enabled;
  }
  /**
   * @return bool
   */
  public function getEnabled()
  {
    return $this->enabled;
  }
  /**
   * @param string
   */
  public function setToggleTime($toggleTime)
  {
    $this->toggleTime = $toggleTime;
  }
  /**
   * @return string
   */
  public function getToggleTime()
  {
    return $this->toggleTime;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(BucketAutoclass::class, 'Google_Service_Storage_BucketAutoclass');


text:
=pod

=head1 NAME

SVG - Perl extension for generating Scalable Vector Graphics (SVG) documents

=cut

package SVG;

use strict;
use vars qw($VERSION @ISA $AUTOLOAD);
use Exporter;
use SVG::XML;
use SVG::Element;
use SVG::Extension;
use Scalar::Util qw/weaken/;
use warnings;

@ISA = qw(SVG::Element SVG::Extension);

$VERSION = "2.50";

#-------------------------------------------------------------------------------

=pod

=head2 VERSION

Version 2.44, 08  April, 2008

Refer to L<SVG::Manual> for the complete manual

=head1 DESCRIPTION

SVG is a 100% Perl module which generates a nested data structure containing the
DOM representation of an SVG (Scalable Vector Graphics) image. Using SVG, you
can generate SVG objects, embed other SVG instances into it, access the DOM
object, create and access javascript, and generate SMIL animation content.

Refer to L<SVG::Manual> for the complete manual.

=head1 AUTHOR

Ronan Oger, RO IT Systemms GmbH, cpan@roitsystems.com.com

=head1 CREDITS

I would like to thank the following people for contributing to this module with
patches, testing, suggestions, and other nice tidbits:
Peter Wainwright, Ian Hickson, Adam Schneider, Steve Lihn, Allen Day

=head1 EXAMPLES

http://www.roitsystems.com/index.shtml?svg.pod

=head1 SEE ALSO

perl(1),L<SVG>,L<SVG::DOM>,L<SVG::XML>,L<SVG::Element>,L<SVG::Parser>, L<SVG::Manual> L<SVG::Extension>
L<http://www.roitsystems.com/> ROASP.com: Serverside SVG server
L<http://www.roitsystems.com/> ROIT Systems: Commercial SVG perl solutions
L<http://www.w3c.org/Graphics/SVG/> SVG at the W3C

=cut

#-------------------------------------------------------------------------------

my %default_attrs = (
    # processing options
    -auto       => 0,       # permit arbitrary autoloads (only at import)
    -printerror => 1,       # print error messages to STDERR
    -raiseerror => 1,       # die on errors (implies -printerror)

    # rendering options
    -indent     => "\t",    # what to indent with
    -elsep      => "\n",    # element line (vertical) separator
    -nocredits  => 0,       # enable/disable credit note comment
    -namespace  => '',      # The root element's (and it's children's) namespace prefix

    # XML and Doctype declarations
    -inline     => 0,       # inline or stand alone
    -docroot    => 'svg',   # The document's root element
    -version    => '1.0',
    -extension  => '',
    -encoding   => 'UTF-8',
    -xml_svg    => 'http://www.w3.org/2000/svg',
    -xml_xlink  => 'http://www.w3.org/1999/xlink',
    -standalone => 'yes',
    -pubid      => "-//W3C//DTD SVG 1.0//EN", # formerly -identifier
    -sysid      => 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
);

sub import {
    my $package=shift;

    my $attr=undef;
    foreach (@_) {
        if ($attr) {
            $default_attrs{$attr}=$_;
            undef $attr;
        } elsif (exists $default_attrs{$_}) {
            $attr=$_;
        } else {
            /^-/ and die "Unknown attribute '$_' in import list\n";
            $SVG::Element::autosubs{$_}=1; # add to list of autoloadable tags
        }
    }

    # switch on AUTOLOADer, if asked.
    if ($default_attrs{'-auto'}) {
        *SVG::Element::AUTOLOAD=\&SVG::Element::autoload;
    }

    # predeclare any additional elements asked for by the user
    foreach my $sub (keys %SVG::Element::autosubs) {
        $SVG::Element::AUTOLOAD=("SVG::Element::$sub");
        SVG::Element::autoload();
    }

    delete $default_attrs{-auto}; # -auto is only allowed here, not in new

    return ();
}

#-------------------------------------------------------------------------------

=pod

=head1 Methods

SVG provides both explicit and generic element constructor methods. Explicit
generators are generally (with a few exceptions) named for the element they
generate. If a tag method is required for a tag containing hyphens, the method
name replaces the hyphen with an underscore. ie: to generate tag <column-heading id="new">
you would use method $svg->column_heading(id=>'new').

All element constructors take a hash of element attributes and options;
element attributes such as 'id' or 'border' are passed by name, while options for the
method (such as the type of an element that supports multiple alternate forms)
are passed preceded by a hyphen, e.g '-type'. Both types may be freely
intermixed; see the L<"fe"> method and code examples througout the documentation
for more examples.

=head2 new (constructor)

$svg = SVG->new(%attributes)

Creates a new SVG object. Attributes of the document SVG element be passed as
an optional list of key value pairs. Additionally, SVG options (prefixed with
a hyphen) may be set on a per object basis:

B<Example:>

    my $svg1=new SVG;

    my $svg2=new SVG(id => 'document_element');

    my $svg3=new SVG(
        -printerror => 1,
        -raiseerror => 0,
        -indent     => '  ',
        -elsep      => "\n",  # element line (vertical) separator
        -docroot    => 'svg', # default document root element (SVG specification assumes svg). Defaults to 'svg' if undefined
        -xml_xlink  => 'http://www.w3.org/1999/xlink', # required by Mozilla's embedded SVG engine
        -sysid      => 'abc', # optional system identifier
        -pubid      => "-//W3C//DTD SVG 1.0//EN", # public identifier default value is "-//W3C//DTD SVG 1.0//EN" if undefined
        -namespace  => 'mysvg',
        -inline     => 1
        id          => 'document_element',
        width       => 300,
        height      => 200,
    );

Default SVG options may also be set in the import list. See L<"EXPORTS"> above
for more on the available options.

Furthermore, the following options:

    -version
    -encoding
    -standalone
    -namespace
    -inline
    -pubid (formerly -identifier)
    -sysid (standalone)

may also be set in xmlify, overriding any corresponding values set in the SVG->new declaration

=cut

#-------------------------------------------------------------------------------
#
# constructor for the SVG data model.
#
# the new constructor creates a new data object with a document tag at its base.
# this document tag then has either:
#     a child entry parent with its child svg generated (when -inline = 1)
# or
#     a child entry svg created.
#
# Because the new method returns the $self reference and not the
# latest child to be created, a hash key -document with the reference to the hash
# entry of its already-created child. hence the document object has a -document reference
# to parent or svg if inline is 1 or 0, and parent will have a -document entry
# pointing to the svg child.
#
# This way, the next tag constructor will descend the
# tree until it finds no more tags with -document, and will add
# the next tag object there.
# refer to the SVG::tag method

sub new ($;@) {
    my ($proto,%attrs) = @_;
    my $class = ref $proto || $proto;
    my $self;

    # establish defaults for unspecified attributes
    foreach my $attr (keys %default_attrs) {
        $attrs{$attr}=$default_attrs{$attr} unless exists $attrs{$attr}
    }
    $self = $class->SUPER::new('document');
    if (not $self->{-docref}) {
      $self->{-docref} = $self;
      weaken( $self->{-docref} );
    }
    unless ($attrs{-namespace}) {
        $attrs{'xmlns'} = $attrs{'xmlns'} || $attrs{'-xml_svg'};
    }
    $attrs{'xmlns:xlink'} = $attrs{'xmlns:xlink'} || $attrs{'-xml_xlink'} || 'http://www.w3.org/1999/xlink';
    $attrs{'xmlns:svg'} = $attrs{'xmlns:svg'} || $attrs{'-xml_svg'} || 'http://www.w3.org/2000/svg';

    $self->{-level} = 0;
    $self->{$_} = $attrs{$_} foreach keys %default_attrs;

    # create SVG object according to nostub attribute
    my $svg;
    unless ($attrs{-nostub}) {
        $svg = $self->svg(%attrs);
        $self->{-document} = $svg;
        weaken( $self->{-document} );
    }

    # add -attributes to SVG object
    #    $self->{-elrefs}->{$self}->{name} = 'document';
    #    $self->{-elrefs}->{$self}->{id} = '';

    return $self;
}

#-------------------------------------------------------------------------------

=pod

=head2 xmlify  (alias: to_xml render serialize serialise )

$string = $svg->xmlify(%attributes);

Returns xml representation of svg document.

B<XML Declaration>

    Name               Default Value
    -version           '1.0'
    -encoding          'UTF-8'
    -standalone        'yes'
    -namespace         'svg' - namespace prefix for elements.
                               Can also be used in any element method to over-ride
                               the current namespace prefix. Make sure to have
                               declared the prefix before using it.
    -inline            '0' - If '1', then this is an inline document.
    -pubid             '-//W3C//DTD SVG 1.0//EN';
    -sysid             'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd'

=cut

sub xmlify ($;@) {

    my ($self,%attrs) = @_;
    my ($decl,$ns);

    my $credits = '';

    # Give the module and myself credit unless explicitly turned off
    unless ($self->{-docref}->{-nocredits}) {
        $self->comment("\n\tGenerated using the Perl SVG Module V$VERSION\n\tby Ronan Oger\n\tInfo: http://www.roitsystems.com/\n" );
    }

    foreach my $key (keys %attrs) {
        next unless ($key =~ /^\-/);
        $self->{$key} = $attrs{$key};
    }

    foreach my $key (keys %$self) {
        next unless ($key =~ /^\-/);
        $attrs{$key} ||= $self->{$key};
    }

    return $self->SUPER::xmlify($self->{-namespace});
}

*render=\&xmlify;
*to_xml=\&xmlify;
*serialise=\&xmlify;
*serialize=\&xmlify;

=head2 perlify ()

return the perl code which generates the SVG document as it currently exists.

=cut

sub perlify ($;@) {
    return shift->SUPER::perlify();
}

=head2 toperl ()

Alias for method perlify()

=cut

*toperl=\&perlify;

#-------------------------------------------------------------------------------

#LICENSE
#
#
#
#The modules in the SVG distribution are distributed under the same license
# as Perl itself. It is provided free of warranty and may be re-used freely.
#
#
#

1;


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
__COPYRIGHT__

This file is processed by the bin/SConsDoc.py module.
See its __doc__ string for a discussion of the format.
-->

<!DOCTYPE sconsdoc [
<!ENTITY % scons SYSTEM '../../../../doc/scons.mod'>
%scons;
<!ENTITY % builders-mod SYSTEM '../../../../doc/generated/builders.mod'>
%builders-mod;
<!ENTITY % functions-mod SYSTEM '../../../../doc/generated/functions.mod'>
%functions-mod;
<!ENTITY % tools-mod SYSTEM '../../../../doc/generated/tools.mod'>
%tools-mod;
<!ENTITY % variables-mod SYSTEM '../../../../doc/generated/variables.mod'>
%variables-mod;
]>

<sconsdoc xmlns="http://www.scons.org/dbxsd/v1.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.scons.org/dbxsd/v1.0 http://www.scons.org/dbxsd/v1.0/scons.xsd">

<tool name="Perforce">
<summary>
<para>
Sets construction variables for interacting with the
Perforce source code management system.
</para>
</summary>
<sets>
<item>P4</item>
<item>P4FLAGS</item>
<item>P4COM</item>
</sets>
<uses>
<item>P4COMSTR</item>
</uses>
</tool>

<cvar name="P4">
<summary>
<para>
The Perforce executable.
</para>
</summary>
</cvar>

<cvar name="P4COM">
<summary>
<para>
The command line used to
fetch source files from Perforce.
</para>
</summary>
</cvar>

<cvar name="P4COMSTR">
<summary>
<para>
The string displayed when
fetching a source file from Perforce.
If this is not set, then &cv-link-P4COM; (the command line) is displayed.
</para>
</summary>
</cvar>

<cvar name="P4FLAGS">
<summary>
<para>
General options that are passed to Perforce.
</para>
</summary>
</cvar>

<scons_function name="Perforce">
<arguments signature="env">
()
</arguments>
<summary>
<para>
A factory function that
returns a Builder object
to be used to fetch source files
from the Perforce source code management system.
The returned Builder
is intended to be passed to the
&f-SourceCode;
function.
</para>

<para>
This function is deprecated.  For details, see the entry for the
&f-SourceCode;
function.
</para>

<para>
Example:
</para>

<example_commands>
env.SourceCode('.', env.Perforce())
</example_commands>

<para>
Perforce uses a number of external
environment variables for its operation.
Consequently, this function adds the
following variables from the user's external environment
to the construction environment's
ENV dictionary:
P4CHARSET,
P4CLIENT,
P4LANGUAGE,
P4PASSWD,
P4PORT,
P4USER,
SystemRoot,
USER,
and
USERNAME.
</para>
</summary>
</scons_function>

</sconsdoc>


text:
<?php
	require "../../pattern/config.php";// carrega as constantes
	require "../../process/connection_operations.php";

	$quest = array("queEnunciado"=> 0, "que_temCodigo" => 0);
	$quest = array(
		"queEnunciado" => $_POST['queEnunciado'],
		"que_temCodigo" => $_POST['que_temCodigo']
	);

	$grava = DBCreate('questao', $quest);
	if($grava){
		echo ":-)";
		echo"<script>alert('Sucesso');</script>;";
	}else{
		echo ":/";
		echo"<script>alert('Falha');</script>;";
	}
	echo '<meta http-equiv="refresh" content=1;url="../../pages/gerenciar/cadastrarquestoes.php">';
?>


text:
<?php

/**
 * SlyS
 *
 * @author     Evgheni Poleacov <evgheni.poleacov@gmail.com>
 *
 * @version    $Id: Login.php 821 2010-12-17 16:24:51Z deeper $
 */
class User_Form_Widget_UserFilter extends Zend_Form_SubForm
{

    public function init()
    {
        $this->setMethod('POST');

        $roles = User_Model_DbTable_Role::getInstance()->getRoles();

        $options = $this->getView()->toList($roles->toArray(), 'id','name');

        $roleElement = new Zend_Form_Element_Select('role');
        $roleElement->addMultiOptions($options);
        $roleElement->setLabel('Role:');
        $roleElement->setRequired(true);
        $this->addElement($roleElement);
    }

}


text:
package org.jclouds.dimensiondata.cloudcontroller.handlers;

import static org.jclouds.Constants.PROPERTY_MAX_RETRIES;
import static org.jclouds.http.HttpUtils.closeClientButKeepContentStream;

import javax.annotation.Resource;
import javax.inject.Named;
import javax.inject.Singleton;

import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.logging.Logger;

import com.google.common.annotations.Beta;
import com.google.inject.Inject;

/**
 * Retry handler that takes into account the DimensionData retriers and delays
 * the requests until they are known to succeed.
 */
@Beta
@Singleton
public class DimensionDataCloudControllerRetryHandler extends BackoffLimitedRetryHandler {

   @Resource
   protected Logger logger = Logger.NULL;

   @Inject(optional = true)
   @Named(PROPERTY_MAX_RETRIES)
   private int retryCountLimit = 5;

   @Override
   public boolean shouldRetryRequest(final HttpCommand command, final HttpResponse response) {
      command.incrementFailureCount();

      byte[] data = closeClientButKeepContentStream(response);
      String message = data != null ? new String(data) : null;
      // Do not retry client errors that are not retryable errors
      if (response.getStatusCode() != 400 &&
              (!message.contains("RESOURCE_BUSY") || !message.contains("UNEXPECTED_ERROR"))) {
         return false;
      } else if (!command.isReplayable()) {
         logger.error("Cannot retry after server error, command is not replayable: %1$s", command);
         return false;
      } else if (command.getFailureCount() > retryCountLimit) {
         logger.error("Cannot retry after server error, command has exceeded retry limit %1$d: %2$s", retryCountLimit,
                 command);
         return false;
      } else {
         imposeBackoffExponentialDelay(command.getFailureCount(), "server error: " + command.toString());
         return true;
      }
   }

}


text:
<?php
/**
 * @package carried-away
 */
?>

<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>

		<?php the_title( sprintf( '
', esc_url( get_permalink() ) ), '
' ); ?>

		<?php if ( 'post' == get_post_type() ) : ?>

			<?php carried_away_posted_on(); ?>

		<?php endif; ?>

		<?php the_content( __( 'Continue reading →', 'carried-away' ) ); ?>
		<?php
			wp_link_pages( array(
				'before' => '
' . __( 'Pages:', 'carried-away' ),
				'after'  => '
',
			) );
		?>

		<?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?>
			<?php
				/* translators: used between list items, there is a space after the comma */
				$categories_list = get_the_category_list( __( ', ', 'carried-away' ) );
				if ( $categories_list && carried_away_categorized_blog() ) :
			?>

				<?php printf( __( 'Posted in %1$s', 'carried-away' ), $categories_list ); ?>

			<?php endif; // End if categories ?>

			<?php
				/* translators: used between list items, there is a space after the comma */
				$tags_list = get_the_tag_list( '', __( ', ', 'carried-away' ) );
				if ( $tags_list ) :
			?>

				<?php printf( __( 'Tagged %1$s', 'carried-away' ), $tags_list ); ?>

			<?php endif; // End if $tags_list ?>
		<?php endif; // End if 'post' == get_post_type() ?>

		<?php if ( ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?>
		<?php comments_popup_link( __( 'Leave a comment', 'carried-away' ), __( '1 Comment', 'carried-away' ), __( '% Comments', 'carried-away' ) ); ?>
		<?php endif; ?>

		<?php edit_post_link( __( 'Edit', 'carried-away' ), '', '' ); ?>


text:
import asyncio
import logging

from app import Server

if __name__ == '__main__':
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
    logger = logging.getLogger(__name__)

    loop = asyncio.get_event_loop()
    start_server = Server().serve()
    server = loop.run_until_complete(start_server)

    logger.info('subot started.')

    loop.run_forever()

    logger.info('subot stopped.')


text:
<?php
declare(strict_types=1);

namespace AppBundle\Form\Type;

use AppBundle\Entity\Document;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolver;

class DocumentDeleteType extends AbstractType
{
    /**
     * @param OptionsResolver $resolver
     */
    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults(
            [
                'class' => Document::class,
            ]
        );
    }
}


text:
/*	$NetBSD: libsa.h,v 1.2 2001/12/15 23:02:34 fredette Exp $	*/

/*
 * This file defines the API for libsa.a
 * as used by the various boot programs.
 */

/*
 * Standard Sun3 PROM load address.
 * i.e. this is where the PROM loads
 * programs, like it or not!
 */
#define KERN_LOADADDR	0x4000

/* SRT0.S */
void	exit __P((void));
void	ICIA __P((void));
void **	getvbr __P((void));

/* SRT1.c */
extern int _is3x;
extern int _is2;
void _start __P((void));
void breakpoint __P((void));
void chain_to __P((void *func));

/* clock.c */
extern int hz;
long getsecs __P((void));
long getticks __P((void));

/* exec_sun.c */
int exec_sun __P((char *file, char *loadaddr));
int load_sun __P((int io, char *loadaddr, char **entry));

/* promboot.c */
extern int debug;
extern char prom_bootdev[];
extern char *prom_bootfile;
extern int prom_boothow;

/* sun2.c */
void sun2_getidprom __P((u_char *ea));
u_long sun2_map_mem_load __P((void));
void *sun2_map_mem_run __P((void *));

/* sun3.c */
void sun3_getidprom __P((u_char *ea));

/* vers.c */
extern const char bootprog_rev[];
extern const char bootprog_name[];


text:
using base::Time;
using base::TimeDelta;

// A lazily created thread local storage for quick access to a thread's message
// loop, if one exists.  This should be safe and free of static constructors.
static base::LazyInstance<base::ThreadLocalPointer<MessageLoop> > lazy_tls_ptr(
    base::LINKER_INITIALIZED);

//------------------------------------------------------------------------------

// Logical events for Histogram profiling. Run with -message-loop-histogrammer
// to get an accounting of messages and actions taken on each thread.
static const int kTaskRunEvent = 0x1;
static const int kTimerEvent = 0x2;

// Provide range of message IDs for use in histogramming and debug display.
static const int kLeastNonZeroMessageId = 1;
static const int kMaxMessageId = 1099;
static const int kNumberOfDistinctMessagesDisplayed = 1100;

//------------------------------------------------------------------------------

#if defined(OS_WIN)

// Upon a SEH exception in this thread, it restores the original unhandled
// exception filter.
static int SEHFilter(LPTOP_LEVEL_EXCEPTION_FILTER old_filter) {
  ::SetUnhandledExceptionFilter(old_filter);
  return EXCEPTION_CONTINUE_SEARCH;
}

// Retrieves a pointer to the current unhandled exception filter. There
// is no standalone getter method.
static LPTOP_LEVEL_EXCEPTION_FILTER GetTopSEHFilter() {
  LPTOP_LEVEL_EXCEPTION_FILTER top_filter = NULL;
  top_filter = ::SetUnhandledExceptionFilter(0);
  ::SetUnhandledExceptionFilter(top_filter);
  return top_filter;
}

#endif  // defined(OS_WIN)

//------------------------------------------------------------------------------

// static
MessageLoop* MessageLoop::current() {
  // TODO(darin): sadly, we cannot enable this yet since people call us even
  // when they have no intention of using us.
  //DCHECK(loop) << "Ouch, did you forget to initialize me?";
  return lazy_tls_ptr.Pointer()->Get();
}

MessageLoop::MessageLoop(Type type)
    : type_(type),
      nestable_tasks_allowed_(true),
      exception_restoration_(false),
      state_(NULL),
      next_sequence_num_(0) {
  DCHECK(!current()) << "should only have one message loop per thread";
  lazy_tls_ptr.Pointer()->Set(this);

#if defined(OS_WIN)
  // TODO(rvargas): Get rid of the OS guards.
  if (type_ == TYPE_DEFAULT) {
    pump_ = new base::MessagePumpDefault();
  } else if (type_ == TYPE_IO) {
    pump_ = new base::MessagePumpForIO();
  } else {
    DCHECK(type_ == TYPE_UI);
    pump_ = new base::MessagePumpForUI();
  }
#elif defined(OS_POSIX)
  if (type_ == TYPE_UI) {
#if defined(OS_MACOSX)
    pump_ = base::MessagePumpMac::Create();
#else
    pump_ = new base::MessagePumpForUI();
#endif
  } else if (type_ == TYPE_IO) {
    pump_ = new base::MessagePumpLibevent();
  } else {
    pump_ = new base::MessagePumpDefault();
  }
#endif  // OS_POSIX
}

MessageLoop::~MessageLoop() {
  DCHECK(this == current());

  // Let interested parties have one last shot at accessing this.
  FOR_EACH_OBSERVER(DestructionObserver, destruction_observers_,
                    WillDestroyCurrentMessageLoop());

  DCHECK(!state_);

  // Clean up any unprocessed tasks, but take care: deleting a task could
  // result in the addition of more tasks (e.g., via DeleteSoon).  We set a
  // limit on the number of times we will allow a deleted task to generate more
  // tasks.  Normally, we should only pass through this loop once or twice.  If
  // we end up hitting the loop limit, then it is probably due to one task that
  // is being stubborn.  Inspect the queues to see who is left.
  bool did_work;
  for (int i = 0; i < 100; ++i) {
    DeletePendingTasks();
    ReloadWorkQueue();
    // If we end up with empty queues, then break out of the loop.
    did_work = DeletePendingTasks();
    if (!did_work)
      break;
  }
  DCHECK(!did_work);

  // OK, now make it so that no one can find us.
  lazy_tls_ptr.Pointer()->Set(NULL);
}

void MessageLoop::AddDestructionObserver(DestructionObserver *obs) {
  DCHECK(this == current());
  destruction_observers_.AddObserver(obs);
}

void MessageLoop::RemoveDestructionObserver(DestructionObserver *obs) {
  DCHECK(this == current());
  destruction_observers_.RemoveObserver(obs);
}

void MessageLoop::Run() {
  AutoRunState save_state(this);
  RunHandler();
}

void MessageLoop::RunAllPending() {
  AutoRunState save_state(this);
  state_->quit_received = true;  // Means run until we would otherwise block.
  RunHandler();
}

// Runs the loop in two different SEH modes:
// enable_SEH_restoration_ = false : any unhandled exception goes to the last
// one that calls SetUnhandledExceptionFilter().
// enable_SEH_restoration_ = true : any unhandled exception goes to the filter
// that was existed before the loop was run.
void MessageLoop::RunHandler() {
#if defined(OS_WIN)
  if (exception_restoration_) {
    RunInternalInSEHFrame();
    return;
  }
#endif

  RunInternal();
}
//------------------------------------------------------------------------------
#if defined(OS_WIN)
__declspec(noinline) void MessageLoop::RunInternalInSEHFrame() {
  LPTOP_LEVEL_EXCEPTION_FILTER current_filter = GetTopSEHFilter();
  __try {
    RunInternal();
  } __except(SEHFilter(current_filter)) {
  }
  return;
}
#endif
//------------------------------------------------------------------------------

void MessageLoop::RunInternal() {
  DCHECK(this == current());

  StartHistogrammer();

#if !defined(OS_MACOSX)
  if (state_->dispatcher && type() == TYPE_UI) {
    static_cast<base::MessagePumpForUI*>(pump_.get())->
        RunWithDispatcher(this, state_->dispatcher);
    return;
  }
#endif

  pump_->Run(this);
}

//------------------------------------------------------------------------------
// Wrapper functions for use in above message loop framework.

bool MessageLoop::ProcessNextDelayedNonNestableTask() {
  if (state_->run_depth != 1)
    return false;

  if (deferred_non_nestable_work_queue_.empty())
    return false;

  Task* task = deferred_non_nestable_work_queue_.front().task;
  deferred_non_nestable_work_queue_.pop();

  RunTask(task);
  return true;
}

//------------------------------------------------------------------------------

void MessageLoop::Quit() {
  DCHECK(current() == this);
  if (state_) {
    state_->quit_received = true;
  } else {
    NOTREACHED() << "Must be inside Run to call Quit";
  }
}

void MessageLoop::PostTask(
    const tracked_objects::Location& from_here, Task* task) {
  PostTask_Helper(from_here, task, 0, true);
}

void MessageLoop::PostDelayedTask(
    const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
  PostTask_Helper(from_here, task, delay_ms, true);
}

void MessageLoop::PostNonNestableTask(
    const tracked_objects::Location& from_here, Task* task) {
  PostTask_Helper(from_here, task, 0, false);
}

void MessageLoop::PostNonNestableDelayedTask(
    const tracked_objects::Location& from_here, Task* task, int64 delay_ms) {
  PostTask_Helper(from_here, task, delay_ms, false);
}

// Possibly called on a background thread!
void MessageLoop::PostTask_Helper(
    const tracked_objects::Location& from_here, Task* task, int64 delay_ms,
    bool nestable) {
  task->SetBirthPlace(from_here);

  PendingTask pending_task(task, nestable);

  if (delay_ms > 0) {
    pending_task.delayed_run_time =
        Time::Now() + TimeDelta::FromMilliseconds(delay_ms);
  } else {
    DCHECK_EQ(delay_ms, 0) << "delay should not be negative";
  }

  // Warning: Don't try to short-circuit, and handle this thread's tasks more
  // directly, as it could starve handling of foreign threads.  Put every task
  // into this queue.

  scoped_refptr<base::MessagePump> pump;
  {
    AutoLock locked(incoming_queue_lock_);

    bool was_empty = incoming_queue_.empty();
    incoming_queue_.push(pending_task);
    if (!was_empty)
      return;  // Someone else should have started the sub-pump.

    pump = pump_;
  }
  // Since the incoming_queue_ may contain a task that destroys this message
  // loop, we cannot exit incoming_queue_lock_ until we are done with |this|.
  // We use a stack-based reference to the message pump so that we can call
  // ScheduleWork outside of incoming_queue_lock_.

  pump->ScheduleWork();
}

void MessageLoop::SetNestableTasksAllowed(bool allowed) {
  if (nestable_tasks_allowed_ != allowed) {
    nestable_tasks_allowed_ = allowed;
    if (!nestable_tasks_allowed_)
      return;
    // Start the native pump if we are not already pumping.
    pump_->ScheduleWork();
  }
}

bool MessageLoop::NestableTasksAllowed() const {
  return nestable_tasks_allowed_;
}

bool MessageLoop::IsNested() {
  return state_->run_depth > 1;
}

//------------------------------------------------------------------------------

void MessageLoop::RunTask(Task* task) {
  DCHECK(nestable_tasks_allowed_);
  // Execute the task and assume the worst: It is probably not reentrant.
  nestable_tasks_allowed_ = false;

  HistogramEvent(kTaskRunEvent);
  task->Run();
  delete task;

  nestable_tasks_allowed_ = true;
}

bool MessageLoop::DeferOrRunPendingTask(const PendingTask& pending_task) {
  if (pending_task.nestable || state_->run_depth == 1) {
    RunTask(pending_task.task);
    // Show that we ran a task (Note: a new one might arrive as a
    // consequence!).
    return true;
  }

  // We couldn't run the task now because we're in a nested message loop
  // and the task isn't nestable.
  deferred_non_nestable_work_queue_.push(pending_task);
  return false;
}

void MessageLoop::AddToDelayedWorkQueue(const PendingTask& pending_task) {
  // Move to the delayed work queue.  Initialize the sequence number
  // before inserting into the delayed_work_queue_.  The sequence number
  // is used to faciliate FIFO sorting when two tasks have the same
  // delayed_run_time value.
  PendingTask new_pending_task(pending_task);
  new_pending_task.sequence_num = next_sequence_num_++;
  delayed_work_queue_.push(new_pending_task);
}

void MessageLoop::ReloadWorkQueue() {
  // We can improve performance of our loading tasks from incoming_queue_ to
  // work_queue_ by waiting until the last minute (work_queue_ is empty) to
  // load.  That reduces the number of locks-per-task significantly when our
  // queues get large.
  if (!work_queue_.empty())
    return;  // Wait till we *really* need to lock and load.

  // Acquire all we can from the inter-thread queue with one lock acquisition.
  {
    AutoLock lock(incoming_queue_lock_);
    if (incoming_queue_.empty())
      return;
    incoming_queue_.Swap(&work_queue_);  // Constant time
    DCHECK(incoming_queue_.empty());
  }
}

bool MessageLoop::DeletePendingTasks() {
  bool did_work = !work_queue_.empty();
  while (!work_queue_.empty()) {
    PendingTask pending_task = work_queue_.front();
    work_queue_.pop();
    if (!pending_task.delayed_run_time.is_null()) {
      // We want to delete delayed tasks in the same order in which they would
      // normally be deleted in case of any funny dependencies between delayed
      // tasks.
      AddToDelayedWorkQueue(pending_task);
    } else {
      // TODO(darin): Delete all tasks once it is safe to do so.
      // Until it is totally safe, just do it when running Purify or
      // Valgrind.
#if defined(PURIFY)
      delete pending_task.task;
#elif defined(OS_POSIX)
      if (RUNNING_ON_VALGRIND)
        delete pending_task.task;
#endif  // defined(OS_POSIX)
    }
  }
  did_work |= !deferred_non_nestable_work_queue_.empty();
  while (!deferred_non_nestable_work_queue_.empty()) {
    // TODO(darin): Delete all tasks once it is safe to do so.
    // Until it is totaly safe, only delete them under Purify and Valgrind.
    Task* task = NULL;
#if defined(PURIFY)
    task = deferred_non_nestable_work_queue_.front().task;
#elif defined(OS_POSIX)
    if (RUNNING_ON_VALGRIND)
      task = deferred_non_nestable_work_queue_.front().task;
#endif
    deferred_non_nestable_work_queue_.pop();
    if (task)
      delete task;
  }
  did_work |= !delayed_work_queue_.empty();
  while (!delayed_work_queue_.empty()) {
    Task* task = delayed_work_queue_.top().task;
    delayed_work_queue_.pop();
    delete task;
  }
  return did_work;
}

bool MessageLoop::DoWork() {
  if (!nestable_tasks_allowed_) {
    // Task can't be executed right now.
    return false;
  }

  for (;;) {
    ReloadWorkQueue();
    if (work_queue_.empty())
      break;

    // Execute oldest task.
    do {
      PendingTask pending_task = work_queue_.front();
      work_queue_.pop();
      if (!pending_task.delayed_run_time.is_null()) {
        AddToDelayedWorkQueue(pending_task);
        // If we changed the topmost task, then it is time to re-schedule.
        if (delayed_work_queue_.top().task == pending_task.task)
          pump_->ScheduleDelayedWork(pending_task.delayed_run_time);
      } else {
        if (DeferOrRunPendingTask(pending_task))
          return true;
      }
    } while (!work_queue_.empty());
  }

  // Nothing happened.
  return false;
}

bool MessageLoop::DoDelayedWork(Time* next_delayed_work_time) {
  if (!nestable_tasks_allowed_ || delayed_work_queue_.empty()) {
    *next_delayed_work_time = Time();
    return false;
  }

  if (delayed_work_queue_.top().delayed_run_time > Time::Now()) {
    *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;
    return false;
  }

  PendingTask pending_task = delayed_work_queue_.top();
  delayed_work_queue_.pop();

  if (!delayed_work_queue_.empty())
    *next_delayed_work_time = delayed_work_queue_.top().delayed_run_time;

  return DeferOrRunPendingTask(pending_task);
}

bool MessageLoop::DoIdleWork() {
  if (ProcessNextDelayedNonNestableTask())
    return true;

  if (state_->quit_received)
    pump_->Quit();

  return false;
}

//------------------------------------------------------------------------------
// MessageLoop::AutoRunState

MessageLoop::AutoRunState::AutoRunState(MessageLoop* loop) : loop_(loop) {
  // Make the loop reference us.
  previous_state_ = loop_->state_;
  if (previous_state_) {
    run_depth = previous_state_->run_depth + 1;
  } else {
    run_depth = 1;
  }
  loop_->state_ = this;

  // Initialize the other fields:
  quit_received = false;
#if !defined(OS_MACOSX)
  dispatcher = NULL;
#endif
}

MessageLoop::AutoRunState::~AutoRunState() {
  loop_->state_ = previous_state_;
}

//------------------------------------------------------------------------------
// MessageLoop::PendingTask

bool MessageLoop::PendingTask::operator<(const PendingTask& other) const {
  // Since the top of a priority queue is defined as the "greatest" element, we
  // need to invert the comparison here.  We want the smaller time to be at the
  // top of the heap.

  if (delayed_run_time < other.delayed_run_time)
    return false;

  if (delayed_run_time > other.delayed_run_time)
    return true;

  // If the times happen to match, then we use the sequence number to decide.
  // Compare the difference to support integer roll-over.
  return (sequence_num - other.sequence_num) > 0;
}

//------------------------------------------------------------------------------
// Method and data for histogramming events and actions taken by each instance
// on each thread.

// static
bool MessageLoop::enable_histogrammer_ = false;

// static
void MessageLoop::EnableHistogrammer(bool enable) {
  enable_histogrammer_ = enable;
}

void MessageLoop::StartHistogrammer() {
  if (enable_histogrammer_ && !message_histogram_.get()
      && StatisticsRecorder::WasStarted()) {
    DCHECK(!thread_name_.empty());
    message_histogram_ = LinearHistogram::FactoryGet("MsgLoop:" + thread_name_,
        kLeastNonZeroMessageId, kMaxMessageId,
        kNumberOfDistinctMessagesDisplayed,
        message_histogram_->kHexRangePrintingFlag);
    message_histogram_->SetRangeDescriptions(event_descriptions_);
  }
}

void MessageLoop::HistogramEvent(int event) {
  if (message_histogram_.get())
    message_histogram_->Add(event);
}

// Provide a macro that takes an expression (such as a constant, or macro
// constant) and creates a pair to initalize an array of pairs.  In this case,
// our pair consists of the expressions value, and the "stringized" version
// of the expression (i.e., the exrpression put in quotes).  For example, if
// we have:
//    #define FOO 2
//    #define BAR 5
// then the following:
//    VALUE_TO_NUMBER_AND_NAME(FOO + BAR)
// will expand to:
//   {7, "FOO + BAR"}
// We use the resulting array as an argument to our histogram, which reads the
// number as a bucket identifier, and proceeds to use the corresponding name
// in the pair (i.e., the quoted string) when printing out a histogram.
#define VALUE_TO_NUMBER_AND_NAME(name) {name, #name},

// static
const LinearHistogram::DescriptionPair MessageLoop::event_descriptions_[] = {
  // Provide some pretty print capability in our histogram for our internal
  // messages.

  // A few events we handle (kindred to messages), and used to profile actions.
  VALUE_TO_NUMBER_AND_NAME(kTaskRunEvent)
  VALUE_TO_NUMBER_AND_NAME(kTimerEvent)

  {-1, NULL}  // The list must be null terminated, per API to histogram.
};

//------------------------------------------------------------------------------
// MessageLoopForUI

#if defined(OS_WIN)
void MessageLoopForUI::WillProcessMessage(const MSG& message) {
  pump_win()->WillProcessMessage(message);
}
void MessageLoopForUI::DidProcessMessage(const MSG& message) {
  pump_win()->DidProcessMessage(message);
}
void MessageLoopForUI::PumpOutPendingPaintMessages() {
  pump_ui()->PumpOutPendingPaintMessages();
}

#endif  // defined(OS_WIN)

#if !defined(OS_MACOSX)
void MessageLoopForUI::AddObserver(Observer* observer) {
  pump_ui()->AddObserver(observer);
}

void MessageLoopForUI::RemoveObserver(Observer* observer) {
  pump_ui()->RemoveObserver(observer);
}

void MessageLoopForUI::Run(Dispatcher* dispatcher) {
  AutoRunState save_state(this);
  state_->dispatcher = dispatcher;
  RunHandler();
}
#endif  // !defined(OS_MACOSX)

//------------------------------------------------------------------------------
// MessageLoopForIO

#if defined(OS_WIN)

void MessageLoopForIO::RegisterIOHandler(HANDLE file, IOHandler* handler) {
  pump_io()->RegisterIOHandler(file, handler);
}

bool MessageLoopForIO::WaitForIOCompletion(DWORD timeout, IOHandler* filter) {
  return pump_io()->WaitForIOCompletion(timeout, filter);
}

#elif defined(OS_POSIX)

bool MessageLoopForIO::WatchFileDescriptor(int fd,
                                           bool persistent,
                                           Mode mode,
                                           FileDescriptorWatcher *controller,
                                           Watcher *delegate) {
  return pump_libevent()->WatchFileDescriptor(
      fd,
      persistent,
      static_cast<base::MessagePumpLibevent::Mode>(mode),
      controller,
      delegate);
}

#endif


text:
package state

import (
	"github.com/thoj/go-ircevent"
	"strings"
)

func (st *StateTracker) joined(event *irc.Event) {
	// Wait until ready
	st.mutex.Lock()

	channel := st.channels[event.Arguments[0]]
	nick := st.nicks[event.Nick]

	// Haven't seen this channel before
	if channel == nil {
		// Create a channel object
		channel = &Channel{
			Name:  event.Arguments[0],
			Nicks: make(map[string]*ChannelPrivileges),
		}

		// Put it in the channels map
		st.channels[event.Arguments[0]] = channel

		// Get some initial info about it
		st.conn.Mode(channel.Name)
		st.conn.Who(channel.Name)
	}

	// Not seen this nick before
	if nick == nil {
		// Create a nick object
		nick = &Nick{
			Nick:     event.Nick,
			User:     event.User,
			Host:     event.Host,
			Channels: make(map[string]*ChannelPrivileges),
		}

		// Put it in the nicks map
		st.nicks[event.Nick] = nick

		// Get some inital info about it
		st.conn.Who(nick.Nick)
	}

	// Associate the nick with the channel
	st.associate(event.Nick, event.Arguments[0])

	// Ready for next event
	st.mutex.Unlock()
}

func (st *StateTracker) kicked(event *irc.Event) {
	st.mutex.Lock()
	st.disassociate(event.Nick, event.Arguments[0])
	st.mutex.Unlock()
}

func (st *StateTracker) nickChanged(event *irc.Event) {
	st.mutex.Lock()
	st.changeNick(event.Nick, event.Arguments[0])
	st.mutex.Unlock()
}

func (st *StateTracker) parted(event *irc.Event) {
	st.mutex.Lock()
	st.disassociate(event.Nick, event.Arguments[0])
	st.mutex.Unlock()
}

func (st *StateTracker) quitted(event *irc.Event) {
	st.mutex.Lock()
	st.deleteNick(event.Nick)
	st.mutex.Unlock()
}

func (st *StateTracker) topicSet(event *irc.Event) {
	st.mutex.Lock()
	st.setTopic(event.Arguments[0], event.Arguments[1])
	st.mutex.Unlock()
}

func (st *StateTracker) whoisReply(event *irc.Event) {
	st.mutex.Lock()
	nick := st.nicks[event.Arguments[1]]
	if nick != nil && nick != st.GetNick(st.conn.GetNick()) {
		nick.User = event.Arguments[2]
		nick.Host = event.Arguments[3]
		nick.Name = event.Arguments[5]
	}
	st.mutex.Unlock()
}

func (st *StateTracker) modeReply(event *irc.Event) {
	st.mutex.Lock()
	if channel, ok := st.channels[event.Arguments[0]]; ok {
		channel.ParseModes(event.Arguments[1], event.Arguments[2:]...)
	}
	st.mutex.Unlock()
}

func (st *StateTracker) topicReply(event *irc.Event) {
	st.mutex.Lock()
	if channel := st.channels[event.Arguments[0]]; channel != nil {
		st.setTopic(channel.Name, event.Arguments[1])
	}
	st.mutex.Unlock()
}

func (st *StateTracker) whoReply(event *irc.Event) {
	st.mutex.Lock()
	if nick, ok := st.nicks[event.Arguments[5]]; ok {
		nick.User = event.Arguments[2]
		nick.Host = event.Arguments[3]
		if idx := strings.Index(event.Arguments[6], "*"); idx != -1 {
			nick.Modes.Oper = true
		}
		if idx := strings.Index(event.Arguments[6], "H"); idx != -1 {
			nick.Modes.Invisible = true
		}
	}
	st.mutex.Unlock()
}

func (st *StateTracker) namesReply(event *irc.Event) {
	st.mutex.Lock()
	if channel, ok := st.channels[event.Arguments[2]]; ok {
		names := strings.Split(strings.TrimSpace(event.Arguments[len(event.Arguments)-1]), " ")
		for _, name := range names {
			switch priv := name[0]; priv {
			case '~', '&', '@', '%', '+':
				name = name[1:]
				fallthrough
			default:
				nick := st.nicks[name]

				if nick == nil {
					st.nicks[name] = &Nick{
						Nick:     name,
						Channels: make(map[string]*ChannelPrivileges),
					}
				}
				privs, ok := channel.Nicks[name]
				if !ok {
					privs = st.associate(name, channel.Name)
				}

				switch priv {
				case '~':
					privs.Owner = true
				case '&':
					privs.Admin = true
				case '@':
					privs.Op = true
				case '%':
					privs.HalfOp = true
				case '+':
					privs.Voice = true
				}
			}
		}
	}
	st.mutex.Unlock()
}

func (st *StateTracker) whoisReplySSL(event *irc.Event) {
	st.mutex.Lock()
	if nick, ok := st.nicks[event.Arguments[0]]; ok && nick != st.GetNick(st.conn.GetNick()) {
		nick.User = event.Arguments[1]
		nick.Host = event.Arguments[2]
		nick.Name = event.Arguments[4]
		nick.Modes.SSL = true
	}
	st.mutex.Unlock()
}

func (st *StateTracker) InitStateCallbacks() {
	st.conn.AddCallback("JOIN", st.joined)
	st.conn.AddCallback("KICK", st.kicked)
	st.conn.AddCallback("NICK", st.nickChanged)
	st.conn.AddCallback("PART", st.parted)
	st.conn.AddCallback("QUIT", st.quitted)
	st.conn.AddCallback("TOPIC", st.topicSet)
	st.conn.AddCallback("311", st.whoisReply)
	st.conn.AddCallback("MODE", st.modeReply)
	st.conn.AddCallback("332", st.topicReply)
	st.conn.AddCallback("352", st.whoReply)
	st.conn.AddCallback("353", st.namesReply)
	st.conn.AddCallback("671", st.whoisReplySSL)
}