text:
from __future__ import print_function
from setuptools import setup, find_packages, Extension
import os
from distutils.errors import DistutilsSetupError
from distutils import log
from distutils.dep_util import newer_group
from distutils.core import Command
import pkg_resources
import platform
import sys

needs_pytest = {'pytest', 'test'}.intersection(sys.argv)
pytest_runner = ['pytest_runner'] if needs_pytest else []
needs_wheel = {'bdist_wheel'}.intersection(sys.argv)
wheel = ['wheel'] if needs_wheel else []

# use Cython if available, else try use pre-generated .cpp sources
cython_min_version = '0.24'
try:
    pkg_resources.require("cython >= %s" % cython_min_version)
except pkg_resources.ResolutionError:
    with_cython = False
    log.info('Distribution mode: Compiling from Cython-generated .cpp sources.')
    from setuptools.command.build_ext import build_ext
else:
    with_cython = True
    log.info('Development mode: Compiling Cython modules from .pyx sources.')
    from Cython.Distutils import build_ext

class custom_build_ext(build_ext):
    """ Custom 'build_ext' command which allows to pass compiler-specific
    'extra_compile_args', 'define_macros' and 'undef_macros' options.
    """

    def finalize_options(self):
        build_ext.finalize_options(self)
        if self.compiler is None:
            # we use this variable with tox to build using GCC on Windows.
            # https://bitbucket.org/hpk42/tox/issues/274/specify-compiler
            self.compiler = os.environ.get("DISTUTILS_COMPILER", None)
        if self.compiler == "mingw32":
            # workaround for virtualenv changing order of libary_dirs on
            # Windows, which makes gcc fail to link with the correct libpython
            # https://github.com/mingwpy/mingwpy.github.io/issues/31
            self.library_dirs.insert(0, os.path.join(sys.exec_prefix, 'libs'))

    def build_extension(self, ext):
        sources = ext.sources
        if sources is None or not isinstance(sources, (list, tuple)):
            raise DistutilsSetupError(
                  "in 'ext_modules' option (extension '%s'), "
                  "'sources' must be present and must be "
                  "a list of source filenames" % ext.name)
        sources = list(sources)

        ext_path = self.get_ext_fullpath(ext.name)
        depends = sources + ext.depends
        if not (self.force or newer_group(depends, ext_path, 'newer')):
            log.debug("skipping '%s' extension (up-to-date)", ext.name)
            return
        else:
            log.info("building '%s' extension", ext.name)

        # do compiler specific customizations
        compiler_type = self.compiler.compiler_type

        if isinstance(ext.extra_compile_args, dict):
            extra_args_dict = ext.extra_compile_args or {}
            if compiler_type in extra_args_dict:
                extra_args = extra_args_dict[compiler_type]
            else:
                extra_args = extra_args_dict.get("default", [])
        else:
            extra_args = ext.extra_compile_args or []

        if isinstance(ext.define_macros, dict):
            macros_dict = ext.define_macros or {}
            if compiler_type in macros_dict:
                macros = macros_dict[compiler_type]
            else:
                macros = macros_dict.get("default", [])
        else:
            macros = ext.define_macros or []

        if isinstance(ext.undef_macros, dict):
            undef_macros_dict = ext.undef_macros
            for tp, undef in undef_macros_dict.items():
                if tp == compiler_type:
                    macros.append((undef,))
        else:
            for undef in ext.undef_macros:
                macros.append((undef,))

        # compile the source code to object files.
        objects = self.compiler.compile(sources,
                                        output_dir=self.build_temp,
                                        macros=macros,
                                        include_dirs=ext.include_dirs,
                                        debug=self.debug,
                                        extra_postargs=extra_args,
                                        depends=ext.depends)

        # Now link the object files together into a "shared object"
        if ext.extra_objects:
            objects.extend(ext.extra_objects)
        # TODO: do compiler-specific extra link args?
        extra_args = ext.extra_link_args or []

        # Detect target language, if not provided
        language = ext.language or self.compiler.detect_language(sources)

        self.compiler.link_shared_object(
            objects, ext_path,
            libraries=self.get_libraries(ext),
            library_dirs=ext.library_dirs,
            runtime_library_dirs=ext.runtime_library_dirs,
            extra_postargs=extra_args,
            export_symbols=self.get_export_symbols(ext),
            debug=self.debug,
            build_temp=self.build_temp,
            target_lang=language)

extensions = [
    Extension(
        "compreffor._compreffor",
        sources=[
            os.path.join('src', 'cython', (
                '_compreffor' + ('.pyx' if with_cython else '.cpp'))),
            os.path.join('src', 'cxx', "cffCompressor.cc"),
        ],
        depends=[os.path.join('src', 'cxx', 'cffCompressor.h')],
        extra_compile_args={
            "default": [
                "-std=c++0x", "-pthread",
                "-Wextra", "-Wno-unused", "-Wno-unused-parameter",
                # pass extra compiler flags on OS X to enable support for C++11
            ] + (["-stdlib=libc++", "-mmacosx-version-min=10.7"]
                 if platform.system() == "Darwin" else []),
            "msvc": ["/EHsc", "/Zi"],
        },
        define_macros={
            # On Windows Python 2.7, pyconfig.h defines "hypot" as "_hypot",
            # This clashes with GCC's cmath, and causes compilation errors when
            # building under MinGW: http://bugs.python.org/issue11566
            "mingw32": [("_hypot", "hypot")],
        },
        language="c++",
    ),
]

class PassCommand(Command):
    """ This is used with Travis `dpl` tool so that it skips creating wheel
    packages, and simply uploads to PyPI the ones that have been previously
    built inside the manylinux1 docker container.
    """

    description = "do nothing"
    user_options = []

    def initialize_options(self):
        pass

    def finalize_options(self):
        pass

    def run(self):
        pass

with open('README.rst', 'r') as f:
    long_description = f.read()

setup_params = dict(
    name="compreffor",
    version="0.4.1",
    description="A CFF subroutinizer for fontTools.",
    long_description=long_description,
    author="Sam Fishman",
    license="Apache 2.0",
    package_dir={'': 'src/python'},
    packages=find_packages('src/python'),
    ext_modules=extensions,
    cmdclass={
        'build_ext': custom_build_ext,
        'pass': PassCommand,
    },
    setup_requires=pytest_runner + wheel,
    tests_require=[
        'pytest>=2.8',
    ],
    install_requires=[
        "fonttools>=3.1",
    ],
    entry_points={
        'console_scripts': [
            "compreffor = compreffor.__main__:main",
        ]
    },
    zip_safe=False,
    classifiers=[
        "Development Status :: 4 - Beta",
        "Environment :: Console",
        "Intended Audience :: Developers",
        "License :: OSI Approved :: Apache Software License",
        "Operating System :: OS Independent",
        "Programming Language :: Python",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 3",
        "Topic :: Multimedia :: Graphics",
        "Topic :: Multimedia :: Graphics :: Graphics Conversion",
    ],
)

if __name__ == "__main__":
    setup(**setup_params)

redpajama_set_name: RedPajamaGithub


text:
package algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-18
 * Site       : https://www.acmicpc.net/problem/11718
 */
public class Boj11718 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        while (true){
            String input = br.readLine();
            if(input != null){
                System.out.println(input);
            }else{
                break;
            }
        }

    }

}


text:
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('pdt', '0001_initial'),
    ]

    operations = [
        migrations.AddField(
            model_name='paypalpdt',
            name='mp_id',
            field=models.CharField(max_length=128, null=True, blank=True),
            preserve_default=True,
        ),
    ]


text:
package com.gdp.rabbitmq.bench;

import com.gdp.rabbitmq.task.consumer.GeneralConsumer;
import java.io.IOException;
import org.junit.After;
import org.junit.Before;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 *
 * @author zerosign
 */
public class CompleteRecycledConsumerBench {

    public CompleteRecycledConsumerBench() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
    }

    @After
    public void tearDown() {
    }

    @Test
    public void testBenchCompleteRecycledConsumer() throws IOException {

        GeneralConsumer consumer;
        consumer = new GeneralConsumer();
        consumer.setAutoAck(false);
        consumer.setQueueName("BENCH");
        consumer.prepare();
        for (long ii = 0; ii < 100000000L; ii++) {
            consumer.run();
        }

    }

}


text:
FOUNDATION_EXPORT double FakeryVersionNumber;
FOUNDATION_EXPORT const unsigned char FakeryVersionString[];


text:
package com.planet_ink.coffee_mud.Races;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Gorilla extends Monkey
{
	@Override
	public String ID()
	{
		return "Gorilla";
	}

	private final static String localizedStaticName = CMLib.lang().L("Gorilla");

	@Override
	public String name()
	{
		return localizedStaticName;
	}

	@Override
	public int shortestMale()
	{
		return 62;
	}

	@Override
	public int shortestFemale()
	{
		return 60;
	}

	@Override
	public int heightVariance()
	{
		return 12;
	}

	@Override
	public int lightestWeight()
	{
		return 220;
	}

	@Override
	public int weightVariance()
	{
		return 80;
	}

	private final static String localizedStaticRacialCat = CMLib.lang().L("Primate");

	@Override
	public String racialCategory()
	{
		return localizedStaticRacialCat;
	}

	private final String[]	racialAbilityNames			= { "ApeSpeak", "Fighter_Intimidate" };
	private final int[]		racialAbilityLevels			= { 1, 21 };
	private final int[]		racialAbilityProficiencies	= { 100, 100 };
	private final boolean[]	racialAbilityQuals			= { false, false };
	private final String[]	racialAbilityParms			= { "", "" };

	@Override
	protected String[] racialAbilityNames()
	{
		return racialAbilityNames;
	}

	@Override
	protected int[] racialAbilityLevels()
	{
		return racialAbilityLevels;
	}

	@Override
	protected int[] racialAbilityProficiencies()
	{
		return racialAbilityProficiencies;
	}

	@Override
	protected boolean[] racialAbilityQuals()
	{
		return racialAbilityQuals;
	}

	@Override
	public String[] racialAbilityParms()
	{
		return racialAbilityParms;
	}

	//  							  an ey ea he ne ar ha to le fo no gi mo wa ta wi
	private static final int[] parts={0 ,2 ,2 ,1 ,1 ,2 ,2 ,1 ,2 ,2 ,1 ,0 ,1 ,1 ,0 ,0 };

	@Override
	public int[] bodyMask()
	{
		return parts;
	}

	private static Vector<RawMaterial>	resources	= new Vector<RawMaterial>();

	@Override
	public void affectCharStats(final MOB affectedMOB, final CharStats affectableStats)
	{
		super.affectCharStats(affectedMOB, affectableStats);
		affectableStats.setRacialStat(CharStats.STAT_STRENGTH,18);
		affectableStats.setRacialStat(CharStats.STAT_DEXTERITY,16);
		affectableStats.setRacialStat(CharStats.STAT_INTELLIGENCE,1);
	}

	@Override
	public void unaffectCharStats(final MOB affectedMOB, final CharStats affectableStats)
	{
		super.unaffectCharStats(affectedMOB, affectableStats);
		affectableStats.setStat(CharStats.STAT_STRENGTH,affectedMOB.baseCharStats().getStat(CharStats.STAT_STRENGTH));
		affectableStats.setStat(CharStats.STAT_MAX_STRENGTH_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_STRENGTH_ADJ));
		affectableStats.setStat(CharStats.STAT_DEXTERITY,affectedMOB.baseCharStats().getStat(CharStats.STAT_DEXTERITY));
		affectableStats.setStat(CharStats.STAT_MAX_DEXTERITY_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_DEXTERITY_ADJ));
		affectableStats.setStat(CharStats.STAT_INTELLIGENCE,affectedMOB.baseCharStats().getStat(CharStats.STAT_INTELLIGENCE));
		affectableStats.setStat(CharStats.STAT_MAX_INTELLIGENCE_ADJ,affectedMOB.baseCharStats().getStat(CharStats.STAT_MAX_INTELLIGENCE_ADJ));
	}

	@Override
	public List<RawMaterial> myResources()
	{
		synchronized(resources)
		{
			if(resources.size()==0)
			{
				for(int i=0;i<3;i++)
				{
					resources.addElement(makeResource
					(L("a strip of @x1 hide",name().toLowerCase()),RawMaterial.RESOURCE_HIDE));
					resources.addElement(makeResource
					(L("a strip of @x1 fur",name().toLowerCase()),RawMaterial.RESOURCE_FUR,L("@x1 fur",name().toLowerCase())));
				}
				resources.addElement(makeResource
				(L("a @x1 nose",name().toLowerCase()),RawMaterial.RESOURCE_HIDE));
				for(int i=0;i<3;i++)
				{
					resources.addElement(makeResource
					(L("a pound of @x1 flesh",name().toLowerCase()),RawMaterial.RESOURCE_MEAT));
				}
				resources.addElement(makeResource
				(L("some @x1 blood",name().toLowerCase()),RawMaterial.RESOURCE_BLOOD));
				resources.addElement(makeResource
				(L("a pile of @x1 bones",name().toLowerCase()),RawMaterial.RESOURCE_BONE));
			}
		}
		return resources;
	}
}


text:
#ifndef _IP6TABLES_USER_H
#define _IP6TABLES_USER_H

#include <xtables.h>

#include "libiptc/libip6tc.h"

#ifndef IP6T_LIB_DIR
#define IP6T_LIB_DIR XT_LIB_DIR
#endif

#ifndef IP6T_SO_GET_REVISION_MATCH /* Old kernel source. */
#define IP6T_SO_GET_REVISION_MATCH	68
#define IP6T_SO_GET_REVISION_TARGET	69
#endif /* IP6T_SO_GET_REVISION_MATCH   Old kernel source */

#define ip6tables_rule_match	xtables_rule_match
#define ip6tables_match		xtables_match
#define ip6tables_target	xtables_target
#define ip6t_tryload		xt_tryload

extern int line;

/* Your shared library should call one of these. */
extern void register_match6(struct ip6tables_match *me);
extern void register_target6(struct ip6tables_target *me);

extern int do_command6(int argc, char *argv[], char **table,
		       ip6tc_handle_t *handle);

extern int for_each_chain(int (*fn)(const ip6t_chainlabel, int, ip6tc_handle_t *), int verbose, int builtinstoo, ip6tc_handle_t *handle);
extern int flush_entries(const ip6t_chainlabel chain, int verbose, ip6tc_handle_t *handle);
extern int delete_chain(const ip6t_chainlabel chain, int verbose, ip6tc_handle_t *handle);

#endif /*_IP6TABLES_USER_H*/


text:
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.ModelBinding;

namespace ygo.api.ServiceExtensions
{
    public static class ModelStateServiceExtensions
    {
        public static IEnumerable<string> Errors(this ModelStateDictionary modelState)
        {
            var allErrors = modelState.Values.SelectMany(v => v.Errors);

            return allErrors.Select(e => e.ErrorMessage);
        }
    }
}


text:
module MissionHub
  class Survey < Base

  end
end


text:
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import javax.inject.Inject;
import javax.xml.transform.stream.StreamResult;

import com.google.common.base.Optional;

import org.daisy.common.priority.Priority;
import org.daisy.common.xproc.XProcInput;
import org.daisy.common.xproc.XProcOutput;
import org.daisy.pipeline.clients.Client;
import org.daisy.pipeline.clients.ClientStorage;
import org.daisy.pipeline.clients.WebserviceStorage;
import org.daisy.pipeline.job.AbstractJob;
import org.daisy.pipeline.job.AbstractJobContext;
import org.daisy.pipeline.job.JobContextFactory;
import org.daisy.pipeline.job.JobMonitorFactory;
import org.daisy.pipeline.job.JobStorage;
import org.daisy.pipeline.script.BoundXProcScript;
import org.daisy.pipeline.script.XProcScriptService;

import org.junit.Assert;
import org.junit.Test;

public class NewDatabaseTest extends TestBase {

	@Inject
	public JobStorage jobStorage;

	@Inject
	public WebserviceStorage webserviceStorage;

	@Inject
	public XProcScriptService script;

	@Inject
	public JobMonitorFactory monitorFactory;

	@Test
	public void testClientStorage() {
		ClientStorage clientStorage = webserviceStorage.getClientStorage();
		Optional<Client> client = clientStorage.addClient("my-client", "my-secret", Client.Role.CLIENTAPP, "me@daisy.org");
		Assert.assertTrue(client.isPresent());
		Assert.assertEquals("my-client", client.get().getId());
		Iterator<? extends Client> allClients = clientStorage.getAll().iterator();
		Assert.assertTrue(allClients.hasNext());
		Assert.assertEquals(client.get(), allClients.next());
		Assert.assertFalse(allClients.hasNext());
		Assert.assertTrue(clientStorage.delete("my-client"));
		Assert.assertTrue(clientStorage.getAll().isEmpty());
	}

	@Test
	public void testJobStorage() {
		ClientStorage clientStorage = webserviceStorage.getClientStorage();
		Optional<Client> client = clientStorage.addClient("my-client", "my-secret", Client.Role.CLIENTAPP, "me@daisy.org");
		Assert.assertTrue(client.isPresent());
		JobContextFactory jobContextFactory = new JobContextFactory(client.get(), monitorFactory);
		Assert.assertEquals("my-script", script.getId());
		BoundXProcScript boundScript = BoundXProcScript.from(
			script.load(),
			new XProcInput.Builder().build(),
			new XProcOutput.Builder()
			    .withOutput("result", () -> new StreamResult(new ByteArrayOutputStream()))
			    .build());
		AbstractJobContext jobContext = jobContextFactory.newJobContext(false, "my-job", null, boundScript, null);
		Optional<AbstractJob> job = jobStorage.add(Priority.MEDIUM, jobContext);
		Assert.assertTrue(job.isPresent());
		jobStorage.remove(job.get().getId());
		Assert.assertFalse(jobStorage.iterator().hasNext());
		clientStorage.delete("my-client");
		Assert.assertTrue(clientStorage.getAll().isEmpty());
	}
}


text:
    <actionbar action="action"></actionbar>

        <content-title title="title"></content-title>

 MFL Geolocation

MFL GEOLOCATION:

                   LEGEND

                   Concentration of Facilities:

                   ● High

                   ● Moderate

                   ● Low

                    Facilities

                        County Hovered:
                            {{hoveredCounty.properties.name}}

                <leaflet
                 id="countrymap"
                  defaults="defaults"
                  width="100%"
                  markers="markers"
                  layers="layers"
                  geojson="geojson"
                  event-broadcast="events"
                  height="80vh">
                </leaflet>


text:
<component name="libraryTable">
  <library name="Gradle: spring-integration-test-3.0.2.RELEASE">
    <CLASSES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-test/3.0.2.RELEASE/6a53bf332a53612488383cc9b1b8643876ede0ef/spring-integration-test-3.0.2.RELEASE.jar!/" />
    </CLASSES>
    <JAVADOC />
    <SOURCES>
      <root url="jar://$USER_HOME$/.gradle/caches/modules-2/files-2.1/org.springframework.integration/spring-integration-test/3.0.2.RELEASE/ef718ac327fb9a9a6b50add85e0963b9d58170c1/spring-integration-test-3.0.2.RELEASE-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
title: Nodenv
date: 2022-09-28 10:00:00 +01:00
tags: [node]
description: Nodenv
---

- [Nodenv](#nodenv)
  - [Install](#install)
  - [Check available versions to install](#check-available-versions-to-install)
  - [Install a version](#install-a-version)
  - [check installed versions](#check-installed-versions)
  - [How set global version](#how-set-global-version)
  - [Set local version](#set-local-version)

------

# Nodenv

[Project page](https://github.com/nodenv/nodenv)

## Install

```
brew upgrade nodenv node-build
```

## Check available versions to install

```
nodenv install --l
```

## Install a version

```
nodenv install 10.15.3
```

## check installed versions

```
nodenv versions
```

## How set global version

```
nodenv global 16.17.1
```

## Set local version

Create a file `.node-version` with the version to use

```
// .node-version
12.16.0
```

or

```
nodenv local 13.7.0
```


text:
namespace blink {

namespace {
namespace rejection_names {
const char* kContainmentNotSatisfied =
    "Containment requirement is not satisfied.";
const char* kUnsupportedDisplay =
    "Element has unsupported display type (display: contents).";
}  // namespace rejection_names

void RecordActivationReason(Document* document,
                            DisplayLockActivationReason reason) {
  int ordered_reason = -1;

  // IMPORTANT: This number needs to be bumped up when adding
  // new reasons.
  static const int number_of_reasons = 9;

  switch (reason) {
    case DisplayLockActivationReason::kAccessibility:
      ordered_reason = 0;
      break;
    case DisplayLockActivationReason::kFindInPage:
      ordered_reason = 1;
      break;
    case DisplayLockActivationReason::kFragmentNavigation:
      ordered_reason = 2;
      break;
    case DisplayLockActivationReason::kScriptFocus:
      ordered_reason = 3;
      break;
    case DisplayLockActivationReason::kScrollIntoView:
      ordered_reason = 4;
      break;
    case DisplayLockActivationReason::kSelection:
      ordered_reason = 5;
      break;
    case DisplayLockActivationReason::kSimulatedClick:
      ordered_reason = 6;
      break;
    case DisplayLockActivationReason::kUserFocus:
      ordered_reason = 7;
      break;
    case DisplayLockActivationReason::kViewportIntersection:
      ordered_reason = 8;
      break;
    case DisplayLockActivationReason::kViewport:
    case DisplayLockActivationReason::kAny:
      NOTREACHED();
      break;
  }
  UMA_HISTOGRAM_ENUMERATION("Blink.Render.DisplayLockActivationReason",
                            ordered_reason, number_of_reasons);

  if (document && reason == DisplayLockActivationReason::kFindInPage)
    document->MarkHasFindInPageContentVisibilityActiveMatch();
}
}  // namespace

DisplayLockContext::DisplayLockContext(Element* element)
    : element_(element), document_(&element_->GetDocument()) {
  document_->GetDisplayLockDocumentState().AddDisplayLockContext(this);
  DetermineIfSubtreeHasFocus();
  DetermineIfSubtreeHasSelection();
}

void DisplayLockContext::SetRequestedState(EContentVisibility state) {
  if (state_ == state)
    return;
  state_ = state;
  switch (state_) {
    case EContentVisibility::kVisible:
      RequestUnlock();
      break;
    case EContentVisibility::kAuto:
      RequestLock(static_cast<uint16_t>(DisplayLockActivationReason::kAny));
      break;
    case EContentVisibility::kHidden:
      RequestLock(0u);
      break;
    case EContentVisibility::kHiddenMatchable:
      RequestLock(
          static_cast<uint16_t>(DisplayLockActivationReason::kAny) &
          ~static_cast<uint16_t>(DisplayLockActivationReason::kViewport));
      break;
  }
  // In a new state, we might need to either start or stop observing viewport
  // intersections.
  UpdateActivationObservationIfNeeded();

  // If we needed a deferred not intersecting signal from 'auto' mode, we can
  // set that to false, since the mode has switched to something else. If we're
  // switching _to_ 'auto' mode, this should already be false and will be a
  // no-op.
  DCHECK(state_ != EContentVisibility::kAuto ||
         !needs_deferred_not_intersecting_signal_);
  needs_deferred_not_intersecting_signal_ = false;
  UpdateLifecycleNotificationRegistration();

  // Note that we call this here since the |state_| change is a render affecting
  // state, but is tracked independently.
  NotifyRenderAffectingStateChanged();

  // Since our state changed, check if we need to create a scoped force update
  // object.
  element_->GetDocument().GetDisplayLockDocumentState().ForceLockIfNeeded(
      element_.Get());
}

void DisplayLockContext::AdjustElementStyle(ComputedStyle* style) const {
  if (state_ == EContentVisibility::kVisible)
    return;
  // If not visible, element gains style, layout, and paint containment. If
  // skipped, it also gains size containment.
  // https://wicg.github.io/display-locking/#content-visibility
  auto contain =
      style->Contain() | kContainsStyle | kContainsLayout | kContainsPaint;
  if (IsLocked())
    contain |= kContainsSize;
  style->SetContain(contain);
}

void DisplayLockContext::RequestLock(uint16_t activation_mask) {
  UpdateActivationMask(activation_mask);
  SetRenderAffectingState(RenderAffectingState::kLockRequested, true);
}

void DisplayLockContext::RequestUnlock() {
  SetRenderAffectingState(RenderAffectingState::kLockRequested, false);
}

void DisplayLockContext::UpdateActivationMask(uint16_t activatable_mask) {
  if (activatable_mask == activatable_mask_)
    return;

  bool all_activation_was_blocked = !activatable_mask_;
  bool all_activation_is_blocked = !activatable_mask;
  UpdateDocumentBookkeeping(IsLocked(), all_activation_was_blocked, IsLocked(),
                            all_activation_is_blocked);

  activatable_mask_ = activatable_mask;
}

void DisplayLockContext::UpdateDocumentBookkeeping(
    bool was_locked,
    bool all_activation_was_blocked,
    bool is_locked,
    bool all_activation_is_blocked) {
  if (!document_)
    return;

  if (was_locked != is_locked) {
    if (is_locked)
      document_->GetDisplayLockDocumentState().AddLockedDisplayLock();
    else
      document_->GetDisplayLockDocumentState().RemoveLockedDisplayLock();
  }

  bool was_locked_and_blocking = was_locked && all_activation_was_blocked;
  bool is_locked_and_blocking = is_locked && all_activation_is_blocked;
  if (was_locked_and_blocking != is_locked_and_blocking) {
    if (is_locked_and_blocking) {
      document_->GetDisplayLockDocumentState()
          .IncrementDisplayLockBlockingAllActivation();
    } else {
      document_->GetDisplayLockDocumentState()
          .DecrementDisplayLockBlockingAllActivation();
    }
  }
}

void DisplayLockContext::UpdateActivationObservationIfNeeded() {
  // If we don't have a document, then we don't have an observer so just make
  // sure we're marked as not observing anything and early out.
  if (!document_) {
    is_observed_ = false;
    return;
  }

  // We require observation if we are in 'auto' mode and we're connected to a
  // view.
  bool should_observe =
      state_ == EContentVisibility::kAuto && ConnectedToView();
  if (is_observed_ == should_observe)
    return;
  is_observed_ = should_observe;

  if (should_observe) {
    document_->GetDisplayLockDocumentState()
        .RegisterDisplayLockActivationObservation(element_);
  } else {
    document_->GetDisplayLockDocumentState()
        .UnregisterDisplayLockActivationObservation(element_);
    // If we're not listening to viewport intersections, then we can assume
    // we're not intersecting:
    // 1. We might not be connected, in which case we're not intersecting.
    // 2. We might not be in 'auto' mode. which means that this doesn't affect
    //    anything consequential but acts as a reset should we switch back to
    //    the 'auto' mode.
    SetRenderAffectingState(RenderAffectingState::kIntersectsViewport, false);
  }
}

bool DisplayLockContext::NeedsLifecycleNotifications() const {
  return needs_deferred_not_intersecting_signal_;
}

void DisplayLockContext::UpdateLifecycleNotificationRegistration() {
  if (!document_ || !document_->View()) {
    is_registered_for_lifecycle_notifications_ = false;
    return;
  }

  bool needs_notifications = NeedsLifecycleNotifications();
  if (needs_notifications == is_registered_for_lifecycle_notifications_)
    return;

  is_registered_for_lifecycle_notifications_ = needs_notifications;
  if (needs_notifications) {
    document_->View()->RegisterForLifecycleNotifications(this);
  } else {
    document_->View()->UnregisterFromLifecycleNotifications(this);
  }
}

void DisplayLockContext::Lock() {
  DCHECK(!IsLocked());
  is_locked_ = true;
  UpdateDocumentBookkeeping(false, !activatable_mask_, true,
                            !activatable_mask_);

  // If we're not connected, then we don't have to do anything else. Otherwise,
  // we need to ensure that we update our style to check for containment later,
  // layout size based on the options, and also clear the painted output.
  if (!ConnectedToView())
    return;

  // There are two ways we can get locked:
  // 1. A new content-visibility property needs us to be locked.
  // 2. We're in 'auto' mode and we are not intersecting the viewport.
  // In the first case, we are already in style processing, so we don't need to
  // invalidate style. However, in the second case we invalidate style so that
  // `AdjustElementStyle()` can be called.
  if (!document_->InStyleRecalc()) {
    element_->SetNeedsStyleRecalc(
        kLocalStyleChange,
        StyleChangeReasonForTracing::Create(style_change_reason::kDisplayLock));
  }

  // In either case, we schedule an animation. If we're already inside a
  // lifecycle update, this will be a no-op.
  ScheduleAnimation();

  // We need to notify the AX cache (if it exists) to update |element_|'s
  // children in the AX cache.
  if (AXObjectCache* cache = element_->GetDocument().ExistingAXObjectCache())
    cache->ChildrenChanged(element_);

  if (!element_->GetLayoutObject())
    return;

  // GraphicsLayer collection would normally skip layers if paint is blocked
  // by display-locking (see: CollectDrawableLayersForLayerListRecursively
  // in LocalFrameView). However, if we don't trigger this collection, then
  // we might use the cached result instead. In order to ensure we skip the
  // newly locked layers, we need to set |need_graphics_layer_collection_|
  // before marking the layer for repaint.
  if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled())
    needs_graphics_layer_collection_ = true;
  MarkPaintLayerNeedsRepaint();
}

// Should* and Did* function for the lifecycle phases. These functions control
// whether or not to process the lifecycle for self or for children.
// =============================================================================
bool DisplayLockContext::ShouldStyle(DisplayLockLifecycleTarget target) const {
  return !is_locked_ || target == DisplayLockLifecycleTarget::kSelf ||
         update_forced_ ||
         (document_->GetDisplayLockDocumentState()
              .ActivatableDisplayLocksForced() &&
          IsActivatable(DisplayLockActivationReason::kAny));
}

void DisplayLockContext::DidStyle(DisplayLockLifecycleTarget target) {
  if (target == DisplayLockLifecycleTarget::kSelf) {
    // TODO(vmpstr): This needs to be in the spec.
    if (ForceUnlockIfNeeded())
      return;

    if (!IsLocked() && state_ != EContentVisibility::kVisible) {
      UpdateActivationObservationIfNeeded();
      NotifyRenderAffectingStateChanged();
    }

    if (blocked_style_traversal_type_ == kStyleUpdateSelf)
      blocked_style_traversal_type_ = kStyleUpdateNotRequired;
  } else {
    if (element_->ChildNeedsReattachLayoutTree())
      element_->MarkAncestorsWithChildNeedsReattachLayoutTree();
    blocked_style_traversal_type_ = kStyleUpdateNotRequired;
    MarkElementsForWhitespaceReattachment();
  }
}

bool DisplayLockContext::ShouldLayout(DisplayLockLifecycleTarget target) const {
  return !is_locked_ || target == DisplayLockLifecycleTarget::kSelf ||
         update_forced_ ||
         (document_->GetDisplayLockDocumentState()
              .ActivatableDisplayLocksForced() &&
          IsActivatable(DisplayLockActivationReason::kAny));
}

void DisplayLockContext::DidLayout(DisplayLockLifecycleTarget target) {
  if (target == DisplayLockLifecycleTarget::kSelf)
    return;
  // Since we did layout on children already, we'll clear this.
  child_layout_was_blocked_ = false;
}

bool DisplayLockContext::ShouldPrePaint(
    DisplayLockLifecycleTarget target) const {
  return !is_locked_ || target == DisplayLockLifecycleTarget::kSelf ||
         update_forced_;
}

void DisplayLockContext::DidPrePaint(DisplayLockLifecycleTarget target) {
  // This is here for symmetry, but could be removed if necessary.
}

bool DisplayLockContext::ShouldPaint(DisplayLockLifecycleTarget target) const {
  // Note that forced updates should never require us to paint, so we don't
  // check |update_forced_| here. In other words, although |update_forced_|
  // could be true here, we still should not paint. This also holds for
  // kUpdating state, since updates should not paint.
  return !is_locked_ || target == DisplayLockLifecycleTarget::kSelf;
}

void DisplayLockContext::DidPaint(DisplayLockLifecycleTarget) {
  // This is here for symmetry, but could be removed if necessary.
}
// End Should* and Did* functions ==============================================

bool DisplayLockContext::IsActivatable(
    DisplayLockActivationReason reason) const {
  return activatable_mask_ & static_cast<uint16_t>(reason);
}

void DisplayLockContext::FireActivationEvent(Element* activated_element) {
  DCHECK(RuntimeEnabledFeatures::CSSContentVisibilityActivationEventEnabled());
  element_->DispatchEvent(
      *MakeGarbageCollected<RenderSubtreeActivationEvent>(*activated_element));
}

void DisplayLockContext::CommitForActivationWithSignal(
    Element* activated_element,
    DisplayLockActivationReason reason) {
  DCHECK(activated_element);
  DCHECK(element_);
  DCHECK(ConnectedToView());
  DCHECK(IsLocked());
  DCHECK(ShouldCommitForActivation(DisplayLockActivationReason::kAny));

  // TODO(vmpstr): Remove this when we have a beforematch event.
  if (RuntimeEnabledFeatures::CSSContentVisibilityActivationEventEnabled()) {
    document_->EnqueueDisplayLockActivationTask(
        WTF::Bind(&DisplayLockContext::FireActivationEvent,
                  WrapWeakPersistent(this), WrapPersistent(activated_element)));
  }

  RecordActivationReason(document_, reason);
}

void DisplayLockContext::NotifyIsIntersectingViewport() {
  // If we are now intersecting, then we are definitely not nested in a locked
  // subtree and we don't need to lock as a result.
  needs_deferred_not_intersecting_signal_ = false;
  UpdateLifecycleNotificationRegistration();
  // If we're not connected, then there is no need to change any state.
  // This could be the case if we were disconnected while a viewport
  // intersection notification was pending.
  if (ConnectedToView())
    SetRenderAffectingState(RenderAffectingState::kIntersectsViewport, true);
}

void DisplayLockContext::NotifyIsNotIntersectingViewport() {
  if (IsLocked()) {
    DCHECK(!needs_deferred_not_intersecting_signal_);
    return;
  }

  // We might have been disconnected while the intersection observation
  // notification was pending. Ensure to unregister from lifecycle
  // notifications if we're doing that, and early out.
  if (!ConnectedToView()) {
    needs_deferred_not_intersecting_signal_ = false;
    UpdateLifecycleNotificationRegistration();
    return;
  }

  // There are two situations we need to consider here:
  // 1. We are off-screen but not nested in any other lock. This means we should
  //    re-lock (also verify that the reason we're in this state is that we're
  //    activated).
  // 2. We are in a nested locked context. This means we don't actually know
  //    whether we should lock or not. In order to avoid needless dirty of the
  //    layout and style trees up to the nested context, we remain unlocked.
  //    However, we also need to ensure that we relock if we become unnested.
  //    So, we simply delay this check to the next frame (via LocalFrameView),
  //    which will call this function again and so we can perform the check
  //    again.
  auto* locked_ancestor =
      DisplayLockUtilities::NearestLockedExclusiveAncestor(*element_);
  if (locked_ancestor) {
    needs_deferred_not_intersecting_signal_ = true;
  } else {
    needs_deferred_not_intersecting_signal_ = false;
    SetRenderAffectingState(RenderAffectingState::kIntersectsViewport, false);
  }
  UpdateLifecycleNotificationRegistration();
}

bool DisplayLockContext::ShouldCommitForActivation(
    DisplayLockActivationReason reason) const {
  return IsActivatable(reason) && IsLocked();
}

void DisplayLockContext::NotifyForcedUpdateScopeStarted() {
  ++update_forced_;
  if (update_forced_ == 1) {
    TRACE_EVENT_NESTABLE_ASYNC_BEGIN0(
        TRACE_DISABLED_BY_DEFAULT("blink.debug.display_lock"), "LockForced",
        TRACE_ID_LOCAL(this));
  }

  if (IsLocked()) {
    // Now that the update is forced, we should ensure that style layout, and
    // prepaint code can reach it via dirty bits. Note that paint isn't a part
    // of this, since |update_forced_| doesn't force paint to happen. See
    // ShouldPaint().
    MarkForStyleRecalcIfNeeded();
    MarkForLayoutIfNeeded();
    MarkAncestorsForPrePaintIfNeeded();
  }
}

void DisplayLockContext::NotifyForcedUpdateScopeEnded() {
  DCHECK(update_forced_);
  --update_forced_;
  if (update_forced_ == 0) {
    TRACE_EVENT_NESTABLE_ASYNC_END0(
        TRACE_DISABLED_BY_DEFAULT("blink.debug.display_lock"), "LockForced",
        TRACE_ID_LOCAL(this));
  }
}

void DisplayLockContext::Unlock() {
  DCHECK(IsLocked());
  is_locked_ = false;
  UpdateDocumentBookkeeping(true, !activatable_mask_, false,
                            !activatable_mask_);

  if (!ConnectedToView())
    return;

  ScheduleAnimation();

  // There are a few ways we can get unlocked:
  // 1. A new content-visibility property needs us to be ulocked.
  // 2. We're in 'auto' mode and we are intersecting the viewport.
  // 3. We're activating in hidden-matchable or auto mode
  // In the first case, we are already in style processing, so we don't need to
  // invalidate style. However, in the second and third cases we invalidate
  // style so that `AdjustElementStyle()` can be called.
  // TODO(vmpstr): Case 3 needs to be reworked, since the spec no longer has a
  // notion of activation.
  if (!document_->InStyleRecalc()) {
    // Since size containment depends on the activatability state, we should
    // invalidate the style for this element, so that the style adjuster can
    // properly remove the containment.
    element_->SetNeedsStyleRecalc(
        kLocalStyleChange,
        StyleChangeReasonForTracing::Create(style_change_reason::kDisplayLock));

    // Also propagate any dirty bits that we have previously blocked.
    // If we're in style recalc, this will be handled by
    // `AdjustStyleRecalcChangeForChildren()`.
    MarkForStyleRecalcIfNeeded();
  }

  // We also need to notify the AX cache (if it exists) to update the childrens
  // of |element_| in the AX cache.
  if (AXObjectCache* cache = element_->GetDocument().ExistingAXObjectCache())
    cache->ChildrenChanged(element_);

  auto* layout_object = element_->GetLayoutObject();
  // We might commit without connecting, so there is no layout object yet.
  if (!layout_object)
    return;

  // Now that we know we have a layout object, we should ensure that we can
  // reach the rest of the phases as well.
  MarkForLayoutIfNeeded();
  MarkAncestorsForPrePaintIfNeeded();
  MarkPaintLayerNeedsRepaint();
}

void DisplayLockContext::AddToWhitespaceReattachSet(Element& element) {
  whitespace_reattach_set_.insert(&element);
}

void DisplayLockContext::MarkElementsForWhitespaceReattachment() {
  for (auto element : whitespace_reattach_set_) {
    if (!element || element->NeedsReattachLayoutTree() ||
        !element->GetLayoutObject())
      continue;

    if (Node* first_child = LayoutTreeBuilderTraversal::FirstChild(*element))
      first_child->MarkAncestorsWithChildNeedsReattachLayoutTree();
  }
  whitespace_reattach_set_.clear();
}

StyleRecalcChange DisplayLockContext::AdjustStyleRecalcChangeForChildren(
    StyleRecalcChange change) {
  // This code is similar to MarkForStyleRecalcIfNeeded, except that it acts on
  // |change| and not on |element_|. This is only called during style recalc.
  // Note that since we're already in self style recalc, this code is shorter
  // since it doesn't have to deal with dirtying self-style.
  DCHECK(document_->InStyleRecalc());

  if (reattach_layout_tree_was_blocked_) {
    change = change.ForceReattachLayoutTree();
    reattach_layout_tree_was_blocked_ = false;
  }

  if (blocked_style_traversal_type_ == kStyleUpdateDescendants)
    change = change.ForceRecalcDescendants();
  else if (blocked_style_traversal_type_ == kStyleUpdateChildren)
    change = change.EnsureAtLeast(StyleRecalcChange::kRecalcChildren);
  blocked_style_traversal_type_ = kStyleUpdateNotRequired;
  return change;
}

bool DisplayLockContext::MarkForStyleRecalcIfNeeded() {
  if (reattach_layout_tree_was_blocked_) {
    // We previously blocked a layout tree reattachment on |element_|'s
    // descendants, so we should mark it for layout tree reattachment now.
    element_->SetForceReattachLayoutTree();
    reattach_layout_tree_was_blocked_ = false;
  }
  if (IsElementDirtyForStyleRecalc()) {
    if (blocked_style_traversal_type_ > kStyleUpdateNotRequired) {
      // We blocked a traversal going to the element previously.
      // Make sure we will traverse this element and maybe its subtree if we
      // previously blocked a style traversal that should've done that.
      element_->SetNeedsStyleRecalc(
          blocked_style_traversal_type_ == kStyleUpdateDescendants
              ? kSubtreeStyleChange
              : kLocalStyleChange,
          StyleChangeReasonForTracing::Create(
              style_change_reason::kDisplayLock));
      if (blocked_style_traversal_type_ == kStyleUpdateChildren)
        element_->SetChildNeedsStyleRecalc();
      blocked_style_traversal_type_ = kStyleUpdateNotRequired;
    } else if (element_->ChildNeedsReattachLayoutTree()) {
      // Mark |element_| as style dirty, as we can't mark for child reattachment
      // before style.
      element_->SetNeedsStyleRecalc(kLocalStyleChange,
                                    StyleChangeReasonForTracing::Create(
                                        style_change_reason::kDisplayLock));
    }
    // Propagate to the ancestors, since the dirty bit in a locked subtree is
    // stopped at the locked ancestor.
    // See comment in IsElementDirtyForStyleRecalc.
    element_->MarkAncestorsWithChildNeedsStyleRecalc();
    return true;
  }
  return false;
}

bool DisplayLockContext::MarkForLayoutIfNeeded() {
  if (IsElementDirtyForLayout()) {
    // Forces the marking of ancestors to happen, even if
    // |DisplayLockContext::ShouldLayout()| returns false.
    base::AutoReset<int> scoped_force(&update_forced_, update_forced_ + 1);
    if (child_layout_was_blocked_) {
      // We've previously blocked a child traversal when doing self-layout for
      // the locked element, so we're marking it with child-needs-layout so that
      // it will traverse to the locked element and do the child traversal
      // again. We don't need to mark it for self-layout (by calling
      // |LayoutObject::SetNeedsLayout()|) because the locked element itself
      // doesn't need to relayout.
      element_->GetLayoutObject()->SetChildNeedsLayout();
      child_layout_was_blocked_ = false;
    } else {
      // Since the dirty layout propagation stops at the locked element, we need
      // to mark its ancestors as dirty here so that it will be traversed to on
      // the next layout.
      element_->GetLayoutObject()->MarkContainerChainForLayout();
    }
    return true;
  }
  return false;
}

bool DisplayLockContext::MarkAncestorsForPrePaintIfNeeded() {
  // TODO(vmpstr): We should add a compositing phase for proper bookkeeping.
  bool compositing_dirtied = MarkForCompositingUpdatesIfNeeded();

  if (IsElementDirtyForPrePaint()) {
    auto* layout_object = element_->GetLayoutObject();
    if (auto* parent = layout_object->Parent())
      parent->SetSubtreeShouldCheckForPaintInvalidation();

    // Note that if either we or our descendants are marked as needing this
    // update, then ensure to mark self as needing the update. This sets up the
    // correct flags for PrePaint to recompute the necessary values and
    // propagate the information into the subtree.
    if (needs_effective_allowed_touch_action_update_ ||
        layout_object->EffectiveAllowedTouchActionChanged() ||
        layout_object->DescendantEffectiveAllowedTouchActionChanged()) {
      // Note that although the object itself should have up to date value, in
      // order to force recalc of the whole subtree, we mark it as needing an
      // update.
      layout_object->MarkEffectiveAllowedTouchActionChanged();
    }
    return true;
  }
  return compositing_dirtied;
}

bool DisplayLockContext::MarkPaintLayerNeedsRepaint() {
  DCHECK(ConnectedToView());
  if (auto* layout_object = element_->GetLayoutObject()) {
    layout_object->PaintingLayer()->SetNeedsRepaint();
    if (!RuntimeEnabledFeatures::CompositeAfterPaintEnabled() &&
        needs_graphics_layer_collection_) {
      document_->View()->SetForeignLayerListNeedsUpdate();
      needs_graphics_layer_collection_ = false;
    }
    return true;
  }
  return false;
}

bool DisplayLockContext::MarkForCompositingUpdatesIfNeeded() {
  if (!ConnectedToView())
    return false;

  auto* layout_object = element_->GetLayoutObject();
  if (!layout_object)
    return false;

  auto* layout_box = DynamicTo<LayoutBoxModelObject>(layout_object);
  if (layout_box && layout_box->HasSelfPaintingLayer()) {
    if (layout_box->Layer()->ChildNeedsCompositingInputsUpdate() &&
        layout_box->Layer()->Parent()) {
      // Note that if the layer's child needs compositing inputs update, then
      // that layer itself also needs compositing inputs update. In order to
      // propagate the dirty bit, we need to mark this layer's _parent_ as a
      // needing an update.
      layout_box->Layer()->Parent()->SetNeedsCompositingInputsUpdate();
    }
    if (needs_compositing_requirements_update_)
      layout_box->Layer()->SetNeedsCompositingRequirementsUpdate();
    needs_compositing_requirements_update_ = false;

    if (needs_compositing_dependent_flag_update_)
      layout_box->Layer()->SetNeedsCompositingInputsUpdate();
    needs_compositing_dependent_flag_update_ = false;

    return true;
  }
  return false;
}

bool DisplayLockContext::IsElementDirtyForStyleRecalc() const {
  // The |element_| checks could be true even if |blocked_style_traversal_type_|
  // is not required. The reason for this is that the
  // blocked_style_traversal_type_ is set during the style walk that this
  // display lock blocked. However, we could dirty element style and commit
  // before ever having gone through the style calc that would have been
  // blocked, meaning we never blocked style during a walk. Instead we might
  // have not propagated the dirty bits up the tree.
  return element_->NeedsStyleRecalc() || element_->ChildNeedsStyleRecalc() ||
         element_->ChildNeedsReattachLayoutTree() ||
         blocked_style_traversal_type_ > kStyleUpdateNotRequired;
}

bool DisplayLockContext::IsElementDirtyForLayout() const {
  if (auto* layout_object = element_->GetLayoutObject())
    return layout_object->NeedsLayout() || child_layout_was_blocked_;
  return false;
}

bool DisplayLockContext::IsElementDirtyForPrePaint() const {
  if (auto* layout_object = element_->GetLayoutObject()) {
    auto* layout_box = DynamicTo<LayoutBoxModelObject>(layout_object);
    return PrePaintTreeWalk::ObjectRequiresPrePaint(*layout_object) ||
           PrePaintTreeWalk::ObjectRequiresTreeBuilderContext(*layout_object) ||
           needs_prepaint_subtree_walk_ ||
           needs_effective_allowed_touch_action_update_ ||
           needs_compositing_requirements_update_ ||
           (layout_box && layout_box->HasSelfPaintingLayer() &&
            layout_box->Layer()->ChildNeedsCompositingInputsUpdate());
  }
  return false;
}

void DisplayLockContext::DidMoveToNewDocument(Document& old_document) {
  DCHECK(element_);
  document_ = &element_->GetDocument();

  old_document.GetDisplayLockDocumentState().RemoveDisplayLockContext(this);
  document_->GetDisplayLockDocumentState().AddDisplayLockContext(this);

  if (is_observed_) {
    old_document.GetDisplayLockDocumentState()
        .UnregisterDisplayLockActivationObservation(element_);
    document_->GetDisplayLockDocumentState()
        .RegisterDisplayLockActivationObservation(element_);
  }

  // Since we're observing the lifecycle updates, ensure that we listen to the
  // right document's view.
  if (is_registered_for_lifecycle_notifications_) {
    if (old_document.View())
      old_document.View()->UnregisterFromLifecycleNotifications(this);

    if (document_->View())
      document_->View()->RegisterForLifecycleNotifications(this);
    else
      is_registered_for_lifecycle_notifications_ = false;
  }

  if (IsLocked()) {
    old_document.GetDisplayLockDocumentState().RemoveLockedDisplayLock();
    document_->GetDisplayLockDocumentState().AddLockedDisplayLock();
    if (!IsActivatable(DisplayLockActivationReason::kAny)) {
      old_document.GetDisplayLockDocumentState()
          .DecrementDisplayLockBlockingAllActivation();
      document_->GetDisplayLockDocumentState()
          .IncrementDisplayLockBlockingAllActivation();
    }
  }

  DetermineIfSubtreeHasFocus();
  DetermineIfSubtreeHasSelection();
}

void DisplayLockContext::WillStartLifecycleUpdate(const LocalFrameView& view) {
  DCHECK(NeedsLifecycleNotifications());
  // We might have delayed processing intersection observation update (signal
  // that we were not intersecting) because this context was nested in another
  // locked context. At the start of the lifecycle, we should check whether
  // that is still true. In other words, this call will check if we're still
  // nested. If we are, we won't do anything. If we're not, then we will lock
  // this context.
  //
  // Note that when we are no longer nested and and we have not received any
  // notifications from the intersection observer, it means that we are not
  // visible.
  if (needs_deferred_not_intersecting_signal_)
    NotifyIsNotIntersectingViewport();
}

void DisplayLockContext::NotifyWillDisconnect() {
  if (!IsLocked() || !element_ || !element_->GetLayoutObject())
    return;
  // If we're locked while being disconnected, we need to layout the parent.
  // The reason for this is that we might skip the layout if we're empty while
  // locked, but it's important to update IsSelfCollapsingBlock property on
  // the parent so that it's up to date. This property is updated during
  // layout.
  if (auto* parent = element_->GetLayoutObject()->Parent())
    parent->SetNeedsLayout(layout_invalidation_reason::kDisplayLock);
}

void DisplayLockContext::ElementDisconnected() {
  UpdateActivationObservationIfNeeded();
}

void DisplayLockContext::ElementConnected() {
  UpdateActivationObservationIfNeeded();
  DetermineIfSubtreeHasFocus();
  DetermineIfSubtreeHasSelection();
}

void DisplayLockContext::ScheduleAnimation() {
  DCHECK(element_);
  if (!ConnectedToView() || !document_ || !document_->GetPage())
    return;

  // Schedule an animation to perform the lifecycle phases.
  document_->GetPage()->Animator().ScheduleVisualUpdate(document_->GetFrame());
}

const char* DisplayLockContext::ShouldForceUnlock() const {
  DCHECK(element_);
  // This function is only called after style, layout tree, or lifecycle
  // updates, so the style should be up-to-date, except in the case of nested
  // locks, where the style recalc will never actually get to |element_|.
  // TODO(vmpstr): We need to figure out what to do here, since we don't know
  // what the style is and whether this element has proper containment. However,
  // forcing an update from the ancestor locks seems inefficient. For now, we
  // just optimistically assume that we have all of the right containment in
  // place. See crbug.com/926276 for more information.
  if (element_->NeedsStyleRecalc()) {
    DCHECK(DisplayLockUtilities::LockedAncestorPreventingStyle(*element_));
    return nullptr;
  }

  if (element_->HasDisplayContentsStyle())
    return rejection_names::kUnsupportedDisplay;

  auto* style = element_->GetComputedStyle();
  // Note that if for whatever reason we don't have computed style, then
  // optimistically assume that we have containment.
  if (!style)
    return nullptr;
  if (!style->ContainsStyle() || !style->ContainsLayout())
    return rejection_names::kContainmentNotSatisfied;

  // We allow replaced elements to be locked. This check is similar to the check
  // in DefinitelyNewFormattingContext() in element.cc, but in this case we
  // allow object element to get locked.
  if (IsA<HTMLObjectElement>(*element_) || IsA<HTMLImageElement>(*element_) ||
      element_->IsFormControlElement() || element_->IsMediaElement() ||
      element_->IsFrameOwnerElement() || element_->IsSVGElement()) {
    return nullptr;
  }

  // From https://www.w3.org/TR/css-contain-1/#containment-layout
  // If the element does not generate a principal box (as is the case with
  // display: contents or display: none), or if the element is an internal
  // table element other than display: table-cell, if the element is an
  // internal ruby element, or if the element's principal box is a
  // non-atomic inline-level box, layout containment has no effect.
  // (Note we're allowing display:none for display locked elements, and a bit
  // more restrictive on ruby - banning <ruby> elements entirely).
  auto* html_element = DynamicTo<HTMLElement>(element_.Get());
  if ((style->IsDisplayTableType() &&
       style->Display() != EDisplay::kTableCell) ||
      (!html_element || IsA<HTMLRubyElement>(html_element)) ||
      (style->IsDisplayInlineType() && !style->IsDisplayReplacedType())) {
    return rejection_names::kContainmentNotSatisfied;
  }
  return nullptr;
}

bool DisplayLockContext::ForceUnlockIfNeeded() {
  // We must have "contain: style layout", and disallow display:contents
  // for display locking. Note that we should always guarantee this after
  // every style or layout tree update. Otherwise, proceeding with layout may
  // cause unexpected behavior. By rejecting the promise, the behavior can be
  // detected by script.
  // TODO(rakina): If this is after acquire's promise is resolved and update()
  // commit() isn't in progress, the web author won't know that the element
  // got unlocked. Figure out how to notify the author.
  if (auto* reason = ShouldForceUnlock()) {
    if (IsLocked())
      Unlock();
    return true;
  }
  return false;
}

bool DisplayLockContext::ConnectedToView() const {
  return element_ && document_ && element_->isConnected() && document_->View();
}

void DisplayLockContext::NotifySubtreeLostFocus() {
  SetRenderAffectingState(RenderAffectingState::kSubtreeHasFocus, false);
}

void DisplayLockContext::NotifySubtreeGainedFocus() {
  SetRenderAffectingState(RenderAffectingState::kSubtreeHasFocus, true);
}

void DisplayLockContext::DetermineIfSubtreeHasFocus() {
  if (!ConnectedToView()) {
    SetRenderAffectingState(RenderAffectingState::kSubtreeHasFocus, false);
    return;
  }

  bool subtree_has_focus = false;
  // Iterate up the ancestor chain from the currently focused element. If at any
  // time we find our element, then our subtree is focused.
  for (auto* focused = document_->FocusedElement(); focused;
       focused = FlatTreeTraversal::ParentElement(*focused)) {
    if (focused == element_.Get()) {
      subtree_has_focus = true;
      break;
    }
  }
  SetRenderAffectingState(RenderAffectingState::kSubtreeHasFocus,
                          subtree_has_focus);
}

void DisplayLockContext::NotifySubtreeGainedSelection() {
  SetRenderAffectingState(RenderAffectingState::kSubtreeHasSelection, true);
}

void DisplayLockContext::NotifySubtreeLostSelection() {
  SetRenderAffectingState(RenderAffectingState::kSubtreeHasSelection, false);
}

void DisplayLockContext::DetermineIfSubtreeHasSelection() {
  if (!ConnectedToView() || !document_->GetFrame()) {
    SetRenderAffectingState(RenderAffectingState::kSubtreeHasSelection, false);
    return;
  }

  auto range = ToEphemeralRangeInFlatTree(document_->GetFrame()
                                              ->Selection()
                                              .GetSelectionInDOMTree()
                                              .ComputeRange());
  bool subtree_has_selection = false;
  for (auto& node : range.Nodes()) {
    for (auto& ancestor : FlatTreeTraversal::InclusiveAncestorsOf(node)) {
      if (&ancestor == element_.Get()) {
        subtree_has_selection = true;
        break;
      }
    }
    if (subtree_has_selection)
      break;
  }
  SetRenderAffectingState(RenderAffectingState::kSubtreeHasSelection,
                          subtree_has_selection);
}

void DisplayLockContext::SetRenderAffectingState(RenderAffectingState state,
                                                 bool new_flag) {
  render_affecting_state_[static_cast<int>(state)] = new_flag;
  NotifyRenderAffectingStateChanged();
}

void DisplayLockContext::NotifyRenderAffectingStateChanged() {
  auto state = [this](RenderAffectingState state) {
    return render_affecting_state_[static_cast<int>(state)];
  };

  // Check that we're visible if and only if lock has not been requested.
  DCHECK(state_ == EContentVisibility::kVisible ||
         state(RenderAffectingState::kLockRequested));
  DCHECK(state_ != EContentVisibility::kVisible ||
         !state(RenderAffectingState::kLockRequested));

  // We should be locked if the lock has been requested (the above DCHECKs
  // verify that this means that we are not 'visible'), and any of the
  // following is true:
  // - We are not in 'auto' mode (meaning 'hidden') or
  // - We are in 'auto' mode and nothing blocks locking: viewport is
  //   not intersecting, subtree doesn't have focus, and subtree doesn't have
  //   selection.
  bool should_be_locked =
      state(RenderAffectingState::kLockRequested) &&
      (state_ != EContentVisibility::kAuto ||
       (!state(RenderAffectingState::kIntersectsViewport) &&
        !state(RenderAffectingState::kSubtreeHasFocus) &&
        !state(RenderAffectingState::kSubtreeHasSelection)));

  if (should_be_locked && !IsLocked())
    Lock();
  else if (!should_be_locked && IsLocked())
    Unlock();
}

void DisplayLockContext::Trace(Visitor* visitor) {
  visitor->Trace(element_);
  visitor->Trace(document_);
  visitor->Trace(whitespace_reattach_set_);
}

}  // namespace blink


text:
.class final enum Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;
.super Ljava/lang/Enum;
.source "Tethering.java"

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/server/connectivity/Tethering;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x401a
    name = "UpstreamInfoUpdateType"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Enum",
        "<",
        "Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;",
        ">;"
    }
.end annotation

# static fields
.field private static final synthetic $VALUES:[Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

.field public static final enum UPSTREAM_IFACE_ADDED:Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

.field public static final enum UPSTREAM_IFACE_REMOVED:Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

# direct methods
.method static constructor <clinit>()V
    .locals 4

    .prologue
    const/4 v3, 0x1

    const/4 v2, 0x0

    .line 129
    new-instance v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    const-string v1, "UPSTREAM_IFACE_REMOVED"

    invoke-direct {v0, v1, v2}, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->UPSTREAM_IFACE_REMOVED:Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    .line 130
    new-instance v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    const-string v1, "UPSTREAM_IFACE_ADDED"

    invoke-direct {v0, v1, v3}, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;-><init>(Ljava/lang/String;I)V

    sput-object v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->UPSTREAM_IFACE_ADDED:Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    .line 128
    const/4 v0, 0x2

    new-array v0, v0, [Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    sget-object v1, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->UPSTREAM_IFACE_REMOVED:Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    aput-object v1, v0, v2

    sget-object v1, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->UPSTREAM_IFACE_ADDED:Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    aput-object v1, v0, v3

    sput-object v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->$VALUES:[Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    return-void
.end method

.method private constructor <init>(Ljava/lang/String;I)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()V"
        }
    .end annotation

    .prologue
    .line 128
    invoke-direct {p0, p1, p2}, Ljava/lang/Enum;-><init>(Ljava/lang/String;I)V

    return-void
.end method

.method public static valueOf(Ljava/lang/String;)Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;
    .locals 1
    .param p0, "name"    # Ljava/lang/String;

    .prologue
    .line 128
    const-class v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    invoke-static {v0, p0}, Ljava/lang/Enum;->valueOf(Ljava/lang/Class;Ljava/lang/String;)Ljava/lang/Enum;

    move-result-object v0

    check-cast v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    return-object v0
.end method

.method public static values()[Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;
    .locals 1

    .prologue
    .line 128
    sget-object v0, Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->$VALUES:[Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    invoke-virtual {v0}, [Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;->clone()Ljava/lang/Object;

    move-result-object v0

    check-cast v0, [Lcom/android/server/connectivity/Tethering$UpstreamInfoUpdateType;

    return-object v0
.end method


text:
"use strict";
// 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.
Object.defineProperty(exports, "__esModule", { value: true });
const data_1 = require("../data");
const vector_1 = require("../vector");
const base_1 = require("./base");
const type_1 = require("../type");
const utf8_1 = require("../util/utf8");
class Utf8Vector extends base_1.BaseVector {
    /** @nocollapse */
    static from(values) {
        const length = values.length;
        const data = utf8_1.encodeUtf8(values.join(''));
        const offsets = values.reduce((offsets, str, idx) => ((!(offsets[idx + 1] = offsets[idx] + str.length) || true) && offsets), new Uint32Array(values.length + 1));
        return vector_1.Vector.new(data_1.Data.Utf8(new type_1.Utf8(), 0, length, 0, null, offsets, data));
    }
    asBinary() {
        return vector_1.Vector.new(this.data.clone(new type_1.Binary()));
    }
}
exports.Utf8Vector = Utf8Vector;

//# sourceMappingURL=utf8.js.map


text:
package org.apache.storm.trident.windowing.strategy;

import org.apache.storm.windowing.EvictionPolicy;
import org.apache.storm.windowing.TriggerHandler;
import org.apache.storm.windowing.TriggerPolicy;
/**
 * Strategy for windowing which will have respective trigger and eviction policies.
 */
public interface WindowStrategy<T> {

    /**
     * Returns a {@code TriggerPolicy}  by creating with {@code triggerHandler} and {@code evictionPolicy} with
     * the given configuration.
     *
     * @param triggerHandler
     * @param evictionPolicy
     * @return
     */
    public TriggerPolicy<T, ?> getTriggerPolicy(TriggerHandler triggerHandler, EvictionPolicy<T, ?> evictionPolicy);

    /**
     * Returns an {@code EvictionPolicy} instance for this strategy with the given configuration.
     *
     * @return
     */
    public EvictionPolicy<T, ?> getEvictionPolicy();
}


text:
module Zadar
  module Models
    class RemoteIsoRepo < Sequel::Model
      one_to_many :remote_iso_files

      alias_method :files, :remote_iso_files

      def before_destroy
        remove_all_remote_iso_files
      end

      def before_validation
        guess_local_dirname unless local_path
      end

      def before_create
        check_local_path_exists
      end

      def before_update
        check_local_path_exists
      end

      def validate
        super
        errors.add(:local_path, "is missing") if local_path.nil? || local_path.to_s.empty?
        errors.add(:url, "is invalid")      if invalid_url?
        errors.add(:url, "already exists")  if RemoteIsoRepo.find(url: url)
        errors.add(:name, "is missing")     if name.nil? || name.length.zero?
        errors.add(:name, "already exists") if RemoteIsoRepo.find(name: name)
      end

      private

      def check_local_path_exists
        errors.add(:local_path, "already exists") if Dir.exist?(local_path)
      end

      def guess_local_dirname
        return if local_path
        self.local_path = name.to_s.downcase.split.join("-")
      end

      def invalid_url?
        uri = URI.parse(url)
        return false unless uri.absolute?

        false
      rescue => e
        return true
      end
    end
  end
end


text:
require "rails_helper"

RSpec.describe HangmanGame do
  let(:initial_lives) { 1 }
  let(:mystery_word) { "abc" }
  subject(:game) {
    HangmanGame.create(mystery_word: mystery_word, initial_lives: initial_lives)
  }

  describe "testing new game validation" do
    context "with an empty word" do
      let(:mystery_word) { "" }

      it "does not save" do
        expect(game).to be_invalid
      end

      it "contains a mystery word error" do
        expect(game.errors[:mystery_word])
      end
    end

    context "with a word that has symbols" do
      let(:mystery_word) { "\@dabomb" }

      it "does not save" do
        expect(game).to be_invalid
      end
    end

    context "with a word that has numbers" do
      let(:mystery_word) { "l33t" }

      it "does not save" do
        expect(game).to be_invalid
      end
    end

    context "with a word that has blank space" do
      let(:mystery_word) { "hello darkness" }

      it "does not save" do
        expect(game).to be_invalid
      end
    end

    context "with a singular letteracter word" do
      let(:mystery_word) { "h" }

      it "does not save" do
        expect(game).to be_invalid
      end
    end

    context "with an alphabetical word containing atleast 2 letteracters" do
      context "containing uppercase chars" do
        let(:mystery_word) { "Hh" }

        it "does not save" do
          expect(game).to be_invalid
        end
      end

      context "with an alphabetical mystery word with more than 1 letteracter" do
        let(:mystery_word) { "hh" }

        it "saves" do
          expect(game).to be_valid
        end
      end
    end

    context "with 0 or less initial lives" do
      let(:initial_lives) { 0 }

      it "does not save with 0 lives" do
        expect(game).to be_invalid
      end

      let(:initial_lives) { -1 }

      it "does not save with -1 lives" do
        expect(game).to be_invalid
      end
    end
  end

  describe "testing valid input" do
    let(:mystery_word) { "abc" }

    context "given input occuring in the mystery word" do
      let(:correct_input) { mystery_word.chars.first }

      describe "#correct_guesses" do
        it "returns the correct guess" do
          create(:guess, letter: correct_input, hangman_game: game)

          expect(game.correct_guesses).to match_array([correct_input])
        end
      end

      it "does not decrement life" do
        initial_lives = game.lives
        create(:guess, letter: correct_input, hangman_game: game)

        expect(game.lives).to eql(initial_lives)
      end
    end

    context "given input not appearing in the mystery word" do
      let(:mystery_word) { "abc" }
      let(:incorrect_input) { "z" }

      describe "#incorrect_guesses" do
        it "returns the incorrect guess" do
          create(:guess, letter: incorrect_input, hangman_game: game)

          expect(game.incorrect_guesses).to match_array([incorrect_input])
        end
      end

      it "does decrement the players life" do
        initial_lives = game.lives
        create(:guess, letter: incorrect_input, hangman_game: game)

        expect(game.lives).to eql(initial_lives - 1)
      end
    end
  end

  describe "testing all chars are guessed" do
    let(:mystery_word) { "abc" }

    it "wins the game" do
      create(:guess, letter: mystery_word.chars.first, hangman_game: game)
      create(:guess, letter: mystery_word.chars.second, hangman_game: game)
      create(:guess, letter: mystery_word.chars.third, hangman_game: game)

      expect(game).to be_won
      expect(game).not_to be_running
    end
  end

  describe "testing player runs out of lives" do
    let(:mystery_word) { "abc" }
    let(:initial_lives) { 1 }

    it "loses the game" do
      create(:guess, letter: "y", hangman_game: game)

      expect(game).not_to be_won
      expect(game).not_to be_running
    end
  end
end


text:
package chana.serializer

import akka.actor.ExtendedActorSystem
import akka.serialization.Serializer
import akka.util.ByteString
import chana.jpql.BinaryProjection
import chana.jpql.RemoveProjection
import java.nio.ByteOrder

final class AvroProjectionSerializer(system: ExtendedActorSystem) extends Serializer {
  implicit val byteOrder = ByteOrder.BIG_ENDIAN

  override def identifier: Int = 124621389

  override def includeManifest: Boolean = false

  override def toBinary(obj: AnyRef): Array[Byte] = obj match {
    case BinaryProjection(id, projection) =>
      val builder = ByteString.newBuilder
      StringSerializer.appendToByteString(builder, id)
      builder.putBytes(projection)
      builder.result.toArray

    case RemoveProjection(id) =>
      val builder = ByteString.newBuilder
      StringSerializer.appendToByteString(builder, id)
      builder.result.toArray

    case _ =>
      throw new IllegalArgumentException("Can't serialize a non-projection message using AvroProjectionSerializer [" + obj + "]")
  }

  override def fromBinary(bytes: Array[Byte], manifest: Option[Class[_]]): AnyRef = {
    val data = ByteString(bytes).iterator
    val id = StringSerializer.fromByteIterator(data)
    val len = data.len
    if (len > 0) {
      val payload = Array.ofDim[Byte](data.len)
      data.getBytes(payload)
      BinaryProjection(id, payload)
    } else {
      RemoveProjection(id)
    }
  }
}


text:
define(['app'], function (app) {
  app.controller('TableSimpleController', ['breadcrumb', function(breadcrumb) {
    breadcrumb.title = 'Simple Tables';
    breadcrumb.subTitle = 'advanced tables';
    breadcrumb.list = [
      { name: 'Table', link: 'main.table.simple'},
      { name: 'Simple' }
    ];
  }]);
});


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

@echo off

if "%OS%" == "Windows_NT" SETLOCAL EnableDelayedExpansion
rem ---------------------------------------------------------------------------
rem Windows start script for Kaazing Gateway
rem ---------------------------------------------------------------------------

cd %~dp0

rem A temporary variable for the location of the gateway installation,
rem to allow determining the conf and lib subdirectories (assumed to
rem be siblings to this script's 'bin' directory).
set GW_HOME=..

rem You can define various Java system properties by setting the value
rem of the GATEWAY_OPTS environment variable before calling this script.
rem The script itself should not be changed. For example, the setting
rem below sets the Java maximum memory to 512MB.
if "%GATEWAY_OPTS%" == "" (
    set GATEWAY_OPTS=-Xmx512m
)

rem You can opt into using early access features by setting the value
rem of the GATEWAY_FEATURES environment variable to a comma separated
rem list of features to enable before calling this script.
rem The script itself should not be changed.
set FEATURE_OPTS=
if not "%GATEWAY_FEATURES%" == "" (
   echo Enabling early access features: %GATEWAY_FEATURES%
   set FEATURE_OPTS=-Dfeature.%GATEWAY_FEATURES:,= -Dfeature.%
)

rem Create the classpath.

rem Add a directory for management support
set JAVA_LIBRARY_PATH=%GW_HOME%\lib\sigar

rem Set the gateway identifier (required by multiple gateway instances)
set GW_ID=
if "%GATEWAY_IDENTIFIER%" NEQ "" (
    set GW_ID="-Dorg.kaazing.gateway.server.GATEWAY_IDENTIFIER=%GATEWAY_IDENTIFIER%"
)

rem Checking java version
java -version 1>nul 2>nul || (
    echo "Java is not installed. Cannot start the Gateway."
    exit /b 2
)
for /f eol^=J^ tokens^=2-5^ delims^=.-_^" %%j in ('java -fullversion 2^>^&1') do set "jver=%%j%%k"

if %jver% LSS 18 (
  echo "Java 8 or higher must be installed to start the Gateway."
  exit /b 1
)

rem Startup the gateway
java %FEATURE_OPTS% %GATEWAY_OPTS% %GW_ID% -Djava.library.path="%JAVA_LIBRARY_PATH%" -XX:+HeapDumpOnOutOfMemoryError -cp "%GW_HOME%\lib\*" org.kaazing.gateway.server.WindowsMain %*


text:
namespace quiche {

const StandardHttpHeaderNameSet& GetStandardHeaderSet() {
  static const StandardHttpHeaderNameSet* const header_map =
      new StandardHttpHeaderNameSet({
          {"Accept"},
          {"Accept-Charset"},
          {"Accept-CH"},
          {"Accept-CH-Lifetime"},
          {"Accept-Encoding"},
          {"Accept-Language"},
          {"Accept-Ranges"},
          {"Access-Control-Allow-Credentials"},
          {"Access-Control-Allow-Headers"},
          {"Access-Control-Allow-Methods"},
          {"Access-Control-Allow-Origin"},
          {"Access-Control-Expose-Headers"},
          {"Access-Control-Max-Age"},
          {"Access-Control-Request-Headers"},
          {"Access-Control-Request-Method"},
          {"Age"},
          {"Allow"},
          {"Authorization"},
          {"Cache-Control"},
          {"Connection"},
          {"Content-Disposition"},
          {"Content-Encoding"},
          {"Content-Language"},
          {"Content-Length"},
          {"Content-Location"},
          {"Content-Range"},
          {"Content-Security-Policy"},
          {"Content-Security-Policy-Report-Only"},
          {"X-Content-Security-Policy"},
          {"X-Content-Security-Policy-Report-Only"},
          {"X-WebKit-CSP"},
          {"X-WebKit-CSP-Report-Only"},
          {"Content-Type"},
          {"Content-MD5"},
          {"X-Content-Type-Options"},
          {"Cookie"},
          {"Cookie2"},
          {"Cross-Origin-Resource-Policy"},
          {"Cross-Origin-Opener-Policy"},
          {"Date"},
          {"DAV"},
          {"Depth"},
          {"Destination"},
          {"DNT"},
          {"DPR"},
          {"Early-Data"},
          {"ETag"},
          {"Expect"},
          {"Expires"},
          {"Follow-Only-When-Prerender-Shown"},
          {"Forwarded"},
          {"From"},
          {"Host"},
          {"HTTP2-Settings"},
          {"If"},
          {"If-Match"},
          {"If-Modified-Since"},
          {"If-None-Match"},
          {"If-Range"},
          {"If-Unmodified-Since"},
          {"Keep-Alive"},
          {"Label"},
          {"Last-Modified"},
          {"Link"},
          {"Location"},
          {"Lock-Token"},
          {"Max-Forwards"},
          {"MS-Author-Via"},
          {"Origin"},
          {"Overwrite"},
          {"P3P"},
          {"Ping-From"},
          {"Ping-To"},
          {"Pragma"},
          {"Proxy-Connection"},
          {"Proxy-Authenticate"},
          {"Public-Key-Pins"},
          {"Public-Key-Pins-Report-Only"},
          {"Range"},
          {"Referer"},
          {"Referrer-Policy"},
          {"Refresh"},
          {"Report-To"},
          {"Retry-After"},
          {"Sec-Fetch-Dest"},
          {"Sec-Fetch-Mode"},
          {"Sec-Fetch-Site"},
          {"Sec-Fetch-User"},
          {"Sec-Metadata"},
          {"Sec-Token-Binding"},
          {"Sec-Provided-Token-Binding-ID"},
          {"Sec-Referred-Token-Binding-ID"},
          {"Sec-WebSocket-Accept"},
          {"Sec-WebSocket-Extensions"},
          {"Sec-WebSocket-Key"},
          {"Sec-WebSocket-Protocol"},
          {"Sec-WebSocket-Version"},
          {"Server"},
          {"Server-Timing"},
          {"Service-Worker"},
          {"Service-Worker-Allowed"},
          {"Service-Worker-Navigation-Preload"},
          {"Set-Cookie"},
          {"Set-Cookie2"},
          {"Status-URI"},
          {"Strict-Transport-Security"},
          {"SourceMap"},
          {"Timeout"},
          {"Timing-Allow-Origin"},
          {"Tk"},
          {"Trailer"},
          {"Trailers"},
          {"Transfer-Encoding"},
          {"TE"},
          {"Upgrade"},
          {"Upgrade-Insecure-Requests"},
          {"User-Agent"},
          {"X-OperaMini-Phone-UA"},
          {"X-UCBrowser-UA"},
          {"X-UCBrowser-Device-UA"},
          {"X-Device-User-Agent"},
          {"Vary"},
          {"Via"},
          {"CDN-Loop"},
          {"Warning"},
          {"WWW-Authenticate"},
      });

  return *header_map;
}

}  // namespace quiche


text:
package com.jiahaoliuliu.listwithcheckableitems.model;

public class Country {

	private String country;
	private String capital;

	public Country() {
		super();
	}

	public Country(String country, String capital) {
		super();
		this.country = country;
		this.capital = capital;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	public String getCapital() {
		return capital;
	}

	public void setCapital(String capital) {
		this.capital = capital;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((capital == null) ? 0 : capital.hashCode());
		result = prime * result + ((country == null) ? 0 : country.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Country other = (Country) obj;
		if (capital == null) {
			if (other.capital != null)
				return false;
		} else if (!capital.equals(other.capital))
			return false;
		if (country == null) {
			if (other.country != null)
				return false;
		} else if (!country.equals(other.country))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Country [country=" + country + ", capital=" + capital + "]";
	}
}


text:
import StringIO
import email
import json
import urllib
from collections import defaultdict
from django.http import MultiPartParser
from django.utils.translation import ugettext as _
from django.core.cache import get_cache
from lrs.util import etag, convert_to_dict, convert_post_body_to_dict
from lrs.util.jws import JWS, JWSException
from lrs.exceptions import OauthUnauthorized, ParamError, BadRequest
from oauth_provider.oauth.oauth import OAuthError
from oauth_provider.utils import send_oauth_error
from oauth_provider.decorators import CheckOAuth

att_cache = get_cache('attachment_cache')

def parse(request, more_id=None):
    r_dict = {}
    # Build headers from request in request dict
    r_dict['headers'] = get_headers(request.META)

    # Traditional authorization should be passed in headers
    r_dict['auth'] = {}
    if 'Authorization' in r_dict['headers']:
        # OAuth will always be dict, not http auth. Set required fields for oauth module and type for authentication
        # module
        set_authorization(r_dict, request)
    elif 'Authorization' in request.body or 'HTTP_AUTHORIZATION' in request.body:
        # Authorization could be passed into body if cross origin request
        r_dict['auth']['type'] = 'http'
    else:
        r_dict['auth']['type'] = 'none'

    r_dict['params'] = {}
    # lookin for weird IE CORS stuff.. it'll be a post with a 'method' url param
    if request.method == 'POST' and 'method' in request.GET:
        bdy = convert_post_body_to_dict(request.body)
        # 'content' is in body for the IE cors POST
        if 'content' in bdy:
            r_dict['body'] = urllib.unquote(bdy.pop('content'))
        # headers are in the body too for IE CORS, we removes them
        r_dict['headers'].update(get_headers(bdy))
        for h in r_dict['headers']:
            bdy.pop(h, None)
        r_dict['params'].update(bdy)
        # all that should be left are params for the request,
        # we adds them to the params object
        for k in request.GET:
            if k == 'method': # make sure the method param goes in the special method spot
                r_dict[k] = request.GET[k]
            r_dict['params'][k] = request.GET[k]
    # Just parse body for all non IE CORS stuff
    else:
        r_dict = parse_body(r_dict, request)

    # Update dict with any GET data
    r_dict['params'].update(request.GET.dict())

    # Method gets set for cors already
    if 'method' not in r_dict['params']:
        # Differentiate GET and POST
        if request.method == "POST" and (request.path[6:] == 'statements' or request.path[6:] == 'statements/'):
            # Can have empty body for POST (acts like GET)
            if 'body' in r_dict:
                # If body is a list, it's a post
                if not isinstance(r_dict['body'], list):
                    # If actor verb and object not in body - means it's a GET or invalid POST
                    if not ('actor' in r_dict['body'] and 'verb' in r_dict['body'] and 'object' in r_dict['body']):
                        # If body keys are in get params - GET - else invalid request
                        if set(r_dict['body'].keys()).issubset(['statementId', 'voidedStatementId', 'agent', 'verb', 'activity', 'registration',
                            'related_activities', 'related_agents', 'since', 'until', 'limit', 'format', 'attachments', 'ascending']):
                            r_dict['method'] = 'GET'
                        else:
                            raise BadRequest("Statement is missing actor, verb, or object")
                    else:
                        r_dict['method'] = 'POST'
                else:
                    r_dict['method'] = 'POST'
            else:
                r_dict['method'] = 'GET'
        else:
            r_dict['method'] = request.method

    # Set if someone is hitting the statements/more endpoint
    if more_id:
        r_dict['more_id'] = more_id
    return r_dict

def set_authorization(r_dict, request):
    auth_params = r_dict['headers']['Authorization']
    if auth_params[:6] == 'OAuth ':
        # Make sure it has the required/valid oauth headers
        if CheckOAuth.is_valid_request(request):
            try:
                consumer, token, parameters = CheckOAuth.validate_token(request)
            except OAuthError, e:
                raise OauthUnauthorized(send_oauth_error(e))
            # Set consumer and token for authentication piece
            r_dict['auth']['oauth_consumer'] = consumer
            r_dict['auth']['oauth_token'] = token
            r_dict['auth']['type'] = 'oauth'
        else:
            raise OauthUnauthorized(send_oauth_error(OAuthError(_('Invalid OAuth request parameters.'))))

        # Used for OAuth scope
        endpoint = request.path[5:]
        # Since we accept with or without / on end
        if endpoint.endswith("/"):
            endpoint = endpoint[:-1]
        r_dict['auth']['endpoint'] = endpoint
    else:
        r_dict['auth']['type'] = 'http'

def parse_attachment(r, request):
    message = request.body
    # i need boundary to be in the message for email to parse it right
    if 'boundary' not in message[:message.index("--")]:
        if 'boundary' in request.META['CONTENT_TYPE']:
            message = request.META['CONTENT_TYPE'] + message
        else:
            raise BadRequest("Could not find the boundary for the multipart content")
    msg = email.message_from_string(message)
    if msg.is_multipart():
        parts = []
        for part in msg.walk():
            parts.append(part)
        if len(parts) < 1:
            raise ParamError("The content of the multipart request didn't contain a statement")
        # ignore parts[0], it's the whole thing
        # parts[1] better be the statement
        r['body'] = convert_to_dict(parts[1].get_payload())
        if len(parts) > 2:
            r['payload_sha2s'] = []
            for a in parts[2:]:
                # attachments
                thehash = a.get("X-Experience-API-Hash")
                if not thehash:
                    raise BadRequest("X-Experience-API-Hash header was missing from attachment")
                headers = defaultdict(str)
                r['payload_sha2s'].append(thehash)
                # Save msg object to cache
                att_cache.set(thehash, a)
    else:
        raise ParamError("This content was not multipart for the multipart request.")
    # see if the posted statements have attachments
    att_stmts = []
    if isinstance(r['body'], list):
        for s in r['body']:
            if 'attachments' in s:
                att_stmts.append(s)
    elif 'attachments' in r['body']:
        att_stmts.append(r['body'])
    if att_stmts:
        # find if any of those statements with attachments have a signed statement
        signed_stmts = [(s,a) for s in att_stmts for a in s.get('attachments', None) if a['usageType'] == "http://adlnet.gov/expapi/attachments/signature"]
        for ss in signed_stmts:
            attmnt = att_cache.get(ss[1]['sha2']).get_payload(decode=True)
            jws = JWS(jws=attmnt)
            try:
                if not jws.verify() or not jws.validate(ss[0]):
                    raise BadRequest("The JSON Web Signature is not valid")
            except JWSException as jwsx:
                raise BadRequest(jwsx)

def parse_body(r, request):
    if request.method == 'POST' or request.method == 'PUT':
        # Parse out profiles/states if the POST dict is not empty
        if 'multipart/form-data' in request.META['CONTENT_TYPE']:
            if request.POST.dict().keys():
                r['params'].update(request.POST.dict())
                parser = MultiPartParser(request.META, StringIO.StringIO(request.raw_post_data),request.upload_handlers)
                post, files = parser.parse()
                r['files'] = files
        # If it is multipart/mixed, parse out all data
        elif 'multipart/mixed' in request.META['CONTENT_TYPE']:
            parse_attachment(r, request)
        # Normal POST/PUT data
        else:
            if request.body:
                # profile uses the request body
                r['raw_body'] = request.body
                # Body will be some type of string, not necessarily JSON
                r['body'] = convert_to_dict(request.body)
            else:
                raise Exception("No body in request")
    return r

def get_headers(headers):
    r = {}
    if 'HTTP_UPDATED' in headers:
        r['updated'] = headers['HTTP_UPDATED']
    elif 'updated' in headers:
        r['updated'] = headers['updated']

    r['CONTENT_TYPE'] = headers.get('CONTENT_TYPE', '')
    if r['CONTENT_TYPE'] == '' and 'Content-Type' in headers:
        r['CONTENT_TYPE'] = headers['Content-Type']

    r['ETAG'] = etag.get_etag_info(headers, required=False)
    if 'HTTP_AUTHORIZATION' in headers:
        r['Authorization'] = headers.get('HTTP_AUTHORIZATION', None)
    elif 'Authorization' in headers:
        r['Authorization'] = headers.get('Authorization', None)

    if 'Accept_Language' in headers:
        r['language'] = headers.get('Accept_Language', None)
    elif 'Accept-Language' in headers:
        r['language'] = headers['Accept-Language']
    return r


text:
require 'aasm'
require 'active_record_inline_schema'

require 'data_miner/run/column_statistic'

class DataMiner
  # A record of what happened when you ran a data miner script.
  #
  # To create the table, use +DataMiner::Run.auto_upgrade!+, possibly in +db/seeds.rb+ or a database migration.
  class Run < ::ActiveRecord::Base
    class << self
      # If a previous run died and you have manually enabled locking, you may find yourself getting +LockMethod::Locked+ exceptions.
      #
      # @note Starting in 2.1.0, runs are no longer locked by default. This method remains in case you want to re-apply locking.
      #
      # @param [String] model_names What locks to clear.
      #
      # @return [nil]
      #
      # @example Re-enable locking (since it was turned off by default in 2.1.0)
      #   require 'data_miner'
      #   require 'lock_method'
      #   DataMiner::Run.lock_method :start
      def clear_locks(model_names = DataMiner.model_names)
        return unless defined?(::LockMethod)
        model_names.each do |model_name|
          dummy = new
          dummy.model_name = model_name
          dummy.lock_method_clear :start
        end
        nil
      end
    end

    # Raise this exception to skip the current run without causing it to fail.
    #
    # @example Avoid running certain data miner scripts too often (because they take too long).
    #   class FlightSegment < ActiveRecord::Base
    #     data_miner do
    #       [...]
    #       process "don't run this more than once an hour" do
    #         if (last_ran_at = data_miner_runs.first(:order => 'created_at DESC').try(:created_at)) and (Time.now.utc - last_ran_at) < 3600
    #           raise DataMiner::Run::Skip
    #         end
    #       end
    #       [...]
    #     end
    #   end
    class Skip < ::Exception
    end

    INITIAL_STATE = :limbo

    self.table_name = 'data_miner_runs'

    col :model_name
    col :aasm_state
    col :created_at, :type => :datetime
    col :stopped_at, :type => :datetime
    col :updated_at, :type => :datetime
    col :error, :type => :text
    col :row_count_before, :type => :integer
    col :row_count_after, :type => :integer
    add_index :model_name
    add_index :aasm_state

    validates_presence_of :model_name

    has_many :column_statistics, :class_name => 'DataMiner::Run::ColumnStatistic', :order => 'id ASC'

    include ::AASM
    aasm_initial_state INITIAL_STATE
    aasm_state :limbo
    aasm_state :skipped
    aasm_state :succeeded
    aasm_state :failed
    aasm_event(:succeed) { transitions :from => :limbo, :to => :succeeded }
    aasm_event(:skip)    { transitions :from => :limbo, :to => :skipped }
    aasm_event(:fail)    { transitions :from => :limbo, :to => :failed }

    # @private
    def start
      model = model_name.constantize
      if model.table_exists?
        self.row_count_before = model.count
      end
      save!
      if DataMiner.per_column_statistics?
        ColumnStatistic.take self
      end
      begin
        catch :data_miner_succeed do
          yield
        end
        succeed!
      rescue Skip
        skip!
      rescue
        self.error = "#{$!.message}\n#{$!.backtrace.join("\n")}"
        fail!
        raise $!
      ensure
        if model.connection.respond_to?(:schema_cache)
          model.connection.schema_cache.clear!
        end
        model.reset_column_information
        if model.table_exists?
          self.row_count_after = model.count
          if DataMiner.per_column_statistics?
            ColumnStatistic.take self
          end
        end
        self.stopped_at = ::Time.now.utc
        save!
        DataMiner.logger.info %{[data_miner] #{model_name} #{aasm_current_state.to_s.upcase} (#{(stopped_at-created_at).round(2)}s)}
      end
      self
    end

    # Get the column statistics for a particular column before this run started.
    #
    # @param [String] column_name The column you want to know about.
    #
    # @return [ColumnStatistic]
    def initial_column_statistics(column_name)
      column_statistics.where(:column_name => column_name.to_s).first
    end

    # Get the column statistics for a particular column after this run finished.
    #
    # @param [String] column_name The column you want to know about.
    #
    # @return [ColumnStatistic]
    def final_column_statistics(column_name)
      column_statistics.where(:column_name => column_name.to_s).last
    end

    # @private
    def as_lock
      database_name = Run.connection.instance_variable_get(:@config).try(:[], :database)
      [database_name, model_name]
    end
  end
end


text:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace Avalara.AvaTax.RestClient
{
    /// <summary>
    /// An account user who is permitted to use AvaTax.
    /// </summary>
    public class UserModel
    {
        /// <summary>
        /// The unique ID number of this user.
        /// </summary>
        public Int32 id { get; set; }

        /// <summary>
        /// The unique ID number of the account to which this user belongs.
        /// </summary>
        public Int32 accountId { get; set; }

        /// <summary>
        /// If this user is locked to one company (and its children), this is the unique ID number of the company to which this user belongs.
        /// </summary>
        public Int32? companyId { get; set; }

        /// <summary>
        /// The username which is used to log on to the AvaTax website, or to authenticate against API calls.
        /// </summary>
        public String userName { get; set; }

        /// <summary>
        /// The first or given name of the user.
        /// </summary>
        public String firstName { get; set; }

        /// <summary>
        /// The last or family name of the user.
        /// </summary>
        public String lastName { get; set; }

        /// <summary>
        /// The email address to be used to contact this user. If the user has forgotten a password, an email can be sent to this email address with information on how to reset this password.
        /// </summary>
        public String email { get; set; }

        /// <summary>
        /// The postal code in which this user resides.
        /// </summary>
        public String postalCode { get; set; }

        /// <summary>
        /// The security level for this user.
        /// </summary>
        public SecurityRoleId securityRoleId { get; set; }

        /// <summary>
        /// The status of the user's password. For a new user created, this is always going to be `UserMustChange`
        /// </summary>
        public PasswordStatusId? passwordStatus { get; set; }

        /// <summary>
        /// True if this user is currently active.
        /// </summary>
        public Boolean? isActive { get; set; }

        /// <summary>
        /// The date when this record was created.
        /// </summary>
        public DateTime? createdDate { get; set; }

        /// <summary>
        /// The date/time when this record was last modified.
        /// </summary>
        public DateTime? modifiedDate { get; set; }

        /// <summary>
        /// Matches the subjectId of corresponding user record in AI.
        /// </summary>
        public String subjectId { get; set; }

        /// <summary>
        /// The date/time when this record was migrated to Avalara Identity modified.
        /// </summary>
        public String migratedDate { get; set; }

        /// <summary>
        /// Suppress new user email
        /// </summary>
        public Boolean? suppressNewUserEmail { get; set; }

        /// <summary>
        /// Convert this object to a JSON string of itself
        /// </summary>
        /// <returns>A JSON string of this object</returns>
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
        }
    }
}


text:
To compile the `knitr-graphics` example, look at the bottom of the file
[`knitr-graphics.lyx`](knitr-graphics.lyx) for its dependencies.


text:
var mod_verror = require('./lib/verror');
var mod_util = require('util');

function MyError()
{
	mod_verror.WError.apply(this, Array.prototype.slice.call(arguments));
}

mod_util.inherits(MyError, mod_verror.WError);

function one()
{
	two();
}

function two()
{
	console.error(new Error('an Error').stack);
	console.error(new mod_verror.VError('a VError').stack);
	console.error(new mod_verror.WError('a WError').stack);
	console.error(new MyError('a MyError').stack);
}

one();