text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  Copyright (C) 2011, FuseSource Corp.  All rights reserved.

      http://fusesource.com

  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:

     * Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
     * Redistributions in binary form must reproduce the above
  copyright notice, this list of conditions and the following disclaimer
  in the documentation and/or other materials provided with the
  distribution.
     * Neither the name of FuseSource Corp. nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>org.fusesource.leveldbjni</groupId>
    <artifactId>leveldbjni-project</artifactId>
    <version>1.8</version>
  </parent>

  <groupId>org.fusesource.leveldbjni</groupId>
  <artifactId>leveldbjni-all</artifactId>
  <version>1.8</version>
  <packaging>bundle</packaging>

  <name>${project.artifactId}</name>
  <description>An uber jar which contains all the leveldbjni platform libraries and dependencies</description>

  <dependencies>
    <dependency>
      <groupId>org.fusesource.leveldbjni</groupId>
      <artifactId>leveldbjni</artifactId>
      <version>1.8</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.fusesource.leveldbjni</groupId>
      <artifactId>leveldbjni-osx</artifactId>
      <version>1.8</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.fusesource.leveldbjni</groupId>
      <artifactId>leveldbjni-linux32</artifactId>
      <version>1.8</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.fusesource.leveldbjni</groupId>
      <artifactId>leveldbjni-linux64</artifactId>
      <version>1.8</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.fusesource.leveldbjni</groupId>
      <artifactId>leveldbjni-win32</artifactId>
      <version>1.8</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>org.fusesource.leveldbjni</groupId>
      <artifactId>leveldbjni-win64</artifactId>
      <version>1.8</version>
      <scope>provided</scope>
    </dependency>

  </dependencies>

  <build>

    <plugins>

      <plugin>
        <groupId>org.apache.felix</groupId>
        <artifactId>maven-bundle-plugin</artifactId>
        <version>2.3.7</version>
        <extensions>true</extensions>
        <inherited>true</inherited>
        <configuration>
          <instructions>
            <Bundle-Name>${project.artifactId}</Bundle-Name>
            <Bundle-SymbolicName>${project.groupId}.${project.artifactId}</Bundle-SymbolicName>
            <Export-Package>
              org.fusesource.leveldbjni;version=${project.version},
              org.iq80.leveldb*;version=${leveldb-api-version},</Export-Package>
            <Import-Package></Import-Package>
            <DynamicImport-Package></DynamicImport-Package>
            <Private-Package>org.fusesource.hawtjni*,org.fusesource.leveldbjni.internal*,!*</Private-Package>
            <Implementation-Title>LevelDB JNI</Implementation-Title>
            <Implementation-Version>${project.version}</Implementation-Version>
            <Embed-Dependency>
              *;groupId=org.fusesource.leveldbjni;inline=META-INF/native/*,
            </Embed-Dependency>
            <Embed-Transitive>true</Embed-Transitive>
            <Bundle-NativeCode>
              META-INF/native/windows32/leveldbjni.dll;osname=Win32;processor=x86,
              META-INF/native/windows64/leveldbjni.dll;osname=Win32;processor=x86-64,
              META-INF/native/osx/libleveldbjni.jnilib;osname=macosx;processor=x86,
              META-INF/native/osx/libleveldbjni.jnilib;osname=macosx;processor=x86-64,
              META-INF/native/linux32/libleveldbjni.so;osname=Linux;processor=x86,
              META-INF/native/linux64/libleveldbjni.so;osname=Linux;processor=x86-64
            </Bundle-NativeCode>
         </instructions>
        </configuration>
      </plugin>
    </plugins>
  </build>

  <profiles>
    <profile>
      <id>release</id>

      <dependencies>
        <dependency>
          <groupId>org.fusesource.leveldbjni</groupId>
          <artifactId>leveldbjni</artifactId>
          <version>1.8</version>
          <classifier>sources</classifier>
          <optional>true</optional>
        </dependency>
        <dependency>
          <groupId>org.iq80.leveldb</groupId>
          <artifactId>leveldb-api</artifactId>
          <version>${leveldb-api-version}</version>
          <classifier>sources</classifier>
          <optional>true</optional>
        </dependency>
        <dependency>
          <groupId>org.fusesource.hawtjni</groupId>
          <artifactId>hawtjni-runtime</artifactId>
          <version>${hawtjni-version}</version>
          <classifier>sources</classifier>
          <optional>true</optional>
        </dependency>
      </dependencies>

      <build>
        <plugins>
          <plugin>
            <artifactId>maven-source-plugin</artifactId>
            <configuration>
              <skipSource>true</skipSource>
            </configuration>
          </plugin>
          <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
              <execution>
                <id>uber-sources-jar</id>
                <phase>package</phase>
                <goals>
                  <goal>single</goal>
                </goals>
                <configuration>
                  <descriptors>
                    <descriptor>${basedir}/src/main/descriptors/uber-sources.xml</descriptor>
                  </descriptors>
                  <appendAssemblyId>true</appendAssemblyId>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>
  </profiles>

</project>


text:
using System.Web.Mvc;

namespace Ext.Net.MVC.Examples.Areas.Kitchen_Sink_TreePanels.Controllers
{
    public class BasicController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
Pattern: Use of restricted `@param`/`@returns` type

Issue: -

## Description

This rule reports types being used on `@param` or `@returns`.

The rule is intended to prevent the indication of types on tags where
the type information would be redundant with TypeScript.

#### Options

##### contexts

Set this to an array of strings representing the AST context
where you wish the rule to be applied.
Overrides the default contexts (see below). Set to `"any"` if you want
the rule to apply to any jsdoc block throughout your files (as is necessary
for finding function blocks not attached to a function declaration or
expression, i.e., `@callback` or `@function` (or its aliases `@func` or
`@method`) (including those associated with an `@interface`).

|||
|---|---|
|Context|`ArrowFunctionExpression`, `FunctionDeclaration`, `FunctionExpression`; others when `contexts` option enabled|
|Tags|`param`, `returns`|
|Aliases|`arg`, `argument`, `return`|
|Options|`contexts`|

The following patterns are considered problems:

````js
/**
 * @param {number} foo
 */
function quux (foo) {

}
// Message: Types are not permitted on @param.

/**
 * @param {number} foo
 */
function quux (foo) {

}
// Options: [{"contexts":["any"]}]
// Message: Types are not permitted on @param.

/**
 * @function
 * @param {number} foo
 */
// Options: [{"contexts":["any"]}]
// Message: Types are not permitted on @param.

/**
 * @callback
 * @param {number} foo
 */
// Options: [{"contexts":["any"]}]
// Message: Types are not permitted on @param.

/**
 * @returns {number}
 */
function quux () {

}
// Message: Types are not permitted on @returns.
````

The following patterns are not considered problems:

````js
/**
 * @param foo
 */
function quux (foo) {

}

/**
 * @param foo
 */
// Options: [{"contexts":["any"]}]

/**
 * @function
 * @param {number} foo
 */

/**
 * @callback
 * @param {number} foo
 */
````

## Further Reading

* [eslint-plugin-jsdoc - no-types](https://github.com/gajus/eslint-plugin-jsdoc/blob/master/README.md#no-types)


text:
package main

import (
	"fmt"
	"math/rand"
	"time"
)

type Result string
type Search func(query string) Result

var (
	Web1   = fakeSearch("web1")
	Web2   = fakeSearch("web2")
	Image1 = fakeSearch("image1")
	Image2 = fakeSearch("image2")
	Video1 = fakeSearch("video1")
	Video2 = fakeSearch("video2")
)

func Google(query string) (results []Result) {
	// START OMIT
	c := make(chan Result, 3)
	go func() { c <- First(query, Web1, Web2) }()     // HL
	go func() { c <- First(query, Image1, Image2) }() // HL
	go func() { c <- First(query, Video1, Video2) }() // HL
	timeout := time.After(80 * time.Millisecond)
	for i := 0; i < 3; i++ {
		select {
		case result := <-c:
			results = append(results, result)
		case <-timeout:
			fmt.Println("timed out")
			return
		}
	}
	return
	// STOP OMIT
}

func First(query string, replicas ...Search) Result {
	c := make(chan Result, len(replicas))
	searchReplica := func(i int) {
		c <- replicas[i](query)
	}
	for i := range replicas {
		go searchReplica(i)
	}
	return <-c
}

func fakeSearch(kind string) Search {
	return func(query string) Result {
		time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
		return Result(fmt.Sprintf("%s result for %q\n", kind, query))
	}
}

func init() {
	rand.Seed(time.Now().UnixNano())
}

func main() {
	start := time.Now()
	results := Google("golang")
	elapsed := time.Since(start)
	fmt.Println(results)
	fmt.Println(elapsed)
}


text:
package org.hellojavaer.ddal.spring.scan;

import org.hellojavaer.ddal.core.utils.Assert;
import org.hellojavaer.ddal.ddr.shard.ShardRoute;
import org.hellojavaer.ddal.ddr.shard.ShardRouteContext;
import org.springframework.stereotype.Component;

/**
 *
 * @author Kaiming Zou,created on 22/06/2017.
 */
@Component
public class ShardRouteTestComponent {

    @ShardRoute(scName = "user,shop", sdValue = "{$0}")
    public void routeWithId(Long id) {
        Assert.isTrue(ShardRouteContext.getRouteInfo("user") == id);
        Assert.isTrue(ShardRouteContext.getRouteInfo("shop") == id);
    }

    @ShardRoute(scName = "user,shop", sdValue = "{$0.id}")
    public void routeWithEntity(UserEntity userEntity) {
        Assert.isTrue(ShardRouteContext.getRouteInfo("user") == userEntity.getId());
        Assert.isTrue(ShardRouteContext.getRouteInfo("shop") == userEntity.getId());
    }

    @ShardRoute(scName = "user,shop", sdValue = "tb_{format('%04d',$0.id)}")
    public void testFunction(UserEntity userEntity) {
        Assert.isTrue(ShardRouteContext.getRouteInfo("user").equals(String.format("tb_%04d", userEntity.getId())));
        Assert.isTrue(ShardRouteContext.getRouteInfo("shop").equals(String.format("tb_%04d", userEntity.getId())));
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:osgi="http://www.eclipse.org/gemini/blueprint/schema/blueprint"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
       http://www.eclipse.org/gemini/blueprint/schema/blueprint http://www.eclipse.org/gemini/blueprint/schema/blueprint/gemini-blueprint.xsd">

    <import resource="classpath*:META-INF/motech/*.xml"/>

    <osgi:reference id="eventRelay" interface="org.motechproject.event.listener.EventRelay" />

    <bean id="rolePermissionRegListener" class="org.motechproject.security.osgi.RolePermissionRegistrationListener"/>

    <osgi:service id="securityRuleLoaderOSGi" ref="securityRuleLoader" interface="org.motechproject.security.service.SecurityRuleLoaderService">
        <osgi:registration-listener ref="rolePermissionRegListener" />
    </osgi:service>

    <osgi:service id="motechPermissionServiceOsgi" ref="motechPermissionService" interface="org.motechproject.security.service.MotechPermissionService">
        <osgi:registration-listener ref="rolePermissionRegListener" />
    </osgi:service>

    <osgi:service id="motechRoleServiceOsgi" ref="motechRoleService" interface="org.motechproject.security.service.MotechRoleService">
        <osgi:registration-listener ref="rolePermissionRegListener" />
    </osgi:service>

    <osgi:service id="motechUserServiceOsgi" ref="motechUserService" interface="org.motechproject.security.service.MotechUserService"/>

    <osgi:service id="passwordRecoveryServiceOsgi" ref="passwordRecoveryServiceImpl" interface="org.motechproject.security.service.PasswordRecoveryService" />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.motechproject.osgi.web.BundledJspView"/>
        <property name="prefix" value="/webapp/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <osgi:service ref="passwordRecoveryServiceImpl" interface="org.motechproject.security.service.PasswordRecoveryService"/>

    <osgi:service ref="sessionHandler" interface="javax.servlet.http.HttpSessionListener"/>

    <osgi:service ref="noneValidator" interface="org.motechproject.security.validator.PasswordValidator"/>

    <osgi:service ref="lowerUpperCaseValidator" interface="org.motechproject.security.validator.PasswordValidator"/>

    <osgi:service ref="lowerUpperCaseDigitValidator" interface="org.motechproject.security.validator.PasswordValidator"/>

    <osgi:service ref="lowerUpperCaseDigitSpecialValidator" interface="org.motechproject.security.validator.PasswordValidator"/>

    <osgi:reference id="transactionManager" interface="org.springframework.transaction.PlatformTransactionManager" context-class-loader="unmanaged"/>

    <osgi:reference id="motechPermissionsDataService" interface="org.motechproject.security.repository.MotechPermissionsDataService"/>

    <osgi:reference id="motechRolesDataService" interface="org.motechproject.security.repository.MotechRolesDataService"/>

    <osgi:reference id="motechURLSecurityRuleDataService" interface="org.motechproject.security.repository.MotechURLSecurityRuleDataService"/>

    <osgi:reference id="motechUsersDataService" interface="org.motechproject.security.repository.MotechUsersDataService"/>

    <osgi:reference id="passwordRecoveriesDataService" interface="org.motechproject.security.repository.PasswordRecoveriesDataService"/>

    <osgi:reference id="configurationService" interface="org.motechproject.config.service.ConfigurationService"/>

    <osgi:reference id="localeService" interface="org.motechproject.osgi.web.service.LocaleService"/>

</beans>


text:
package mock_user

import (
	errors "github.com/dnp1/conversa/server/errors"
	gomock "github.com/golang/mock/gomock"
)

// Mock of Model interface
type MockModel struct {
	ctrl     *gomock.Controller
	recorder *_MockModelRecorder
}

// Recorder for MockModel (not exported)
type _MockModelRecorder struct {
	mock *MockModel
}

func NewMockModel(ctrl *gomock.Controller) *MockModel {
	mock := &MockModel{ctrl: ctrl}
	mock.recorder = &_MockModelRecorder{mock}
	return mock
}

func (_m *MockModel) EXPECT() *_MockModelRecorder {
	return _m.recorder
}

func (_m *MockModel) Create(_param0 string, _param1 string, _param2 string) errors.Error {
	ret := _m.ctrl.Call(_m, "Create", _param0, _param1, _param2)
	ret0, _ := ret[0].(errors.Error)
	return ret0
}

func (_mr *_MockModelRecorder) Create(arg0, arg1, arg2 interface{}) *gomock.Call {
	return _mr.mock.ctrl.RecordCall(_mr.mock, "Create", arg0, arg1, arg2)
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Newtonsoft.Json.Linq;

namespace Microsoft.Azure.Management.Compute
{
    /// <summary>
    /// The Compute Management Client.
    /// </summary>
    public partial class ComputeManagementClient : ServiceClient<ComputeManagementClient>, IComputeManagementClient
    {
        private string _apiVersion;

        /// <summary>
        /// Gets the API version.
        /// </summary>
        public string ApiVersion
        {
            get { return this._apiVersion; }
        }

        private Uri _baseUri;

        /// <summary>
        /// Gets the URI used as the base for all cloud service requests.
        /// </summary>
        public Uri BaseUri
        {
            get { return this._baseUri; }
        }

        private SubscriptionCloudCredentials _credentials;

        /// <summary>
        /// Gets subscription credentials which uniquely identify Microsoft
        /// Azure subscription. The subscription ID forms part of the URI for
        /// every service call.
        /// </summary>
        public SubscriptionCloudCredentials Credentials
        {
            get { return this._credentials; }
        }

        private int _longRunningOperationInitialTimeout;

        /// <summary>
        /// Gets or sets the initial timeout for Long Running Operations.
        /// </summary>
        public int LongRunningOperationInitialTimeout
        {
            get { return this._longRunningOperationInitialTimeout; }
            set { this._longRunningOperationInitialTimeout = value; }
        }

        private int _longRunningOperationRetryTimeout;

        /// <summary>
        /// Gets or sets the retry timeout for Long Running Operations.
        /// </summary>
        public int LongRunningOperationRetryTimeout
        {
            get { return this._longRunningOperationRetryTimeout; }
            set { this._longRunningOperationRetryTimeout = value; }
        }

        private IAvailabilitySetOperations _availabilitySets;

        /// <summary>
        /// Operations for managing the availability sets in compute management.
        /// </summary>
        public virtual IAvailabilitySetOperations AvailabilitySets
        {
            get { return this._availabilitySets; }
        }

        private IUsageOperations _usage;

        /// <summary>
        /// Operations for listing usage.
        /// </summary>
        public virtual IUsageOperations Usage
        {
            get { return this._usage; }
        }

        private IVirtualMachineExtensionImageOperations _virtualMachineExtensionImages;

        /// <summary>
        /// Operations for managing the virtual machine extension images in
        /// compute management.
        /// </summary>
        public virtual IVirtualMachineExtensionImageOperations VirtualMachineExtensionImages
        {
            get { return this._virtualMachineExtensionImages; }
        }

        private IVirtualMachineExtensionOperations _virtualMachineExtensions;

        /// <summary>
        /// Operations for managing the virtual machine extensions in compute
        /// management.
        /// </summary>
        public virtual IVirtualMachineExtensionOperations VirtualMachineExtensions
        {
            get { return this._virtualMachineExtensions; }
        }

        private IVirtualMachineImageOperations _virtualMachineImages;

        /// <summary>
        /// Operations for managing the virtual machine images in compute
        /// management.
        /// </summary>
        public virtual IVirtualMachineImageOperations VirtualMachineImages
        {
            get { return this._virtualMachineImages; }
        }

        private IVirtualMachineOperations _virtualMachines;

        /// <summary>
        /// Operations for managing the virtual machines in compute management.
        /// </summary>
        public virtual IVirtualMachineOperations VirtualMachines
        {
            get { return this._virtualMachines; }
        }

        private IVirtualMachineSizeOperations _virtualMachineSizes;

        /// <summary>
        /// Operations for listing virtual machine sizes available in a region.
        /// </summary>
        public virtual IVirtualMachineSizeOperations VirtualMachineSizes
        {
            get { return this._virtualMachineSizes; }
        }

        /// <summary>
        /// Initializes a new instance of the ComputeManagementClient class.
        /// </summary>
        public ComputeManagementClient()
            : base()
        {
            this._availabilitySets = new AvailabilitySetOperations(this);
            this._usage = new UsageOperations(this);
            this._virtualMachineExtensionImages = new VirtualMachineExtensionImageOperations(this);
            this._virtualMachineExtensions = new VirtualMachineExtensionOperations(this);
            this._virtualMachineImages = new VirtualMachineImageOperations(this);
            this._virtualMachines = new VirtualMachineOperations(this);
            this._virtualMachineSizes = new VirtualMachineSizeOperations(this);
            this._apiVersion = "2015-06-15";
            this._longRunningOperationInitialTimeout = -1;
            this._longRunningOperationRetryTimeout = -1;
            this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
        }

        /// <summary>
        /// Initializes a new instance of the ComputeManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        public ComputeManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
            : this()
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._credentials = credentials;
            this._baseUri = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }

        /// <summary>
        /// Initializes a new instance of the ComputeManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        public ComputeManagementClient(SubscriptionCloudCredentials credentials)
            : this()
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._credentials = credentials;
            this._baseUri = new Uri("https://management.azure.com");

            this.Credentials.InitializeServiceClient(this);
        }

        /// <summary>
        /// Initializes a new instance of the ComputeManagementClient class.
        /// </summary>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public ComputeManagementClient(HttpClient httpClient)
            : base(httpClient)
        {
            this._availabilitySets = new AvailabilitySetOperations(this);
            this._usage = new UsageOperations(this);
            this._virtualMachineExtensionImages = new VirtualMachineExtensionImageOperations(this);
            this._virtualMachineExtensions = new VirtualMachineExtensionOperations(this);
            this._virtualMachineImages = new VirtualMachineImageOperations(this);
            this._virtualMachines = new VirtualMachineOperations(this);
            this._virtualMachineSizes = new VirtualMachineSizeOperations(this);
            this._apiVersion = "2015-06-15";
            this._longRunningOperationInitialTimeout = -1;
            this._longRunningOperationRetryTimeout = -1;
            this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
        }

        /// <summary>
        /// Initializes a new instance of the ComputeManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='baseUri'>
        /// Optional. Gets the URI used as the base for all cloud service
        /// requests.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public ComputeManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
            : this(httpClient)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            if (baseUri == null)
            {
                throw new ArgumentNullException("baseUri");
            }
            this._credentials = credentials;
            this._baseUri = baseUri;

            this.Credentials.InitializeServiceClient(this);
        }

        /// <summary>
        /// Initializes a new instance of the ComputeManagementClient class.
        /// </summary>
        /// <param name='credentials'>
        /// Required. Gets subscription credentials which uniquely identify
        /// Microsoft Azure subscription. The subscription ID forms part of
        /// the URI for every service call.
        /// </param>
        /// <param name='httpClient'>
        /// The Http client
        /// </param>
        public ComputeManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
            : this(httpClient)
        {
            if (credentials == null)
            {
                throw new ArgumentNullException("credentials");
            }
            this._credentials = credentials;
            this._baseUri = new Uri("https://management.azure.com");

            this.Credentials.InitializeServiceClient(this);
        }

        /// <summary>
        /// Clones properties from current instance to another
        /// ComputeManagementClient instance
        /// </summary>
        /// <param name='client'>
        /// Instance of ComputeManagementClient to clone to
        /// </param>
        protected override void Clone(ServiceClient<ComputeManagementClient> client)
        {
            base.Clone(client);

            if (client is ComputeManagementClient)
            {
                ComputeManagementClient clonedClient = ((ComputeManagementClient)client);

                clonedClient._credentials = this._credentials;
                clonedClient._baseUri = this._baseUri;
                clonedClient._apiVersion = this._apiVersion;
                clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
                clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;

                clonedClient.Credentials.InitializeServiceClient(clonedClient);
            }
        }

        /// <summary>
        /// The Get Delete Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call GetDeleteOperationStatus to determine whether the
        /// operation has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operationStatusLink'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The compute long running operation response.
        /// </returns>
        public async Task<DeleteOperationResponse> GetDeleteOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
        {
            // Validate
            if (operationStatusLink == null)
            {
                throw new ArgumentNullException("operationStatusLink");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("operationStatusLink", operationStatusLink);
                TracingAdapter.Enter(invocationId, this, "GetDeleteOperationStatusAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + operationStatusLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    DeleteOperationResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new DeleteOperationResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken operationIdValue = responseDoc["operationId"];
                            if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
                            {
                                string operationIdInstance = ((string)operationIdValue);
                                result.TrackingOperationId = operationIdInstance;
                            }

                            JToken statusValue = responseDoc["status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                OperationStatus statusInstance = ((OperationStatus)Enum.Parse(typeof(OperationStatus), ((string)statusValue), true));
                                result.Status = statusInstance;
                            }

                            JToken startTimeValue = responseDoc["startTime"];
                            if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                result.StartTime = startTimeInstance;
                            }

                            JToken endTimeValue = responseDoc["endTime"];
                            if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                result.EndTime = endTimeInstance;
                            }

                            JToken errorValue = responseDoc["error"];
                            if (errorValue != null && errorValue.Type != JTokenType.Null)
                            {
                                ApiError errorInstance = new ApiError();
                                result.Error = errorInstance;

                                JToken detailsArray = errorValue["details"];
                                if (detailsArray != null && detailsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken detailsValue in ((JArray)detailsArray))
                                    {
                                        ApiErrorBase apiErrorBaseInstance = new ApiErrorBase();
                                        errorInstance.Details.Add(apiErrorBaseInstance);

                                        JToken codeValue = detailsValue["code"];
                                        if (codeValue != null && codeValue.Type != JTokenType.Null)
                                        {
                                            string codeInstance = ((string)codeValue);
                                            apiErrorBaseInstance.Code = codeInstance;
                                        }

                                        JToken targetValue = detailsValue["target"];
                                        if (targetValue != null && targetValue.Type != JTokenType.Null)
                                        {
                                            string targetInstance = ((string)targetValue);
                                            apiErrorBaseInstance.Target = targetInstance;
                                        }

                                        JToken messageValue = detailsValue["message"];
                                        if (messageValue != null && messageValue.Type != JTokenType.Null)
                                        {
                                            string messageInstance = ((string)messageValue);
                                            apiErrorBaseInstance.Message = messageInstance;
                                        }
                                    }
                                }

                                JToken innererrorValue = errorValue["innererror"];
                                if (innererrorValue != null && innererrorValue.Type != JTokenType.Null)
                                {
                                    InnerError innererrorInstance = new InnerError();
                                    errorInstance.InnerError = innererrorInstance;

                                    JToken exceptiontypeValue = innererrorValue["exceptiontype"];
                                    if (exceptiontypeValue != null && exceptiontypeValue.Type != JTokenType.Null)
                                    {
                                        string exceptiontypeInstance = ((string)exceptiontypeValue);
                                        innererrorInstance.ExceptionType = exceptiontypeInstance;
                                    }

                                    JToken errordetailValue = innererrorValue["errordetail"];
                                    if (errordetailValue != null && errordetailValue.Type != JTokenType.Null)
                                    {
                                        string errordetailInstance = ((string)errordetailValue);
                                        innererrorInstance.ErrorDetail = errordetailInstance;
                                    }
                                }

                                JToken codeValue2 = errorValue["code"];
                                if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
                                {
                                    string codeInstance2 = ((string)codeValue2);
                                    errorInstance.Code = codeInstance2;
                                }

                                JToken targetValue2 = errorValue["target"];
                                if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
                                {
                                    string targetInstance2 = ((string)targetValue2);
                                    errorInstance.Target = targetInstance2;
                                }

                                JToken messageValue2 = errorValue["message"];
                                if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
                                {
                                    string messageInstance2 = ((string)messageValue2);
                                    errorInstance.Message = messageInstance2;
                                }
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }

        /// <summary>
        /// The Get Operation Status operation returns the status of the
        /// specified operation. After calling an asynchronous operation, you
        /// can call GetLongRunningOperationStatus to determine whether the
        /// operation has succeeded, failed, or is still in progress.
        /// </summary>
        /// <param name='operationStatusLink'>
        /// Required. Location value returned by the Begin operation.
        /// </param>
        /// <param name='cancellationToken'>
        /// Cancellation token.
        /// </param>
        /// <returns>
        /// The Compute service response for long-running operations.
        /// </returns>
        public async Task<ComputeLongRunningOperationResponse> GetLongRunningOperationStatusAsync(string operationStatusLink, CancellationToken cancellationToken)
        {
            // Validate
            if (operationStatusLink == null)
            {
                throw new ArgumentNullException("operationStatusLink");
            }

            // Tracing
            bool shouldTrace = TracingAdapter.IsEnabled;
            string invocationId = null;
            if (shouldTrace)
            {
                invocationId = TracingAdapter.NextInvocationId.ToString();
                Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
                tracingParameters.Add("operationStatusLink", operationStatusLink);
                TracingAdapter.Enter(invocationId, this, "GetLongRunningOperationStatusAsync", tracingParameters);
            }

            // Construct URL
            string url = "";
            url = url + operationStatusLink;
            url = url.Replace(" ", "%20");

            // Create HTTP transport objects
            HttpRequestMessage httpRequest = null;
            try
            {
                httpRequest = new HttpRequestMessage();
                httpRequest.Method = HttpMethod.Get;
                httpRequest.RequestUri = new Uri(url);

                // Set Headers

                // Set Credentials
                cancellationToken.ThrowIfCancellationRequested();
                await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);

                // Send Request
                HttpResponseMessage httpResponse = null;
                try
                {
                    if (shouldTrace)
                    {
                        TracingAdapter.SendRequest(invocationId, httpRequest);
                    }
                    cancellationToken.ThrowIfCancellationRequested();
                    httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
                    if (shouldTrace)
                    {
                        TracingAdapter.ReceiveResponse(invocationId, httpResponse);
                    }
                    HttpStatusCode statusCode = httpResponse.StatusCode;
                    if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
                        if (shouldTrace)
                        {
                            TracingAdapter.Error(invocationId, ex);
                        }
                        throw ex;
                    }

                    // Create Result
                    ComputeLongRunningOperationResponse result = null;
                    // Deserialize Response
                    if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
                    {
                        cancellationToken.ThrowIfCancellationRequested();
                        string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                        result = new ComputeLongRunningOperationResponse();
                        JToken responseDoc = null;
                        if (string.IsNullOrEmpty(responseContent) == false)
                        {
                            responseDoc = JToken.Parse(responseContent);
                        }

                        if (responseDoc != null && responseDoc.Type != JTokenType.Null)
                        {
                            JToken operationIdValue = responseDoc["operationId"];
                            if (operationIdValue != null && operationIdValue.Type != JTokenType.Null)
                            {
                                string operationIdInstance = ((string)operationIdValue);
                                result.TrackingOperationId = operationIdInstance;
                            }

                            JToken statusValue = responseDoc["status"];
                            if (statusValue != null && statusValue.Type != JTokenType.Null)
                            {
                                ComputeOperationStatus statusInstance = ((ComputeOperationStatus)Enum.Parse(typeof(ComputeOperationStatus), ((string)statusValue), true));
                                result.Status = statusInstance;
                            }

                            JToken startTimeValue = responseDoc["startTime"];
                            if (startTimeValue != null && startTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset startTimeInstance = ((DateTimeOffset)startTimeValue);
                                result.StartTime = startTimeInstance;
                            }

                            JToken endTimeValue = responseDoc["endTime"];
                            if (endTimeValue != null && endTimeValue.Type != JTokenType.Null)
                            {
                                DateTimeOffset endTimeInstance = ((DateTimeOffset)endTimeValue);
                                result.EndTime = endTimeInstance;
                            }

                            JToken propertiesValue = responseDoc["properties"];
                            if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
                            {
                                JToken outputValue = propertiesValue["output"];
                                if (outputValue != null && outputValue.Type != JTokenType.Null)
                                {
                                    string outputInstance = outputValue.ToString(Newtonsoft.Json.Formatting.Indented);
                                    result.Output = outputInstance;
                                }
                            }

                            JToken errorValue = responseDoc["error"];
                            if (errorValue != null && errorValue.Type != JTokenType.Null)
                            {
                                ApiError errorInstance = new ApiError();
                                result.Error = errorInstance;

                                JToken detailsArray = errorValue["details"];
                                if (detailsArray != null && detailsArray.Type != JTokenType.Null)
                                {
                                    foreach (JToken detailsValue in ((JArray)detailsArray))
                                    {
                                        ApiErrorBase apiErrorBaseInstance = new ApiErrorBase();
                                        errorInstance.Details.Add(apiErrorBaseInstance);

                                        JToken codeValue = detailsValue["code"];
                                        if (codeValue != null && codeValue.Type != JTokenType.Null)
                                        {
                                            string codeInstance = ((string)codeValue);
                                            apiErrorBaseInstance.Code = codeInstance;
                                        }

                                        JToken targetValue = detailsValue["target"];
                                        if (targetValue != null && targetValue.Type != JTokenType.Null)
                                        {
                                            string targetInstance = ((string)targetValue);
                                            apiErrorBaseInstance.Target = targetInstance;
                                        }

                                        JToken messageValue = detailsValue["message"];
                                        if (messageValue != null && messageValue.Type != JTokenType.Null)
                                        {
                                            string messageInstance = ((string)messageValue);
                                            apiErrorBaseInstance.Message = messageInstance;
                                        }
                                    }
                                }

                                JToken innererrorValue = errorValue["innererror"];
                                if (innererrorValue != null && innererrorValue.Type != JTokenType.Null)
                                {
                                    InnerError innererrorInstance = new InnerError();
                                    errorInstance.InnerError = innererrorInstance;

                                    JToken exceptiontypeValue = innererrorValue["exceptiontype"];
                                    if (exceptiontypeValue != null && exceptiontypeValue.Type != JTokenType.Null)
                                    {
                                        string exceptiontypeInstance = ((string)exceptiontypeValue);
                                        innererrorInstance.ExceptionType = exceptiontypeInstance;
                                    }

                                    JToken errordetailValue = innererrorValue["errordetail"];
                                    if (errordetailValue != null && errordetailValue.Type != JTokenType.Null)
                                    {
                                        string errordetailInstance = ((string)errordetailValue);
                                        innererrorInstance.ErrorDetail = errordetailInstance;
                                    }
                                }

                                JToken codeValue2 = errorValue["code"];
                                if (codeValue2 != null && codeValue2.Type != JTokenType.Null)
                                {
                                    string codeInstance2 = ((string)codeValue2);
                                    errorInstance.Code = codeInstance2;
                                }

                                JToken targetValue2 = errorValue["target"];
                                if (targetValue2 != null && targetValue2.Type != JTokenType.Null)
                                {
                                    string targetInstance2 = ((string)targetValue2);
                                    errorInstance.Target = targetInstance2;
                                }

                                JToken messageValue2 = errorValue["message"];
                                if (messageValue2 != null && messageValue2.Type != JTokenType.Null)
                                {
                                    string messageInstance2 = ((string)messageValue2);
                                    errorInstance.Message = messageInstance2;
                                }
                            }
                        }

                    }
                    result.StatusCode = statusCode;
                    if (httpResponse.Headers.Contains("x-ms-request-id"))
                    {
                        result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
                    }

                    if (shouldTrace)
                    {
                        TracingAdapter.Exit(invocationId, result);
                    }
                    return result;
                }
                finally
                {
                    if (httpResponse != null)
                    {
                        httpResponse.Dispose();
                    }
                }
            }
            finally
            {
                if (httpRequest != null)
                {
                    httpRequest.Dispose();
                }
            }
        }
    }
}


text:
```c
From patchwork Tue Sep 17 01:02:01 2019
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Tiwei Bie <tiwei.bie@intel.com>
X-Patchwork-Id: 11147971
Return-Path: <SRS0=dK0e=XM=vger.kernel.org=kvm-owner@kernel.org>
Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org
 [172.30.200.123])
	by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id A851013BD
	for <patchwork-kvm@patchwork.kernel.org>;
 Tue, 17 Sep 2019 01:05:17 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [209.132.180.67])
	by mail.kernel.org (Postfix) with ESMTP id 86E12216C8
	for <patchwork-kvm@patchwork.kernel.org>;
 Tue, 17 Sep 2019 01:05:17 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1733257AbfIQBE7 (ORCPT
        <rfc822;patchwork-kvm@patchwork.kernel.org>);
        Mon, 16 Sep 2019 21:04:59 -0400
Received: from mga04.intel.com ([192.55.52.120]:34819 "EHLO mga04.intel.com"
        rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP
        id S1727996AbfIQBE7 (ORCPT <rfc822;kvm@vger.kernel.org>);
        Mon, 16 Sep 2019 21:04:59 -0400
X-Amp-Result: SKIPPED(no attachment in message)
X-Amp-File-Uploaded: False
Received: from orsmga008.jf.intel.com ([10.7.209.65])
  by fmsmga104.fm.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384;
 16 Sep 2019 18:04:58 -0700
X-ExtLoop1: 1
X-IronPort-AV: E=Sophos;i="5.64,514,1559545200";
   d="scan'208";a="180611926"
Received: from dpdk-virtio-tbie-2.sh.intel.com ([10.67.104.71])
  by orsmga008.jf.intel.com with ESMTP; 16 Sep 2019 18:04:55 -0700
From: Tiwei Bie <tiwei.bie@intel.com>
To: mst@redhat.com, jasowang@redhat.com, alex.williamson@redhat.com,
        maxime.coquelin@redhat.com
Cc: linux-kernel@vger.kernel.org, kvm@vger.kernel.org,
        virtualization@lists.linux-foundation.org, netdev@vger.kernel.org,
        dan.daly@intel.com, cunming.liang@intel.com,
        zhihong.wang@intel.com, lingshan.zhu@intel.com, tiwei.bie@intel.com
Subject: [RFC v4 0/3] vhost: introduce mdev based hardware backend
Date: Tue, 17 Sep 2019 09:02:01 +0800
Message-Id: <20190917010204.30376-1-tiwei.bie@intel.com>
X-Mailer: git-send-email 2.17.1
Sender: kvm-owner@vger.kernel.org
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

This RFC is to demonstrate below ideas,

a) Build vhost-mdev on top of the same abstraction defined in
   the virtio-mdev series [1];

b) Introduce /dev/vhost-mdev to do vhost ioctls and support
   setting mdev device as backend;

Now the userspace API looks like this:

- Userspace generates a compatible mdev device;

- Userspace opens this mdev device with VFIO API (including
  doing IOMMU programming for this mdev device with VFIO's
  container/group based interface);

- Userspace opens /dev/vhost-mdev and gets vhost fd;

- Userspace uses vhost ioctls to setup vhost (userspace should
  do VHOST_MDEV_SET_BACKEND ioctl with VFIO group fd and device
  fd first before doing other vhost ioctls);

Only compile test has been done for this series for now.

RFCv3: https://patchwork.kernel.org/patch/11117785/

[1] https://lkml.org/lkml/2019/9/10/135

Tiwei Bie (3):
  vfio: support getting vfio device from device fd
  vfio: support checking vfio driver by device ops
  vhost: introduce mdev based hardware backend

 drivers/vfio/mdev/vfio_mdev.c    |   3 +-
 drivers/vfio/vfio.c              |  32 +++
 drivers/vhost/Kconfig            |   9 +
 drivers/vhost/Makefile           |   3 +
 drivers/vhost/mdev.c             | 462 +++++++++++++++++++++++++++++++
 drivers/vhost/vhost.c            |  39 ++-
 drivers/vhost/vhost.h            |   6 +
 include/linux/vfio.h             |  11 +
 include/uapi/linux/vhost.h       |  10 +
 include/uapi/linux/vhost_types.h |   5 +
 10 files changed, 573 insertions(+), 7 deletions(-)
 create mode 100644 drivers/vhost/mdev.c
```
#### [PATCH v5 0/9] Enable Sub-page Write Protection Support
##### From: Yang Weijiang <weijiang.yang@intel.com>

```c
From patchwork Tue Sep 17 08:52:55 2019
Content-Type: text/plain; charset="utf-8"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
X-Patchwork-Submitter: Yang Weijiang <weijiang.yang@intel.com>
X-Patchwork-Id: 11148287
Return-Path: <SRS0=dK0e=XM=vger.kernel.org=kvm-owner@kernel.org>
Received: from mail.kernel.org (pdx-korg-mail-1.web.codeaurora.org
 [172.30.200.123])
	by pdx-korg-patchwork-2.web.codeaurora.org (Postfix) with ESMTP id 6FB9C912
	for <patchwork-kvm@patchwork.kernel.org>;
 Tue, 17 Sep 2019 08:53:22 +0000 (UTC)
Received: from vger.kernel.org (vger.kernel.org [209.132.180.67])
	by mail.kernel.org (Postfix) with ESMTP id 57C5D2189D
	for <patchwork-kvm@patchwork.kernel.org>;
 Tue, 17 Sep 2019 08:53:22 +0000 (UTC)
Received: (majordomo@vger.kernel.org) by vger.kernel.org via listexpand
        id S1726178AbfIQIwv (ORCPT
        <rfc822;patchwork-kvm@patchwork.kernel.org>);
        Tue, 17 Sep 2019 04:52:51 -0400
Received: from mga18.intel.com ([134.134.136.126]:37165 "EHLO mga18.intel.com"
        rhost-flags-OK-OK-OK-OK) by vger.kernel.org with ESMTP
        id S1725811AbfIQIw2 (ORCPT <rfc822;kvm@vger.kernel.org>);
        Tue, 17 Sep 2019 04:52:28 -0400
X-Amp-Result: SKIPPED(no attachment in message)
X-Amp-File-Uploaded: False
Received: from fmsmga003.fm.intel.com ([10.253.24.29])
  by orsmga106.jf.intel.com with ESMTP/TLS/DHE-RSA-AES256-GCM-SHA384;
 17 Sep 2019 01:52:27 -0700
X-ExtLoop1: 1
X-IronPort-AV: E=Sophos;i="5.64,515,1559545200";
   d="scan'208";a="193695456"
Received: from unknown (HELO local-michael-cet-test.sh.intel.com)
 ([10.239.159.128])
  by FMSMGA003.fm.intel.com with ESMTP; 17 Sep 2019 01:52:25 -0700
From: Yang Weijiang <weijiang.yang@intel.com>
To: kvm@vger.kernel.org, linux-kernel@vger.kernel.org,
        pbonzini@redhat.com, sean.j.christopherson@intel.com
Cc: mst@redhat.com, rkrcmar@redhat.com, jmattson@google.com,
        yu.c.zhang@intel.com, alazar@bitdefender.com,
        Yang Weijiang <weijiang.yang@intel.com>
Subject: [PATCH v5 0/9] Enable Sub-page Write Protection Support
Date: Tue, 17 Sep 2019 16:52:55 +0800
Message-Id: <20190917085304.16987-1-weijiang.yang@intel.com>
X-Mailer: git-send-email 2.17.2
Sender: kvm-owner@vger.kernel.org
Precedence: bulk
List-ID: <kvm.vger.kernel.org>
X-Mailing-List: kvm@vger.kernel.org

EPT-Based Sub-Page write Protection(SPP)is a HW capability which allows
Virtual Machine Monitor(VMM) to specify write-permission for guest
physical memory at a sub-page(128 byte) granularity. When this
capability is enabled, the CPU enforces write-access check for sub-pages
within a 4KB page.

The feature is targeted to provide fine-grained memory protection for
usages such as device virtualization, memory check-point and VM
introspection etc.

SPP is active when the "sub-page write protection" (bit 23) is 1 in
Secondary VM-Execution Controls. The feature is backed with a Sub-Page
Permission Table(SPPT), SPPT is referenced via a 64-bit control field
called Sub-Page Permission Table Pointer (SPPTP) which contains a
4K-aligned physical address.

To enable SPP for certain physical page, the gfn should be first mapped
to a 4KB entry, then set bit 61 of the corresponding EPT leaf entry.
While HW walks EPT, if bit 61 is set, it traverses SPPT with the guset
physical address to find out the sub-page permissions at the leaf entry.
If the corresponding bit is set, write to sub-page is permitted,
otherwise, SPP induced EPT violation is generated.

This patch serial passed SPP function test and selftest on Ice-Lake platform.

Please refer to the SPP introduction document in this patch set and
Intel SDM for details:

Intel SDM:
https://software.intel.com/sites/default/files/managed/39/c5/325462-sdm-vol-1-2abcd-3abcd.pdf

SPP selftest patch:
https://lkml.org/lkml/2019/6/18/1197

Previous patch:
https://lkml.org/lkml/2019/8/14/97

Patch 1: Introduction to SPP.
Patch 2: Add SPP related flags and control bits.
Patch 3: Functions for SPPT setup.
Patch 4: Add SPP access bitmaps for memslots.
Patch 5: Introduce SPP {init,set,get} functions
Patch 6: Implement User space access IOCTLs.
Patch 7: Set up SPP paging table at vm-entry/exit.
Patch 8: Enable lazy mode SPPT setup.
Patch 9: Handle SPP protected pages when VM memory changes

Change logs:

V5 -> V4:
  1. Enable SPP support for Hugepage(1GB/2MB) to extend application.
  2. Make SPP miss vm-exit handler as the unified place to set up SPPT.
  3. If SPP protected pages are access-tracked or dirty-page-tracked,
     store SPP flag in reserved address bit, restore it in
     fast_page_fault() handler.
  4. Move SPP specific functions to vmx/spp.c and vmx/spp.h
  5. Rebased code to kernel v5.3
  6. Other change suggested by KVM community.

V3 -> V4:
  1. Modified documentation to make it consistent with patches.
  2. Allocated SPPT root page in init_spp() instead of vmx_set_cr3() to
     avoid SPPT miss error.
  3. Added back co-developers and sign-offs.

V2 -> V3:
  1. Rebased patches to kernel 5.1 release
  2. Deferred SPPT setup to EPT fault handler if the page is not
     available while set_subpage() is being called.
  3. Added init IOCTL to reduce extra cost if SPP is not used.
  4. Refactored patch structure, cleaned up cross referenced functions.
  5. Added code to deal with memory swapping/migration/shrinker cases.

V2 -> V1:
  1. Rebased to 4.20-rc1
  2. Move VMCS change to a separated patch.
  3. Code refine and Bug fix

Yang Weijiang (9):
  Documentation: Introduce EPT based Subpage Protection
  vmx: spp: Add control flags for Sub-Page Protection(SPP)
  mmu: spp: Add SPP Table setup functions
  mmu: spp: Add functions to create/destroy SPP bitmap block
  mmu: spp: Introduce SPP {init,set,get} functions
  x86: spp: Introduce user-space SPP IOCTLs
  vmx: spp: Set up SPP paging table at vm-entry/exit
  mmu: spp: Enable Lazy mode SPP protection
  mmu: spp: Handle SPP protected pages when VM memory changes

 Documentation/virtual/kvm/spp_kvm.txt | 178 +++++++
 arch/x86/include/asm/cpufeatures.h    |   1 +
 arch/x86/include/asm/kvm_host.h       |  10 +-
 arch/x86/include/asm/vmx.h            |  10 +
 arch/x86/include/uapi/asm/vmx.h       |   2 +
 arch/x86/kernel/cpu/intel.c           |   4 +
 arch/x86/kvm/mmu.c                    |  78 ++-
 arch/x86/kvm/mmu.h                    |   2 +
 arch/x86/kvm/vmx/capabilities.h       |   5 +
 arch/x86/kvm/vmx/spp.c                | 651 ++++++++++++++++++++++++++
 arch/x86/kvm/vmx/spp.h                |  27 ++
 arch/x86/kvm/vmx/vmx.c                |  99 ++++
 arch/x86/kvm/x86.c                    |  51 ++
 include/uapi/linux/kvm.h              |  17 +
 14 files changed, 1133 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/virtual/kvm/spp_kvm.txt
 create mode 100644 arch/x86/kvm/vmx/spp.c
 create mode 100644 arch/x86/kvm/vmx/spp.h
```


text:
PAGE_TRANSITION(LINK, 0)

// User got this page by typing the URL in the URL bar.  This should not be
// used for cases where the user selected a choice that didn't look at all
// like a URL; see GENERATED below.
//
// We also use this for other "explicit" navigation actions.
PAGE_TRANSITION(TYPED, 1)

// User got to this page through a suggestion in the UI, for example)
// through the destinations page.
PAGE_TRANSITION(AUTO_BOOKMARK, 2)

// This is a subframe navigation. This is any content that is automatically
// loaded in a non-toplevel frame. For example, if a page consists of
// several frames containing ads, those ad URLs will have this transition
// type. The user may not even realize the content in these pages is a
// separate frame, so may not care about the URL (see MANUAL below).
PAGE_TRANSITION(AUTO_SUBFRAME, 3)

// For subframe navigations that are explicitly requested by the user and
// generate new navigation entries in the back/forward list. These are
// probably more important than frames that were automatically loaded in
// the background because the user probably cares about the fact that this
// link was loaded.
PAGE_TRANSITION(MANUAL_SUBFRAME, 4)

// User got to this page by typing in the URL bar and selecting an entry
// that did not look like a URL.  For example, a match might have the URL
// of a Google search result page, but appear like "Search Google for ...".
// These are not quite the same as TYPED navigations because the user
// didn't type or see the destination URL.
// See also KEYWORD.
PAGE_TRANSITION(GENERATED, 5)

// This is a toplevel navigation. This is any content that is automatically
// loaded in a toplevel frame.  For example, opening a tab to show the ASH
// screen saver, opening the devtools window, opening the NTP after the safe
// browsing warning, opening web-based dialog boxes are examples of
// AUTO_TOPLEVEL navigations.
PAGE_TRANSITION(AUTO_TOPLEVEL, 6)

// The user filled out values in a form and submitted it. NOTE that in
// some situations submitting a form does not result in this transition
// type. This can happen if the form uses script to submit the contents.
PAGE_TRANSITION(FORM_SUBMIT, 7)

// The user "reloaded" the page, either by hitting the reload button or by
// hitting enter in the address bar.  NOTE: This is distinct from the
// concept of whether a particular load uses "reload semantics" (i.e.
// bypasses cached data).  For this reason, lots of code needs to pass
// around the concept of whether a load should be treated as a "reload"
// separately from their tracking of this transition type, which is mainly
// used for proper scoring for consumers who care about how frequently a
// user typed/visited a particular URL.
//
// SessionRestore and undo tab close use this transition type too.
PAGE_TRANSITION(RELOAD, 8)

// The url was generated from a replaceable keyword other than the default
// search provider. If the user types a keyword (which also applies to
// tab-to-search) in the omnibox this qualifier is applied to the transition
// type of the generated url. TemplateURLModel then may generate an
// additional visit with a transition type of KEYWORD_GENERATED against the
// url 'http://' + keyword. For example, if you do a tab-to-search against
// wikipedia the generated url has a transition qualifer of KEYWORD, and
// TemplateURLModel generates a visit for 'wikipedia.org' with a transition
// type of KEYWORD_GENERATED.
PAGE_TRANSITION(KEYWORD, 9)

// Corresponds to a visit generated for a keyword. See description of
// KEYWORD for more details.
PAGE_TRANSITION(KEYWORD_GENERATED, 10)

// ADDING NEW CORE VALUE? Be sure to update the LAST_CORE and CORE_MASK
// values below.  Also update CoreTransitionString().
PAGE_TRANSITION(LAST_CORE,   PAGE_TRANSITION_KEYWORD_GENERATED)
PAGE_TRANSITION(CORE_MASK, 0xFF)

// Qualifiers
// Any of the core values above can be augmented by one or more qualifiers.
// These qualifiers further define the transition.

// A managed user attempted to visit a URL but was blocked.
PAGE_TRANSITION(BLOCKED, 0x00800000)

// User used the Forward or Back button to navigate among browsing history.
PAGE_TRANSITION(FORWARD_BACK, 0x01000000)

// User used the address bar to trigger this navigation.
PAGE_TRANSITION(FROM_ADDRESS_BAR, 0x02000000)

// User is navigating to the home page.
PAGE_TRANSITION(HOME_PAGE, 0x04000000)

// The transition originated from an external application; the exact definition
// of this is embedder dependent.
PAGE_TRANSITION(FROM_API, 0x08000000)

// The beginning of a navigation chain.
PAGE_TRANSITION(CHAIN_START, 0x10000000)

// The last transition in a redirect chain.
PAGE_TRANSITION(CHAIN_END, 0x20000000)

// Redirects caused by JavaScript or a meta refresh tag on the page.
PAGE_TRANSITION(CLIENT_REDIRECT, 0x40000000)

// Redirects sent from the server by HTTP headers. It might be nice to
// break this out into 2 types in the future, permanent or temporary, if we
// can get that information from WebKit.
PAGE_TRANSITION(SERVER_REDIRECT, 0x80000000)

// Used to test whether a transition involves a redirect.
PAGE_TRANSITION(IS_REDIRECT_MASK, 0xC0000000)

// General mask defining the bits used for the qualifiers.
PAGE_TRANSITION(QUALIFIER_MASK, 0xFFFFFF00)


text:
package com.hzg.tools;

public class CommonConstant {

    public final static String success = "success";
    public final static String fail = "fail";

    public final static String add = "add";
    public final static String subtract = "subtract";

    public final static String result = "result";

    public final static String recordsSum = "recordsSum";

    public final static String sessionId = "sessionId";
    public final static String oldSessionId = "oldSessionId";
    public final static String username = "username";
    public final static String user = "user";
    public final static String resources = "resources";
    public final static String salt = "salt";

    public final static String underline = "_";

    public final static String ip = "ip";
}


text:
package network;

import java.net.*;
import java.util.ArrayList;
import java.io.*;

import user_interface.GameController;
import user_interface.ControlCreatePage;

public class Server extends Thread {
	private ServerSocket accepter;
	private ControlCreatePage controller;
	private GameController gameController;

	private static final ArrayList<String> IPaddresses = new ArrayList<String>();

	private boolean isSettingUp;
	private boolean isGameStarted;

	public Server(int port, ControlCreatePage controller) throws IOException {
		accepter = new ServerSocket(port);
		this.controller = controller;
	}

	public void listen() throws IOException {
		for (;;) {
			Socket s = accepter.accept();
			if( isSettingUp ) {
				GameSetupThread gameSetup = new GameSetupThread(s, controller, isGameStarted, this);
				gameSetup.start();
			} else if (isGameStarted) {
				if (gameController != null) {
					GameRunningThread gameRunning = new GameRunningThread(s, gameController);
					gameRunning.start();
				}
			}
		}
	}

	@Override
	public void run() {
		try {
			listen();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public Boolean containsIPAddress(String address) {
		return IPaddresses.contains(address);
	}

	public void addIPAddress(String address) {
		IPaddresses.add(address);
	}

	public int getIPAddressIndex(String address) {
		return IPaddresses.indexOf(address);
	}

	public void startGame( GameController controller ) {
		gameController = controller;
	}

	public void setSettingUp(Boolean value) {
		isSettingUp = value;
	}

	public void setGameStarted(Boolean value) {
		isGameStarted = value;
	}

}


text:
<!DOCTYPE html>

  <title>Example 6</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

Using Dygraphs to load down-sampled data while zooming
         - Example 6

This example shows that the overall technique works with live continuous data loading as well, but it
        requires some additional handling and complexity.  The main difference when using live data and dynamic
        zooming, is that it's necessary to prevent changing graph automatically unless the user
        intends to be looking at the most recent live data continuously.  This is highly dependent on user interface
        design and expectations.

In this simple example, if the user has zoomed in to detail view with the detail
        end time less than 10 seconds from current time, then code assumes user intends to look at the most recent
        live data continuously and so it resets the detail window end time on each data load. If the user
        pans/zooms away from the current time, then code does not automatically reset detail view even though new
        data is still continuing to be loaded and will be visible in the range viewer.

Note that the original demos were not written with live data loading in mind. Some minor refactoring would make
         for much cleaner implementation.

            <button name="range-btn-5y" class="btn btn-default btn-mini">
              5y
            </button>
            <button name="range-btn-1y" class="btn btn-default btn-mini">
              1y
            </button>
            <button name="range-btn-ytd" class="btn btn-default  btn-mini">
              YTD
            </button>
            <button name="range-btn-6m" class="btn btn-default btn-mini">
              6m
            </button>
            <button name="range-btn-1m" class="btn btn-default  btn-mini">
              1m
            </button>
            <button name="range-btn-1d" class="btn btn-default btn-mini">
              1d
            </button>
            <button name="range-btn-15min" class="btn btn-default  btn-mini">
              15min
            </button>
            <button name="range-btn-5min" class="btn btn-default btn-mini">
              5min
            </button>

        <button type="button" class="btn btn-success liveupdate-btn">Enable Live Updates</button>

Files

example6.html

This page. Contains the graph container's HTML, range selector buttons, and this documentation. No
          javascript.

j/JGS.Demo6Page.js

This is the most relevant file. Contains all of the Dygraphs specific handling. 90% the same as example 3, but adds live
            data loading and additional hooks to track mouse button to prevent redrawing with live data while user is interacting.

j/JGS.GraphDataProviderLive.js

Responsible for getting range and detail data from the server/simulator and then aggregating,splicing, and
          converting it for dygraphs. This file is same as the GraphDataProvider used for example 1 & 2 & 3, but uses
          GraphDataSimulatorLive.js to source data.

j/JGS.ServerDataSimulatorLive.js

Simulates a remote time series data service. Includes simulated delays. This file is the same as ServerDataSimulator used in example
          1 & 2 & 3, but also simulates loading of new live data on each data load call.  This is poorly coded and is meant only to support this demo.

         Back to examples list

        © 2016 JGS Technical LLC


text:
package com.wumbleminky.luxincraft.item;

import com.wumbleminky.luxincraft.creativetab.CreativeTabLC;
import com.wumbleminky.luxincraft.reference.Names;
import com.wumbleminky.luxincraft.reference.Reference;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;

public class ItemLuxinCraft extends Item {

    public ItemLuxinCraft(){
        super();
        setCreativeTab(CreativeTabLC.LuxinCraftTab);
    }

    public ItemLuxinCraft(String name){
        this();
        setUnlocalizedName(name);
    }

    @Override
    public String getUnlocalizedName(){
        return String.format("item.%s", Reference.withMODID(Names.getUnwrappedName(super.getUnlocalizedName())));
    }

    @Override
    public String getUnlocalizedName(ItemStack itemStack){
        return this.getUnlocalizedName();
    }

}


text:
"""custom command to build doc.zip file"""
#=============================================================================
# imports
#=============================================================================
# core
import os
from distutils import dir_util
from distutils.cmd import Command
from distutils.errors import *
from distutils.spawn import spawn
# local
__all__ = [
    "docdist"
]
#=============================================================================
# command
#=============================================================================
class docdist(Command):

    description = "create zip file containing standalone html docs"

    user_options = [
        ('build-dir=', None, 'Build directory'),
        ('dist-dir=', 'd',
         "directory to put the source distribution archive(s) in "
         "[default: dist]"),
        ('format=', 'f',
         "archive format to create (tar, ztar, gztar, zip)"),
        ('sign', 's', 'sign files using gpg'),
        ('identity=', 'i', 'GPG identity used to sign files'),
    ]

    def initialize_options(self):
        self.build_dir = None
        self.dist_dir = None
        self.format = None
        self.keep_temp = False
        self.sign = False
        self.identity = None

    def finalize_options(self):
        if self.identity and not self.sign:
            raise DistutilsOptionError(
                "Must use --sign for --identity to have meaning"
            )
        if self.build_dir is None:
            cmd = self.get_finalized_command('build')
            self.build_dir = os.path.join(cmd.build_base, 'docdist')
        if not self.dist_dir:
            self.dist_dir = "dist"
        if not self.format:
            self.format = "zip"

    def run(self):
        # call build sphinx to build docs
        self.run_command("build_sphinx")
        cmd = self.get_finalized_command("build_sphinx")
        source_dir = cmd.builder_target_dir

        # copy to directory with appropriate name
        dist = self.distribution
        arc_name = "%s-docs-%s" % (dist.get_name(), dist.get_version())
        tmp_dir = os.path.join(self.build_dir, arc_name)
        if os.path.exists(tmp_dir):
            dir_util.remove_tree(tmp_dir, dry_run=self.dry_run)
        self.copy_tree(source_dir, tmp_dir, preserve_symlinks=True)

        # make archive from dir
        arc_base = os.path.join(self.dist_dir, arc_name)
        self.arc_filename = self.make_archive(arc_base, self.format,
                                              self.build_dir)

        # Sign if requested
        if self.sign:
            gpg_args = ["gpg", "--detach-sign", "-a", self.arc_filename]
            if self.identity:
                gpg_args[2:2] = ["--local-user", self.identity]
            spawn(gpg_args,
                  dry_run=self.dry_run)

        # cleanup
        if not self.keep_temp:
            dir_util.remove_tree(tmp_dir, dry_run=self.dry_run)

#=============================================================================
# eof
#=============================================================================


text:
<?php

namespace backend\controllers;

use Yii;
use backend\models\Module;
use common\models\search\ModuleSearch;
use backend\components\BackendController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;

/**
 * ModuleController implements the CRUD actions for Module model.
 */
class ModuleController extends BackendController
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    /**
     * Lists all Module models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new ModuleSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Module model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Module model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Module();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Module model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing Module model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        //$this->findModel($id)->delete();
        $model = $this->findModel($id);
        $model->deleted = 1;
        $model->save();
        return $this->redirect(['index']);
    }

    /**
     * Change status
     * @throws NotFoundHttpException
     * @throws \yii\base\ExitException
     */
    public function actionChangeStatus()
    {
        if (!Yii::$app->getRequest()->isAjax)
            Yii::$app->end();

        $id = (int)ArrayHelper::getValue($_REQUEST, 'id', 0);
        $status = (int)ArrayHelper::getValue($_REQUEST, 'status', 0);
        $statusChange = ($status == 1) ? 0 : 1;

        $model = $this->findModel($id);
        if ($model instanceof Module) {
            $updateStatus = $model->updateAttributes(['id' => $id, 'status' => $statusChange]);
            if ($updateStatus) {
                echo Json::encode(['status' => true]);
                Yii::$app->end();
            } else {
                echo Json::encode(['status' => false]);
                Yii::$app->end();
            }
        } else {
            echo Json::encode(['status' => false]);
            Yii::$app->end();
        }
    }

    /**
     * Finds the Module model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Module the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Module::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}


text:
package org.carlspring.strongbox.configuration;

import org.carlspring.strongbox.security.encryption.EncryptionAlgorithms;
import org.carlspring.strongbox.security.Credentials;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author mtodorov
 */
@XmlRootElement (name = "anonymous-access")
@XmlAccessorType(XmlAccessType.FIELD)
public class AnonymousAccessConfiguration
{

    private boolean enabled = true;

    private String username = "anonymous";

    private Credentials credentials = new Credentials("password", EncryptionAlgorithms.PLAIN.toString());

    public AnonymousAccessConfiguration()
    {
    }

    public boolean isEnabled()
    {
        return enabled;
    }

    public void setEnabled(boolean enabled)
    {
        this.enabled = enabled;
    }

    public String getUsername()
    {
        return username;
    }

    public void setUsername(String username)
    {
        this.username = username;
    }

    public Credentials getCredentials()
    {
        return credentials;
    }

    public void setCredentials(Credentials credentials)
    {
        this.credentials = credentials;
    }

}


text:
Bug #39863 (file_exists() silently truncates after a null byte)
--CREDITS--
Andrew van der Stock, vanderaj @ owasp.org
--FILE--
<?php

$filename = __FILE__ . chr(0). ".ridiculous";

if (file_exists($filename)) {
    echo "FAIL\n";
}
else {
    echo "PASS\n";
}
?>
===DONE===
<?php exit(0); ?>
--EXPECTF--
Warning: file_exists() expects parameter 1 to be a valid path, string given in %s on line %d
PASS
===DONE===


text:
const Promise = require('bluebird');
const path = require('path');
const LRU = require('lru-cache');

module.exports = function(app) {
  app.media.album = function(options) {
    var cache = LRU();

    options.model.observe('before save', clearCache);
    options.model.observe('after delete', clearCache);

    function clearCache() {
      cache.reset();
      return Promise.resolve();
    }

    function getSize(image) {
      var location = path.join(image.location, 'extra_large');

      return app.models.Media.findOne({
        where: {
          location: location
        },
        fields: {
          image: true
        }
      }).then(function(data) {
        image.large = {
          width: data.image.width,
          height: data.image.height
        };
        return image;
      });
    }

    return {
      cache: cache,
      getSize: getSize
    };
  };
};


text:
These config files are used to bootstrap experiment values into the runtime and are merged directly into the `AMP_CONFIG` field during the build. `prod-config.json` is used in all [release channels](../../docs/release-schedule.md#release-channels) except Experimental, which uses `canary-config.json`.

# experiments-config.json

This config is used to run server side diverted experiments. Please review the instruction [here](../../docs/running-server-side-experiment.md) beforehand.

-   `name`: Experiment name
-   `environment`: Specify the type of environment the experiment runs. Only support `AMP` and `INABOX`.
-   `issue`: The issue tracker URL for this experiment
-   `expiration_date_utc`: The experiment expiration date in YYYY-MM-DD format, in UTC. If an experiment is expired, it will fail the build process. This expiration date is only read during the build. As a result, the experiment will actually end on the following release date after the expiration.
-   `define_experiment_constant`: (Optional) The flag that is used to section out experiment code. This is passed into the `minify-replace` babel plugin and defaults to `false`. If an experiment relies on `minify-replace` to replace its experiment flag, this value must be defined.

Experiments will be built automatically for AMP releases by running `amp dist --esm --define_experiment_constant ${define_experiment_constant} && amp dist --define_experiment_constant ${define_experiment_constant}`

# custom-config.json

If `build-system/global-configs/custom-config.json` exists at build time, its properties will overlay the active config. For example, consider `amp dist --config=canary` with the following configs:

`canary-config.json` (simplified for brevity)

```json
{
  "canary": 1,
  "chunked-amp": 1,
  "version-locking": 1
}
```

`custom-config.json`

```json
{
  "cdnUrl": "https://example.com/amp",
  "version-locking": 0
}
```

The resulting config is

```json
{
  "canary": 1,
  "chunked-amp": 1,
  "version-locking": 0,
  "cdnUrl": "https://example.com/amp"
}
```

# custom-flavors-config.json

Additional release flavors can be defined in `build-system/global-configs/custom-flavors-config.json` and they will automatically be made available to `amp release`. This file should be an array of `DistFlavorDef` objects (see definition in [build-system/tasks/release/index.js](../tasks/release/index.js)). For example:

```json
[
  {
    "flavorType": "custom-exp",
    "name": "Custom Experimental Release",
    "environment": "AMP",
    "rtvPrefixes": [ "00" ],
    "command": "amp dist --noconfig"
  },
  {
    "flavorType": "custom-prod",
    "name": "Custom Production Release",
    "environment": "AMP",
    "rtvPrefixes": [ "01" ],
    "command": "amp dist --noconfig"
  }
]
```

and then "Custom Production Release" could be built with:

```sh
amp release --flavor="custom-prod"
```

**Tips:**

-   Be sure to pass flag `--noconfig` to `amp dist` in the flavor command, otherwise you will end up with multiple `AMP_CONFIG` definitions in entrypoint files (`v0.js`, `shadow-v0.js`, etc.).
-   Flag `--version_override` is not supported.
-   `AMP_CONFIG` can be customized with [`custom-config.json`](#custom-configjson) to further tailor the build.

# Looking for client-side-experiments-config.json?

This file now resides in the [ampproject/cdn-configuration](https://github.com/ampproject/cdn-configuration/blob/main/configs/client-side-experiments.json) repository.


text:
#include "SwallowCompiler.h"
#include "semantics/ScopedNodeFactory.h"
#include "semantics/ScopedNodes.h"
#include "semantics/SymbolRegistry.h"
#include "semantics/OperatorResolver.h"
#include "semantics/SemanticAnalyzer.h"
#include "semantics/DeclarationAnalyzer.h"
#include "semantics/GlobalScope.h"
#include "common/CompilerResults.h"
#include "parser/Parser.h"
using namespace std;
USE_SWALLOW_NS

SwallowCompiler::SwallowCompiler(const wstring& moduleName)
{
    symbolRegistry = new SymbolRegistry();
    compilerResults = new CompilerResults();
    nodeFactory = new ScopedNodeFactory();
    module = ModulePtr(new Module(moduleName, symbolRegistry->getGlobalScope()->getModuleType()));
    operatorResolver = new OperatorResolver(symbolRegistry, compilerResults);
    semanticAnalyzer = new SemanticAnalyzer(symbolRegistry, compilerResults, module);
    declarationAnalyzer = new DeclarationAnalyzer(semanticAnalyzer, semanticAnalyzer->getContext());
    scope = new SymbolScope();
}
SwallowCompiler::~SwallowCompiler()
{
    delete declarationAnalyzer;
    delete semanticAnalyzer;
    delete operatorResolver;
    delete nodeFactory;
    delete compilerResults;
    delete symbolRegistry;
}
void SwallowCompiler::addSourceFile(const SourceFilePtr& sourceFile)
{
    sourceFiles.push_back(sourceFile);
}
void SwallowCompiler::addSource(const wstring& name, const wstring& code)
{
    addSourceFile(SourceFilePtr(new SourceFile(name, code)));
}

ProgramPtr SwallowCompiler::createProgramNode()
{
    ScopedProgramPtr ret(new ScopedProgram());
    ret->setScope(scope);
    return ret;
}

bool SwallowCompiler::compile()
{
    std::vector<ProgramPtr> programs;
    return compile(programs);
}
bool SwallowCompiler::compile(std::vector<ProgramPtr>& programs)
{
    programs.clear();
    try
    {
        for(const SourceFilePtr& source : sourceFiles)
        {
            ProgramPtr program = createProgramNode();
            programs.push_back(program);
            Parser parser(nodeFactory, compilerResults);
            parser.setSourceFile(source);
            if(!parser.parse(source->code.c_str(), program))
                throw Abort();

            program->accept(operatorResolver);
            //program->accept(declarationAnalyzer);
            program->accept(semanticAnalyzer);
        }
    }
    catch(const Abort&)
    {
        //TODO: refactor compiler
        // ScopedProgram shouldn't maintaince its own scope.
        for(ProgramPtr p : programs)
        {
            if(ScopedProgramPtr sp = dynamic_pointer_cast<ScopedProgram>(p))
            {
                sp->setScope(scope);
            }

        }
        return false;
    }
    return true;
}
ModulePtr SwallowCompiler::getModule()
{
    return module;
}
ProgramPtr SwallowCompiler::getProgram()
{
    return program;
}
CompilerResults* SwallowCompiler::getCompilerResults()
{
    return compilerResults;
}

SymbolRegistry* SwallowCompiler::getSymbolRegistry()
{
    return symbolRegistry;
}
SymbolScope* SwallowCompiler::getScope()
{
    return scope;
}


text:
/* global app */

'use strict';

app.controller('MainController', function ($scope, $location, identity, $http, notifier) {
    $scope.identity = identity;

    $http.get('/api/statistics')
        .success(function(data){
            $scope.statistics = data;
        })
        .error(function(error){
            notifier.error('Failed to load statistics: ' + error.message || error);
        });
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Sibbaldia emodi H.Ikeda & H.Ohba

### Remarks
null