text:
package com.jetbrains.python.refactoring.changeSignature;

import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtilCore;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiElement;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.changeSignature.ChangeInfo;
import com.intellij.refactoring.changeSignature.ChangeSignatureUsageProcessor;
import com.intellij.refactoring.rename.RenameUtil;
import com.intellij.refactoring.rename.ResolveSnapshotProvider;
import com.intellij.usageView.UsageInfo;
import com.intellij.util.Query;
import com.intellij.util.containers.ContainerUtil;
import com.intellij.util.containers.MultiMap;
import com.jetbrains.python.PythonLanguage;
import com.jetbrains.python.codeInsight.PyPsiIndexUtil;
import com.jetbrains.python.documentation.docstrings.PyDocstringGenerator;
import com.jetbrains.python.inspections.quickfix.PyChangeSignatureQuickFix;
import com.jetbrains.python.psi.*;
import com.jetbrains.python.psi.impl.PyCallExpressionHelper;
import com.jetbrains.python.psi.search.PyOverridingMethodsSearch;
import com.jetbrains.python.psi.types.PyCallableParameter;
import com.jetbrains.python.psi.types.TypeEvalContext;
import one.util.streamex.StreamEx;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.*;

/**
 * User : ktisha
 */

public class PyChangeSignatureUsageProcessor implements ChangeSignatureUsageProcessor {

  @Override
  public UsageInfo[] findUsages(ChangeInfo info) {
    if (info instanceof PyChangeInfo) {
      final PyFunction targetFunction = ((PyChangeInfo)info).getMethod();
      final List<UsageInfo> usages = PyPsiIndexUtil.findUsages(targetFunction, true);
      if (!PyUtil.isInitOrNewMethod(targetFunction)) {
        final Query<PyFunction> search = PyOverridingMethodsSearch.search(targetFunction, true);
        for (PyFunction override : search.findAll()) {
          usages.add(new UsageInfo(override));
          usages.addAll(PyPsiIndexUtil.findUsages(override, true));
        }
      }
      return usages.toArray(UsageInfo.EMPTY_ARRAY);
    }
    return UsageInfo.EMPTY_ARRAY;
  }

  @Nullable
  @Override
  public MultiMap<PsiElement, String> findConflicts(ChangeInfo info, Ref<UsageInfo[]> refUsages) {
    final MultiMap<PsiElement, String> conflicts = new MultiMap<>();
    if (info instanceof PyChangeInfo && info.isNameChanged()) {
      final PyFunction function = ((PyChangeInfo)info).getMethod();
      final PyClass clazz = function.getContainingClass();
      if (clazz != null && clazz.findMethodByName(info.getNewName(), true, null) != null) {
        conflicts.putValue(function, RefactoringBundle.message("method.0.is.already.defined.in.the.1",
                                                               info.getNewName(),
                                                               "class " + clazz.getQualifiedName()));
      }
    }
    return conflicts;
  }

  @Override
  public boolean processUsage(final ChangeInfo changeInfo,
                              UsageInfo usageInfo,
                              boolean beforeMethodChange,
                              final UsageInfo[] usages) {
    if (!isPythonUsage(usageInfo)) return false;
    if (!(changeInfo instanceof PyChangeInfo)) return false;
    if (!beforeMethodChange) return false;
    PsiElement element = usageInfo.getElement();

    if (changeInfo.isNameChanged()) {
      final PsiElement method = changeInfo.getMethod();
      RenameUtil.doRenameGenericNamedElement(method, changeInfo.getNewName(), usages, null);
    }
    if (element == null) return false;

    if (element.getParent() instanceof PyCallExpression) {
      final PyCallExpression call = (PyCallExpression)element.getParent();
      // Don't modify the call that was the cause of Change Signature invocation
      if (call.getUserData(PyChangeSignatureQuickFix.CHANGE_SIGNATURE_ORIGINAL_CALL) != null) {
        return true;
      }
      final PyArgumentList argumentList = call.getArgumentList();
      if (argumentList != null) {
        final PyElementGenerator elementGenerator = PyElementGenerator.getInstance(element.getProject());
        StringBuilder builder = buildSignature((PyChangeInfo)changeInfo, call);

        final PyExpression newCall;
        if (call instanceof PyDecorator) {
          newCall = elementGenerator.createDecoratorList("@" + builder).getDecorators()[0];
        }
        else {
          newCall = elementGenerator.createExpressionFromText(LanguageLevel.forElement(element), builder.toString());
        }
        call.replace(newCall);

        return true;
      }
    }
    else if (element instanceof PyFunction && element != changeInfo.getMethod()) {
      processFunctionDeclaration((PyChangeInfo)changeInfo, (PyFunction)element);
    }
    return false;
  }

  @NotNull
  private static StringBuilder buildSignature(@NotNull PyChangeInfo changeInfo, @NotNull PyCallExpression call) {
    final PyArgumentList argumentList = call.getArgumentList();
    final PyExpression callee = call.getCallee();
    String name = callee != null ? callee.getText() : changeInfo.getNewName();
    StringBuilder builder = new StringBuilder(name + "(");
    if (argumentList != null) {
      List<String> params = collectParameters(changeInfo, call);
      builder.append(StringUtil.join(params, ","));
    }
    builder.append(")");
    return builder;
  }

  @NotNull
  private static List<String> collectParameters(@NotNull PyChangeInfo changeInfo, @NotNull PyCallExpression call) {
    boolean keywordArgsRequired = false;
    final List<String> newArguments = new ArrayList<>();

    final TypeEvalContext typeEvalContext = TypeEvalContext.userInitiated(call.getProject(), null);
    final PyFunction function = changeInfo.getMethod();

    final List<PyCallableParameter> allOrigParams = function.getParameters(typeEvalContext);
    final PyCallExpression.PyArgumentsMapping mapping = PyCallExpressionHelper.mapArguments(call, function, typeEvalContext);

    MultiMap<Integer, PyExpression> oldParamIndexToArgs = MultiMap.create();
    for (Map.Entry<PyExpression, PyCallableParameter> entry : mapping.getMappedParameters().entrySet()) {
      final PyCallableParameter param = entry.getValue();
      oldParamIndexToArgs.putValue(allOrigParams.indexOf(param), entry.getKey());
    }
    assert oldParamIndexToArgs.keySet().stream().allMatch(index -> index >= 0);

    List<PyParameterInfo> newParamInfos = Arrays.asList(changeInfo.getNewParameters());

    final int posVarargIndex = ContainerUtil.indexOf(newParamInfos, info -> isPositionalVarargName(info.getName()));
    final int posOnlyMarkerIndex = ContainerUtil.indexOf(newParamInfos, info -> PySlashParameter.TEXT.equals(info.getName()));
    final boolean posVarargEmpty = posVarargIndex != -1 && oldParamIndexToArgs.get(newParamInfos.get(posVarargIndex).getOldIndex()).isEmpty();
    List<PyExpression> notInsertedVariadicKeywordArgs = ContainerUtil.filter(call.getArguments(), a -> {
      return a instanceof PyStarArgument && ((PyStarArgument)a).isKeyword();
    });
    boolean variadicKeywordArgsUsed = false;
    final int implicitCount = mapping.getImplicitParameters().size();
    for (int paramIndex = implicitCount; paramIndex < newParamInfos.size(); paramIndex++) {
      PyParameterInfo info = newParamInfos.get(paramIndex);
      final String paramName = info.getName();
      final boolean isKeywordVararg = isKeywordVarargName(paramName);
      final boolean isPositionalVararg = isPositionalVarargName(paramName);
      final boolean beforePositionalOnlyMarker = paramIndex < posOnlyMarkerIndex;
      final boolean defaultShouldBeInlined = beforePositionalOnlyMarker &&
                                             ContainerUtil.exists(newParamInfos.subList(paramIndex + 1, posOnlyMarkerIndex),
                                                                  i -> !i.isNew() && !oldParamIndexToArgs.get(i.getOldIndex()).isEmpty());
      if (paramName.equals(PySingleStarParameter.TEXT)) {
        keywordArgsRequired = true;
        continue;
      }
      if (paramName.equals(PySlashParameter.TEXT)) {
        continue;
      }
      final String paramDefault = StringUtil.notNullize(info.getDefaultValue());
      final int oldIndex = info.getOldIndex();
      if (oldIndex < 0) {
        if (info.getDefaultInSignature() && !defaultShouldBeInlined) {
          // If the next argument was passed by position it would match with this new default.
          // Imagine "def f(x, y=None): ..." -> "def f(x, foo=None, y=None): ..." and a call "f(1, 2)"
          keywordArgsRequired = true;
        }
        else {
          newArguments.add(formatArgument(paramName, paramDefault, keywordArgsRequired));
        }
      }
      else {
        final Collection<PyExpression> existingArgs = oldParamIndexToArgs.get(oldIndex);
        final PyCallableParameter oldParam = allOrigParams.get(oldIndex);
        final boolean usesValueFromVariadic = mapping.getParametersMappedToVariadicKeywordArguments().contains(oldParam);
        variadicKeywordArgsUsed |= usesValueFromVariadic;
        if (!existingArgs.isEmpty()) {
          for (PyExpression arg : existingArgs) {
            PyExpression argValue;
            String argName;
            if (arg instanceof PyKeywordArgument) {
              argValue = ((PyKeywordArgument)arg).getValueExpression();
              argName = StringUtil.notNullize(((PyKeywordArgument)arg).getKeyword());
            }
            else {
              argValue = arg;
              argName = "";
            }
            notInsertedVariadicKeywordArgs.remove(argValue);
            // Keep format of existing keyword arguments unless it's illegal in their new position
            if (!argName.isEmpty() && !(paramIndex < posVarargIndex && !posVarargEmpty) && !beforePositionalOnlyMarker) {
              keywordArgsRequired = true;
            }
            assert !(isPositionalVararg && keywordArgsRequired);
            final String argValueText = argValue != null ? argValue.getText() : "";
            final String newArgumentName = isKeywordVararg ? argName : paramName;
            newArguments.add(formatArgument(newArgumentName, argValueText, keywordArgsRequired));
          }
        }
        // Parameter receives its default value from the signature, all subsequent arguments must use keyword form
        else if (info.getDefaultInSignature() && !defaultShouldBeInlined) {
          keywordArgsRequired = true;
        }
        else if (!isPositionalVararg && !isKeywordVararg && !usesValueFromVariadic) {
          // Existing ordinary parameter with neither a default value in the signature, not a corresponding argument.
          // Most likely its default was propagated from the signature down to calls.
          newArguments.add(formatArgument(paramName, paramDefault, keywordArgsRequired));
        }
      }
      // Keyword-only arguments should follow (Python 3)
      if (isPositionalVararg) {
        keywordArgsRequired = true;
      }
    }
    if (variadicKeywordArgsUsed) {
      newArguments.addAll(ContainerUtil.map(notInsertedVariadicKeywordArgs, PsiElement::getText));
    }

    return newArguments;
  }

  private static boolean isPositionalVarargName(@NotNull String paramName) {
    return !isKeywordVarargName(paramName) && !paramName.equals(PySingleStarParameter.TEXT) && paramName.startsWith("*");
  }

  private static boolean isKeywordVarargName(@NotNull String paramName) {
    return paramName.startsWith("**");
  }

  @NotNull
  private static String formatArgument(@NotNull String name, @NotNull String value, boolean keywordArgument) {
    if (keywordArgument && !value.startsWith("*")) {
      return name + "=" + value;
    }
    else {
      return value;
    }
  }

  private static boolean isPythonUsage(UsageInfo info) {
    final PsiElement element = info.getElement();
    if (element == null) return false;
    return element.getLanguage() == PythonLanguage.getInstance();
  }

  @Override
  public boolean processPrimaryMethod(ChangeInfo changeInfo) {
    if (changeInfo instanceof PyChangeInfo && changeInfo.getLanguage().is(PythonLanguage.getInstance())) {
      final PyChangeInfo pyChangeInfo = (PyChangeInfo)changeInfo;
      processFunctionDeclaration(pyChangeInfo, pyChangeInfo.getMethod());
      return true;
    }
    return false;
  }

  private static void processFunctionDeclaration(@NotNull PyChangeInfo changeInfo, @NotNull PyFunction function) {
    if (changeInfo.isParameterNamesChanged()) {
      final PyParameter[] oldParameters = function.getParameterList().getParameters();
      final Map<PyParameter, String> paramRenames = StreamEx.of(changeInfo.getNewParameters())
                                                            .filter(info -> info.getOldIndex() >= 0 && info.isRenamed())
                                                            .toMap(info -> oldParameters[info.getOldIndex()],
                                                                   info -> StringUtil.trimLeading(info.getName(), '*').trim());
      final Map<PsiElement, String> allRenames = new HashMap<>(paramRenames);
      if (changeInfo.isNameChanged()) {
        allRenames.put(function, changeInfo.getNewName());
      }
      for (Map.Entry<PyParameter, String> entry : paramRenames.entrySet()) {
        final PyParameter oldParameter = entry.getKey();
        final String newName = entry.getValue();
        final UsageInfo[] usages = RenameUtil.findUsages(oldParameter, newName, true, false, allRenames);
        for (UsageInfo info : usages) {
          RenameUtil.rename(info, newName);
        }
      }
    }
    if (changeInfo.isParameterSetOrOrderChanged()) {
      fixDoc(changeInfo, function);
      updateParameterList(changeInfo, function);
    }
    if (changeInfo.isNameChanged()) {
      RenameUtil.doRenameGenericNamedElement(function, changeInfo.getNewName(), UsageInfo.EMPTY_ARRAY, null);
    }
  }

  private static void fixDoc(PyChangeInfo changeInfo, @NotNull PyFunction function) {
    PyStringLiteralExpression docStringExpression = function.getDocStringExpression();
    if (docStringExpression == null) return;
    final PyParameterInfo[] parameters = changeInfo.getNewParameters();
    Set<String> names = new HashSet<>();
    for (PyParameterInfo info : parameters) {
      names.add(StringUtil.trimLeading(info.getName(), '*').trim());
    }
    final Module module = ModuleUtilCore.findModuleForPsiElement(function);
    if (module == null) return;
    final PyDocstringGenerator generator = PyDocstringGenerator.forDocStringOwner(function);
    for (PyParameter p : function.getParameterList().getParameters()) {
      final String paramName = p.getName();
      if (paramName != null && !names.contains(paramName)) {
        generator.withoutParam(paramName);
      }
    }
    generator.buildAndInsert();
  }

  private static void updateParameterList(PyChangeInfo changeInfo, PyFunction baseMethod) {
    final PsiElement parameterList = baseMethod.getParameterList();

    final PyParameterInfo[] parameters = changeInfo.getNewParameters();
    final StringBuilder builder = new StringBuilder("def foo(");
    final PyStringLiteralExpression docstring = baseMethod.getDocStringExpression();
    final PyParameter[] oldParameters = baseMethod.getParameterList().getParameters();
    final PyElementGenerator generator = PyElementGenerator.getInstance(baseMethod.getProject());
    final PyDocstringGenerator docStringGenerator = PyDocstringGenerator.forDocStringOwner(baseMethod);
    boolean newParameterInDocString = false;
    for (int i = 0; i < parameters.length; ++i) {
      final PyParameterInfo info = parameters[i];

      final int oldIndex = info.getOldIndex();
      if (i != 0 && oldIndex < oldParameters.length) {
        builder.append(", ");
      }

      if (docstring != null && oldIndex < 0) {
        newParameterInDocString = true;
        docStringGenerator.withParam(info.getName());
      }

      if (oldIndex < oldParameters.length) {
        builder.append(info.getName());
      }
      if (oldIndex >= 0 && oldIndex < oldParameters.length) {
        final PyParameter parameter = oldParameters[oldIndex];
        if (parameter instanceof PyNamedParameter) {
          final PyAnnotation annotation = ((PyNamedParameter)parameter).getAnnotation();
          if (annotation != null) {
            builder.append(annotation.getText());
          }
        }
      }
      final String defaultValue = info.getDefaultValue();
      if (defaultValue != null && info.getDefaultInSignature() && StringUtil.isNotEmpty(defaultValue)) {
        builder.append(" = ").append(defaultValue);
      }
    }
    builder.append("): pass");

    if (newParameterInDocString) {
      docStringGenerator.buildAndInsert();
    }

    final PyParameterList newParameterList = generator.createFromText(LanguageLevel.forElement(baseMethod),
                                                                      PyFunction.class,
                                                                      builder.toString()).getParameterList();
    parameterList.replace(newParameterList);
  }

  @Override
  public boolean shouldPreviewUsages(ChangeInfo changeInfo, UsageInfo[] usages) {
    return false;
  }

  @Override
  public boolean setupDefaultValues(ChangeInfo changeInfo, Ref<UsageInfo[]> refUsages, Project project) {
    return true;
  }

  @Override
  public void registerConflictResolvers(List<ResolveSnapshotProvider.ResolveSnapshot> snapshots,
                                        @NotNull ResolveSnapshotProvider resolveSnapshotProvider,
                                        UsageInfo[] usages, ChangeInfo changeInfo) {
  }
}


text:
package auth.domain.address;

import auth.domain.AbstractDomain;

public class Country extends AbstractDomain {

    private String name;

    public Country() {

    }

    public Country(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>doClose method - TorrentClientFrontNerve class - hetimatorrent library - Dart API</title>

    <base href="../..">

    <link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="static-assets/prettify.css">
    <link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
    <link rel="stylesheet" href="static-assets/styles.css">

    <meta name="description" content="API docs for the doClose method from the TorrentClientFrontNerve class, for the Dart programming language.">
    <link rel="icon" href="static-assets/favicon.png">

            <button id="sidenav-left-toggle" type="button"> </button>

hetimatorrent

hetimatorrent

TorrentClientFrontNerve

doClose

doClose

hetimatorrent

hetimatorrent

TorrentClientFrontNerve

doClose

method
 doClose

Source

hetimatorrent

hetimatorrent

TorrentClientFrontNerve

Static methods

doClose

doReceiveMessage

doSendMessage

Properties

id

reason

v

Constructors

TorrentClientFrontNerve

Methods

toString

            void
            doClose(

                TorrentClientFront front,
int reason

            )

Not documented.

Source

static void doClose(TorrentClientFront front, int reason) {
  front._streamSignal.add(new TorrentClientSignalWithFront(front, TorrentClientSignal.ID_CLOSE, reason, ""));
}

                  hetimatorrent 0.0.1 api docs

                •

                •

                  cc license


text:
{% assign companiesraw = (site.data.companies | sort ) | reverse %}

   {% assign companies = companiesraw limit: 3 %}
   {% for company in companies limit: 1 %}

   {% assign companyitem = company %}

   {{ companyitem.name }}

成立年份

{{ companyitem.founded }}

公司基地

{% for base in companyitem.base %} {{ base }}
 {% endfor %}

公司类型

                           {% for category in companyitem.category %} {{ category }}
 {% endfor %}

                     {% if companyitem.link == null %}

网站

                           未提供

                     {% elsif companyitem.link == '' %}

网站

                           未提供

                     {% else %}

网站

                           {{ companyitem.link }}

                     {% endif %} {% if companyitem.author == null %}

添加

保密

                     {% elsif companyitem.author == '' %}

添加

保密

                     {% else %}

添加

{{ companyitem.author }}

                     {% endif %}

{{ companyitem.about | markdownify }}

      {% endfor %}


text:
<?xml version="1.0"?>
<config-project>
    <environmentType>QA</environmentType>
    <environments>
        <environment name="Developer">
            <!-- For chrome driver location add the path on your local directory-->
            <!--<browser-type><name>chrome</name><driver>webdriver.chrome.driver</driver><location>chromedriver.exe</location></browser-type>-->
            <!-- For firefox driver location add the path on your local directory-->
            <browser-type><name>firefox</name><driver>webdriver.firefox.bin</driver><location>C:/Program Files (x86)/Mozilla Firefox/firefox.exe</location></browser-type>
            <!--<browser-type><name>ie</name><driver>webdriver.ie.driver</driver><location>iedriver2_47.exe</location></browser-type>-->
            <os-type>Windows</os-type>
            <grid-mode>OFF</grid-mode>
            <perf-mode>OFF</perf-mode>
            <mobile-mode>OFF</mobile-mode>
            <testlink-mode>
                <test-link>OFF</test-link>
                <test-link-url>http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php/index.php</test-link-url>
                <test-link-key>8669eb2c00e5c56242b788b5ebdb3d07</test-link-key>
                <test-link-project>OMNIX</test-link-project>
                <test-link-plan>Smoke Test</test-link-plan>
                <test-link-platform>BAT Chrome</test-link-platform>
                <test-link-build>V1.2015.11.27</test-link-build>
                <test-link-prefix>OMX-</test-link-prefix>
            </testlink-mode>
            <baseurl>
                <!-- protocol types http , https -->
                <protocol>http</protocol>
                <server>puppies.herokuapp.com</server>
                <port></port>
                <directory></directory>
                <page></page>
            </baseurl>
            <!-- REPORT DOWNLOAD PATH-->
            <downloadpath>C:\Reports\</downloadpath>
            <timeout>
                <implicit>8000</implicit>
                <script>2000</script>
                <pageload>10000</pageload>
                <!--element visible time based on env-->
                <env-timeout>3000</env-timeout>
            </timeout>
            <!--Framework level brows
            er specific error messages -->
            <errortypes>
                <!--Content missing message for fire fox browser -->
                <contentnotfoundff>//*[text()='Unable to connect']</contentnotfoundff>
                <!--Content missing message for chrome browser -->
                <contentnotfoundgc>//*[text()='This webpage is not available']</contentnotfoundgc>
                <!--Content missing message for ie browser -->
                <contentnotfoundie>//*[text()='You're not connected to a network']</contentnotfoundie>
                <!--Timeout message for fire fox browser -->
                <timeoutff>//*[text()='The connection has timed out']</timeoutff>
                <!--Timeout message for chrome browser -->
                <timeoutgc>//*[text()='This webpage is not available']</timeoutgc>
                <!--Timeout message for ie browser -->
                <timeoutie>//*[text()='This page can't be displayed']</timeoutie>
            </errortypes>
        </environment>
        <environment name = "QA">
            <!-- For chrome driver location add the path on your local directory-->
            <browser-type><name>chrome</name><driver>webdriver.chrome.driver</driver><location>chromedriver2_20.exe</location></browser-type>
            <!-- For firefox driver location add the path on your local directory-->
            <!--<browser-type><name>firefox</name><driver>webdriver.firefox.bin</driver><location>C:/Program Files (x86)/Mozilla Firefox/firefox.exe</location></browser-type>-->
            <!--<browser-type><name>ie</name><driver>webdriver.ie.driver</driver><location>iedriver2_53.exe</location></browser-type>-->
            <os-type>Windows</os-type>
            <grid-mode>OFF</grid-mode>
            <perf-mode>OFF</perf-mode>
            <mobile-mode>OFF</mobile-mode>
            <testlink-mode>
                <test-link>OFF</test-link>
                <test-link-url>http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php/index.php</test-link-url>
                <test-link-key>8669eb2c00e5c56242b788b5ebdb3d07</test-link-key>
                <test-link-project>Smoke Test</test-link-project>
                <test-link-project>OMNIX</test-link-project>
                <test-link-plan>Spike Test</test-link-plan>
                <test-link-platform>BAT Chrome</test-link-platform>
                <test-link-build>V1.2015.11.27</test-link-build>
                <test-link-prefix>OMX-</test-link-prefix>
            </testlink-mode>
            <baseurl>
                <!-- protocol types http , https -->
                <protocol>http</protocol>
                <server>puppies.herokuapp.com</server>
                <port></port>
                <directory></directory>
                <page></page>
            </baseurl>
            <!-- REPORT DOWNLOAD PATH-->
            <downloadpath>C:\Reports\</downloadpath>
            <timeout>
                <implicit>8000</implicit>
                <script>2000</script>
                <pageload>10000</pageload>
                <!--element visible time based on env-->
                <env-timeout>3000</env-timeout>
            </timeout>
            <!--Framework level brows
            er specific error messages -->
            <errortypes>
                <!--Content missing message for fire fox browser -->
                <contentnotfoundff>//*[text()='Unable to connect']</contentnotfoundff>
                <!--Content missing message for chrome browser -->
                <contentnotfoundgc>//*[text()='This webpage is not available']</contentnotfoundgc>
                <!--Content missing message for ie browser -->
                <contentnotfoundie>//*[text()='You're not connected to a network']</contentnotfoundie>
                <!--Timeout message for fire fox browser -->
                <timeoutff>//*[text()='The connection has timed out']</timeoutff>
                <!--Timeout message for chrome browser -->
                <timeoutgc>//*[text()='This webpage is not available']</timeoutgc>
                <!--Timeout message for ie browser -->
                <timeoutie>//*[text()='This page can't be displayed']</timeoutie>
            </errortypes>
        </environment>
        <environment name = "Production">
            <!-- For chrome driver location add the path on your local directory-->
            <browser-type><name>chrome</name><driver>webdriver.chrome.driver</driver><location>chromedriver2_19.exe</location></browser-type>
            <!-- For firefox driver location add the path on your local directory-->
            <!--<browser-type><name>firefox</name><driver>webdriver.firefox.bin</driver><location>C:/Program Files (x86)/Mozilla Firefox/firefox.exe</location></browser-type>-->
            <!--<browser-type><name>ie</name><driver>webdriver.ie.driver</driver><location>iedriver2_47.exe</location></browser-type>-->
            <os-type>Windows</os-type>
            <grid-mode>OFF</grid-mode>
            <perf-mode>OFF</perf-mode>
            <mobile-mode>OFF</mobile-mode>
            <testlink-mode>
                <test-link>OFF</test-link>
                <test-link-url>http://localhost/testlink/lib/api/xmlrpc/v1/xmlrpc.php/index.php</test-link-url>
                <test-link-key>8669eb2c00e5c56242b788b5ebdb3d07</test-link-key>
                <test-link-project>OMNIX</test-link-project>
                <test-link-plan>Smoke Test</test-link-plan>
                <test-link-platform>BAT Chrome</test-link-platform>
                <test-link-build>V1.2015.11.27</test-link-build>
                <test-link-prefix>OMX-</test-link-prefix>
            </testlink-mode>
            <baseurl>
                <!-- protocol types http , https -->
                <protocol>http</protocol>
                <server>puppies.herokuapp.com</server>
                <port></port>
                <directory></directory>
                <page></page>
            </baseurl>
            <!-- REPORT DOWNLOAD PATH-->
            <downloadpath>C:\Reports\</downloadpath>
            <timeout>
                <implicit>8000</implicit>
                <script>2000</script>
                <pageload>10000</pageload>
                <!--element visible time based on env-->
                <env-timeout>3000</env-timeout>
            </timeout>
            <!--Framework level brows
            er specific error messages -->
            <errortypes>
                <!--Content missing message for fire fox browser -->
                <contentnotfoundff>//*[text()='Unable to connect']</contentnotfoundff>
                <!--Content missing message for chrome browser -->
                <contentnotfoundgc>//*[text()='This webpage is not available']</contentnotfoundgc>
                <!--Content missing message for ie browser -->
                <contentnotfoundie>//*[text()='You're not connected to a network']</contentnotfoundie>
                <!--Timeout message for fire fox browser -->
                <timeoutff>//*[text()='The connection has timed out']</timeoutff>
                <!--Timeout message for chrome browser -->
                <timeoutgc>//*[text()='This webpage is not available']</timeoutgc>
                <!--Timeout message for ie browser -->
                <timeoutie>//*[text()='This page can't be displayed']</timeoutie>
            </errortypes>
        </environment>
    </environments>
</config-project>


text:
Application deployed on Heroku: http://lthforum-gnr.herokuapp.com/

### background
"The Great Neighborhood Restaurants and Resources are a crazy mish-mash of great places, nominated by members of LTHForum.com and chosen by all of us. They started as an answer to the one question we always get – "Can you tell us what places you love?" and have grown to become a full list of spots we love and are happy to recommend to anyone. These are destinations all over Chicagoland, restaurants to try if you want to get a true sense of the depth and breadth of the food scene in our city."

-LTH Forum

http://www.lthforum.com/2013/03/gnr/

### Overview
A RESTful API built on Rails with a database of Great Neighborhood Restaurants off of the LTH Forum website.  Currently, the GNR list is managed on the forum and it can be somewhat difficult to navigate the list.  This API was created to better manage the data on the site and to allow developers to build out applications using the database of restaurants on the list.  As a bonus feature, I added a random restaurant 'roulette' button on the home page.

### Project Scope
* Use Ruby & Sinatra OR Rails to build an API.
* Create a RESTful API using at least one model.
* Include all major CRUD functions in a RESTful API that will work using CocoaREST, Postman, or any client of your choosing.
* Consume your own API by making your front-end with HTML, Javascript, & jQuery, and Backbone.js.
* Add support in your API for Backbone. Do not neglect support for standardized API access as well.
* Add authentication to your API to restrict access to appropriate users. This can be done using API keys, user accounts, or any other form of authenication except OAuth (because we'll cover that soon).
* Craft thoughtful user stories to explain your API.
* Manage your source code using a standard Git flow on Github.
* Layout and style your front-end with clean & well-formatted CSS and make it Responsive. Bootstrap, Skeleton, Foundation, and other front-end CSS frameworks are all welcome here!
* Deploy your application online so it's publicly accessible. For Sinatra, use Digital Ocean. For Rails, use Heroku.

### Technologies used
* HTML5/CSS
* SASS
* Bootstrap
* Ruby on Rails
* Backbone.js
* jQuery
* underscore.js
* Postgres

### Deployment
* Clone down the application.
* Bundle the Gems
* Launch PSQL
* Build the database - rake db:create db:create db:seed
* Lauch the app in the console > rails s
* Open the browser and point it to http://localhost/3000

### Requesting an API Key
* As of now, there's one API key for the application.  Future iterations of the application will include a role based key for updates.


text:
package org.jetbrains.plugins.groovy.lang.editor.actions.moveUpDown;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.LogicalPosition;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiComment;
import com.intellij.psi.PsiDocumentManager;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.PsiDocumentManagerImpl;
import com.intellij.psi.impl.source.tree.LeafPsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.groovy.lang.lexer.GroovyTokenTypes;
import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrBlockStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrForStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrIfStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrWhileStatement;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinitionBody;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMembersDeclaration;
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.GrTopStatement;
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.literals.GrLiteralImpl;
import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;

/**
 * @author ilyas
 */
public class StatementMover extends LineMover {

  private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.lang.editor.actions.moveUpDown.StatementMover");

  public StatementMover(boolean down) {
    super(down);
  }

  protected boolean checkAvailable(Editor editor, PsiFile file) {
    final boolean available = super.checkAvailable(editor, file);
    if (!available) return false;
    LineRange range = toMove;

    if (editor == null) return false;
    final Document document = editor.getDocument();

    range = expandLineRangeToCoverPsiElements(range, editor, file);
    if (range == null) return false;
    final int startOffset = editor.logicalPositionToOffset(new LogicalPosition(range.startLine, 0));
    final int endOffset = editor.logicalPositionToOffset(new LogicalPosition(range.endLine, 0));
    final PsiElement[] statements = GroovyRefactoringUtil.findStatementsInRange(file, startOffset, endOffset, false);
    if (statements.length == 0) return false;
    for (final PsiElement statement : statements) {
      if (statement instanceof GrMembersDeclaration) {
        final GrMembersDeclaration declaration = (GrMembersDeclaration)statement;
        if (declaration.getMembers().length > 0) {
          return false;
        }
      }
    }

    range = toMove = new LineRange(statements[0], statements[statements.length - 1], document);

    updateComplementaryRange();

    final PsiElement commonParent = PsiTreeUtil.findCommonParent(range.firstElement, range.lastElement);

    // cannot move in/outside method/class/comment
    Class<? extends PsiElement>[] classes = new Class[]{GrMethod.class, GrTypeDefinition.class, PsiComment.class, GroovyFile.class};
    PsiElement guard = PsiTreeUtil.getParentOfType(commonParent, classes);
    if (!calcInsertOffset(file, editor, range)) return false;
    int insertOffset = isDown ? getLineStartSafeOffset(document, toMove2.endLine) - 1 : document.getLineStartOffset(toMove2.startLine);

    PsiElement newGuard = file.getViewProvider().findElementAt(insertOffset);
    newGuard = PsiTreeUtil.getParentOfType(newGuard, classes);
    if (newGuard != null && newGuard != guard && isInside(insertOffset, newGuard) != PsiTreeUtil.isAncestor(newGuard, range.lastElement, false)) {
      if (!PsiTreeUtil.isAncestor(guard, newGuard, false)) {
        return false;
      }
      while (true) {
        PsiElement candidate = PsiTreeUtil.getParentOfType(newGuard, classes);
        if (candidate == null || candidate == guard || !PsiTreeUtil.isAncestor(guard, candidate, false)) {
          break;
        }
        newGuard = candidate;
      }
      toMove2 = new LineRange(newGuard, newGuard, document);
    }

    return true;
  }

  @Nullable
  private static LineRange expandLineRangeToCoverPsiElements(final LineRange range, Editor editor, final PsiFile file) {
    Pair<PsiElement, PsiElement> psiRange = getElementRange(editor, file, range);
    if (psiRange == null) return null;
    final PsiElement parent = PsiTreeUtil.findCommonParent(psiRange.getFirst(), psiRange.getSecond());
    if (parent instanceof LeafPsiElement && parent.getParent() instanceof GrLiteralImpl) {
      return null; //multiline GString
    }

    Pair<PsiElement, PsiElement> elementRange = getElementRange(parent, psiRange.getFirst(), psiRange.getSecond());
    if (elementRange == null) return null;
    int endOffset = elementRange.getSecond().getTextRange().getEndOffset();
    Document document = editor.getDocument();
    if (endOffset > document.getTextLength()) {
      LOG.assertTrue(!PsiDocumentManager.getInstance(file.getProject()).isUncommited(document));
      LOG.assertTrue(PsiDocumentManagerImpl.checkConsistency(file, document));
    }
    int endLine;
    if (endOffset == document.getTextLength()) {
      endLine = document.getLineCount();
    } else {
      endLine = editor.offsetToLogicalPosition(endOffset).line + 1;
      endLine = Math.min(endLine, document.getLineCount());
    }
    int startLine = Math.min(range.startLine, editor.offsetToLogicalPosition(elementRange.getFirst().getTextOffset()).line);
    endLine = Math.max(endLine, range.endLine);
    return new LineRange(startLine, endLine);
  }

  private static boolean isInside(final int offset, final PsiElement guard) {
    if (guard == null) return false;

    TextRange inside = null;
    if (guard instanceof GrMethod) {
      GrOpenBlock block = ((GrMethod) guard).getBlock();
      if (block != null) inside = block.getTextRange();
    } else if (guard instanceof GrClosableBlock) {
      inside = guard.getTextRange();
    } else if (guard instanceof GrTypeDefinition) {
      GrTypeDefinitionBody body = ((GrTypeDefinition) guard).getBody();
      if (body != null) {
        final PsiElement lBrace = body.getLBrace();
        if (lBrace != null) {
          inside = new TextRange(lBrace.getTextOffset(), body.getTextRange().getEndOffset());
        }
      }

    }
    return inside != null && inside.contains(offset);
  }

  private boolean calcInsertOffset(PsiFile file, final Editor editor, LineRange range) {
    int line = isDown ? range.endLine + 1 : range.startLine - 1;
    int startLine = isDown ? range.endLine : range.startLine - 1;
    if (line < 0 || startLine < 0) return false;

    while (true) {
      final int offset = editor.logicalPositionToOffset(new LogicalPosition(line, 0));
      if (offset == file.getTextLength()) {
        return true;
      }

      PsiElement element = firstNonWhiteElement(offset, file, true, true);

      while (element != null && !(element instanceof PsiFile)) {
        if (!element.getTextRange().grown(-1).shiftRight(1).contains(offset)) {
          boolean found = false;
          if ((element instanceof GrTopStatement || element instanceof PsiComment)
              && statementCanBePlacedAlong(element)) {
            found = true;
          } else if (element.getNode() != null &&
              element.getNode().getElementType() == GroovyTokenTypes.mRCURLY) {
            // before code block closing brace
            found = true;
          }
          if (found) {
            toMove = range;
            int endLine = line;
            if (startLine > endLine) {
              int tmp = endLine;
              endLine = startLine;
              startLine = tmp;
            }
//            startLine--;
//            endLine--;
            toMove2 = isDown ? new LineRange(startLine, endLine) : new LineRange(startLine, endLine + 1);
            return true;
          }
        }
        element = element.getParent();
      }
      line += isDown ? 1 : -1;
      if (line == 0 || line >= editor.getDocument().getLineCount()) {
        return false;
      }
    }
  }

  private static boolean statementCanBePlacedAlong(final PsiElement element) {
    if (element instanceof GrBlockStatement) return false;
    final PsiElement parent = element.getParent();
    if (parent instanceof GrCodeBlock) return true;
    if (parent instanceof GroovyFile) return true;
    if (parent instanceof GrIfStatement &&
        (element == ((GrIfStatement) parent).getThenBranch() || element == ((GrIfStatement) parent).getElseBranch())) {
      return true;
    }
    if (parent instanceof GrWhileStatement && element == ((GrWhileStatement) parent).getBody()) {
      return true;
    }
    if (parent instanceof GrForStatement && element == ((GrForStatement) parent).getBody()) {
      return true;
    }
    // know nothing about that
    return false;
  }

}


text:
#ifndef INCLUDED_SVF_H
#define INCLUDED_SVF_H
#include "svf_macros.h"

#include "svf_component.h"
#include "svf_component_ctor.h"

#endif /* INCLUDED_SVF_H */


text:
namespace boost
{
namespace concurrent
{
namespace detail
{

  template <class ValueType, class Queue>
  class sync_queue_base
  {
  public:
    typedef ValueType value_type;
    typedef Queue underlying_queue_type;
    typedef typename Queue::size_type size_type;
    typedef queue_op_status op_status;

    // Constructors/Assignment/Destructors
    BOOST_THREAD_NO_COPYABLE(sync_queue_base)
    inline sync_queue_base();
    //template <typename Range>
    //inline explicit sync_queue(Range range);
    inline ~sync_queue_base();

    // Observers
    inline bool empty() const;
    inline bool full() const;
    inline size_type size() const;
    inline bool closed() const;

    // Modifiers
    inline void close();

    inline underlying_queue_type underlying_queue() {
      lock_guard<mutex> lk(mtx_);
      return boost::move(data_);
    }

  protected:
    mutable mutex mtx_;
    condition_variable cond_;
    underlying_queue_type data_;
    bool closed_;

    inline bool empty(unique_lock<mutex>& ) const BOOST_NOEXCEPT
    {
      return data_.empty();
    }
    inline bool empty(lock_guard<mutex>& ) const BOOST_NOEXCEPT
    {
      return data_.empty();
    }

    inline size_type size(lock_guard<mutex>& ) const BOOST_NOEXCEPT
    {
      return data_.size();
    }
    inline bool closed(unique_lock<mutex>& lk) const;
    inline bool closed(lock_guard<mutex>& lk) const;

    inline void throw_if_closed(unique_lock<mutex>&);
    inline void throw_if_closed(lock_guard<mutex>&);

    inline bool not_empty_or_closed(unique_lock<mutex>& ) const;

    inline bool wait_until_not_empty_or_closed(unique_lock<mutex>& lk);
    template <class WClock, class Duration>
    queue_op_status wait_until_not_empty_or_closed_until(unique_lock<mutex>& lk, chrono::time_point<WClock,Duration> const&tp);

    inline void notify_elem_added(unique_lock<mutex>& )
    {
      cond_.notify_all();
    }
    inline void notify_elem_added(lock_guard<mutex>& )
    {
      cond_.notify_all();
    }

  };

  template <class ValueType, class Queue>
  sync_queue_base<ValueType, Queue>::sync_queue_base() :
    data_(), closed_(false)
  {
    BOOST_ASSERT(data_.empty());
  }

  template <class ValueType, class Queue>
  sync_queue_base<ValueType, Queue>::~sync_queue_base()
  {
  }

  template <class ValueType, class Queue>
  void sync_queue_base<ValueType, Queue>::close()
  {
    {
      lock_guard<mutex> lk(mtx_);
      closed_ = true;
    }
    cond_.notify_all();
  }

  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::closed() const
  {
    lock_guard<mutex> lk(mtx_);
    return closed(lk);
  }
  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::closed(unique_lock<mutex>&) const
  {
    return closed_;
  }
  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::closed(lock_guard<mutex>&) const
  {
    return closed_;
  }

  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::empty() const
  {
    lock_guard<mutex> lk(mtx_);
    return empty(lk);
  }
  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::full() const
  {
    return false;
  }

  template <class ValueType, class Queue>
  typename sync_queue_base<ValueType, Queue>::size_type sync_queue_base<ValueType, Queue>::size() const
  {
    lock_guard<mutex> lk(mtx_);
    return size(lk);
  }

  template <class ValueType, class Queue>
  void sync_queue_base<ValueType, Queue>::throw_if_closed(unique_lock<mutex>& lk)
  {
    if (closed(lk))
    {
      BOOST_THROW_EXCEPTION( sync_queue_is_closed() );
    }
  }
  template <class ValueType, class Queue>
  void sync_queue_base<ValueType, Queue>::throw_if_closed(lock_guard<mutex>& lk)
  {
    if (closed(lk))
    {
      BOOST_THROW_EXCEPTION( sync_queue_is_closed() );
    }
  }

  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::not_empty_or_closed(unique_lock<mutex>& ) const
  {
    return ! data_.empty() || closed_;
  }

  template <class ValueType, class Queue>
  bool sync_queue_base<ValueType, Queue>::wait_until_not_empty_or_closed(unique_lock<mutex>& lk)
  {
    cond_.wait(lk, boost::bind(&sync_queue_base<ValueType, Queue>::not_empty_or_closed, boost::ref(*this), boost::ref(lk)));
    if (! empty(lk)) return false; // success
    return true; // closed
  }

  template <class ValueType, class Queue>
  template <class WClock, class Duration>
  queue_op_status sync_queue_base<ValueType, Queue>::wait_until_not_empty_or_closed_until(unique_lock<mutex>& lk, chrono::time_point<WClock,Duration> const&tp)
  {
    if (! cond_.wait_until(lk, tp, boost::bind(&sync_queue_base<ValueType, Queue>::not_empty_or_closed, boost::ref(*this), boost::ref(lk))))
      return queue_op_status::timeout;
    if (! empty(lk)) return queue_op_status::success;
    return queue_op_status::closed;
  }

} // detail
} // concurrent
} // boost

#include <boost/config/abi_suffix.hpp>

#endif


text:
package org.docksidestage.app.web.product;

import org.dbflute.cbean.result.PagingResultBean;
import org.docksidestage.app.web.base.MigueldoraBaseView;
import org.docksidestage.dbflute.exentity.Product;
import org.lastaflute.mixer2.view.Mixer2Supporter;
import org.mixer2.jaxb.xhtml.A;
import org.mixer2.jaxb.xhtml.Body;
import org.mixer2.jaxb.xhtml.Html;

/**
 * @author jflute
 */
public class ProductListView extends MigueldoraBaseView {

    private final ProductSearchForm form;
    private final PagingResultBean<Product> page;

    public ProductListView(ProductSearchForm form, PagingResultBean<Product> page) {
        this.form = form;
        this.page = page;
    }

    @Override
    protected void render(Html html, Mixer2Supporter supporter) {
        Body body = html.getBody();
        if (form.productStatus != null) {
            supporter.reflectSelectSelected(body, "productStatus", form.productStatus.code());
        }
        supporter.reflectListToTBody(page, body, "products", res -> {
            Product product = res.getEntity();
            res.register(product.getProductId());
            res.registerWithInner(inner -> {
                inner.findFirst(A.class).alwaysPresent(atag -> {
                    String url = supporter.toLinkUrl(ProductDetailAction.class, moreUrl(product.getProductId()));
                    supporter.reflectLinkUrl(atag, url);
                    atag.replaceInner(product.getProductName());
                });
            });
            res.register(product.getProductStatus().get().getProductStatusName());
            res.register(product.getProductCategory().get().getProductCategoryName());
            res.register(product.getRegularPrice());
            res.register(toDate(product.getLatestPurchaseDate()).orElse(null));
        });
    }
}


text:
package authorization_test

import (
	"context"
	"errors"
	"io/ioutil"
	"os"
	"testing"

	"github.com/influxdata/influxdb/v2"
	"github.com/influxdata/influxdb/v2/authorization"
	"github.com/influxdata/influxdb/v2/bolt"
	"github.com/influxdata/influxdb/v2/kv"
	"github.com/influxdata/influxdb/v2/kv/migration/all"
	"github.com/influxdata/influxdb/v2/tenant"
	influxdbtesting "github.com/influxdata/influxdb/v2/testing"
	"go.uber.org/zap/zaptest"
)

func initBoltAuthService(f influxdbtesting.AuthorizationFields, t *testing.T) (influxdb.AuthorizationService, string, func()) {
	s, closeBolt, err := NewTestBoltStore(t)
	if err != nil {
		t.Fatalf("failed to create new kv store: %v", err)
	}

	svc, closeSvc := initAuthService(s, f, t)
	return svc, "service_auth", func() {
		closeSvc()
		closeBolt()
	}
}

func initAuthService(s kv.Store, f influxdbtesting.AuthorizationFields, t *testing.T) (influxdb.AuthorizationService, func()) {
	st := tenant.NewStore(s)
	if f.OrgIDGenerator != nil {
		st.OrgIDGen = f.OrgIDGenerator
	}

	ts := tenant.NewService(st)
	storage, err := authorization.NewStore(s)
	if err != nil {
		t.Fatal(err)
	}

	svc := authorization.NewService(storage, ts)

	for _, u := range f.Users {
		if err := ts.CreateUser(context.Background(), u); err != nil {
			t.Fatalf("error populating users: %v", err)
		}
	}

	for _, o := range f.Orgs {
		if err := ts.CreateOrganization(context.Background(), o); err != nil {
			t.Fatalf("failed to populate organizations: %s", err)
		}
	}

	for _, m := range f.Authorizations {
		if err := svc.CreateAuthorization(context.Background(), m); err != nil {
			t.Fatalf("failed to populate authorizations: %v", err)
		}
	}

	return svc, func() {
		for _, m := range f.Authorizations {
			if err := svc.DeleteAuthorization(context.Background(), m.ID); err != nil {
				t.Logf("failed to remove authorization token: %v", err)
			}
		}
	}
}

func NewTestBoltStore(t *testing.T) (kv.Store, func(), error) {
	f, err := ioutil.TempFile("", "influxdata-bolt-")
	if err != nil {
		return nil, nil, errors.New("unable to open temporary boltdb file")
	}
	f.Close()

	path := f.Name()
	ctx := context.Background()
	logger := zaptest.NewLogger(t)

	s := bolt.NewKVStore(logger, path)

	if err := s.Open(ctx); err != nil {
		return nil, nil, err
	}

	if err := all.Up(ctx, logger, s); err != nil {
		return nil, nil, err
	}

	close := func() {
		s.Close()
		os.Remove(path)
	}

	return s, close, nil
}

func TestBoltAuthService(t *testing.T) {
	t.Parallel()
	influxdbtesting.AuthorizationService(initBoltAuthService, t)
}


text:
package grails.plugin.standalone;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import javax.servlet.ServletException;

/**
 * Abstract base class for the Tomcat and Jetty launchers.
 *
 * @author Burt Beckwith
 */
public abstract class AbstractLauncher {

	protected static final int BUFFER_SIZE = 4096;

	protected static final List<String> SUPPORTED_ARGS = Arrays.asList(
			"context", "host", "port", "httpsPort", "keystorePath", "javax.net.ssl.keyStore",
			"keystorePassword", "javax.net.ssl.keyStorePassword", "truststorePath", "javax.net.ssl.trustStore",
			"trustStorePassword", "javax.net.ssl.trustStorePassword", "enableClientAuth", "workDir",
			"enableCompression", "compressableMimeTypes", "sessionTimeout", "nio", "tomcat.nio",
			"serverName", "enableProxySupport");

	protected Map<String, String> argsMap;

	protected AbstractLauncher(String[] args) {
		argsMap = argsToMap(args);
	}

	protected File getWorkDir() {
		return new File(getArg("workDir", getArg("java.io.tmpdir", "")));
	}

	protected File extractWar() throws IOException {
		File dir = new File(getWorkDir(), "standalone-war");
		deleteDir(dir);
		dir.mkdirs();
		return extractWar(dir);
	}

	protected File extractWar(File dir) throws IOException {
		return extractWar(getClass().getClassLoader().getResourceAsStream("embedded.war"),
				File.createTempFile("embedded", ".war", dir).getAbsoluteFile());
	}

	protected File extractWar(InputStream embeddedWarfile, File destinationWarfile) throws IOException {
		destinationWarfile.getParentFile().mkdirs();
		destinationWarfile.deleteOnExit();
		copy(embeddedWarfile, new FileOutputStream(destinationWarfile));
		return explode(destinationWarfile);
	}

	protected File explode(File war) throws IOException {
		String basename = war.getName();
		int index = basename.lastIndexOf('.');
		if (index > -1) {
			basename = basename.substring(0, index);
		}
		File explodedDir = new File(war.getParentFile(), basename + "-exploded-" + System.currentTimeMillis());

		ZipFile zipfile = new ZipFile(war);
		for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements(); ) {
			unzip(e.nextElement(), zipfile, explodedDir);
		}
		zipfile.close();

		return explodedDir;
	}

	protected void unzip(ZipEntry entry, ZipFile zipfile, File explodedDir) throws IOException {

		if (entry.isDirectory()) {
			new File(explodedDir, entry.getName()).mkdirs();
			return;
		}

		File outputFile = new File(explodedDir, entry.getName());
		if (!outputFile.getParentFile().exists()) {
			outputFile.getParentFile().mkdirs();
		}

		BufferedInputStream inputStream = new BufferedInputStream(zipfile.getInputStream(entry));
		BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

		try {
			copy(inputStream, outputStream);
		}
		finally {
			outputStream.close();
			inputStream.close();
		}
	}

	protected abstract void start(File exploded) throws IOException, ServletException;

	protected boolean hasLength(String s) {
		return s != null && s.trim().length() > 0;
	}

	protected Map<String, String> argsToMap(String[] args) {
		Map<String, String> map = new HashMap<String, String>();
		for (String arg : args) {
			int index = arg.indexOf('=');
			if (index == -1) {
				System.err.println("Warning, arguments must be specified in name=value format, ignoring argument '" + arg + "'");
				continue;
			}
			String name = arg.substring(0, index).trim();
			if (!SUPPORTED_ARGS.contains(name)) {
				System.err.println("Warning, the specified argument '" + name + "' is not supported, ignoring");
				continue;
			}

			String value = arg.substring(index + 1).trim();
			map.put(name, value);
		}
		return map;
	}

	protected String getArg(String name) {
		return getArg(name, null);
	}

	protected String getArg(String name, String defaultIfMissing) {
		String value = argsMap.get(name);
		if (value == null) {
			if (System.getProperties().containsKey(name)) {
				value = System.getProperty(name);
			}
		}
		if (value == null) {
			value = defaultIfMissing;
		}
		else if (System.getProperties().containsKey(value)) {
			value = System.getProperty(value);
		}
		return value;
	}

	protected int getIntArg(String name, int defaultIfMissing) {
		String value = argsMap.get(name);
		if (value == null) {
			return defaultIfMissing;
		}

		try {
			return Integer.parseInt(value);
		}
		catch (NumberFormatException e) {
			return defaultIfMissing;
		}
	}

	protected boolean getBooleanArg(String name, boolean defaultIfMissing) {
		return "true".equalsIgnoreCase(getArg(name, String.valueOf(defaultIfMissing)));
	}

	// from org.springframework.util.FileCopyUtils.copy()
	protected void copy(InputStream in, OutputStream out) throws IOException {
		try {
			byte[] buffer = new byte[BUFFER_SIZE];
			int bytesRead = -1;
			while ((bytesRead = in.read(buffer)) != -1) {
				out.write(buffer, 0, bytesRead);
			}
			out.flush();
		}
		finally {
			try { in.close(); }
			catch (IOException ignored) { /*ignored*/ }
			try { out.close(); }
			catch (IOException ignored) { /*ignored*/ }
		}
	}

	// from DefaultGroovyMethods.deleteDir()
	protected boolean deleteDir(final File dir) {
		if (!dir.exists()) {
			return true;
		}

		if (!dir.isDirectory()) {
			return false;
		}

		File[] files = dir.listFiles();
		if (files == null) {
			return false;
		}

		boolean result = true;
		for (File file : files) {
			if (file.isDirectory()) {
				if (!deleteDir(file)) {
					result = false;
				}
			}
			else {
				if (!file.delete()) {
					result = false;
				}
			}
		}

		if (!dir.delete()) {
			result = false;
		}

		return result;
	}

	protected void deleteExplodedOnShutdown(final File exploded) {
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				deleteDir(exploded);
			}
		});
	}

	protected Class<?> getKeyToolClass() throws ClassNotFoundException {
		try {
			return Class.forName("sun.security.tools.KeyTool");
		}
		catch (ClassNotFoundException e) {
			// no try/catch for this one, if neither is found let it fail
			return Class.forName("com.ibm.crypto.tools.KeyTool");
		}
	}

	protected void initSsl(File keystoreFile, String keystorePassword, boolean usingUserKeystore) throws IOException {
		if (keystoreFile.exists()) {
			return;
		}

		if (usingUserKeystore) {
			throw new IllegalStateException(
					"cannot start in https because use keystore does not exist (value: " + keystoreFile + ")");
		}

		System.out.println("Creating SSL Certificate...");

		File keystoreDir = keystoreFile.getParentFile();
		if (!keystoreDir.exists() && !keystoreDir.mkdir()) {
			throw new RuntimeException("Unable to create keystore folder: " + keystoreDir.getCanonicalPath());
		}

		try {
			getKeyToolClass().getMethod("main", String[].class).invoke(null, new Object[] { new String[] {
					"-genkey",
					"-alias", "localhost",
					"-dname", "CN=localhost,OU=Test,O=Test,C=US",
					"-keyalg", "RSA",
					"-validity", "365",
					"-storepass", "key",
					"-keystore", keystoreFile.getAbsolutePath(),
					"-storepass", keystorePassword,
					"-keypass", keystorePassword}});
			System.out.println("Created SSL Certificate.");
		}
		catch (Exception e) {
			System.err.println("Unable to create an SSL certificate: " + e.getMessage());
		}
	}
}


text:
package java_8_in_action.parallelStream;

import java.util.concurrent.RecursiveTask;

/**
 * Created by yaojie.hou on 2017/4/1.
 *
 * 用分支/合并框架并行求和
 */
public class ForkJoinSumCalculator extends RecursiveTask<Long> {
	//要求和的数组
	private final long[] numbers;
	//子任务处理的数组的起始和终止位置
	private final int start;
	private final int end;
	//不再将任务分解为子任务的数组大小
	public static final long THRESHOLD = 10000;
	//公共构造函数用于创建主任务

	public ForkJoinSumCalculator(long[] numbers) {
		this(numbers, 0, numbers.length);
	}

	public ForkJoinSumCalculator(long[] numbers, int start, int end) {
		this.numbers = numbers;
		this.start = start;
		this.end = end;
	}

	@Override
	protected Long compute() {
		//该任务负责求和的部分的大小
		int length = end - start;
		if (length <= THRESHOLD) {
			return computeSequentially();
		}
		//创建一个任务为数组的前一半求和
		ForkJoinSumCalculator leftTask = new ForkJoinSumCalculator(numbers, start, start + length / 2);
		//利用另一个ForkJoinPool线程异步执行新创建的子任务
		leftTask.fork();
		//创建一个任务为数组的后一半求和
		ForkJoinSumCalculator rightTask = new ForkJoinSumCalculator(numbers, start + length / 2, end);
		//同步执行第二个子任务,有可能允许进一步递归划分
		Long rightResult = rightTask.compute();
		//读取第一个子任务的结果,如果尚未完成就等待
		Long leftResult = leftTask.join();
		//该任务的结果是两个子任务结果的组合
		return rightResult + leftResult;
	}

	private long computeSequentially () {
		long sum = 0;
		for (int i = start; i < end; i++) {
			sum += numbers[i];
		}
		return sum;
	}
}


text:
using System;
using Elasticsearch.Net;
using Nest;
using Tests.Framework;
using Tests.Framework.Integration;
using Tests.Framework.ManagedElasticsearch.Clusters;
using Xunit;

namespace Tests.Indices.Monitoring.IndicesStats
{
	public class IndicesStatsApiTests : ApiIntegrationTestBase<ReadOnlyCluster, IIndicesStatsResponse, IIndicesStatsRequest, IndicesStatsDescriptor, IndicesStatsRequest>
	{
		public IndicesStatsApiTests(ReadOnlyCluster cluster, EndpointUsage usage) : base(cluster, usage) { }

		protected override LazyResponses ClientUsage() => Calls(
			fluent: (client, f) => client.IndicesStats(Infer.AllIndices, f),
			fluentAsync: (client, f) => client.IndicesStatsAsync(Infer.AllIndices, f),
			request: (client, r) => client.IndicesStats(r),
			requestAsync: (client, r) => client.IndicesStatsAsync(r)
		);

		protected override bool ExpectIsValid => true;
		protected override int ExpectStatusCode => 200;
		protected override HttpMethod HttpMethod => HttpMethod.GET;
		protected override string UrlPath => "/_stats";

		protected override Func<IndicesStatsDescriptor, IIndicesStatsRequest> Fluent => d => d;

		protected override IndicesStatsRequest Initializer => new IndicesStatsRequest(Infer.AllIndices);
	}
}


text:
package org.rocksdb;

import org.junit.ClassRule;
import org.junit.Test;

import static org.assertj.core.api.Assertions.assertThat;

public class SliceTest {

  @ClassRule
  public static final RocksNativeLibraryResource ROCKS_NATIVE_LIBRARY_RESOURCE =
      new RocksNativeLibraryResource();

  @Test
  public void slice() {
    try (final Slice slice = new Slice("testSlice")) {
      assertThat(slice.empty()).isFalse();
      assertThat(slice.size()).isEqualTo(9);
      assertThat(slice.data()).isEqualTo("testSlice".getBytes());
    }

    try (final Slice otherSlice = new Slice("otherSlice".getBytes())) {
      assertThat(otherSlice.data()).isEqualTo("otherSlice".getBytes());
    }

    try (final Slice thirdSlice = new Slice("otherSlice".getBytes(), 5)) {
      assertThat(thirdSlice.data()).isEqualTo("Slice".getBytes());
    }
  }

  @Test
  public void sliceClear() {
    try (final Slice slice = new Slice("abc")) {
      assertThat(slice.toString()).isEqualTo("abc");
      slice.clear();
      assertThat(slice.toString()).isEmpty();
      slice.clear();  // make sure we don't double-free
    }
  }

  @Test
  public void sliceRemovePrefix() {
    try (final Slice slice = new Slice("abc")) {
      assertThat(slice.toString()).isEqualTo("abc");
      slice.removePrefix(1);
      assertThat(slice.toString()).isEqualTo("bc");
    }
  }

  @Test
  public void sliceEquals() {
    try (final Slice slice = new Slice("abc");
         final Slice slice2 = new Slice("abc")) {
      assertThat(slice.equals(slice2)).isTrue();
      assertThat(slice.hashCode() == slice2.hashCode()).isTrue();
    }
  }

  @Test
  public void sliceStartWith() {
    try (final Slice slice = new Slice("matchpoint");
         final Slice match = new Slice("mat");
         final Slice noMatch = new Slice("nomatch")) {
      assertThat(slice.startsWith(match)).isTrue();
      assertThat(slice.startsWith(noMatch)).isFalse();
    }
  }

  @Test
  public void sliceToString() {
    try (final Slice slice = new Slice("stringTest")) {
      assertThat(slice.toString()).isEqualTo("stringTest");
      assertThat(slice.toString(true)).isNotEqualTo("");
    }
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
HandlerInfo (Axis API)
</TITLE>

<META NAME="keywords" CONTENT="javax.xml.rpc.handler.HandlerInfo class">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

javax.xml.rpc.handler

Class HandlerInfo

java.lang.Object
  javax.xml.rpc.handler.HandlerInfo

All Implemented Interfaces:
java.io.Serializable

public class HandlerInfo
extends java.lang.Object
implements java.io.Serializable

The javax.xml.rpc.handler.HandlerInfo represents
 information about a handler in the HandlerChain. A HandlerInfo
 instance is passed in the Handler.init method to
 initialize a Handler instance.

Version:

1.0

See Also:
HandlerChain,
Serialized Form

Constructor Summary

HandlerInfo()

          Default constructor.

HandlerInfo(java.lang.Class handlerClass,
            java.util.Map config,
            QName[] headers)

          Constructor for HandlerInfo.

Method Summary

 java.lang.Class
getHandlerClass()

          Gets the Handler class.

 java.util.Map
getHandlerConfig()

          Gets the Handler configuration.

 QName[]
getHeaders()

          Gets the header blocks processed by this Handler.

 void
setHandlerClass(java.lang.Class handlerClass)

          Sets the Handler class.

 void
setHandlerConfig(java.util.Map config)

          Sets the Handler configuration as java.util.Map

 void
setHeaders(QName[] headers)

          Sets the header blocks processed by this Handler.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

HandlerInfo

public HandlerInfo()

Default constructor.

HandlerInfo

public HandlerInfo(java.lang.Class handlerClass,
                   java.util.Map config,
                   QName[] headers)

Constructor for HandlerInfo.

Parameters:
handlerClass - Java Class for the Handler
config - Handler Configuration as a java.util.Map
headers - QNames for the header blocks processed
          by this Handler.  QName is the qualified name
          of the outermost element of a header block

Method Detail

setHandlerClass

public void setHandlerClass(java.lang.Class handlerClass)

Sets the Handler class.

Parameters:
handlerClass - Class for the Handler

getHandlerClass

public java.lang.Class getHandlerClass()

Gets the Handler class.

Returns:
Returns null if no Handler class has been
    set; otherwise the set handler class

setHandlerConfig

public void setHandlerConfig(java.util.Map config)

Sets the Handler configuration as java.util.Map

Parameters:
config - Configuration map

getHandlerConfig

public java.util.Map getHandlerConfig()

Gets the Handler configuration.

Returns:
Returns empty Map if no configuration map
     has been set; otherwise returns the set configuration map

setHeaders

public void setHeaders(QName[] headers)

Sets the header blocks processed by this Handler.

Parameters:
headers - QNames of the header blocks. QName
            is the qualified name of the outermost
            element of the SOAP header block

getHeaders

public QName[] getHeaders()

Gets the header blocks processed by this Handler.

Returns:
Array of QNames for the header blocks. Returns
      null if no header blocks have been
      set using the setHeaders method.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

Copyright © 2005 Apache Web Services Project. All Rights Reserved.


text:
#ifndef CompositedLayerMapping_h
#define CompositedLayerMapping_h

#include "core/layout/compositing/GraphicsLayerUpdater.h"
#include "core/paint/PaintLayer.h"
#include "platform/geometry/FloatPoint.h"
#include "platform/geometry/FloatPoint3D.h"
#include "platform/graphics/GraphicsLayer.h"
#include "platform/graphics/GraphicsLayerClient.h"
#include "wtf/Allocator.h"

namespace blink {

class PaintLayerCompositor;

// A GraphicsLayerPaintInfo contains all the info needed to paint a partial subtree of Layers into a GraphicsLayer.
struct GraphicsLayerPaintInfo {
    DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
    PaintLayer* paintLayer;

    LayoutRect compositedBounds;

    // The clip rect to apply, in the local coordinate space of the squashed layer, when painting it.
    IntRect localClipRectForSquashedLayer;

    // Offset describing where this squashed Layer paints into the shared GraphicsLayer backing.
    IntSize offsetFromLayoutObject;
    bool offsetFromLayoutObjectSet;

    GraphicsLayerPaintInfo() : paintLayer(nullptr), offsetFromLayoutObjectSet(false) { }
};

enum GraphicsLayerUpdateScope {
    GraphicsLayerUpdateNone,
    GraphicsLayerUpdateLocal,
    GraphicsLayerUpdateSubtree,
};

// CompositedLayerMapping keeps track of how Layers of the layout tree correspond to
// GraphicsLayers of the composited layer tree. Each instance of CompositedLayerMapping
// manages a small cluster of GraphicsLayers and the references to which Layers
// and paint phases contribute to each GraphicsLayer.
//
// Currently (Oct. 2013) there is one CompositedLayerMapping for each Layer,
// but this is likely to evolve soon.
class CORE_EXPORT CompositedLayerMapping final : public GraphicsLayerClient {

    WTF_MAKE_NONCOPYABLE(CompositedLayerMapping); USING_FAST_MALLOC(CompositedPaintLayerMapping);
public:
    explicit CompositedLayerMapping(PaintLayer&);
    ~CompositedLayerMapping() override;

    PaintLayer& owningLayer() const { return m_owningLayer; }

    bool updateGraphicsLayerConfiguration();
    void updateGraphicsLayerGeometry(const PaintLayer* compositingContainer, const PaintLayer* compositingStackingContext, Vector<PaintLayer*>& layersNeedingPaintInvalidation);

    // Update whether layer needs blending.
    void updateContentsOpaque();

    GraphicsLayer* mainGraphicsLayer() const { return m_graphicsLayer.get(); }

    // Layer to clip children
    bool hasClippingLayer() const { return m_childContainmentLayer; }
    GraphicsLayer* clippingLayer() const { return m_childContainmentLayer.get(); }

    // Layer to get clipped by ancestor
    bool hasAncestorClippingLayer() const { return m_ancestorClippingLayer; }
    GraphicsLayer* ancestorClippingLayer() const { return m_ancestorClippingLayer.get(); }

    GraphicsLayer* foregroundLayer() const { return m_foregroundLayer.get(); }

    GraphicsLayer* backgroundLayer() const { return m_backgroundLayer.get(); }
    bool backgroundLayerPaintsFixedRootBackground() const { return m_backgroundLayerPaintsFixedRootBackground; }

    bool hasScrollingLayer() const { return m_scrollingLayer; }
    GraphicsLayer* scrollingLayer() const { return m_scrollingLayer.get(); }
    GraphicsLayer* scrollingContentsLayer() const { return m_scrollingContentsLayer.get(); }
    GraphicsLayer* scrollingBlockSelectionLayer() const { return m_scrollingBlockSelectionLayer.get(); }

    bool hasMaskLayer() const { return m_maskLayer; }
    GraphicsLayer* maskLayer() const { return m_maskLayer.get(); }

    bool hasChildClippingMaskLayer() const { return m_childClippingMaskLayer; }
    GraphicsLayer* childClippingMaskLayer() const { return m_childClippingMaskLayer.get(); }

    GraphicsLayer* parentForSublayers() const;
    GraphicsLayer* childForSuperlayers() const;

    bool hasChildTransformLayer() const { return m_childTransformLayer; }
    GraphicsLayer* childTransformLayer() const { return m_childTransformLayer.get(); }

    GraphicsLayer* squashingContainmentLayer() const { return m_squashingContainmentLayer.get(); }
    GraphicsLayer* squashingLayer() const { return m_squashingLayer.get(); }

    void setSquashingContentsNeedDisplay();
    void setContentsNeedDisplay();
    // LayoutRect is in the coordinate space of the layer's layout object.
    void setContentsNeedDisplayInRect(const LayoutRect&, PaintInvalidationReason);

    // If |visualRect| is not nullptr, it contains all pixels that might be painted by the display item client,
    // in coordinate space of the layer's layout object.
    // |visualRect| can be nullptr if we know it's unchanged and PaintController has cached the previous value.
    void invalidateDisplayItemClient(const DisplayItemClientWrapper&, PaintInvalidationReason, const LayoutRect* visualRect);

    // Notification from the layoutObject that its content changed.
    void contentChanged(ContentChangeType);

    LayoutRect compositedBounds() const { return m_compositedBounds; }
    IntRect pixelSnappedCompositedBounds() const;

    void positionOverflowControlsLayers();

    // Returns true if the assignment actually changed the assigned squashing layer.
    bool updateSquashingLayerAssignment(PaintLayer* squashedLayer, size_t nextSquashedLayerIndex);
    void removeLayerFromSquashingGraphicsLayer(const PaintLayer*);
#if ENABLE(ASSERT)
    bool verifyLayerInSquashingVector(const PaintLayer*);
#endif

    void finishAccumulatingSquashingLayers(size_t nextSquashedLayerIndex);
    void updateRenderingContext();
    void updateShouldFlattenTransform();

    // GraphicsLayerClient interface
    void notifyAnimationStarted(const GraphicsLayer*, double monotonicTime, int group) override;
    void notifyFirstPaint() override;
    void notifyFirstTextPaint() override;
    void notifyFirstImagePaint() override;

    void paintContents(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect* clip) const override;
    bool isTrackingPaintInvalidations() const override;

#if ENABLE(ASSERT)
    void verifyNotPainting() override;
#endif

    LayoutRect contentsBox() const;

    GraphicsLayer* layerForHorizontalScrollbar() const { return m_layerForHorizontalScrollbar.get(); }
    GraphicsLayer* layerForVerticalScrollbar() const { return m_layerForVerticalScrollbar.get(); }
    GraphicsLayer* layerForScrollCorner() const { return m_layerForScrollCorner.get(); }

    // Returns true if the overflow controls cannot be positioned within this
    // CLM's internal hierarchy without incorrectly stacking under some
    // scrolling content. If this returns true, these controls must be
    // repositioned in the graphics layer tree to ensure that they stack above
    // scrolling content.
    bool needsToReparentOverflowControls() const;

    // Removes the overflow controls host layer from its parent and positions it
    // so that it can be inserted as a sibling to this CLM without changing
    // position.
    GraphicsLayer* detachLayerForOverflowControls(const PaintLayer& enclosingLayer);

    void updateFilters(const ComputedStyle&);
    void updateBackdropFilters(const ComputedStyle&);

    void setBlendMode(WebBlendMode);

    bool needsGraphicsLayerUpdate() { return m_pendingUpdateScope > GraphicsLayerUpdateNone; }
    void setNeedsGraphicsLayerUpdate(GraphicsLayerUpdateScope scope) { m_pendingUpdateScope = std::max(static_cast<GraphicsLayerUpdateScope>(m_pendingUpdateScope), scope); }
    void clearNeedsGraphicsLayerUpdate() { m_pendingUpdateScope = GraphicsLayerUpdateNone; }

    GraphicsLayerUpdater::UpdateType updateTypeForChildren(GraphicsLayerUpdater::UpdateType) const;

#if ENABLE(ASSERT)
    void assertNeedsToUpdateGraphicsLayerBitsCleared() {  ASSERT(m_pendingUpdateScope == GraphicsLayerUpdateNone); }
#endif

    String debugName(const GraphicsLayer*) override;

    LayoutSize contentOffsetInCompositingLayer() const;

    LayoutPoint squashingOffsetFromTransformedAncestor()
    {
        return m_squashingLayerOffsetFromTransformedAncestor;
    }

    // If there is a squashed layer painting into this CLM that is an ancestor of the given LayoutObject, return it. Otherwise return nullptr.
    const GraphicsLayerPaintInfo* containingSquashedLayer(const LayoutObject*, unsigned maxSquashedLayerIndex);

    void updateScrollingBlockSelection();

    DisplayItemClient displayItemClient() const { return toDisplayItemClient(this); }
    String debugName() const { return "CompositedLayerMapping for " + owningLayer().debugName(); }

private:
    static IntRect computeInterestRect(const GraphicsLayer*, LayoutObject* owningLayoutObject);
    static bool interestRectChangedEnoughToRepaint(const IntRect& previousInterestRect, const IntRect& newInterestRect, const IntSize& layerSize);

    static const GraphicsLayerPaintInfo* containingSquashedLayer(const LayoutObject*,  const Vector<GraphicsLayerPaintInfo>& layers, unsigned maxSquashedLayerIndex);

    // Helper methods to updateGraphicsLayerGeometry:
    void computeGraphicsLayerParentLocation(const PaintLayer* compositingContainer, const IntRect& ancestorCompositingBounds, IntPoint& graphicsLayerParentLocation);
    void updateSquashingLayerGeometry(const LayoutPoint& offsetFromCompositedAncestor, const IntPoint& graphicsLayerParentLocation, const PaintLayer& referenceLayer, Vector<GraphicsLayerPaintInfo>& layers, GraphicsLayer*, LayoutPoint* offsetFromTransformedAncestor, Vector<PaintLayer*>& layersNeedingPaintInvalidation);
    void updateMainGraphicsLayerGeometry(const IntRect& relativeCompositingBounds, const IntRect& localCompositingBounds, const IntPoint& graphicsLayerParentLocation);
    void updateAncestorClippingLayerGeometry(const PaintLayer* compositingContainer, const IntPoint& snappedOffsetFromCompositedAncestor, IntPoint& graphicsLayerParentLocation);
    void updateOverflowControlsHostLayerGeometry(const PaintLayer* compositingStackingContext, const PaintLayer* compositingContainer);
    void updateChildContainmentLayerGeometry(const IntRect& clippingBox, const IntRect& localCompositingBounds);
    void updateChildTransformLayerGeometry();
    void updateMaskLayerGeometry();
    void updateTransformGeometry(const IntPoint& snappedOffsetFromCompositedAncestor, const IntRect& relativeCompositingBounds);
    void updateForegroundLayerGeometry(const FloatSize& relativeCompositingBoundsSize, const IntRect& clippingBox);
    void updateBackgroundLayerGeometry(const FloatSize& relativeCompositingBoundsSize);
    void updateReflectionLayerGeometry(Vector<PaintLayer*>& layersNeedingPaintInvalidation);
    void updateScrollingLayerGeometry(const IntRect& localCompositingBounds);
    void updateChildClippingMaskLayerGeometry();

    void createPrimaryGraphicsLayer();
    void destroyGraphicsLayers();

    PassOwnPtr<GraphicsLayer> createGraphicsLayer(CompositingReasons);
    bool toggleScrollbarLayerIfNeeded(OwnPtr<GraphicsLayer>&, bool needsLayer, CompositingReasons);

    LayoutBoxModelObject* layoutObject() const { return m_owningLayer.layoutObject(); }
    PaintLayerCompositor* compositor() const { return m_owningLayer.compositor(); }

    void updateInternalHierarchy();
    void updatePaintingPhases();
    bool updateClippingLayers(bool needsAncestorClip, bool needsDescendantClip);
    bool updateChildTransformLayer(bool needsChildTransformLayer);
    bool updateOverflowControlsLayers(bool needsHorizontalScrollbarLayer, bool needsVerticalScrollbarLayer, bool needsScrollCornerLayer, bool needsAncestorClip);
    bool updateForegroundLayer(bool needsForegroundLayer);
    bool updateBackgroundLayer(bool needsBackgroundLayer);
    bool updateMaskLayer(bool needsMaskLayer);
    void updateChildClippingMaskLayer(bool needsChildClippingMaskLayer);
    bool requiresHorizontalScrollbarLayer() const { return m_owningLayer.scrollableArea() && m_owningLayer.scrollableArea()->horizontalScrollbar(); }
    bool requiresVerticalScrollbarLayer() const { return m_owningLayer.scrollableArea() && m_owningLayer.scrollableArea()->verticalScrollbar(); }
    bool requiresScrollCornerLayer() const { return m_owningLayer.scrollableArea() && !m_owningLayer.scrollableArea()->scrollCornerAndResizerRect().isEmpty(); }
    bool updateScrollingLayers(bool scrollingLayers);
    void updateScrollParent(PaintLayer*);
    void updateClipParent(PaintLayer* scrollParent);
    bool updateSquashingLayers(bool needsSquashingLayers);
    void updateDrawsContent();
    void updateChildrenTransform();
    void updateCompositedBounds();
    void registerScrollingLayers();

    // Also sets subpixelAccumulation on the layer.
    void computeBoundsOfOwningLayer(const PaintLayer* compositedAncestor, IntRect& localCompositingBounds, IntRect& compositingBoundsRelativeToCompositedAncestor, LayoutPoint& offsetFromCompositedAncestor, IntPoint& snappedOffsetFromCompositedAncestor);

    void setBackgroundLayerPaintsFixedRootBackground(bool);

    GraphicsLayerPaintingPhase paintingPhaseForPrimaryLayer() const;

    // Result is transform origin in pixels.
    FloatPoint3D computeTransformOrigin(const IntRect& borderBox) const;

    void updateOpacity(const ComputedStyle&);
    void updateTransform(const ComputedStyle&);
    void updateLayerBlendMode(const ComputedStyle&);
    void updateIsRootForIsolatedGroup();
    // Return the opacity value that this layer should use for compositing.
    float compositingOpacity(float layoutObjectOpacity) const;

    bool paintsChildren() const;

    // Returns true if this layer has content that needs to be displayed by painting into the backing store.
    bool containsPaintedContent() const;
    // Returns true if the Layer just contains an image that we can composite directly.
    bool isDirectlyCompositedImage() const;
    void updateImageContents();

    Color layoutObjectBackgroundColor() const;
    void updateBackgroundColor();
    void updateContentsRect();
    void updateContentsOffsetInCompositingLayer(const IntPoint& snappedOffsetFromCompositedAncestor, const IntPoint& graphicsLayerParentLocation);
    void updateAfterPartResize();
    void updateCompositingReasons();

    static bool hasVisibleNonCompositingDescendant(PaintLayer* parent);

    void doPaintTask(const GraphicsLayerPaintInfo&, const PaintLayerFlags&, GraphicsContext*, const IntRect& clip) const;

    // Computes the background clip rect for the given squashed layer, up to any containing layer that is squashed into the
    // same squashing layer and contains this squashed layer's clipping ancestor.
    // The clip rect is returned in the coordinate space of the given squashed layer.
    // If there is no such containing layer, returns the infinite rect.
    // FIXME: unify this code with the code that sets up m_ancestorClippingLayer. They are doing very similar things.
    static IntRect localClipRectForSquashedLayer(const PaintLayer& referenceLayer, const GraphicsLayerPaintInfo&,  const Vector<GraphicsLayerPaintInfo>& layers);

    // Return true if |m_owningLayer|'s compositing ancestor is not a descendant (inclusive) of the
    // clipping container for |m_owningLayer|.
    bool owningLayerClippedByLayerNotAboveCompositedAncestor(PaintLayer* scrollParent);

    PaintLayer* scrollParent();

    // Clear the groupedMapping entry on the layer at the given index, only if that layer does
    // not appear earlier in the set of layers for this object.
    bool invalidateLayerIfNoPrecedingEntry(size_t);

    void paintContentsInternal(const GraphicsLayer*, GraphicsContext&, GraphicsLayerPaintingPhase, const IntRect& interestRect) const;

    PaintLayer& m_owningLayer;

    // The hierarchy of layers that is maintained by the CompositedLayerMapping looks like this:
    //
    //  + m_ancestorClippingLayer [OPTIONAL]
    //    + m_graphicsLayer
    //      + m_childTransformLayer [OPTIONAL]
    //      | + m_childContainmentLayer [OPTIONAL] <-OR-> m_scrollingLayer [OPTIONAL]
    //      |                                             + m_scrollingContentsLayer [Present iff m_scrollingLayer is present]
    //      |                                               + m_scrollingBlockSelectionLayer [Present iff m_scrollingLayer is present]
    //      + m_overflowControlsClippingLayer [OPTIONAL] // *The overflow controls may need to be repositioned in the
    //        + m_overflowControlsHostLayer [OPTIONAL]   //  graphics layer tree by the RLC to ensure that they stack
    //          + m_layerForVerticalScrollbar [OPTIONAL] //  above scrolling content.
    //          + m_layerForHorizontalScrollbar [OPTIONAL]
    //          + m_layerForScrollCorner [OPTIONAL]
    //
    // We need an ancestor clipping layer if our clipping ancestor is not our ancestor in the
    // clipping tree. Here's what that might look like.
    //
    // Let A = the clipping ancestor,
    //     B = the clip descendant, and
    //     SC = the stacking context that is the ancestor of A and B in the stacking tree.
    //
    // SC
    //  + A = m_graphicsLayer
    //  |  + m_childContainmentLayer
    //  |     + ...
    //  ...
    //  |
    //  + B = m_ancestorClippingLayer [+]
    //     + m_graphicsLayer
    //        + ...
    //
    // In this case B is clipped by another layer that doesn't happen to be its ancestor: A.
    // So we create an ancestor clipping layer for B, [+], which ensures that B is clipped
    // as if it had been A's descendant.
    OwnPtr<GraphicsLayer> m_ancestorClippingLayer; // Only used if we are clipped by an ancestor which is not a stacking context.
    OwnPtr<GraphicsLayer> m_graphicsLayer;
    OwnPtr<GraphicsLayer> m_childContainmentLayer; // Only used if we have clipping on a stacking context with compositing children.
    OwnPtr<GraphicsLayer> m_childTransformLayer; // Only used if we have perspective.
    OwnPtr<GraphicsLayer> m_scrollingLayer; // Only used if the layer is using composited scrolling.
    OwnPtr<GraphicsLayer> m_scrollingContentsLayer; // Only used if the layer is using composited scrolling.
    OwnPtr<GraphicsLayer> m_scrollingBlockSelectionLayer; // Only used if the layer is using composited scrolling, but has no scrolling contents apart from block selection gaps.

    // This layer is also added to the hierarchy by the RLB, but in a different way than
    // the layers above. It's added to m_graphicsLayer as its mask layer (naturally) if
    // we have a mask, and isn't part of the typical hierarchy (it has no children).
    OwnPtr<GraphicsLayer> m_maskLayer; // Only used if we have a mask.
    OwnPtr<GraphicsLayer> m_childClippingMaskLayer; // Only used if we have to clip child layers or accelerated contents with border radius or clip-path.

    // There are two other (optional) layers whose painting is managed by the CompositedLayerMapping,
    // but whose position in the hierarchy is maintained by the PaintLayerCompositor. These
    // are the foreground and background layers. The foreground layer exists if we have composited
    // descendants with negative z-order. We need the extra layer in this case because the layer
    // needs to draw both below (for the background, say) and above (for the normal flow content, say)
    // the negative z-order descendants and this is impossible with a single layer. The RLC handles
    // inserting m_foregroundLayer in the correct position in our descendant list for us (right after
    // the neg z-order dsecendants).
    //
    // The background layer is only created if this is the root layer and our background is entirely
    // fixed. In this case we want to put the background in a separate composited layer so that when
    // we scroll, we don't have to re-raster the background into position. This layer is also inserted
    // into the tree by the RLC as it gets a special home. This layer becomes a descendant of the
    // frame clipping layer. That is:
    //   ...
    //     + frame clipping layer
    //       + m_backgroundLayer
    //       + frame scrolling layer
    //         + root content layer
    //
    // With the hierarchy set up like this, the root content layer is able to scroll without affecting
    // the background layer (or paint invalidation).
    OwnPtr<GraphicsLayer> m_foregroundLayer; // Only used in cases where we need to draw the foreground separately.
    OwnPtr<GraphicsLayer> m_backgroundLayer; // Only used in cases where we need to draw the background separately.

    OwnPtr<GraphicsLayer> m_layerForHorizontalScrollbar;
    OwnPtr<GraphicsLayer> m_layerForVerticalScrollbar;
    OwnPtr<GraphicsLayer> m_layerForScrollCorner;

    // This layer exists to simplify the reparenting of overflow control that is occasionally required
    // to ensure that scrollbars appear above scrolling content.
    OwnPtr<GraphicsLayer> m_overflowControlsHostLayer;

    // The reparented overflow controls sometimes need to be clipped by a non-ancestor. In just the same
    // way we need an ancestor clipping layer to clip this CLM's internal hierarchy, we add another layer
    // to clip the overflow controls. It would be possible to make m_overflowControlsHostLayer be
    // responsible for applying this clip, but that could require repositioning all of the overflow
    // controls since the this clip may apply an offset. By using a separate layer, the overflow controls
    // can remain ignorant of the layers above them and still work correctly.
    OwnPtr<GraphicsLayer> m_overflowControlsClippingLayer;

    // A squashing CLM has two possible squashing-related structures.
    //
    // If m_ancestorClippingLayer is present:
    //
    // m_ancestorClippingLayer
    //   + m_graphicsLayer
    //   + m_squashingLayer
    //
    // If not:
    //
    // m_squashingContainmentLayer
    //   + m_graphicsLayer
    //   + m_squashingLayer
    //
    // Stacking children of a squashed layer receive graphics layers that are parented to the compositd ancestor of the
    // squashed layer (i.e. nearest enclosing composited layer that is not squashed).
    OwnPtr<GraphicsLayer> m_squashingContainmentLayer; // Only used if any squashed layers exist and m_squashingContainmentLayer is not present, to contain the squashed layers as siblings to the rest of the GraphicsLayer tree chunk.
    OwnPtr<GraphicsLayer> m_squashingLayer; // Only used if any squashed layers exist, this is the backing that squashed layers paint into.
    Vector<GraphicsLayerPaintInfo> m_squashedLayers;
    LayoutPoint m_squashingLayerOffsetFromTransformedAncestor;

    LayoutRect m_compositedBounds;

    LayoutSize m_contentOffsetInCompositingLayer;
    unsigned m_contentOffsetInCompositingLayerDirty : 1;

    unsigned m_pendingUpdateScope : 2;
    unsigned m_isMainFrameLayoutViewLayer : 1;

    unsigned m_backgroundLayerPaintsFixedRootBackground : 1;
    unsigned m_scrollingContentsAreEmpty : 1;

    mutable IntRect m_previousPaintInterestRect;

    friend class CompositedLayerMappingTest;
};

} // namespace blink

#endif // CompositedLayerMapping_h


text:
require 'spec_helper'

describe Obfuscator::Generic do
  before(:each) do
    User.create!(
      login: "login",
      email: "email@example.com",
      password: "pword",
      birthdate: 20.years.ago
    )

    User.create!(
      login: "login2",
      email: "email2@example.com",
      password: "pword"
    )
  end

  let(:obfuscator) { Obfuscator::Generic.new }
  let(:first_user) { User.first }
  let(:last_user)  { User.last }

  describe ".scrub!" do
    context "given a model" do
      it "assigns @model to the given model name" do
        obfuscator.scrub!("Person")
        obfuscator.model.should == Person
      end
    end

    context "not given a model" do
      it "defaults to 'User'" do
        obfuscator.scrub!
        obfuscator.model.should == User
      end
    end

    context "given an array of columns" do
      it "updates the given columns for each record" do
        first_user.login.should == "login"
        last_user.login.should == "login2"

        obfuscator.scrub!("User", [:login])

        first_user.reload.login.should_not == "login"
        last_user.reload.login.should_not == "login2"
      end

      it "obfuscates the given columns with dummy data" do
        Faker::Lorem.should_receive(:sentence).any_number_of_times.
          and_return("The quick brown fox")

        obfuscator.scrub!("User", [:email])

        first_user.reload.email.should == "The quick brown fox"
      end

      context "given a text column" do
        let(:paragraph) do
          "A slightly long section of text, one that would perhaps be too
          long to be stored as a string and might therefore be better stored
          as a text blizzle bluzzle."
        end

        it "obfuscates the column with a dummy paragraph" do
          Faker::Lorem.should_receive(:paragraph).any_number_of_times.
            and_return(paragraph)

          obfuscator.scrub!("User", [:bio])

          last_user.reload.bio.should == paragraph
        end
      end

      context "given an integer column" do
        it "obfuscates the column with a dummy number" do
          Obfuscator::Utilities.should_receive(:random_number).
            any_number_of_times.with(10)

          obfuscator.scrub!("User", [:id])
        end
      end

      context "given a boolean column" do
        let!(:person) { Person.create!(good_looking: true) }

        it "obfuscates the column with a random true or false" do
          Obfuscator::Utilities.should_receive(:random_boolean).
            and_return(false)

          obfuscator.scrub!("Person", [:good_looking])

          person.reload.good_looking.should be_false
        end
      end

      context "given a datetime column" do
        it "obfuscates the column with a random date" do
          Obfuscator::Utilities.stub(:random_date).any_number_of_times.
            and_return(1.year.ago.beginning_of_day)

          obfuscator.scrub!("User", [:birthdate])

          first_user.reload.birthdate.should == 1.year.ago.beginning_of_day
        end
      end

      context "given a string column" do
        context "not given a type parameter" do
          it "obfuscates the column with a dummy sentence" do
            Faker::Lorem.should_receive(:sentence).any_number_of_times.
              and_return("The quick brown fox")

            obfuscator.scrub!("User", [:login])

            first_user.reload.login.should == "The quick brown fox"
          end

          it "generates unique dummy sentences" do
            obfuscator.scrub!("User", [:login])

            first_user.reload.login.should_not == last_user.reload.login
          end
        end

        context "given a type parameter" do
          context "given valid type parameters" do
            it "generates a plausible user_name" do
              Faker::Internet.should_receive(:user_name).
                any_number_of_times.
                and_return("bryanawesome")

              Faker::Internet.should_receive(:email).
                any_number_of_times.
                and_return("bryanawesome@example.com")

              obfuscator.scrub!("User", { login: :user_name, email: :email })
            end

            context "given an invalid type parameter" do
              it "raises an UnkownObfuscationTypeError" do
                expect { obfuscator.scrub!("User", { login: :invalid_type }) }.
                  to raise_error(
                    Obfuscator::Generic::UnkownObfuscationTypeError
                  )
              end
            end
          end
        end
      end
    end

    context "not given an array of columns" do
      it "returns nil" do
        obfuscator.scrub!("User").should be_nil
      end
    end
  end
end


text:
module Keisan
  module Parsing
    class LogicalOr < LogicalOperator
      def node_class
        AST::LogicalOr
      end
    end
  end
end


text:
using System.Collections.Generic;

namespace Umbraco.Web.Media.EmbedProviders
{
    public class Twitter : EmbedProviderBase
    {
        public override string ApiEndpoint => "http://publish.twitter.com/oembed";

        public override string[] UrlSchemeRegex => new string[]
        {
            @"twitter.com/.*/status/.*"
        };

        public override Dictionary<string, string> RequestParams => new Dictionary<string, string>();

        public override string GetMarkup(string url, int maxWidth = 0, int maxHeight = 0)
        {
            var requestUrl = base.GetEmbedProviderUrl(url, maxWidth, maxHeight);
            var oembed = base.GetJsonResponse<OEmbedResponse>(requestUrl);

            return oembed.GetHtml();
        }
    }
}


text:
/**
 * \file
 * \brief kprintf support
 */

/*
 * Copyright (c) 2008, 2010, 2011, 2012 ETH Zurich
 * All rights reserved.
 *
 * This file is distributed under the terms in the attached LICENSE file.
 * If you do not find this file, copies can be found by writing to:
 * ETH Zurich D-INFK, Universitaetstrasse 6, CH-8092 Zurich. Attn: Systems Group.
 */

#ifndef KERNEL_ARCH_X86_KPUTCHAR_H
#define KERNEL_ARCH_X86_KPUTCHAR_H

#include <arch/x86/conio.h>
#include <serial.h>
#include <arch/x86/global.h>

#define kprintf_begin()  acquire_spinlock(&global->locks.print)
#define kprintf_end()    release_spinlock(&global->locks.print)

#if 0
static void delay(uint64_t ticks)
{
    uint64_t start = rdtsc();
    while (rdtsc() < start + ticks) {}
}
#endif

/* send all output to both VGA console and serial port, for now */
static inline int
kputchar(int c)
{
    if (c == '\n') {
        serial_console_putchar('\r');
        //delay(200000000);
    }

    conio_putchar(c);
    serial_console_putchar(c);
    return c;
}

#endif // KERNEL_ARCH_X86_KPUTCHAR_H