text:
from collections import deque

import numpy as np
import gym
from gym import spaces
import cv2  # pytype:disable=import-error
cv2.ocl.setUseOpenCL(False)

class NoopResetEnv(gym.Wrapper):
    def __init__(self, env, noop_max=30):
        """
        Sample initial states by taking random number of no-ops on reset.
        No-op is assumed to be action 0.

        :param env: (Gym Environment) the environment to wrap
        :param noop_max: (int) the maximum value of no-ops to run
        """
        gym.Wrapper.__init__(self, env)
        self.noop_max = noop_max
        self.override_num_noops = None
        self.noop_action = 0
        assert env.unwrapped.get_action_meanings()[0] == 'NOOP'

    def reset(self, **kwargs):
        self.env.reset(**kwargs)
        if self.override_num_noops is not None:
            noops = self.override_num_noops
        else:
            noops = self.unwrapped.np_random.randint(1, self.noop_max + 1)
        assert noops > 0
        obs = None
        for _ in range(noops):
            obs, _, done, _ = self.env.step(self.noop_action)
            if done:
                obs = self.env.reset(**kwargs)
        return obs

    def step(self, action):
        return self.env.step(action)

class FireResetEnv(gym.Wrapper):
    def __init__(self, env):
        """
        Take action on reset for environments that are fixed until firing.

        :param env: (Gym Environment) the environment to wrap
        """
        gym.Wrapper.__init__(self, env)
        assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
        assert len(env.unwrapped.get_action_meanings()) >= 3

    def reset(self, **kwargs):
        self.env.reset(**kwargs)
        obs, _, done, _ = self.env.step(1)
        if done:
            self.env.reset(**kwargs)
        obs, _, done, _ = self.env.step(2)
        if done:
            self.env.reset(**kwargs)
        return obs

    def step(self, action):
        return self.env.step(action)

class EpisodicLifeEnv(gym.Wrapper):
    def __init__(self, env):
        """
        Make end-of-life == end-of-episode, but only reset on true game over.
        Done by DeepMind for the DQN and co. since it helps value estimation.

        :param env: (Gym Environment) the environment to wrap
        """
        gym.Wrapper.__init__(self, env)
        self.lives = 0
        self.was_real_done = True

    def step(self, action):
        obs, reward, done, info = self.env.step(action)
        self.was_real_done = done
        # check current lives, make loss of life terminal,
        # then update lives to handle bonus lives
        lives = self.env.unwrapped.ale.lives()
        if 0 < lives < self.lives:
            # for Qbert sometimes we stay in lives == 0 condtion for a few frames
            # so its important to keep lives > 0, so that we only reset once
            # the environment advertises done.
            done = True
        self.lives = lives
        return obs, reward, done, info

    def reset(self, **kwargs):
        """
        Calls the Gym environment reset, only when lives are exhausted.
        This way all states are still reachable even though lives are episodic,
        and the learner need not know about any of this behind-the-scenes.

        :param kwargs: Extra keywords passed to env.reset() call
        :return: ([int] or [float]) the first observation of the environment
        """
        if self.was_real_done:
            obs = self.env.reset(**kwargs)
        else:
            # no-op step to advance from terminal/lost life state
            obs, _, _, _ = self.env.step(0)
        self.lives = self.env.unwrapped.ale.lives()
        return obs

class MaxAndSkipEnv(gym.Wrapper):
    def __init__(self, env, skip=4):
        """
        Return only every `skip`-th frame (frameskipping)

        :param env: (Gym Environment) the environment
        :param skip: (int) number of `skip`-th frame
        """
        gym.Wrapper.__init__(self, env)
        # most recent raw observations (for max pooling across time steps)
        self._obs_buffer = np.zeros((2,) + env.observation_space.shape, dtype=env.observation_space.dtype)
        self._skip = skip

    def step(self, action):
        """
        Step the environment with the given action
        Repeat action, sum reward, and max over last observations.

        :param action: ([int] or [float]) the action
        :return: ([int] or [float], [float], [bool], dict) observation, reward, done, information
        """
        total_reward = 0.0
        done = None
        for i in range(self._skip):
            obs, reward, done, info = self.env.step(action)
            if i == self._skip - 2:
                self._obs_buffer[0] = obs
            if i == self._skip - 1:
                self._obs_buffer[1] = obs
            total_reward += reward
            if done:
                break
        # Note that the observation on the done=True frame
        # doesn't matter
        max_frame = self._obs_buffer.max(axis=0)

        return max_frame, total_reward, done, info

    def reset(self, **kwargs):
        return self.env.reset(**kwargs)

class ClipRewardEnv(gym.RewardWrapper):
    def __init__(self, env):
        """
        clips the reward to {+1, 0, -1} by its sign.

        :param env: (Gym Environment) the environment
        """
        gym.RewardWrapper.__init__(self, env)

    def reward(self, reward):
        """
        Bin reward to {+1, 0, -1} by its sign.

        :param reward: (float)
        """
        return np.sign(reward)

class WarpFrame(gym.ObservationWrapper):
    def __init__(self, env):
        """
        Warp frames to 84x84 as done in the Nature paper and later work.

        :param env: (Gym Environment) the environment
        """
        gym.ObservationWrapper.__init__(self, env)
        self.width = 84
        self.height = 84
        self.observation_space = spaces.Box(low=0, high=255, shape=(self.height, self.width, 1),
                                            dtype=env.observation_space.dtype)

    def observation(self, frame):
        """
        returns the current observation from a frame

        :param frame: ([int] or [float]) environment frame
        :return: ([int] or [float]) the observation
        """
        frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        frame = cv2.resize(frame, (self.width, self.height), interpolation=cv2.INTER_AREA)
        return frame[:, :, None]

class FrameStack(gym.Wrapper):
    def __init__(self, env, n_frames):
        """Stack n_frames last frames.

        Returns lazy array, which is much more memory efficient.

        See Also
        --------
        stable_baselines.common.atari_wrappers.LazyFrames

        :param env: (Gym Environment) the environment
        :param n_frames: (int) the number of frames to stack
        """
        gym.Wrapper.__init__(self, env)
        self.n_frames = n_frames
        self.frames = deque([], maxlen=n_frames)
        shp = env.observation_space.shape
        self.observation_space = spaces.Box(low=0, high=255, shape=(shp[0], shp[1], shp[2] * n_frames),
                                            dtype=env.observation_space.dtype)

    def reset(self, **kwargs):
        obs = self.env.reset(**kwargs)
        for _ in range(self.n_frames):
            self.frames.append(obs)
        return self._get_ob()

    def step(self, action):
        obs, reward, done, info = self.env.step(action)
        self.frames.append(obs)
        return self._get_ob(), reward, done, info

    def _get_ob(self):
        assert len(self.frames) == self.n_frames
        return LazyFrames(list(self.frames))

class ScaledFloatFrame(gym.ObservationWrapper):
    def __init__(self, env):
        gym.ObservationWrapper.__init__(self, env)
        self.observation_space = spaces.Box(low=0, high=1.0, shape=env.observation_space.shape, dtype=np.float32)

    def observation(self, observation):
        # careful! This undoes the memory optimization, use
        # with smaller replay buffers only.
        return np.array(observation).astype(np.float32) / 255.0

class LazyFrames(object):
    def __init__(self, frames):
        """
        This object ensures that common frames between the observations are only stored once.
        It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay
        buffers.

        This object should only be converted to np.ndarray before being passed to the model.

        :param frames: ([int] or [float]) environment frames
        """
        self._frames = frames
        self._out = None

    def _force(self):
        if self._out is None:
            self._out = np.concatenate(self._frames, axis=2)
            self._frames = None
        return self._out

    def __array__(self, dtype=None):
        out = self._force()
        if dtype is not None:
            out = out.astype(dtype)
        return out

    def __len__(self):
        return len(self._force())

    def __getitem__(self, i):
        return self._force()[i]

def make_atari(env_id):
    """
    Create a wrapped atari Environment

    :param env_id: (str) the environment ID
    :return: (Gym Environment) the wrapped atari environment
    """
    env = gym.make(env_id)
    assert 'NoFrameskip' in env.spec.id
    env = NoopResetEnv(env, noop_max=30)
    env = MaxAndSkipEnv(env, skip=4)
    return env

def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):
    """
    Configure environment for DeepMind-style Atari.

    :param env: (Gym Environment) the atari environment
    :param episode_life: (bool) wrap the episode life wrapper
    :param clip_rewards: (bool) wrap the reward clipping wrapper
    :param frame_stack: (bool) wrap the frame stacking wrapper
    :param scale: (bool) wrap the scaling observation wrapper
    :return: (Gym Environment) the wrapped atari environment
    """
    if episode_life:
        env = EpisodicLifeEnv(env)
    if 'FIRE' in env.unwrapped.get_action_meanings():
        env = FireResetEnv(env)
    env = WarpFrame(env)
    if scale:
        env = ScaledFloatFrame(env)
    if clip_rewards:
        env = ClipRewardEnv(env)
    if frame_stack:
        env = FrameStack(env, 4)
    return env


text:
import {
  isCustomProperty,
  isStandardProperty,
  report,
  ruleMessages,
  validateOptions,
} from "../../utils"

export const ruleName = "property-case"

export const messages = ruleMessages(ruleName, {
  expected: (actual, expected) => `Expected "${actual}" to be "${expected}"`,
})

export default function (expectation) {
  return (root, result) => {
    const validOptions = validateOptions(result, ruleName, {
      actual: expectation,
      possible: [
        "lower",
        "upper",
      ],
    })
    if (!validOptions) { return }

    root.walkDecls(decl => {
      const { prop } = decl
      if (!isStandardProperty(prop)) { return }
      if (isCustomProperty(prop)) { return }

      const expectedProp = expectation === "lower" ? prop.toLowerCase() : prop.toUpperCase()
      if (prop === expectedProp) { return }

      report({
        message: messages.expected(prop, expectedProp),
        node: decl,
        ruleName,
        result,
      })
    })
  }
}

redpajama_set_name: RedPajamaGithub


text:
package com.gargoylesoftware.css.parser;

/**
 * Util methods used by the parser and lexer.
 *
 * @author Ronald Brill
 */
public final class ParserUtils {

    private ParserUtils() {
    }

    /**
     * Remove the given number of chars from start and end.
     * There is no parameter checking, the caller has to take care of this.
     *
     * @param s the StringBuilder
     * @param left no of chars to be removed from start
     * @param right no of chars to be removed from end
     * @return the trimmed string
     */
    public static String trimBy(final StringBuilder s, final int left, final int right) {
        return s.substring(left, s.length() - right);
    }

    /**
     * Helper that removes the leading "url(", the trailing ")"
     * and surrounding quotes from the given string builder.
     * @param s the StringBuilder
     * @return the trimmed string
     */
    public static String trimUrl(final StringBuilder s) {
        final String s1 = trimBy(s, 4, 1).trim();
        if (s1.length() == 0) {
            return s1;
        }

        final int end = s1.length() - 1;
        final char c0 = s1.charAt(0);
        if ((c0 == '"' && s1.charAt(end) == '"')
            || (c0 == '\'' && s1.charAt(end) == '\'')) {
            return s1.substring(1, end);
        }

        return s1;
    }

}


text:
package com.falcon.suitagent.web;
/*
 * 修订记录:
 * guqiu@yiji.com 2016-07-26 13:45 创建
 */

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author guqiu@yiji.com
 */
@Slf4j
public class HttpServer extends Thread {

    private static final String SHUTDOWN_COMMAND = "/__SHUTDOWN__";
    private boolean shutdown = false;
    /**
     * 0 : 服务未启动
     * 1 : 服务已启动
     * -1 : 服务正在关闭
     */
    public static int status = 0;

    private int port;
    private static ServerSocket serverSocket;

    public HttpServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            startServer();
        } catch (IOException e) {
            log.error("web服务启动异常", e);
            status = 0;
            System.exit(0);
        }
    }

    public void startServer() throws IOException {
        serverSocket = new ServerSocket(port, 10, InetAddress.getByName("0.0.0.0"));
        log.info("Web服务启动地址:http://{}:{}", InetAddress.getByName("0.0.0.0").getHostName(), serverSocket.getLocalPort());
        status = 1;
        while (!shutdown) {
            try (Socket socket = serverSocket.accept();
                 InputStream input = socket.getInputStream();
                 OutputStream output = socket.getOutputStream();) {
                Request request = new Request(input);
                request.parse();
                Response response = new Response(output);
                response.setRequest(request);
                shutdown = SHUTDOWN_COMMAND.equals(request.getUri());
                if (shutdown) {
                    status = -1;
                    response.send("Shutdown OK");
                } else {
                    response.doRequest();
                }
            } catch (Exception e) {
                log.error("Web处理异常", e);
            }
        }
        try {
            close();
        } catch (Exception e) {
            log.error("web服务关闭异常", e);
        }
    }

    public static void close() throws IOException {
        if (serverSocket != null && !serverSocket.isClosed()) {
            serverSocket.close();
            status = 0;
            log.info("Web 服务已关闭");
        }
    }
}


text:
Template reference variables

Pass value to an event handler

See console for output.

  <input #phone placeholder="phone number" />

  <button (click)="callPhone(phone.value)">Call</button>

  <input ref-fax placeholder="fax number" />
  <button (click)="callFax(fax.value)">Fax</button>

Template reference variable with disabled button

btn refers to the button element.

  <button
    #btn
    disabled
    [innerHTML]="'disabled by attribute: ' + btn.disabled"
  ></button>

Reference variables, forms, and NgForm

<form #itemForm="ngForm" (ngSubmit)="onSubmit(itemForm)">
  Name <input class="form-control" name="name" ngModel required />

  <button type="submit">Submit</button>
</form>

{{ submitMessage }}

JSON: {{ itemForm.form.value | json }}

Template Reference Variable Scope

This section demonstrates in which situations you can access local template reference variables (#ref).

Accessing in a child template

  <input #ref1 type="text" [(ngModel)]="firstExample" />
  Value: {{ ref1.value }}

Here's the desugared syntax:

Accessing from outside parent template. (Doesn't work.)

  <input *ngIf="true" #ref2 type="text" [(ngModel)]="secondExample" />

Here's the desugared syntax:

*ngFor and template reference variable scope

Accessing a on an ng-template

See the console output to see that when you declare the variable on an ng-template, the variable refers to a TemplateRef instance, which represents the template.

<ng-template #ref3></ng-template>
<button (click)="log(ref3)">Log type of #ref</button>


text:
package org.apache.asterix.runtime.evaluators.functions;

import java.io.DataOutput;
import java.io.IOException;

import org.apache.asterix.dataflow.data.nontagged.serde.AOrderedListSerializerDeserializer;
import org.apache.asterix.dataflow.data.nontagged.serde.AUnorderedListSerializerDeserializer;
import org.apache.asterix.formats.nontagged.AqlSerializerDeserializerProvider;
import org.apache.asterix.om.base.ABoolean;
import org.apache.asterix.om.functions.AsterixBuiltinFunctions;
import org.apache.asterix.om.functions.IFunctionDescriptor;
import org.apache.asterix.om.functions.IFunctionDescriptorFactory;
import org.apache.asterix.om.types.ATypeTag;
import org.apache.asterix.om.types.BuiltinType;
import org.apache.asterix.om.types.EnumDeserializer;
import org.apache.asterix.om.types.hierachy.ATypeHierarchy;
import org.apache.asterix.runtime.evaluators.base.AbstractScalarFunctionDynamicDescriptor;
import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException;
import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluator;
import org.apache.hyracks.algebricks.runtime.base.IScalarEvaluatorFactory;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.data.std.api.IPointable;
import org.apache.hyracks.data.std.primitive.VoidPointable;
import org.apache.hyracks.data.std.util.ArrayBackedValueStorage;
import org.apache.hyracks.dataflow.common.data.accessors.IFrameTupleReference;

/**
 * Checks whether a list with an edit distance threshold can be filtered with a lower bounding on the number of common list elements.
 * This function returns 'true' if the lower bound on the number of common elements is positive, 'false' otherwise.
 * For example, this function is used during an indexed nested-loop join based on edit distance. We partition the tuples of the probing
 * dataset into those that are filterable and those that are not. Those that are filterable are forwarded to the index. The others are
 * are fed into a (non indexed) nested-loop join.
 */
public class EditDistanceListIsFilterable extends AbstractScalarFunctionDynamicDescriptor {

    private static final long serialVersionUID = 1L;

    public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() {
        @Override
        public IFunctionDescriptor createFunctionDescriptor() {
            return new EditDistanceListIsFilterable();
        }
    };

    @Override
    public IScalarEvaluatorFactory createEvaluatorFactory(final IScalarEvaluatorFactory[] args)
            throws AlgebricksException {
        return new IScalarEvaluatorFactory() {
            private static final long serialVersionUID = 1L;

            @Override
            public IScalarEvaluator createScalarEvaluator(IHyracksTaskContext ctx) throws AlgebricksException {
                return new EditDistanceListIsFilterableEvaluator(args, ctx);
            }
        };
    }

    @Override
    public FunctionIdentifier getIdentifier() {
        return AsterixBuiltinFunctions.EDIT_DISTANCE_LIST_IS_FILTERABLE;
    }

    private static class EditDistanceListIsFilterableEvaluator implements IScalarEvaluator {

        protected final IPointable argPtr = new VoidPointable();
        protected final ArrayBackedValueStorage resultStorage = new ArrayBackedValueStorage();
        protected final DataOutput output = resultStorage.getDataOutput();

        protected final IScalarEvaluator listEval;
        protected final IScalarEvaluator edThreshEval;

        @SuppressWarnings("unchecked")
        private final ISerializerDeserializer<ABoolean> booleanSerde = AqlSerializerDeserializerProvider.INSTANCE
                .getSerializerDeserializer(BuiltinType.ABOOLEAN);

        public EditDistanceListIsFilterableEvaluator(IScalarEvaluatorFactory[] args, IHyracksTaskContext context)
                throws AlgebricksException {
            listEval = args[0].createScalarEvaluator(context);
            edThreshEval = args[1].createScalarEvaluator(context);
        }

        @Override
        public void evaluate(IFrameTupleReference tuple, IPointable result) throws AlgebricksException {
            resultStorage.reset();
            ATypeTag typeTag = null;

            // Check type and compute string length.
            listEval.evaluate(tuple, argPtr);
            byte[] bytes = argPtr.getByteArray();
            int offset = argPtr.getStartOffset();

            typeTag = EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(bytes[offset]);
            long listLen = 0;
            switch (typeTag) {
                case UNORDEREDLIST: {
                    listLen = AUnorderedListSerializerDeserializer.getNumberOfItems(bytes, offset);
                    break;
                }
                case ORDEREDLIST: {
                    listLen = AOrderedListSerializerDeserializer.getNumberOfItems(bytes, offset);
                    break;
                }
                default: {
                    throw new AlgebricksException(AsterixBuiltinFunctions.EDIT_DISTANCE_LIST_IS_FILTERABLE.getName()
                            + ": expects input type ORDEREDLIST or UNORDEREDLIST as the first argument, but got "
                            + typeTag + ".");
                }
            }

            // Check type and extract edit-distance threshold.
            edThreshEval.evaluate(tuple, argPtr);
            bytes = argPtr.getByteArray();
            offset = argPtr.getStartOffset();
            typeTag = EnumDeserializer.ATYPETAGDESERIALIZER.deserialize(bytes[offset]);
            long edThresh;

            try {
                edThresh = ATypeHierarchy.getIntegerValue(bytes, offset);
            } catch (HyracksDataException e1) {
                throw new AlgebricksException(e1);
            }

            // Compute result.
            long lowerBound = listLen - edThresh;
            try {
                if (lowerBound <= 0) {
                    booleanSerde.serialize(ABoolean.FALSE, output);
                } else {
                    booleanSerde.serialize(ABoolean.TRUE, output);
                }
            } catch (IOException e) {
                throw new AlgebricksException(e);
            }
            result.set(resultStorage);
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Rezolver.Tests
{
    public enum VarianceSearch
    {
        BaseTypesAndInterfaces = -1,
        Initial = 0,
        DerivedTypesAndImplementations = 1,
        Disabled = 2
    }

    [DebuggerDisplay("{Type}")]
    public sealed partial class TypeIndexEntry : IEquatable<TypeIndexEntry>, IEquatable<Type>
    {
        public static readonly (Type, TypeIndexEntry)[] EmptyArgs = new (Type, TypeIndexEntry)[0];

        /// <summary>
        /// The type that this metadata describes
        /// </summary>
        public Type Type { get; }

        /// <summary>
        /// If the type is a class, this is the metadata for its base class.
        ///
        /// Note - Value Types and Interfaces will have <c>null</c>.
        /// All other types terminate at the metadata for <see cref="object"/>, which will also have a <c>null</c>
        /// </summary>
        public TypeIndexEntry Base { get; set; }

        /// <summary>
        /// Gets all the bases of this type in order, starting with <see cref="Base"/>
        /// </summary>
        public IEnumerable<TypeIndexEntry> Bases
        {
            get
            {
                var next = Base;
                while (next != null)
                {
                    yield return next;
                    next = next.Base;
                }
            }
        }

        /// <summary>
        /// Only includes *immediate* derived types
        /// </summary>
        public HashSet<TypeIndexEntry> DerivedTypes { get; } = new HashSet<TypeIndexEntry>();

        /// <summary>
        /// Gets an enumerable of all the types which are derived from this type, in *generally* increasing order of inheritance.
        ///
        /// So, the <see cref="DerivedTypes"/> come first, and then each of their derived types, and so on.
        ///
        /// However, derived generic types are not ordered by inheritance of their generic arguments.
        /// </summary>
        public IEnumerable<TypeIndexEntry> AllDerivedTypes
        {
            get
            {
                // breadth-first enumerable of derived types
                var nextLevel = new List<TypeIndexEntry>() { this };

                while (nextLevel.Count != 0)
                {
                    var temp = new List<TypeIndexEntry>();
                    foreach (var next in nextLevel)
                    {
                        foreach (var derived in next.DerivedTypes)
                        {
                            yield return derived;
                            temp.Add(derived);
                        }
                    }
                    nextLevel = temp;
                }
            }
        }

        public bool IsValueType => Type.IsValueType;

        public bool IsClass => Type.IsClass;

        public bool IsInterface => Type.IsInterface;

        public bool IsVariantTypeParameter => Type.IsVariantTypeParameter();

        public bool IsCovariantTypeParameter => Type.IsCovariantTypeParameter();

        public bool IsContravariantTypeParameter => Type.IsContravariantTypeParameter();

        /// <summary>
        /// Metadata for the generic type definition, if this type is a closed generic.
        ///
        /// Note - <c>null</c> if this type is a generic type definition, or is not a generic.
        /// </summary>
        public TypeIndexEntry GenericTypeDefinition { get; set; }

        public HashSet<TypeIndexEntry> KnownGenerics { get; } = new HashSet<TypeIndexEntry>();

        /// <summary>
        /// If the type is a generic type, then this will be the metadata for the arguments.
        ///
        /// If the type is not a generic type, then this array will be empty.
        ///
        /// This is lazy because arguments can be recursive - e.g. `class MyType : BaseType<MyType>`
        /// </summary>
        //public Lazy<(Type param, TypeIndexEntry argMeta)[]> GenericParametersAndArgs { get; }
        public (TypeIndexEntry param, TypeIndexEntry argMeta)[] GenericParametersAndArgs { get; private set; }

        public TypeIndexEntry[] GenericParameters { get; private set; }

        public HashSet<TypeIndexEntry> KnownArguments { get; } = new HashSet<TypeIndexEntry>();

        /// <summary>
        /// Generic interfaces implemented or inferred (if it's an interface) by this type
        /// </summary>
        public TypeIndexEntry[] GenericInterfaces { get; set; }

        /// <summary>
        /// Non-generic interfaces implemented or inferred (if it's an interface) by this type
        /// </summary>
        public TypeIndexEntry[] NonGenericInterfaces { get; set; }

        /// <summary>
        /// Classes or value types which implement this interface
        /// </summary>
        public HashSet<TypeIndexEntry> ImplementingTypes { get; } = new HashSet<TypeIndexEntry>();

        /// <summary>
        /// Other interfaces which infer this interface
        /// </summary>
        public HashSet<TypeIndexEntry> ImplementingInterfaces { get; } = new HashSet<TypeIndexEntry>();

        public TypeIndex Index { get; set; }

        internal TypeIndexEntry(TypeIndex index, Type type)
        {
            Index = index;
            Type = type;

            //GenericParametersAndArgs = new Lazy<(Type, TypeIndexEntry)[]>(
            //    () => Type.IsGenericType && !Type.IsGenericTypeDefinition ? Type.GetGenericArguments().Select(ga => (ga, Index.For(ga))).ToArray() : EmptyArgs);
        }

        internal void Initialise(Dictionary<Type, TypeIndexEntry> beingBuilt)
        {
            beingBuilt[Type] = this;

            if (Type.IsClass)
            {
                if (Type != typeof(object))
                {
                    Base = Index.For(Type.BaseType);
                    Base.DerivedTypes.Add(this);
                }
            }

            var interfaces = Type.GetInterfaces().Select(iface => Index.For(iface, beingBuilt)).ToArray();

            GenericInterfaces = interfaces.Where(iface => iface.Type.IsGenericType).ToArray();
            NonGenericInterfaces = interfaces.Where(iface => !iface.Type.IsGenericType).ToArray();

            if (!Type.IsInterface)
            {
                foreach (var iface in interfaces)
                {
                    iface.ImplementingTypes.Add(this);
                }
            }
            else
            {
                foreach (var iface in interfaces)
                {
                    iface.ImplementingInterfaces.Add(this);
                }
            }

            if (Type.IsGenericType)
            {
                if (!Type.IsGenericTypeDefinition)
                {
                    GenericTypeDefinition = Index.For(Type.GetGenericTypeDefinition(), beingBuilt);

                    GenericParametersAndArgs =
                        GenericTypeDefinition
                            .GenericParameters
                            .Zip(Type.GetGenericArguments(), (p, a) => (param: p, arg: a))
                            .Select(pa => (pa.param, Index.For(pa.arg, beingBuilt))).ToArray();

                    GenericTypeDefinition.AddKnownGeneric(this);
                }
                else
                {
                    GenericParameters = Type.IsGenericTypeDefinition ?
                        Type.GetGenericArguments().Select(p => Index.For(p, beingBuilt)).ToArray() : new TypeIndexEntry[0];
                }
            }
        }

        public bool Equals(TypeIndexEntry other)
        {
            return Type.Equals(other?.Type);
        }

        public bool Equals(Type other)
        {
            return Type.Equals(other);
        }

        public override bool Equals(object obj)
        {
            return obj is TypeIndexEntry entry ? Equals(entry) : Equals(obj as Type);
        }

        public override int GetHashCode()
        {
            return Type.GetHashCode();
        }

        public IEnumerable<(Type type, bool isVariant)> GetCompatibleTypes()
        {
            return GetCompatibleEntries().Select(ev => (ev.entry.Type, ev.isVariant));
        }

        public IEnumerable<(TypeIndexEntry entry, bool isVariant)> GetCompatibleEntries()
        {
            var search = new TypeIndexSearch(typeParameter: null);
            GetCompatibleEntries(search);
            return search.Results.Distinct();
        }

        internal void AddKnownGeneric(TypeIndexEntry entry)
        {
            KnownGenerics.Add(this);

            foreach(var (param, arg) in GenericParameters.Zip(entry.GenericParametersAndArgs, (param, incoming) => (param, incoming.argMeta)))
            {
                param.KnownArguments.Add(arg);
            }
        }

        private void GetCompatibleEntries(in TypeIndexSearch search)
        {
            if (GenericTypeDefinition != null)
            {
                var searchCopy = search;
                // recurse for the type arguments, permutating the results.
                foreach (var (type, isVariant) in GenericParametersAndArgs
                    .Select(pa =>
                    {
                        var argSearch = new TypeIndexSearch(
                            parent: in searchCopy,
                            includeClassVariants: true,
                            includeInterfaceVariants: true,
                            includeGenericDefinition: true,
                            typeParameter: pa.param,
                            useNewResultsList: true);

                        pa.argMeta.GetCompatibleEntries(argSearch);

                        return argSearch.Results;
                    })
                    .Permutate()
                    .Select(typeArgs => (
                        type: GenericTypeDefinition.Type.MakeGenericType(typeArgs.Select(a => a.entry.Type).ToArray()),
                        isVariant: typeArgs.Any(ev => ev.variantMatch)))
                    .Where(result => !searchCopy.KnownGenericsOnly ||
                                    (!result.type.ContainsGenericParameters
                                        ? Index.Has(result.type)
                                        : result.type.GetGenericArguments().All(ta => ta.IsGenericTypeParameter || Index.Has(ta))))
                    .Select(result => (Index.For(result.type), result.isVariant)))
                {
                    if (type.Equals(this))
                        search.AddResult(type, false);
                    else
                        search.AddResult(type, isVariant);
                }

                if (search.IncludeGenericDefinition && GenericTypeDefinition != null)
                {
                    search.AddResult(GenericTypeDefinition);
                }
            }
            else
            {
                search.AddResult(this);
            }

            // gets only concrete types to which this type can be assigned by reference.
            // therefore value types are excluded.
            if (Type.IsValueType)
                return;

            TypeIndexEntry objectEntry = null;
            if (search.IncludeClassVariants)
            {
                if (search.VarianceDirection < 0)
                {
                    if (Base != null && Base.Equals(typeof(object)))
                        objectEntry = Base;
                    else
                        search.AddResult(Base, true);

                    Base.GetCompatibleEntries(new TypeIndexSearch(
                        parent: in search,
                        includeClassVariants: true,
                        includeInterfaceVariants: false,
                        includeGenericDefinition: search.IncludeGenericDefinition,
                        typeParameter: search.TypeParameter,
                        resultsAreVariant: true));
                }
                else if (search.VarianceDirection > 0)
                {
                    if (IsClass)
                        search.AddResults(AllDerivedTypes, true);
                    else if (IsInterface)
                        search.AddResults(ImplementingTypes.Where(t => !t.IsValueType), true);
                }
            }

            if (search.IncludeInterfaceVariants)
            {
                if (search.VarianceDirection < 0)
                {
                    search.AddResults(GenericInterfaces, true);
                    search.AddResults(NonGenericInterfaces, true);
                }
                else if (search.VarianceDirection > 0)
                {
                    search.AddResults(ImplementingInterfaces, true);
                }
            }

            if (objectEntry != null)
                search.AddResult(objectEntry, true);
        }
    }
}


text:
            <open-quiz></open-quiz>

            <input type="button" class="btn btn-primary" value="Start Quiz" ng-click="letStartQuiz()"/>

                            Author: {{quiz.author}}

                            Quiz Name: {{quiz.quizName}}

                            Questions: {{quiz.questionLength}}

{{potentialQuestion[count].question}}

                    <input type="button" class="btn btn-primary btn-block" role="alert"
                           ng-click="checkAnswer(potentialQuestion[count].choices.choice1);"
                           ng-disabled="questionAnswered"
                           ng-value="potentialQuestion[count].choices.choice1"/>

                    <input type="button" class="btn btn-primary btn-block" role="alert"
                           ng-click="checkAnswer(potentialQuestion[count].choices.choice2);"
                           ng-disabled="questionAnswered"
                           ng-value="potentialQuestion[count].choices.choice2"/>

                    <input type="button" class="btn btn-primary btn-block" role="alert"
                           ng-click="checkAnswer(potentialQuestion[count].choices.choice3);"
                           ng-disabled="questionAnswered"
                           ng-value="potentialQuestion[count].choices.choice3"/>

                    <input type="button" class="btn btn-primary btn-block" role="alert"
                           ng-click="checkAnswer(potentialQuestion[count].choices.choice4);"
                           ng-disabled="questionAnswered"
                           ng-value="potentialQuestion[count].choices.choice4"/>

                    <input type="button" class="btn btn-dark btn-block" ng-click="nextQuestion()"
                           ng-disabled="!questionAnswered"
                           value="Next Question"/>

            Quiz Result

                        Questions: {{result.question}}

                            Correct Answer: {{result.answer}}

                            Your Answer: {{result.selectedAnswer}}

                        Wrong
                        Correct

                <input type="button" class="btn btn-danger btn-block" value="Restart App" ng-click="restartApp()"/>


text:
package org.xenei.jdbc4sparql.iface.name;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;

import org.junit.Test;
import org.xenei.jdbc4sparql.impl.NameUtils;

public class CatalogNameTests {
	private CatalogName catalogName;

	public CatalogNameTests() {
	}

	@Test
	public void testCatalog() {
		catalogName = new CatalogName("catalog");
		assertEquals("catalog", catalogName.getCatalog());
		assertNull(catalogName.getSchema());
		assertNull(catalogName.getColumn());
		assertNull(catalogName.getTable());
		assertEquals("catalog", catalogName.getDBName());
		assertEquals("catalog", catalogName.getSPARQLName());
		assertEquals("catalog", catalogName.getShortName());
	}

	@Test
	public void testCatalogFromCatalog() {
		catalogName = new CatalogName(new CatalogName("catalog"));
		assertEquals("catalog", catalogName.getCatalog());
		assertNull(catalogName.getSchema());
		assertNull(catalogName.getColumn());
		assertNull(catalogName.getTable());
		assertEquals("catalog", catalogName.getDBName());
		assertEquals("catalog", catalogName.getSPARQLName());
		assertEquals("catalog", catalogName.getShortName());
	}

	@Test
	public void testCatalogFromOtherItemName() {
		final ItemName itemName = new SearchName("catalog", "schema", "table",
				"column");
		catalogName = new CatalogName(itemName);
		assertEquals("catalog", catalogName.getCatalog());
		assertNull(catalogName.getSchema());
		assertNull(catalogName.getColumn());
		assertNull(catalogName.getTable());
		assertEquals("catalog", catalogName.getDBName());
		assertEquals("catalog", catalogName.getSPARQLName());
		assertEquals("catalog", catalogName.getShortName());

	}

	@Test
	public void testCatalogWithDBDot() {
		try {
			catalogName = new CatalogName("cata" + NameUtils.DB_DOT + "log");
			fail("Should have thrown IllegalArgumentException");
		} catch (final IllegalArgumentException expected) {
			assertEquals("Catalog name may not contain '.'",
					expected.getMessage());
		}

	}

	@Test
	public void testCatalogWithSPARQLDot() {
		try {
			catalogName = new CatalogName("cata" + NameUtils.SPARQL_DOT + "log");
			fail("Should have thrown IllegalArgumentException");
		} catch (final IllegalArgumentException expected) {
			assertEquals("Catalog name may not contain '"
					+ NameUtils.SPARQL_DOT + "'", expected.getMessage());
		}
	}

	@Test
	public void testEmptyCatalog() {
		catalogName = new CatalogName("");
		assertEquals("", catalogName.getCatalog());
		assertNull(catalogName.getSchema());
		assertNull(catalogName.getColumn());
		assertNull(catalogName.getTable());
		assertEquals("", catalogName.getDBName());
		assertEquals("", catalogName.getSPARQLName());
		assertEquals("", catalogName.getShortName());
	}

	@Test
	public void testEmptyCatalogFromCatalog() {
		catalogName = new CatalogName(new CatalogName(""));
		assertEquals("", catalogName.getCatalog());
		assertNull(catalogName.getSchema());
		assertNull(catalogName.getColumn());
		assertNull(catalogName.getTable());
		assertEquals("", catalogName.getDBName());
		assertEquals("", catalogName.getSPARQLName());
		assertEquals("", catalogName.getShortName());
	}

}


text:
/**
 * HeatMapAction.java
 * @author Vagisha Sharma
 * Apr 23, 2010
 * @version 1.0
 */
package org.yeastrc.www.compare.clustering;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.yeastrc.www.compare.ProteinComparisonDataset;
import org.yeastrc.www.compare.ProteinGroupComparisonDataset;
import org.yeastrc.www.compare.ProteinSetComparisonForm;
import org.yeastrc.www.compare.clustering.ClusteringConstants.GRADIENT;
import org.yeastrc.www.user.User;
import org.yeastrc.www.user.UserUtils;

/**
 *
 */
public class HeatMapAction extends Action {

	private static final Logger log = Logger.getLogger(ReadClusteredSpectrumCountsAction.class.getName());

	public ActionForward execute( ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response )
	throws Exception {

		// User making this request
		User user = UserUtils.getUser(request);
		if (user == null) {
			ActionErrors errors = new ActionErrors();
			errors.add("username", new ActionMessage("error.login.notloggedin"));
			saveErrors( request, errors );
			return mapping.findForward("authenticate");
		}

		long jobToken = 0;
		String strId = (String)request.getParameter("token");
		try {
			if(strId != null) {
				jobToken = Long.parseLong(strId);
			}
		}
		catch (NumberFormatException e) {}
		if(jobToken <= 0) {
			ActionErrors errors = new ActionErrors();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
					"Invalid token in request: "+strId));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		}

		// Check if we have a results directory matching this token
		String clustDir = request.getSession().getServletContext().getRealPath(ClusteringConstants.BASE_DIR);
		clustDir += File.separator+jobToken;

		if(!(new File(clustDir).exists())) {
			ActionErrors errors = new ActionErrors();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
					"No results found for token: "+strId));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		}

		ObjectInputStream ois = null;

		// Read the form
		String formFile = clustDir+File.separator+ClusteringConstants.FORM_SER;
		ProteinSetComparisonForm myForm = null;
		try {
			ois = new ObjectInputStream(new FileInputStream(formFile));
			myForm = (ProteinSetComparisonForm) ois.readObject();
			//myForm.setNumPerPage(numPerPage);
		}
		catch (IOException e) {
			ActionErrors errors = new ActionErrors();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
			"Error reading result for ProteinGroupComparisonDataset. "+e.getMessage()));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		}
		catch(ClassCastException e) {
			ActionErrors errors = new ActionErrors();
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
			"Error reading result for ProteinGroupComparisonDataset. "+e.getMessage()));
			saveErrors( request, errors );
			return mapping.findForward("Failure");
		}
		finally {
			if(ois != null) try {ois.close();} catch(IOException e){}
		}

		// Are we given an order in which to display the datasets.
		String dsOrder = request.getParameter("dsOrder");
		List<Integer> piRunIds = null;
		if(dsOrder != null) {

			String[] tokens = dsOrder.split("_");
			piRunIds = new ArrayList<Integer>(tokens.length);
			for(String tok: tokens) {
				try {piRunIds.add(Integer.parseInt(tok));}
				catch(NumberFormatException e) {
					ActionErrors errors = new ActionErrors();
					errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
					"Error parsing dataset order: "+dsOrder));
					saveErrors( request, errors );
					return mapping.findForward("Failure");
				}
			}
		}

		// Are we given a gradient preference in the request
		String gradient = request.getParameter("gradient");
		String[] gradientColors = null;
		if(gradient != null) {
			List<String> colors = null;

			GRADIENT grad = GRADIENT.valueOf(GRADIENT.class, gradient);
			if(grad == GRADIENT.BY) {
				String colorFile = clustDir+File.separator+ClusteringConstants.COLORS_BY;
				try {colors = SpectrumCountClusterer.readColors(new File(colorFile));}
				catch(IOException e) {log.error("Error reading colors file: "+colorFile, e);}
				myForm.setHeatMapGradient(GRADIENT.BY);
			}
			if(grad == GRADIENT.GR) {
				String colorFile = clustDir+File.separator+ClusteringConstants.COLORS_RG;
				try {colors = SpectrumCountClusterer.readColors(new File(colorFile));}
				catch(IOException e) {log.error("Error reading colors file: "+colorFile, e);}
				myForm.setHeatMapGradient(GRADIENT.GR);
			}

			if(colors != null && colors.size() > 0) {
				gradientColors = new String[colors.size()];
				gradientColors = colors.toArray(gradientColors);
			}
		}

		// Read the results
		if(myForm.getGroupIndistinguishableProteins()) {
			String grpComparisonFile = clustDir+File.separator+ClusteringConstants.PROT_GRP_SER;
			ProteinGroupComparisonDataset grpComparison = null;
			try {
				ois = new ObjectInputStream(new FileInputStream(grpComparisonFile));
				grpComparison = (ProteinGroupComparisonDataset) ois.readObject();
				if(piRunIds != null)
					grpComparison.setDatasetOrder(piRunIds);
				if(gradientColors != null)
					grpComparison.setSpectrumCountColors(gradientColors);
			}
			catch (IOException e) {
				ActionErrors errors = new ActionErrors();
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
						"Error reading result for ProteinGroupComparisonDataset. "+e.getMessage()));
				saveErrors( request, errors );
				return mapping.findForward("Failure");
			}
			catch(ClassCastException e) {
				ActionErrors errors = new ActionErrors();
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
						"Error reading result for ProteinGroupComparisonDataset. "+e.getMessage()));
				saveErrors( request, errors );
				return mapping.findForward("Failure");
			}
			finally {
				if(ois != null) try {ois.close();} catch(IOException e){}
			}
			request.setAttribute("heatmap", new HeatMapData(grpComparison));
			request.setAttribute("hasGroups", true);
		}

		else {

			String comparisonFile = clustDir+File.separator+ClusteringConstants.PROT_SER;
			ProteinComparisonDataset comparison = null;
			try {
				ois = new ObjectInputStream(new FileInputStream(comparisonFile));
				comparison = (ProteinComparisonDataset) ois.readObject();
				if(piRunIds != null)
					comparison.setDatasetOrder(piRunIds);
				if(gradientColors != null)
					comparison.setSpectrumCountColors(gradientColors);
			}
			catch (IOException e) {
				ActionErrors errors = new ActionErrors();
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
						"Error reading result for ProteinComparisonDataset. "+e.getMessage()));
				saveErrors( request, errors );
				return mapping.findForward("Failure");
			}
			catch(ClassCastException e) {
				ActionErrors errors = new ActionErrors();
				errors.add(ActionErrors.GLOBAL_ERROR, new ActionMessage("error.general.errorMessage",
						"Error reading result for ProteinComparisonDataset. "+e.getMessage()));
				saveErrors( request, errors );
				return mapping.findForward("Failure");
			}
			finally {
				if(ois != null) try {ois.close();} catch(IOException e){}
			}

			request.setAttribute("heatmap", new HeatMapData(comparison));

		}

		return mapping.findForward("Success");
	}
}


text:
namespace irr
{
namespace scene
{

//! Scene node which is a quake3 shader.
class CQuake3ShaderSceneNode : public scene::IMeshSceneNode
{
public:

	CQuake3ShaderSceneNode( ISceneNode* parent, ISceneManager* mgr, s32 id,
				io::IFileSystem* fileSystem,
				const IMeshBuffer* original,
				const quake3::IShader* shader
			);

	virtual ~CQuake3ShaderSceneNode();

	virtual void OnRegisterSceneNode();
	virtual void render();
	virtual void OnAnimate(u32 timeMs);
	virtual const core::aabbox3d<f32>& getBoundingBox() const;

	virtual u32 getMaterialCount() const;
	virtual video::SMaterial& getMaterial(u32 i);

	//! Returns type of the scene node
	virtual ESCENE_NODE_TYPE getType() const { return ESNT_Q3SHADER_SCENE_NODE; }

	virtual void setMesh(IMesh* mesh){}
	virtual IMesh* getMesh() { return Mesh; }
	virtual void setReadOnlyMaterials(bool readonly) {}
	virtual bool isReadOnlyMaterials() const { return true; }

private:
	const quake3::IShader* Shader;
	SMesh *Mesh;
	const SMeshBufferLightMap* Original;
	SMeshBuffer* MeshBuffer;
	core::vector3df MeshOffset;

	struct SQ3Texture
	{
		SQ3Texture () :
			TextureIndex ( 0 ),
			TextureFrequency(0.f),
			TextureAddressMode( video::ETC_REPEAT )
			{
				Texture.setAllocStrategy ( core::ALLOC_STRATEGY_SAFE );
			}

		quake3::tTexArray Texture;

		u32 TextureIndex;
		f32 TextureFrequency;
		video::E_TEXTURE_CLAMP TextureAddressMode;	// Wrapping/Clamping
	};

	core::array< SQ3Texture > Q3Texture;

	void loadTextures ( io::IFileSystem * fileSystem );
	void addBuffer ( scene::SMeshBufferLightMap * buffer );
	void cloneBuffer ( scene::SMeshBuffer *dest, const scene::SMeshBufferLightMap * buffer, bool translateCenter );

	void deformvertexes_wave ( f32 dt, quake3::SModifierFunction &function );
	void deformvertexes_move ( f32 dt, quake3::SModifierFunction &function );
	void deformvertexes_bulge( f32 dt, quake3::SModifierFunction &function );
	void deformvertexes_autosprite( f32 dt, quake3::SModifierFunction &function );
	void deformvertexes_autosprite2( f32 dt, quake3::SModifierFunction &function );
	void deformvertexes_normal ( f32 dt, quake3::SModifierFunction &function );

	void vertextransform_tcgen ( f32 dt, quake3::SModifierFunction &function );
	void vertextransform_rgbgen ( f32 dt, quake3::SModifierFunction &function );
	void vertextransform_alphagen ( f32 dt, quake3::SModifierFunction &function );

	void transformtex ( const core::matrix4 &m, const u32 clamp );

	f32 TimeAbs;

	void animate( u32 stage, core::matrix4 &texture );

	E_SCENE_NODE_RENDER_PASS getRenderStage() const;

};

} // end namespace scene
} // end namespace irr

#endif


text:
#ifndef _ANavListCtrl_h
#define _ANavListCtrl_h

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

class  CNavListCtrl;

class CNavDropSource : public COleDropSource
{
public:
    CNavDropSource();

    CNavListCtrl* m_pListCtrl;

    // Overrides
    SCODE GiveFeedback(DROPEFFECT dropEffect);
};

class ANAV_PORT CNavListCtrl : public CAdUiListCtrl {
public:
    CNavListCtrl ();

// ClassWizard-controlled
public:
    //{{AFX_VIRTUAL(CNavListCtrl)
    //}}AFX_VIRTUAL

protected:
    //{{AFX_MSG(CNavListCtrl)
    afx_msg void OnBeginDrag(NMHDR* pNMHDR, LRESULT* pResult);
    //}}AFX_MSG
    afx_msg LONG OnHandleDrag(UINT pDataSource, LONG nSelectedItem);
    DECLARE_MESSAGE_MAP()

    CImageList* m_pDragImage;
    CNavDropSource m_dropSource;

};

#endif // _ANavListCtrl_h


text:
layout: page
title: Lloyd Dart Foundation Party
date: 2016-05-24
author: Gregory Mcdowell
tags: weekly links, java
status: published
summary: Aliquam ut tincidunt justo, id sodales est.
banner: images/banner/leisure-05.jpg
booking:
  startDate: 02/26/2016
  endDate: 02/29/2016
  ctyhocn: SACNNHX
  groupCode: LDFP
published: true
---
Aenean gravida, eros et aliquam laoreet, nisl turpis ultrices mauris, quis bibendum tortor nunc fermentum nibh. Quisque dignissim elementum rhoncus. Donec facilisis lectus sem, eu posuere nisl interdum nec. Curabitur dapibus interdum erat, ac porta turpis ultricies a. Nullam tristique nulla in arcu varius efficitur. Curabitur dictum magna maximus orci dictum, ut fringilla sapien tempor. Mauris ultrices, leo vitae tincidunt volutpat, lectus nulla fermentum nunc, sed egestas ante mauris sit amet lacus. In ultrices nulla et eros suscipit lacinia. Cras faucibus tristique ante, eu tincidunt dui suscipit cursus. Aenean sed nibh libero. Mauris porta sem sed nibh pellentesque tempor.

* Maecenas at sapien pellentesque, blandit tortor non, ullamcorper purus
* Sed volutpat libero tristique, porttitor dolor non, tristique purus
* Morbi ornare odio sed nunc fringilla vulputate
* Pellentesque at sem aliquam, porta purus eu, feugiat arcu
* Ut faucibus velit placerat, mattis lacus a, bibendum neque.

Duis convallis feugiat magna, eget egestas nisl convallis et. Morbi tempus vehicula justo et rhoncus. Nam dapibus orci quis dolor ullamcorper, quis placerat felis convallis. Integer tincidunt efficitur orci vel bibendum. Mauris sollicitudin ultricies ipsum et tempus. Praesent a posuere nulla. Nam iaculis, mi gravida fermentum ultricies, lectus libero laoreet lorem, in dapibus elit urna a arcu. Nunc viverra, sapien sit amet rutrum bibendum, justo sapien cursus nibh, sit amet lobortis nibh dui a velit. Nunc pretium nisl a nisl pretium auctor.


text:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))

from proxy.run import run

def main():
    run(BASE_DIR)

if __name__ == '__main__':
    main()


text:
from oslo_config import cfg

from networking_cisco._i18n import _
from networking_cisco.config import base

nexus_sub_opts = [
    cfg.BoolOpt('https_verify', default=False,
        help=_('This configuration option defaults to False but '
               'will change to True in Cisco Release 6.0.0. '
               'Set https_verify to True when certification '
               'authority (CA) file is in the Operating Systems '
               'repository or is a locally defined file whose name is '
               'provided in https_local_certificate.  Set https_verify '
               'to False to skip https certification checking thus '
               'making the connection insecure. When True, the Nexus '
               'device must be configured with both certificate and key '
               'files and enabled.  Refer to the "nxapi certificate" '
               'commands defined in the "Nexus 9K NXAPI Programmability '
               'Guide" for details.')),
    cfg.StrOpt('https_local_certificate',
        help=_('Configure a local certificate file to present in https '
               'requests. This is for experimental purposes when an '
               'official certificate from a Trust Certificate Authority '
               'is not yet available. The default configuration is None. '
               'An example configuration would look like '
               'https_local_certificate=/path/to/cafile.crt.')),
    cfg.StrOpt('intfcfg_portchannel', deprecated_name='intfcfg.portchannel',
        help=_('intfcfg_portchannel is a list of Nexus port-channel config '
               'CLI used when baremetal port-channels are created by the '
               'Nexus driver.  It is dependent on "vpc_pool" being '
               'configured.  Any number of Nexus port-channel commands '
               'separated by ";" can be provided.  When there are multiple '
               'interfaces in a baremetal event, the nexus driver checks to '
               'determine whether a port-channel is already applied to the '
               'interfaces; otherwise, it creates a port channel. This '
               'optional configuration allows the administrator to custom '
               'configure the port-channel.  When not configured, the nexus '
               'driver defaults to configuring "spanning-tree port type edge '
               'trunk;no lacp suspend-individual" beneath the port-channel. '
               'An example of this configuration is "intfcfg_portchannel=no '
               'lacp suspend-individual;spanning-tree port type edge '
               'trunk".')),
    cfg.StrOpt('nve_src_intf',
        help=_('Only valid if VXLAN overlay is configured and '
               'vxlan_global_config is set to True. The NVE source interface '
               'is a loopback interface that is configured on the switch with '
               'valid /32 IP address. This /32 IP address must be known by '
               'the transient devices in the transport network and the remote '
               'VTEPs.  This is accomplished by advertising it through a '
               'dynamic routing protocol in the transport network. If '
               'nve_src_intf is not defined, a default setting of 0 '
               'is used to create "loopback0".  This is configured for '
               'non-baremetal only.')),
    cfg.StrOpt('password', secret=True,
        help=_('The password of the Nexus Switch Administrator is required '
               'to allow configuration access to the Nexus switch.')),
    cfg.StrOpt('physnet',
        help=_('This is required if Nexus VXLAN overlay feature is '
               'configured.  It should be the physical network name defined '
               'in "network_vlan_ranges" (defined beneath the "ml2_type_vlan" '
               'section) that this switch is controlling.  The configured '
               '"physnet" is the physical network domain that is connected '
               'to this switch. The vlan ranges defined in '
               '"network_vlan_ranges" for a physical '
               'network are allocated dynamically and are unique per physical '
               'network. These dynamic vlans may be reused across physical '
               'networks.  This configuration applies to non-baremetal '
               'only.')),
    cfg.IntOpt('ssh_port', default=22, deprecated_for_removal=True,
        help=_('"ssh_port" specifies the TCP port for connecting via SSH to '
               'manage the switch.  Port number 22 is the default unless the '
               'switch has been configured otherwise. Since "ssh_port" is '
               'associated to the "ncclient" driver which is being '
               'deprecated, "ssh_port" too will be deprecated.')),
    cfg.StrOpt('username',
        help=_('The username of the Nexus Switch Administrator is required '
               'to allow configuration access to the Nexus switch.')),
    cfg.StrOpt('vpc_pool',
        help=_('This is port-channel/VPC allocation pool of ids used with '
               'baremetal deployments only.  When there is a list of ethernet '
               'interfaces provided by Ironic to neutron in a port '
               'event, these are assumed to be a port-channel type '
               'configuration.  Ironic only knows about ethernet interfaces '
               'so it is up to the Nexus Driver to either learn the '
               'port channel if the user preconfigured the channel-group on '
               'the ethernet interfaces; otherwise, the driver will create a '
               'new port-channel and apply the channel-group to the ethernet '
               'interfaces.  This pool is the reserved port-channel IDs '
               'available for allocation by the Nexus driver for each switch. '
               'The full format for "vpc_pool" is '
               'vpc_pool=<start_vpc_no-end_vpc_no> | '
               '<vpc_no> {,<start_vpc_no-end_vpc_no> | <vpc_no>}. The "-" in '
               '<start_vpc_no,end_vpc_no> allows you to configure a range '
               'from start to end and <vpc_no> allows just individual '
               'numbers.  There can be any number of ranges and numbers '
               'separated by commas. There is no default value.  If not '
               'configured, the port-channel will only handle learned cases '
               'and attempts to create port-channels will fail since there is '
               'no id pool available from which to allocate an id. Once '
               'defined, it can be redefined by changing "vpc_pool" and '
               'restarting neutron. Existing VPC ids in the database are '
               'gathered and compared against the new "vpc_pool" config.  New '
               'configured vpcids not found in the database are added.  '
               'Inactive entries in the database not found in the new '
               'configured vpcids list are removed. An example of this '
               'configuration is `vpc_pool=1001-1025,1028`.')),
    base.RemainderOpt('host_port_mapping',
        help=_('The "host_port_mapping" option is not actually an option '
               'keyword but rather a documentation placeholder for describing '
               'how hosts are configured. For each host '
               'connected to a port on the switch, specify the hostname and '
               'assign the Nexus switch physical port (interface) it is '
               'connected to.  All compute nodes must be configured while '
               'controllers are optional depending on your network '
               'configuration. The format of this configuration '
               'is <your-hostname>=<intf_type:port>). Depending on the '
               'configuration of the host, the hostname is expected to be the '
               'full hostname (hostname.domainname) which can be derived by '
               'running "hostname -f" on the host itself. Valid '
               'intf_types are "ethernet" or "port-channel".  The default '
               'setting for <intf_type:> is "ethernet" and need not be added '
               'to this setting. (Sample configs are: host-1=1/1 or '
               'host-2=ethernet:1/2 or host-3=port-channel:1). If you '
               'have multiple hosts connected to the same switch, '
               'they must each be configured on a different line in the '
               'config file.  This configuration applies to VM deployments '
               'only.'
               ))]

ml2_cisco_opts = [
    cfg.BoolOpt('host_key_checks', default=False, deprecated_for_removal=True,
        help=_('Set to True to enable strict hostkey checks when connecting '
               'to Nexus switches via ncclient; otherwise, no hostkey checks '
               'are performed). This will be deprecated along with '
               'nexus_driver since this is associated to the ncclient driver '
               'which is going away.')),
    cfg.StrOpt('managed_physical_network',
        help=_('When "managed_physical_network" is configured, it restricts '
               'the network segment that the nexus driver supports. '
               'Setting it to a specific network name will limit the '
               'actions taken by this driver to only that network. The '
               'network name must match a name defined in the '
               '"network_vlan_ranges" configuration.  When '
               '"managed_physical_network" is not set, events for all '
               'network segments will be processed by the driver.')),
    cfg.BoolOpt('never_cache_ssh_connection', default=True,
        deprecated_for_removal=True,
        help=_('Prevent caching ssh connections to a Nexus switch. Set this '
               'to True when there are multiple neutron controllers and/or '
               'when there may be non-neutron ssh connections to the same '
               'Nexus device. Nexus devices have a limit of 8 such '
               'connections. When a single neutron controller has more than '
               '8 processes, caching is automatically disabled without regard '
               'to this configuration. This flag defaults to True which '
               'indicates that ssh connections to a Nexus switch are not '
               'cached when the neutron controller has fewer than 8 '
               'processes.  This will be deprecated along with "nexus_driver" '
               'since this is associated to the ncclient driver which is '
               'going away.')),
    cfg.StrOpt('nexus_driver', default='restapi', deprecated_for_removal=True,
        help=_('The Nexus Mechanism Driver has two driver methods to '
               'configure Nexus devices. The default choice is now "restapi" '
               'which replaces the original "ncclient" driver.  The RESTAPI '
               'driver is preferred because it has better performance with '
               'less Nexus session limits. Additionally, new feature '
               'development is applied only to the restapi driver. To use the '
               'restapi driver, the Nexus 9K image version must be '
               '7.0(3)I5(2) or greater.  For a short term, the original '
               'driver can be used by setting the "nexus_driver" '
               'configuration to "ncclient".  This is short term because '
               'the "ncclient" driver will be removed in Cisco 7.0.0 release '
               'of the networking-cisco repository.')),
    cfg.BoolOpt('persistent_switch_config', default=False,
        deprecated_for_removal=True,
        help=_('To make Nexus device persistent by running the Nexus '
               'CLI "copy run start" after applying successful '
               'configurations. This will be deprecated along with '
               'nexus_driver since this is associated to the ncclient '
               'driver which is going away.')),
    cfg.BoolOpt('provider_vlan_auto_create', default=True,
        help=_('A flag indicating whether the Nexus driver should manage '
               'the creation and removal of VLANs for provider networks on '
               'the Nexus switches. When this flag is False, the Nexus'
               'driver will not create or remove VLANs for provider '
               'networks and the administrator needs to manage these '
               'interfaces manually or by external orchestration.')),
    cfg.BoolOpt('provider_vlan_auto_trunk', default=True,
        help=_('A flag indicating whether Nexus driver should manage '
               'the adding and removing of provider VLANs from trunk ports on '
               'the Nexus switches. When this flag is False, the Nexus '
               'driver will not add or remove provider VLANs from trunk '
               'ports and the administrator needs to manage these operations '
               'manually or by external orchestration.')),
    cfg.IntOpt('switch_heartbeat_time', default=30,
        help=_('Configuration replay is enabled by default by defining the '
               'time interval to 30 seconds.  This is the amount of time to '
               'check the state of all known Nexus device(s). To disable '
               'the replay feature, set this "switch_heartbeat_time" to 0 '
               'seconds.')),
    cfg.BoolOpt('vxlan_global_config', default=False,
        help=_('A flag indicating whether the Nexus driver should manage '
               'the creating and removing of the Nexus switch VXLAN global '
               'settings of "feature nv overlay", "feature '
               'vn-segment-vlan-based", "interface nve 1" and the NVE '
               'subcommand "source-interface loopback #". When set to the '
               'default of False, the Nexus driver will not add or remove '
               'these VXLAN settings and the administrator needs to manage '
               'these operations manually or by external orchestration.')),
]

nexus_switches = base.SubsectionOpt(
    'ml2_mech_cisco_nexus',
    dest='nexus_switches',
    help=_("Subgroups that allow you to specify the nexus switches to be "
           "managed by the nexus ML2 driver."),
    subopts=nexus_sub_opts)

cfg.CONF.register_opts(ml2_cisco_opts, "ml2_cisco")
cfg.CONF.register_opt(nexus_switches, "ml2_cisco")

#
# Format for ml2_conf_cisco.ini 'ml2_mech_cisco_nexus' is:
# {('<device ipaddr>', '<keyword>'): '<value>', ...}
#
# Example:
# {('1.1.1.1', 'username'): 'admin',
#  ('1.1.1.1', 'password'): 'mySecretPassword',
#  ('1.1.1.1', 'compute1'): '1/1', ...}
#


text:
package net.beaconcontroller.devicemanager.dao.impl;

import java.util.HashMap;
import java.util.Map;

import net.beaconcontroller.devicemanager.Device;
import net.beaconcontroller.devicemanager.dao.IDeviceManagerDao;
import net.beaconcontroller.packet.IPv4;
import net.beaconcontroller.storage.IResultSet;
import net.beaconcontroller.storage.IStorageSource;
import net.beaconcontroller.topology.SwitchPortTuple;

import org.openflow.util.HexString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SSDeviceManagerDao implements IDeviceManagerDao {
    protected static Logger logger = LoggerFactory.getLogger(SSDeviceManagerDao.class);
    protected IStorageSource storageSource;

    private static final String DEVICE_TABLE_NAME = "controller_host";
    private static final String MAC_COLUMN_NAME = "mac";
    private static final String IP_COLUMN_NAME = "ip";
    private static final String SWITCH_COLUMN_NAME = "switch_id";
    private static final String PORT_COLUMN_NAME = "inport";

    public SSDeviceManagerDao() {}

    public void setStorageSource(IStorageSource storageSource) {
        this.storageSource = storageSource;
        storageSource.createTable(DEVICE_TABLE_NAME);
        /*
        try {
            storageSource.createTable(DEVICE_TABLE_NAME);
        }
        catch (Exception exc) {
            // Table may already exist, so ignore error.
            // FIXME: Should check for more specific exception and only
            // ignore the exception if it's because the table already exists.
        }
        */
        storageSource.setTablePrimaryKeyName(DEVICE_TABLE_NAME, "mac");
    }

    protected void addOrUpdateDevice(Device device) {
        Map<String, Object> rowValues = new HashMap<String, Object>();
        String macString = HexString.toHexString(device.getDataLayerAddress());
        rowValues.put(MAC_COLUMN_NAME, macString);
        Integer nwAddr = null;
        for (Integer a : device.getNetworkAddresses()) { nwAddr = a; }
        rowValues.put(IP_COLUMN_NAME, (nwAddr == null) ? "" : IPv4.fromIPv4Address(nwAddr));
        SwitchPortTuple swPort = null;
        for (SwitchPortTuple t : device.getSwPorts()) { swPort = t; }
        rowValues.put(SWITCH_COLUMN_NAME, (swPort == null) ? "" : HexString.toHexString(swPort.getSw().getId()));
        rowValues.put(PORT_COLUMN_NAME, (swPort == null) ? "" : swPort.getPort());
        rowValues.put("id", macString);
        storageSource.updateRow(DEVICE_TABLE_NAME, rowValues);
    }

    @Override
    public void addDevice(Device device) {
        addOrUpdateDevice(device);
    }

    @Override
    public Device getDevice(byte[] dlAddress) {
        String macString = HexString.toHexString(dlAddress);
        IResultSet rs = storageSource.getRow(DEVICE_TABLE_NAME, macString);
        if (!rs.next())
            return null;
        Device d = new Device();
        d.setDataLayerAddress(dlAddress);
        String ipString = rs.getString(IP_COLUMN_NAME);
        d.getNetworkAddresses().add(IPv4.toIPv4Address(ipString));
        String switchString = rs.getString(SWITCH_COLUMN_NAME);
        Long switchId = HexString.toLong(switchString);
        // d.setSwId(switchId); // FIXME xyx
        // d.setSwPort(rs.getShort(PORT_COLUMN_NAME)); // FIXME xyx
        return d;
    }

    @Override
    public void removeDevice(Device device) {
        String macString = HexString.toHexString(device.getDataLayerAddress());
        storageSource.deleteRow(DEVICE_TABLE_NAME, macString);
    }

    @Override
    public void updateDevice(Device device) {
        addOrUpdateDevice(device);
    }
}


text:
layout: post
title: "Problem 1_1 [CTCI]"
modified:
categories: /ctci/ch1
excerpt:
tags: []
image:
  feature:
date: 2015-11-18T22:24:27-08:00
---
###Q
Implement an algoirthm to determine if a string has all unique characters.  What if you cannot use additional data structures?

###A

Here's the Java solution.

[Java for Problem 1.1](https://github.com/patricknyu/CtCInterview/tree/master/ch_1/1_1)

Here's the Python one.

[Python for Problem 1.1](https://github.com/patricknyu/CtCInterview/tree/master/ch_1/Python/1_1)

```python
import fileinput

def unique(s):
	charArr = list(s)
	charIdx = [0]*26
	#print(charArr)
	for i in charArr:
		if(i=='\n'):
			continue
		if(charIdx[ord(i)-97] == 1):
			return False
		else:
			charIdx[ord(i)-97]+=1
	return True

if __name__ == "__main__":
	for line in fileinput.input():
		print(line)
		print(unique(str(line)))
```

I'm not going to do 1.2 since it is a C++ problem.  My C++ is nowhere near strong enough to do difficult problems.


text:
"""Top-level Gutenberg package."""

from gutenberg._domain_model.exceptions import Error  # noqa


text:
package org.consumersunion.stories.server.business_logic;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.consumersunion.stories.common.shared.model.Collection;
import org.consumersunion.stories.common.shared.model.NotificationTrigger;
import org.consumersunion.stories.common.shared.model.Story;
import org.consumersunion.stories.common.shared.model.Subscription;
import org.consumersunion.stories.common.shared.model.SystemEntity;
import org.consumersunion.stories.common.shared.model.questionnaire.Questionnaire;
import org.consumersunion.stories.common.shared.model.questionnaire.QuestionnaireI15d;
import org.consumersunion.stories.server.notification_channel.NotificationChannel;
import org.consumersunion.stories.server.notification_channel.NotificationEvent;
import org.consumersunion.stories.server.notification_channel.StoriesAddedEvent;
import org.consumersunion.stories.server.notification_channel.SubscriptionSummary;
import org.consumersunion.stories.server.persistence.SubscriptionPersister;
import org.jukito.JukitoModule;
import org.jukito.JukitoRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InOrder;
import org.mockito.Matchers;
import org.mockito.Mockito;

import com.google.common.collect.Lists;
import com.google.common.eventbus.EventBus;
import com.google.inject.TypeLiteral;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

@RunWith(JukitoRunner.class)
public class NotificationServiceImplTest {
    public static class Module extends JukitoModule {
        @Override
        protected void configureTest() {
            forceMock(SubscriptionPersister.class);
            forceMock(EventBus.class);

            bind(new TypeLiteral<List<NotificationChannel>>() {
            }).toInstance(new ArrayList<NotificationChannel>());
        }
    }

    private static final int TARGET = 1;

    @Inject
    NotificationServiceImpl notificationService;
    @Inject
    SystemEntityService systemEntityService;
    @Inject
    AuthorizationService authService;
    @Inject
    SubscriptionPersister subscriptionPersister;
    @Inject
    List<NotificationChannel> notificationChannels;

    @Test
    public void onNotification_storyAdded_notifyGoodChannels() {
        NotificationChannel notificationChannel1 = Mockito.mock(NotificationChannel.class);
        NotificationChannel notificationChannel2 = Mockito.mock(NotificationChannel.class);
        SystemEntity systemEntity = Mockito.mock(SystemEntity.class);
        NotificationEvent event = new StoriesAddedEvent(systemEntity, Lists.<Story>newArrayList());
        List<SubscriptionSummary> subscriptionSummaries = Lists.newArrayList();

        notificationChannels.add(notificationChannel1);
        notificationChannels.add(notificationChannel2);

        when(notificationChannel1.canHandle(NotificationTrigger.STORY_ADDED)).thenReturn(true);
        when(notificationChannel2.canHandle(NotificationTrigger.STORY_ADDED)).thenReturn(false);
        when(subscriptionPersister.getActiveSubscriptions(Matchers.same(systemEntity),
                eq(NotificationTrigger.STORY_ADDED)))
                .thenReturn(subscriptionSummaries);

        notificationService.onNotification(event);

        InOrder inOrder = Mockito.inOrder(notificationChannel1);
        inOrder.verify(notificationChannel1).handleAll(Matchers.same(event), Matchers.same(subscriptionSummaries));
        inOrder.verify(notificationChannel1).flush();

        Mockito.verify(notificationChannel2, Mockito.never()).handleAll(
                Matchers.same(event), Matchers.same(subscriptionSummaries));
    }

    @Test
    public void subscribe_collection() {
        Collection collection = Mockito.mock(Collection.class);
        when(systemEntityService.getSystemEntity(TARGET)).thenReturn(collection);
        when(authService.canRead(collection)).thenReturn(true);

        notificationService.subscribe(TARGET, NotificationTrigger.STORY_ADDED);
    }

    @Test
    public void subscribe_questionnaire() {
        Questionnaire questionnaire = Mockito.mock(Questionnaire.class);
        when(systemEntityService.getSystemEntity(TARGET)).thenReturn(questionnaire);
        when(authService.canRead(questionnaire)).thenReturn(true);

        notificationService.subscribe(TARGET, NotificationTrigger.STORY_ADDED);
    }

    @Test
    public void subscribe_questionnaireI15d() {
        QuestionnaireI15d questionnaire = Mockito.mock(QuestionnaireI15d.class);
        when(systemEntityService.getSystemEntity(TARGET)).thenReturn(questionnaire);
        when(authService.canRead(questionnaire)).thenReturn(true);

        notificationService.subscribe(TARGET, NotificationTrigger.STORY_ADDED);
    }

    @Test(expected = IllegalArgumentException.class)
    public void subscribe_invalidTarget_fails() {
        Story story = Mockito.mock(Story.class);
        when(systemEntityService.getSystemEntity(TARGET)).thenReturn(story);
        when(authService.canRead(story)).thenReturn(true);

        notificationService.subscribe(TARGET, NotificationTrigger.STORY_ADDED);
    }

    @Test
    public void unsubscribe_deletesSubscription(SubscriptionPersister subscriptionPersister) {
        notificationService.unsubscribe(1, NotificationTrigger.STORY_ADDED);

        Mockito.verify(subscriptionPersister).setInactive(any(Subscription.class));
    }
}


text:
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Nest
{
	[JsonConverter(typeof(StringEnumConverter))]
	public enum TranslogDurability
	{
		[EnumMember(Value = "request")]
		Request,
		[EnumMember(Value = "async")]
		Async
	}
}


text:
from typing import cast

import sympy

import cirq
from cirq.study import sweeps
from cirq_google.api.v1 import params_pb2

def sweep_to_proto(sweep: cirq.Sweep, repetitions: int = 1) -> params_pb2.ParameterSweep:
    """Converts sweep into an equivalent protobuf representation."""
    product_sweep = None
    if sweep != cirq.UnitSweep:
        sweep = _to_zip_product(sweep)
        product_sweep = params_pb2.ProductSweep(
            factors=[_sweep_zip_to_proto(cast(cirq.Zip, factor)) for factor in sweep.factors]
        )
    msg = params_pb2.ParameterSweep(repetitions=repetitions, sweep=product_sweep)
    return msg

def _to_zip_product(sweep: cirq.Sweep) -> cirq.Product:
    """Converts sweep to a product of zips of single sweeps, if possible."""
    if not isinstance(sweep, cirq.Product):
        sweep = cirq.Product(sweep)
    if not all(isinstance(f, cirq.Zip) for f in sweep.factors):
        factors = [f if isinstance(f, cirq.Zip) else cirq.Zip(f) for f in sweep.factors]
        sweep = cirq.Product(*factors)
    for factor in sweep.factors:
        for term in cast(cirq.Zip, factor).sweeps:
            if not isinstance(term, sweeps.SingleSweep):
                raise ValueError(f'cannot convert to zip-product form: {sweep}')
    return sweep

def _sweep_zip_to_proto(sweep: cirq.Zip) -> params_pb2.ZipSweep:
    sweep_list = [_single_param_sweep_to_proto(cast(sweeps.SingleSweep, s)) for s in sweep.sweeps]
    return params_pb2.ZipSweep(sweeps=sweep_list)

def _single_param_sweep_to_proto(sweep: sweeps.SingleSweep) -> params_pb2.SingleSweep:
    if isinstance(sweep, cirq.Linspace) and not isinstance(sweep.key, sympy.Expr):
        return params_pb2.SingleSweep(
            parameter_key=sweep.key,
            linspace=params_pb2.Linspace(
                first_point=sweep.start, last_point=sweep.stop, num_points=sweep.length
            ),
        )
    elif isinstance(sweep, cirq.Points) and not isinstance(sweep.key, sympy.Expr):
        return params_pb2.SingleSweep(
            parameter_key=sweep.key, points=params_pb2.Points(points=sweep.points)
        )
    else:
        raise ValueError(f'invalid single-parameter sweep: {sweep}')

def sweep_from_proto(param_sweep: params_pb2.ParameterSweep) -> cirq.Sweep:
    if param_sweep.HasField('sweep') and len(param_sweep.sweep.factors) > 0:
        return cirq.Product(
            *[_sweep_from_param_sweep_zip_proto(f) for f in param_sweep.sweep.factors]
        )
    return cirq.UnitSweep

def _sweep_from_param_sweep_zip_proto(param_sweep_zip: params_pb2.ZipSweep) -> cirq.Sweep:
    if len(param_sweep_zip.sweeps) > 0:
        return cirq.Zip(
            *[_sweep_from_single_param_sweep_proto(sweep) for sweep in param_sweep_zip.sweeps]
        )
    return cirq.UnitSweep

def _sweep_from_single_param_sweep_proto(single_param_sweep: params_pb2.SingleSweep) -> cirq.Sweep:
    key = single_param_sweep.parameter_key
    if single_param_sweep.HasField('points'):
        points = single_param_sweep.points
        return cirq.Points(key, list(points.points))
    if single_param_sweep.HasField('linspace'):
        sl = single_param_sweep.linspace
        return cirq.Linspace(key, sl.first_point, sl.last_point, sl.num_points)

    raise ValueError('Single param sweep type undefined')


text:
// Generated by LiveScript 1.5.0
/**
 * @package CleverStyle Widgets
 * @author  Nazar Mokrynskyi <nazar@mokrynskyi.com>
 * @license 0BSD
 */
(function(){
  Polymer({
    is: 'cs-modal',
    behaviors: csw.behaviors.csModal
  });
}).call(this);


text:
package org.jbehave.examples.trader.i18n.steps;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;

import java.util.Locale;
import java.util.Map;

import org.hamcrest.Matchers;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.i18n.LocalizedKeywords;
import org.jbehave.core.model.ExamplesTable;
import org.jbehave.core.model.OutcomesTable;
import org.jbehave.core.steps.Parameters;
import org.jbehave.examples.core.model.Stock;

public class FrSteps {

    private Stock stock;
    private ExamplesTable table;

    @Given("l'on a une action avec symbole $symbol et un seuil de $threshold")
    public void aStock(@Named("symbol") String symbol, @Named("threshold") double threshold) {
        stock = new Stock(symbol, threshold);
    }

    @When("l'action est échangée au prix de $price")
    public void stockIsTraded(@Named("price") double price) {
        stock.tradeAt(price);
    }

    @Then("la position de l'alerte est $status")
    public void alertStatusIs(@Named("status") String status) {
        assertThat(stock.getStatus().name(), equalTo(status));
    }

    @Given("l'on a une table $table")
    public void aTable(ExamplesTable table) {
        this.table = table;
    }

    @Then("la table a $rows rangs")
    public void hasRows(int rows) {
        assertThat(table.getRowCount(), equalTo(rows));
    }

    @Then("au rang $row et en colonne $column on trouve: $value")
    public void theRowValuesAre(int row, String column, String value) {
        Map<String,String> rowValues = table.getRow(row-1);
        assertThat(rowValues.get(column), equalTo(value));
    }

    @Then("les valeurs multipliées par $multiplier sont: $table")
    public void theResultsMultipliedByAre(int multiplier, ExamplesTable results) {
        OutcomesTable outcomes = new OutcomesTable(new LocalizedKeywords(new Locale("fr")));
        for (int row = 0; row < results.getRowCount(); row++) {
            Parameters expected = results.getRowAsParameters(row);
            Parameters original = table.getRowAsParameters(row);
            int one = original.valueAs("un", Integer.class);
            int two = original.valueAs("deux", Integer.class);
            outcomes.addOutcome("un", one*multiplier, Matchers.equalTo(expected.valueAs("un", Integer.class)));
            outcomes.addOutcome("deux", two*multiplier, Matchers.equalTo(expected.valueAs("deux", Integer.class)));
        }
        outcomes.verify();
    }

}


text:
using System;
using Common.Base;

namespace Core.Commands.TemplateCommands
{
    public class DeleteTemplate : Command
    {
        public DeleteTemplate(Guid id)
        {
            Id = id;
        }

        public override Guid? GetAggregateId()
        {
            return null;
        }

        public override ValidationResult Validate()
        {
            var validationResult = new ValidationResult();
            return validationResult;
        }
    }
}


text:
ServerTask::ServerTask():
m_port(0),
m_netServer(nullptr)
{

}

void ServerTask::DoTask()
{
	if (!m_netServer->initServer(m_port))
	{
		return;
	}

	m_netServer->m_receiveThreadId = CTaskThreadManager::Instance().Init();

	std::shared_ptr<ReceiveNetTask> spReceiveTask(new ReceiveNetTask);
	spReceiveTask->setParam(&m_netServer->m_receiveQueue, &m_netServer->m_receiveSemaphore, m_netServer);
	CTaskThreadManager::Instance().GetThreadInterface(m_netServer->m_receiveThreadId)->PostTask(spReceiveTask);

	m_netServer->head();

	m_netServer->loop();
}

void ServerTask::setParam(int32_t port, NetServer* netServer)
{
	m_port = port;
	m_netServer = netServer;
}


text:
<?php

namespace HiPay\Wallet\Mirakl\Exception;

use Exception;

class WrongWalletBalance extends DispatchableException
{
    /** @var int  */
    protected $miraklId;
    protected $balance;

    /**
     * NoFundsAvailable constructor.
     *
     * @param int       $miraklId
     * @param string    $message
     * @param int       $code
     * @param Exception $previous
     */
    public function __construct(
        $miraklId,
        $operation,
        $amount,
        $balance,
        $code = 0,
        Exception $previous = null
    ) {
        $this->miraklId = $miraklId;
        $this->balance = $balance;
        parent::__construct(
            "This vendor ({$miraklId}) balance is insufficient. Operation type $operation / Operation amount $amount / Balance $balance",
            $code,
            $previous
        );
    }

    /**
     * @return string
     */
    public function getEventName()
    {
        return 'wrong.wallet.balance';
    }

    /**
     * @return int
     */
    public function getMiraklId()
    {
        return $this->miraklId;
    }

    /**
     * @return int
     */
    public function getBalance()
    {
        return $this->balance;
    }
}


text:
class VagrantCompletion < Formula
  desc "Bash completion for Vagrant"
  homepage "https://github.com/hashicorp/vagrant"
  url "https://github.com/hashicorp/vagrant/archive/v2.1.2.tar.gz"
  sha256 "610d704e737cbc0ccb9d27fd1b40be8bb1917cad693d2a3d841c8c36c8066939"
  head "https://github.com/hashicorp/vagrant.git"

  bottle :unneeded

  def install
    bash_completion.install "contrib/bash/completion.sh" => "vagrant"
  end

  test do
    assert_match "-F _vagrant",
      shell_output("source #{bash_completion}/vagrant && complete -p vagrant")
  end
end


text:
/**************************************************
 * Source Code for the Original Compiler for the
 * Programming Language Wake
 *
 * AddressAllocator.h
 *
 * Licensed under the MIT license
 * See LICENSE.TXT for details
 *
 * Author: Michael Fairhurst
 * Revised By:
 *
 **************************************************/

#ifndef HEADER_ADDRESS_ALLOCATOR
#define HEADER_ADDRESS_ALLOCATOR

#include <string>

using namespace std;

class AddressAllocator {

	public:
		AddressAllocator();
		string allocate();
		void deallocate();

	private:
		int stringgenerator;

};

#endif


text:
'use strict'

function isRequire(a) {
	if (a.type !== 'VariableDeclaration')
		return
	if (a.declarations.length !== 1)
		return
	a = a.declarations[0].init
	if (!a)
		return
	if (a.type !== 'CallExpression')
		return
	if (a.callee.type !== 'Identifier')
		return
	if (a.callee.name !== 'require')
		return
	return true
}

exports.isRequire = isRequire


text:
//engine: JScript
//uname: diff_doc_file
//dname: Backend к diff просмотру (doc,docx)

var objArgs,num,sBaseDoc,sNewDoc,sTempDoc,objScript,word,destination;
// Microsoft Office versions for Microsoft Windows OS
var vOffice2000 = 9;
var vOffice2002 = 10;
var vOffice2003 = 11;
var vOffice2007 = 12;
// WdCompareTarget
var wdCompareTargetSelected = 0;
var wdCompareTargetCurrent = 1;
var wdCompareTargetNew = 2;
// WdViewType
var wdMasterView = 5;
var wdNormalView = 1;
var wdOutlineView = 2;
// WdSaveOptions
var wdDoNotSaveChanges = 0;
var wdPromptToSaveChanges = -2;
var wdSaveChanges = -1;

//objArgs = WScript.Arguments;
//num = objArgs.length;
//if (num < 2)
//{
//   Message("Usage: [CScript | WScript] diff-doc.js base.doc new.doc");
//   // WScript.Quit(1);
 //}

//sBaseDoc = objArgs(0);
//sNewDoc = objArgs(1);

function diff (sBaseDoc, sNewDoc) {
// extensions: doc;docx;docm
//
// TortoiseSVN Diff script for Word Doc files
//
// Copyright (C) 2004-2008 the TortoiseSVN team
// This file is distributed under the same license as TortoiseSVN
//
// Last commit by:
// $Author: tortoisesvn $
// $Date: 2011-04-01 22:28:10 +0200 (Fr, 01. Apr 2011) $
// $Rev: 21095 $
//
// Authors:
// Stefan Kueng, 2011
// Jared Silva, 2008
// Davide Orlandi and Hans-Emil Skogh, 2005
//

objScript = new ActiveXObject("Scripting.FileSystemObject");
if ( ! objScript.FileExists(sBaseDoc))
{
    Message("File " + sBaseDoc + " does not exist.  Cannot compare the documents.");
    // WScript.Quit(1);
 return
}
if ( ! objScript.FileExists(sNewDoc))
{
    Message("File " + sNewDoc + " does not exist.  Cannot compare the documents.");
    // WScript.Quit(1);
 return
}

try
{
   word = new ActiveXObject("Word.Application");
}
catch(e)
{
	// before giving up, try with OpenOffice
	try
	{
		var OO;
		OO = new ActiveXObject("com.sun.star.ServiceManager");
	}
	catch(e)
	{
		Message("You must have Microsoft Word or OpenOffice installed to perform this operation.");
		//WScript.Quit(1);
        return;
	}
	// yes, OO is installed - do the diff with that one instead
	var objFile = objScript.GetFile(sNewDoc);
	if ((objFile.Attributes & 1)==1)
	{
		// reset the readonly attribute
		objFile.Attributes = objFile.Attributes & (~1);
	}
	//Create the DesktopSet
	var objDesktop = OO.createInstance("com.sun.star.frame.Desktop");
	var objUriTranslator = OO.createInstance("com.sun.star.uri.ExternalUriReferenceTranslator");
	//Adjust the paths for OO
	sBaseDoc = sBaseDoc.replace(/\\/g, "/");
	sBaseDoc = sBaseDoc.replace(/:/g, "|");
	sBaseDoc = sBaseDoc.replace(/ /g, "%20");
	sBaseDoc="file:///" + sBaseDoc;
	sBaseDoc=objUriTranslator.translateToInternal(sBaseDoc);
	sNewDoc = sNewDoc.replace(/\\/g, "/");
	sNewDoc = sNewDoc.replace(/:/g, "|");
	sNewDoc = sNewDoc.replace(/ /g, "%20");
	sNewDoc="file:///" + sNewDoc;
	sNewDoc=objUriTranslator.translateToInternal(sNewDoc);

	//Open the %base document
	var oPropertyValue = new Array();
	oPropertyValue[0] = OO.Bridge_GetStruct("com.sun.star.beans.PropertyValue");
	oPropertyValue[0].Name = "ShowTrackedChanges";
	oPropertyValue[0].Value = true;
	var objDocument=objDesktop.loadComponentFromURL(sNewDoc,"_blank", 0, oPropertyValue);

	//Set the frame
	var Frame = objDesktop.getCurrentFrame();

	var dispatcher=OO.CreateInstance("com.sun.star.frame.DispatchHelper");

	//Execute the comparison
	dispatcher.executeDispatch(Frame, ".uno:ShowTrackedChanges", "", 0, oPropertyValue);
	oPropertyValue[0].Name = "URL";
	oPropertyValue[0].Value = sBaseDoc;
	dispatcher.executeDispatch(Frame, ".uno:CompareDocuments", "", 0, oPropertyValue);
    return
	//WScript.Quit(0);
}

if (parseInt(word.Version) >= vOffice2007)
{
	sTempDoc = sNewDoc;
	sNewDoc = sBaseDoc;
	sBaseDoc = sTempDoc;
}

objScript = null;

word.visible = true;

// Open the new document
try
{
    destination = word.Documents.Open(sNewDoc, true, true);
}
catch(e)
{
    try
    {
        // open empty document to prevent bug where first Open() call fails
        word.Documents.Add();
        destination = word.Documents.Open(sNewDoc, true, true);
    }
    catch(e)
    {
        Message("Error opening " + sNewDoc);
        // Quit
        // WScript.Quit(1);
 return
    }
}

// If the Type property returns either wdOutlineView or wdMasterView and the Count property returns zero, the current document is an outline.
if (((destination.ActiveWindow.View.Type == wdOutlineView) || (destination.ActiveWindow.View.Type == wdMasterView)) && (destination.Subdocuments.Count == 0))
{
    // Change the Type property of the current document to normal
    destination.ActiveWindow.View.Type = wdNormalView;
}

// Compare to the base document
if (parseInt(word.Version) <= vOffice2000)
{
    // Compare for Office 2000 and earlier
    try
    {
        destination.Compare(sBaseDoc);
    }
    catch(e)
    {
        Message("Error comparing " + sBaseDoc + " and " + sNewDoc);
        // Quit
        //WScript.Quit(1);
        return
    }
}
else
{
    // Compare for Office XP (2002) and later
    try
    {
        destination.Compare(sBaseDoc, "Comparison", wdCompareTargetNew, true, true);
    }
    catch(e)
    {
        Message("Error comparing " + sBaseDoc + " and " + sNewDoc);
        // Close the first document and quit
        destination.Close(wdDoNotSaveChanges);
        // WScript.Quit(1);
 return
    }
}

// Show the comparison result
if (parseInt(word.Version) < vOffice2007)
{
	word.ActiveDocument.Windows(1).Visible = 1;
}

// Mark the comparison document as saved to prevent the annoying
// "Save as" dialog from appearing.
word.ActiveDocument.Saved = 1;

// Close the first document
if (parseInt(word.Version) >= vOffice2002)
{
    destination.Close(wdDoNotSaveChanges);
}
} //diff

function GetExtension () {
    return "doc|docx";
} //GetExtension

function GetBackend() {
    return diff
} //GetBackend


text:
<?php

namespace Zend\Filter;

/**
 * Stub class for backwards compatibility.
 *
 * Since PHP 7 adds "int" as a reserved keyword, we can no longer have a class
 * named that and retain PHP 7 compatibility. The original class has been
 * renamed to "ToInt", and this class is now an extension of it. It raises an
 * E_USER_DEPRECATED to warn users to migrate.
 *
 * @deprecated
 */
class Int extends ToInt
{
    public function __construct()
    {
        trigger_error(
            sprintf(
                'The class %s has been deprecated; please use %s\\ToInt',
                __CLASS__,
                __NAMESPACE__
            ),
            E_USER_DEPRECATED
        );
    }
}


text:
using std::string;
using std::cout;
using std::endl;

void ParseLsysXML::start(const char *el, const char *attr[]) {
  ParseXML::start(el, attr);
  for (int i = 0; attr[i]; i += 2) {
    if ( string(el)=="rule" && attr[i]==string("nonterminal") ) {
      lastNonTerminal = attr[i+1];
    }
  }
}

void ParseLsysXML::chars(const char *text, int textlen) {
  ParseXML::chars(text, textlen);
  // The text is not zero terminated; thus we need the  length:
  string str(text, textlen);
  // The text is likely to have trailing white space, e.g. newline, etc
  stripTrailWhiteSpace(str);
  if ( str.size() ) {
    if ( lastElementTag == "rule") {
      grammar.insert(std::pair<char,string>(lastNonTerminal[0], str));
    }
  }
}

void ParseLsysXML::
wrapper4Start(void *data, const char *el, const char **attr) {
  ParseLsysXML * parser = static_cast<ParseLsysXML*>(data);
  parser->start(el, attr);
}

void ParseLsysXML::wrapper4Chars(void *data, const char *text, int textlen) {
  ParseLsysXML * parser = static_cast<ParseLsysXML*>(data);
  parser->chars(text, textlen);
}


text:
using System.Threading.Tasks;

namespace MarekMotykaBot.Services.External.Interfaces
{
	public interface IImgFlipService
	{
		Task<string> CreateMarekFace(params string[] text);

		Task<string> CreateLaughingMarekMeme(params string[] text);

		Task<string> CreateSkeletorMarekMeme(params string[] text);

		Task<string> CreateDrakeMarekMeme(params string[] text);

		Task<string> CreateNosaczMeme(params string[] text);
	}
}


text:
{{extend "layout.html"}}
{{try:}}
 {{=H2(title)}}
{{except:}}
{{pass}}
Export entire Database as CSV{{=DIV( _class="tooltip", _title=T("Export Database as CSV") + "|" + T("This is the way to transfer data between machines as it maintains referential integrity."))}}

Selective export:
<form id="exporter" action="/eden/module/resource?format=representation" method="GET">

Module:
    <select id="module" name="module">
     <option value="org">Organization Registry</option>
     <option value="pr">Person Registry</option>
     <option value="cr">Shelter Registry</option>
     <option value="gis">Situation Awareness</option>
     <option value="budget">Budgetting</option>
    </select>

Resource:
    <select id="resource" name="resource">
     <option value="organisation">Organization</option>
     <option value="office">Office</option>
    </select>

Format:
    <select id="representation" name="representation">
     <option value="csv">CSV</option>
     <option value="json">JSON</option>
     <option value="xml">XML</option>
    </select>

    <input id="submit" type="submit" value="Download"/>

</form>

{{include 'admin/resources.js'}}