<?xml version="1.0" encoding="UTF-8"?>
<window>
	<defaultcontrol>3</defaultcontrol>
	<include>Animation_DialogPopupOpenClose</include>
	<controls>
		<control type="group">
			<centertop>50%</centertop>
			<centerleft>50%</centerleft>
			<width>1820</width>
			<height>870</height>
			<include content="DialogBackgroundCommons">
				<param name="width" value="1820" />
				<param name="height" value="870" />
				<param name="header_label" value="$LOCALIZE[35058]" />
				<param name="header_id" value="2" />
			</include>
			<control type="group">
				<description>Controller list</description>
				<top>90</top>
				<left>30</left>
				<width>410</width>
				<height>580</height>
				<control type="label">
					<description>Controller profiles grouplist heading</description>
					<height>25</height>
					<right>20</right>
					font12
					$LOCALIZE[35050]
					<align>center</align>
					<aligny>center</aligny>
					<textcolor>button_focus</textcolor>
				</control>
				<control type="image">
					<description>Controller profiles grouplist background</description>
					<top>20</top>
					<bottom>-20</bottom>
					<left>-20</left>
					<right>0</right>
					<texture border="40">buttons/dialogbutton-nofo.png</texture>
				</control>
				<control type="grouplist" id="3">
					<description>Controller profiles grouplist</description>
					<top>40</top>
					<right>20</right>
					<onleft>9001</onleft>
					<onright>5</onright>
					<onup>3</onup>
					<ondown>3</ondown>
					<pagecontrol>62</pagecontrol>
				</control>
				<control type="scrollbar" id="62">
					<top>40</top>
					<right>0</right>
					<width>12</width>
					<orientation>vertical</orientation>
				</control>
				<control type="button" id="10">
					<description>Default controller button</description>
					<width>390</width>
					<height>60</height>
					<align>center</align>
					<aligny>center</aligny>
					font25_title
					<texturefocus colordiffuse="button_focus">lists/focus.png</texturefocus>
					<texturenofocus />
				</control>
			</control>
			<control type="gamecontroller" id="31">
				<top>130</top>
				<left>470</left>
				<width>540</width>
				<height>540</height>
			</control>

			<control type="group">
				<description>Feature list</description>
				<top>90</top>
				<left>1040</left>
				<width>410</width>
				<height>580</height>
				<control type="label">
					<description>Feature list heading</description>
					<height>25</height>
					font12
					$LOCALIZE[35059]
					<align>center</align>
					<aligny>center</aligny>
					<textcolor>button_focus</textcolor>
				</control>
				<control type="image">
					<top>20</top>
					<bottom>-20</bottom>
					<left>-20</left>
					<right>0</right>
					<texture border="40">buttons/dialogbutton-nofo.png</texture>
				</control>
				<control type="grouplist" id="5">
					<description>Features grouplist</description>
					<top>40</top>
					<right>20</right>
					<onleft>3</onleft>
					<onright>9001</onright>
					<onup>5</onup>
					<ondown>5</ondown>
					<pagecontrol>61</pagecontrol>
				</control>
				<control type="scrollbar" id="61">
					<right>0</right>
					<top>40</top>
					<width>12</width>
					<orientation>vertical</orientation>
				</control>
				<control type="button" id="7">
					<description>Default feature button</description>
					<width>390</width>
					<height>60</height>
					<left>20</left>
					<right>20</right>
					<align>center</align>
					<aligny>center</aligny>
					font27
					<texturefocus colordiffuse="button_focus">lists/focus.png</texturefocus>
					<texturenofocus />
				</control>
				<control type="label" id="8">
					<description>Feature group title</description>
					<width>390</width>
					<height>40</height>
					<align>center</align>
					<aligny>center</aligny>
					font20_title
					<textcolor>grey</textcolor>
					<shadowcolor>black</shadowcolor>
				</control>
				<control type="image" id="9">
					<description>Feature separator image</description>
					<height>3</height>
					<texture colordiffuse="AAAAAAAA" border="3">dialogs/separator-grey.png</texture>
				</control>
			</control>
			<control type="grouplist" id="9001">
				<top>110</top>
				<right>20</right>
				<width>340</width>
				<onleft>5</onleft>
				<onright>3</onright>
				<itemgap>dialogbuttons_itemgap</itemgap>
				<include content="DefaultDialogButton">
					<param name="width" value="350" />
					<param name="id" value="18" />
					<param name="label" value="$LOCALIZE[186]" />
				</include>
				<include content="DefaultDialogButton">
					<param name="width" value="350" />
					<param name="id" value="19" />
					<param name="label" value="$LOCALIZE[13007]" />
				</include>
				<include content="DefaultDialogButton">
					<param name="width" value="350" />
					<param name="id" value="20" />
					<param name="label" value="$LOCALIZE[21452]" />
				</include>
				<include content="DefaultDialogButton">
					<param name="width" value="350" />
					<param name="id" value="22" />
					<param name="label" value="$LOCALIZE[35021]" />
				</include>
				<include content="DefaultDialogButton">
					<param name="width" value="350" />
					<param name="id" value="17" />
					<param name="label" value="$LOCALIZE[10043]" />
				</include>
				<include content="DefaultDialogButton">
					<param name="width" value="350" />
					<param name="id" value="21" />
					<param name="label" value="$LOCALIZE[35019]" />
				</include>
			</control>
			<control type="group">
				<description>Bottom controller description</description>
				<bottom>30</bottom>
				<left>30</left>
				<right>30</right>
				<height>140</height>
				<control type="image">
					<description>Controller description background image</description>
					<top>-20</top>
					<bottom>-20</bottom>
					<left>-20</left>
					<right>-20</right>
					<texture border="40">buttons/dialogbutton-nofo.png</texture>
				</control>
				<control type="textbox" id="32">
					<top>5</top>
					<bottom>5</bottom>
					<left>10</left>
					<right>10</right>
					<description>Controller description</description>
					<textcolor>grey</textcolor>
				</control>
			</control>
		</control>
	</controls>
</window>


# Copyright 2018 The TensorFlow 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.
# ==============================================================================
"""Session hook for logging benchmark metric."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf  # pylint: disable=g-bad-import-order

class LoggingMetricHook(tf.estimator.LoggingTensorHook):
  """Hook to log benchmark metric information.

  This hook is very similar as tf.train.LoggingTensorHook, which logs given
  tensors every N local steps, every N seconds, or at the end. The metric
  information will be logged to given log_dir or via metric_logger in JSON
  format, which can be consumed by data analysis pipeline later.

  Note that if `at_end` is True, `tensors` should not include any tensor
  whose evaluation produces a side effect such as consuming additional inputs.
  """

  def __init__(self, tensors, metric_logger=None,
               every_n_iter=None, every_n_secs=None, at_end=False):
    """Initializer for LoggingMetricHook.

    Args:
      tensors: `dict` that maps string-valued tags to tensors/tensor names,
          or `iterable` of tensors/tensor names.
      metric_logger: instance of `BenchmarkLogger`, the benchmark logger that
          hook should use to write the log.
      every_n_iter: `int`, print the values of `tensors` once every N local
          steps taken on the current worker.
      every_n_secs: `int` or `float`, print the values of `tensors` once every N
          seconds. Exactly one of `every_n_iter` and `every_n_secs` should be
          provided.
      at_end: `bool` specifying whether to print the values of `tensors` at the
          end of the run.

    Raises:
      ValueError:
        1. `every_n_iter` is non-positive, or
        2. Exactly one of every_n_iter and every_n_secs should be provided.
        3. Exactly one of log_dir and metric_logger should be provided.
    """
    super(LoggingMetricHook, self).__init__(
        tensors=tensors,
        every_n_iter=every_n_iter,
        every_n_secs=every_n_secs,
        at_end=at_end)

    if metric_logger is None:
      raise ValueError("metric_logger should be provided.")
    self._logger = metric_logger

  def begin(self):
    super(LoggingMetricHook, self).begin()
    self._global_step_tensor = tf.compat.v1.train.get_global_step()
    if self._global_step_tensor is None:
      raise RuntimeError(
          "Global step should be created to use LoggingMetricHook.")
    if self._global_step_tensor.name not in self._current_tensors:
      self._current_tensors[self._global_step_tensor.name] = (
          self._global_step_tensor)

  def after_run(self, unused_run_context, run_values):
    # should_trigger is a internal state that populated at before_run, and it is
    # using self_timer to determine whether it should trigger.
    if self._should_trigger:
      self._log_metric(run_values.results)

    self._iter_count += 1

  def end(self, session):
    if self._log_at_end:
      values = session.run(self._current_tensors)
      self._log_metric(values)

  def _log_metric(self, tensor_values):
    self._timer.update_last_triggered_step(self._iter_count)
    global_step = tensor_values[self._global_step_tensor.name]
    # self._tag_order is populated during the init of LoggingTensorHook
    for tag in self._tag_order:
      self._logger.log_metric(tag, tensor_values[tag], global_step=global_step)


import "androguard"

rule Banker
{
	meta:
		description = "Detects a Banker"
		author = "vitorafonso"
		sample = "e5df30b41b0c50594c2b77c1d5d6916a9ce925f792c563f692426c2d50aa2524"
		report = "https://blog.fortinet.com/2016/11/01/android-banking-malware-masquerades-as-flash-player-targeting-large-banks-and-popular-social-media-apps"

	strings:
		$a1 = "kill_on"
		$a2 = "intercept_down"
		$a3 = "send_sms"
		$a4 = "check_manager_status"
		$a5 = "browserappsupdate"
		$a6 = "YnJvd3NlcmFwcHN1cGRhdGU=" // browserappsupdate
		$a7 = "browserrestart"
		$a8 = "YnJvd3NlcnJlc3RhcnQ=" // browserrestart
		$a9 = "setMobileDataEnabled"
		$a10 = "adminPhone"

	condition:
		8 of ($a*)

}

rule Acecard
{
	meta:
		description = "Detects some acecard samples"
		author = "vitorafonso"
		sample = "0973da0f5cc7e4570659174612a650f3dbd93b3545f07bcc8b438af09dc257a9"
		report = "https://securelist.com/blog/research/73777/the-evolution-of-acecard/"

	strings:
		$a = "#control_number"
		$b = "client number"
		$c = "INTERCEPTING_INCOMING_ENABLED"
		$d = "#intercept_sms_start"
		$e = "#intercept_sms_stop"
		$f = "intercepted incoming sms"

	condition:
		all of them
}

rule Acecard2
{
	meta:
		description = "Detects some acecard samples"
		author = "vitorafonso"
		sample = "88c744e563f7637e5630cb9b01cad663033ce2861cf01100f6c4e6fbb3e56df9"
		report = "https://securelist.com/blog/research/73777/the-evolution-of-acecard/"

	strings:
		$a = "Internet password"
		$b = "Security no."
		$c = "Keep your Internet Banking and secret authorisation code (SMS) secret. Don't reveal these details to anyone, not even if they claim to be NAB."
		$d = "TYPE_INSTALLED_APPS"
		$e = "TYPE_INTERCEPTED_INCOMING_SMS"
		$f = "TYPE_LISTENED_INCOMING_SMS"
		$g = "TYPE_CONTROL_NUMBER_DATA"

	condition:
		all of them and
		androguard.permission(/android.permission.RECEIVE_SMS/)
}


(set-env!
 :resource-paths #{"resources"}
 :dependencies '[[cljsjs/boot-cljsjs "0.10.5" :scope "test"]])

(require '[cljsjs.boot-cljsjs.packaging :refer :all])

;; The library doesn't use any kind of versioning scheme, so a sha is used to
;; guarantee a specific version.
(def +lib-version+ "0.1.0")
(def +version+ (str +lib-version+ "-0"))
(def sha "546cebafebd34b4b10cc47c2d6412310e6372159")

(task-options!
 pom {:project     'cljsjs/three-decalgeometry
      :version     +version+
      :description "Decal Geometry for three.js"
      :url         "https://github.com/spite/THREE.DecalGeometry"
      :scm         {:url "https://github.com/spite/THREE.DecalGeometry"}
      :license     {"MIT" "http://opensource.org/licenses/MIT"}})

(deftask package []
  (comp
   (download  :url      (str "https://raw.githubusercontent.com/spite/THREE.DecalGeometry/" sha "/src/THREE.DecalGeometry.js")
              :checksum "508d58a0ab13c95d040a32a13581d0ce")
   (sift      :move     {#"^THREE.DecalGeometry.js"
                         "cljsjs/three-decalgeometry/development/THREE.DecalGeometry.inc.js"})
   (minify    :in       "cljsjs/three-decalgeometry/development/THREE.DecalGeometry.inc.js"
              :out      "cljsjs/three-decalgeometry/production/THREE.DecalGeometry.min.inc.js")
   (sift      :include  #{#"^cljsjs"})
   (deps-cljs :name     "cljsjs.three-decalgeometry"
              :requires ["cljsjs.three"])
   (pom)
   (jar)))


version: 1
update_configs:
  - package_manager: "javascript"
    directory: "/"
    update_schedule: "daily"
    version_requirement_updates: "increase_versions"
    default_labels:
      - "category: engineering"
      - "dependencies"
    commit_message:
      prefix: "chore"
      include_scope: true
    ignored_updates:
      - match:
          # We use webdriverio only indirectly via spectron; our direct
          # dependency on the package is only for the sake of typings, so
          # we stick to the major version of webdriverio used by spectron.
          #
          # The spectron issue tracking their update to v5 is
          # https://github.com/electron-userland/spectron/issues/349
          dependency_name: "webdriverio"
          version_requirement: ">=5.0.0"
      - match:
          # axe-core updates require enough extra validation
          # on false positives and breaking ai-web, so avoiding
          # dependabot auto-update for them like other deps.
          dependency_name: "axe-core"
      - match:
          # All electron builds are going to be manually updated
          # since our release builds use a non-standard Electron build with distribution-restricted media codecs stripped out
          dependency_name: "electron"
      - match:
          # Temporarily ignoring fabric updates until fix for
          # https://github.com/OfficeDev/office-ui-fabric-react/issues/12195
          dependency_name: "office-ui-fabric-react"


/*
 * SonarQube PHP Plugin
 * Copyright (C) 2010-2020 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package org.sonar.php.parser.statement;

import org.junit.Test;
import org.sonar.php.parser.PHPLexicalGrammar;

import static org.sonar.php.utils.Assertions.assertThat;

public class DoWhileStatementTest {

  @Test
  public void test() {
    assertThat(PHPLexicalGrammar.DO_WHILE_STATEMENT)
      .matches("do ; while ($a) ;")
      .matches("do {} while ($a) ;")

      .notMatches("do {} while ($a) ")
      .notMatches("while {} do ($a) ;");
  }
}


/**
 * This file has no copyright assigned and is placed in the Public Domain.
 * This file is part of the mingw-w64 runtime package.
 * No warranty is given; refer to the file DISCLAIMER.PD within this package.
 */

#include <_mingw_unicode.h>

#ifdef _WCHAR_T_DEFINED
typedef void (__cdecl *POGOAUTOSWEEPPROCW)(const wchar_t *);
#else
typedef void (__cdecl *POGOAUTOSWEEPPROCW)(const unsigned short *);
#endif
typedef void (__cdecl *POGOAUTOSWEEPPROCA)(const char *);

#ifdef __cplusplus
extern "C"
#else
extern
#endif
POGOAUTOSWEEPPROCW PogoAutoSweepW;
#ifdef __cplusplus
extern "C"
#else
extern
#endif
POGOAUTOSWEEPPROCA PogoAutoSweepA;

#define PgoAutoSweep __MINGW_NAME_AW(PogoAutoSweep)


package com.devicehive.service;

/*
 * #%L
 * DeviceHive Java Server Common business logic
 * %%
 * Copyright (C) 2016 DataArt
 * %%
 * 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.
 * #L%
 */

import com.devicehive.configuration.Messages;
import com.devicehive.dao.PluginDao;
import com.devicehive.exceptions.HiveException;
import com.devicehive.model.enums.PluginStatus;
import com.devicehive.util.HiveValidator;
import com.devicehive.vo.PluginVO;
import org.hibernate.exception.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.NOT_FOUND;

@Component
public class PluginService {
    private static final Logger logger = LoggerFactory.getLogger(PluginService.class);

    private final HiveValidator hiveValidator;
    private final PluginDao pluginDao;

    @Autowired
    public PluginService(HiveValidator hiveValidator,
            PluginDao pluginDao) {
        this.hiveValidator = hiveValidator;
        this.pluginDao = pluginDao;
    }

    @Transactional
    public PluginVO create(PluginVO pluginVO) {
        pluginDao.persist(pluginVO);

        return pluginVO;
    }

    @Transactional
    public PluginVO update(PluginVO pluginVO) {
        return pluginDao.merge(pluginVO);
    }

    @Transactional
    public List<PluginVO> findByStatus(PluginStatus status) {
        return pluginDao.findByStatus(status);
    }

    @Transactional
    public PluginVO findByTopic(String topicName) {
        try {
            return pluginDao.findByTopic(topicName);
        } catch (Exception e) {
            return null;
        }
    }

    @Transactional
    public PluginVO findByName(String pluginName) {
        return pluginDao.findByName(pluginName);
    }

    @Transactional
    public boolean delete(long id) {
        int result = pluginDao.deleteById(id);
        return result > 0;
    }

}


<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="12.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup Label="ProjectConfigurations">
    <ProjectConfiguration Include="Debug|Win32">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|Win32">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|x64">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|x64">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|ARM">
      <Configuration>Debug</Configuration>
      <Platform>ARM</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|ARM">
      <Configuration>Release</Configuration>
      <Platform>ARM</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Debug|ARM64">
      <Configuration>Debug</Configuration>
      <Platform>ARM64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include="Release|ARM64">
      <Configuration>Release</Configuration>
      <Platform>ARM64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <ProjectGuid>{BB17323A-2460-4AE1-8AFE-B367400B934F}</ProjectGuid>
    <TemplateGuid>{1bc93793-694f-48fe-9372-81e2b05556fd}</TemplateGuid>
    <TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
    <MinimumVisualStudioVersion>12.0</MinimumVisualStudioVersion>
    <Configuration>Debug</Configuration>
    <Platform Condition="'$(Platform)' == ''">Win32</Platform>
    <RootNamespace>MyHypervisorDriver</RootNamespace>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>true</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'" Label="Configuration">
    <TargetVersion>Windows10</TargetVersion>
    <UseDebugLibraries>false</UseDebugLibraries>
    <PlatformToolset>WindowsKernelModeDriver10.0</PlatformToolset>
    <ConfigurationType>Driver</ConfigurationType>
    <DriverType>KMDF</DriverType>
    <DriverTargetPlatform>Universal</DriverTargetPlatform>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
    <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.props" />
  </ImportGroup>
  <ImportGroup Label="PropertySheets">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup />
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
    <Inf2CatUseLocalTime>true</Inf2CatUseLocalTime>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
    <Inf2CatUseLocalTime>true</Inf2CatUseLocalTime>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM64'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
  </PropertyGroup>
  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM64'">
    <DebuggerFlavor>DbgengKernelDebugger</DebuggerFlavor>
  </PropertyGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
    <ClCompile>
      <TreatWarningAsError>false</TreatWarningAsError>
    </ClCompile>
    <Link>
      <TreatLinkerWarningAsErrors>false</TreatLinkerWarningAsErrors>
      <EntryPointSymbol>DriverEntry</EntryPointSymbol>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
    <Link>
      <EntryPointSymbol>DriverEntry</EntryPointSymbol>
      <TreatLinkerWarningAsErrors>false</TreatLinkerWarningAsErrors>
    </Link>
    <ClCompile>
      <TreatWarningAsError>false</TreatWarningAsError>
    </ClCompile>
  </ItemDefinitionGroup>
  <ItemGroup>
    <Inf Include="MyHypervisorDriver.inf" />
  </ItemGroup>
  <ItemGroup>
    <FilesToPackage Include="$(TargetPath)" />
  </ItemGroup>
  <ItemGroup>
    <ClCompile Include="EPT.c" />
    <ClCompile Include="Memory.c" />
    <ClCompile Include="Driver.c" />
    <ClCompile Include="Processor.c" />
    <ClCompile Include="ProtectedMode.c" />
    <ClCompile Include="VMX.c" />
  </ItemGroup>
  <ItemGroup>
    <MASM Include="Main.asm" />
    <MASM Include="VMExitHandler.asm" />
    <MASM Include="VMXState.asm" />
  </ItemGroup>
  <ItemGroup>
    <ClInclude Include="ProtectedMode.h" />
    <ClInclude Include="VMX.h" />
    <ClInclude Include="EPT.h" />
    <ClInclude Include="MSR.h" />
    <ClInclude Include="Common.h" />
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
    <Import Project="$(VCTargetsPath)\BuildCustomizations\masm.targets" />
  </ImportGroup>
</Project>


goog.module('com.google.j2cl.transpiler.readable.intersectiontype.Setable.$LambdaAdaptor$impl');

const Setable = goog.require('com.google.j2cl.transpiler.readable.intersectiontype.Setable$impl');
const j_l_Object = goog.require('java.lang.Object$impl');
const $Util = goog.require('nativebootstrap.Util$impl');

/**
 * @implements {Setable}
 */
class $LambdaAdaptor extends j_l_Object {
  constructor(/** ?function(number):void */ fn) {
    $LambdaAdaptor.$clinit();
    super();
    /**@type {?function(number):void}*/
    this.f_fn__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$LambdaAdaptor;
    this.$ctor__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$LambdaAdaptor__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$JsFunction(
        fn);
  }

  $ctor__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$LambdaAdaptor__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$JsFunction(
      /** ?function(number):void */ fn) {
    this.$ctor__java_lang_Object__();
    this.f_fn__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$LambdaAdaptor =
        fn;
  }
  /** @override */
  m_set__int(/** number */ arg0) {
    {
      let $function =
          this.f_fn__com_google_j2cl_transpiler_readable_intersectiontype_Setable_$LambdaAdaptor;
      $function(arg0);
    }
  }

  static $clinit() {
    $LambdaAdaptor.$clinit = () => {};
    $LambdaAdaptor.$loadModules();
    j_l_Object.$clinit();
  }
  /** @return {boolean} */
  static $isInstance(/** ? */ instance) {
    return instance instanceof $LambdaAdaptor;
  }

  static $loadModules() {}
}
$Util.$setClassMetadata(
    $LambdaAdaptor,
    'com.google.j2cl.transpiler.readable.intersectiontype.Setable$$LambdaAdaptor');
Setable.$markImplementor($LambdaAdaptor);

exports = $LambdaAdaptor;
//# sourceMappingURL=Setable$$LambdaAdaptor.js.map


function submit()
  addpath('./lib');

  conf.assignmentSlug = 'logistic-regression';
  conf.itemName = 'Logistic Regression';
  conf.partArrays = { ...
    { ...
      '1', ...
      { 'sigmoid.m' }, ...
      'Sigmoid Function', ...
    }, ...
    { ...
      '2', ...
      { 'costFunction.m' }, ...
      'Logistic Regression Cost', ...
    }, ...
    { ...
      '3', ...
      { 'costFunction.m' }, ...
      'Logistic Regression Gradient', ...
    }, ...
    { ...
      '4', ...
      { 'predict.m' }, ...
      'Predict', ...
    }, ...
    { ...
      '5', ...
      { 'costFunctionReg.m' }, ...
      'Regularized Logistic Regression Cost', ...
    }, ...
    { ...
      '6', ...
      { 'costFunctionReg.m' }, ...
      'Regularized Logistic Regression Gradient', ...
    }, ...
  };
  conf.output = @output;

  submitWithConfiguration(conf);
end

function out = output(partId, auxstring)
  % Random Test Cases
  X = [ones(20,1) (exp(1) * sin(1:1:20))' (exp(0.5) * cos(1:1:20))'];
  y = sin(X(:,1) + X(:,2)) > 0;
  if partId == '1'
    out = sprintf('%0.5f ', sigmoid(X));
  elseif partId == '2'
    out = sprintf('%0.5f ', costFunction([0.25 0.5 -0.5]', X, y));
  elseif partId == '3'
    [cost, grad] = costFunction([0.25 0.5 -0.5]', X, y);
    out = sprintf('%0.5f ', grad);
  elseif partId == '4'
    out = sprintf('%0.5f ', predict([0.25 0.5 -0.5]', X));
  elseif partId == '5'
    out = sprintf('%0.5f ', costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1));
  elseif partId == '6'
    [cost, grad] = costFunctionReg([0.25 0.5 -0.5]', X, y, 0.1);
    out = sprintf('%0.5f ', grad);
  end
end


import logging
from typing import List

from validr import Invalid, T, mark_index

from rssant_common.validator import compiler

from .raw_parser import RawFeedResult, FeedParserError
from .feed_checksum import FeedChecksum
from rssant_api.helper import shorten
from .processor import (
    story_html_to_text, story_html_clean, story_extract_attach,
    story_has_mathjax, process_story_links, normalize_url, validate_url,
)

LOG = logging.getLogger(__name__)

FeedSchema = T.dict(
    version=T.str.maxlen(200),
    title=T.str.maxlen(200),
    url=T.url,
    home_url=T.url.invalid_to_default.optional,
    icon_url=T.url.invalid_to_default.optional,
    description=T.str.maxlen(300).optional,
    dt_updated=T.datetime.object.optional,
    author_name=T.str.maxlen(100).optional,
    author_url=T.url.invalid_to_default.optional,
    author_avatar_url=T.url.invalid_to_default.optional,
)

_MAX_CONTENT_LENGTH = 300 * 1024
_MAX_SUMMARY_LENGTH = 300
_MAX_STORYS = 300

StorySchema = T.dict(
    ident=T.str.maxlen(200),
    title=T.str.maxlen(200),
    url=T.url.optional,
    content=T.str.maxlen(_MAX_CONTENT_LENGTH).optional,
    summary=T.str.maxlen(_MAX_SUMMARY_LENGTH).optional,
    has_mathjax=T.bool.optional,
    image_url=T.url.invalid_to_default.optional,
    iframe_url=T.url.invalid_to_default.optional,
    audio_url=T.url.invalid_to_default.optional,
    dt_published=T.datetime.object.optional,
    dt_updated=T.datetime.object.optional,
    author_name=T.str.maxlen(100).optional,
    author_url=T.url.invalid_to_default.optional,
    author_avatar_url=T.url.invalid_to_default.optional,
)

validate_feed = compiler.compile(FeedSchema)
validate_story = compiler.compile(StorySchema)

class FeedResult:

    __slots__ = ('_feed', '_storys', '_checksum')

    def __init__(self, feed, storys, checksum):
        self._feed = feed
        self._storys = storys
        self._checksum = checksum

    def __repr__(self):
        return '<{} url={!r} version={!r} title={!r} has {} storys>'.format(
            type(self).__name__,
            self.feed['url'],
            self.feed['version'],
            self.feed['title'],
            len(self.storys),
        )

    @property
    def feed(self) -> FeedSchema:
        return self._feed

    @property
    def storys(self) -> List[StorySchema]:
        return self._storys

    @property
    def checksum(self) -> FeedChecksum:
        return self._checksum

class FeedParser:
    def __init__(self, checksum: FeedChecksum = None, validate: bool = True):
        if checksum is None:
            checksum = FeedChecksum()
        else:
            checksum = checksum.copy()
        self._checksum = checksum
        self._validate = validate

    def _parse_feed(self, feed: dict):
        url = feed['url']
        title = story_html_to_text(feed['title'])[:200]
        if not title:
            title = url  # when title is empty after clean
        home_url = normalize_url(feed['home_url'], base_url=url)
        icon_url = normalize_url(feed['icon_url'], base_url=url)
        description = story_html_to_text(feed['description'])[:300]
        author_name = story_html_to_text(feed['author_name'])[:100]
        author_url = normalize_url(feed['author_url'], base_url=url)
        author_avatar_url = normalize_url(feed['author_avatar_url'], base_url=url)
        return dict(
            version=feed['version'],
            title=title,
            url=url,
            home_url=home_url,
            icon_url=icon_url,
            description=description,
            dt_updated=feed['dt_updated'],
            author_name=author_name,
            author_url=author_url,
            author_avatar_url=author_avatar_url,
        )

    def _process_content(self, content, link):
        # use loose=True to reserve iframe
        content = story_html_clean(content, loose=True)
        # extract video iframe, eg: bilibili.com
        attach = None
        is_short_story = content and len(content) < 2000
        if is_short_story:
            attach = story_extract_attach(content, base_url=link)
        # clean again, remove iframe from content
        content = story_html_clean(content)
        content = process_story_links(content, link)
        if len(content) > _MAX_CONTENT_LENGTH:
            msg = 'story link=%r content length=%s too large, will only save plain text'
            LOG.warning(msg, link, len(content))
            content = story_html_to_text(content)
        if len(content) > _MAX_CONTENT_LENGTH:
            msg = 'story link=%r content length=%s still too large, will truncate it'
            LOG.warning(msg, link, len(content))
            content = content[:_MAX_CONTENT_LENGTH]
        return content, attach

    def _parse_story(self, story: dict, feed_url: str):
        ident = story['ident'][:200]
        title = story_html_to_text(story['title'])[:200]
        if not title:
            title = ident  # when title is empty after clean
        url = normalize_url(story['url'] or story['ident'], base_url=feed_url)
        try:
            valid_url = validate_url(url)
        except Invalid:
            valid_url = None
        base_url = valid_url or feed_url
        image_url = normalize_url(story['image_url'], base_url=base_url)
        audio_url = normalize_url(story['audio_url'], base_url=base_url)
        author_name = story_html_to_text(story['author_name'])[:100]
        author_url = normalize_url(story['author_url'], base_url=base_url)
        author_avatar_url = normalize_url(story['author_avatar_url'], base_url=base_url)
        iframe_url = None
        content, attach = self._process_content(story['content'], link=base_url)
        if attach:
            iframe_url = attach.iframe_url
            if (not audio_url) and attach.audio_url:
                audio_url = attach.audio_url
        if story['summary']:
            summary = story_html_clean(story['summary'])
        else:
            summary = content
        summary = shorten(story_html_to_text(summary), width=_MAX_SUMMARY_LENGTH)
        has_mathjax = story_has_mathjax(content)
        return dict(
            ident=ident,
            title=title,
            url=valid_url,
            content=content,
            summary=summary,
            has_mathjax=has_mathjax,
            image_url=image_url,
            iframe_url=iframe_url,
            audio_url=audio_url,
            dt_published=story['dt_published'],
            dt_updated=story['dt_updated'],
            author_name=author_name,
            author_url=author_url,
            author_avatar_url=author_avatar_url,
        )

    def _validate_result(self, result: FeedResult) -> FeedResult:
        storys = []
        try:
            feed = validate_feed(result.feed)
            for i, s in enumerate(result.storys):
                with mark_index(i):
                    s = validate_story(s)
                    storys.append(s)
        except Invalid as ex:
            raise FeedParserError(str(ex)) from ex
        return FeedResult(feed, storys, checksum=result.checksum)

    def _check_update_storys(self, storys: list):
        update_storys = []
        for story in storys:
            ident = story['ident']
            content = story['content'] or ''
            if self._checksum.update(ident, content):
                update_storys.append(story)
        return update_storys

    @staticmethod
    def _story_sort_key(story):
        """
        1. dt_published is None
        2. dt_published is smaller
        ...
        3. dt_published is latest
        """
        dt = story['dt_published'] or story['dt_updated'] or None
        return (bool(dt), dt, story['ident'])

    def _limit_max_storys(self, storys: list) -> list:
        if len(storys) <= _MAX_STORYS:
            return storys
        storys = list(sorted(storys, key=self._story_sort_key))
        return storys[-_MAX_STORYS:]

    def parse(self, raw: RawFeedResult) -> FeedResult:
        update_storys = self._limit_max_storys(raw.storys)
        update_storys = self._check_update_storys(update_storys)
        feed = self._parse_feed(raw.feed)
        feed_url = feed['url']
        storys = []
        for story in update_storys:
            story = self._parse_story(story, feed_url=feed_url)
            storys.append(story)
        result = FeedResult(feed, storys, checksum=self._checksum)
        if self._validate:
            result = self._validate_result(result)
        return result


/*=============================================================================
    Copyright (c) 2011 Hartmut Kaiser

    Distributed under the Boost Software License, Version 1.0. (See accompanying
    file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/

#if !defined(BOOST_PHOENIX_PREPROCESSED_BIND_FUNCTION_HPP)
#define BOOST_PHOENIX_PREPROCESSED_BIND_FUNCTION_HPP

#if BOOST_PHOENIX_LIMIT <= 10
#include <boost/phoenix/bind/detail/cpp03/preprocessed/bind_function_10.hpp>
#elif BOOST_PHOENIX_LIMIT <= 20
#include <boost/phoenix/bind/detail/cpp03/preprocessed/bind_function_20.hpp>
#elif BOOST_PHOENIX_LIMIT <= 30
#include <boost/phoenix/bind/detail/cpp03/preprocessed/bind_function_30.hpp>
#elif BOOST_PHOENIX_LIMIT <= 40
#include <boost/phoenix/bind/detail/cpp03/preprocessed/bind_function_40.hpp>
#elif BOOST_PHOENIX_LIMIT <= 50
#include <boost/phoenix/bind/detail/cpp03/preprocessed/bind_function_50.hpp>
#else
#error "BOOST_PHOENIX_LIMIT out of bounds for preprocessed headers"
#endif

#endif


/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.distributedlog.exceptions;

/**
 * Exception indicates that there is an internal error at distributedlog service side.
 */
public class InternalServerException extends DLException {

    private static final long serialVersionUID = 288438028880978802L;

    public InternalServerException(String msg) {
        super(StatusCode.INTERNAL_SERVER_ERROR, msg);
    }

    public InternalServerException(Throwable t) {
        super(StatusCode.INTERNAL_SERVER_ERROR, t);
    }

    public InternalServerException(String msg, Throwable t) {
        super(StatusCode.INTERNAL_SERVER_ERROR, msg, t);
    }
}


### About
This project is a simple python3 version of [speaker-recognition](https://github.com/ppwwyyxx/speaker-recognition) and I make a little change for the convenience of command line usage.

### difference with speaker-recognition of python2
+ Neither use MFCC implementation of bob nor implement that myself. Use the [python_speech_features](https://github.com/jameslyons/python_speech_features) instead.
+ Remove the GUI and you can only use the command line to train and predict the model.
+ Replace the function and class in sklearn which will be removed in the later version.
+ Use softmax function to output the probability.
+ convert to mono if the origin audio if stereo.

### Usage
```sh
usage: speaker-recognition.py [-h] -t TASK -i INPUT -m MODEL

Speaker Recognition Command Line Tool

optional arguments:
  -h, --help            show this help message and exit
  -t TASK, --task TASK  Task to do. Either "enroll" or "predict"
  -i INPUT, --input INPUT
                        Input Files(to predict) or Directories(to enroll)
  -m MODEL, --model MODEL
                        Model file to save(in enroll) or use(in predict)

Wav files in each input directory will be labeled as the basename of the directory.
Note that wildcard inputs should be *quoted*, and they will be sent to glob module.

Examples:
    Train:
    ./speaker-recognition.py -t enroll -i "/tmp/person* ./mary" -m model.out

    Predict:
    ./speaker-recognition.py -t predict -i "./*.wav" -m model.out
```


var test = require('tap').test
var path = require('path')
var fs = require('fs')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var readInstalled = require('../')

var root = path.resolve(__dirname, 'root')
var pkg = path.resolve(root, 'pkg')
var pkgnm = path.resolve(pkg, 'node_modules')
var linkdepSrc = path.resolve(root, 'linkdep')
var linkdepLink = path.resolve(pkgnm, 'linkdep')
var devdep = path.resolve(linkdepSrc, 'node_modules', 'devdep')

function pjson (dir, data) {
  mkdirp.sync(dir)
  var d = path.resolve(dir, 'package.json')
  fs.writeFileSync(d, JSON.stringify(data))
}

test('setup', function (t) {
  rimraf.sync(root)
  pjson(pkg, {
    name: 'root',
    version: '1.2.3',
    dependencies: {
      linkdep: ''
    }
  })
  pjson(linkdepSrc, {
    name: 'linkdep',
    version: '1.2.3',
    devDependencies: {
      devdep: ''
    }
  })
  pjson(devdep, {
    name: 'devdep',
    version: '1.2.3'
  })

  mkdirp.sync(pkgnm)
  fs.symlinkSync(linkdepSrc, linkdepLink, 'dir')

  t.end()
})

test('basic', function (t) {
  readInstalled(pkg, { dev: true }, function (er, data) {
    var dd = data.dependencies.linkdep.dependencies.devdep
    t.notOk(dd.extraneous, 'linked dev dep should not be extraneous')
    t.end()
  })
})

test('cleanup', function (t) {
  rimraf.sync(root)
  t.end()
})


[flake8]
exclude = docs/*
ignore = E128
max-line-length = 119

[wheel]
universal = 1


table_create Documents TABLE_HASH_KEY ShortText
column_create Documents content COLUMN_SCALAR Text

table_create Terms TABLE_PAT_KEY|KEY_NORMALIZE ShortText --default_tokenizer TokenBigram
column_create Terms document_index COLUMN_INDEX|WITH_POSITION Documents content

load --table Documents
[
["_key", "content"],
["Groonga", "Groonga can be used with MySQL."]
]

select Documents \
  --match_columns content --query 'MySQL' \
  --output_columns '_key, snippet_html(_key)'


/** Used as references for the maximum length and index of an array. */
var MAX_ARRAY_LENGTH = 4294967295,
    MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1;

/* Built-in method references for those with the same name as other `lodash` methods. */
var nativeFloor = Math.floor,
    nativeMin = Math.min;

/**
 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
 * which invokes `iteratee` for `value` and each element of `array` to compute
 * their sort ranking. The iteratee is invoked with one argument; (value).
 *
 * @private
 * @param {Array} array The sorted array to inspect.
 * @param {*} value The value to evaluate.
 * @param {Function} iteratee The iteratee invoked per element.
 * @param {boolean} [retHighest] Specify returning the highest qualified index.
 * @returns {number} Returns the index at which `value` should be inserted into `array`.
 */
function baseSortedIndexBy(array, value, iteratee, retHighest) {
  value = iteratee(value);

  var low = 0,
      high = array ? array.length : 0,
      valIsNaN = value !== value,
      valIsNull = value === null,
      valIsUndef = value === undefined;

  while (low < high) {
    var mid = nativeFloor((low + high) / 2),
        computed = iteratee(array[mid]),
        isDef = computed !== undefined,
        isReflexive = computed === computed;

    if (valIsNaN) {
      var setLow = isReflexive || retHighest;
    } else if (valIsNull) {
      setLow = isReflexive && isDef && (retHighest || computed != null);
    } else if (valIsUndef) {
      setLow = isReflexive && (retHighest || isDef);
    } else if (computed == null) {
      setLow = false;
    } else {
      setLow = retHighest ? (computed <= value) : (computed < value);
    }
    if (setLow) {
      low = mid + 1;
    } else {
      high = mid;
    }
  }
  return nativeMin(high, MAX_ARRAY_INDEX);
}

module.exports = baseSortedIndexBy;


import { Centered } from '~/templates/global/grid';
import { cols, LIGHT_GREY } from '~/styles/vars';
import styled from 'styled-components';

const FrameContainer = styled(Centered.withComponent('div'))`
  margin-top: ${cols(2)};
  margin-bottom: ${cols(2)};
  border: 2px solid ${LIGHT_GREY};
`;

export default ({ id, height = 447 }) => (
  <FrameContainer>
    <iframe
      height={height}
      scrolling="no"
      title=""
      src={`https://codepen.io/popmotion/embed/${id}/?height=${height}&theme-id=17364&default-tab=result&embed-version=2`}
      frameBorder="no"
      allowTransparency="true"
      allowFullScreen="true"
      style={{ width: '100%' }}
    />
  </FrameContainer>
);


'\"
'\" Copyright (c) 2011-2015 Andreas Kupries
'\" Copyright (c) 2018 Donal K. Fellows
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
.TH classvariable n 0.3 TclOO "TclOO Commands"
.so man.macros
.BS
'\" Note:  do not modify the .SH NAME line immediately below!
.SH NAME
classvariable \- create link from local variable to variable in class
.SH SYNOPSIS
.nf
package require TclOO

\fBclassvariable\fR \fIvariableName\fR ?\fI...\fR?
.fi
.BE
.SH DESCRIPTION
The \fBclassvariable\fR command is available within methods. It takes a series
of one or more variable names and makes them available in the method's scope;
those variable names must not be qualified and must not refer to array
elements. The originating scope for the variables is the namespace of the
class that the method was defined by. In other words, the referenced variables
are shared between all instances of that class.
.PP
Note: This command is equivalent to the command \fBtypevariable\fR provided by
the snit package in tcllib for approximately the same purpose. If used in a
method defined directly on a class instance (e.g., through the
\fBoo::objdefine\fR \fBmethod\fR definition) this is very much like just
using:
.PP
.CS
namespace upvar [namespace current] $var $var
.CE
.PP
for each variable listed to \fBclassvariable\fR.
.SH EXAMPLE
This class counts how many instances of it have been made.
.PP
.CS
oo::class create Counted {
    initialise {
        variable count 0
    }

    variable number
    constructor {} {
        \fBclassvariable\fR count
        set number [incr count]
    }

    method report {} {
        \fBclassvariable\fR count
        puts "This is instance $number of $count"
    }
}

set a [Counted new]
set b [Counted new]
$a report
        \fI\(-> This is instance 1 of 2\fR
set c [Counted new]
$b report
        \fI\(-> This is instance 2 of 3\fR
$c report
        \fI\(-> This is instance 3 of 3\fR
.CE
.SH "SEE ALSO"
global(n), namespace(n), oo::class(n), oo::define(n), upvar(n), variable(n)
.SH KEYWORDS
class, class variable, variable
.\" Local Variables:
.\" mode: nroff
.\" fill-column: 78
.\" End:


import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Title } from "@angular/platform-browser";
@Injectable({
  providedIn: "root",
})
export class TranslateService {
  data: any = {};
  constructor(private http: HttpClient, private titleService: Title) {}

  use(lang: string): Promise<{}> {
    return new Promise<{}>((resolve, reject) => {
      const langPath = `assets/i18n/${lang || "en"}.json`;
      this.http.get<{}>(langPath).subscribe(
        (translation) => {
          this.data = Object.assign({}, translation || {});
          this.titleService.setTitle(this.data.TITLE);
          resolve(this.data);
        },
        (error) => {
          this.data = {};
          console.log("Error");
          resolve(this.data);
        }
      );
    });
  }
}


/* crypto/ui/ui_util.c -*- mode:C; c-file-style: "eay" -*- */
/* ====================================================================
 * Copyright (c) 2001-2002 The OpenSSL Project.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. 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.
 *
 * 3. All advertising materials mentioning features or use of this
 *    software must display the following acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
 *
 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
 *    endorse or promote products derived from this software without
 *    prior written permission. For written permission, please contact
 *    openssl-core@openssl.org.
 *
 * 5. Products derived from this software may not be called "OpenSSL"
 *    nor may "OpenSSL" appear in their names without prior written
 *    permission of the OpenSSL Project.
 *
 * 6. Redistributions of any form whatsoever must retain the following
 *    acknowledgment:
 *    "This product includes software developed by the OpenSSL Project
 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
 *
 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
 * EXPRESSED 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 OpenSSL PROJECT OR
 * ITS 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.
 * ====================================================================
 *
 * This product includes cryptographic software written by Eric Young
 * (eay@cryptsoft.com).  This product includes software written by Tim
 * Hudson (tjh@cryptsoft.com).
 *
 */

#include <string.h>
#include "ui_locl.h"

int UI_UTIL_read_pw_string(char *buf,int length,const char *prompt,int verify)
	{
	char buff[BUFSIZ];
	int ret;

	ret=UI_UTIL_read_pw(buf,buff,(length>BUFSIZ)?BUFSIZ:length,prompt,verify);
	OPENSSL_cleanse(buff,BUFSIZ);
	return(ret);
	}

int UI_UTIL_read_pw(char *buf,char *buff,int size,const char *prompt,int verify)
	{
	int ok = 0;
	UI *ui;

	if (size < 1)
		return -1;

	ui = UI_new();
	if (ui)
		{
		ok = UI_add_input_string(ui,prompt,0,buf,0,size-1);
		if (ok >= 0 && verify)
			ok = UI_add_verify_string(ui,prompt,0,buff,0,size-1,
				buf);
		if (ok >= 0)
			ok=UI_process(ui);
		UI_free(ui);
		}
	if (ok > 0)
		ok = 0;
	return(ok);
	}


#include <assert.h>
#include <string.h>
#include "mgpriv.h"
#include "gfa-priv.h"
#include "algo.h"
#include "kalloc.h"

void mg_cov_map(const gfa_t *g, const mg_gchains_t *gt, int32_t min_mapq, int32_t min_blen, double *c_seg, double *c_link, const char *qname)
{
	int32_t i, j;
	if (c_seg == 0 && c_link == 0) return;
	if (gt == 0 || gt->n_gc == 0) return;
	for (i = 0; i < gt->n_gc; ++i) {
		const mg_gchain_t *gc = &gt->gc[i];
		const mg128_t *last_an;
		assert(gc->cnt > 0 && gc->n_anchor > 0);
		if (gc->mapq < min_mapq || gc->blen < min_blen) continue;
		// count segment coverage
		for (j = 0; j < gc->cnt; ++j) {
			const mg_llchain_t *lc = &gt->lc[gc->off + j];
			int32_t s, e;
			s = 0, e = g->seg[lc->v>>1].len;
			if (j == 0) s = (int32_t)gt->a[lc->off].x + 1 - (int32_t)(gt->a[lc->off].y>>32&0xff);
			if (j == gc->cnt - 1) e = (int32_t)gt->a[lc->off + lc->cnt - 1].x + 1;
			if (c_seg) c_seg[lc->v>>1] += (double)(e - s) / g->seg[lc->v>>1].len;
		}
		// count link
		assert(gt->lc[gc->off].cnt > 0);
		last_an = &gt->a[gt->lc[gc->off].off + gt->lc[gc->off].cnt - 1];
		for (j = 1; j < gc->cnt; ++j) {
			const mg_llchain_t *lc0 = &gt->lc[gc->off + j - 1];
			const mg_llchain_t *lc1 = &gt->lc[gc->off + j];
			int64_t a01, a10;
			if (lc1->cnt > 0) {
				const mg128_t *curr_an = &gt->a[lc1->off];
				int32_t is_skip = (mg_seg_id(*curr_an) != mg_seg_id(*last_an));
				last_an = &gt->a[lc1->off + lc1->cnt - 1];
				if (is_skip) continue;
			}
			a01 = gfa_find_arc(g, lc0->v, lc1->v);
			a10 = gfa_find_arc(g, lc1->v^1, lc0->v^1);
			if (a01 < 0 || a10 < 0) {
				if (mg_verbose >= 2)
					fprintf(stderr, "[W] Multi/disconnected link: %c%s[%d] -> %c%s[%d] (%s, %ld, %ld). Continue anyway!\n",
							"><"[lc0->v&1], g->seg[lc0->v>>1].name, lc0->v,
							"><"[lc1->v&1], g->seg[lc1->v>>1].name, lc1->v, qname, (long)a01, (long)a10);
				continue;
			}
			assert((g->arc[a01].comp ^ g->arc[a10].comp) == 1);
			if (c_link) c_link[a01] += 1.0, c_link[a10] += 1.0;
		}
	}
}

void mg_cov_asm(const gfa_t *g, int32_t n_seq, mg_gchains_t *const *gcs, int32_t min_mapq, int32_t min_blen, double *cov_seg, double *cov_link)
{
	int32_t i, j, t, *soff, *scnt, *cnt_link;
	int64_t k;
	mg_intv_t *sintv = 0;
	void *km = 0;

	// precalculate the size of sintv[] for each segment
	KCALLOC(km, scnt, g->n_seg);
	for (t = 0; t < n_seq; ++t) {
		const mg_gchains_t *gt = gcs[t];
		if (gt == 0 || gt->n_gc == 0) continue;
		for (i = 0; i < gt->n_gc; ++i) {
			const mg_gchain_t *gc = &gt->gc[i];
			assert(gc->cnt > 0 && gc->n_anchor > 0);
			if (gc->mapq < min_mapq || gc->blen < min_blen) continue;
			for (j = 0; j < gc->cnt; ++j) {
				const mg_llchain_t *lc = &gt->lc[gc->off + j];
				++scnt[lc->v>>1];
			}
		}
	}
	KMALLOC(km, soff, g->n_seg + 1);
	for (soff[0] = 0, i = 1; i <= g->n_seg; ++i)
		soff[i] = soff[i - 1] + scnt[i - 1];
	memset(scnt, 0, 4 * g->n_seg);
	KMALLOC(km, sintv, soff[g->n_seg]);

	// fill sintv[]
	KCALLOC(km, cnt_link, g->n_arc);
	for (t = 0; t < n_seq; ++t) {
		int32_t a_off = 0;
		const mg_gchains_t *gt = gcs[t];
		if (gt == 0 || gt->n_gc == 0) continue;
		for (i = 0; i < gt->n_gc; a_off += gt->gc[i++].n_anchor) {
			const mg_gchain_t *gc = &gt->gc[i];
			if (gc->mapq < min_mapq || gc->blen < min_blen) continue;
			// count segment coverage
			for (j = 0; j < gc->cnt; ++j) {
				const mg_llchain_t *lc = &gt->lc[gc->off + j];
				int32_t s, e, tmp;
				mg_intv_t *p;
				s = 0, e = g->seg[lc->v>>1].len;
				if (j == 0) s = (int32_t)gt->a[lc->off].x + 1 - (int32_t)(gt->a[lc->off].y>>32&0xff);
				if (j == gc->cnt - 1) e = (int32_t)gt->a[lc->off + lc->cnt - 1].x + 1;
				if (lc->v&1) // convert to the forward strand of segment lc->v>>1
					tmp = g->seg[lc->v>>1].len - s, s = g->seg[lc->v>>1].len - e, e = tmp;
				p = &sintv[soff[lc->v>>1] + scnt[lc->v>>1]];
				++scnt[lc->v>>1];
				p->st = s, p->en = e, p->rev = lc->v&1, p->far = -1, p->i = -1;
			}
			// count link
			for (j = 1; j < gc->cnt; ++j) {
				const mg_llchain_t *lc0 = &gt->lc[gc->off + j - 1];
				const mg_llchain_t *lc1 = &gt->lc[gc->off + j];
				int64_t a01, a10;
				a01 = gfa_find_arc(g, lc0->v, lc1->v);
				a10 = gfa_find_arc(g, lc1->v^1, lc0->v^1);
				assert(a01 >= 0 && a10 >= 0);
				assert((g->arc[a01].comp ^ g->arc[a10].comp) == 1);
				++cnt_link[a01];
				++cnt_link[a10];
			}
		}
	}

	// update cov_link[] and cov_seg[]
	for (k = 0; k < g->n_arc; ++k)
		if (cnt_link[k] > 0) cov_link[k] += 1.0;
	for (i = 0; i < g->n_seg; ++i) {
		int32_t st = 0, en = 0, cov = 0;
		assert(scnt[i] == soff[i+1] - soff[i]);
		radix_sort_mg_intv(&sintv[soff[i]], &sintv[soff[i+1]]);
		for (j = soff[i]; j < soff[i+1]; ++j) {
			if (sintv[j].st > en)
				cov += en - st, st = sintv[j].st, en = sintv[j].en;
			else en = sintv[j].en > en? sintv[j].en : en;
		}
		cov += en - st;
		cov_seg[i] += (double)cov / g->seg[i].len;
	}

	// free
	kfree(km, cnt_link);
	kfree(km, sintv); kfree(km, soff); kfree(km, scnt);
}


<?xml version="1.0"?>
<!--

    Copyright (c) 1997-2018 Oracle and/or its affiliates. All rights reserved.
    Copyright 2004 The Apache Software Foundation

    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.

-->

<mbeans-descriptors>

  <mbean name="ContextConfig"
         description="Startup event listener for a Context that configures the properties of that Context, and the associated defined servlets"
         domain="Catalina"
         group="Listener"
         type="org.apache.catalina.startup.ContextConfig">

    <attribute name="className"
               description="Fully qualified class name of the managed object"
               type="java.lang.String"
               writeable="false"/>

    <attribute name="debug"
               description="The debugging detail level for this component"
               type="int"/>
  </mbean>

  <mbean name="EngineConfig"
         description="Startup event listener for a Engine that configures the properties of that Engine, and the associated defined contexts"
         domain="Catalina"
         group="Listener"
         type="org.apache.catalina.startup.EngineConfig">

    <attribute name="className"
               description="Fully qualified class name of the managed object"
               type="java.lang.String"
               writeable="false"/>

    <attribute name="debug"
               description="The debugging detail level for this component"
               type="int"/>
  </mbean>

  <mbean name="HostConfig"
         description="Startup event listener for a Host that configures the properties of that Host, and the associated defined contexts"
         domain="Catalina"
         group="Listener"
         type="org.apache.catalina.startup.HostConfig">

    <attribute name="className"
               description="Fully qualified class name of the managed object"
               type="java.lang.String"
               writeable="false"/>

    <attribute name="configClass"
               description="The Java class name of the Context configuration class we should use"
               type="java.lang.String"/>

    <attribute name="contextClass"
               description="The Java class name of the Context implementation we should use"
               type="java.lang.String"/>

    <attribute   name="debug"
               description="The debugging detail level for this component"
               type="int"/>
  </mbean>

</mbeans-descriptors>


// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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 Google Inc. 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.

// Author: kenton@google.com (Kenton Varda)
//  Based on original Protocol Buffers design by
//  Sanjay Ghemawat, Jeff Dean, and others.

#include <google/protobuf/compiler/java/java_service.h>

#include <google/protobuf/compiler/java/java_context.h>
#include <google/protobuf/compiler/java/java_doc_comment.h>
#include <google/protobuf/compiler/java/java_helpers.h>
#include <google/protobuf/compiler/java/java_name_resolver.h>
#include <google/protobuf/io/printer.h>
#include <google/protobuf/stubs/strutil.h>

namespace google {
namespace protobuf {
namespace compiler {
namespace java {

ServiceGenerator::ServiceGenerator(const ServiceDescriptor* descriptor)
  : descriptor_(descriptor) {}

ServiceGenerator::~ServiceGenerator() {}

// ===================================================================
ImmutableServiceGenerator::ImmutableServiceGenerator(
    const ServiceDescriptor* descriptor, Context* context)
    : ServiceGenerator(descriptor), context_(context),
    name_resolver_(context->GetNameResolver()) {}

ImmutableServiceGenerator::~ImmutableServiceGenerator() {}

void ImmutableServiceGenerator::Generate(io::Printer* printer) {
  bool is_own_file = IsOwnFile(descriptor_, /* immutable = */ true);
  WriteServiceDocComment(printer, descriptor_);
  MaybePrintGeneratedAnnotation(context_, printer, descriptor_,
                                /* immutable = */ true);
  printer->Print(
    "public $static$ abstract class $classname$\n"
    "    implements com.google.protobuf.Service {\n",
    "static", is_own_file ? "" : "static",
    "classname", descriptor_->name());
  printer->Indent();

  printer->Print(
    "protected $classname$() {}\n\n",
    "classname", descriptor_->name());

  GenerateInterface(printer);

  GenerateNewReflectiveServiceMethod(printer);
  GenerateNewReflectiveBlockingServiceMethod(printer);

  GenerateAbstractMethods(printer);

  // Generate getDescriptor() and getDescriptorForType().
  printer->Print(
    "public static final\n"
    "    com.google.protobuf.Descriptors.ServiceDescriptor\n"
    "    getDescriptor() {\n"
    "  return $file$.getDescriptor().getServices().get($index$);\n"
    "}\n",
    "file", name_resolver_->GetImmutableClassName(descriptor_->file()),
    "index", SimpleItoa(descriptor_->index()));
  GenerateGetDescriptorForType(printer);

  // Generate more stuff.
  GenerateCallMethod(printer);
  GenerateGetPrototype(REQUEST, printer);
  GenerateGetPrototype(RESPONSE, printer);
  GenerateStub(printer);
  GenerateBlockingStub(printer);

  // Add an insertion point.
  printer->Print(
    "\n"
    "// @@protoc_insertion_point(class_scope:$full_name$)\n",
    "full_name", descriptor_->full_name());

  printer->Outdent();
  printer->Print("}\n\n");
}

void ImmutableServiceGenerator::GenerateGetDescriptorForType(
    io::Printer* printer) {
  printer->Print(
    "public final com.google.protobuf.Descriptors.ServiceDescriptor\n"
    "    getDescriptorForType() {\n"
    "  return getDescriptor();\n"
    "}\n");
}

void ImmutableServiceGenerator::GenerateInterface(io::Printer* printer) {
  printer->Print("public interface Interface {\n");
  printer->Indent();
  GenerateAbstractMethods(printer);
  printer->Outdent();
  printer->Print("}\n\n");
}

void ImmutableServiceGenerator::GenerateNewReflectiveServiceMethod(
    io::Printer* printer) {
  printer->Print(
    "public static com.google.protobuf.Service newReflectiveService(\n"
    "    final Interface impl) {\n"
    "  return new $classname$() {\n",
    "classname", descriptor_->name());
  printer->Indent();
  printer->Indent();

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    printer->Print("@java.lang.Override\n");
    GenerateMethodSignature(printer, method, IS_CONCRETE);
    printer->Print(
      " {\n"
      "  impl.$method$(controller, request, done);\n"
      "}\n\n",
      "method", UnderscoresToCamelCase(method));
  }

  printer->Outdent();
  printer->Print("};\n");
  printer->Outdent();
  printer->Print("}\n\n");
}

void ImmutableServiceGenerator::GenerateNewReflectiveBlockingServiceMethod(
    io::Printer* printer) {
  printer->Print(
    "public static com.google.protobuf.BlockingService\n"
    "    newReflectiveBlockingService(final BlockingInterface impl) {\n"
    "  return new com.google.protobuf.BlockingService() {\n");
  printer->Indent();
  printer->Indent();

  GenerateGetDescriptorForType(printer);

  GenerateCallBlockingMethod(printer);
  GenerateGetPrototype(REQUEST, printer);
  GenerateGetPrototype(RESPONSE, printer);

  printer->Outdent();
  printer->Print("};\n");
  printer->Outdent();
  printer->Print("}\n\n");
}

void ImmutableServiceGenerator::GenerateAbstractMethods(io::Printer* printer) {
  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    WriteMethodDocComment(printer, method);
    GenerateMethodSignature(printer, method, IS_ABSTRACT);
    printer->Print(";\n\n");
  }
}

void ImmutableServiceGenerator::GenerateCallMethod(io::Printer* printer) {
  printer->Print(
    "\n"
    "public final void callMethod(\n"
    "    com.google.protobuf.Descriptors.MethodDescriptor method,\n"
    "    com.google.protobuf.RpcController controller,\n"
    "    com.google.protobuf.Message request,\n"
    "    com.google.protobuf.RpcCallback<\n"
    "      com.google.protobuf.Message> done) {\n"
    "  if (method.getService() != getDescriptor()) {\n"
    "    throw new java.lang.IllegalArgumentException(\n"
    "      \"Service.callMethod() given method descriptor for wrong \" +\n"
    "      \"service type.\");\n"
    "  }\n"
    "  switch(method.getIndex()) {\n");
  printer->Indent();
  printer->Indent();

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    map<string, string> vars;
    vars["index"] = SimpleItoa(i);
    vars["method"] = UnderscoresToCamelCase(method);
    vars["input"] = name_resolver_->GetImmutableClassName(
        method->input_type());
    vars["output"] = name_resolver_->GetImmutableClassName(
        method->output_type());
    printer->Print(vars,
      "case $index$:\n"
      "  this.$method$(controller, ($input$)request,\n"
      "    com.google.protobuf.RpcUtil.<$output$>specializeCallback(\n"
      "      done));\n"
      "  return;\n");
  }

  printer->Print(
    "default:\n"
    "  throw new java.lang.AssertionError(\"Can't get here.\");\n");

  printer->Outdent();
  printer->Outdent();

  printer->Print(
    "  }\n"
    "}\n"
    "\n");
}

void ImmutableServiceGenerator::GenerateCallBlockingMethod(
    io::Printer* printer) {
  printer->Print(
    "\n"
    "public final com.google.protobuf.Message callBlockingMethod(\n"
    "    com.google.protobuf.Descriptors.MethodDescriptor method,\n"
    "    com.google.protobuf.RpcController controller,\n"
    "    com.google.protobuf.Message request)\n"
    "    throws com.google.protobuf.ServiceException {\n"
    "  if (method.getService() != getDescriptor()) {\n"
    "    throw new java.lang.IllegalArgumentException(\n"
    "      \"Service.callBlockingMethod() given method descriptor for \" +\n"
    "      \"wrong service type.\");\n"
    "  }\n"
    "  switch(method.getIndex()) {\n");
  printer->Indent();
  printer->Indent();

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    map<string, string> vars;
    vars["index"] = SimpleItoa(i);
    vars["method"] = UnderscoresToCamelCase(method);
    vars["input"] = name_resolver_->GetImmutableClassName(
        method->input_type());
    vars["output"] = name_resolver_->GetImmutableClassName(
        method->output_type());
    printer->Print(vars,
      "case $index$:\n"
      "  return impl.$method$(controller, ($input$)request);\n");
  }

  printer->Print(
    "default:\n"
    "  throw new java.lang.AssertionError(\"Can't get here.\");\n");

  printer->Outdent();
  printer->Outdent();

  printer->Print(
    "  }\n"
    "}\n"
    "\n");
}

void ImmutableServiceGenerator::GenerateGetPrototype(RequestOrResponse which,
                                            io::Printer* printer) {
  /*
   * TODO(cpovirk): The exception message says "Service.foo" when it may be
   * "BlockingService.foo."  Consider fixing.
   */
  printer->Print(
    "public final com.google.protobuf.Message\n"
    "    get$request_or_response$Prototype(\n"
    "    com.google.protobuf.Descriptors.MethodDescriptor method) {\n"
    "  if (method.getService() != getDescriptor()) {\n"
    "    throw new java.lang.IllegalArgumentException(\n"
    "      \"Service.get$request_or_response$Prototype() given method \" +\n"
    "      \"descriptor for wrong service type.\");\n"
    "  }\n"
    "  switch(method.getIndex()) {\n",
    "request_or_response", (which == REQUEST) ? "Request" : "Response");
  printer->Indent();
  printer->Indent();

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    map<string, string> vars;
    vars["index"] = SimpleItoa(i);
    vars["type"] = name_resolver_->GetImmutableClassName(
      (which == REQUEST) ? method->input_type() : method->output_type());
    printer->Print(vars,
      "case $index$:\n"
      "  return $type$.getDefaultInstance();\n");
  }

  printer->Print(
    "default:\n"
    "  throw new java.lang.AssertionError(\"Can't get here.\");\n");

  printer->Outdent();
  printer->Outdent();

  printer->Print(
    "  }\n"
    "}\n"
    "\n");
}

void ImmutableServiceGenerator::GenerateStub(io::Printer* printer) {
  printer->Print(
    "public static Stub newStub(\n"
    "    com.google.protobuf.RpcChannel channel) {\n"
    "  return new Stub(channel);\n"
    "}\n"
    "\n"
    "public static final class Stub extends $classname$ implements Interface {"
    "\n",
    "classname", name_resolver_->GetImmutableClassName(descriptor_));
  printer->Indent();

  printer->Print(
    "private Stub(com.google.protobuf.RpcChannel channel) {\n"
    "  this.channel = channel;\n"
    "}\n"
    "\n"
    "private final com.google.protobuf.RpcChannel channel;\n"
    "\n"
    "public com.google.protobuf.RpcChannel getChannel() {\n"
    "  return channel;\n"
    "}\n");

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    printer->Print("\n");
    GenerateMethodSignature(printer, method, IS_CONCRETE);
    printer->Print(" {\n");
    printer->Indent();

    map<string, string> vars;
    vars["index"] = SimpleItoa(i);
    vars["output"] = name_resolver_->GetImmutableClassName(
        method->output_type());
    printer->Print(vars,
      "channel.callMethod(\n"
      "  getDescriptor().getMethods().get($index$),\n"
      "  controller,\n"
      "  request,\n"
      "  $output$.getDefaultInstance(),\n"
      "  com.google.protobuf.RpcUtil.generalizeCallback(\n"
      "    done,\n"
      "    $output$.class,\n"
      "    $output$.getDefaultInstance()));\n");

    printer->Outdent();
    printer->Print("}\n");
  }

  printer->Outdent();
  printer->Print(
    "}\n"
    "\n");
}

void ImmutableServiceGenerator::GenerateBlockingStub(io::Printer* printer) {
  printer->Print(
    "public static BlockingInterface newBlockingStub(\n"
    "    com.google.protobuf.BlockingRpcChannel channel) {\n"
    "  return new BlockingStub(channel);\n"
    "}\n"
    "\n");

  printer->Print(
    "public interface BlockingInterface {");
  printer->Indent();

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    GenerateBlockingMethodSignature(printer, method);
    printer->Print(";\n");
  }

  printer->Outdent();
  printer->Print(
    "}\n"
    "\n");

  printer->Print(
    "private static final class BlockingStub implements BlockingInterface {\n");
  printer->Indent();

  printer->Print(
    "private BlockingStub(com.google.protobuf.BlockingRpcChannel channel) {\n"
    "  this.channel = channel;\n"
    "}\n"
    "\n"
    "private final com.google.protobuf.BlockingRpcChannel channel;\n");

  for (int i = 0; i < descriptor_->method_count(); i++) {
    const MethodDescriptor* method = descriptor_->method(i);
    GenerateBlockingMethodSignature(printer, method);
    printer->Print(" {\n");
    printer->Indent();

    map<string, string> vars;
    vars["index"] = SimpleItoa(i);
    vars["output"] = name_resolver_->GetImmutableClassName(
        method->output_type());
    printer->Print(vars,
      "return ($output$) channel.callBlockingMethod(\n"
      "  getDescriptor().getMethods().get($index$),\n"
      "  controller,\n"
      "  request,\n"
      "  $output$.getDefaultInstance());\n");

    printer->Outdent();
    printer->Print(
      "}\n"
      "\n");
  }

  printer->Outdent();
  printer->Print("}\n");
}

void ImmutableServiceGenerator::GenerateMethodSignature(io::Printer* printer,
                                               const MethodDescriptor* method,
                                               IsAbstract is_abstract) {
  map<string, string> vars;
  vars["name"] = UnderscoresToCamelCase(method);
  vars["input"] = name_resolver_->GetImmutableClassName(method->input_type());
  vars["output"] = name_resolver_->GetImmutableClassName(method->output_type());
  vars["abstract"] = (is_abstract == IS_ABSTRACT) ? "abstract" : "";
  printer->Print(vars,
    "public $abstract$ void $name$(\n"
    "    com.google.protobuf.RpcController controller,\n"
    "    $input$ request,\n"
    "    com.google.protobuf.RpcCallback<$output$> done)");
}

void ImmutableServiceGenerator::GenerateBlockingMethodSignature(
    io::Printer* printer,
    const MethodDescriptor* method) {
  map<string, string> vars;
  vars["method"] = UnderscoresToCamelCase(method);
  vars["input"] = name_resolver_->GetImmutableClassName(method->input_type());
  vars["output"] = name_resolver_->GetImmutableClassName(method->output_type());
  printer->Print(vars,
    "\n"
    "public $output$ $method$(\n"
    "    com.google.protobuf.RpcController controller,\n"
    "    $input$ request)\n"
    "    throws com.google.protobuf.ServiceException");
}

}  // namespace java
}  // namespace compiler
}  // namespace protobuf
}  // namespace google


import MESSAGES from '../../../../messages';
import helpers from './index';

const isValidSecret = (secret) => {
  if (!secret) {
    throw new Error(MESSAGES.MESSAGING.ENCRYPTION.ERRORS.NO_SECRET_OR_SECRET_ID);
  }

  if (!helpers.utils.isValidString(secret)) {
    throw new Error(MESSAGES.MESSAGING.ENCRYPTION.ERRORS.INVALID_TYPE);
  }

  return true;
};

const isValidSecretId = (secretId, updatedEncryptSecrets) => {
  if (!secretId) {
    throw new Error(MESSAGES.MESSAGING.ENCRYPTION.ERRORS.NO_SECRET_OR_SECRET_ID);
  }

  if (!helpers.utils.isValidString(secretId)) {
    throw new Error(MESSAGES.MESSAGING.ENCRYPTION.ERRORS.INVALID_TYPE);
  }

  if (helpers.utils.isExisting(secretId, updatedEncryptSecrets)) {
    throw new Error(MESSAGES.MESSAGING.ENCRYPTION.ERRORS.SECRET_ID_NOT_UNIQUE);
  }

  return true;
};

// eslint-disable-next-line consistent-return
const setEncryptSecret = (encryptSecrets, secret, secretId) => {
  const updatedEncryptSecrets = encryptSecrets;

  if (isValidSecret(secret) && isValidSecretId(secretId, updatedEncryptSecrets)) {
    updatedEncryptSecrets[secretId] = secret;
    return updatedEncryptSecrets;
  }
};

export default setEncryptSecret;


package terminal

import (
	"syscall"
	"unsafe"
)

func EraseLine(out FileWriter, mode EraseLineMode) {
	handle := syscall.Handle(out.Fd())

	var csbi consoleScreenBufferInfo
	procGetConsoleScreenBufferInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&csbi)))

	var w uint32
	var x Short
	cursor := csbi.cursorPosition
	switch mode {
	case ERASE_LINE_END:
		x = csbi.size.X
	case ERASE_LINE_START:
		x = 0
	case ERASE_LINE_ALL:
		cursor.X = 0
		x = csbi.size.X
	}
	procFillConsoleOutputCharacter.Call(uintptr(handle), uintptr(' '), uintptr(x), uintptr(*(*int32)(unsafe.Pointer(&cursor))), uintptr(unsafe.Pointer(&w)))
}


package android.encrypt;

public interface ISDCardCryptedHelper {
    int addUserKeyAuth(int i, int i2, byte[] bArr, byte[] bArr2);

    int unlockKey(int i, int i2, byte[] bArr, byte[] bArr2);
}


//=================================================================================================
//
//  MJP's DX12 Sample Framework
//  http://mynameismjp.wordpress.com/
//
//  All code licensed under the MIT license
//
//=================================================================================================

#pragma once

#include "PCH.h"

namespace SampleFramework12
{

struct KeyState
{
    bool Pressed;
    bool RisingEdge;
    bool FallingEdge;

    KeyState();
};

class MouseState
{

public:

    MouseState();

    static MouseState GetMouseState(HWND hwnd = NULL);
    static void SetCursorPos(int x, int y, HWND hwnd = NULL);

    int X;
    int Y;
    int DX;
    int DY;

    KeyState LButton;
    KeyState MButton;
    KeyState RButton;

    bool IsOverWindow;

private:

    static MouseState prevState;
};

class KeyboardState
{

public:

    enum Keys
    {
        A = 0x41,
        Add = 0x6b,
        Apps = 0x5d,
        Attn = 0xf6,
        B = 0x42,
        Back = 8,
        BrowserBack = 0xa6,
        BrowserFavorites = 0xab,
        BrowserForward = 0xa7,
        BrowserHome = 0xac,
        BrowserRefresh = 0xa8,
        BrowserSearch = 170,
        BrowserStop = 0xa9,
        C = 0x43,
        CapsLock = 20,
        ChatPadGreen = 0xca,
        ChatPadOrange = 0xcb,
        Crsel = 0xf7,
        D = 0x44,
        D0 = 0x30,
        D1 = 0x31,
        D2 = 50,
        D3 = 0x33,
        D4 = 0x34,
        D5 = 0x35,
        D6 = 0x36,
        D7 = 0x37,
        D8 = 0x38,
        D9 = 0x39,
        Decimal = 110,
        Delete = 0x2e,
        Divide = 0x6f,
        Down = 40,
        E = 0x45,
        End = 0x23,
        Enter = 13,
        EraseEof = 0xf9,
        Escape = 0x1b,
        Execute = 0x2b,
        Exsel = 0xf8,
        F = 70,
        F1 = 0x70,
        F10 = 0x79,
        F11 = 0x7a,
        F12 = 0x7b,
        F13 = 0x7c,
        F14 = 0x7d,
        F15 = 0x7e,
        F16 = 0x7f,
        F17 = 0x80,
        F18 = 0x81,
        F19 = 130,
        F2 = 0x71,
        F20 = 0x83,
        F21 = 0x84,
        F22 = 0x85,
        F23 = 0x86,
        F24 = 0x87,
        F3 = 0x72,
        F4 = 0x73,
        F5 = 0x74,
        F6 = 0x75,
        F7 = 0x76,
        F8 = 0x77,
        F9 = 120,
        G = 0x47,
        H = 0x48,
        Help = 0x2f,
        Home = 0x24,
        I = 0x49,
        ImeConvert = 0x1c,
        ImeNoConvert = 0x1d,
        Insert = 0x2d,
        J = 0x4a,
        K = 0x4b,
        Kana = 0x15,
        Kanji = 0x19,
        L = 0x4c,
        LaunchApplication1 = 0xb6,
        LaunchApplication2 = 0xb7,
        LaunchMail = 180,
        Left = 0x25,
        LeftAlt = 0xa4,
        LeftControl = 0xa2,
        LeftShift = 160,
        LeftWindows = 0x5b,
        M = 0x4d,
        MediaNextTrack = 0xb0,
        MediaPlayPause = 0xb3,
        MediaPreviousTrack = 0xb1,
        MediaStop = 0xb2,
        Multiply = 0x6a,
        N = 0x4e,
        None = 0,
        NumLock = 0x90,
        NumPad0 = 0x60,
        NumPad1 = 0x61,
        NumPad2 = 0x62,
        NumPad3 = 0x63,
        NumPad4 = 100,
        NumPad5 = 0x65,
        NumPad6 = 0x66,
        NumPad7 = 0x67,
        NumPad8 = 0x68,
        NumPad9 = 0x69,
        O = 0x4f,
        Oem8 = 0xdf,
        OemAuto = 0xf3,
        OemBackslash = 0xe2,
        OemClear = 0xfe,
        OemCloseBrackets = 0xdd,
        OemComma = 0xbc,
        OemCopy = 0xf2,
        OemEnlW = 0xf4,
        OemMinus = 0xbd,
        OemOpenBrackets = 0xdb,
        OemPeriod = 190,
        OemPipe = 220,
        OemPlus = 0xbb,
        OemQuestion = 0xbf,
        OemQuotes = 0xde,
        OemSemicolon = 0xba,
        OemTilde = 0xc0,
        P = 80,
        Pa1 = 0xfd,
        PageDown = 0x22,
        PageUp = 0x21,
        Pause = 0x13,
        Play = 250,
        Print = 0x2a,
        PrintScreen = 0x2c,
        ProcessKey = 0xe5,
        Q = 0x51,
        R = 0x52,
        Right = 0x27,
        RightAlt = 0xa5,
        RightControl = 0xa3,
        RightShift = 0xa1,
        RightWindows = 0x5c,
        S = 0x53,
        Scroll = 0x91,
        Select = 0x29,
        SelectMedia = 0xb5,
        Separator = 0x6c,
        Sleep = 0x5f,
        Space = 0x20,
        Subtract = 0x6d,
        T = 0x54,
        Tab = 9,
        U = 0x55,
        Up = 0x26,
        V = 0x56,
        VolumeDown = 0xae,
        VolumeMute = 0xad,
        VolumeUp = 0xaf,
        W = 0x57,
        X = 0x58,
        Y = 0x59,
        Z = 90,
        Zoom = 0xfb
    };

public:

    KeyState GetKeyState(Keys key) const;
    bool IsKeyDown(Keys key) const;
    bool RisingEdge(Keys key) const;

    static KeyboardState GetKeyboardState(HWND hwnd);

private:

    KeyState keyStates[256];

    static KeyboardState prevState;
    static BYTE currState[256];

    static inline bool KeyPressed(BYTE value) { return (value & 0x80) > 0; };
};

}


<!doctype html>

  <meta charset="utf-8">
  <title>KISSY - 全终端适配的 JS 类库</title>
  <meta name="viewport" content="width=device-width">
  <link href="http://fonts.googleapis.com/css?family=Droid+Sans|Lekton|Ubuntu+Mono:400,700" rel="stylesheet">
	<link rel="stylesheet" href="templates/assets/bootstrap.css">
	<link href="templates/assets/normalize.css" rel="stylesheet">
	<link href="templates/assets/kissy.css" rel="stylesheet">
	<link href="templates/assets/prettify.css" rel="stylesheet">
	<link href="templates/assets/forkit.css" rel="stylesheet">

	<link href="api/assets/tomorrow-night-bright.css" rel=stylesheet />
	<link rel="shortcut icon" href="http://a.tbcdn.cn/s/kissy/favicon.ico">

首页

Why KISSY?

KISSY 1.4.x 教程大纲

核心模块列表

KISSY 模块规范 (KMD)

浏览器兼容基准(GBS)

jQuery KISSY 对比手册

KISSY 组件开发规范

历史版本

API Doc

Demos

KISSY Gallery

KISSY 项目构建工具

KS Module Compiler

ABC

Clam

第三方代码库

面向第三方安全的 KISSY

BUI

MUI

为 KISSY Core 贡献代码

HTML/CSS编码规范

JavaScript 编码规范

1.3.x->1.4.0 升级指南

FAQ

GitHub

KISSY 核心小组

UA

判断浏览器类型、版本、外壳等信息，引入种子文件后，通过KISSY.UA来访问UserAgent相关属性

此处的外壳表示广义的外壳，即 IE, Firefox, Chrome, Opera, Safari 等浏览器都属于外壳。可以利用此标识符直接识别浏览器类型。 可以首先使用 UA.shell 返回的标识符判断当前浏览器类型，若需浏览器具体版本信息，可以再通过 UA[UA.shell] 取出版本号。

UA.core 返回字符串，目前支持 trident, webkit, gecko, presto 四大浏览器内核.

UA.shell 返回字符串，比如 firefox, opera, chrome, ie, safari

UA.mobile 返回字符串，目前支持 apple, nokia, android, opera mini/mobile 等设备/浏览器的探测.

通过 KISSY.UA, 你可以获取浏览器等用户代理信息. 属性值遵循以下规则：

表示当前引擎或浏览器的版本. 版本号 1.2.3.4 会转换为数值 1.234

如果不是当前引擎或浏览器, 返回 0

如果当前引擎或浏览器的版本号无法准确判定, 返回 0.1

通过 KISSY.UA 的属性，你可以获取浏览器等用户代理的信息。属性值遵循以下规则：

表示当前引擎或浏览器的版本。版本号 1.2.3.4 会转换为数值 1.234

如果不是当前引擎或浏览器，返回 0 或者 undefined

如果当前浏览器版本号无法准确判定，均返回 0.1

KISSY.use('ua',function(S,UA){
    alert(UA); // UA可以使用了
});

trident  <static>

{Number} - trident 的版本号。IE 浏览器 8 系列以下都无法准确探测 Trident 内核的版本号。

webkit  <static>

{Number} - webkit 的版本号。

gecko  <static>

{Number} - gecko 的版本号。

presto  <static>

{Number} - presto 的版本号。

chrome  <static>

{Number} - chrome 的版本号。

safari  <static>

{Number} - safari 的版本号。

firefox  <static>

{Number} - firefox 的版本号。

ie  <static>

{Number} - ie 的版本号。

opera  <static>

{Number} - opera 的版本号。

mobile  <static>

{String} - mobile 的标志符。 若无法探测或非移动设备浏览器，将返回空字符串。

core  <static>

{String} - core 的标志符。此标识符表示浏览器的内核标识。若浏览器内核不是 trident, webkit, gecko, presto 将返回空字符串。

shell  <static>

{String} - shell 的标志符。此标识符表示用户所用浏览器的外壳标识。

os  <static>

{String} - 操作系统标志符。例如 windows android ios linux

ipad  <static>

{Number} - ipad ios 版本号。例如 5.0

iphone  <static>

{Number} - iphone ios 版本号。例如 5.0

ipod  <static>

{Number} - ipod ios 版本号。例如 5.0

ios  <static>

{Number} - ios 版本号。例如 5.0

android  <static>

{Number} - android 版本号。例如 5.0

examples

判断浏览器类型

KISSY.use('ua',function(S,UA){
    if(UA.chrome > 0){
        alert('Your browser is chrome');
    }else if(UA.safari > 0){
        alert('Your browser is safari');
    }else if(UA.opera > 0){
        alert('Your browser is opera');
    }else if(UA.firefox > 0){
        alert('Your browser is firefox');
    }else if(UA.ie > 0){
        alert('Your browser is ie');
    }else{
        alert('Your browser is unknown');
    }
});

判断操作系统类型

KISSY.use('ua',function(S,UA){
    if(UA.os == 'windows'){
        alert('Your os is Windows');
    }else if(UA.os == 'Linux'){
        alert('Your os is Linux');
    }else if(UA.os == 'ios'){
        alert('Your os is ios and version is' + UA.ios);
        if(UA.ipad > 0){
            alert('Your device is iPad');
        }else if(UA.iphone > 0){
            alert('Your device is iPhone');
        }else if(UA.ipod > 0){
            alert('Your device is iPod')
        }
    }else if(UA.os == 'android'){
        alert('Your os is Android');
    }
});

判断mobile类型

KISSY.use('ua',function(S,UA){
    if(UA.mobile == 'apple'){
        alert('Your device is Apple');
    }else if(UA.mobile == 'nokia'){
        alert('Your device is Nokia');
    }else if(UA.mobile == 'android'){
        alert('Your device is Android');
    }else if(UA.mobile == 'opera mini' || UA.mobile == 'opera mobi'){
        alert('Your browser is opera mobile');
    }
});

判断浏览器外壳

KISSY.use('ua',function(S,UA){
    if(UA.shell == 'chrome'){
        alert('Your browser is chrome and the version is' + UA[UA.shell]);
    }else if(UA.shell == 'se360'){
        alert('Your browser is 360浏览器');
    }else if(UA.shell == 'tt'){
        alert('Your browser is 腾讯TT浏览器');
    }else if(UA.shell == 'maxthon'){
        alert('Your browser is 遨游浏览器');
    }
});

		©2013 - 2033 KISSY UI LIBRARY


        <%- gettext('Coupon Codes') %>

            <%- gettext('Create Coupon') %>

<%- gettext('Current Coupon Codes') %>


/**
 * Adds a sticker to an editor state
 */

import {
  BlockMapBuilder,
  CharacterMetadata,
  ContentBlock,
  EditorState,
  genKey,
  Modifier,
} from 'draft-js';
import { List, Repeat } from 'immutable';

export default (editorState: Object, stickerId: any) => {
  const currentContentState = editorState.getCurrentContent();
  const currentSelectionState = editorState.getSelection();

  // in case text is selected it is removed and then the sticker is appended
  const afterRemovalContentState = Modifier.removeRange(
    currentContentState,
    currentSelectionState,
    'backward'
  );

  // deciding on the postion to split the text
  const targetSelection = afterRemovalContentState.getSelectionAfter();
  const blockKeyForTarget = targetSelection.get('focusKey');
  const block = currentContentState.getBlockForKey(blockKeyForTarget);
  let insertionTargetSelection;
  let insertionTargetBlock;

  // In case there are no characters or entity or the selection is at the start it
  // is safe to insert the sticker in the current block.
  // Otherwise a new block is created (the sticker is always its own block)
  const isEmptyBlock = block.getLength() === 0 && block.getEntityAt(0) === null;
  const selectedFromStart = currentSelectionState.getStartOffset() === 0;
  if (isEmptyBlock || selectedFromStart) {
    insertionTargetSelection = targetSelection;
    insertionTargetBlock = afterRemovalContentState;
  } else {
    // the only way to insert a new seems to be by splitting an existing in to two
    insertionTargetBlock = Modifier.splitBlock(
      afterRemovalContentState,
      targetSelection
    );

    // the position to insert our blocks
    insertionTargetSelection = insertionTargetBlock.getSelectionAfter();
  }

  // TODO not sure why we need it …
  const newContentStateAfterSplit = Modifier.setBlockType(
    insertionTargetBlock,
    insertionTargetSelection,
    'sticker'
  );

  // creating a new ContentBlock including the entity with data
  const contentStateWithEntity = newContentStateAfterSplit.createEntity(
    'sticker',
    'IMMUTABLE',
    { id: stickerId }
  );
  const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
  const charDataOfSticker = CharacterMetadata.create({ entity: entityKey });

  const fragmentArray = [
    new ContentBlock({
      key: genKey(),
      type: 'sticker',
      text: ' ',
      characterList: List(Repeat(charDataOfSticker, 1)), // eslint-disable-line new-cap
    }),

    // new contentblock so we can continue wrting right away after inserting the sticker
    new ContentBlock({
      key: genKey(),
      type: 'unstyled',
      text: '',
      characterList: List(), // eslint-disable-line new-cap
    }),
  ];

  // create fragment containing the two content blocks
  const fragment = BlockMapBuilder.createFromArray(fragmentArray);

  // replace the contentblock we reserved for our insert
  const contentStateWithSticker = Modifier.replaceWithFragment(
    newContentStateAfterSplit,
    insertionTargetSelection,
    fragment
  );

  // update editor state with our new state including the sticker
  const newState = EditorState.push(
    editorState,
    contentStateWithSticker,
    'insert-sticker'
  );
  return EditorState.forceSelection(
    newState,
    contentStateWithSticker.getSelectionAfter()
  );
};


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

package com.facebook.buck.jvm.java.toolchain;

import com.facebook.buck.core.toolchain.Toolchain;
import com.facebook.buck.core.util.immutables.BuckStyleValue;
import com.facebook.buck.cxx.toolchain.UnresolvedCxxPlatform;

@BuckStyleValue
public interface JavaCxxPlatformProvider extends Toolchain {
  String DEFAULT_NAME = "java-cxx-platform";

  UnresolvedCxxPlatform getDefaultJavaCxxPlatform();

  @Override
  default String getName() {
    return DEFAULT_NAME;
  }

  static JavaCxxPlatformProvider of(UnresolvedCxxPlatform defaultJavaCxxPlatform) {
    return ImmutableJavaCxxPlatformProvider.of(defaultJavaCxxPlatform);
  }
}


# frozen_string_literal: true

Puppet::DataTypes.create_type('Target') do
  begin
    inventory = Puppet.lookup(:bolt_inventory)
    target_implementation_class = inventory.target_implementation_class
  rescue Puppet::Context::UndefinedBindingError
    target_implementation_class = Bolt::Target
  end

  interface <<-PUPPET
    attributes => {
      uri => { type => Optional[String[1]], kind => given_or_derived },
      name => { type => Optional[String[1]] , kind => given_or_derived },
      safe_name => { type =>  Optional[String[1]], kind => given_or_derived },
      target_alias => { type => Optional[Variant[String[1], Array[String[1]]]], kind => given_or_derived },
      config => { type => Optional[Hash[String[1], Data]], kind => given_or_derived },
      vars => { type => Optional[Hash[String[1], Data]], kind => given_or_derived },
      facts => { type => Optional[Hash[String[1], Data]], kind => given_or_derived },
      features => { type => Optional[Array[String[1]]], kind => given_or_derived },
      plugin_hooks => { type => Optional[Hash[String[1], Data]], kind => given_or_derived },
      resources => { type => Optional[Hash[String[1], ResourceInstance]], kind => given_or_derived }
    },
    functions => {
      host => Callable[[], Optional[String]],
      password => Callable[[], Optional[String[1]]],
      port => Callable[[], Optional[Integer]],
      protocol => Callable[[], Optional[String[1]]],
      transport => Callable[[], String[1]],
      transport_config => Callable[[], Hash[String[1], Data]],
      user => Callable[[], Optional[String[1]]]
    }
  PUPPET

  # Needed for Puppet to recognize targets as Puppet objects when deserializing
  target_implementation_class.include(Puppet::Pops::Types::PuppetObject)
  implementation_class target_implementation_class
end


#include "blacklist4.h"

#include "mod/common/dev.h"
#include "mod/common/address.h"
#include "mod/common/xlator.h"
#include "mod/common/rcu.h"

/* TODO (fine) fuse this module and pool.c */

struct addr4_pool *blacklist4_alloc(void)
{
	return pool_alloc();
}

void blacklist4_get(struct addr4_pool *pool)
{
	pool_get(pool);
}

void blacklist4_put(struct addr4_pool *pool)
{
	pool_put(pool);
}

int blacklist4_add(struct addr4_pool *pool, struct ipv4_prefix *prefix)
{
	return pool_add(pool, prefix, false);
}

int blacklist4_rm(struct addr4_pool *pool, struct ipv4_prefix *prefix)
{
	return pool_rm(pool, prefix);
}

int blacklist4_flush(struct addr4_pool *pool)
{
	return pool_flush(pool);
}

#define NOT_BLACKLISTED false
#define BLACKLISTED true

/* "Check interface address" */
static int check_ifa(struct in_ifaddr *ifa, void const *arg)
{
	struct in_addr const *query = arg;
	struct in_addr ifaddr;

	/* Broadcast */
	/* (RFC3021: /31 and /32 networks lack broadcast) */
	if (ifa->ifa_prefixlen < 31) {
		ifaddr.s_addr = ifa->ifa_local | ~ifa->ifa_mask;
		if (ipv4_addr_cmp(&ifaddr, query) == 0)
			return BLACKLISTED;
	}

	/* Secondary addresses */
	/* https://github.com/NICMx/Jool/issues/223 */
	if (ifa->ifa_flags & IFA_F_SECONDARY)
		return NOT_BLACKLISTED;

	/* Primary addresses */
	ifaddr.s_addr = ifa->ifa_local;
	if (ipv4_addr_cmp(&ifaddr, query) == 0)
		return BLACKLISTED;

	return NOT_BLACKLISTED;
}

/**
 * Is @addr *NOT* translatable, according to the interfaces?
 *
 * The name comes from the fact that interface addresses are usually
 * non-translatable (ie. the traffic is meant for the translator box).
 *
 * Recognizable directed broadcast is also not translatable.
 */
bool interface_contains(struct net *ns, struct in_addr *addr)
{
	return foreach_ifa(ns, check_ifa, addr);
}

bool blacklist4_contains(struct addr4_pool *pool, struct in_addr *addr)
{
	return pool_contains(pool, addr);
}

int blacklist4_foreach(struct addr4_pool *pool,
		int (*func)(struct ipv4_prefix *, void *), void *arg,
		struct ipv4_prefix *offset)
{
	return pool_foreach(pool, func, arg, offset);
}

bool blacklist4_is_empty(struct addr4_pool *pool)
{
	return pool_is_empty(pool);
}