text:
package com.fincatto.documentofiscal.cte300.classes.nota;

import com.fincatto.documentofiscal.DFBase;
import com.fincatto.documentofiscal.validadores.DFStringValidador;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Namespace;
import org.simpleframework.xml.Root;

/**
 * @author Caio
 * @info Informações das Ferrovias Envolvidas
 */

@Root(name = "ferroEnv")
@Namespace(reference = "http://www.portalfiscal.inf.br/cte")
public class CTeNotaInfoCTeNormalInfoModalFerroviarioTrafegoMutuoFerroviasEnvolvidas extends DFBase {
    private static final long serialVersionUID = -7408236804856205178L;

    @Element(name = "CNPJ")
    private String cnpj;

    @Element(name = "cInt", required = false)
    private String codigoInterno;

    @Element(name = "IE", required = false)
    private String inscricaoEstadual;

    @Element(name = "xNome")
    private String razaoSocial;

    @Element(name = "enderFerro")
    private CTeNotaEnderecoFerrovia endereco;

    public CTeNotaInfoCTeNormalInfoModalFerroviarioTrafegoMutuoFerroviasEnvolvidas() {
        this.cnpj = null;
        this.codigoInterno = null;
        this.inscricaoEstadual = null;
        this.razaoSocial = null;
        this.endereco = null;
    }

    public String getCnpj() {
        return this.cnpj;
    }

    /**
     * Número do CNPJ

     * Informar o CNPJ da Ferrovia Envolvida. Caso a Ferrovia envolvida não seja inscrita no CNPJ o campo deverá preenchido com zeros. Informar os zeros não significativos.
     */
    public void setCnpj(final String cnpj) {
        DFStringValidador.cnpj(cnpj);
        this.cnpj = cnpj;
    }

    public String getCodigoInterno() {
        return this.codigoInterno;
    }

    /**
     * Código interno da Ferrovia envolvida

     * Uso da transportadora
     */
    public void setCodigoInterno(final String codigoInterno) {
        DFStringValidador.tamanho10(codigoInterno, "Código interno da Ferrovia envolvida");
        this.codigoInterno = codigoInterno;
    }

    public String getInscricaoEstadual() {
        return this.inscricaoEstadual;
    }

    /**
     * Inscrição Estadual
     */
    public void setInscricaoEstadual(final String inscricaoEstadual) {
        DFStringValidador.inscricaoEstadual(inscricaoEstadual);
        this.inscricaoEstadual = inscricaoEstadual;
    }

    public String getRazaoSocial() {
        return this.razaoSocial;
    }

    /**
     * Razão Social ou Nome
     */
    public void setRazaoSocial(final String razaoSocial) {
        DFStringValidador.tamanho2ate60(razaoSocial, "Razão Social ou Nome");
        this.razaoSocial = razaoSocial;
    }

    public CTeNotaEnderecoFerrovia getEndereco() {
        return this.endereco;
    }

    /**
     * Dados do endereço da ferrovia envolvida
     */
    public void setEndereco(final CTeNotaEnderecoFerrovia endereco) {
        this.endereco = endereco;
    }
}


text:
.class Landroid/webkit/WebViewClassic$TrustStorageListener;
.super Landroid/content/BroadcastReceiver;
.source "WebViewClassic.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/webkit/WebViewClassic;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "TrustStorageListener"
.end annotation

# direct methods
.method private constructor <init>()V
    .locals 0

    .prologue
    .line 1529
    invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V

    return-void
.end method

.method synthetic constructor <init>(Landroid/webkit/WebViewClassic$1;)V
    .locals 0
    .parameter "x0"

    .prologue
    .line 1529
    invoke-direct {p0}, Landroid/webkit/WebViewClassic$TrustStorageListener;-><init>()V

    return-void
.end method

# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
    .locals 2
    .parameter "context"
    .parameter "intent"

    .prologue
    .line 1532
    invoke-virtual {p2}, Landroid/content/Intent;->getAction()Ljava/lang/String;

    move-result-object v0

    const-string v1, "android.security.STORAGE_CHANGED"

    invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v0

    if-eqz v0, :cond_0

    .line 1533
    #calls: Landroid/webkit/WebViewClassic;->handleCertTrustChanged()V
    invoke-static {}, Landroid/webkit/WebViewClassic;->access$1200()V

    .line 1535
    :cond_0
    return-void
.end method

redpajama_set_name: RedPajamaGithub


text:
BEGIN;

-- Add a field to ExportConfig to indicate which signing key to use.

ALTER TABLE ExportConfig ADD COLUMN signing_key VARCHAR(500);

ALTER TABLE ExportBatch ADD COLUMN signing_key VARCHAR(500);

END;


text:
/* eslint-disable */

'use strict';

/*::
import type { ConcreteRequest } from 'relay-runtime';
type useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment$ref = any;
export type useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQueryVariables = {|
  id?: ?string,
|};
export type useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQueryResponse = {|
  +node: ?{|
    +id: string,
    +name: ?string,
    +$fragmentRefs: useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment$ref,
  |},
|};
export type useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery = {|
  variables: useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQueryVariables,
  response: useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQueryResponse,
|};
*/

var node/*: ConcreteRequest*/ = (function(){
var v0 = [
  {
    "defaultValue": null,
    "kind": "LocalArgument",
    "name": "id"
  }
],
v1 = [
  {
    "kind": "Variable",
    "name": "id",
    "variableName": "id"
  }
],
v2 = {
  "alias": null,
  "args": null,
  "kind": "ScalarField",
  "name": "id",
  "storageKey": null
},
v3 = {
  "alias": null,
  "args": null,
  "kind": "ScalarField",
  "name": "name",
  "storageKey": null
};
return {
  "fragment": {
    "argumentDefinitions": (v0/*: any*/),
    "kind": "Fragment",
    "metadata": null,
    "name": "useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery",
    "selections": [
      {
        "alias": null,
        "args": (v1/*: any*/),
        "concreteType": null,
        "kind": "LinkedField",
        "name": "node",
        "plural": false,
        "selections": [
          (v2/*: any*/),
          (v3/*: any*/),
          {
            "kind": "Defer",
            "selections": [
              {
                "args": null,
                "kind": "FragmentSpread",
                "name": "useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment"
              }
            ]
          }
        ],
        "storageKey": null
      }
    ],
    "type": "Query",
    "abstractKey": null
  },
  "kind": "Request",
  "operation": {
    "argumentDefinitions": (v0/*: any*/),
    "kind": "Operation",
    "name": "useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery",
    "selections": [
      {
        "alias": null,
        "args": (v1/*: any*/),
        "concreteType": null,
        "kind": "LinkedField",
        "name": "node",
        "plural": false,
        "selections": [
          {
            "alias": null,
            "args": null,
            "kind": "ScalarField",
            "name": "__typename",
            "storageKey": null
          },
          (v2/*: any*/),
          (v3/*: any*/),
          {
            "if": null,
            "kind": "Defer",
            "label": "useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery$defer$useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment",
            "selections": [
              {
                "kind": "InlineFragment",
                "selections": [
                  {
                    "alias": null,
                    "args": null,
                    "kind": "ScalarField",
                    "name": "firstName",
                    "storageKey": null
                  }
                ],
                "type": "User",
                "abstractKey": null
              }
            ]
          }
        ],
        "storageKey": null
      }
    ]
  },
  "params": {
    "cacheID": "24949dd00df70202822f15fe3ed87c7a",
    "id": null,
    "metadata": {},
    "name": "useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery",
    "operationKind": "query",
    "text": "query useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery(\n  $id: ID\n) {\n  node(id: $id) {\n    __typename\n    id\n    name\n    ...useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment @defer(label: \"useLazyLoadQueryNodeReactDoubleEffectsTestUserQueryWithDeferQuery$defer$useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment\")\n  }\n}\n\nfragment useLazyLoadQueryNodeReactDoubleEffectsTestUserFragment on User {\n  firstName\n}\n"
  }
};
})();

if (__DEV__) {
  (node/*: any*/).hash = "12d18891ad074f33e2e0064f4d26ebd2";
}

module.exports = node;


text:
package org.peelframework.spark.beans.system

import java.lang.{System => Sys}
import java.nio.file.Paths
import java.util.regex.Pattern

import com.samskivert.mustache.Mustache
import org.peelframework.core.beans.experiment.Experiment.Run
import org.peelframework.core.beans.system.Lifespan.Lifespan
import org.peelframework.core.beans.system.{LogCollection, SetUpTimeoutException, System}
import org.peelframework.core.config.{Model, SystemConfig}
import org.peelframework.core.util.console.ConsoleColorise
import org.peelframework.core.util.shell

import scala.collection.JavaConverters._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.util.matching.Regex

/** Wrapper class for Spark.
  *
  * Implements Spark as a Peel `System` and provides setup and teardown methods.
  *
  * @param version Version of the system (e.g. "7.1")
  * @param configKey The system configuration resides under `system.\${configKey}`.
  * @param lifespan `Lifespan` of the system
  * @param dependencies Set of dependencies that this system needs
  * @param mc The moustache compiler to compile the templates that are used to generate property files for the system
  */
class Spark(
  version      : String,
  configKey    : String,
  lifespan     : Lifespan,
  dependencies : Set[System] = Set(),
  mc           : Mustache.Compiler) extends System("spark", version, configKey, lifespan, dependencies, mc)
                                       with LogCollection {

  // ---------------------------------------------------
  // LogCollection.
  // ---------------------------------------------------

  var latestEventLogBeforeRun: Option[String] = None

  def eventLogPattern() = {
    val logDir = config.getString(s"system.$configKey.path.log")
    s"$logDir/app-*"
  }

  /** The patterns of the log files to watch. */
  override protected def logFilePatterns(): Seq[Regex] = {
    val user = Pattern.quote(config.getString(s"system.$configKey.user"))
    config.getStringList(s"system.$configKey.config.slaves").asScala.map(Pattern.quote).flatMap(slave => Seq(
      s"spark-$user-.+-$slave\\.log".r,
      s"spark-$user-.+-$slave\\.out".r))
  }

  override def beforeRun(run: Run[System]): Unit = {
    // delegate to parent
    super[LogCollection].beforeRun(run)
    // custom logic for Spark
    try {
      latestEventLogBeforeRun = for {
        f <- (shell !! s"ls -t ${eventLogPattern()}").split(Sys.lineSeparator).headOption.map(_.trim)
      } yield f
    } catch {
      case e: Exception =>
        latestEventLogBeforeRun = None
    }
  }

  override def afterRun(run: Run[System]): Unit = {
    // delegate to parent
    super[LogCollection].afterRun(run)
    // custom logic for Spark
    val eventLog = for {
      f <- (shell !! s"ls -t ${eventLogPattern()}").split(Sys.lineSeparator).headOption.map(_.trim)
    } yield f
    if (eventLog.isEmpty || eventLog == latestEventLogBeforeRun) {
      logger.warn("No event log created for experiment".yellow)
    }
    else {
      shell ! s"cp ${eventLog.head} ${run.home}/logs/$name/$beanName/${Paths.get(eventLog.head).getFileName}"
    }
  }

  // ---------------------------------------------------
  // System.
  // ---------------------------------------------------

  /** Parses the configuration and generates the Spark configuration files (slaves, spark-env.sh, spark-defaults.conf)
    * from the moustache templates
    *
    * @return System configuration for this system.
    */
  override def configuration() = SystemConfig(config, {
    val conf = config.getString(s"system.$configKey.path.config")
    //rename template files - strip the .template
    // TODO: this needs to be done only on demand
    shell ! s"""if [ ! -e "$conf/spark-env.sh" ]; then mv "$conf/spark-env.sh.template" "$conf/spark-env.sh"; fi """
    shell ! s"""if [ ! -e "$conf/spark-defaults.conf" ]; then mv "$conf/spark-defaults.conf.template" "$conf/spark-defaults.conf"; fi """
    List(
      SystemConfig.Entry[Model.Hosts](s"system.$configKey.config.slaves", s"$conf/slaves", templatePath("conf/hosts"), mc),
      SystemConfig.Entry[Model.Env](s"system.$configKey.config.env", s"$conf/spark-env.sh", templatePath("conf/spark-env.sh"), mc),
      SystemConfig.Entry[Model.Site](s"system.$configKey.config.defaults", s"$conf/spark-defaults.conf", templatePath("conf/spark-defaults.conf"), mc),
      SystemConfig.Entry[Model.Yaml](s"system.$configKey.config.log4j", s"$conf/log4j.properties", templatePath("conf/log4j.properties"), mc)
    )
  })

  /** Starts up the system and polls to check whether everything is up.
    *
    * This methods attempts to set up and start the system on all specified nodes.
    * If an attempt fails, we retry to start it `\${system.spark.startup.max.attempts}` times or shut down the system
    * after exceeding this limit.
    *
    * @throws SetUpTimeoutException If the system was not brought after `\${system.spark.startup.max.attempts}` or
    *                               `\${startup.pollingCounter}` times `\${startup.pollingInterval}` milliseconds.
    */
  override def start(): Unit = {
    val user = config.getString(s"system.$configKey.user")
    val logDir = config.getString(s"system.$configKey.path.log")

    val init = (host: String, paths: Seq[String]) => {
      val cmd = paths.map(path => s"rm -Rf $path && mkdir -p $path").mkString(" && ")
      s""" ssh $user@$host "$cmd" """
    }

    val hosts = config.getStringList(s"system.$configKey.config.slaves").asScala
    val paths = config.getString(s"system.$configKey.config.defaults.spark.local.dir").split(',')
    val workDir = config.getString(s"system.$configKey.path.work")

    val futureInitOps = Future.traverse(hosts){ host =>
      for {
        _ <- Future {
          logger.info(s"Initializing Spark tmp directories '${paths.mkString(",")}' at $host")
          shell ! (init(host, paths), s"Unable to initialize Spark tmp directories '${paths.mkString(",")}' at $host.")
        }
        f <- Future {
          logger.debug(s"Removing Spark work directory content '$workDir' at $host")
          // we ignore the failure here cause they are (most likely) due to 'stale file handles' in shared folders
          // aka. shared files are deleted concurrently
          shell ! rmWorkDir(user, host, workDir)
        }
      } yield f
    }

    // await for all futureInitOps to finish
    Await.result(futureInitOps, Math.max(30, 5 * hosts.size).seconds)

    var failedStartUpAttempts = 0
    while (!isUp) {
      try {
        val totl = config.getStringList(s"system.$configKey.config.slaves").size()
        val init = 0 // Spark resets the job manager log on startup

        shell ! s"${config.getString(s"system.$configKey.path.home")}/sbin/start-all.sh"
        logger.info(s"Waiting for nodes to connect")

        var curr = init
        var cntr = config.getInt(s"system.$configKey.startup.polling.counter")
        while (curr - init < totl) {
          logger.info(s"Connected ${curr - init} from $totl nodes")
          // wait a bit
          Thread.sleep(config.getInt(s"system.$configKey.startup.polling.interval"))
          // get new values
          curr = Integer.parseInt((shell !! s"""cat $logDir/spark-$user-org.apache.spark.deploy.master.Master-*.out | grep 'Registering worker' | wc -l""").trim())
          // timeout if counter goes below zero
          cntr = cntr - 1
          if (cntr < 0) throw new SetUpTimeoutException(s"Cannot start system '$toString'; node connection timeout at system ")
        }
        isUp = true
      } catch {
        case e: SetUpTimeoutException =>
          failedStartUpAttempts = failedStartUpAttempts + 1
          if (failedStartUpAttempts < config.getInt(s"system.$configKey.startup.max.attempts")) {
            shell ! s"${config.getString(s"system.$configKey.path.home")}/sbin/stop-all.sh"
            logger.info(s"Could not bring system '$toString' up in time, trying again...")
          } else {
            throw e
          }
      }
    }
  }

  override def stop(): Unit = {
    shell ! s"${config.getString(s"system.$configKey.path.home")}/sbin/stop-all.sh"
    isUp = false

    // remove work dir; as in start
    val user = config.getString(s"system.$configKey.user")
    val hosts = config.getStringList(s"system.$configKey.config.slaves").asScala
    val workDir = config.getString(s"system.$configKey.path.work")

    val futureOps = Future.traverse(hosts) { host =>
      Future {
        logger.debug(s"Removing Spark work directory content '$workDir' at $host")
        shell ! rmWorkDir(user, host, workDir)
      }
    }

    Await.result(futureOps, Math.max(30, 5 * hosts.size).seconds)
  }

  def isRunning = {
    val pidDir = config.getString(s"system.$configKey.config.env.SPARK_PID_DIR")
    (shell ! s""" ps -p `cat $pidDir/spark-*Master*.pid` """) == 0 ||
      (shell ! s""" ps -p `cat $pidDir/spark-*Worker*.pid` """) == 0
  }

  private def rmWorkDir(user: String, host: String, workDir: String) = {
    val cmd = s""" rm -Rf $workDir/* """
    s""" ssh $user@$host "$cmd" """
  }
}


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

/**
 * @fileoverview Directive for the NumberWithUnits short response.
 */

require('domain/objects/NumberWithUnitsObjectFactory.ts');
require('services/html-escaper.service.ts');

angular.module('oppia').component('oppiaShortResponseNumberWithUnits', {
  template: require('./number-with-units-short-response.component.html'),
  controllerAs: '$ctrl',
  controller: [
    '$attrs', 'HtmlEscaperService', 'NumberWithUnitsObjectFactory',
    function(
        $attrs, HtmlEscaperService, NumberWithUnitsObjectFactory) {
      var ctrl = this;
      ctrl.$onInit = function() {
        var answer = HtmlEscaperService.escapedJsonToObj($attrs.answer);
        ctrl.answer = NumberWithUnitsObjectFactory.fromDict(
          answer).toString();
      };
    }]
});


text:
#include "vulkan/PlatformVkLinuxX11.h"

#include "VulkanConstants.h"
#include "VulkanDriverFactory.h"

#include <utils/Panic.h>

#include <bluevk/BlueVK.h>

#include <dlfcn.h>

using namespace bluevk;

namespace filament::backend {

static constexpr const char* LIBRARY_X11 = "libX11.so.6";

#ifdef FILAMENT_SUPPORTS_XCB
typedef xcb_connection_t* (*XCB_CONNECT)(const char *displayname, int *screenp);
#endif

#ifdef FILAMENT_SUPPORTS_XLIB
typedef Display* (*X11_OPEN_DISPLAY)(const char*);
#endif

struct X11Functions {
#ifdef FILAMENT_SUPPORTS_XCB
    XCB_CONNECT xcbConnect;
#endif

#ifdef FILAMENT_SUPPORTS_XLIB
    X11_OPEN_DISPLAY openDisplay;
#endif
    void* library = nullptr;
} g_x11;

Driver* PlatformVkLinuxX11::createDriver(void* const sharedContext, const Platform::DriverConfig& driverConfig) noexcept {
    ASSERT_PRECONDITION(sharedContext == nullptr, "Vulkan does not support shared contexts.");
    const char* requiredInstanceExtensions[] = {
#ifdef FILAMENT_SUPPORTS_XCB
        "VK_KHR_xcb_surface",
#endif
#ifdef FILAMENT_SUPPORTS_XLIB
        "VK_KHR_xlib_surface",
#endif
    };
    return VulkanDriverFactory::create(this, requiredInstanceExtensions,
            sizeof(requiredInstanceExtensions) / sizeof(requiredInstanceExtensions[0]), driverConfig);
}

void* PlatformVkLinuxX11::createVkSurfaceKHR(void* nativeWindow, void* instance, uint64_t flags) noexcept {
    if (g_x11.library == nullptr) {
        g_x11.library = dlopen(LIBRARY_X11, RTLD_LOCAL | RTLD_NOW);
        ASSERT_PRECONDITION(g_x11.library, "Unable to open X11 library.");

#ifdef FILAMENT_SUPPORTS_XCB
        g_x11.xcbConnect = (XCB_CONNECT) dlsym(g_x11.library, "xcb_connect");
        int screen;
        mConnection = g_x11.xcbConnect(nullptr, &screen);
        ASSERT_POSTCONDITION(vkCreateXcbSurfaceKHR, "Unable to load vkCreateXcbSurfaceKHR function.");
#endif

#ifdef FILAMENT_SUPPORTS_XLIB
        g_x11.openDisplay  = (X11_OPEN_DISPLAY)  dlsym(g_x11.library, "XOpenDisplay");
        mDisplay = g_x11.openDisplay(NULL);
        ASSERT_PRECONDITION(mDisplay, "Unable to open X11 display.");
        ASSERT_POSTCONDITION(vkCreateXlibSurfaceKHR, "Unable to load vkCreateXlibSurfaceKHR function.");
#endif

    }

    VkSurfaceKHR surface = nullptr;

#ifdef FILAMENT_SUPPORTS_XCB
#ifdef FILAMENT_SUPPORTS_XLIB
const bool windowIsXCB = flags & SWAP_CHAIN_CONFIG_ENABLE_XCB;
#else
const bool windowIsXCB = true;
#endif

    if (windowIsXCB) {
        const uint64_t ptrval = reinterpret_cast<uint64_t>(nativeWindow);
        VkXcbSurfaceCreateInfoKHR createInfo = {
            .sType = VK_STRUCTURE_TYPE_XCB_SURFACE_CREATE_INFO_KHR,
            .connection = mConnection,
            .window = (xcb_window_t) ptrval,
        };
        vkCreateXcbSurfaceKHR((VkInstance) instance, &createInfo, VKALLOC, &surface);
        return surface;
    }
#endif

#ifdef FILAMENT_SUPPORTS_XLIB
    VkXlibSurfaceCreateInfoKHR createInfo = {
        .sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR,
        .dpy = mDisplay,
        .window = (Window) nativeWindow,
    };
    vkCreateXlibSurfaceKHR((VkInstance) instance, &createInfo, VKALLOC, &surface);
#endif

    return surface;
}

} // namespace filament::backend


text:
This is a SPA blog that can render the following on both the client and server:

* Syntax highlighted code
* Sequence diagrams
* Markdown

This is done using custom components.

This means when you load a new page, we will simply send the client some markdown to render.


text:
var angular = angular || {};

angular.module('app.router', [])
    .config(function($stateProvider, $urlRouterProvider) {
        $stateProvider
        .state('basic', {
            url: '/',
            templateUrl:'views/basic.html',
            controller: 'BasicCtrl'
        })

        ///redirect to default.
        $urlRouterProvider.otherwise('/');
    })


text:
layout: post
title: "如何在VMware Workstations上安装windows11"
date:   2021-10-11 15:30:00
categories: "Others"
catalog: true
tags:
    - Others
---

Windows 11 已经于 10月4日正式发布,在VMware Workstations 15.5.2 上安装时会提示没有满足最小安装需求

    This PC doesn't meet the minimum system requirements to install this version of Windows. For more informaiton, visit https://aka.ms/WindowsSysReq

![img](https://github.com/kerwenzhang/kerwenzhang.github.io/blob/master/_posts/image/win11.png?raw=true)

解决方法:
1. 按Shift+F10,调出 cmd窗口
2. 输入regedit,调出注册表窗口
3. 定位到HKEY_LOCAL_MACHINE\SYSTEM\SETUP,创建子健LabConfig
4. 定位到LabConfig, 在右边新建以下四个 DWORD 值, Data都是1

    BypassTPMCheck
    BypassCPUCheck
    BypassRAMCheck
    BypassSecureBootCheck

5. 关掉注册表和cmd窗口,然后关掉windows安装错误提示窗口
6. 回到Install Now界面,重新选择edition

## 参考
[How to Fix Cannot Install Windows 11 on VMware Workstation | Windows 11 VMware Not Meet Requirements](https://www.youtube.com/watch?v=sCLJYNI77Bk&ab_channel=TeeVee)


text:
<?xml version="1.0" encoding="UTF-8"?>
<head xmlns="http://www.unfine.de/schema/menu">
    <icon-item src="resource/img/framebars/console/auto_scroll.png"
               tool-tip="console_toggle_auto_scroll_tooltip"
               action="console_toggle_auto_scroll" checkable="true"/>
    <icon-item src="resource/img/framebars/console/auto_show.png"
               tool-tip="console_toggle_auto_show_tooltip"
               action="console_toggle_auto_show" checkable="true"/>
    <icon-item src="resource/img/framebars/console/clear.png"
               tool-tip="console_clear_tooltip"
               action="console_action_clear"/>
</head>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>DartAngularHello</title>
    <link rel="stylesheet" href="dartangularhello.css">

DartAngularHello

Hello world from AngularDart!

Hello {{hello.name|capitalize}} Age={{hello.age}}!

    Name: <input type="text" ng-model="hello.name">

Age: {{hello.age}}

      Age: <input type="number" ng-model="hello.age">
     <button ng-click="hello.foo()">foo</button>


text:
from collections import defaultdict
import gzip
import os
import re
import subprocess

from django.conf import settings
from settings import JBROWSE_DATA_URL_ROOT
from settings import S3_BUCKET

from main.model_utils import get_dataset_with_type
from main.models import Dataset
from utils.bam_utils import sort_bam_by_coordinate
from utils.bam_utils import index_bam
from utils.import_util import add_dataset_to_entity
from utils.jbrowse_util import prepare_jbrowse_ref_sequence
from utils.jbrowse_util import write_tracklist_json

def maybe_create_reads_to_contig_bam(contig):
    if not contig.dataset_set.filter(
            type=Dataset.TYPE.BWA_ALIGN).exists():
        prepare_jbrowse_ref_sequence(contig)
        align_contig_reads_to_contig(contig)

        # TODO(dbg): Maybe fix.
        # add_contig_reads_to_contig_bam_track(contig, Dataset.TYPE.BWA_ALIGN)

def align_contig_reads_to_contig(contig):

    # Get fasta of reads used to make contig
    contig_reads_fasta = os.path.join(
            contig.get_model_data_dir(),
            'extracted_reads.fa')

    # Pull out contig read qnames and put in dictionary contig_reads
    p1 = re.compile('>(\S+)/(\d)')
    contig_reads = defaultdict(list)
    with open(contig_reads_fasta) as fh:
        for line in fh:
            m1 = p1.match(line)
            if m1:
                read_id = m1.group(1)
                read_number = int(m1.group(2))
                contig_reads[read_id].append(read_number)

    # Get source reads fastqs
    sample = contig.experiment_sample_to_alignment.experiment_sample
    source_fq1 = sample.dataset_set.get(
            type=Dataset.TYPE.FASTQ1).get_absolute_location()
    source_fq2_query = sample.dataset_set.filter(
            type=Dataset.TYPE.FASTQ2)
    is_paired_end = source_fq2_query.exists()
    if is_paired_end:
        source_fq2 = source_fq2_query[0].get_absolute_location()

    # Make filenames for contig read fastqs
    output_fq1 = os.path.join(
            contig.get_model_data_dir(),
            'reads.1.fq')
    if is_paired_end:
        output_fq2 = os.path.join(
                contig.get_model_data_dir(),
                'reads.2.fq')

    # Go through source fastqs and write reads in contig_reads to file
    source_fq_list = [source_fq1]
    output_fq_list = [output_fq1]
    if is_paired_end:
        source_fq_list.append(source_fq2)
        output_fq_list.append(output_fq2)

    p1 = re.compile('@(\S+)')
    for input_fq_path, output_fq_path in zip(source_fq_list, output_fq_list):
        if input_fq_path.endswith('.fq'):
            file_like = open(input_fq_path)
        elif input_fq_path.endswith('.gz'):
            file_like = gzip.open(input_fq_path)
        else:
            raise Exception('Compression type not supported')

        with file_like as in_fh, \
             open(output_fq_path, 'w') as out_fh:
            for line in in_fh:
                m1 = p1.match(line)
                if m1:
                    qname = m1.group(1)
                    if qname in contig_reads:
                        out_fh.write(line)
                        out_fh.write(in_fh.next())
                        out_fh.write(in_fh.next())
                        out_fh.write(in_fh.next())

    # Align fastqs to contig fasta
    contig_fasta = contig.dataset_set.get(
            type=Dataset.TYPE.REFERENCE_GENOME_FASTA).get_absolute_location()
    contig_reads_to_contig_bam = os.path.join(
            contig.get_model_data_dir(),
            'reads_to_contig.bam')
    simple_align_paired_with_bwa_mem(
            output_fq_list,
            contig_fasta,
            contig_reads_to_contig_bam)

    # Coordinate sort and index bam for jbrowse
    coordinate_sorted_bam = (os.path.splitext(contig_reads_to_contig_bam)[0] +
            '.coordinate_sorted.bam')
    sort_bam_by_coordinate(contig_reads_to_contig_bam, coordinate_sorted_bam)
    index_bam(coordinate_sorted_bam)

    # Add the bam file to contig as BWA_ALIGN dataset, overwriting it
    # if it already exists
    dataset_query = contig.dataset_set.filter(
            type=Dataset.TYPE.BWA_ALIGN)
    if dataset_query.count():
        dataset_query[0].delete()

    add_dataset_to_entity(
            contig,
            Dataset.TYPE.BWA_ALIGN,
            Dataset.TYPE.BWA_ALIGN,
            filesystem_location=coordinate_sorted_bam)

def simple_align_paired_with_bwa_mem(reads_fq, reference_fasta,
        output_bam_path):

    # Ensure reference fasta is indexed
    subprocess.call(' '.join([
            '%s/bwa/bwa' % settings.TOOLS_DIR,
            'index',
            reference_fasta
            ]),
            shell=True, executable=settings.BASH_PATH)

    # Align the fastqs to the reference
    align_input_args = [
            '%s/bwa/bwa' % settings.TOOLS_DIR,
            'mem',
            reference_fasta]

    align_input_args.extend(reads_fq)
    align_input_cmd = ' '.join(align_input_args)

    # To skip saving the SAM file to disk directly, pipe output directly to
    # make a BAM file.
    align_input_cmd += (' | ' + settings.SAMTOOLS_BINARY +
            ' view -bS -')

    # Run alignment
    with open(output_bam_path, 'w') as fh:
        subprocess.check_call(
                align_input_cmd, stdout=fh,
                shell=True, executable=settings.BASH_PATH)

def add_contig_reads_to_contig_bam_track(contig, alignment_type):
    """Update the JBrowse track config file, trackList.json, for this
    Contig with a track for the alignment of its reads to itself
    """
    # Get the bam file location from the the Dataset of the contig
    # keyed by the alignment_type.
    bam_dataset = get_dataset_with_type(contig, alignment_type)

    # Figure out the url that JBrowse would use to show the data, e.g.:
    #     /jbrowse/gd_data/projects/58a62c7d/genomes/8dc829ec/align.bam
    # urlTemplate = os.path.join(JBROWSE_DATA_URL_ROOT,
    #         bam_dataset.filesystem_location)

    # NOTE: We should construct bam file urls using project.get_client
    # jbrowse_link() rather than checking S3 flag here.
    if contig.parent_reference_genome.project.is_s3_backed():
        urlTemplate = os.path.join('http://%s.s3.amazonaws.com/' % S3_BUCKET,
            bam_dataset.filesystem_location.strip("/jbrowse"))
    else:
        urlTemplate = os.path.join(JBROWSE_DATA_URL_ROOT,
            bam_dataset.filesystem_location)

    label = bam_dataset.internal_string(
            contig)

    key = bam_dataset.external_string(contig)

    # Build the JSON object.
    raw_dict_obj = {
        'tracks': [
            {
                'storeClass': 'JBrowse/Store/SeqFeature/BAM',
                'urlTemplate': urlTemplate,
                'label': label,
                'type': 'JBrowse/View/Track/Alignments2',
                'chunkSizeLimit': 10000000, # double the default chunk size
                'key': key,
                'category': 'Contig BAM Tracks',
                'style': {
                    'className': 'alignment',
                    'arrowheadClass': 'arrowhead',
                    'labelScale': 100
                }
            }
        ]}
    write_tracklist_json(contig, raw_dict_obj, label)

    # Also add a snp coverage track.
    snp_coverage_label = bam_dataset.internal_string(
            contig) + '_COVERAGE'

    snp_coverage_key = key + ' Coverage'
    coverage_raw_dict_obj = {
        'tracks': [
            {
                'storeClass': 'JBrowse/Store/SeqFeature/BAM',
                'urlTemplate': urlTemplate,
                'label': snp_coverage_label,
                'type': 'JBrowse/View/Track/SNPCoverage',
                'category': 'Contig Coverage Tracks',
                'key': snp_coverage_key
            }
        ]}
    write_tracklist_json(contig, coverage_raw_dict_obj,
            snp_coverage_label)

def add_contig_reads_bam_track(contig, alignment_type):
    """Update the JBrowse track config file, trackList.json, for this
    ReferenceGenome with a track for the given sample_alignment and
    alignment_type.
    """
    # Get the bam file location from the the Dataset of the genome
    # keyed by the alignment_type.
    bam_dataset = get_dataset_with_type(contig, alignment_type)

    # Figure out the url that JBrowse would use to show the data, e.g.:
    #     /jbrowse/gd_data/projects/58a62c7d/genomes/8dc829ec/align.bam
    # urlTemplate = os.path.join(JBROWSE_DATA_URL_ROOT,
    #         bam_dataset.filesystem_location)

    # NOTE: We should construct bam file urls using project.get_client
    # jbrowse_link() rather than checking S3 flag here.
    reference_genome = contig.parent_reference_genome
    if reference_genome.project.is_s3_backed():
        urlTemplate = os.path.join('http://%s.s3.amazonaws.com/' % S3_BUCKET,
            bam_dataset.filesystem_location.strip("/jbrowse"))
    else:
        urlTemplate = os.path.join(JBROWSE_DATA_URL_ROOT,
            bam_dataset.filesystem_location)

    # doing label as ES_AG because SA isn't currently used in the variant view
    label = bam_dataset.internal_string(contig)

    key = bam_dataset.external_string(contig)

    # Build the JSON object.
    raw_dict_obj = {
        'tracks': [
            {
                'storeClass': 'JBrowse/Store/SeqFeature/BAM',
                'urlTemplate': urlTemplate,
                'label': label,
                'type': 'JBrowse/View/Track/Alignments2',
                'chunkSizeLimit': 10000000, # double the default chunk size
                'key': key,
                'category': 'Contig BAM Tracks',
                'style': {
                    'className': 'alignment',
                    'arrowheadClass': 'arrowhead',
                    'labelScale': 100
                }
            }
        ]}
    write_tracklist_json(reference_genome, raw_dict_obj, label)

    # Also add a snp coverage track.
    snp_coverage_label = bam_dataset.internal_string(
            contig) + '_COVERAGE'

    snp_coverage_key = key + ' Coverage'
    coverage_raw_dict_obj = {
        'tracks': [
            {
                'storeClass': 'JBrowse/Store/SeqFeature/BAM',
                'urlTemplate': urlTemplate,
                'label': snp_coverage_label,
                'type': 'JBrowse/View/Track/SNPCoverage',
                'category': 'Contig Coverage Tracks',
                'key': snp_coverage_key
            }
        ]}
    write_tracklist_json(reference_genome, coverage_raw_dict_obj,
            snp_coverage_label)


text:
class SerialFactory {

  protected:
      volatile uint8_t * const _ubrrh;
      volatile uint8_t * const _ubrrl;
      volatile uint8_t * const _ucsra;
      volatile uint8_t * const _ucsrb;
      volatile uint8_t * const _ucsrc;
      volatile uint8_t * const _udr;

      volatile uint8_t _tx_buffer[SERIAL_TX_BUFFER_SIZE];
      volatile uint8_t _rx_buffer[SERIAL_RX_BUFFER_SIZE];

      volatile uint8_t _tx_buffer_head;
      volatile uint8_t _tx_buffer_tail;
      volatile uint8_t _rx_buffer_head;
      volatile uint8_t _rx_buffer_tail;

  public:
    SerialFactory(
        volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
        volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
        volatile uint8_t *ucsrc, volatile uint8_t *udr);

    void begin(uint32_t);
    void end();

    uint8_t available();
    uint8_t read();

    void write(uint8_t);
    void print(const char*);
    void print(uint16_t);

    inline void print(uint32_t n) { write(n); }
    inline void write(uint32_t n) { write((uint8_t)n); }
    inline void write(int32_t n) { write((uint8_t)n); }
    inline void write(uint16_t n) { write((uint8_t)n); }
    inline void write(int16_t n) { write((uint8_t)n); }

    void flush();
    void clear();

    // Private-ish members used by interrupts
    void _sendNextByte();
    void _receiveByte();
};

#endif


text:
SPHINXOPTS    =
SPHINXBUILD   = sphinx-build
PAPER         =
BUILDDIR      = _build

# Internal variables.
PAPEROPT_a4     = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .

.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext

help:
	@echo "Please use \`make <target>' where <target> is one of"
	@echo "  html       to make standalone HTML files"
	@echo "  livehtml   to create a live version of the documentation"
	@echo "  dirhtml    to make HTML files named index.html in directories"
	@echo "  singlehtml to make a single large HTML file"
	@echo "  pickle     to make pickle files"
	@echo "  json       to make JSON files"
	@echo "  htmlhelp   to make HTML files and a HTML help project"
	@echo "  qthelp     to make HTML files and a qthelp project"
	@echo "  devhelp    to make HTML files and a Devhelp project"
	@echo "  epub       to make an epub"
	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
	@echo "  latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
	@echo "  text       to make text files"
	@echo "  man        to make manual pages"
	@echo "  texinfo    to make Texinfo files"
	@echo "  info       to make Texinfo files and run them through makeinfo"
	@echo "  gettext    to make PO message catalogs"
	@echo "  changes    to make an overview of all changed/added/deprecated items"
	@echo "  xml        to make Docutils-native XML files"
	@echo "  pseudoxml  to make pseudoxml-XML files for display purposes"
	@echo "  linkcheck  to check all external links for integrity"
	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
	@echo "  spelling   to check for typos in documentation"

clean:
	rm -rf $(BUILDDIR)/*

html:
	$(SPHINXBUILD) -W -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

livehtml:
	sphinx-autobuild -W -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."

dirhtml:
	$(SPHINXBUILD) -W -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
	@echo
	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."

singlehtml:
	$(SPHINXBUILD) -W -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
	@echo
	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."

pickle:
	$(SPHINXBUILD) -W -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
	@echo
	@echo "Build finished; now you can process the pickle files."

json:
	$(SPHINXBUILD) -W -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
	@echo
	@echo "Build finished; now you can process the JSON files."

htmlhelp:
	$(SPHINXBUILD) -W -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
	@echo
	@echo "Build finished; now you can run HTML Help Workshop with the" \
	      ".hhp project file in $(BUILDDIR)/htmlhelp."

qthelp:
	$(SPHINXBUILD) -W -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
	@echo
	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/ovmm.qhcp"
	@echo "To view the help file:"
	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/ovmm.qhc"

devhelp:
	$(SPHINXBUILD) -W -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
	@echo
	@echo "Build finished."
	@echo "To view the help file:"
	@echo "# mkdir -p $$HOME/.local/share/devhelp/ovmm"
	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/ovmm"
	@echo "# devhelp"

epub:
	$(SPHINXBUILD) -W -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
	@echo
	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."

latex:
	$(SPHINXBUILD) -W -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo
	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
	@echo "Run \`make' in that directory to run these through (pdf)latex" \
	      "(use \`make latexpdf' here to do that automatically)."

latexpdf:
	$(SPHINXBUILD) -W -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through pdflatex..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

latexpdfja:
	$(SPHINXBUILD) -W -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
	@echo "Running LaTeX files through platex and dvipdfmx..."
	$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."

text:
	$(SPHINXBUILD) -W -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
	@echo
	@echo "Build finished. The text files are in $(BUILDDIR)/text."

man:
	$(SPHINXBUILD) -W -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
	@echo
	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."

texinfo:
	$(SPHINXBUILD) -W -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo
	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
	@echo "Run \`make' in that directory to run these through makeinfo" \
	      "(use \`make info' here to do that automatically)."

info:
	$(SPHINXBUILD) -W -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
	@echo "Running Texinfo files through makeinfo..."
	make -C $(BUILDDIR)/texinfo info
	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."

gettext:
	$(SPHINXBUILD) -W -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
	@echo
	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."

changes:
	$(SPHINXBUILD) -W -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
	@echo
	@echo "The overview file is in $(BUILDDIR)/changes."

linkcheck:
	$(SPHINXBUILD) -W -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
	@echo
	@echo "Link check complete; look for any errors in the above output " \
	      "or in $(BUILDDIR)/linkcheck/output.txt."

doctest:
	$(SPHINXBUILD) -W -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
	@echo "Testing of doctests in the sources finished, look at the " \
	      "results in $(BUILDDIR)/doctest/output.txt."

xml:
	$(SPHINXBUILD) -W -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
	@echo
	@echo "Build finished. The XML files are in $(BUILDDIR)/xml."

pseudoxml:
	$(SPHINXBUILD) -W -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
	@echo
	@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."

spelling:
	$(SPHINXBUILD) -W -b spelling $(ALLSPHINXOPTS) $(BUILDDIR)/spelling
	@echo
	@echo "Check finished. Wrong words can be found in " \
		"$(BUILDDIR)/spelling/output.txt."


text:
typedef void(*event_callback)(void* args);
inline int add_fd_event(int fd, event_t et, event_callback event_cb, void* args) { return 0; }
inline void del_fd_event(int fd, event_t et) { }
inline void event_loop(int millisecs) { }
inline void event_loop_init(int maxconn) { }
#endif

#endif


text:
namespace enterprise_reporting {

class ReportingDelegateFactory;

class ReportGenerator {
 public:
  using ReportCallback = base::OnceCallback<void(ReportRequestQueue)>;

  class Delegate {
   public:
    Delegate() = default;
    Delegate(const Delegate&) = delete;
    Delegate& operator=(const Delegate&) = delete;
    virtual ~Delegate() = default;

    // Collect the Android application information installed on primary profile,
    // and set it to |basic_request_|. Only implemented for Chrome OS. The
    // fields are empty on other platforms.
    virtual void SetAndroidAppInfos(ReportRequest* basic_request) = 0;
  };

  explicit ReportGenerator(ReportingDelegateFactory* delegate_factory);

  ReportGenerator(const ReportGenerator&) = delete;
  ReportGenerator& operator=(const ReportGenerator&) = delete;

  virtual ~ReportGenerator();

  // Asynchronously generates a queue of report requests, providing them to
  // |callback| when ready. If |report_type| is kFull, all details are
  // included for all loaded profiles. Otherwise, the report only contains
  // information that are needed by that particular type.
  virtual void Generate(ReportType report_type, ReportCallback callback);

 protected:
  // Creates a basic request that will be used by all Profiles.
  void CreateBasicRequest(std::unique_ptr<ReportRequest> basic_request,
                          ReportType report_type,
                          ReportCallback callback);

  // Returns the name of computer.
  virtual std::string GetMachineName();

  // Returns the name of OS user.
  virtual std::string GetOSUserName();

  // Returns the Serial number of the device. It's Windows only field and empty
  // on other platforms.
  virtual std::string GetSerialNumber();

 private:
  void GenerateReport(ReportType report_type,
                      ReportCallback callback,
                      std::unique_ptr<ReportRequest> basic_request);

  void SetHardwareInfo(
      std::unique_ptr<ReportRequest> basic_request,
      base::OnceCallback<void(std::unique_ptr<ReportRequest>)> callback,
      base::SysInfo::HardwareInfo hardware_info);

  void OnBrowserReportReady(
      std::unique_ptr<ReportRequest> basic_request,
      ReportType report_type,
      ReportCallback callback,
      std::unique_ptr<enterprise_management::BrowserReport> browser_report);

  std::unique_ptr<Delegate> delegate_;

  ReportRequestQueueGenerator report_request_queue_generator_;
  BrowserReportGenerator browser_report_generator_;

  base::WeakPtrFactory<ReportGenerator> weak_ptr_factory_{this};
};

}  // namespace enterprise_reporting

#endif  // COMPONENTS_ENTERPRISE_BROWSER_REPORTING_REPORT_GENERATOR_H_


text:
external help file: AutomatedLabWorker-help.xml
Module Name: AutomatedLabWorker
online version: https://automatedlab.org/en/latest/AutomatedLabWorker/en-us/New-LabAzureResourceGroupDeployment
schema: 2.0.0
---

# New-LabAzureResourceGroupDeployment

## SYNOPSIS
Deploy the lab definition as an Azure resource group

## SYNTAX

```
New-LabAzureResourceGroupDeployment [-Lab] <Lab> [-PassThru] [-Wait] [<CommonParameters>]
```

## DESCRIPTION
Deploy the lab definition as an Azure resource group

## EXAMPLES

### Example 1
```powershell
PS C:\> New-LabAzureResourceGroupDeployment -Lab (Get-LabDefinition) -Wait
```

Build current definition on Azure, wait for deployment to finish

## PARAMETERS

### -Lab
Lab definition

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

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

### -PassThru
Indicates that resulting job or resulting path will be returned

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

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

### -Wait
Indicates that cmdlet should wait for the deployment to finish

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

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

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

## INPUTS

### None
## OUTPUTS

### System.Object
## NOTES

## RELATED LINKS


text:
'use strict';

/*
 * Module Definition
 *
 */

import React from 'react';
import { getClassNames, isEqual } from '../../utils/index';

/*
 * Class Definition
 *
 */

class ResultsListItem extends React.Component {
  constructor(props) {
    super(props);

    this.onClick = props.onClick.bind(null, props.idx);
  }

  /*
   * componentDidUpdate
   *
   */

  componentDidUpdate(prevProps, prevState) {
    const isSelectedEntityChanged = !isEqual(prevProps.selectedEntity, this.props.selectedEntity);
    isSelectedEntityChanged && this.toggle();
  }

  /*
   * isSelected
   *
   */

  isSelected() {
    return this.props.idx === this.props.selectedEntity
  }

  /*
   * render
   *
   */

  render() {
    const { item } = this.props;

    const classNames = getClassNames({
      active: (this.isSelected()) ? true : false
    });

    const renderPhoneNumbers = (phones) => {
      return (

          {phones.map((phone, idx) =>
{ phone.type }: <a href={`tel:${ phone.telNumber }`}>{ phone.phoneNumber }
)}

      )
    };

    return (

            { item.dist }miles

{ item.title }

{ item.address.address1}

            { item.address.address2 != '' &&

{ item.address.address2 }

            }

{ item.address.city }, { item.address.state } { item.address.zip }

              { renderPhoneNumbers(item.phones) }

    )
  }
}

/*
 * Module Export
 *
 */

export default ResultsListItem;


text:
name: I am having difficulty installing Flutter or getting it to work
about: You have run into problems while downloading or installing Flutter, or the
  "flutter" tool is crashing, or you are running into some other issue before even
  being able to use "flutter run".
title: ''
labels: ''
assignees: ''

---

<!-- Thank you for using Flutter!

     If you are looking for support, please check out our documentation
     or consider asking a question on Stack Overflow:
      * https://flutter.dev/
      * https://api.flutter.dev/
      * https://stackoverflow.com/questions/tagged/flutter?sort=frequent

     If you have found a bug or if our documentation doesn't have an answer
     to what you're looking for, then fill out the template below. Please read
     our guide to filing a bug first: https://flutter.dev/docs/resources/bug-reports
-->

## Steps to Reproduce

<!-- Please tell us exactly how to reproduce the problem you are running into. -->

1. ...
2. ...
3. ...

## Logs

<!--
      Include the full logs of the commands you are running between the lines
      with the backticks below. If you are running any "flutter" commands,
      please include the output of running them with "--verbose"; for example,
      the output of running "flutter --verbose create foo".
-->

```
```

<!-- If possible, paste the output of running `flutter doctor -v` here. -->

```
```


text: const int UtilConstants::NO_COMPONENTS = 0;


text:
using UnityEngine;
using System.Collections;

public class playerRender : MonoBehaviour {

	public int playerID;

	public Transform ActorMesh;

	public PlayerSync PlayerSyncScript;

	void Awake () {
		playerID = PlayerSyncScript.MyPlayer;

		foreach (Transform child in ActorMesh) {
			child.gameObject.SetActive(false);
		}
		ActorMesh.GetChild(playerID++).gameObject.SetActive(true);
	}

}


text:
#ifndef SECURITY_STREAMHTMLPARSER_JSPARSER_H
#define SECURITY_STREAMHTMLPARSER_JSPARSER_H

#include <config.h>
#include "htmlparser/statemachine.h"

#ifdef __cplusplus
namespace ctemplate_htmlparser {
#endif /* __cplusplus */

/* Size of the ring buffer used to lookup the last token in the javascript
 * stream. The size is pretty much arbitrary at this point but must be bigger
 * than the biggest token we want to lookup plus 3: Two delimiters plus an empty
 * ring buffer slot. */
#define JSPARSER_RING_BUFFER_SIZE 18

enum js_state_external_enum {
    JSPARSER_STATE_TEXT,
    JSPARSER_STATE_Q,
    JSPARSER_STATE_DQ,
    JSPARSER_STATE_REGEXP,
    JSPARSER_STATE_COMMENT
};

/* Stores the context of the javascript parser.
 *
 * If this structure is changed, jsparser_new(), jsparser_copy() and
 * jsparser_reset() should be updated accordingly.
 */
typedef struct jsparser_ctx_s {

  /* Reference to the statemachine context. */
  statemachine_ctx *statemachine;

  /* Reference to the statemachine definition.
   *
   * It should be readonly and contain the same values across jsparser
   * instances.
   */
  /* TODO(falmeida): Change statemachine_def to const. */
  statemachine_definition *statemachine_def;

  /* Index to the start of the buffer. */
  int buffer_start;

  /* Index the current writing position (end of the buffer plus one). */
  int buffer_end;

  /* Ring buffer used to lookup the last token. */
  char buffer[JSPARSER_RING_BUFFER_SIZE];

} jsparser_ctx;

void jsparser_reset(jsparser_ctx *ctx);
jsparser_ctx *jsparser_new(void);

/* Returns a pointer to a context which is a duplicate of the jsparser src.
 */
jsparser_ctx *jsparser_duplicate(jsparser_ctx *src);

/* Copies the context of the jsparser pointed to by src to the jsparser dst.
 */
void jsparser_copy(jsparser_ctx *dst, jsparser_ctx *src);
int jsparser_state(jsparser_ctx *ctx);
int jsparser_parse(jsparser_ctx *ctx, const char *str, int size);

void jsparser_delete(jsparser_ctx *ctx);

/**
 * Ring buffer functions.
 *
 * These functions are only exported for testing and should not be called from
 * outside of jsparser.c in production code.
 */

/* Appends a character to the ring buffer.
 *
 * Sequences of whitespaces and newlines are folded into one character.
 */
void jsparser_buffer_append_chr(jsparser_ctx *js, char chr);

/* Appends a string to the ring buffer.
 *
 * Sequences of whitespaces and newlines are folded into one character.
 */
void jsparser_buffer_append_str(jsparser_ctx *js, const char *str);

/* Returns the last appended character and removes it from the buffer. If the
 * buffer is empty, then it returns ASCII 0 ('\0').
 */
char jsparser_buffer_pop(jsparser_ctx *js);

/* Returns the value of the character at a certain index in the buffer or an
 * ASCII 0 ('\0') character if the index is extends beyond the size of the
 * buffer, either because we don't have as many characters in the buffer, or
 * because the index points to a place bigger than the size of the buffer..
 *
 * Index positions must be negative, where -1 is the last character appended to
 * the buffer.
 */
char jsparser_buffer_get(jsparser_ctx *js, int pos);

/* Sets the value of the character at a certain index in the buffer. Returns
 * true if the write was successful or false if there was an attempt to write
 * outside of the buffer boundaries.
 *
 * Index positions are negative, were -1 is the last character appended to the
 * buffer. Using positive integers for the index will result in undefined
 * behaviour.
 */
int jsparser_buffer_set(jsparser_ctx *js, int pos, char value);

/* Copies a slice of the buffer to the string pointed to by output. start and
 * end are the indexes of the sliced region. If the start argument extends
 * beyond the beginning of the buffer, the slice will only contain characters
 * starting from beginning of the buffer.
 */
void jsparser_buffer_slice(jsparser_ctx *js, char *buffer, int start, int end);

/* Copy the last javascript identifier or keyword found in the buffer to the
 * string pointed by identifier.
 */
int jsparser_buffer_last_identifier(jsparser_ctx *js, char *identifier);

#define jsparser_parse_chr(a,b) jsparser_parse(a, &(b), 1);
#ifdef __cplusplus
#define jsparser_parse_str(a,b) jsparser_parse(a, b, \
                                               static_cast<int>(strlen(b)));
#else
#define jsparser_parse_str(a,b) jsparser_parse(a, b, (int)strlen(b));
#endif

#ifdef __cplusplus
}  /* namespace security_streamhtmlparser */
#endif /* __cplusplus */

#endif /* SECURITY_STREAMHTMLPARSER_JSPARSER_H */


text:
Red Colony
=============

Red Colony ([play now](http://theplasm.github.com/red-colony))

Controls:
---------

* WASD Motion
* Mouse camera rotation
* Left Click shooting
* 1 & 2: Orange and Blue
* 3: Place a voxel
* 4: Restore voxel
* 5: Destroy voxel
* R: Reset

Credits:
--------

Made by Rasmus Jepsen, with three.js and pointer lock API.


text:
title: "Brainbench CSS3"
date: "2012-08-21T00:12:12+03:00"
published: true
tags: [brainbench, css, тест]
---

В данный момент [Brainbench](http://www.brainbench.com) предлагает бесплатный тест по CSS3. И все неравнодушные
к Web-программированию могут его пройти, он не очень сложный. Когда проходил тест, у меня почему-то не грузились их
картинки, поэтому многие вопросы я угадывал интуитивно, не видя полного условия.

![Скриншот с неправильным тестом](/images/screenshots/broken-brainbench.png)

Может, это с моим браузером что-то случилось, но в любом случае было неприятно, и я уже написал им в поддержку гневное
письмо. Правда, всё это не помешало мне набрать 4.23 и получить CSS3 Master. Думаю, что закажу себе еще один сертификат
(за казенные деньги, ага) в дополнение к PHP 5.3, JavaScript 1.5 и CSS2. Будут висеть на стене и радовать глаз.


text:
package users

import (
    "net/http"
    "github.com/upwork/golang-upwork-oauth2/api"
)

const (
    EntryPoint = "api"
)

type a struct {
    client *api.ApiClient
}

// Constructor
func New(c *api.ApiClient) *a {
    c.SetEntryPoint(EntryPoint)

    return &a{c}
}

// Get Auth User Info
func (r a) GetMyInfo() (*http.Response, interface{}) {
    return r.client.Get("/hr/v2/users/me", nil)
}

// Get Specific User Info
func (r a) GetSpecific(userReference string) (*http.Response, interface{}) {
    return r.client.Get("/hr/v2/users/" + userReference, nil)
}


text:
import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
import moment from 'moment-timezone';

// Source: https://medium.com/@markuretsky/extend-angular-datepipe-for-timezone-abbreviations-support-9b65fa0807fb

@Pipe({
	name: 'momentDate'
})
export class MomentDatePipe extends DatePipe implements PipeTransform {
	// For some reason, TS doesn't allow this implementation unless you explicitly specify the overloads
	transform(value: null, format: string, timezone: string): null;
	transform(value: moment.MomentInput, format: string, timezone: string): string | null;
	transform(value: moment.MomentInput, format: string, timezone: string) {
		const momentObj = moment(value).tz(timezone);
		return super.transform(momentObj.toDate(), format, momentObj.format('Z'));
	}
}


text:
@implementation WPSPSegmentationDSLParser

+ (instancetype)defaultParser {
    static dispatch_once_t onceToken;
    static WPSPSegmentationDSLParser *rtn = nil;
    static WPSPDefaultValueNodeParser *defaultValueNodeParser = nil;
    static WPSPDefaultCriterionNodeParser *defaultCriterionNodeParser = nil;
    dispatch_once(&onceToken, ^{
        defaultValueNodeParser = [WPSPDefaultValueNodeParser new];
        defaultCriterionNodeParser = [WPSPDefaultCriterionNodeParser new];
        WPSPParserConfig *parserConfig = [[WPSPParserConfig alloc]
                                          initWithValueParser:VALUE_NODE_PARSER_BLOCK { return [defaultValueNodeParser parseValueWithContext:context key:key input:input]; }
                                          criterionParser:CRITERION_NODE_PARSER_BLOCK { return [defaultCriterionNodeParser parseCriterionWithContext:context key:key input:input]; }
                                          throwOnUnknownCriterion:NO
                                          throwOnUnknownValue:NO];
        rtn = [[WPSPSegmentationDSLParser alloc] initWithParserConfig:parserConfig];
    });
    return rtn;
}

+ (instancetype)defaultThrowingParser {
    static dispatch_once_t onceToken;
    static WPSPSegmentationDSLParser *rtn = nil;
    static WPSPDefaultValueNodeParser *defaultValueNodeParser = nil;
    static WPSPDefaultCriterionNodeParser *defaultCriterionNodeParser = nil;
    dispatch_once(&onceToken, ^{
        defaultValueNodeParser = [WPSPDefaultValueNodeParser new];
        defaultCriterionNodeParser = [WPSPDefaultCriterionNodeParser new];
        WPSPParserConfig *parserConfig = [[WPSPParserConfig alloc]
                                          initWithValueParser:VALUE_NODE_PARSER_BLOCK { return [defaultValueNodeParser parseValueWithContext:context key:key input:input]; }
                                          criterionParser:CRITERION_NODE_PARSER_BLOCK { return [defaultCriterionNodeParser parseCriterionWithContext:context key:key input:input]; }
                                          throwOnUnknownCriterion:YES
                                          throwOnUnknownValue:YES];
        rtn = [[WPSPSegmentationDSLParser alloc] initWithParserConfig:parserConfig];
    });
    return rtn;
}

- (instancetype)initWithParserConfig:(WPSPParserConfig *)parserConfig {
    if (self = [super init]) {
        _parserConfig = parserConfig;
    }
    return self;
}

- (WPSPASTCriterionNode *)parse:(NSDictionary *)input dataSource:(WPSPDataSource *)dataSource {
    WPSPParsingContext *ctx = [[WPSPParsingContext alloc] initWithParser:self parentContext:nil dataSource:dataSource];
    return [self parseCriterionWithContext:ctx input:input];
}

- (WPSPASTCriterionNode *)parseCriterionWithContext:(WPSPParsingContext *)context input:(NSDictionary *)input {
    if (!input || ![input isKindOfClass:NSDictionary.class]) {
        @throw [WPSPBadInputException new]; // Expects an object
    }
    if (input.count == 0) {
        if (context.dataSource.rootDataSource != context.dataSource) {
            @throw [WPSPBadInputException new]; // Missing data criterion
        }
        return [[WPSPMatchAllCriterionNode alloc] initWithContext:context];
    }
    if (input.count > 1) {
        NSMutableArray<WPSPASTCriterionNode *> *children = [NSMutableArray new];
        for (NSString *key in input.allKeys) {
            [children addObject:[self parseCriterionWithContext:context input:@{
                key: input[key]
            }]];
        }
        return [[WPSPAndCriterionNode alloc] initWithContext:context children:[NSArray arrayWithArray:children]];
    }
    NSString * _Nonnull inputKey = input.allKeys.firstObject;
    if (inputKey.length == 0) {
        @throw [WPSPBadInputException new]; // Bad key ""
    }

    id inputValue = input[inputKey];
    WPSPASTCriterionNode *parsed = self.parserConfig.criterionParser(context, inputKey, inputValue);
    if (!parsed) {
        parsed = [[WPSPASTUnknownCriterionNode alloc] initWithContext:context key:inputKey value:inputValue];
        if (self.parserConfig.throwOnUnknownCriterion) {
            @throw [WPSPUnknownCriterionException new];
        }
    }

    return parsed;
}

- (WPSPASTValueNode *)parseValueWithContext:(WPSPParsingContext *)context input:(id)input {
    if (!input || [NSNull.null isEqual:input]) {
        return [[WPSPNullValueNode alloc] initWithContext:context value:NSNull.null];
    }
    if ([WPJsonUtil isBoolNumber:input]) {
        return [[WPSPBooleanValueNode alloc] initWithContext:context value:input];
    }
    if ([input isKindOfClass:NSNumber.class]) {
        return [[WPSPNumberValueNode alloc] initWithContext:context value:input];
    }
    if ([input isKindOfClass:NSString.class]) {
        return [[WPSPStringValueNode alloc] initWithContext:context value:input];
    }
    if ([input isKindOfClass:NSArray.class]) {
        @throw [WPSPBadInputException new]; // array values are not accepted
    }
    if (![input isKindOfClass:NSDictionary.class]) {
        @throw [WPSPBadInputException new]; // NSStringFromClass(input.class) is not accepted
    }

    NSDictionary *inputDictionary = input;
    if (inputDictionary.count != 1) {
        @throw [WPSPBadInputException new]; // object values can only have 1 key defining their type
    }
    NSString *inputKey = inputDictionary.allKeys.firstObject;
    if (inputKey.length == 0) {
        @throw [WPSPBadInputException new]; // bad key ""
    }
    id inputValue = inputDictionary[inputKey];
    WPSPASTValueNode *parsed = self.parserConfig.valueParser(context, inputKey, inputValue);
    if (!parsed) {
        parsed = [[WPSPASTUnknownValueNode alloc] initWithContext:context key:inputKey value:inputValue];
        if (self.parserConfig.throwOnUnknownValue) {
            @throw [WPSPUnknownValueException new];
        }
    }
    return parsed;
}

@end


text:
package main

import (
	"fmt"
	"os"

	. "github.com/logrusorgru/aurora"
)

type Cleaner struct {
	outputer IOutputer
	os       OS
}

func NewCleaner(outputer IOutputer, os OS) Cleaner {
	return Cleaner{
		outputer: outputer,
		os:       os,
	}
}

func (c *Cleaner) CleanDeadSymlinks(dirPath string) error {
	dir, err := c.os.Open(dirPath)
	if err != nil {
		return err
	}

	defer func() {
		dirCloseErr := dir.Close()
		if err == nil {
			err = dirCloseErr
		}
	}()

	dirInfo, err := dir.Stat()
	if err != nil {
		return err
	}

	if !dirInfo.IsDir() {
		return fmt.Errorf("Specified dirPath %s is not a directory", dirPath)
	}

	files, err := dir.Readdir(0)
	if err != nil {
		return err
	}

	return c.cleanFiles(dirPath, files)
}

// Checks each file, if it is a bad symlink - removes it.
func (c *Cleaner) cleanFiles(dirPath string, files []os.FileInfo) error {
	removedAny := false
	for _, fileInfo := range files {
		if fileInfo.Mode()&os.ModeSymlink != os.ModeSymlink {
			continue
		}

		filepath := dirPath + "/" + fileInfo.Name()
		_, err := c.os.Stat(filepath)
		if err == nil {
			// symlink is correct
			continue
		}

		if !os.IsNotExist(err) {
			return err
		}

		// file not exists => bad symlink, remove it

		if err := c.os.Remove(filepath); err != nil {
			return err
		}

		if !removedAny {
			removedAny = true
			c.outputer.OutInfo("Cleaning dead symlinks...")
		}

		c.outputer.OutInfo("  %s %s has been removed (broken symlink)", Green("✓"), Brown(filepath))
	}

	return nil
}


text:
from nca47.db import api as db_api
from nca47.db.sqlalchemy.models import GslbZoneInfo
from nca47.objects import base
from nca47.objects import fields as object_fields
from nca47.common.exception import HaveSameObject
from nca47.common.exception import IsNotExistError

class GslbZone(base.Nca47Object):
    VERSION = '1.0'
    fields = {
        'name': object_fields.StringField(),
        'devices': object_fields.ListOfStringsField(),
        'syn_server': object_fields.StringField(),
        'enable': object_fields.StringField(),
        'gslb_zone_id': object_fields.StringField(),
        'tenant_id': object_fields.StringField()
    }

    def __init__(self, context=None, **kwarg):
        self.db_api = db_api.get_instance()
        super(GslbZone, self).__init__(context=None, **kwarg)

    @staticmethod
    def _from_db_object(dns_gslb_zone, db_dns_gslb_zone):
        """Converts a database entity to a formal :class:`GslbZone` object.

        :param dns_zone: An object of :class:`GslbZone`.
        :param db_dns_zone: A DB model of a GslbZone.
        :return: a :class:`GslbZone` object.
        """
        for field in dns_gslb_zone.fields:
            dns_gslb_zone[field] = db_dns_gslb_zone[field]

        dns_gslb_zone.obj_reset_changes()
        return dns_gslb_zone

    def create(self, context, values):
        value = {}
        value["name"] = values["name"]
        value["tenant_id"] = values["tenant_id"]
        obj_old = self.get_objects(context, **value)
        if len(obj_old) != 0:
            raise HaveSameObject(param_name=value["name"])
        zone = self.db_api.create(GslbZoneInfo, values)
        return zone

    def update(self, context, zone_id, values):
        value = {}
        value["id"] = zone_id
        obj_old = self.get_objects(context, **value)
        if len(obj_old) == 0:
            raise IsNotExistError(param_name=zone_id)
        record = self.db_api.update_object(GslbZoneInfo, zone_id, values)
        return record

    def delete(self, context, zone_id):
        value = {}
        value["id"] = zone_id
        obj_old = self.get_objects(context, **value)
        if len(obj_old) == 0:
            raise IsNotExistError(param_name=value["id"])
        record = self.db_api.delete_object(GslbZoneInfo, zone_id)
        return record

    def get_objects(self, context, **values):
        values["deleted"] = False
        record = self.db_api.get_objects(GslbZoneInfo, **values)
        return record

    def get_object(self, context, **values):
        values["deleted"] = False
        try:
            record = self.db_api.get_object(GslbZoneInfo, **values)
        except Exception:
            raise IsNotExistError(param_name=values["id"])
        return record

    def get_object_one(self, context, **values):
        # get one information of gslb_zone
        record = self.db_api.get_object(GslbZoneInfo, **values)
        return record


text:
<?php

require_once __DIR__.'/../autoload.php';
require_once __DIR__.'/../AppKernel.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('dev', true);
$kernel->loadClassCache();
$request = Request::createFromGlobals();
$response = $kernel->handle($request);
$response->send();
$kernel->terminate($request, $response);


text:
namespace imagefilter {

// Helper functions for pointer indexing.
template <class T>
T* PtrOffset(T* t, int offset) {
  return reinterpret_cast<T*>(reinterpret_cast<uchar*>(t) + offset);
}

template <class T>
const T* PtrOffset(const T* t, int offset) {
  return reinterpret_cast<const T*>(reinterpret_cast<const uchar*>(t) + offset);
}

// Dimension checks
inline bool HasSameDimensions(const cv::Mat& img_1, const cv::Mat& img_2) {
  return (img_1.cols == img_2.cols && img_1.rows == img_2.rows);
}

inline cv::Point trunc(const cv::Point2f& pt) {
  return cv::Point((int)pt.x, (int)pt.y);
}

inline cv::Point2f rotate(const cv::Point2f& pt, float angle) {
  const float c = cos(angle);
  const float s = sin(angle);
  return cv::Point2f(c * pt.x - s * pt.y, s * pt.x + c * pt.y);
}

inline cv::Point2f normalize(const cv::Point2f& pt) {
  return pt * (1.0f / norm(pt));
}

inline cv::Point3f homogPt(const cv::Point2f& pt) {
  return cv::Point3f(pt.x, pt.y, 1.0f);
}

inline cv::Point2f homogPt(const cv::Point3f& pt) {
  if (pt.z != 0) {
    return cv::Point2f(pt.x / pt.z, pt.y / pt.z);
  } else {
    return cv::Point2f(0, 0);
  }
}

template <class T>
inline T clamp(const T& value, const T& a, const T& b) {
  return std::max<T>(a, std::min<T>(value, b));
}

}  // namespace imagefilter.

#endif  // VIDEO_SEGMENT_IMAGEFILTER_IMAGE_UTIL_H__


text:
<!doctype html>

	<meta charset="utf-8">
	<title>jQuery UI mouse documentation</title>

QuickNav

Options

cancel

delay

distance

Methods

_mouseInit

_mouseDestroy

_mouseDown

_mouseMove

_mouseUp

_mouseDistanceMet

_mouseDelayMet

_mouseStart

_mouseDrag

_mouseStop

_mouseCapture

Events

Mouse Interaction

Description: The base interaction layer.

Options

cancelType: Selector

Default: "input,textarea,button,select,option"

Prevents interactions from starting on specified elements.

delayType: Number

Default: 0

Time in milliseconds after mousedown until the interaction should start. This option can be used to prevent unwanted interactions when clicking on an element.

distanceType: Number

Default: 1

Distance in pixels after mousedown the mouse must move before the interaction should start. This option can be used to prevent unwanted interactions when clicking on an element.

Methods

_mouseCapture() Returns: Boolean

				Determines whether an interaction should start based on event target of the interaction. The default implementation always returns true.

_mouseDelayMet() Returns: Boolean

				Determines whether the delay option has been met for the current interaction.

_mouseDestroy()

				Destroys the interaction event handlers. This must be called from the extending widget's _destroy() method.

_mouseDistanceMet() Returns: Boolean

				Determines whether the distance option has been met for the current interaction.

_mouseDown()

				Handles the beginning of an interaction. Verifies that the event is associated with the primary mouse button and ensures that the delay and distance options are met prior to starting the interaction. When the interaction is ready to start, invokes the _mouseStart() method for the extending widget to handle.

_mouseDrag()

				The extending widget should implement a _mouseDrag() method to handle each movement of an interaction. This method will receive the mouse event associated with the movement.

_mouseInit()

				Initializes the interaction event handlers. This must be called from the extending widget's _create() method.

_mouseMove()

				Handles each movement of the interaction. Invokes the mouseDrag() method for the extending widget to handle.

_mouseStart()

				The extending widget should implement a _mouseStart() method to handle the beginning of an interaction. This method will receive the mouse event associated with the start of the interaction.

_mouseStop()

				The extending widget should implement a _mouseStop() method to handle the end of an interaction. This method will receive the mouse event associated with the end of the interaction.

_mouseUp()

				Handles the end of the interaction. Invokes the mouseStop() method for the extending widget to handle.

Similar to jQuery.Widget, the mouse interaction is not intended to be used directly. It is purely a base layer for other widgets to inherit from. This page only documents what is added to jQuery.Widget, but it does include internal methods that are not intended to be overwritten. The intended public API is _mouseStart(), _mouseDrag(), _mouseStop(), and _mouseCapture().


text:
<?php
/**
 * NativeAd
 *
 * PHP version 5
 *
 * @category Class
 * @package  CollingMedia\StackAdapt
 * @author   http://github.com/swagger-api/swagger-codegen
 * @license  http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link     https://github.com/swagger-api/swagger-codegen
 */

/**
 * StackAdapt API
 *
 * Use this API to create Native Ads and Campaigns on the StackAdapt Platform Use this API to create Native Ads and Campaigns on the StackAdapt Platform
 *
 * OpenAPI spec version: 2.0.0
 *
 * Generated by: https://github.com/swagger-api/swagger-codegen.git
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * NOTE: This class is auto generated by the swagger code generator program.
 * https://github.com/swagger-api/swagger-codegen
 * Do not edit the class manually.
 */

namespace CollingMedia\StackAdapt\Model;

use \ArrayAccess;

/**
 * NativeAd Class Doc Comment
 *
 * @category    Class */
/**
 * @package     CollingMedia\StackAdapt
 * @author      http://github.com/swagger-api/swagger-codegen
 * @license     http://www.apache.org/licenses/LICENSE-2.0 Apache Licene v2
 * @link        https://github.com/swagger-api/swagger-codegen
 */
class NativeAd implements ArrayAccess
{
    /**
      * The original name of the model.
      * @var string
      */
    protected static $swaggerModelName = 'NativeAd';

    /**
      * Array of property to type mappings. Used for (de)serialization
      * @var string[]
      */
    protected static $swaggerTypes = array(
        'id' => 'int',
        'click_url' => 'string',
        'input_data' => '\CollingMedia\StackAdapt\Model\InputData',
        'audit_status' => 'string',
        'name' => 'string',
        'state' => 'string',
        'imp_tracker_urls' => 'string[]',
        'brandname' => 'string'
    );

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

    /**
     * Array of attributes where the key is the local name, and the value is the original name
     * @var string[]
     */
    protected static $attributeMap = array(
        'id' => 'id',
        'click_url' => 'click_url',
        'input_data' => 'input_data',
        'audit_status' => 'audit_status',
        'name' => 'name',
        'state' => 'state',
        'imp_tracker_urls' => 'imp_tracker_urls',
        'brandname' => 'brandname'
    );

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

    /**
     * Array of attributes to setter functions (for deserialization of responses)
     * @var string[]
     */
    protected static $setters = array(
        'id' => 'setId',
        'click_url' => 'setClickUrl',
        'input_data' => 'setInputData',
        'audit_status' => 'setAuditStatus',
        'name' => 'setName',
        'state' => 'setState',
        'imp_tracker_urls' => 'setImpTrackerUrls',
        'brandname' => 'setBrandname'
    );

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

    /**
     * Array of attributes to getter functions (for serialization of requests)
     * @var string[]
     */
    protected static $getters = array(
        'id' => 'getId',
        'click_url' => 'getClickUrl',
        'input_data' => 'getInputData',
        'audit_status' => 'getAuditStatus',
        'name' => 'getName',
        'state' => 'getState',
        'imp_tracker_urls' => 'getImpTrackerUrls',
        'brandname' => 'getBrandname'
    );

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

    const AUDIT_STATUS_PENDING = 'pending';
    const AUDIT_STATUS_PASSED = 'passed';
    const AUDIT_STATUS_FAILED = 'failed';
    const STATE_ACTIVE = 'active';
    const STATE_PAUSED = 'paused';

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public function getAuditStatusAllowableValues()
    {
        return [
            self::AUDIT_STATUS_PENDING,
            self::AUDIT_STATUS_PASSED,
            self::AUDIT_STATUS_FAILED,
        ];
    }

    /**
     * Gets allowable values of the enum
     * @return string[]
     */
    public function getStateAllowableValues()
    {
        return [
            self::STATE_ACTIVE,
            self::STATE_PAUSED,
        ];
    }

    /**
     * Associative array for storing property values
     * @var mixed[]
     */
    protected $container = array();

    /**
     * Constructor
     * @param mixed[] $data Associated array of property value initalizing the model
     */
    public function __construct(array $data = null)
    {
        $this->container['id'] = isset($data['id']) ? $data['id'] : 22;
        $this->container['click_url'] = isset($data['click_url']) ? $data['click_url'] : 'www.stackadapt.com';
        $this->container['input_data'] = isset($data['input_data']) ? $data['input_data'] : null;
        $this->container['audit_status'] = isset($data['audit_status']) ? $data['audit_status'] : 'pending';
        $this->container['name'] = isset($data['name']) ? $data['name'] : 'API New Native Ad';
        $this->container['state'] = isset($data['state']) ? $data['state'] : 'active';
        $this->container['imp_tracker_urls'] = isset($data['imp_tracker_urls']) ? $data['imp_tracker_urls'] : null;
        $this->container['brandname'] = isset($data['brandname']) ? $data['brandname'] : 'My Brand';

        // Initialize discriminator property with the model name.
        $discrimintor = array_search('native_ad', self::$attributeMap);
        $this->container[$discrimintor] = static::$swaggerModelName;
    }

    /**
     * show all the invalid properties with reasons.
     *
     * @return array invalid properties with reasons
     */
    public function listInvalidProperties()
    {
        $invalid_properties = array();
        if ($this->container['id'] === null) {
            $invalid_properties[] = "'id' can't be null";
        }
        if ($this->container['click_url'] === null) {
            $invalid_properties[] = "'click_url' can't be null";
        }
        if ($this->container['input_data'] === null) {
            $invalid_properties[] = "'input_data' can't be null";
        }
        $allowed_values = array("pending", "passed", "failed");
        if (!in_array($this->container['audit_status'], $allowed_values)) {
            $invalid_properties[] = "invalid value for 'audit_status', must be one of #{allowed_values}.";
        }

        if ($this->container['name'] === null) {
            $invalid_properties[] = "'name' can't be null";
        }
        $allowed_values = array("active", "paused");
        if (!in_array($this->container['state'], $allowed_values)) {
            $invalid_properties[] = "invalid value for 'state', must be one of #{allowed_values}.";
        }

        if ($this->container['brandname'] === null) {
            $invalid_properties[] = "'brandname' can't be null";
        }
        return $invalid_properties;
    }

    /**
     * validate all the properties in the model
     * return true if all passed
     *
     * @return bool True if all properteis are valid
     */
    public function valid()
    {
        if ($this->container['id'] === null) {
            return false;
        }
        if ($this->container['click_url'] === null) {
            return false;
        }
        if ($this->container['input_data'] === null) {
            return false;
        }
        $allowed_values = array("pending", "passed", "failed");
        if (!in_array($this->container['audit_status'], $allowed_values)) {
            return false;
        }
        if ($this->container['name'] === null) {
            return false;
        }
        $allowed_values = array("active", "paused");
        if (!in_array($this->container['state'], $allowed_values)) {
            return false;
        }
        if ($this->container['brandname'] === null) {
            return false;
        }
        return true;
    }

    /**
     * Gets id
     * @return int
     */
    public function getId()
    {
        return $this->container['id'];
    }

    /**
     * Sets id
     * @param int $id The ID of the native ad.
     * @return $this
     */
    public function setId($id)
    {
        $this->container['id'] = $id;

        return $this;
    }

    /**
     * Gets click_url
     * @return string
     */
    public function getClickUrl()
    {
        return $this->container['click_url'];
    }

    /**
     * Sets click_url
     * @param string $click_url The click URL of the native ad. Not used for App Install Campaigns, where the click url is on the campaign object.
     * @return $this
     */
    public function setClickUrl($click_url)
    {
        $this->container['click_url'] = $click_url;

        return $this;
    }

    /**
     * Gets input_data
     * @return \CollingMedia\StackAdapt\Model\InputData
     */
    public function getInputData()
    {
        return $this->container['input_data'];
    }

    /**
     * Sets input_data
     * @param \CollingMedia\StackAdapt\Model\InputData $input_data
     * @return $this
     */
    public function setInputData($input_data)
    {
        $this->container['input_data'] = $input_data;

        return $this;
    }

    /**
     * Gets audit_status
     * @return string
     */
    public function getAuditStatus()
    {
        return $this->container['audit_status'];
    }

    /**
     * Sets audit_status
     * @param string $audit_status The audit status of the audit.
     * @return $this
     */
    public function setAuditStatus($audit_status)
    {
        $allowed_values = array('pending', 'passed', 'failed');
        if (!in_array($audit_status, $allowed_values)) {
            throw new \InvalidArgumentException("Invalid value for 'audit_status', must be one of 'pending', 'passed', 'failed'");
        }
        $this->container['audit_status'] = $audit_status;

        return $this;
    }

    /**
     * Gets name
     * @return string
     */
    public function getName()
    {
        return $this->container['name'];
    }

    /**
     * Sets name
     * @param string $name The name of the native ad
     * @return $this
     */
    public function setName($name)
    {
        $this->container['name'] = $name;

        return $this;
    }

    /**
     * Gets state
     * @return string
     */
    public function getState()
    {
        return $this->container['state'];
    }

    /**
     * Sets state
     * @param string $state The state of the campaign.
     * @return $this
     */
    public function setState($state)
    {
        $allowed_values = array('active', 'paused');
        if (!in_array($state, $allowed_values)) {
            throw new \InvalidArgumentException("Invalid value for 'state', must be one of 'active', 'paused'");
        }
        $this->container['state'] = $state;

        return $this;
    }

    /**
     * Gets imp_tracker_urls
     * @return string[]
     */
    public function getImpTrackerUrls()
    {
        return $this->container['imp_tracker_urls'];
    }

    /**
     * Sets imp_tracker_urls
     * @param string[] $imp_tracker_urls List of URLs for impression tracking.
     * @return $this
     */
    public function setImpTrackerUrls($imp_tracker_urls)
    {
        $this->container['imp_tracker_urls'] = $imp_tracker_urls;

        return $this;
    }

    /**
     * Gets brandname
     * @return string
     */
    public function getBrandname()
    {
        return $this->container['brandname'];
    }

    /**
     * Sets brandname
     * @param string $brandname Brand name associated with the creative.
     * @return $this
     */
    public function setBrandname($brandname)
    {
        $this->container['brandname'] = $brandname;

        return $this;
    }
    /**
     * Returns true if offset exists. False otherwise.
     * @param  integer $offset Offset
     * @return boolean
     */
    public function offsetExists($offset)
    {
        return isset($this->container[$offset]);
    }

    /**
     * Gets offset.
     * @param  integer $offset Offset
     * @return mixed
     */
    public function offsetGet($offset)
    {
        return isset($this->container[$offset]) ? $this->container[$offset] : null;
    }

    /**
     * Sets value based on offset.
     * @param  integer $offset Offset
     * @param  mixed   $value  Value to be set
     * @return void
     */
    public function offsetSet($offset, $value)
    {
        if (is_null($offset)) {
            $this->container[] = $value;
        } else {
            $this->container[$offset] = $value;
        }
    }

    /**
     * Unsets offset.
     * @param  integer $offset Offset
     * @return void
     */
    public function offsetUnset($offset)
    {
        unset($this->container[$offset]);
    }

    /**
     * Gets the string presentation of the object
     * @return string
     */
    public function __toString()
    {
        if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
            return json_encode(\CollingMedia\StackAdapt\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT);
        }

        return json_encode(\CollingMedia\StackAdapt\ObjectSerializer::sanitizeForSerialization($this));
    }
}


text:
require File.dirname(__FILE__) + '/../../spec_helper'

describe Prawn::SVG::Color do
  describe "::css_color_to_prawn_color" do
    it "converts #xxx to a hex value" do
      Prawn::SVG::Color.css_color_to_prawn_color("#9ab").should == "99aabb"
    end

    it "converts #xxxxxx to a hex value" do
      Prawn::SVG::Color.css_color_to_prawn_color("#9ab123").should == "9ab123"
    end

    it "converts an html colour name to a hex value" do
      Prawn::SVG::Color.css_color_to_prawn_color("White").should == "ffffff"
    end

    it "converts an rgb string to a hex value" do
      Prawn::SVG::Color.css_color_to_prawn_color("rgb(16, 32, 48)").should == "102030"
      Prawn::SVG::Color.css_color_to_prawn_color("rgb(-5, 50%, 120%)").should == "007fff"
    end

    it "converts a CMYK string to an array of numbers" do
      expect(Prawn::SVG::Color.css_color_to_prawn_color("device-cmyk(0, 0.32, 0.48, 1)")).to eq [0, 32, 48, 100]
      expect(Prawn::SVG::Color.css_color_to_prawn_color("device-cmyk(-5, 50%, 120%, -5%)")).to eq [0, 50, 100, 0]
    end

    it "scans the string and finds the first colour it can parse" do
      Prawn::SVG::Color.css_color_to_prawn_color("function(#someurl, 0) nonexistent rgb( 3 ,4,5 ) white").should == "030405"
    end

    it "ignores url()s" do
      expect(Prawn::SVG::Color.css_color_to_prawn_color("url(#someplace) red")).to eq 'ff0000'
    end

    it "returns black if the color doesn't exist" do
      expect(Prawn::SVG::Color.css_color_to_prawn_color("blurble")).to eq '000000'
    end

    it "returns nil if there's no fallback after a url()" do
      expect(Prawn::SVG::Color.css_color_to_prawn_color("url(#someplace)")).to be nil
    end
  end

  describe "::parse" do
    let(:gradients) { {"flan" => flan_gradient, "drob" => drob_gradient} }
    let(:flan_gradient) { double }
    let(:drob_gradient) { double }

    it "returns a list of all colors parsed, ignoring impossible or non-existent colors" do
      results = Prawn::SVG::Color.parse("url(#nope) url(#flan) blurble green #123", gradients, :rgb)
      expect(results).to eq [
        flan_gradient,
        Prawn::SVG::Color::RGB.new("008000"),
        Prawn::SVG::Color::RGB.new("112233")
      ]
    end

    it "appends black to the list if there aren't any url() references" do
      results = Prawn::SVG::Color.parse("blurble green", gradients, :rgb)
      expect(results).to eq [
        Prawn::SVG::Color::RGB.new("008000"),
        Prawn::SVG::Color::RGB.new("000000")
      ]
    end

    it "works in CMYK color mode" do
      results = Prawn::SVG::Color.parse("blurble green", gradients, :cmyk)
      expect(results).to eq [
        Prawn::SVG::Color::CMYK.new([100, 0, 100, 50]),
        Prawn::SVG::Color::CMYK.new([0, 0, 0, 100])
      ]
    end
  end
end