text:
from __future__ import absolute_import, division, print_function, unicode_literals

import collections
import os
from builtins import next, object, open
from contextlib import contextmanager
from unittest import TestCase
from xml.etree.ElementTree import ParseError

from mock import Mock, patch

from pants.base.exceptions import ErrorWhileTesting
from pants.task.task import TaskBase
from pants.task.testrunner_task_mixin import TestRunnerTaskMixin
from pants.util.contextutil import temporary_dir
from pants.util.dirutil import safe_open
from pants.util.process_handler import ProcessHandler, subprocess
from pants_test.task_test_base import TaskTestBase

class DummyTestTarget(object):
  def __init__(self, name, timeout=None):
    self.name = name
    self.timeout = timeout
    self.address = collections.namedtuple('address', ['spec'])(name)

targetA = DummyTestTarget('TargetA')
targetB = DummyTestTarget('TargetB', timeout=1)
targetC = DummyTestTarget('TargetC', timeout=10)

class TestRunnerTaskMixinTest(TaskTestBase):
  @classmethod
  def task_type(cls):
    class TestRunnerTaskMixinTask(TestRunnerTaskMixin, TaskBase):
      call_list = []

      def _execute(self, all_targets):
        self.call_list.append(['_execute', all_targets])
        self.spawn_and_wait()

      def _spawn(self, *args, **kwargs):
        self.call_list.append(['_spawn', args, kwargs])

        class FakeProcessHandler(ProcessHandler):
          def wait(_, timeout=None):
            self.call_list.append(['process_handler.wait'])
            return 0

          def kill(_):
            self.call_list.append(['process_handler.kill'])

          def terminate(_):
            self.call_list.append(['process_handler.terminate'])

          def poll(_):
            self.call_list.append(['process_handler.poll'])

        return FakeProcessHandler()

      def _get_targets(self):
        return [targetA, targetB]

      def _test_target_filter(self):
        def target_filter(target):
          self.call_list.append(['target_filter', target])
          if target.name == 'TargetA':
            return False
          else:
            return True

        return target_filter

      def _validate_target(self, target):
        self.call_list.append(['_validate_target', target])

    return TestRunnerTaskMixinTask

  def test_execute_normal(self):
    task = self.create_task(self.context())

    task.execute()

    # Confirm that everything ran as expected
    self.assertIn(['target_filter', targetA], task.call_list)
    self.assertIn(['target_filter', targetB], task.call_list)
    self.assertIn(['_validate_target', targetB], task.call_list)
    self.assertIn(['_execute', [targetA, targetB]], task.call_list)

  def test_execute_skip(self):
    # Set the skip option
    self.set_options(skip=True)
    task = self.create_task(self.context())
    task.execute()

    # Ensure nothing got called
    self.assertListEqual(task.call_list, [])

  def test_get_timeouts_no_default(self):
    """If there is no default and one of the targets has no timeout, then there is no timeout for the entire run."""

    self.set_options(timeouts=True, timeout_default=None)
    task = self.create_task(self.context())

    self.assertIsNone(task._timeout_for_targets([targetA, targetB]))

  def test_get_timeouts_disabled(self):
    """If timeouts are disabled, there is no timeout for the entire run."""

    self.set_options(timeouts=False, timeout_default=2)
    task = self.create_task(self.context())

    self.assertIsNone(task._timeout_for_targets([targetA, targetB]))

  def test_get_timeouts_with_default(self):
    """If there is a default timeout, use that for targets which have no timeout set."""

    self.set_options(timeouts=True, timeout_default=2)
    task = self.create_task(self.context())

    self.assertEqual(task._timeout_for_targets([targetA, targetB]), 3)

  def test_get_timeouts_with_maximum(self):
    """If a timeout exceeds the maximum, set it to that."""

    self.set_options(timeouts=True, timeout_maximum=1)
    task = self.create_task(self.context())
    self.assertEqual(task._timeout_for_targets([targetC]), 1)

  def test_default_maximum_conflict(self):
    """If the default exceeds the maximum, throw an error."""

    self.set_options(timeouts=True, timeout_maximum=1, timeout_default=10)
    task = self.create_task(self.context())
    with self.assertRaises(ErrorWhileTesting):
      task.execute()

class TestRunnerTaskMixinSimpleTimeoutTest(TaskTestBase):
  @classmethod
  def task_type(cls):
    class TestRunnerTaskMixinTask(TestRunnerTaskMixin, TaskBase):
      waited_for = None

      def _execute(self, all_targets):
        self.spawn_and_wait()

      def _spawn(self, *args, **kwargs):
        timeouts = self.get_options().timeouts

        class FakeProcessHandler(ProcessHandler):
          def wait(_, timeout=None):
            self.waited_for = timeout
            if timeouts and timeout:
              raise subprocess.TimeoutExpired(cmd='', timeout=timeout)
            return 0

          def kill(_):
            pass

          def terminate(_):
            pass

          def poll(_):
            return 0

        return FakeProcessHandler()

      def _get_targets(self):
        return [targetB]

      def _test_target_filter(self):
        return lambda target: True

      def _validate_target(self, target):
        pass

    return TestRunnerTaskMixinTask

  def test_timeout(self):
    self.set_options(timeouts=True)
    task = self.create_task(self.context())

    with self.assertRaises(ErrorWhileTesting):
      task.execute()

    # Ensures that the wait is for 1 second.
    self.assertEqual(task.waited_for, 1)

  def test_timeout_disabled(self):
    self.set_options(timeouts=False)
    task = self.create_task(self.context())

    task.execute()

    # Ensures that the wait time is forever (no timeout).
    self.assertIsNone(task.waited_for)

class TestRunnerTaskMixinGracefulTimeoutTest(TaskTestBase):

  def create_process_handler(self, poll_returns, wait_succeeds):
    poll_return_values = iter(poll_returns)
    wait_succeeds_values = iter(wait_succeeds)

    class FakeProcessHandler(ProcessHandler):
      call_list = []
      poll_called = False

      def wait(self, timeout=None):
        self.call_list.append(['process_handler.wait'])
        if next(wait_succeeds_values):
          return 0
        else:
          raise subprocess.TimeoutExpired(cmd='', timeout=timeout)

      def kill(self):
        self.call_list.append(['process_handler.kill'])

      def terminate(self):
        self.call_list.append(['process_handler.terminate'])

      def poll(self):
        self.call_list.append(['process_handler.poll'])
        return next(poll_return_values)

    return FakeProcessHandler()

  def task_type(cls):
    class TestRunnerTaskMixinTask(TestRunnerTaskMixin, TaskBase):
      call_list = []

      def _execute(self, all_targets):
        self.call_list.append(['_execute', all_targets])
        self.spawn_and_wait()

      def _spawn(self, *args, **kwargs):
        self.call_list.append(['_spawn', args, kwargs])

        return cls.process_handler

      def _get_targets(self):
        return [targetA, targetB]

      def _test_target_filter(self):
        def target_filter(target):
          self.call_list.append(['target_filter', target])
          if target.name == 'TargetA':
            return False
          else:
            return True

        return target_filter

      def _validate_target(self, target):
        self.call_list.append(['_validate_target', target])

    return TestRunnerTaskMixinTask

  @contextmanager
  def mock_timer(self):
    with patch('threading.Timer') as timer_class:
      timer = Mock()

      def start():
        args, _ = timer_class.call_args
        wait_time, action = args
        self.assertEqual(10, wait_time)
        action()

      timer.start.side_effect = start
      timer_class.return_value = timer

      yield

  def test_graceful_kill_if_terminate_expires(self):
    self.process_handler = self.create_process_handler(poll_returns=[None],
                                                       wait_succeeds=[False, False])
    self.set_options(timeouts=True)
    task = self.create_task(self.context())

    with self.mock_timer():
      with self.assertRaises(ErrorWhileTesting):
        task.execute()

    # Ensure that all the calls we want to kill the process gracefully are made.
    self.assertEqual(self.process_handler.call_list,
                     [['process_handler.wait'],
                      ['process_handler.poll'],
                      ['process_handler.terminate'],
                      ['process_handler.wait'],
                      ['process_handler.kill']])

  def test_graceful_terminate(self):
    self.process_handler = self.create_process_handler(poll_returns=[None],
                                                       wait_succeeds=[False, True])

    self.set_options(timeouts=True)
    task = self.create_task(self.context())

    with self.mock_timer():
      with self.assertRaises(ErrorWhileTesting):
        task.execute()

    # Ensure that we only call terminate, and not kill.
    self.assertEqual(self.process_handler.call_list,
                     [['process_handler.wait'],
                      ['process_handler.poll'],
                      ['process_handler.terminate'],
                      ['process_handler.wait']])

class TestRunnerTaskMixinMultipleTargets(TaskTestBase):

  @classmethod
  def task_type(cls):
    class TestRunnerTaskMixinMultipleTargetsTask(TestRunnerTaskMixin, TaskBase):
      wait_time = None

      def _execute(self, all_targets):
        self.spawn_and_wait()

      def _spawn(self, *args, **kwargs):
        terminate_wait = self.get_options().timeout_terminate_wait

        class FakeProcessHandler(ProcessHandler):
          def wait(_, timeout=None):
            # If this is not a call to `wait` for the termination timeout, count it.
            if timeout != terminate_wait:
              self.wait_time = timeout
            raise subprocess.TimeoutExpired(cmd='', timeout=timeout)

          def kill(_):
            pass

          def terminate(_):
            pass

          def poll(_):
            pass

        return FakeProcessHandler()

      def _test_target_filter(self):
        return lambda target: True

      def _validate_target(self, target):
        pass

      def _get_test_targets_for_spawn(self):
        return self.current_targets

    return TestRunnerTaskMixinMultipleTargetsTask

  def test_multiple_targets(self):
    self.set_options(timeouts=True, timeout_terminate_wait=1337)
    task = self.create_task(self.context())

    task.current_targets = [targetB]
    with self.assertRaises(ErrorWhileTesting) as cm:
      task.execute()
    self.assertEqual(1, task.wait_time)
    self.assertEqual([targetB], cm.exception.failed_targets)

    task.current_targets = [targetC]
    with self.assertRaises(ErrorWhileTesting) as cm:
      task.execute()
    self.assertEqual(10, task.wait_time)
    self.assertEqual([targetC], cm.exception.failed_targets)

    task.current_targets = [targetB, targetC]
    with self.assertRaises(ErrorWhileTesting) as cm:
      task.execute()
    self.assertEqual(11, task.wait_time)  # We should wait for the sum of the target timeouts.
    self.assertEqual([targetB, targetC], cm.exception.failed_targets)

class TestRunnerTaskMixinXmlParsing(TestRunnerTaskMixin, TestCase):
  @staticmethod
  def _raise_handler(e):
    raise e

  class CollectHandler(object):
    def __init__(self):
      self._errors = []

    def __call__(self, e):
      self._errors.append(e)

    @property
    def errors(self):
      return self._errors

  def test_parse_test_info_no_files(self):
    with temporary_dir() as xml_dir:
      test_info = self.parse_test_info(xml_dir, self._raise_handler)

      self.assertEqual({}, test_info)

  def test_parse_test_info_all_testcases(self):
    with temporary_dir() as xml_dir:
      with open(os.path.join(xml_dir, 'TEST-a.xml'), 'w') as fp:
        fp.write("""
        <testsuite failures="1" errors="1">
          <testcase classname="org.pantsbuild.Green" name="testOK" time="1.290"/>
          <testcase classname="org.pantsbuild.Failure" name="testFailure" time="0.27">
            <failure/>
          </testcase>
          <testcase classname="org.pantsbuild.Error" name="testError" time="0.932">
            <error/>
          </testcase>
          <testcase classname="org.pantsbuild.Skipped" name="testSkipped" time="0.1">
            <skipped/>
          </testcase>
        </testsuite>
        """)

      tests_info = self.parse_test_info(xml_dir, self._raise_handler)
      self.assertEqual(
        {
          'testOK': {
            'result_code': 'success',
            'time': 1.290
          },
          'testFailure': {
            'result_code': 'failure',
            'time': 0.27
          },
          'testError': {
            'result_code': 'error',
            'time': 0.932
          },
          'testSkipped': {
            'result_code': 'skipped',
            'time': 0.1
          }
        }, tests_info)

  def test_parse_test_info_with_missing_attributes(self):
    with temporary_dir() as xml_dir:
      with open(os.path.join(xml_dir, 'TEST-a.xml'), 'w') as fp:
        fp.write("""
        <testsuite failures="1">
          <testcase classname="org.pantsbuild.Green" name="testOK"/>
          <testcase classname="org.pantsbuild.Failure" time="0.27">
            <failure/>
          </testcase>
          <testcase classname="org.pantsbuild.Skipped" name="testSkipped" time="0.1" extra="">
            <skipped/>
          </testcase>
        </testsuite>
        """)

      tests_info = self.parse_test_info(xml_dir, self._raise_handler)
      self.assertEqual(
        {
          'testOK': {
            'result_code': 'success',
            'time': None
          },
          '': {
            'result_code': 'failure',
            'time': 0.27
          },
          'testSkipped': {
            'result_code': 'skipped',
            'time': 0.1
          }
        }, tests_info)

  def test_parse_test_info_invalid_file_name(self):
    with temporary_dir() as xml_dir:
      with open(os.path.join(xml_dir, 'random.xml'), 'w') as fp:
        fp.write('<invalid></xml>')

      tests_info = self.parse_test_info(xml_dir, self._raise_handler)
      self.assertEqual({}, tests_info)

  def test_parse_test_info_invalid_dir(self):
    with temporary_dir() as xml_dir:
      with safe_open(os.path.join(xml_dir, 'subdir', 'TEST-c.xml'), 'w') as fp:
        fp.write('<invalid></xml>')

      tests_info = self.parse_test_info(xml_dir, self._raise_handler)
      self.assertEqual({}, tests_info)

  def test_parse_test_info_error_raise(self):
    with temporary_dir() as xml_dir:
      xml_file = os.path.join(xml_dir, 'TEST-bad.xml')
      with open(xml_file, 'w') as fp:
        fp.write('<invalid></xml>')
      with self.assertRaises(Exception) as exc:
        self.parse_test_info(xml_dir, self._raise_handler)
      self.assertEqual(xml_file, exc.exception.xml_path)
      self.assertIsInstance(exc.exception.cause, ParseError)

  def test_parse_test_info_error_continue(self):
    with temporary_dir() as xml_dir:
      bad_file1 = os.path.join(xml_dir, 'TEST-bad1.xml')
      with open(bad_file1, 'w') as fp:
        fp.write('<invalid></xml>')
      with open(os.path.join(xml_dir, 'TEST-good.xml'), 'w') as fp:
        fp.write("""
        <testsuite failures="0" errors="1">
          <testcase classname="org.pantsbuild.Error" name="testError" time="1.2">
            <error/>
          </testcase>
        </testsuite>
        """)

      collect_handler = self.CollectHandler()
      tests_info = self.parse_test_info(xml_dir, collect_handler)
      self.assertEqual(1, len(collect_handler.errors))
      self.assertEqual({bad_file1}, {e.xml_path for e in collect_handler.errors})

      self.assertEqual(
        {'testError':
          {
            'result_code': 'error',
            'time': 1.2
          }
        }, tests_info)

  def test_parse_test_info_extra_attributes(self):
    with temporary_dir() as xml_dir:
      with open(os.path.join(xml_dir, 'TEST-a.xml'), 'w') as fp:
        fp.write("""
        <testsuite errors="1">
          <testcase classname="org.pantsbuild.Green" name="testOK1" time="1.290" file="file.py"/>
          <testcase classname="org.pantsbuild.Green" name="testOK2" time="1.12"/>
          <testcase classname="org.pantsbuild.Green" name="testOK3" file="file.py"/>
          <testcase name="testOK4" time="1.79" file="file.py"/>
          <testcase name="testOK5" time="0.832"/>
          <testcase classname="org.pantsbuild.Error" name="testError" time="0.27" file="file.py">
            <error/>
          </testcase>
        </testsuite>
        """)

      tests_info = self.parse_test_info(xml_dir, self._raise_handler, ['file', 'classname'])
      self.assertEqual(
        {
          'testOK1': {
            'file': 'file.py',
            'classname': 'org.pantsbuild.Green',
            'result_code': 'success',
            'time': 1.290
          },
          'testOK2': {
            'file': None,
            'classname': 'org.pantsbuild.Green',
            'result_code': 'success',
            'time': 1.12
          },
          'testOK3': {
            'file': 'file.py',
            'classname': 'org.pantsbuild.Green',
            'result_code': 'success',
            'time': None
          },
          'testOK4': {
            'file': 'file.py',
            'classname': None,
            'result_code': 'success',
            'time': 1.79
          },
          'testOK5': {
            'file': None,
            'classname': None,
            'result_code': 'success',
            'time': 0.832
          },
          'testError': {
            'file': 'file.py',
            'classname': 'org.pantsbuild.Error',
            'result_code': 'error',
            'time': 0.27
          }
        }, tests_info)


text:
package com.intellij.util.containers;

import java.util.Collections;
import java.util.ListIterator;
import java.util.NoSuchElementException;

/**
 * @deprecated Use {@link Collections#emptyListIterator()} instead
 */
@Deprecated
class EmptyListIterator<E> extends EmptyIterator<E> implements ListIterator<E> {
  private EmptyListIterator() {
  }

  private static final EmptyListIterator<Object> INSTANCE = new EmptyListIterator<Object>();

  public static <E> EmptyListIterator<E> getInstance() {
    //noinspection unchecked
    return (EmptyListIterator<E>)INSTANCE;
  }

  public boolean hasPrevious() {
    return false;
  }

  public E previous() {
    throw new NoSuchElementException();
  }

  public int nextIndex() {
    return 0;
  }

  public int previousIndex() {
    return -1;
  }

  public void set(E e) {
    throw new IllegalStateException();
  }

  public void add(E e) {
    throw new UnsupportedOperationException();
  }
}

redpajama_set_name: RedPajamaGithub


text:
<?php if ($status == "sucess") {
    ?>

            ×

           Patient Ward Admission Requested Successfully..!

    <?php
} elseif ($status == "fail") {
    ?>

            ×

           Patient Ward Admission Requested Not Successfully..!

    <?php
}
?>


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

<title>org.ojalgo.optimisation.quadratic Class Hierarchy</title>
<meta name="date" content="2013-04-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes

Hierarchy For Package org.ojalgo.optimisation.quadratic

Package Hierarchies:

All Packages

Class Hierarchy

java.lang.Object

org.ojalgo.optimisation.GenericSolver (implements org.ojalgo.optimisation.Optimisation.Solver)

org.ojalgo.optimisation.BaseSolver

org.ojalgo.optimisation.quadratic.QuadraticSolver

org.ojalgo.optimisation.quadratic.SequentailQuadraticSolver

org.ojalgo.optimisation.quadratic.QuadraticSolver.Builder

Overview

Package

Class

Tree

Deprecated

Help

Prev

Next

Frames

No Frames

All Classes


text:
__attribute__((weak))
__attribute__((visibility("hidden")))
void _compilerrt_abort_impl(const char *file, int line, const char *func) {
}
#endif


text:
package de.peeeq.wurstscript.types;

import com.google.common.collect.ImmutableCollection;
import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Lists;
import de.peeeq.wurstscript.ast.*;
import de.peeeq.wurstscript.attributes.names.*;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

import java.util.*;
import java.util.stream.Stream;

public abstract class WurstTypeNamedScope extends WurstType {

    private final boolean isStaticRef;
    // TODO change this to a list of TypeParamDef and add typeMapping?
    private final List<WurstTypeBoundTypeParam> typeParameters;

    public WurstTypeNamedScope(List<WurstTypeBoundTypeParam> typeParameters, boolean isStaticRef) {
        this.isStaticRef = isStaticRef;
        this.typeParameters = typeParameters;
    }

    public WurstTypeNamedScope(List<WurstTypeBoundTypeParam> typeParameters) {
        this.isStaticRef = false;
        this.typeParameters = typeParameters;
    }

    public WurstTypeNamedScope(boolean isStaticRef) {
        this.isStaticRef = isStaticRef;
        this.typeParameters = Collections.emptyList();
    }

    @Override
    public String getName() {
        NamedScope def = getDef();
        if (def == null) {
            return "not found";
        }
        return def.getName();
    }

    public abstract @Nullable NamedScope getDef();

    @Override
    public String getFullName() {
        return getName();
    }

    @Override
    public boolean isStaticRef() {
        return isStaticRef;
    }

    @Override
    VariableBinding matchAgainstSupertypeIntern(WurstType obj, @Nullable Element location, VariableBinding mapping, VariablePosition variablePosition) {
        if (obj instanceof WurstTypeNamedScope) {
            WurstTypeNamedScope other = (WurstTypeNamedScope) obj;
            if (other.getDef() == this.getDef()) {
                return matchTypeParams(getTypeParameters(), other.getTypeParameters(), location, mapping, variablePosition);
            }
        }
        return null;
    }

    public List<WurstTypeBoundTypeParam> getTypeParameters() {
        return typeParameters;
    }

    protected String printTypeParams() {
        if (typeParameters.size() == 0) {
            return "";
        }
        StringBuilder s = new StringBuilder("<");
        for (int i = 0; i < typeParameters.size(); i++) {
            if (i > 0) {
                s.append(", ");
            }
            s.append(typeParameters.get(i).getName());
        }
        return s + ">";
    }

    @Override
    public VariableBinding getTypeArgBinding() {
        VariableBinding res = VariableBinding.emptyMapping();
        for (WurstTypeBoundTypeParam tp : typeParameters) {
            res = res.set(tp.getTypeParamDef(), tp);
        }
        return res;
    }

    @Override
    public WurstType setTypeArgs(@NonNull VariableBinding typeParamBounds) {
        List<WurstTypeBoundTypeParam> newTypes = Lists.newArrayList();
        for (WurstTypeBoundTypeParam t : typeParameters) {
            newTypes.add(t.setTypeArgs(typeParamBounds));
        }
        return replaceTypeVars(newTypes);
    }

    abstract public WurstType replaceTypeVars(List<WurstTypeBoundTypeParam> newTypes);

    public WurstType replaceTypeVarsUsingTypeArgs(TypeExprList typeArgs) {
        if (typeArgs.isEmpty()) {
            // TODO replace with unknown types?
            return this;
        }
        List<WurstTypeBoundTypeParam> typeParams = new ArrayList<>();

        if (typeArgs.size() != typeParameters.size()) {
            typeArgs.addError("Expected " + typeParameters.size() + " type arguments, but got " + typeArgs.size());
        }

        for (int i = 0; i < typeArgs.size() && i < typeParameters.size(); i++) {
            WurstTypeBoundTypeParam tp = typeParameters.get(i);
            TypeParamDef tpDef = tp.getTypeParamDef();
            TypeExpr typeArg = typeArgs.get(i);
            WurstType baseType = typeArg.attrTyp().dynamic();
            typeParams.add(new WurstTypeBoundTypeParam(tpDef, baseType, typeArg));
        }

//		List<WurstType> newTypes = node.getTypeArgs().stream()
//				.map((TypeExpr te) -> te.attrTyp().dynamic())
//				.collect(Collectors.toList());

        return replaceTypeVars(typeParams);
    }

    protected VariableBinding matchTypeParams(List<WurstTypeBoundTypeParam> list, List<WurstTypeBoundTypeParam> list2, @Nullable Element location, VariableBinding mapping, VariablePosition variablePosition) {

        if (list.size() != list2.size()) {
            return null;
        }
        for (int i = 0; i < list.size(); i++) {
            WurstType thisTp = list.get(i).normalize();
            WurstType otherTp = list2.get(i).normalize();
            mapping = thisTp.matchTypes(otherTp, location, mapping, variablePosition);
            if (mapping == null) {
                return null;
            }
        }
        return mapping;
    }

    @Override
    public boolean allowsDynamicDispatch() {
        // dynamic dispatch is possible if this is not a static reference
        return !isStaticRef();
    }

    /**
     * get the name links available in this class or interface
     * This includes inherited names
     */
    public ImmutableMultimap<String, DefLink> nameLinks() {
        ImmutableMultimap<String, DefLink> res = getDef().attrNameLinks();
        VariableBinding binding = getTypeArgBinding();
        if (!binding.isEmpty()) {
            // OPT maybe cache this
            ImmutableMultimap.Builder<String, DefLink> resBuilder = ImmutableMultimap.builder();
            for (Map.Entry<String, DefLink> e : res.entries()) {
                resBuilder.put(e.getKey(), e.getValue().withTypeArgBinding(getDef(), binding));
            }
            return resBuilder.build();
        }
        return res;
    }

    public ImmutableCollection<DefLink> nameLinks(String name) {
        return nameLinks().get(name);
    }

    @Override
    public void addMemberMethods(Element node, String name,
                                 List<FuncLink> result) {
        for (DefLink defLink : nameLinks(name)) {
            if (defLink instanceof FuncLink) {
                FuncLink f = (FuncLink) defLink;
                if (f.getVisibility().isPublic()) {
                    result.add(f);
                } else if (f.getVisibility().isInherited()) {
                    // for protected members:
                    NamedScope def = getDef();
                    if (def != null && node.attrNearestPackage() != def.attrNearestPackage()) {
                        // if in different package, check if we are in a subclass:
                        ClassDef nearestClass = node.attrNearestClassDef();
                        if (nearestClass == null
                                || !nearestClass.attrTypC().isSubtypeOf(this, node)) {
                            // if not in a subclass, change to not visible
                            f = f.withVisibility(Visibility.PROTECTED_OTHER);
                        }
                    }
                    result.add(f);
                }
            }
        }
    }

    @Override
    public Stream<FuncLink> getMemberMethods(Element node) {
        return nameLinks().values().stream()
                .filter(n -> {
                    WurstType receiverType = n.getReceiverType();
                    return n instanceof FuncLink
                            && receiverType != null;
                }).map(n -> (FuncLink) n);
    }

    @Override
    public boolean isNestedInside(WurstType other) {
        if (other instanceof WurstTypeNamedScope) {
            WurstTypeNamedScope wtns = (WurstTypeNamedScope) other;
            NamedScope scope = wtns.getDef();
            Element node = this.getDef();
            while (node != null) {
                if (node == scope) {
                    return true;
                }
                node = node.getParent();
            }
        }
        return false;
    }

    @Override
    protected boolean isNullable() {
        return true;
    }

}


text:
'use strict';

/**
 * 编辑规范 Controller
 * @class WebGuideManageCtrl
 * @author Linder linder0209@126.com
 * @createdDate 2015-5-29
 * */

angular.module('webGuideApp').controller('WebGuideManageCtrl',
  function ($scope, $location, $modal, webGuideManageService, publishMethod) {
    //先销毁tinyMCE实例
    if (tinymce && tinymce.get('ui-tinymce-0')) {
      tinymce.get('ui-tinymce-0').destroy();
    }

    $scope.guide = {
      type: '',
      content: '',//原内容
      catalogueHtml: '',//目录
      catalogueContent: ''//带目录的内容
    };

    //jshint -W106
    $scope.tinymceOptions = {
      height: document.documentElement.clientHeight - 198,
      menubar: false, //Disable all menu
      content_css: '/styles/tinymce.css',
      code_dialog_width: Math.min(tinymce.DOM.getViewPort().w - 50, 500),
      code_dialog_height: Math.min(tinymce.DOM.getViewPort().h - 50, 500),
      plugins: [
        'autolink link image preview hr code fullscreen table textcolor charmap syntaxhighlighter'
      ],
      toolbar: 'undo redo | bold italic underline strikethrough subscript superscript | styleselect | fontselect fontsizeselect formatselect ' +
      '| forecolor backcolor removeformat | bullist numlist outdent indent blockquote | alignleft aligncenter alignright alignjustify | ' +
      'hr image link unlink | charmap table syntaxhighlighter code | preview fullscreen'
    };

    $scope.switchTo = function (type, event) {
      if (type === $scope.guide.type) {
        return;
      }
      var $el = event ? $(event.currentTarget) : $('.nav-sidebar a[guide-docs="' + type + '"]');
      location.hash = type;
      webGuideManageService.getGuide(type, function (data) {
        if (data.success === true) {
          $el.parent().addClass('active').siblings().removeClass('active');
          $scope.guide.type = type;
          $scope.guide.content = data.content;
        }
      });
    };

    $scope.switchTo(location.hash !== '' ? location.hash.slice(2) : 'html');

    /**
     * 保存
     */
    $scope.saveGuide = function (confirm) {
      //生成带目录的html片段
      var guide = $scope.guide;
      var html = publishMethod.generateHtml(guide.content);
      guide.catalogueHtml = html.catalogue || '';
      guide.catalogueContent = html.content || '';

      webGuideManageService.saveGuide(guide, function (data) {
        if (confirm !== false) {
          $modal.open({
            templateUrl: '../views/templates/alert-modal.html',
            controller: 'AlertModalCtrl',
            size: 'sm',
            resolve: {
              config: function () {
                return {
                  modalTitle: '提示信息',
                  modalContent: data.success === true ? '保存成功!' : '保存失败!'
                };
              }
            }
          });
        }
      });
    };

    //十分钟自动保存一次
    setInterval(function () {
      $scope.saveGuide(false);
    }, 600000);

    //添加resize事件
    $(window).resize(function () {
      tinymce.get('ui-tinymce-0').iframeElement.style.height = document.documentElement.clientHeight - 198 + 'px';
    });
  });


text:
'''
Module: exceptions.py
Desc: stateful arib teletext decoder
Author: John O'Neil
Email: oneil.john@gmail.com
DATE: Sat, March 16th 2014

handling for code sets in japanese closed captions

'''
class UnimplimentedError(Exception):
  def __init__(self, msg='No further info'):
    self._msg = msg
  def __str__(self):
    return 'Unimplimented: {msg}'.format(msg=self._msg)

class DecodingError(Exception):
  def __init__(self, msg='No further info'):
    self._msg = msg
  def __str__(self):
    return 'Decoding Error: {msg}'.format(msg=self._msg)

class FileOpenError(Exception):
  def __init__(self, msg='No further info'):
    self._msg = msg

  def __str__(self):
    return 'File open error: : {msg}'.format(msg=self._msg)


text:
require_relative 'common_examples'

shared_examples_for 'exists command' do
  before do
    args << 'exists'
  end

  it 'returns 0 for an existing container' do
    expect(specification).to receive(:exists?).with(no_args).and_return(true)
    expect(command_run).to eq(0)
  end

  it 'returns 1 for a non-existent container' do
    expect(specification).to receive(:exists?).with(no_args).and_return(false)
    expect(command_run).to eq(1)
  end
end

describe 'tainers exists' do
  it_behaves_like 'a command', 'exists command'
end


text:
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>
#include <sys/queue.h>

#include <rte_random.h>
#include <rte_cycles.h>
#include <rte_memory.h>
#include <rte_memzone.h>
#include <rte_eal.h>
#include <rte_eal_memconfig.h>
#include <rte_common.h>
#include <rte_string_fns.h>
#include <rte_errno.h>
#include <rte_malloc.h>
#include "../../lib/librte_eal/common/malloc_elem.h"

#include "test.h"

/*
 * Memzone
 * =======
 *
 * - Search for three reserved zones or reserve them if they do not exist:
 *
 *   - One is on any socket id.
 *   - The second is on socket 0.
 *   - The last one is on socket 1 (if socket 1 exists).
 *
 * - Check that the zones exist.
 *
 * - Check that the zones are cache-aligned.
 *
 * - Check that zones do not overlap.
 *
 * - Check that the zones are on the correct socket id.
 *
 * - Check that a lookup of the first zone returns the same pointer.
 *
 * - Check that it is not possible to create another zone with the
 *   same name as an existing zone.
 *
 * - Check flags for specific huge page size reservation
 */

/* Test if memory overlaps: return 1 if true, or 0 if false. */
static int
is_memory_overlap(phys_addr_t ptr1, size_t len1, phys_addr_t ptr2, size_t len2)
{
	if (ptr2 >= ptr1 && (ptr2 - ptr1) < len1)
		return 1;
	else if (ptr2 < ptr1 && (ptr1 - ptr2) < len2)
		return 1;
	return 0;
}

static int
test_memzone_invalid_alignment(void)
{
	const struct rte_memzone * mz;

	mz = rte_memzone_lookup("invalid_alignment");
	if (mz != NULL) {
		printf("Zone with invalid alignment has been reserved\n");
		return -1;
	}

	mz = rte_memzone_reserve_aligned("invalid_alignment", 100,
			SOCKET_ID_ANY, 0, 100);
	if (mz != NULL) {
		printf("Zone with invalid alignment has been reserved\n");
		return -1;
	}
	return 0;
}

static int
test_memzone_reserving_zone_size_bigger_than_the_maximum(void)
{
	const struct rte_memzone * mz;

	mz = rte_memzone_lookup("zone_size_bigger_than_the_maximum");
	if (mz != NULL) {
		printf("zone_size_bigger_than_the_maximum has been reserved\n");
		return -1;
	}

	mz = rte_memzone_reserve("zone_size_bigger_than_the_maximum", (size_t)-1,
			SOCKET_ID_ANY, 0);
	if (mz != NULL) {
		printf("It is impossible to reserve such big a memzone\n");
		return -1;
	}

	return 0;
}

static int
test_memzone_reserve_flags(void)
{
	const struct rte_memzone *mz;
	const struct rte_memseg *ms;
	int hugepage_2MB_avail = 0;
	int hugepage_1GB_avail = 0;
	int hugepage_16MB_avail = 0;
	int hugepage_16GB_avail = 0;
	const size_t size = 100;
	int i = 0;
	ms = rte_eal_get_physmem_layout();
	for (i = 0; i < RTE_MAX_MEMSEG; i++) {
		if (ms[i].hugepage_sz == RTE_PGSIZE_2M)
			hugepage_2MB_avail = 1;
		if (ms[i].hugepage_sz == RTE_PGSIZE_1G)
			hugepage_1GB_avail = 1;
		if (ms[i].hugepage_sz == RTE_PGSIZE_16M)
			hugepage_16MB_avail = 1;
		if (ms[i].hugepage_sz == RTE_PGSIZE_16G)
			hugepage_16GB_avail = 1;
	}
	/* Display the availability of 2MB ,1GB, 16MB, 16GB pages */
	if (hugepage_2MB_avail)
		printf("2MB Huge pages available\n");
	if (hugepage_1GB_avail)
		printf("1GB Huge pages available\n");
	if (hugepage_16MB_avail)
		printf("16MB Huge pages available\n");
	if (hugepage_16GB_avail)
		printf("16GB Huge pages available\n");
	/*
	 * If 2MB pages available, check that a small memzone is correctly
	 * reserved from 2MB huge pages when requested by the RTE_MEMZONE_2MB flag.
	 * Also check that RTE_MEMZONE_SIZE_HINT_ONLY flag only defaults to an
	 * available page size (i.e 1GB ) when 2MB pages are unavailable.
	 */
	if (hugepage_2MB_avail) {
		mz = rte_memzone_reserve("flag_zone_2M", size, SOCKET_ID_ANY,
				RTE_MEMZONE_2MB);
		if (mz == NULL) {
			printf("MEMZONE FLAG 2MB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_2M) {
			printf("hugepage_sz not equal 2M\n");
			return -1;
		}

		mz = rte_memzone_reserve("flag_zone_2M_HINT", size, SOCKET_ID_ANY,
				RTE_MEMZONE_2MB|RTE_MEMZONE_SIZE_HINT_ONLY);
		if (mz == NULL) {
			printf("MEMZONE FLAG 2MB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_2M) {
			printf("hugepage_sz not equal 2M\n");
			return -1;
		}

		/* Check if 1GB huge pages are unavailable, that function fails unless
		 * HINT flag is indicated
		 */
		if (!hugepage_1GB_avail) {
			mz = rte_memzone_reserve("flag_zone_1G_HINT", size, SOCKET_ID_ANY,
					RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY);
			if (mz == NULL) {
				printf("MEMZONE FLAG 1GB & HINT\n");
				return -1;
			}
			if (mz->hugepage_sz != RTE_PGSIZE_2M) {
				printf("hugepage_sz not equal 2M\n");
				return -1;
			}

			mz = rte_memzone_reserve("flag_zone_1G", size, SOCKET_ID_ANY,
					RTE_MEMZONE_1GB);
			if (mz != NULL) {
				printf("MEMZONE FLAG 1GB\n");
				return -1;
			}
		}
	}

	/*As with 2MB tests above for 1GB huge page requests*/
	if (hugepage_1GB_avail) {
		mz = rte_memzone_reserve("flag_zone_1G", size, SOCKET_ID_ANY,
				RTE_MEMZONE_1GB);
		if (mz == NULL) {
			printf("MEMZONE FLAG 1GB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_1G) {
			printf("hugepage_sz not equal 1G\n");
			return -1;
		}

		mz = rte_memzone_reserve("flag_zone_1G_HINT", size, SOCKET_ID_ANY,
				RTE_MEMZONE_1GB|RTE_MEMZONE_SIZE_HINT_ONLY);
		if (mz == NULL) {
			printf("MEMZONE FLAG 1GB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_1G) {
			printf("hugepage_sz not equal 1G\n");
			return -1;
		}

		/* Check if 1GB huge pages are unavailable, that function fails unless
		 * HINT flag is indicated
		 */
		if (!hugepage_2MB_avail) {
			mz = rte_memzone_reserve("flag_zone_2M_HINT", size, SOCKET_ID_ANY,
					RTE_MEMZONE_2MB|RTE_MEMZONE_SIZE_HINT_ONLY);
			if (mz == NULL){
				printf("MEMZONE FLAG 2MB & HINT\n");
				return -1;
			}
			if (mz->hugepage_sz != RTE_PGSIZE_1G) {
				printf("hugepage_sz not equal 1G\n");
				return -1;
			}
			mz = rte_memzone_reserve("flag_zone_2M", size, SOCKET_ID_ANY,
					RTE_MEMZONE_2MB);
			if (mz != NULL) {
				printf("MEMZONE FLAG 2MB\n");
				return -1;
			}
		}

		if (hugepage_2MB_avail && hugepage_1GB_avail) {
			mz = rte_memzone_reserve("flag_zone_2M_HINT", size, SOCKET_ID_ANY,
								RTE_MEMZONE_2MB|RTE_MEMZONE_1GB);
			if (mz != NULL) {
				printf("BOTH SIZES SET\n");
				return -1;
			}
		}
	}
	/*
	 * This option is for IBM Power. If 16MB pages available, check
	 * that a small memzone is correctly reserved from 16MB huge pages
	 * when requested by the RTE_MEMZONE_16MB flag. Also check that
	 * RTE_MEMZONE_SIZE_HINT_ONLY flag only defaults to an available
	 * page size (i.e 16GB ) when 16MB pages are unavailable.
	 */
	if (hugepage_16MB_avail) {
		mz = rte_memzone_reserve("flag_zone_16M", size, SOCKET_ID_ANY,
				RTE_MEMZONE_16MB);
		if (mz == NULL) {
			printf("MEMZONE FLAG 16MB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_16M) {
			printf("hugepage_sz not equal 16M\n");
			return -1;
		}

		mz = rte_memzone_reserve("flag_zone_16M_HINT", size,
		SOCKET_ID_ANY, RTE_MEMZONE_16MB|RTE_MEMZONE_SIZE_HINT_ONLY);
		if (mz == NULL) {
			printf("MEMZONE FLAG 2MB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_16M) {
			printf("hugepage_sz not equal 16M\n");
			return -1;
		}

		/* Check if 1GB huge pages are unavailable, that function fails
		 * unless HINT flag is indicated
		 */
		if (!hugepage_16GB_avail) {
			mz = rte_memzone_reserve("flag_zone_16G_HINT", size,
				SOCKET_ID_ANY,
				RTE_MEMZONE_16GB|RTE_MEMZONE_SIZE_HINT_ONLY);
			if (mz == NULL) {
				printf("MEMZONE FLAG 16GB & HINT\n");
				return -1;
			}
			if (mz->hugepage_sz != RTE_PGSIZE_16M) {
				printf("hugepage_sz not equal 16M\n");
				return -1;
			}

			mz = rte_memzone_reserve("flag_zone_16G", size,
				SOCKET_ID_ANY, RTE_MEMZONE_16GB);
			if (mz != NULL) {
				printf("MEMZONE FLAG 16GB\n");
				return -1;
			}
		}
	}
	/*As with 16MB tests above for 16GB huge page requests*/
	if (hugepage_16GB_avail) {
		mz = rte_memzone_reserve("flag_zone_16G", size, SOCKET_ID_ANY,
				RTE_MEMZONE_16GB);
		if (mz == NULL) {
			printf("MEMZONE FLAG 16GB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_16G) {
			printf("hugepage_sz not equal 16G\n");
			return -1;
		}

		mz = rte_memzone_reserve("flag_zone_16G_HINT", size,
		SOCKET_ID_ANY, RTE_MEMZONE_16GB|RTE_MEMZONE_SIZE_HINT_ONLY);
		if (mz == NULL) {
			printf("MEMZONE FLAG 16GB\n");
			return -1;
		}
		if (mz->hugepage_sz != RTE_PGSIZE_16G) {
			printf("hugepage_sz not equal 16G\n");
			return -1;
		}

		/* Check if 1GB huge pages are unavailable, that function fails
		 * unless HINT flag is indicated
		 */
		if (!hugepage_16MB_avail) {
			mz = rte_memzone_reserve("flag_zone_16M_HINT", size,
				SOCKET_ID_ANY,
				RTE_MEMZONE_16MB|RTE_MEMZONE_SIZE_HINT_ONLY);
			if (mz == NULL) {
				printf("MEMZONE FLAG 16MB & HINT\n");
				return -1;
			}
			if (mz->hugepage_sz != RTE_PGSIZE_16G) {
				printf("hugepage_sz not equal 16G\n");
				return -1;
			}
			mz = rte_memzone_reserve("flag_zone_16M", size,
				SOCKET_ID_ANY, RTE_MEMZONE_16MB);
			if (mz != NULL) {
				printf("MEMZONE FLAG 16MB\n");
				return -1;
			}
		}

		if (hugepage_16MB_avail && hugepage_16GB_avail) {
			mz = rte_memzone_reserve("flag_zone_16M_HINT", size,
				SOCKET_ID_ANY,
				RTE_MEMZONE_16MB|RTE_MEMZONE_16GB);
			if (mz != NULL) {
				printf("BOTH SIZES SET\n");
				return -1;
			}
		}
	}
	return 0;
}

/* Find the heap with the greatest free block size */
static size_t
find_max_block_free_size(const unsigned _align)
{
	struct rte_malloc_socket_stats stats;
	unsigned i, align = _align;
	size_t len = 0;

	for (i = 0; i < RTE_MAX_NUMA_NODES; i++) {
		rte_malloc_get_socket_stats(i, &stats);
		if (stats.greatest_free_size > len)
			len = stats.greatest_free_size;
	}

	if (align < RTE_CACHE_LINE_SIZE)
		align = RTE_CACHE_LINE_ROUNDUP(align+1);

	if (len <= MALLOC_ELEM_OVERHEAD + align)
		return 0;

	return len - MALLOC_ELEM_OVERHEAD - align;
}

static int
test_memzone_reserve_max(void)
{
	const struct rte_memzone *mz;
	size_t maxlen;

	maxlen = find_max_block_free_size(0);

	if (maxlen == 0) {
		printf("There is no space left!\n");
		return 0;
	}

	mz = rte_memzone_reserve("max_zone", 0, SOCKET_ID_ANY, 0);
	if (mz == NULL){
		printf("Failed to reserve a big chunk of memory - %s\n",
				rte_strerror(rte_errno));
		rte_dump_physmem_layout(stdout);
		rte_memzone_dump(stdout);
		return -1;
	}

	if (mz->len != maxlen) {
		printf("Memzone reserve with 0 size did not return bigest block\n");
		printf("Expected size = %zu, actual size = %zu\n", maxlen, mz->len);
		rte_dump_physmem_layout(stdout);
		rte_memzone_dump(stdout);
		return -1;
	}
	return 0;
}

static int
test_memzone_reserve_max_aligned(void)
{
	const struct rte_memzone *mz;
	size_t maxlen = 0;

	/* random alignment */
	rte_srand((unsigned)rte_rdtsc());
	const unsigned align = 1 << ((rte_rand() % 8) + 5); /* from 128 up to 4k alignment */

	maxlen = find_max_block_free_size(align);

	if (maxlen == 0) {
		printf("There is no space left for biggest %u-aligned memzone!\n", align);
		return 0;
	}

	mz = rte_memzone_reserve_aligned("max_zone_aligned", 0,
			SOCKET_ID_ANY, 0, align);
	if (mz == NULL){
		printf("Failed to reserve a big chunk of memory - %s\n",
				rte_strerror(rte_errno));
		rte_dump_physmem_layout(stdout);
		rte_memzone_dump(stdout);
		return -1;
	}

	if (mz->len != maxlen) {
		printf("Memzone reserve with 0 size and alignment %u did not return"
				" bigest block\n", align);
		printf("Expected size = %zu, actual size = %zu\n",
				maxlen, mz->len);
		rte_dump_physmem_layout(stdout);
		rte_memzone_dump(stdout);
		return -1;
	}
	return 0;
}

static int
test_memzone_aligned(void)
{
	const struct rte_memzone *memzone_aligned_32;
	const struct rte_memzone *memzone_aligned_128;
	const struct rte_memzone *memzone_aligned_256;
	const struct rte_memzone *memzone_aligned_512;
	const struct rte_memzone *memzone_aligned_1024;

	/* memzone that should automatically be adjusted to align on 64 bytes */
	memzone_aligned_32 = rte_memzone_reserve_aligned("aligned_32", 100,
				SOCKET_ID_ANY, 0, 32);

	/* memzone that is supposed to be aligned on a 128 byte boundary */
	memzone_aligned_128 = rte_memzone_reserve_aligned("aligned_128", 100,
				SOCKET_ID_ANY, 0, 128);

	/* memzone that is supposed to be aligned on a 256 byte boundary */
	memzone_aligned_256 = rte_memzone_reserve_aligned("aligned_256", 100,
				SOCKET_ID_ANY, 0, 256);

	/* memzone that is supposed to be aligned on a 512 byte boundary */
	memzone_aligned_512 = rte_memzone_reserve_aligned("aligned_512", 100,
				SOCKET_ID_ANY, 0, 512);

	/* memzone that is supposed to be aligned on a 1024 byte boundary */
	memzone_aligned_1024 = rte_memzone_reserve_aligned("aligned_1024", 100,
				SOCKET_ID_ANY, 0, 1024);

	printf("check alignments and lengths\n");
	if (memzone_aligned_32 == NULL) {
		printf("Unable to reserve 64-byte aligned memzone!\n");
		return -1;
	}
	if ((memzone_aligned_32->phys_addr & RTE_CACHE_LINE_MASK) != 0)
		return -1;
	if (((uintptr_t) memzone_aligned_32->addr & RTE_CACHE_LINE_MASK) != 0)
		return -1;
	if ((memzone_aligned_32->len & RTE_CACHE_LINE_MASK) != 0)
		return -1;

	if (memzone_aligned_128 == NULL) {
		printf("Unable to reserve 128-byte aligned memzone!\n");
		return -1;
	}
	if ((memzone_aligned_128->phys_addr & 127) != 0)
		return -1;
	if (((uintptr_t) memzone_aligned_128->addr & 127) != 0)
		return -1;
	if ((memzone_aligned_128->len & RTE_CACHE_LINE_MASK) != 0)
		return -1;

	if (memzone_aligned_256 == NULL) {
		printf("Unable to reserve 256-byte aligned memzone!\n");
		return -1;
	}
	if ((memzone_aligned_256->phys_addr & 255) != 0)
		return -1;
	if (((uintptr_t) memzone_aligned_256->addr & 255) != 0)
		return -1;
	if ((memzone_aligned_256->len & RTE_CACHE_LINE_MASK) != 0)
		return -1;

	if (memzone_aligned_512 == NULL) {
		printf("Unable to reserve 512-byte aligned memzone!\n");
		return -1;
	}
	if ((memzone_aligned_512->phys_addr & 511) != 0)
		return -1;
	if (((uintptr_t) memzone_aligned_512->addr & 511) != 0)
		return -1;
	if ((memzone_aligned_512->len & RTE_CACHE_LINE_MASK) != 0)
		return -1;

	if (memzone_aligned_1024 == NULL) {
		printf("Unable to reserve 1024-byte aligned memzone!\n");
		return -1;
	}
	if ((memzone_aligned_1024->phys_addr & 1023) != 0)
		return -1;
	if (((uintptr_t) memzone_aligned_1024->addr & 1023) != 0)
		return -1;
	if ((memzone_aligned_1024->len & RTE_CACHE_LINE_MASK) != 0)
		return -1;

	/* check that zones don't overlap */
	printf("check overlapping\n");
	if (is_memory_overlap(memzone_aligned_32->phys_addr, memzone_aligned_32->len,
					memzone_aligned_128->phys_addr, memzone_aligned_128->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_32->phys_addr, memzone_aligned_32->len,
					memzone_aligned_256->phys_addr, memzone_aligned_256->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_32->phys_addr, memzone_aligned_32->len,
					memzone_aligned_512->phys_addr, memzone_aligned_512->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_32->phys_addr, memzone_aligned_32->len,
					memzone_aligned_1024->phys_addr, memzone_aligned_1024->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_128->phys_addr, memzone_aligned_128->len,
					memzone_aligned_256->phys_addr, memzone_aligned_256->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_128->phys_addr, memzone_aligned_128->len,
					memzone_aligned_512->phys_addr, memzone_aligned_512->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_128->phys_addr, memzone_aligned_128->len,
					memzone_aligned_1024->phys_addr, memzone_aligned_1024->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_256->phys_addr, memzone_aligned_256->len,
					memzone_aligned_512->phys_addr, memzone_aligned_512->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_256->phys_addr, memzone_aligned_256->len,
					memzone_aligned_1024->phys_addr, memzone_aligned_1024->len))
		return -1;
	if (is_memory_overlap(memzone_aligned_512->phys_addr, memzone_aligned_512->len,
					memzone_aligned_1024->phys_addr, memzone_aligned_1024->len))
		return -1;
	return 0;
}

static int
check_memzone_bounded(const char *name, uint32_t len,  uint32_t align,
	uint32_t bound)
{
	const struct rte_memzone *mz;
	phys_addr_t bmask;

	bmask = ~((phys_addr_t)bound - 1);

	if ((mz = rte_memzone_reserve_bounded(name, len, SOCKET_ID_ANY, 0,
			align, bound)) == NULL) {
		printf("%s(%s): memzone creation failed\n",
			__func__, name);
		return -1;
	}

	if ((mz->phys_addr & ((phys_addr_t)align - 1)) != 0) {
		printf("%s(%s): invalid phys addr alignment\n",
			__func__, mz->name);
		return -1;
	}

	if (((uintptr_t) mz->addr & ((uintptr_t)align - 1)) != 0) {
		printf("%s(%s): invalid virtual addr alignment\n",
			__func__, mz->name);
		return -1;
	}

	if ((mz->len & RTE_CACHE_LINE_MASK) != 0 || mz->len < len ||
			mz->len < RTE_CACHE_LINE_SIZE) {
		printf("%s(%s): invalid length\n",
			__func__, mz->name);
		return -1;
	}

	if ((mz->phys_addr & bmask) !=
			((mz->phys_addr + mz->len - 1) & bmask)) {
		printf("%s(%s): invalid memzone boundary %u crossed\n",
			__func__, mz->name, bound);
		return -1;
	}

	return 0;
}

static int
test_memzone_bounded(void)
{
	const struct rte_memzone *memzone_err;
	const char *name;
	int rc;

	/* should fail as boundary is not power of two */
	name = "bounded_error_31";
	if ((memzone_err = rte_memzone_reserve_bounded(name,
			100, SOCKET_ID_ANY, 0, 32, UINT32_MAX)) != NULL) {
		printf("%s(%s)created a memzone with invalid boundary "
			"conditions\n", __func__, memzone_err->name);
		return -1;
	}

	/* should fail as len is greater then boundary */
	name = "bounded_error_32";
	if ((memzone_err = rte_memzone_reserve_bounded(name,
			100, SOCKET_ID_ANY, 0, 32, 32)) != NULL) {
		printf("%s(%s)created a memzone with invalid boundary "
			"conditions\n", __func__, memzone_err->name);
		return -1;
	}

	if ((rc = check_memzone_bounded("bounded_128", 100, 128, 128)) != 0)
		return rc;

	if ((rc = check_memzone_bounded("bounded_256", 100, 256, 128)) != 0)
		return rc;

	if ((rc = check_memzone_bounded("bounded_1K", 100, 64, 1024)) != 0)
		return rc;

	if ((rc = check_memzone_bounded("bounded_1K_MAX", 0, 64, 1024)) != 0)
		return rc;

	return 0;
}

static int
test_memzone_free(void)
{
	const struct rte_memzone *mz[RTE_MAX_MEMZONE];
	int i;
	char name[20];

	mz[0] = rte_memzone_reserve("tempzone0", 2000, SOCKET_ID_ANY, 0);
	mz[1] = rte_memzone_reserve("tempzone1", 4000, SOCKET_ID_ANY, 0);

	if (mz[0] > mz[1])
		return -1;
	if (!rte_memzone_lookup("tempzone0"))
		return -1;
	if (!rte_memzone_lookup("tempzone1"))
		return -1;

	if (rte_memzone_free(mz[0])) {
		printf("Fail memzone free - tempzone0\n");
		return -1;
	}
	if (rte_memzone_lookup("tempzone0")) {
		printf("Found previously free memzone - tempzone0\n");
		return -1;
	}
	mz[2] = rte_memzone_reserve("tempzone2", 2000, SOCKET_ID_ANY, 0);

	if (mz[2] > mz[1]) {
		printf("tempzone2 should have gotten the free entry from tempzone0\n");
		return -1;
	}
	if (rte_memzone_free(mz[2])) {
		printf("Fail memzone free - tempzone2\n");
		return -1;
	}
	if (rte_memzone_lookup("tempzone2")) {
		printf("Found previously free memzone - tempzone2\n");
		return -1;
	}
	if (rte_memzone_free(mz[1])) {
		printf("Fail memzone free - tempzone1\n");
		return -1;
	}
	if (rte_memzone_lookup("tempzone1")) {
		printf("Found previously free memzone - tempzone1\n");
		return -1;
	}

	i = 0;
	do {
		snprintf(name, sizeof(name), "tempzone%u", i);
		mz[i] = rte_memzone_reserve(name, 1, SOCKET_ID_ANY, 0);
	} while (mz[i++] != NULL);

	if (rte_memzone_free(mz[0])) {
		printf("Fail memzone free - tempzone0\n");
		return -1;
	}
	mz[0] = rte_memzone_reserve("tempzone0new", 0, SOCKET_ID_ANY, 0);

	if (mz[0] == NULL) {
		printf("Fail to create memzone - tempzone0new - when MAX memzones were "
				"created and one was free\n");
		return -1;
	}

	for (i = i - 2; i >= 0; i--) {
		if (rte_memzone_free(mz[i])) {
			printf("Fail memzone free - tempzone%d\n", i);
			return -1;
		}
	}

	return 0;
}

static int
test_memzone(void)
{
	const struct rte_memzone *memzone1;
	const struct rte_memzone *memzone2;
	const struct rte_memzone *memzone3;
	const struct rte_memzone *memzone4;
	const struct rte_memzone *mz;

	memzone1 = rte_memzone_reserve("testzone1", 100,
				SOCKET_ID_ANY, 0);

	memzone2 = rte_memzone_reserve("testzone2", 1000,
				0, 0);

	memzone3 = rte_memzone_reserve("testzone3", 1000,
				1, 0);

	memzone4 = rte_memzone_reserve("testzone4", 1024,
				SOCKET_ID_ANY, 0);

	/* memzone3 may be NULL if we don't have NUMA */
	if (memzone1 == NULL || memzone2 == NULL || memzone4 == NULL)
		return -1;

	rte_memzone_dump(stdout);

	/* check cache-line alignments */
	printf("check alignments and lengths\n");

	if ((memzone1->phys_addr & RTE_CACHE_LINE_MASK) != 0)
		return -1;
	if ((memzone2->phys_addr & RTE_CACHE_LINE_MASK) != 0)
		return -1;
	if (memzone3 != NULL && (memzone3->phys_addr & RTE_CACHE_LINE_MASK) != 0)
		return -1;
	if ((memzone1->len & RTE_CACHE_LINE_MASK) != 0 || memzone1->len == 0)
		return -1;
	if ((memzone2->len & RTE_CACHE_LINE_MASK) != 0 || memzone2->len == 0)
		return -1;
	if (memzone3 != NULL && ((memzone3->len & RTE_CACHE_LINE_MASK) != 0 ||
			memzone3->len == 0))
		return -1;
	if (memzone4->len != 1024)
		return -1;

	/* check that zones don't overlap */
	printf("check overlapping\n");

	if (is_memory_overlap(memzone1->phys_addr, memzone1->len,
			memzone2->phys_addr, memzone2->len))
		return -1;
	if (memzone3 != NULL &&
			is_memory_overlap(memzone1->phys_addr, memzone1->len,
					memzone3->phys_addr, memzone3->len))
		return -1;
	if (memzone3 != NULL &&
			is_memory_overlap(memzone2->phys_addr, memzone2->len,
					memzone3->phys_addr, memzone3->len))
		return -1;

	printf("check socket ID\n");

	/* memzone2 must be on socket id 0 and memzone3 on socket 1 */
	if (memzone2->socket_id != 0)
		return -1;
	if (memzone3 != NULL && memzone3->socket_id != 1)
		return -1;

	printf("test zone lookup\n");
	mz = rte_memzone_lookup("testzone1");
	if (mz != memzone1)
		return -1;

	printf("test duplcate zone name\n");
	mz = rte_memzone_reserve("testzone1", 100,
			SOCKET_ID_ANY, 0);
	if (mz != NULL)
		return -1;

	printf("test free memzone\n");
	if (test_memzone_free() < 0)
		return -1;

	printf("test reserving memzone with bigger size than the maximum\n");
	if (test_memzone_reserving_zone_size_bigger_than_the_maximum() < 0)
		return -1;

	printf("test memzone_reserve flags\n");
	if (test_memzone_reserve_flags() < 0)
		return -1;

	printf("test alignment for memzone_reserve\n");
	if (test_memzone_aligned() < 0)
		return -1;

	printf("test boundary alignment for memzone_reserve\n");
	if (test_memzone_bounded() < 0)
		return -1;

	printf("test invalid alignment for memzone_reserve\n");
	if (test_memzone_invalid_alignment() < 0)
		return -1;

	printf("test reserving the largest size memzone possible\n");
	if (test_memzone_reserve_max() < 0)
		return -1;

	printf("test reserving the largest size aligned memzone possible\n");
	if (test_memzone_reserve_max_aligned() < 0)
		return -1;

	return 0;
}

REGISTER_TEST_COMMAND(memzone_autotest, test_memzone);


text:
PRAGMA writable_schema=on;
INSERT INTO sqlite_stat1 VALUES(null,null,null);
PRAGMA writable_schema=off;


text:
- infos = Information about the boolean plugin is in keys below
- infos/author = Thomas Waser <thomas.waser@libelektra.org>
- infos/licence = BSD
- infos/needs =
- infos/provides = check
- infos/recommends =
- infos/placements = postgetstorage presetstorage
- infos/status = recommended productive maintained reviewed conformant compatible coverage specific unittest tested nodep configurable
- infos/metadata =
- infos/description = canonicalizes boolean values

## Introduction

Different configurations might use different values for `TRUE`/`FALSE`. The `boolean` plugin canonicalizes boolean values.

## Example

```sh
# Mount plugin
sudo kdb mount config.ecf user/tests/boolean dump boolean

# By default the plugin uses `1` (true) and `0` (false) to represent boolean values
kdb set user/tests/boolean/truthiness false
kdb setmeta user/tests/boolean/truthiness type boolean
kdb get user/tests/boolean/truthiness
#> 0

# The plugin does not change ordinary values
kdb set user/tests/boolean/key value
kdb get user/tests/boolean/key
#> value

# Undo changes
kdb rm -r user/tests/boolean
sudo kdb umount user/tests/boolean
```

## Configuration

- `on/true` specifies the normalized value for `TRUE`. Default: `1`
- `on/false` specifies the normalized value for `FALSE`. Default: `0`
- `on/invalid` specifies the normalized value for keys that don't contain a valid boolean value. Values: `TRUE`, `FALSE`. Default: `TRUE`.
- `on/invalid/warning` specifies if the plugin will yield a warning when a invalid value is found during kdbGet. Values: `TRUE`, `FALSE`. Default: `TRUE`
- `true` specifies a (case insensitive) list of valid `TRUE`-values. The values have to be separated by a `;`. Default: `TRUE; 1; ON; ENABLE; ENABLED; YES`
- `false` specifies a (case insensitive) list of valid `FALSE`-values. The values have to be separated by a `;`. Default: `FALSE; 0; OFF; DISABLE; DISABLED; NO; NOT`


text:
namespace Google.Cloud.Compute.V1.Snippets
{
    // [START compute_v1_generated_Projects_Get_sync_flattened]
    using Google.Cloud.Compute.V1;

    public sealed partial class GeneratedProjectsClientSnippets
    {
        /// <summary>Snippet for Get</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void Get()
        {
            // Create client
            ProjectsClient projectsClient = ProjectsClient.Create();
            // Initialize request argument(s)
            string project = "";
            // Make the request
            Project response = projectsClient.Get(project);
        }
    }
    // [END compute_v1_generated_Projects_Get_sync_flattened]
}


text:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Common;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Objects;

namespace Csla.Data.EF5.Test
{
    [Table("Table2")]
    public class Table2
    {
        [Key]
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string SmallColumns { get; set; }
    }

    public partial class DataPortalDbContext : DbContext
    {
        public DataPortalDbContext()
        {
        }

        public DataPortalDbContext(string connection)
            : base(connection)
        {
        }

        public DataPortalDbContext(DbCompiledModel model)
            : base(model)
        {
        }

        public DataPortalDbContext(string database, DbCompiledModel model)
            : base(database, model)
        {
        }

        public DataPortalDbContext(ObjectContext context, bool contextOwnsConnection)
            : base(context, contextOwnsConnection)
        {
        }

        public DataPortalDbContext(DbConnection connection, bool contextOwnsConnection)
            : base(connection, contextOwnsConnection)
        {
        }

        public DataPortalDbContext(DbConnection connection, DbCompiledModel model, bool contextOwnsConnection)
            : base(connection, model, contextOwnsConnection)
        {
        }

        public DbSet<Table2> Table2 { get; set; }
    }
}


text:
<div [ngSwitch]="isRendering">
    <div *ngSwitchCase="false" class="row">
        <etb-tune-list-menu class="col-1" [tunes]="tunes"></etb-tune-list-menu>
        <div class="col-11 card-deck">
            <etb-tune-list-item [tune]="tune" *ngFor="let tune of tunes"></etb-tune-list-item>
        </div>
    </div>

    <etb-spinner *ngSwitchCase="true" [isRunning]="isRendering"></etb-spinner>
</div>


text:
/* See LICENSE for license details. */

/*

Module: meat_chunk.h

Description:

    String of characters stored as a linked list of chunks (or parts).

*/

/* Header file dependencies */
#if !defined(INC_MEAT_LIST_H)
#error include meat_list.h first
#endif /* #if !defined(INC_MEAT_LIST_H) */

/* Reverse include guard */
#if defined(INC_MEAT_CHUNK_H)
#error include meat_chunk.h once
#endif /* #if defined(INC_MEAT_CHUNK_H) */

#define INC_MEAT_CHUNK_H

/* Predefine */
struct meat_ctxt;

/* Number of characters in a single chunk */
#define MEAT_CHUNK_BUFFER_LENGTH 32u

/*

Structure: meat_chunk

Description:

    Data representation of a single chunk.

*/
struct meat_chunk
{
    struct meat_list
        o_list;

    unsigned int
        i_len;

    unsigned char
        a_buf[
            MEAT_CHUNK_BUFFER_LENGTH];

}; /* struct meat_chunk */

struct meat_chunk_list
{
    struct meat_list
        o_list;

    unsigned int
        i_total_len;

}; /* struct meat_chunk_list */

#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
meat_chunk_list_init(
    struct meat_ctxt * const
        p_ctxt,
    struct meat_chunk_list * const
        p_chunk_list);

#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
meat_chunk_list_cleanup(
    struct meat_ctxt * const
        p_ctxt,
    struct meat_chunk_list * const
        p_chunk_list);

#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
meat_chunk_list_write(
    struct meat_ctxt * const
        p_ctxt,
    struct meat_chunk_list * const
        p_chunk_list,
    unsigned char const
        c_data);

#if defined(__cplusplus)
extern "C"
#endif /* #if defined(__cplusplus) */
void
meat_chunk_list_read(
    struct meat_ctxt * const
        p_ctxt,
    struct meat_chunk_list * const
        p_chunk_list,
    unsigned char * const
        p_buf,
    unsigned int const
        i_buf_len);

/* end-o-file: meat_chunk.h */


text:
title: "White & Nerdy" by Weird Al Yankovic
date: 2009-01-21 02:55:00 +0100
excerpt: A humorous take on nerds.
categories: Tumblelog
tags: [Satire, Video]
permalink: /tumblelog/white-nerdy-by-weird-al-yankovic
redirect_from: /white-nerdy-by-weird-al-yankovic
layout: post
---

[White & Nerdy](https://vimeo.com/752979)


text:
<?php
/**
 * Created by PhpStorm.
 * User: Rachid
 * Date: 03/06/2017
 * Time: 16:49
 */

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use AppBundle\Entity\Utilisateur;
use AppBundle\Entity\CommentaireNews;

/**
 * Actualite
 *
 * @ORM\Table(name="actualite")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ActualiteRepository")
 * @ORM\HasLifecycleCallbacks()
 */
class Actualite
{

    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Utilisateur", inversedBy="annonces")
     */
    private $auteur;

    /**
     * @var string
     *
     * @ORM\Column(name="titre", type="string", length=255)
     */
    private $titre;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text")
     */
    private $description;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateactualite", type="date", nullable=true)
     */
    private $dateactualite;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="dateevenement", type="date", nullable=true)
     */
    private $dateevenement;

    /**
     * @var string
     *
     * @ORM\Column(name="firstimage", type="string", length=255)
     */
    private $firstimage;

    /**
     * @ORM\OneToMany(targetEntity="AppBundle\Entity\CommentaireNews", mappedBy="actualite")
     */
    private $commentairesnews;

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->commentairesnews = new \Doctrine\Common\Collections\ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set titre
     *
     * @param string $titre
     *
     * @return Actualite
     */
    public function setTitre($titre)
    {
        $this->titre = $titre;

        return $this;
    }

    /**
     * Get titre
     *
     * @return string
     */
    public function getTitre()
    {
        return $this->titre;
    }

    /**
     * Set description
     *
     * @param string $description
     *
     * @return Actualite
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set dateactualite
     *
     * @param \DateTime $dateactualite
     *
     * @return Actualite
     */
    public function setDateactualite($dateactualite)
    {
        $this->dateactualite = $dateactualite;

        return $this;
    }

    /**
     * Get dateactualite
     *
     * @return \DateTime
     */
    public function getDateactualite()
    {
        return $this->dateactualite;
    }

    /**
     * Set dateevenement
     *
     * @param \DateTime $dateevenement
     *
     * @return Actualite
     */
    public function setDateevenement($dateevenement)
    {
        $this->dateevenement = $dateevenement;

        return $this;
    }

    /**
     * Get dateevenement
     *
     * @return \DateTime
     */
    public function getDateevenement()
    {
        return $this->dateevenement;
    }

    /**
     * Set firstimage
     *
     * @param string $firstimage
     *
     * @return Actualite
     */
    public function setFirstimage($firstimage)
    {
        $this->firstimage = $firstimage;

        return $this;
    }

    /**
     * Get firstimage
     *
     * @return string
     */
    public function getFirstimage()
    {
        return $this->firstimage;
    }

    /**
     * Set auteur
     *
     * @param \AppBundle\Entity\Utilisateur $auteur
     *
     * @return Actualite
     */
    public function setAuteur(\AppBundle\Entity\Utilisateur $auteur = null)
    {
        $this->auteur = $auteur;

        return $this;
    }

    /**
     * Get auteur
     *
     * @return \AppBundle\Entity\Utilisateur
     */
    public function getAuteur()
    {
        return $this->auteur;
    }

    /**
     * Add commentairesnews
     *
     * @param \AppBundle\Entity\CommentaireNews $commentairesnews
     *
     * @return Actualite
     */
    public function addCommentairesnews(\AppBundle\Entity\CommentaireNews $commentairesnews)
    {
        $this->commentairesnews[] = $commentairesnews;

        return $this;
    }

    /**
     * Remove commentairesnews
     *
     * @param \AppBundle\Entity\CommentaireNews $commentairesnews
     */
    public function removeCommentairesnews(\AppBundle\Entity\CommentaireNews $commentairesnews)
    {
        $this->commentairesnews->removeElement($commentairesnews);
    }

    /**
     * Get commentairesnews
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getCommentairesnews()
    {
        return $this->commentairesnews;
    }
}


text:
require 'faraday'
require 'json'

# fetch pull request data for given API url

class PullRequestFetcher

  def metadata_for url
    raw = get_json(url)
    raw.select { |k,v| metadata_keys.include? k }
  end

  def merged_at_for url
    raw = get_json(url)
    raw['merged_at']
  end

  private

  def metadata_keys
    %w{url html_url number title body merged_at}
  end

  def get_json url
    body = client.get(url).body
    JSON.parse body
  end

  def client
    Faraday
  end
end