text:
namespace chromeos {
namespace system {

// Activation date key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kActivateDateKey[];

// The key that will be present in VPD if the device was enrolled in a domain
// that blocks dev mode.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kBlockDevModeKey[];
// The key that will be present in VPD if the device ever was enrolled.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kCheckEnrollmentKey[];

// The key and values present in VPD to indicate if RLZ ping should be sent.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kShouldSendRlzPingKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kShouldSendRlzPingValueFalse[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kShouldSendRlzPingValueTrue[];

// The key present in VPD that indicates the date after which the RLZ ping is
// allowed to be sent. It is in the format of "yyyy-mm-dd".
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kRlzEmbargoEndDateKey[];

// The key present in VPD that indicates the date after which enterprise
// management pings are allowed to be sent. It is in the format of "yyyy-mm-dd".
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kEnterpriseManagementEmbargoEndDateKey[];

// Customization ID key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kCustomizationIdKey[];

// Developer switch value.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kDevSwitchBootKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kDevSwitchBootValueDev[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kDevSwitchBootValueVerified[];

// Dock MAC address key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kDockMacAddressKey[];

// Ethernet MAC address key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kEthernetMacAddressKey[];

// Firmware write protect switch value.
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kFirmwareWriteProtectCurrentKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kFirmwareWriteProtectCurrentValueOn[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kFirmwareWriteProtectCurrentValueOff[];

// Firmware type and associated values. The values are from crossystem output
// for the mainfw_type key. Normal and developer correspond to Chrome OS
// firmware with MP and developer keys respectively, nonchrome indicates the
// machine doesn't run on Chrome OS firmware. See crossystem source for more
// details.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kFirmwareTypeKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kFirmwareTypeValueDeveloper[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kFirmwareTypeValueNonchrome[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kFirmwareTypeValueNormal[];

// HWID key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kHardwareClassKey[];

// Key/values reporting if Chrome OS is running in a VM or not. These values are
// read from crossystem output. See crossystem source for VM detection logic.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kIsVmKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kIsVmValueFalse[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kIsVmValueTrue[];

// Manufacture date key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kManufactureDateKey[];

// OEM customization flag that permits exiting enterprise enrollment flow in
// OOBE when 'oem_enterprise_managed' flag is set.
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kOemCanExitEnterpriseEnrollmentKey[];

// OEM customization directive that specified intended device purpose.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kOemDeviceRequisitionKey[];

// OEM customization flag that enforces enterprise enrollment flow in OOBE.
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kOemIsEnterpriseManagedKey[];

// OEM customization flag that specifies if OOBE flow should be enhanced for
// keyboard driven control.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kOemKeyboardDrivenOobeKey[];

// Offer coupon code key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kOffersCouponCodeKey[];

// Offer group key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kOffersGroupCodeKey[];

// Release Brand Code key.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kRlzBrandCodeKey[];

// Regional data
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kRegionKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kInitialLocaleKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kInitialTimezoneKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kKeyboardLayoutKey[];
COMPONENT_EXPORT(CHROMEOS_SYSTEM)
extern const char kKeyboardMechanicalLayoutKey[];

// The key that will be present in RO VPD to indicate what identifier is used
// for attestation-based registration of a device.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kAttestedDeviceIdKey[];

// Serial number key (VPD v2+ devices, Samsung: caroline and later) for use in
// tests. Outside of tests GetEnterpriseMachineID() is the backward-compatible
// way to obtain the serial number.
COMPONENT_EXPORT(CHROMEOS_SYSTEM) extern const char kSerialNumberKeyForTest[];

// This interface provides access to Chrome OS statistics.
class COMPONENT_EXPORT(CHROMEOS_SYSTEM) StatisticsProvider {
 public:
  // Starts loading the machine statistics.
  virtual void StartLoadingMachineStatistics(bool load_oem_manifest) = 0;

  // Schedules |callback| on the current sequence when machine statistics are
  // loaded. That can be immediately if machine statistics are already loaded.
  virtual void ScheduleOnMachineStatisticsLoaded(
      base::OnceClosure callback) = 0;

  // GetMachineStatistic(), GetMachineFlag() and GetEnterpriseMachineId() will
  // block if called before statistics have been loaded. To avoid this, call
  // from a callback passed to ScheduleOnMachineStatisticsLoaded(). These
  // methods are safe to call on any sequence. StartLoadingMachineStatistics()
  // must be called before these methods.

  // Returns true if the named machine statistic (e.g. "hardware_class") is
  // found and stores it in |result| (if provided). Probing for the existence of
  // a statistic by setting |result| to nullptr supresses the usual warning in
  // case the statistic is not found.
  virtual bool GetMachineStatistic(const std::string& name,
                                   std::string* result) = 0;

  // Similar to GetMachineStatistic for boolean flags.
  virtual bool GetMachineFlag(const std::string& name, bool* result) = 0;

  // Returns the machine serial number after examining a set of well-known
  // keys. In case no serial is found an empty string is returned.
  // Caveat: On older Samsung devices, the last letter is omitted from the
  // serial number for historical reasons. This is fine.
  // TODO(tnagel): Drop "Enterprise" from the method name and remove Samsung
  // special casing after kevin EOL.
  std::string GetEnterpriseMachineID();

  // Cancels any pending file operations.
  virtual void Shutdown() = 0;

  // Returns true if the machine is a VM.
  virtual bool IsRunningOnVm() = 0;

  // Get the Singleton instance.
  static StatisticsProvider* GetInstance();

  // Set the instance returned by GetInstance() for testing.
  static void SetTestProvider(StatisticsProvider* test_provider);

 protected:
  virtual ~StatisticsProvider() {}
};

}  // namespace system
}  // namespace chromeos

// TODO(https://crbug.com/1164001): remove after the //chrome/browser/chromeos
// source migration is finished.
namespace ash {
namespace system {
using ::chromeos::system::kActivateDateKey;
using ::chromeos::system::kBlockDevModeKey;
using ::chromeos::system::kCheckEnrollmentKey;
using ::chromeos::system::kEnterpriseManagementEmbargoEndDateKey;
using ::chromeos::system::kHardwareClassKey;
using ::chromeos::system::kIsVmKey;
using ::chromeos::system::kIsVmValueFalse;
using ::chromeos::system::kIsVmValueTrue;
using ::chromeos::system::kOemKeyboardDrivenOobeKey;
using ::chromeos::system::kRlzBrandCodeKey;
using ::chromeos::system::kSerialNumberKeyForTest;
using ::chromeos::system::StatisticsProvider;
}  // namespace system
}  // namespace ash

#endif  // CHROMEOS_SYSTEM_STATISTICS_PROVIDER_H_


text:
<?xml version="1.0" encoding="utf-8"?>

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_record_pressed" android:state_selected="true" />
    <item android:drawable="@drawable/icon_record_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/icon_record_pressed" android:state_checked="true" />
    <item android:drawable="@drawable/icon_record_normal" />
</selector>

redpajama_set_name: RedPajamaGithub


text:
package pirc

import (
    "strings"
    "fmt"
)

type Channel struct {
    Name string
    Topic string
    Type string
    Mode string
    Users []*User
    UserCount int
    Operators []*User
}

func (c *Channel) UserJoin(u *User) {
    // Check if user already in channel
    for _, cu := range c.Users {
        if cu == u {
            return
        }
    }
    c.Users = append(c.Users[0:], u)
    c.UserCount += 1
    u.JoinChannel(c)
}

func (c *Channel) UserPart(u *User) {
    // Check if user is in channel and find the index in the slice
    index := 0
    found := false
    for i, cu := range c.Users[0:] {
        index = i
        if cu == u {
            found = true
            break
        }
    }

    // Delete user from channel list
    if found {
        if index == (len(c.Users) - 1) {
            c.Users = c.Users[:index]
        } else {
            c.Users = append(c.Users[:index], c.Users[index+1])
        }
        c.UserCount -= 1
    }
}

func (c *Channel) BroadcastClientCmd(sender *User, cmd string) {
    r := fmt.Sprintf(":%v!%v@%v %v\r\n", sender.Nick, sender.Username, sender.Hostname, cmd)
    for _, u := range c.Users {
        u.Conn.Write([]byte(r))
    }
}

func (c *Channel) BroadcastClientCmdNoOrig(sender *User, cmd string) {
    r := fmt.Sprintf(":%v!%v@%v %v\r\n", sender.Nick, sender.Username, sender.Hostname, cmd)
    for _, u := range c.Users {
        if u == sender { continue }
        u.Conn.Write([]byte(r))
    }
}

func (c *Channel) InChannel(u *User) bool {
    for _, cu := range c.Users {
        if cu == u {
            return true
        }
    }

    return false
}

func (c *Channel) Names(current *User) string {
    var s []string
    for _, cu := range c.Users {
        s = append(s, cu.Nick)
    }

    return strings.Join(s[0:], " ")
}


text:
package bg.abv.king_hell.shortcut;

import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import bg.abv.king_hell.util.Configuration;
import bg.abv.king_hell.util.Constants;

public class LowLevelKeyListener implements NativeKeyListener
{
	private static LowLevelKeyListener listener;
	private static boolean enabled;

	public static void initialize() throws NativeHookException
	{
		GlobalScreen.initialize();
		GlobalScreen.registerNativeHook();
		if(GlobalScreen.isNativeHookRegistered())
		{
			listener = new LowLevelKeyListener();
			GlobalScreen.getInstance().addNativeKeyListener(listener);
			enabled = true;
		}
		else
		{
			enabled = false;
			throw new NativeHookException("Could not register hook");
		}
	}

	public static boolean isEnabled()
	{
		return enabled;
	}

	public static void dispose()
	{
		GlobalScreen.getInstance().removeNativeKeyListener(listener);
		GlobalScreen.unregisterNativeHook();
	}

	public static LowLevelKeyListener getInstance()
	{
		return listener;
	}

	@Override
	public void nativeKeyPressed(NativeKeyEvent e)
	{
		if(e.isMenuKey()) ControlKeys.setKeyPressed(e.getKeyCode()-16, true);
		else if(Constants.KEYS_ENABLED)
		{
			String[] scs = Configuration.getSetting("shortcuts").split("\\|");
			for(byte i=0;i<scs.length;++i)
			{
				if(Byte.parseByte(scs[i].substring(3)) != (byte)e.getKeyCode() || !KeyProcessor.checkMenuKeys(scs[i])) continue;
				KeyProcessor.processShortcut(i);
			}
		}
	}

	@Override
	public void nativeKeyReleased(NativeKeyEvent e)
	{
		if(e.isMenuKey()) ControlKeys.setKeyPressed(e.getKeyCode()-16, false);
	}

	@Override
	public void nativeKeyTyped(NativeKeyEvent e)
	{

	}
}


text:
using System;
using System.Runtime.Serialization;
using System.Security.Permissions;

using NSane.L10n;

namespace NSane
{
    /// <summary>
    /// This exception is thrown from many of the operations invoking the SANE
    /// system.
    /// </summary>
    [Serializable]
    public class NSaneException : Exception
    {
        /// <summary>
        /// Default constructor - no message
        /// </summary>
        public NSaneException()
        {
        }

        /// <summary>
        /// Construct with a message
        /// </summary>
        /// <param name="message"></param>
        public NSaneException(string message)
            : base(message)
        {
        }

        /// <summary>
        /// Construct with a message and inner exception
        /// </summary>
        /// <param name="message"></param>
        /// <param name="innerException"></param>
        public NSaneException(string message, Exception innerException) :
            base(message, innerException)
        {
        }

        /// <summary>
        /// Construct for serilization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected NSaneException(SerializationInfo info,
                                 StreamingContext context)
            : base(info, context)
        {
        }

        /// <summary>
        /// Gets the status that caused this exception to be raised
        /// </summary>
        public SaneStatus Status { get; private set; }

        /// <summary>
        /// Constructor for serialization
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        [SecurityPermission(SecurityAction.Demand,
            SerializationFormatter = true)]
        public override void GetObjectData(SerializationInfo info,
                                           StreamingContext context)
        {
            if (info == null)
                throw new ArgumentNullException("info");

            info.AddValue("Status", Status);

            base.GetObjectData(info, context);
        }

        /// <summary>
        /// Create from a status value
        /// </summary>
        /// <param name="status">The status value returned from SANE</param>
        /// <returns></returns>
        internal static NSaneException CreateFromStatus(int status)
        {
            // If status is 0 - it is a bug in this API since it is not an
            // exception
            // ReSharper disable LocalizableElement
            if (status == 0)
                throw new ArgumentOutOfRangeException(
                    "status",
                    "The status is 0 which is not an error so why are "
                    + "you calling this method?");
            // ReSharper restore LocalizableElement

            // TODO: Get all the status messages from the resx
            switch (status)
            {
                case 1:
                    return new NSaneException(Strings.EXCEPTION_UNSUPPORTED)
                        {
                            Status = SaneStatus.Unsupported
                        };
                case 2:
                    return new NSaneException(Strings.EXCEPTION_CANCELED)
                        {
                            Status = SaneStatus.Canceled
                        };
                case 3:
                    return new NSaneException(Strings.EXCEPTION_DEVICE_BUSY)
                        {
                            Status = SaneStatus.DeviceBusy
                        };
                case 4:
                    return new NSaneException(Strings
                        .EXCEPTION_INVALID_OPERATION)
                        {
                            Status = SaneStatus.Invalid
                        };
                case 5:
                    return new NSaneException(Strings.EXCEPTION_END_OF_FILE)
                        {
                            Status = SaneStatus.EndOfFile
                        };
                case 6:
                    return new NSaneException(Strings.EXCEPTION_PAPER_JAMMED)
                        {
                            Status = SaneStatus.Jammed
                        };
                case 7:
                    return new NSaneException(Strings.EXCEPTION_NO_DOCUMENT)
                        {
                            Status = SaneStatus.NoDocuments
                        };
                case 8:
                    return new NSaneException(Strings.EXCEPTION_COVER_OPEN)
                        {
                            Status = SaneStatus.CoverOpen
                        };
                case 9:
                    return new NSaneException(Strings.EXCEPTION_IO_ERROR)
                        {
                            Status = SaneStatus.IOError
                        };
                case 10:
                    return new NSaneException(Strings.EXCEPTION_OUT_OF_MEMORY)
                        {
                            Status = SaneStatus.OutOfMemory
                        };
                case 11:
                    return new NSaneException(Strings.EXCEPTION_ACCESS_DENIED)
                        {
                            Status = SaneStatus.AccessDenied
                        };
                default:
                    return new NSaneException(Strings.EXCEPTION_UNKNOWN);
            }
        }
    }
}


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chrome_browser_main_win.h"

#include "base/base_switches.h"
#include "base/command_line.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/about_flags.h"
#include "components/flags_ui/feature_entry_macros.h"
#include "components/flags_ui/flags_ui_pref_names.h"
#include "components/flags_ui/flags_ui_switches.h"
#include "components/flags_ui/pref_service_flags_storage.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "testing/gtest/include/gtest/gtest.h"

// Test GetRestartCommandLine function behavior. It should remove the program at
// the beginning of the command line, and any non-switch args, since the
// intention is to restore the session, by adding --restore-last-session. It
// should also remove any flags within the flag sentinels, and the sentinels
// themselves.
TEST(ChromeBrowserMainWinTest, GetRestartCommand) {
  base::FilePath chrome_path(L"chrome.exe");
  base::CommandLine simple_command_line(chrome_path);

  // Simple command line with just the program.
  const base::CommandLine::StringType kNoArgsResult =
      L" --restore-last-session";
  base::CommandLine restart_command_line =
      ChromeBrowserMainPartsWin::GetRestartCommandLine(simple_command_line);
  EXPECT_EQ(restart_command_line.GetCommandLineString(), kNoArgsResult);

  // Command line with a url argument - url should be removed.
  base::CommandLine url_command_line(chrome_path);
  url_command_line.AppendArg("https://www.example.com");
  restart_command_line =
      ChromeBrowserMainPartsWin::GetRestartCommandLine(url_command_line);
  EXPECT_EQ(restart_command_line.GetCommandLineString(), kNoArgsResult);

  // Command line with a retained switch.
  const std::string kRetainedSwitch = "--enable-sandbox-audio";
  const base::CommandLine::StringType kRetainedSwitchResult =
      L" --enable-sandbox-audio --restore-last-session";
  base::CommandLine retained_switch_command_line(chrome_path);
  retained_switch_command_line.AppendSwitch(kRetainedSwitch);
  restart_command_line = ChromeBrowserMainPartsWin::GetRestartCommandLine(
      retained_switch_command_line);
  EXPECT_EQ(restart_command_line.GetCommandLineString(), kRetainedSwitchResult);

  // Command line with flag switches.
  base::CommandLine experiments_command_line(chrome_path);
  // Add an --enable-features flag outside the flag sentinels, as if the user or
  // admin had added it. It should be retained, because Chrome won't add it
  // automatically.
  experiments_command_line.AppendSwitchASCII(switches::kEnableFeatures, "Exp2");
  experiments_command_line.AppendSwitch("enable-foo");
  experiments_command_line.AppendSwitch("--enable-sandbox-audio");

  // Setup the feature infrastructure so that ConvertFlagsToSwitches works.
  TestingPrefServiceSimple prefs;
  flags_ui::PrefServiceFlagsStorage flags_storage(&prefs);
  prefs.registry()->RegisterListPref(flags_ui::prefs::kAboutFlagsEntries);
  prefs.registry()->RegisterDictionaryPref(
      flags_ui::prefs::kAboutFlagsOriginLists);
  const char kExperimentName[] = "exp-flag";
  about_flags::testing::ScopedFeatureEntries scoped_feature_entries(
      {{kExperimentName, "Exp", "description", static_cast<unsigned short>(-1),
        ORIGIN_LIST_VALUE_TYPE("flag-switch", "")}});
  about_flags::SetFeatureEntryEnabled(&flags_storage, kExperimentName,
                                      /*enable=*/true);
  about_flags::ConvertFlagsToSwitches(&flags_storage, &experiments_command_line,
                                      flags_ui::kAddSentinels);
  // Check that ConvertFlagsToSwitches added the start sentinel.
  ASSERT_TRUE(
      experiments_command_line.HasSwitch(::switches::kFlagSwitchesBegin));
  ASSERT_EQ(
      experiments_command_line.GetCommandLineString(),
      L"chrome.exe --enable-features=Exp2 --enable-foo --enable-sandbox-audio"
      L" --flag-switches-begin --flag-switch --flag-switches-end");
  // Check that the args and flag switches and sentinels are removed.
  restart_command_line = ChromeBrowserMainPartsWin::GetRestartCommandLine(
      experiments_command_line);
  EXPECT_EQ(restart_command_line.GetCommandLineString(),
            L" --enable-features=Exp2 --enable-foo"
            L" --enable-sandbox-audio"
            L" --restore-last-session");
}

// Test RegisterApplicationRestart to make sure there are no crashes.
TEST(ChromeBrowserMainWinTest, RegisterRestart) {
  const base::CommandLine command_line = base::CommandLine::FromString(
      L"chrome.exe --enable-features=Exp2 --enable-foo -- "
      L"http://www.chromium.org");
  ChromeBrowserMainPartsWin::RegisterApplicationRestart(command_line);
}


text:
<?php

declare(strict_types=1);

namespace Jose\Component\KeyManagement\Analyzer;

use Jose\Component\Core\JWKSet;

final class MixedPublicAndPrivateKeys implements KeysetAnalyzer
{
    public function analyze(JWKSet $jwkset, MessageBag $bag): void
    {
        if ($jwkset->count() === 0) {
            return;
        }

        $hasPublicKeys = false;
        $hasPrivateKeys = false;

        foreach ($jwkset as $jwk) {
            switch ($jwk->get('kty')) {
                case 'OKP':
                case 'RSA':
                case 'EC':
                    if ($jwk->has('d')) {
                        $hasPrivateKeys = true;
                    } else {
                        $hasPublicKeys = true;
                    }

                    break;
            }
        }

        if ($hasPrivateKeys && $hasPublicKeys) {
            $bag->add(Message::high('This key set mixes public and private keys.'));
        }
    }
}


text:
package utils;

public interface ValueCallback {
    public void valueChanged(int value);
}


text:
package bixie.boogie.controlflow.util;

import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map.Entry;

import bixie.boogie.controlflow.BasicBlock;
import bixie.boogie.controlflow.CfgProcedure;

import java.util.Set;

/**
 * @author schaef
 * this class computes an effectual set for a given procedure
 * as described in the vstte'12 paper "infeasible code detection"
 */
public class HasseDiagram {

	private PartialBlockOrderNode rootNode;

	public HasseDiagram(CfgProcedure proc) {
		HashMap<BasicBlock, HashSet<BasicBlock>> dom = new HashMap<BasicBlock, HashSet<BasicBlock>>();
		HashMap<BasicBlock, HashSet<BasicBlock>> pdom = new HashMap<BasicBlock, HashSet<BasicBlock>>();
		//compute the (post)dominators for all blocks

		if (proc.getRootNode()==null) {
			throw new RuntimeException("Cannot compute HasseDiagram: Root is null!");
		}
		if (proc.getExitNode()==null) {
			throw new RuntimeException("Cannot compute HasseDiagram: Exit is null!");
		}

		computeDominators(proc.getRootNode(), dom, true);
		computeDominators(proc.getExitNode(), pdom, false);
		//merge post-dom into dom
		for (Entry<BasicBlock, HashSet<BasicBlock>>  entry : pdom.entrySet()) {
			dom.get(entry.getKey()).addAll(entry.getValue());
		}

		LinkedList<BasicBlock> todo = new LinkedList<BasicBlock>(dom.keySet());
		LinkedList<PartialBlockOrderNode> nodes = new LinkedList<PartialBlockOrderNode>();
		while (!todo.isEmpty()) {
			BasicBlock current = todo.pop();
			HashSet<BasicBlock> equivalenceClassDescriptor = dom.get(current);
			HashSet<BasicBlock> equivalenceClass = new HashSet<BasicBlock>();
			for (BasicBlock b : dom.keySet()) {
				if (dom.get(b).containsAll(equivalenceClassDescriptor) && equivalenceClassDescriptor.containsAll(dom.get(b))) {
					equivalenceClass.add(b);
				}
			}
			todo.removeAll(equivalenceClass);
			PartialBlockOrderNode node = new PartialBlockOrderNode(equivalenceClass, equivalenceClassDescriptor);
			nodes.add(node);
			if (node.getElements().contains(proc.getRootNode())) rootNode = node;
		}

		for (PartialBlockOrderNode node : nodes) {
			bestFitParent(node, nodes);
		}

		//actually, we could both loops ... but for now, we don't
		//to do some debug printing in the middle
//		rootNode = new PartialBlockOrderNode(proc.getRootNode(), dom.get(proc.getRootNode()));
//		for (Entry<BasicBlock, HashSet<BasicBlock>>  entry : dom.entrySet()) {
//			rootNode.insert(entry.getKey(), entry.getValue());
//		}
	}

	private void bestFitParent(PartialBlockOrderNode n, LinkedList<PartialBlockOrderNode> nodes) {

		PartialBlockOrderNode bestFit = null;

		for (PartialBlockOrderNode p : nodes) {
			if (p==n) continue;
			if (n.getUnavoidables().containsAll(p.getUnavoidables())) {
				if (bestFit==null || p.getUnavoidables().containsAll(bestFit.getUnavoidables())) {
					bestFit = p;
				}
			}
		}

		if (bestFit != null) {
			n.connectParent(bestFit);
		}

	}

	public Set<BasicBlock> getEffectualSet(){
		return rootNode.getLeafRepresentatives();
	}

	public Set<BasicBlock> getRootSet(){
		return this.rootNode.getElements();
	}

	public PartialBlockOrderNode getRoot(){
		return this.rootNode;
	}

	public PartialBlockOrderNode findNode(BasicBlock b) {
		LinkedList<PartialBlockOrderNode> todo = new LinkedList<PartialBlockOrderNode>();
		LinkedList<PartialBlockOrderNode> done = new LinkedList<PartialBlockOrderNode>();
		todo.add(this.rootNode);
		while(!todo.isEmpty()) {
			PartialBlockOrderNode current = todo.removeFirst();
			if (current.currentClass.contains(b)) {
				return current;
			}
			for (PartialBlockOrderNode next : current.successors) {
				if (!done.contains(next) && !todo.contains(next)) {
					todo.add(next);
				}
			}

		}
		return null;
	}

	private static void computeDominators(BasicBlock b, HashMap<BasicBlock, HashSet<BasicBlock>> dominators, boolean forward) {

		LinkedList<BasicBlock> todo = new LinkedList<BasicBlock>();
		LinkedList<BasicBlock> done = new LinkedList<BasicBlock>();

		if (b!=null) todo.add(b);

		while (!todo.isEmpty()) {
			BasicBlock current = todo.removeLast();
			//check if all predecessors have been processed already.
			//if not, add the block to the end of the cue and start over
			boolean allGood = true;
			for (BasicBlock prev : getNext(current, !forward)) {
				if (!done.contains(prev)) {
					allGood=false;
					break;
				}
			}
			if (!allGood){
				todo.addFirst(current);
				continue;
			}
			//if all predecessors have been processed,
			//we can compute the dominators list by
			//intersecting the list of all predecessors
			HashSet<BasicBlock> currentDom = null;
			for (BasicBlock prev : getNext(current, !forward)) {
				if (currentDom == null) {
					currentDom = new HashSet<BasicBlock>(dominators.get(prev));
				} else {
					//retainAll computes the intersection of the two sets.
					currentDom.retainAll(dominators.get(prev));
				}
			}

			//special case, only occurs for the root/sink
			if (currentDom == null) {
				currentDom = new HashSet<BasicBlock>();
			}

			currentDom.add(current); //of course, a block dominates itself
			dominators.put(current, currentDom);
			done.add(current);

			for (BasicBlock next : getNext(current, forward)) {
				if (!todo.contains(next) && !done.contains(next)) {
					todo.addLast(next);
				}
			}

		}
	}
	/*
	 * computes this intersection of two hashsets.
	 */

	private static HashSet<BasicBlock> getNext(BasicBlock current, boolean forward) {
		HashSet<BasicBlock> nextblocks = current.getSuccessors();
		if (!forward) nextblocks = current.getPredecessors();
		return nextblocks;
	}

}


text:
'use strict';

describe('Directive', function() {

    var element, scope;

    function compileDirective(tpl) {
        inject(function ($compile) {
            element = $compile(tpl)(scope);
            element.appendTo(document.body);
        });
        scope.$digest();
    }

    describe('aclSref', function () {

        var statesTested, isAllowed;

        beforeEach(function () {
            angular.mock.module('directives', function ($provide) {
                $provide.provider('AppControl', function () {
                    this.$get = function () {
                        return {
                            isAllowed: function (state) {
                                statesTested.push(state);
                                return isAllowed;
                            },
                        };
                    };
                });
            });
        });

        beforeEach(inject(function ($rootScope) {
            scope = $rootScope.$new();
        }));

        it('should hide and show', function () {
            statesTested = [];
            isAllowed = true;
            compileDirective('

');
            expect(element.css('display')).toBe('block');
            expect(statesTested).toEqual([ 'state1', 'state2' ]);

            statesTested = [];
            isAllowed = false;
            compileDirective('

');
            expect(element.css('display')).toBe('none');
            expect(statesTested).toEqual([ 'state1', 'state2' ]);
        });

    });

    describe('onKeyEnter', function () {

        beforeEach(angular.mock.module('directives'));

        beforeEach(inject(function ($rootScope) {
            scope = $rootScope.$new();
            scope.execute = function (value) {
                scope.executed = value;
            };
        }));

        it('should execute on enter key', function () {
            scope.executed = false;
            compileDirective('<input on-key-enter="execute(true)">');

            var e = jQuery.Event('keypress');
            e.keyCode = 42;
            element.trigger(e);
            expect(scope.executed).toBeFalsy();

            var e = jQuery.Event('keypress');
            e.keyCode = 13;
            element.trigger(e);
            expect(scope.executed).toBeTruthy();
        });

    });

    describe('focusOn', function () {

        beforeEach(angular.mock.module('directives'));

        beforeEach(inject(function ($rootScope) {
            scope = $rootScope.$new();
        }));

        it('should set focus', inject(function ($timeout) {
            scope.setFocus = false;
            compileDirective('<input focus-on="setFocus">');
            expect(scope.setFocus).toBeFalsy();
            expect(element[0]).not.toBe(document.activeElement);

            scope.setFocus = true;
            compileDirective('<input focus-on="setFocus">');
            $timeout.flush();
            expect(scope.setFocus).toBeFalsy();
            expect(element[0]).toBe(document.activeElement);
        }));

    });

    describe('sidebar', function () {

        beforeEach(angular.mock.module('directives'));

        beforeEach(inject(function ($rootScope) {
            scope = $rootScope.$new();
        }));

        it('should set fixed position for md sidebar in lg window', function () {
            var style = $('');
            style.html(
                '.hidden-lg { display: none !important; } '
                + '.hidden-md { display: block !important; } '
                + '.hidden-sm { display: block !important; } '
                + '.hidden-xs { display: block !important; } '
            );
            style.appendTo($('head'));

            compileDirective('

');
            expect(element.css('position')).toBe('fixed');
        });

        it('should set fixed position for md sidebar in md window', function () {
            var style = $('');
            style.html(
                '.hidden-lg { display: block !important; } '
                + '.hidden-md { display: none !important; } '
                + '.hidden-sm { display: block !important; } '
                + '.hidden-xs { display: block !important; } '
            );
            style.appendTo($('head'));

            compileDirective('

');
            expect(element.css('position')).toBe('fixed');
        });

        it('should set static position for md sidebar in sm window', function () {
            var style = $('');
            style.html(
                '.hidden-lg { display: block !important; } '
                + '.hidden-md { display: block !important; } '
                + '.hidden-sm { display: none !important; } '
                + '.hidden-xs { display: block !important; } '
            );
            style.appendTo($('head'));

            compileDirective('

');
            expect(element.css('position')).toBe('static');
        });

        it('should set static position for md sidebar in xs window', function () {
            var style = $('');
            style.html(
                '.hidden-lg { display: block !important; } '
                + '.hidden-md { display: block !important; } '
                + '.hidden-sm { display: block !important; } '
                + '.hidden-xs { display: none !important; } '
            );
            style.appendTo($('head'));

            compileDirective('

');
            expect(element.css('position')).toBe('static');
        });

    });

});


text:
package fmts

import (
	"encoding/json"
	"fmt"
	"path/filepath"
	"strconv"

	"github.com/go-openapi/swag"

	"gopkg.in/yaml.v2"
)

// YAMLMatcher matches yaml
func YAMLMatcher(path string) bool {
	ext := filepath.Ext(path)
	return ext == ".yaml" || ext == ".yml"
}

// YAMLToJSON converts YAML unmarshaled data into json compatible data
func YAMLToJSON(data interface{}) (json.RawMessage, error) {
	jm, err := transformData(data)
	if err != nil {
		return nil, err
	}
	b, err := swag.WriteJSON(jm)
	return json.RawMessage(b), err
}

func BytesToYAMLDoc(data []byte) (interface{}, error) {
	var document map[interface{}]interface{}
	if err := yaml.Unmarshal(data, &document); err != nil {
		return nil, err
	}

	return document, nil
}

func transformData(in interface{}) (out interface{}, err error) {
	switch in.(type) {
	case map[interface{}]interface{}:
		o := make(map[string]interface{})
		for k, v := range in.(map[interface{}]interface{}) {
			sk := ""
			switch k.(type) {
			case string:
				sk = k.(string)
			case int:
				sk = strconv.Itoa(k.(int))
			default:
				return nil, fmt.Errorf("types don't match: expect map key string or int get: %T", k)
			}
			v, err = transformData(v)
			if err != nil {
				return nil, err
			}
			o[sk] = v
		}
		return o, nil
	case []interface{}:
		in1 := in.([]interface{})
		len1 := len(in1)
		o := make([]interface{}, len1)
		for i := 0; i < len1; i++ {
			o[i], err = transformData(in1[i])
			if err != nil {
				return nil, err
			}
		}
		return o, nil
	}
	return in, nil
}

// YAMLDoc loads a yaml document from either http or a file and converts it to json
func YAMLDoc(path string) (json.RawMessage, error) {
	yamlDoc, err := YAMLData(path)
	if err != nil {
		return nil, err
	}

	data, err := YAMLToJSON(yamlDoc)
	if err != nil {
		return nil, err
	}

	return json.RawMessage(data), nil
}

// YAMLData loads a yaml document from either http or a file
func YAMLData(path string) (interface{}, error) {
	data, err := swag.LoadFromFileOrHTTP(path)
	if err != nil {
		return nil, err
	}

	return BytesToYAMLDoc(data)
}


text:
<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Judite\Models\Student;
use App\Judite\Models\Exchange;
use App\Judite\Models\Enrollment;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class CreateExchangeTest extends TestCase
{
    use DatabaseTransactions;

    protected $fromEnrollment;
    protected $toEnrollment;

    public function setUp(): void
    {
        parent::setUp();
        $this->enableExchangesPeriod();
        $this->fromEnrollment = factory(Enrollment::class)->create();
        $this->toEnrollment = factory(Enrollment::class)->create([
            'course_id' => $this->fromEnrollment->course->id,
        ]);
    }

    /** @test */
    public function a_student_can_propose_a_shift_exchange()
    {
        $requestData = ['to_enrollment_id' => $this->toEnrollment->id];

        $response = $this->actingAs($this->fromEnrollment->student->user)
            ->post(route('exchanges.store', $this->fromEnrollment->id), $requestData);

        $response->assertRedirect();
        $this->assertEquals(1, Exchange::count());
        $actualExchange = Exchange::first();
        $this->assertEquals($this->fromEnrollment->id, $actualExchange->from_enrollment_id);
        $this->assertEquals($this->toEnrollment->id, $actualExchange->to_enrollment_id);
    }

    /** @test */
    public function a_student_may_not_propose_a_shift_exchange_of_a_third_party_enrollment()
    {
        $unauthorizedStudent = factory(Student::class)->create();
        $requestData = ['to_enrollment_id' => $this->toEnrollment->id];

        $response = $this->actingAs($unauthorizedStudent->user)
            ->post(route('exchanges.store', $this->fromEnrollment->id), $requestData);

        $response->assertStatus(404);
        $this->assertEquals(0, Exchange::count());
    }

    /** @test */
    public function unauthenticated_users_may_not_create_exchanges()
    {
        $requestData = ['to_enrollment_id' => $this->toEnrollment->id];

        $response = $this->post(route('exchanges.store', $this->fromEnrollment->id), $requestData);

        $response->assertRedirect(route('login'));
        $this->assertEquals(0, Exchange::count());
    }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="/css/admin.css" rel="stylesheet" type="text/css" />

<link type="text/css" rel="stylesheet" href="/js/formValidator/style/validatorAuto.css" />

当前位置:帐号管理 > 管理员添加

    	<form action="" method="post" name="form1" id="form1" onsubmit="return $.formValidator.pageIsValid('1')">

管理员添加

登录名:(只读,不能修改)

                    <input type="hidden" name="SYSUser.id" value="${data.id}" />
            		<input name="SYSUser.username" id="username" class="input-box site-box-w" type="text"  value="${data.username}" readonly="readonly" />

密码:(如果不修改,请留空)

            		<input name="password" id="password" class="input-box site-box-w" type="text" />

管理员组:(要添加的管理员属于哪个管理员组)

            		<select name="SYSUser.group_id" id="group_id">
					<#list groups as group>
                    <option value="${group.id}" ${HTML.selected(group.id?string, data.group_id?string)}>${group.name}</option>
                    </#list>
					</select>

真实姓名:(必填)

            		<input name="SYSUser.realname" type="text" id="realname"  class="input-box site-box-w" value="${data.realname!""}" />

性别:

	            	<input name="SYSUser.sex" type="radio" value="1" ${HTML.checked(true, data.sex)} />男
	            	<input name="SYSUser.sex" type="radio" value="0" ${HTML.checked(false, data.sex)} />女

电话:

            		<input name="SYSUser.telphone" id="telphone" class="input-box site-box-w" type="text" value="${data.telphone!""}" />

<input type="submit" id="submitBtn" name="submit" value="保存修改" />

		</form>


text:
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt.

using System;
using System.Collections.Generic;

namespace Sce.Atf.Adaptation
{
    ///
    /// Interface for types whose instances can be decorated
    public interface IDecoratable
    {
        ///
        /// Gets all decorators of the specified type
        /// <param name="type">Decorator type</param>
        /// <returns>Enumeration of non-null decorators that are of the specified type. The enumeration may be empty.</returns>
        IEnumerable<object> GetDecorators(Type type);
    }
}


text:
package com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.Presentation;
import com.intellij.openapi.roots.ui.configuration.artifacts.ArtifactEditorEx;
import com.intellij.openapi.roots.ui.configuration.artifacts.sourceItems.SourceItemsTree;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.packaging.ui.PackagingSourceItem;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author nik
 */
public class PutSourceItemIntoDefaultLocationAction extends PutIntoDefaultLocationActionBase {
  public PutSourceItemIntoDefaultLocationAction(SourceItemsTree sourceItemsTree, ArtifactEditorEx artifactEditor) {
    super(sourceItemsTree, artifactEditor);
  }

  @Override
  public void update(AnActionEvent e) {
    final List<PackagingSourceItem> items = mySourceItemsTree.getSelectedItems();
    boolean enabled = false;
    final Presentation presentation = e.getPresentation();
    if (!items.isEmpty()) {
      enabled = true;
      Set<String> paths = new HashSet<String>();
      for (PackagingSourceItem item : items) {
        final String path = getDefaultPath(item);
        if (path == null) {
          enabled = false;
          break;
        }
        paths.add(StringUtil.trimStart(StringUtil.trimEnd(path, "/"), "/"));
      }
      presentation.setText("Put into " + getTargetLocationText(paths));
    }
    presentation.setVisible(enabled);
    presentation.setEnabled(enabled);
  }

  @Override
  public void actionPerformed(AnActionEvent e) {
    myArtifactEditor.getLayoutTreeComponent().putIntoDefaultLocations(mySourceItemsTree.getSelectedItems());
  }
}


text:
<?php

declare(strict_types=1);

namespace sad_spirit\pg_wrapper;

/**
 * Class representing a prepared statement
 */
class PreparedStatement
{
    /**
     * Used to generate statement names for pg_prepare()
     * @var int
     */
    protected static $statementIdx = 0;

    /**
     * Connection object
     * @var Connection
     */
    private $connection;

    /**
     * SQL query text
     * @var string
     */
    private $query;

    /**
     * Statement name for pg_prepare() / pg_execute()
     * @var string|null
     */
    private $queryId;

    /**
     * Values for input parameters
     * @var array<int, mixed>
     */
    private $values = [];

    /**
     * Converters for input parameters
     * @var TypeConverter[]
     */
    private $converters = [];

    /**
     * Constructor.
     *
     * @param Connection        $connection Reference to the connection object.
     * @param string            $query      SQL query to prepare.
     * @param array<int, mixed> $paramTypes Types information used to convert input parameters.
     *
     * @throws exceptions\ServerException
     */
    public function __construct(Connection $connection, string $query, array $paramTypes = [])
    {
        $this->connection = $connection;
        $this->query      = $query;

        foreach ($paramTypes as $key => $type) {
            if (null !== $type) {
                $this->converters[$key] = $this->connection->getTypeConverter($type);
            }
        }

        $this->prepare();
    }

    /**
     * Re-prepares the statement and removes bound values in cloned object
     */
    public function __clone()
    {
        $this->queryId = null;
        $this->values  = [];
        $this->prepare();
    }

    /**
     * Actually prepares the statement with pg_prepare()
     *
     * @return $this
     * @throws exceptions\ServerException
     * @throws exceptions\RuntimeException
     */
    public function prepare(): self
    {
        if ($this->queryId) {
            throw new exceptions\RuntimeException('The statement has already been prepared');
        }

        $this->queryId = 'statement' . ++self::$statementIdx;
        if (!@pg_prepare($this->connection->getResource(), $this->queryId, $this->query)) {
            throw exceptions\ServerException::fromConnection($this->connection);
        }

        return $this;
    }

    /**
     * Manually deallocates the prepared statement
     *
     * This is usually not needed as all the prepared statements are automatically
     * deallocated when database connection is closed. Trying to call execute()
     * after deallocate() will result in an Exception.
     *
     * @return $this
     * @throws exceptions\ServerException
     * @throws exceptions\RuntimeException
     */
    public function deallocate(): self
    {
        if (!$this->queryId) {
            throw new exceptions\RuntimeException('The statement has already been deallocated');
        }

        $this->connection->execute('deallocate ' . $this->queryId);
        $this->queryId = null;

        return $this;
    }

    /**
     * Sets the value for a parameter of a prepared query
     *
     * @param int   $paramNum Parameter number, 1-based
     * @param mixed $value    Parameter value
     * @param mixed $type     Type name / converter object to use for converting to DB type
     * @return $this
     *
     * @throws exceptions\OutOfBoundsException
     */
    public function bindValue(int $paramNum, $value, $type = null): self
    {
        if ($paramNum < 1) {
            throw new exceptions\OutOfBoundsException(sprintf(
                '%s: parameter number should be an integer >= 1, %d given',
                __METHOD__,
                $paramNum
            ));
        }
        $this->values[$paramNum - 1] = $value;
        if (null !== $type) {
            $this->converters[$paramNum - 1] = $this->connection->getTypeConverter($type);
        }

        return $this;
    }

    /**
     * Binds a variable to a parameter of a prepared query
     *
     * @param int   $paramNum Parameter number, 1-based
     * @param mixed $param    Variable to bind
     * @param mixed $type     Type name / converter object to use for converting to DB type
     * @return $this
     *
     * @throws exceptions\OutOfBoundsException
     */
    public function bindParam(int $paramNum, &$param, $type = null): self
    {
        if ($paramNum < 1) {
            throw new exceptions\OutOfBoundsException(sprintf(
                '%s: parameter number should be an integer >= 1, %d given',
                __METHOD__,
                $paramNum
            ));
        }
        $this->values[$paramNum - 1] =& $param;
        if (null !== $type) {
            $this->converters[$paramNum - 1] = $this->connection->getTypeConverter($type);
        }

        return $this;
    }

    /**
     * Executes a prepared query
     *
     * @param array $params      Input parameters for query, will override those bound by
     *                           bindValue() and bindParam() methods when provided.
     * @param array $resultTypes Types information for result fields, passed to ResultSet
     *
     * @return ResultSet Execution result.
     * @throws exceptions\TypeConversionException
     * @throws exceptions\ServerException
     * @throws exceptions\RuntimeException
     */
    public function execute(array $params = [], array $resultTypes = []): ResultSet
    {
        if (!$this->queryId) {
            throw new exceptions\RuntimeException('The statement has already been deallocated');
        }
        $this->connection->checkRollbackNotNeeded();

        if (!empty($params)) {
            $this->values = [];
            foreach (array_values($params) as $i => $value) {
                $this->bindValue($i + 1, $value);
            }
        }

        $stringParams = [];
        foreach ($this->values as $key => $value) {
            if (isset($this->converters[$key])) {
                $stringParams[$key] = $this->converters[$key]->output($value);
            } else {
                $stringParams[$key] = $this->connection->getTypeConverterFactory()
                    ->getConverterForPHPValue($value)
                    ->output($value);
            }
        }

        return ResultSet::createFromResultResource(
            @pg_execute($this->connection->getResource(), $this->queryId, $stringParams),
            $this->connection,
            $resultTypes
        );
    }
}


text:
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

cd "$DIR/../.."

catkin_make || true
sudo apt-get update
source ./devel/setup.sh
rosdep update
rosdep -y install igvc
sudo apt-get -y install qt5-default


text:
<html>
<body>
	<textarea id='comment'>TEXT</textarea>
</body>
</html>


text:
namespace GoogleARCoreInternal
{
    internal enum ApiAugmentedFaceMode
    {
        Disabled = 0,
        Mesh3D = 2,
    }
}


text:
namespace v8 {
namespace internal {

void MemoryChunk::DiscardUnusedMemory(Address addr, size_t size) {
  base::AddressRegion memory_area =
      MemoryAllocator::ComputeDiscardMemoryArea(addr, size);
  if (memory_area.size() != 0) {
    MemoryAllocator* memory_allocator = heap_->memory_allocator();
    v8::PageAllocator* page_allocator =
        memory_allocator->page_allocator(executable());
    CHECK(page_allocator->DiscardSystemPages(
        reinterpret_cast<void*>(memory_area.begin()), memory_area.size()));
  }
}

void MemoryChunk::InitializationMemoryFence() {
  base::SeqCst_MemoryFence();
#ifdef THREAD_SANITIZER
  // Since TSAN does not process memory fences, we use the following annotation
  // to tell TSAN that there is no data race when emitting a
  // InitializationMemoryFence. Note that the other thread still needs to
  // perform MemoryChunk::synchronized_heap().
  base::Release_Store(reinterpret_cast<base::AtomicWord*>(&heap_),
                      reinterpret_cast<base::AtomicWord>(heap_));
#endif
}

void MemoryChunk::DecrementWriteUnprotectCounterAndMaybeSetPermissions(
    PageAllocator::Permission permission) {
  DCHECK(permission == PageAllocator::kRead ||
         permission == PageAllocator::kReadExecute);
  DCHECK(IsFlagSet(MemoryChunk::IS_EXECUTABLE));
  DCHECK(owner_identity() == CODE_SPACE || owner_identity() == CODE_LO_SPACE);
  // Decrementing the write_unprotect_counter_ and changing the page
  // protection mode has to be atomic.
  base::MutexGuard guard(page_protection_change_mutex_);
  if (write_unprotect_counter_ == 0) {
    // This is a corner case that may happen when we have a
    // CodeSpaceMemoryModificationScope open and this page was newly
    // added.
    return;
  }
  write_unprotect_counter_--;
  DCHECK_LT(write_unprotect_counter_, kMaxWriteUnprotectCounter);
  if (write_unprotect_counter_ == 0) {
    Address protect_start =
        address() + MemoryChunkLayout::ObjectStartOffsetInCodePage();
    size_t page_size = MemoryAllocator::GetCommitPageSize();
    DCHECK(IsAligned(protect_start, page_size));
    size_t protect_size = RoundUp(area_size(), page_size);
    CHECK(reservation_.SetPermissions(protect_start, protect_size, permission));
  }
}

void MemoryChunk::SetReadable() {
  DecrementWriteUnprotectCounterAndMaybeSetPermissions(PageAllocator::kRead);
}

void MemoryChunk::SetReadAndExecutable() {
  DCHECK(!FLAG_jitless);
  DecrementWriteUnprotectCounterAndMaybeSetPermissions(
      PageAllocator::kReadExecute);
}

void MemoryChunk::SetReadAndWritable() {
  DCHECK(IsFlagSet(MemoryChunk::IS_EXECUTABLE));
  DCHECK(owner_identity() == CODE_SPACE || owner_identity() == CODE_LO_SPACE);
  // Incrementing the write_unprotect_counter_ and changing the page
  // protection mode has to be atomic.
  base::MutexGuard guard(page_protection_change_mutex_);
  write_unprotect_counter_++;
  DCHECK_LE(write_unprotect_counter_, kMaxWriteUnprotectCounter);
  if (write_unprotect_counter_ == 1) {
    Address unprotect_start =
        address() + MemoryChunkLayout::ObjectStartOffsetInCodePage();
    size_t page_size = MemoryAllocator::GetCommitPageSize();
    DCHECK(IsAligned(unprotect_start, page_size));
    size_t unprotect_size = RoundUp(area_size(), page_size);
    CHECK(reservation_.SetPermissions(unprotect_start, unprotect_size,
                                      PageAllocator::kReadWrite));
  }
}

namespace {

PageAllocator::Permission DefaultWritableCodePermissions() {
  return FLAG_jitless ? PageAllocator::kReadWrite
                      : PageAllocator::kReadWriteExecute;
}

}  // namespace

MemoryChunk* MemoryChunk::Initialize(BasicMemoryChunk* basic_chunk, Heap* heap,
                                     Executability executable) {
  MemoryChunk* chunk = static_cast<MemoryChunk*>(basic_chunk);

  base::AsAtomicPointer::Release_Store(&chunk->slot_set_[OLD_TO_NEW], nullptr);
  base::AsAtomicPointer::Release_Store(&chunk->slot_set_[OLD_TO_OLD], nullptr);
  base::AsAtomicPointer::Release_Store(&chunk->sweeping_slot_set_, nullptr);
  base::AsAtomicPointer::Release_Store(&chunk->typed_slot_set_[OLD_TO_NEW],
                                       nullptr);
  base::AsAtomicPointer::Release_Store(&chunk->typed_slot_set_[OLD_TO_OLD],
                                       nullptr);
  chunk->invalidated_slots_[OLD_TO_NEW] = nullptr;
  chunk->invalidated_slots_[OLD_TO_OLD] = nullptr;
  chunk->progress_bar_ = 0;
  chunk->set_concurrent_sweeping_state(ConcurrentSweepingState::kDone);
  chunk->page_protection_change_mutex_ = new base::Mutex();
  chunk->write_unprotect_counter_ = 0;
  chunk->mutex_ = new base::Mutex();
  chunk->young_generation_bitmap_ = nullptr;

  chunk->external_backing_store_bytes_[ExternalBackingStoreType::kArrayBuffer] =
      0;
  chunk->external_backing_store_bytes_
      [ExternalBackingStoreType::kExternalString] = 0;

  chunk->categories_ = nullptr;

  heap->incremental_marking()->non_atomic_marking_state()->SetLiveBytes(chunk,
                                                                        0);
  if (executable == EXECUTABLE) {
    chunk->SetFlag(IS_EXECUTABLE);
    if (heap->write_protect_code_memory()) {
      chunk->write_unprotect_counter_ =
          heap->code_space_memory_modification_scope_depth();
    } else {
      size_t page_size = MemoryAllocator::GetCommitPageSize();
      DCHECK(IsAligned(chunk->area_start(), page_size));
      size_t area_size =
          RoundUp(chunk->area_end() - chunk->area_start(), page_size);
      CHECK(chunk->reservation_.SetPermissions(
          chunk->area_start(), area_size, DefaultWritableCodePermissions()));
    }
  }

  if (chunk->owner()->identity() == CODE_SPACE) {
    chunk->code_object_registry_ = new CodeObjectRegistry();
  } else {
    chunk->code_object_registry_ = nullptr;
  }

  chunk->possibly_empty_buckets_.Initialize();

#ifdef V8_ENABLE_CONSERVATIVE_STACK_SCANNING
  chunk->object_start_bitmap_ = ObjectStartBitmap(chunk->area_start());
#endif

#ifdef DEBUG
  ValidateOffsets(chunk);
#endif

  return chunk;
}

size_t MemoryChunk::CommittedPhysicalMemory() {
  if (!base::OS::HasLazyCommits() || owner_identity() == LO_SPACE)
    return size();
  return high_water_mark_;
}

void MemoryChunk::SetOldGenerationPageFlags(bool is_marking) {
  if (is_marking) {
    SetFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
    SetFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
    SetFlag(MemoryChunk::INCREMENTAL_MARKING);
  } else {
    ClearFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
    SetFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
    ClearFlag(MemoryChunk::INCREMENTAL_MARKING);
  }
}

void MemoryChunk::SetYoungGenerationPageFlags(bool is_marking) {
  SetFlag(MemoryChunk::POINTERS_TO_HERE_ARE_INTERESTING);
  if (is_marking) {
    SetFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
    SetFlag(MemoryChunk::INCREMENTAL_MARKING);
  } else {
    ClearFlag(MemoryChunk::POINTERS_FROM_HERE_ARE_INTERESTING);
    ClearFlag(MemoryChunk::INCREMENTAL_MARKING);
  }
}
// -----------------------------------------------------------------------------
// MemoryChunk implementation

void MemoryChunk::ReleaseAllocatedMemoryNeededForWritableChunk() {
  if (mutex_ != nullptr) {
    delete mutex_;
    mutex_ = nullptr;
  }
  if (page_protection_change_mutex_ != nullptr) {
    delete page_protection_change_mutex_;
    page_protection_change_mutex_ = nullptr;
  }
  if (code_object_registry_ != nullptr) {
    delete code_object_registry_;
    code_object_registry_ = nullptr;
  }

  possibly_empty_buckets_.Release();
  ReleaseSlotSet<OLD_TO_NEW>();
  ReleaseSweepingSlotSet();
  ReleaseSlotSet<OLD_TO_OLD>();
  ReleaseTypedSlotSet<OLD_TO_NEW>();
  ReleaseTypedSlotSet<OLD_TO_OLD>();
  ReleaseInvalidatedSlots<OLD_TO_NEW>();
  ReleaseInvalidatedSlots<OLD_TO_OLD>();

  if (young_generation_bitmap_ != nullptr) ReleaseYoungGenerationBitmap();

  if (!IsLargePage()) {
    Page* page = static_cast<Page*>(this);
    page->ReleaseFreeListCategories();
  }
}

void MemoryChunk::ReleaseAllAllocatedMemory() {
  ReleaseAllocatedMemoryNeededForWritableChunk();
}

template V8_EXPORT_PRIVATE SlotSet* MemoryChunk::AllocateSlotSet<OLD_TO_NEW>();
template V8_EXPORT_PRIVATE SlotSet* MemoryChunk::AllocateSlotSet<OLD_TO_OLD>();

template <RememberedSetType type>
SlotSet* MemoryChunk::AllocateSlotSet() {
  return AllocateSlotSet(&slot_set_[type]);
}

SlotSet* MemoryChunk::AllocateSweepingSlotSet() {
  return AllocateSlotSet(&sweeping_slot_set_);
}

SlotSet* MemoryChunk::AllocateSlotSet(SlotSet** slot_set) {
  SlotSet* new_slot_set = SlotSet::Allocate(buckets());
  SlotSet* old_slot_set = base::AsAtomicPointer::AcquireRelease_CompareAndSwap(
      slot_set, nullptr, new_slot_set);
  if (old_slot_set != nullptr) {
    SlotSet::Delete(new_slot_set, buckets());
    new_slot_set = old_slot_set;
  }
  DCHECK(new_slot_set);
  return new_slot_set;
}

template void MemoryChunk::ReleaseSlotSet<OLD_TO_NEW>();
template void MemoryChunk::ReleaseSlotSet<OLD_TO_OLD>();

template <RememberedSetType type>
void MemoryChunk::ReleaseSlotSet() {
  ReleaseSlotSet(&slot_set_[type]);
}

void MemoryChunk::ReleaseSweepingSlotSet() {
  ReleaseSlotSet(&sweeping_slot_set_);
}

void MemoryChunk::ReleaseSlotSet(SlotSet** slot_set) {
  if (*slot_set) {
    SlotSet::Delete(*slot_set, buckets());
    *slot_set = nullptr;
  }
}

template TypedSlotSet* MemoryChunk::AllocateTypedSlotSet<OLD_TO_NEW>();
template TypedSlotSet* MemoryChunk::AllocateTypedSlotSet<OLD_TO_OLD>();

template <RememberedSetType type>
TypedSlotSet* MemoryChunk::AllocateTypedSlotSet() {
  TypedSlotSet* typed_slot_set = new TypedSlotSet(address());
  TypedSlotSet* old_value = base::AsAtomicPointer::Release_CompareAndSwap(
      &typed_slot_set_[type], nullptr, typed_slot_set);
  if (old_value != nullptr) {
    delete typed_slot_set;
    typed_slot_set = old_value;
  }
  DCHECK(typed_slot_set);
  return typed_slot_set;
}

template void MemoryChunk::ReleaseTypedSlotSet<OLD_TO_NEW>();
template void MemoryChunk::ReleaseTypedSlotSet<OLD_TO_OLD>();

template <RememberedSetType type>
void MemoryChunk::ReleaseTypedSlotSet() {
  TypedSlotSet* typed_slot_set = typed_slot_set_[type];
  if (typed_slot_set) {
    typed_slot_set_[type] = nullptr;
    delete typed_slot_set;
  }
}

template InvalidatedSlots* MemoryChunk::AllocateInvalidatedSlots<OLD_TO_NEW>();
template InvalidatedSlots* MemoryChunk::AllocateInvalidatedSlots<OLD_TO_OLD>();

template <RememberedSetType type>
InvalidatedSlots* MemoryChunk::AllocateInvalidatedSlots() {
  DCHECK_NULL(invalidated_slots_[type]);
  invalidated_slots_[type] = new InvalidatedSlots();
  return invalidated_slots_[type];
}

template void MemoryChunk::ReleaseInvalidatedSlots<OLD_TO_NEW>();
template void MemoryChunk::ReleaseInvalidatedSlots<OLD_TO_OLD>();

template <RememberedSetType type>
void MemoryChunk::ReleaseInvalidatedSlots() {
  if (invalidated_slots_[type]) {
    delete invalidated_slots_[type];
    invalidated_slots_[type] = nullptr;
  }
}

template V8_EXPORT_PRIVATE void
MemoryChunk::RegisterObjectWithInvalidatedSlots<OLD_TO_NEW>(HeapObject object);
template V8_EXPORT_PRIVATE void
MemoryChunk::RegisterObjectWithInvalidatedSlots<OLD_TO_OLD>(HeapObject object);

template <RememberedSetType type>
void MemoryChunk::RegisterObjectWithInvalidatedSlots(HeapObject object) {
  bool skip_slot_recording;

  if (type == OLD_TO_NEW) {
    skip_slot_recording = InYoungGeneration();
  } else {
    skip_slot_recording = ShouldSkipEvacuationSlotRecording();
  }

  if (skip_slot_recording) {
    return;
  }

  if (invalidated_slots<type>() == nullptr) {
    AllocateInvalidatedSlots<type>();
  }

  invalidated_slots<type>()->insert(object);
}

void MemoryChunk::InvalidateRecordedSlots(HeapObject object) {
  if (V8_DISABLE_WRITE_BARRIERS_BOOL) return;
  if (heap()->incremental_marking()->IsCompacting()) {
    // We cannot check slot_set_[OLD_TO_OLD] here, since the
    // concurrent markers might insert slots concurrently.
    RegisterObjectWithInvalidatedSlots<OLD_TO_OLD>(object);
  }

  if (!FLAG_always_promote_young_mc || slot_set_[OLD_TO_NEW] != nullptr)
    RegisterObjectWithInvalidatedSlots<OLD_TO_NEW>(object);
}

template bool MemoryChunk::RegisteredObjectWithInvalidatedSlots<OLD_TO_NEW>(
    HeapObject object);
template bool MemoryChunk::RegisteredObjectWithInvalidatedSlots<OLD_TO_OLD>(
    HeapObject object);

template <RememberedSetType type>
bool MemoryChunk::RegisteredObjectWithInvalidatedSlots(HeapObject object) {
  if (invalidated_slots<type>() == nullptr) {
    return false;
  }
  return invalidated_slots<type>()->find(object) !=
         invalidated_slots<type>()->end();
}

void MemoryChunk::AllocateYoungGenerationBitmap() {
  DCHECK_NULL(young_generation_bitmap_);
  young_generation_bitmap_ =
      static_cast<Bitmap*>(base::Calloc(1, Bitmap::kSize));
}

void MemoryChunk::ReleaseYoungGenerationBitmap() {
  DCHECK_NOT_NULL(young_generation_bitmap_);
  base::Free(young_generation_bitmap_);
  young_generation_bitmap_ = nullptr;
}

#ifdef DEBUG
void MemoryChunk::ValidateOffsets(MemoryChunk* chunk) {
  // Note that we cannot use offsetof because MemoryChunk is not a POD.
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->slot_set_) - chunk->address(),
            MemoryChunkLayout::kSlotSetOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->progress_bar_) - chunk->address(),
            MemoryChunkLayout::kProgressBarOffset);
  DCHECK_EQ(
      reinterpret_cast<Address>(&chunk->live_byte_count_) - chunk->address(),
      MemoryChunkLayout::kLiveByteCountOffset);
  DCHECK_EQ(
      reinterpret_cast<Address>(&chunk->sweeping_slot_set_) - chunk->address(),
      MemoryChunkLayout::kSweepingSlotSetOffset);
  DCHECK_EQ(
      reinterpret_cast<Address>(&chunk->typed_slot_set_) - chunk->address(),
      MemoryChunkLayout::kTypedSlotSetOffset);
  DCHECK_EQ(
      reinterpret_cast<Address>(&chunk->invalidated_slots_) - chunk->address(),
      MemoryChunkLayout::kInvalidatedSlotsOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->mutex_) - chunk->address(),
            MemoryChunkLayout::kMutexOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->concurrent_sweeping_) -
                chunk->address(),
            MemoryChunkLayout::kConcurrentSweepingOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->page_protection_change_mutex_) -
                chunk->address(),
            MemoryChunkLayout::kPageProtectionChangeMutexOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->write_unprotect_counter_) -
                chunk->address(),
            MemoryChunkLayout::kWriteUnprotectCounterOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->external_backing_store_bytes_) -
                chunk->address(),
            MemoryChunkLayout::kExternalBackingStoreBytesOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->list_node_) - chunk->address(),
            MemoryChunkLayout::kListNodeOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->categories_) - chunk->address(),
            MemoryChunkLayout::kCategoriesOffset);
  DCHECK_EQ(
      reinterpret_cast<Address>(&chunk->young_generation_live_byte_count_) -
          chunk->address(),
      MemoryChunkLayout::kYoungGenerationLiveByteCountOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->young_generation_bitmap_) -
                chunk->address(),
            MemoryChunkLayout::kYoungGenerationBitmapOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->code_object_registry_) -
                chunk->address(),
            MemoryChunkLayout::kCodeObjectRegistryOffset);
  DCHECK_EQ(reinterpret_cast<Address>(&chunk->possibly_empty_buckets_) -
                chunk->address(),
            MemoryChunkLayout::kPossiblyEmptyBucketsOffset);
}
#endif

}  // namespace internal
}  // namespace v8


text:
import React, { PropTypes, Component } from 'react'
import { View, StyleSheet, Animated } from 'react-native'
import { colors } from '~/styles'

export default class PreSplash extends Component {
  static propTypes = {}
  state = {
    rotation: new Animated.Value(0)
  }
  componentDidMount () {
    this.interval = setInterval(() => {
      Animated.sequence([
        Animated.timing(this.state.rotation, {toValue: -1, duration: 150}),
        Animated.timing(this.state.rotation, {toValue: 1, duration: 150}),
        Animated.timing(this.state.rotation, {toValue: 0, duration: 250})
      ]).start()
    }, 1000)
  }
  componentWillUnmount () {
    window.clearInterval(this.interval)
  }
  getTransform () {
    return {
      transform: [
        {
          rotate: this.state.rotation.interpolate({
            inputRange: [-1, 1],
            outputRange: ['-20deg', '20deg']
          })
        }
      ]
    }
  }
  render () {
    return (
      <View style={styles.container}>
        <Animated.Image
          style={[styles.image, this.getTransform()]}
          source={require('../../images/logo.png')} />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colors.white,
    alignItems: 'center',
    justifyContent: 'center',
  },
  image: {
    resizeMode: 'contain',
    height: 300,
  }
})


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="content-language" content="en" />
    <title>How to test properly a string var in Javascript? – VatWeb <CODE> Blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Reminder how to test properly a string var in Javascript">
    <meta name="author" content="Vincent Audebert">
    <meta name="copyright" content="© 2014 Vincent Audebert" />
    <meta name="keywords" content="javascript, string">
    <link rel="canonical" href="http://vincentaudebert.github.io/javascript/string/2014/09/11/javascript-test-string-date/">

    <meta itemprop="name" content="How to test properly a string var in Javascript? – VatWeb <CODE> Blog"/>
    <meta itemprop="description" content="You can keep liking lolcat pictures... or you can check out VatWeb coding blog and learn something new"/>
    <meta itemprop="image" content="/ico/apple-touch-icon-144-precomposed.png"/>

    <meta property="og:title" content="How to test properly a string var in Javascript? – VatWeb <CODE> Blog"/>
    <meta property="og:type" content="blog"/>
    <meta property="og:url" content="http://vincentaudebert.github.io/javascript/string/2014/09/11/javascript-test-string-date/"/>
    <meta property="og:image" content="/ico/apple-touch-icon-144-precomposed.png"/>
    <meta property="og:description" content="You can keep liking lolcat pictures... or you can check out VatWeb coding blog and learn something new"/>

    <meta name="twitter:card" content="summary">
    <meta name="twitter:url" content="http://vincentaudebert.github.io/javascript/string/2014/09/11/javascript-test-string-date/">
    <meta name="twitter:title" content="How to test properly a string var in Javascript? – VatWeb <CODE> Blog">
    <meta name="twitter:description" content="You can retweet Justin Bieber... or you can check out VatWeb coding blog and learn something new">
    <meta name="twitter:image" content="/ico/apple-touch-icon-144-precomposed.png">
    <meta name="twitter:creator" content="@vatweb">

    <link rel="stylesheet" href="/css/basscss.css" type="text/css">
    <link rel="stylesheet" href="/css/pixyll.css" type="text/css">
    <link rel="stylesheet" href="/css/solarized-dark.css" type="text/css">

    <link href="htp://fonts.googleapis.com/css?family=Merriweather:900,900italic,300,300italic" rl="stlesheet" tpe="tet/css">
    <link href="htp://fonts.googleapis.com/css?family=Lato:900,300" rl="stlesheet" tpe="tet/css">
    <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/ico/apple-touch-icon-144-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/ico/apple-touch-icon-114-precomposed.png">
    <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/ico/apple-touch-icon-72-precomposed.png">
    <link rel="apple-touch-icon-precomposed" href="/ico/apple-touch-icon-57-precomposed.png">
    <link rel="shortcut icon" href="/ico/favicon.ico">

      VatWeb <CODE> Blog

        About
RSS
Contact

How to test properly a string var in Javascript?

  Sep 11, 2014

Sometimes it's good to remind the basics.

Today, I was trying to test if a Date object that I made becoming a string using toISOString() was a string.

And I immediately thought about if(date instanceof String) but this was always false…

And then I found this post: http://stackoverflow.com/a/21605936

It was painful to see how sometimes you forget that Javascript can be crap and you need a basic reminder.

I created a little JSFiddle to show exactly what I wanted to do and to make obvious the difference between literals and objects.
But you can also see the code just here:

var date = new Date();
var dateStr = date.toISOString();

console.log(dateStr instanceof String); //false
console.log(typeof dateStr === "string"); //true

var dateStrObj = new String(dateStr);

console.log(dateStrObj instanceof String); //true
console.log(typeof dateStrObj === "string"); //false

//Recommendation
//For more security keep testing the two ways
console.log(dateStr instanceof String || typeof dateStr === "string"); //true
console.log(dateStrObj instanceof String || typeof dateStrObj === "string"); //true

Finally, another link you might find useful on the Literals Vs Objects topic: http://stackoverflow.com/questions/203739/why-does-instanceof-return-false-for-some-literals

  		Follow @vatweb

        		Vincent Audebert

        Copyright © 2014 Vincent Audebert.

          Wellington 6011, New Zealand

        Powered by Jekyll and Pixyll theme.


text:
import SignatureWidget from '../../widget/signature-external/signature-external';

const range = document.createRange();

describe('External Signature Widget instantiation', () => {
    const html = `
        <fieldset class="question simple-select ">
            <fieldset>
                <legend>
                    enter
                </legend>

                        <input type="checkbox" name="/data/f" value="agreed"
                            data-oc-external="signature" data-type-xml="string" maxlength="3999">
                        Agreed

            </fieldset>
        </fieldset>
        `;

    it('instantiates with correct question type and external attribute value', () => {
        const fragment = range.createContextualFragment(html);
        const control = fragment.querySelector('input');
        expect(control.matches(SignatureWidget.selector)).to.equal(true);
    });

    it('does not instantiate if there is more than 1 option', () => {
        const fragment = range.createContextualFragment(html);
        const label = fragment.querySelector('.option-wrapper label');
        const secondOption = label.cloneNode(true);
        secondOption.querySelector('input').value = 'Disagreed';
        fragment.querySelector('.option-wrapper').append(secondOption);
        const control = fragment.querySelector('input');
        expect(control.matches(SignatureWidget.selector)).to.equal(false);
    });

    it('does not instantiate for unsupported question types: text, number and radiobutton', () => {
        const fragment = range.createContextualFragment(html);
        const control = fragment.querySelector('input');
        ['text', 'number', 'radiobutton'].forEach((type) => {
            control.setAttribute('type', type);
            expect(control.matches(SignatureWidget.selector)).to.equal(false);
        });
    });

    it('does not instantiate for unsupported external attributes', () => {
        const fragment = range.createContextualFragment(html);
        const control = fragment.querySelector('input');
        control.removeAttribute('data-oc-external');
        expect(control.matches(SignatureWidget.selector)).to.equal(false);
        control.setAttribute('data-oc-external', 'clinicaldata');
        expect(control.matches(SignatureWidget.selector)).to.equal(false);
    });
});


text:
@interface BackGrayView : UIView

@property (nonatomic, strong) UIImageView * icon;
@property (nonatomic, strong) UILabel * companyLabel;
@property (nonatomic, strong) UIImageView * phoneIcon;
@property (nonatomic, strong) UIButton * phoneButton;
@property (nonatomic, strong) UIImageView * qqIcon;
@property (nonatomic, strong) UIButton * qqButton;
@property (nonatomic, strong) UIView * backView;

@end


text:
function changeTypeCartouche() {
	var choice = $("#type option:selected").attr('value');
	$("#cartouche2").hide();
	$("#cartouche1").show();
	if (choice == "procedure") {
		$("label[for='sortie']").text("Paramètre de sortie");
		$("#blocPostCond").show();
		$("#addParamSortie").show();

		$("#blocSortie a.moins").show();
		$("#blocSortie a.plus").show();

	} else if (choice == "fonction") {
		$("label[for='sortie']").text("Retourne");
		$("#blocPostCond").hide();
		$("#addParamSortie").hide();

		$("#blocSortie a.moins").hide();
		$("#blocSortie a.plus").hide();

		if (!$("#blocSortie textarea").length) {//Correction du bug découvert par Simon : retourne sans champ
			var nouvEntree = document.createElement("textarea");
			var br = document.createElement("br");
			nouvEntree.setAttribute("placeholder", "Retourne");
			nouvEntree.setAttribute("class", "form-control");
			nouvEntree.setAttribute("cols", "40");
			nouvEntree.setAttribute("rows", "1");
			nouvEntree.setAttribute("name", "sortie1");
			$("#blocSortie").append(nouvEntree);
			$("#blocSortie").append(br);
			$("#blocSortie textarea:last").hide().fadeIn("slow");
		}
	} else {
		$("#cartouche1").hide();
		$("#cartouche2").show();
	}

}

function addInput(o) {
	var parent = $(o).parent();
	var br = document.createElement("br");

	var id = $(parent).attr("id");
	var name;
	var placeholder;

	switch(id) {
	case "blocEntree":
		name = "entree";
		placeholder = "Paramètre d'entrée";
		break;

	case "blocSortie":
		name = "sortie";
		placeholder = "Paramètre de sortie";
		break;

	case "blocPreCond":
		name = "precondition";
		placeholder = "Pre-condition";
		break;

	case "blocPostCond":
		name = "postcondition";
		placeholder = "Post-condition";
		break;
	}

	var lastName = $("#" + id + " textarea:last").attr("name");
	if (lastName) {
		var number = lastName.replace(name, "");
		number++;
	} else {
		var number = 1;
		$("#"+id+ " br").remove();
	}
	if (number > 10)
		return;
	var nouvEntree = document.createElement("textarea");
	nouvEntree.setAttribute("placeholder", placeholder);
	nouvEntree.setAttribute("class", "form-control");
	nouvEntree.setAttribute("cols", "40");
	nouvEntree.setAttribute("rows", "1");
	nouvEntree.setAttribute("name", name + number);
	$("#" + id).append(nouvEntree);
	$("#" + id).append(br);
	$("#" + id + " textarea:last").hide().fadeIn("slow");

	var id = $(parent).attr("id");
	$("#" + id + " a.moins").show();

}

$(function() {

	$("a.plus").click(function() {
		addInput(this);
	});

});

function removeInput(o) {
	var parent = $(o).parent();
	var id = $(parent).attr("id");
	$("#" + id + " textarea:last").remove();
	if (!$("#" + id + " textarea").length) {
		$("#" + id + " a.moins").hide();
		var br = document.createElement("br");
		$("#"+id).append(br);
	} else {
		$("#" + id + " br:last").remove();
	}
}

$(function() {
	$("a.moins").click(function() {
		removeInput(this);
	});
});

//Pour afficher correctement le formulaire lors de l'actualisation
$(function() {
	changeTypeCartouche();
});


text:
package swt

import "github.com/timob/javabind"

type CustomControlEditorInterface interface {
	JavaLangObjectInterface

	// public void dispose()
	Dispose()

	// public org.eclipse.swt.widgets.Control getEditor()
	GetEditor() *WidgetsControl

	// public void layout()
	Layout()

	// public void setEditor(org.eclipse.swt.widgets.Control)
	SetEditor(a WidgetsControlInterface)
}

type CustomControlEditor struct {
	JavaLangObject
}

// public org.eclipse.swt.custom.ControlEditor(org.eclipse.swt.widgets.Composite)
func NewCustomControlEditor(a WidgetsCompositeInterface) (*CustomControlEditor) {
	conv_a := javabind.NewGoToJavaCallable()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}

	obj, err := javabind.GetEnv().NewObject("org/eclipse/swt/custom/ControlEditor", conv_a.Value().Cast("org/eclipse/swt/widgets/Composite"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()
	x := &CustomControlEditor{}
	x.Callable = &javabind.Callable{obj}
	return x
}

// public void dispose()
func (jbobject *CustomControlEditor) Dispose()  {
	_, err := jbobject.CallMethod(javabind.GetEnv(), "dispose", javabind.Void)
	if err != nil {
		panic(err)
	}

}

// public org.eclipse.swt.widgets.Control getEditor()
func (jbobject *CustomControlEditor) GetEditor() *WidgetsControl {
	jret, err := jbobject.CallMethod(javabind.GetEnv(), "getEditor", "org/eclipse/swt/widgets/Control")
	if err != nil {
		panic(err)
	}
	retconv := javabind.NewJavaToGoCallable()
	dst := &javabind.Callable{}
	retconv.Dest(dst)
	if err := retconv.Convert(javabind.ObjectRef(jret)); err != nil {
		panic(err)
	}
	retconv.CleanUp()
	unique_x := &WidgetsControl{}
	unique_x.Callable = dst
	return unique_x
}

// public void layout()
func (jbobject *CustomControlEditor) Layout()  {
	_, err := jbobject.CallMethod(javabind.GetEnv(), "layout", javabind.Void)
	if err != nil {
		panic(err)
	}

}

// public void setEditor(org.eclipse.swt.widgets.Control)
func (jbobject *CustomControlEditor) SetEditor(a WidgetsControlInterface)  {
	conv_a := javabind.NewGoToJavaCallable()
	if err := conv_a.Convert(a); err != nil {
		panic(err)
	}
	_, err := jbobject.CallMethod(javabind.GetEnv(), "setEditor", javabind.Void, conv_a.Value().Cast("org/eclipse/swt/widgets/Control"))
	if err != nil {
		panic(err)
	}
	conv_a.CleanUp()

}

func (jbobject *CustomControlEditor) HorizontalAlignment() int {
	jret, err := jbobject.GetField(javabind.GetEnv(), "horizontalAlignment", javabind.Int)
	if err != nil {
		panic(err)
	}
	return jret.(int)
}

func (jbobject *CustomControlEditor) SetFieldHorizontalAlignment(val int) {
	err := jbobject.SetField(javabind.GetEnv(), "horizontalAlignment", val)
	if err != nil {
		panic(err)
	}

}

func (jbobject *CustomControlEditor) GrabHorizontal() bool {
	jret, err := jbobject.GetField(javabind.GetEnv(), "grabHorizontal", javabind.Boolean)
	if err != nil {
		panic(err)
	}
	return jret.(bool)
}

func (jbobject *CustomControlEditor) SetFieldGrabHorizontal(val bool) {
	err := jbobject.SetField(javabind.GetEnv(), "grabHorizontal", val)
	if err != nil {
		panic(err)
	}

}

func (jbobject *CustomControlEditor) MinimumWidth() int {
	jret, err := jbobject.GetField(javabind.GetEnv(), "minimumWidth", javabind.Int)
	if err != nil {
		panic(err)
	}
	return jret.(int)
}

func (jbobject *CustomControlEditor) SetFieldMinimumWidth(val int) {
	err := jbobject.SetField(javabind.GetEnv(), "minimumWidth", val)
	if err != nil {
		panic(err)
	}

}

func (jbobject *CustomControlEditor) VerticalAlignment() int {
	jret, err := jbobject.GetField(javabind.GetEnv(), "verticalAlignment", javabind.Int)
	if err != nil {
		panic(err)
	}
	return jret.(int)
}

func (jbobject *CustomControlEditor) SetFieldVerticalAlignment(val int) {
	err := jbobject.SetField(javabind.GetEnv(), "verticalAlignment", val)
	if err != nil {
		panic(err)
	}

}

func (jbobject *CustomControlEditor) GrabVertical() bool {
	jret, err := jbobject.GetField(javabind.GetEnv(), "grabVertical", javabind.Boolean)
	if err != nil {
		panic(err)
	}
	return jret.(bool)
}

func (jbobject *CustomControlEditor) SetFieldGrabVertical(val bool) {
	err := jbobject.SetField(javabind.GetEnv(), "grabVertical", val)
	if err != nil {
		panic(err)
	}

}

func (jbobject *CustomControlEditor) MinimumHeight() int {
	jret, err := jbobject.GetField(javabind.GetEnv(), "minimumHeight", javabind.Int)
	if err != nil {
		panic(err)
	}
	return jret.(int)
}

func (jbobject *CustomControlEditor) SetFieldMinimumHeight(val int) {
	err := jbobject.SetField(javabind.GetEnv(), "minimumHeight", val)
	if err != nil {
		panic(err)
	}

}