text:
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author  Matthew Saltz, John Miller
 *  @version 1.3
 *  @date    Fri Jul 10 12:39:33 EDT 2015
 *  @see     LICENSE (MIT style license file).
 */

package scalation.graphalytics
package mutable

import java.io.PrintWriter

import scala.collection.mutable.{Set => SET}
import scala.io.Source.fromFile
import scala.reflect.ClassTag

import scalation.util.Error

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphIO` class is used to write digraphs to a file.
 *  @param g  the digraph to write
 */
class GraphIO [TLabel: ClassTag] (g: Graph [TLabel])
      extends Error
{
    private val DEBUG = true                                     // debug flag

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Write digraph 'g' to a file in the following format:
     *

     *      Graph (<name>, <inverse>, <nVertices>
     *      <vertexId>  <chVertex0> <chVertex1> ...
     *      ...
     *      )
     *

     *  @param name  the file-name containing the graph's vertex, edge and label information
     *  @param base  the base sub-directory for storing graphs
     *  @param ext   the standard file extension for graph
     */
    def write (name: String = g.name, base: String = BASE_DIR, ext: String = EXT)
    {
        val gFile = base + name + ext                             // relative path-name for file
        val pw    = new PrintWriter (gFile)
        if (DEBUG) println (s"write: gFile = $gFile")
        pw.println (s"Graph (${g.name}, ${g.inverse}, ${g.size}")
        for (i <- g.ch.indices) pw.println (g.toLine (i))
        pw.println (")")
        pw.close ()
    } // write

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Write the graph to TWO 'igraph' compatible files.
     *  @see igraph.sourceforge.net
     */
    def write2IgraphFiles (prefix: String): (String, String) =
    {
        val lFile = prefix + "igl.txt"
        val eFile  = prefix + "ige.txt"
        val lOut   = new PrintWriter (lFile)
        g.label.foreach (lOut.println (_))
        lOut.close
        val eOut   = new PrintWriter (eFile)
        for (i <- g.ch.indices) g.ch(i).foreach (x => eOut.println (i + " " + x))
        eOut.close
        (lFile, eFile)
    } // write2IgraphFiles

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Write the graph to TWO 'Neo4J' compatible files: 'lFile' and 'eFile' so that
     *  they may be fed into 'Neo4j' with one of its utilities.
     *  FIX:  need to handle multiple edge types.
     *  @param lFile  the file containing the graph labels (line: vertex-id TAB label)
     *  @param eFile  the file the edges (line: start-id TAB end-id TAB type)
     */
    def write2Neo4JFiles (lFile: String, eFile: String)
    {
        val vertexLine = new PrintWriter (lFile)       // write the vertex ids and their labels
        vertexLine.println ("id\tlabel")
        g.label.foldLeft (1) { (i, l) => vertexLine.println (i + "\t" + l); i + 1 }
        vertexLine.close
        val edgeLine = new PrintWriter (eFile)        // write the edges and their types.
        edgeLine.println ("start\tend\ttype")
        g.ch.foldLeft (1) { (i, v) =>
            v.foreach { c => edgeLine.println (i + "\t" + (c+1) + "\tEDGE") }
            i + 1
        } // foldLeft
        edgeLine.close
    } // write2Neo4JFiles

} // GraphIO class

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphIO` object is the companion object to the `GraphIO` class and
 *  is used for reading digraphs from files.
 */
object GraphIO
       extends Error
{
    /** The standard file extension for digraphs
     */
    private val EXT = ".dig"

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Given an array of integers as strings, make the corresponding set.
     *  @param line  the element string array
     */
    def makeSet (eStrArr: Array [String]): SET [Int] =
    {
        if (eStrArr(0) == "") SET [Int] () else SET (eStrArr.map (_.toInt): _*)
    } // makeSet

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Convert a string into a label according to the type `TLabel`.
     *  @param s  the string to convert
     */
    def toLabel [TLabel] (s: String): TLabel =
    {
        val t: TLabel = null.asInstanceOf [TLabel]
        t match {
        case _: Int     => s.toInt.asInstanceOf [TLabel]
        case _: Double  => s.toDouble.asInstanceOf [TLabel]
        case _: String  => s.asInstanceOf [TLabel]
//      case _: VectorD => VectorD (s.split (","))
        case _          => { flaw ("toLabel", "label type not supported"); null.asInstanceOf [TLabel] }
        } // match
    } // toLabel

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Read a digraph from a file based on the format used by 'print' and 'write':
     *

     *      Graph (<name>, <inverse>, <nVertices>
     *      <vertexId>, , <chVertex0>, <chVertex1> ...
     *      ...
     *      )
     *

     *  @param name  the file-name containing the graph's vertex, edge and label information
     *  @param base  the base sub-directory for storing graphs
     *  @param ext   the standard file extension for graph
     *  @param sep   the character separating the values (e.g., ',', ' ', '\t')
     */
    def apply [TLabel: ClassTag] (name: String, base: String = BASE_DIR, ext: String = EXT, sep: Char = ','): Graph [TLabel] =
    {
        val gFile = base + name + ext                             // relative path-name for file
        val l     = fromFile (gFile).getLines.toArray             // get the lines from gFile
        var l0    = l(0).split ('(')(1).split (sep).map (_.trim)  // array for line 0
        val n     = l0(2).toInt                                   // number of lines in file
        val ch    = Array.ofDim [SET [Int]] (n)                   // adjacency: array of children (ch)
        val label = Array.ofDim [TLabel] (n)                      // array of vertex labels
        println (s"apply: read $n vertices from $gFile")

        for (i <- ch.indices) {
            val li   = l(i+1).split (sep).map (_.trim)            // line i (>0) splits into i, label, ch
            label(i) = toLabel (li(1))                            // make vertex label
            ch(i)    = makeSet (li.slice (2, li.length))          // make ch set
        } // for
        new Graph (ch, label, l0(1) == "true", l0(0))
    } // apply

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Read a graph from TWO files:
     *  'lFile' is a file with one label per line, where each line represents
     *    the vertex with id <lineNumber>.
     *  'eFile' is a file with each line representing the vertex with id
     *    <lineNumber>, and each line contains a space-separated list of vertices
     *    to which the current vertex is adjacent.
     *  @param lFile  the file containing the graph labels
     *  @param eFile  the file the edges (to create adjacency sets)
     *  @param inverse   whether to store inverse adjacency sets (parents)
     */
    def read2Files [TLabel: ClassTag] (lFile: String, eFile: String, inverse: Boolean = false): Graph [TLabel] =
    {
        val lLines = fromFile (lFile).getLines                    // get the lines from lFile
        val label  = lLines.map (x => toLabel (x.trim)).toArray   // make the label array
        val eLines = fromFile (eFile).getLines                    // get the lines from eFile
        val ch     = eLines.map ( line =>                         // make the adj array
            if (line.trim != "") line.split (" ").map (x => x.trim.toInt).toSet.asInstanceOf [SET [Int]]
            else SET [Int] ()
        ).toArray
        new Graph (ch, label)
    } // read2Files

    //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /** Read a graph from TWO specially formatted Pajek files.
     *  @param lFile     the file containing the graph labels
     *  @param eFile     the file the edges (to create adjacency sets)
     *  @param inverse   whether to store inverse adjacency sets (parents)
     */
    def read2PajekFile [TLabel: ClassTag] (lFile: String, eFile: String, inverse: Boolean = false): Graph [TLabel] =
    {
        val lLines = fromFile (lFile).getLines               // get the lines from lFile
        val label  = lLines.map (x => toLabel (x.trim)).toArray
        val ch     = Array.ofDim [SET [Int]] (label.size)
        for (i <- ch.indices) ch(i) = SET [Int] ()
        val eLines = fromFile (eFile).getLines               // get the lines from eFile
        for (line <- eLines) {
            val splitL = line.split (" ").map (_.trim)
            val adjs   = splitL.slice (1, splitL.length).map(_.trim.toInt).toSet
            ch(splitL(0).toInt-1) ++= adjs
        } // for
        new Graph (ch, label)
    } // read2PajekFile

} // GraphIO object

//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `GraphIOTest` object is used to test the `GraphIO` class and object.
 *  > run-main scalation.graphalytics.mutable.GraphIOTest
 */
object GraphIOTest extends App
{
    val gGen = new GraphGen [Double] (0.0)

    val name     = "ran_graph"    // the name of the graph
    val size     = 50             // size of the graph
    val nLabels  = 10             // number of distinct vertex labels
    val avDegree =  5             // average vertex out degree for the graph
    val inverse  = false

    // Create a random graph and print it out

    val ran_graph = gGen.genRandomGraph (size, nLabels, avDegree, inverse, "ran_graph")
    println (s"ran_graph = $ran_graph")
    ran_graph.printG (false)
    ran_graph.printG ()

    // Write the graph to a file

    val gIO = new GraphIO [Double] (ran_graph)
    println ("start writing graph to " + name)
    gIO.write ()
    println ("end writing graph to " + name)

    // Read the file to create a new identical graph

    val g = GraphIO (name)
    println (s"g = $g")
    g.printG ()

} // GraphIOTest object


text:
package com.cisco.trex.stateless;

import com.cisco.trex.stateless.model.RPCResponse;
import com.cisco.trex.stateless.util.IDataCompressor;
import com.cisco.trex.stateless.util.TRexDataCompressor;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.SocketType;
import org.zeromq.ZMQ;
import org.zeromq.ZMQException;

/** TRex Transport class to create zmq socket for connection to trex server */
public class TRexTransport {

  private static final Logger LOGGER = LoggerFactory.getLogger(TRexTransport.class);
  private static final int DEFAULT_TIMEOUT = 3000;
  private static final String PROTOCOL = "tcp";
  private final String connectionString;
  private final IDataCompressor dataCompressor;
  private final ZMQ.Context zmqCtx = ZMQ.context(1);
  private final ZMQ.Socket zmqSocket;
  private final String host;
  private final String port;

  /**
   * @param host Server address
   * @param port Server port
   * @param timeout How long to wait for server response
   * @param dataCompressor
   */
  public TRexTransport(String host, String port, int timeout, IDataCompressor dataCompressor) {
    this.host = host;
    this.port = port;
    this.zmqSocket = zmqCtx.socket(SocketType.REQ);
    int actualTimeout = timeout <= 0 ? DEFAULT_TIMEOUT : timeout;
    zmqSocket.setReceiveTimeOut(actualTimeout);
    zmqSocket.setSendTimeOut(actualTimeout);
    zmqSocket.setHeartbeatIvl(10 * 60 * 1000);
    zmqSocket.setHeartbeatTimeout(60000);
    zmqSocket.setReconnectIVL(20);
    zmqSocket.setReconnectIVLMax(500);
    zmqSocket.setTCPKeepAlive(1);
    this.connectionString = PROTOCOL + "://" + this.host + ":" + this.port;
    zmqSocket.connect(connectionString);
    this.dataCompressor = dataCompressor;
  }

  /**
   * @param host Server address
   * @param port Server port
   * @param timeout How long to wait for server response
   */
  public TRexTransport(String host, String port, int timeout) {
    this(host, port, timeout, new TRexDataCompressor());
  }

  /**
   * Send TRex command to the server
   *
   * @param command
   * @return RPCResponse
   * @throws IOException
   */
  public RPCResponse sendCommand(TRexCommand command) throws IOException {
    String json = new ObjectMapper().writeValueAsString(command.getParameters());
    String response = sendJson(json);
    ObjectMapper objectMapper = new ObjectMapper();
    if (objectMapper.readTree(response).isArray()) {
      // for versions of TRex before v2.61, single entry response also wrapped with json array
      RPCResponse[] rpcResult = objectMapper.readValue(response, RPCResponse[].class);
      return rpcResult[0];
    }
    return objectMapper.readValue(response, RPCResponse.class);
  }

  /**
   * Send TRex command list to the server
   *
   * @param commands
   * @return RPCResponse
   * @throws IOException
   */
  public RPCResponse[] sendCommands(List<TRexCommand> commands) throws IOException {
    if (commands.size() == 1) {
      return new RPCResponse[] {sendCommand(commands.get(0))};
    }

    List<Map<String, Object>> commandList =
        commands.stream().map(TRexCommand::getParameters).collect(Collectors.toList());

    if (commandList.isEmpty()) {
      return new RPCResponse[0];
    }

    String json = new ObjectMapper().writeValueAsString(commandList);
    String response = sendJson(json);
    return new ObjectMapper().readValue(response, RPCResponse[].class);
  }

  /** @return server host address */
  public String getHost() {
    return host;
  }

  /** @return server port */
  public String getPort() {
    return port;
  }

  /** close zmq connection to server */
  public synchronized void close() {
    zmqSocket.disconnect(connectionString);
    zmqSocket.close();
    zmqCtx.close();
  }

  /** @return zmq socket */
  public ZMQ.Socket getSocket() {
    return zmqSocket;
  }

  /**
   * Send json string to server
   *
   * @param json
   * @return json string
   */
  public synchronized String sendJson(String json) {
    LOGGER.debug("JSON Req: {}", json);

    byte[] compressed = this.dataCompressor.compressStringToBytes(json);

    String response;
    try {
      zmqSocket.send(compressed);
      byte[] msg = zmqSocket.recv();
      response = this.dataCompressor.decompressBytesToString(msg);
    } catch (ZMQException e) {
      throw new IllegalStateException(
          "Failed to send or recv json request or response due to ZMQ error: " + e.getErrorCode(),
          e);
    }

    if (response == null) {
      throw new IllegalStateException(
          "Got null json response, the reason could be get no response from server within timeout, or the ZMQ socket connection is in bad state either on client side or on server side.");
    }
    LOGGER.debug("JSON Resp: {}", response);
    return response;
  }
}

redpajama_set_name: RedPajamaGithub


text:
   /*******************************************************/
   /*      "C" Language Integrated Production System      */
   /*                                                     */
   /*             CLIPS Version 6.22  06/15/04            */
   /*                                                     */
   /*         DEFMODULE BASIC COMMANDS HEADER FILE        */
   /*******************************************************/

/*************************************************************/
/* Purpose: Implements core commands for the defmodule       */
/*   construct such as clear, reset, save, ppdefmodule       */
/*   list-defmodules, and get-defmodule-list.                */
/*                                                           */
/* Principal Programmer(s):                                  */
/*      Gary D. Riley                                        */
/*                                                           */
/* Contributing Programmer(s):                               */
/*      Brian L. Dantes                                      */
/*                                                           */
/* Revision History:                                         */
/*                                                           */
/*************************************************************/

#define _MODULBSC_SOURCE_

#include "setup.h"

#include <stdio.h>
#define _STDIO_INCLUDED_
#include <string.h>

#include "constrct.h"
#include "extnfunc.h"
#include "modulbin.h"
#include "prntutil.h"
#include "modulcmp.h"
#include "router.h"
#include "argacces.h"
#include "bload.h"
#include "envrnmnt.h"

#include "modulbsc.h"

/***************************************/
/* LOCAL INTERNAL FUNCTION DEFINITIONS */
/***************************************/

   static void                    ClearDefmodules(void *);
#if DEFMODULE_CONSTRUCT
   static void                    SaveDefmodules(void *,void *,char *);
#endif

/*****************************************************************/
/* DefmoduleBasicCommands: Initializes basic defmodule commands. */
/*****************************************************************/
globle void DefmoduleBasicCommands(
  void *theEnv)
  {
   EnvAddClearFunction(theEnv,"defmodule",ClearDefmodules,2000);

#if DEFMODULE_CONSTRUCT
   AddSaveFunction(theEnv,"defmodule",SaveDefmodules,1100);

#if ! RUN_TIME
   EnvDefineFunction2(theEnv,"get-defmodule-list",'m',PTIEF EnvGetDefmoduleList,"EnvGetDefmoduleList","00");

#if DEBUGGING_FUNCTIONS
   EnvDefineFunction2(theEnv,"list-defmodules",'v', PTIEF ListDefmodulesCommand,"ListDefmodulesCommand","00");
   EnvDefineFunction2(theEnv,"ppdefmodule",'v',PTIEF PPDefmoduleCommand,"PPDefmoduleCommand","11w");
#endif
#endif
#endif

#if (BLOAD || BLOAD_ONLY || BLOAD_AND_BSAVE)
   DefmoduleBinarySetup(theEnv);
#endif

#if CONSTRUCT_COMPILER && (! RUN_TIME)
   DefmoduleCompilerSetup(theEnv);
#endif
  }

/*********************************************************/
/* ClearDefmodules: Defmodule clear routine for use with */
/*   the clear command. Creates the MAIN module.         */
/*********************************************************/
static void ClearDefmodules(
  void *theEnv)
  {
#if (BLOAD || BLOAD_AND_BSAVE || BLOAD_ONLY) && (! RUN_TIME)
   if (Bloaded(theEnv) == TRUE) return;
#endif
#if (! RUN_TIME)
   RemoveAllDefmodules(theEnv);

   CreateMainModule(theEnv);
   DefmoduleData(theEnv)->MainModuleRedefinable = TRUE;
#else
#if MAC_MCW || WIN_MCW || MAC_XCD
#pragma unused(theEnv)
#endif
#endif
  }

#if DEFMODULE_CONSTRUCT

/******************************************/
/* SaveDefmodules: Defmodule save routine */
/*   for use with the save command.       */
/******************************************/
static void SaveDefmodules(
  void *theEnv,
  void *theModule,
  char *logicalName)
  {
   char *ppform;

   ppform = EnvGetDefmodulePPForm(theEnv,theModule);
   if (ppform != NULL)
     {
      PrintInChunks(theEnv,logicalName,ppform);
      EnvPrintRouter(theEnv,logicalName,"\n");
     }
  }

/*************************************************/
/* EnvGetDefmoduleList: H/L and C access routine */
/*   for the get-defmodule-list function.        */
/*************************************************/
globle void EnvGetDefmoduleList(
  void *theEnv,
  DATA_OBJECT_PTR returnValue)
  {
   OldGetConstructList(theEnv,returnValue,EnvGetNextDefmodule,EnvGetDefmoduleName);
  }

#if DEBUGGING_FUNCTIONS

/********************************************/
/* PPDefmoduleCommand: H/L access routine   */
/*   for the ppdefmodule command.           */
/********************************************/
globle void PPDefmoduleCommand(
  void *theEnv)
  {
   char *defmoduleName;

   defmoduleName = GetConstructName(theEnv,"ppdefmodule","defmodule name");
   if (defmoduleName == NULL) return;

   PPDefmodule(theEnv,defmoduleName,WDISPLAY);

   return;
  }

/*************************************/
/* PPDefmodule: C access routine for */
/*   the ppdefmodule command.        */
/*************************************/
globle int PPDefmodule(
  void *theEnv,
  char *defmoduleName,
  char *logicalName)
  {
   void *defmodulePtr;

   defmodulePtr = EnvFindDefmodule(theEnv,defmoduleName);
   if (defmodulePtr == NULL)
     {
      CantFindItemErrorMessage(theEnv,"defmodule",defmoduleName);
      return(FALSE);
     }

   if (EnvGetDefmodulePPForm(theEnv,defmodulePtr) == NULL) return(TRUE);
   PrintInChunks(theEnv,logicalName,EnvGetDefmodulePPForm(theEnv,defmodulePtr));
   return(TRUE);
  }

/***********************************************/
/* ListDefmodulesCommand: H/L access routine   */
/*   for the list-defmodules command.          */
/***********************************************/
globle void ListDefmodulesCommand(
  void *theEnv)
  {
   if (EnvArgCountCheck(theEnv,"list-defmodules",EXACTLY,0) == -1) return;

   EnvListDefmodules(theEnv,WDISPLAY);
  }

/***************************************/
/* EnvListDefmodules: C access routine */
/*   for the list-defmodules command.  */
/***************************************/
globle void EnvListDefmodules(
  void *theEnv,
  char *logicalName)
  {
   void *theModule;
   int count = 0;

   for (theModule = EnvGetNextDefmodule(theEnv,NULL);
        theModule != NULL;
        theModule = EnvGetNextDefmodule(theEnv,theModule))
    {
     EnvPrintRouter(theEnv,logicalName,EnvGetDefmoduleName(theEnv,theModule));
     EnvPrintRouter(theEnv,logicalName,"\n");
     count++;
    }

   PrintTally(theEnv,logicalName,count,"defmodule","defmodules");
  }

#endif /* DEBUGGING_FUNCTIONS */

#endif /* DEFMODULE_CONSTRUCT */


text:
Genetic Algorithm for Traveling Salesman with feature to choose only right angle paths and a real time graph.

Link: https://drive.google.com/a/ostatemail.okstate.edu/file/d/0B0Ii9uXaBZhBYlZDOXVpQ3RHelU/view?usp=drive_web

The file is password protected. Email me at rahul.chidurala@okstate.edu for the password.


text:
// ----------------------------------------------------------------------------------
// <copyright file="ForeignKeyViolationException.cs" company="NMemory Team">
//     Copyright (C) NMemory Team
//
//     Permission is hereby granted, free of charge, to any person obtaining a copy
//     of this software and associated documentation files (the "Software"), to deal
//     in the Software without restriction, including without limitation the rights
//     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//     copies of the Software, and to permit persons to whom the Software is
//     furnished to do so, subject to the following conditions:
//
//     The above copyright notice and this permission notice shall be included in
//     all copies or substantial portions of the Software.
//
//     THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//     THE SOFTWARE.
// </copyright>
// ----------------------------------------------------------------------------------

namespace NMemory.Exceptions
{
    using System.Linq;
    using NMemory.Indexes;

    public class ForeignKeyViolationException : NMemoryException
    {
        public ForeignKeyViolationException(
            IIndex primaryIndex,
            IIndex foreignIndex,
            object primaryKey)
            : base(
                ErrorCode.RelationError,
                GetMessage(primaryIndex, foreignIndex, primaryKey))
        {
        }

        private static string GetMessage(
            IIndex primaryIndex,
            IIndex foreignIndex,
            object primaryKey)
        {
            string foreignTable =
                foreignIndex.Table.EntityType.Name;

            string foreignColumns =
                string.Join(", ", foreignIndex.KeyInfo.EntityKeyMembers.Select(m => m.Name));

            string primaryTable =
                primaryIndex.Table.EntityType.Name;

            string primaryColumns =
                string.Join(", ", primaryIndex.KeyInfo.EntityKeyMembers.Select(m => m.Name));

            return string.Format(
                ExceptionMessages.ForeignKeyViolation,
                foreignTable,
                foreignColumns,
                primaryKey,
                primaryTable,
                primaryColumns);

        }
    }
}


text:
using JetBrains.Application.UI.Options;
using JetBrains.Application.UI.Options.OptionsDialog;
using JetBrains.ReSharper.Feature.Services.Daemon.OptionPages;
using JetBrains.ReSharper.Feature.Services.Resources;

namespace AsyncConverter.Settings
{
    [OptionsPage(PID, "Async Converter", typeof(ServicesThemedIcons.FileStorage), ParentId = CodeInspectionPage.PID)]
    public sealed class AsyncConverterPage : AEmptyOptionsPage
    {
        public const string PID = "AsyncConverter";
    }
}


text:
import unittest
import pytest
from mock import Mock, patch

from calvin.tests import DummyNode
from calvin.runtime.north.actormanager import ActorManager
from calvin.runtime.north.plugins.port import queue

pytestmark = pytest.mark.unittest

class ActorManagerTests(unittest.TestCase):

    def setUp(self):
        n = DummyNode()
        self.am = ActorManager(node=n)
        n.am = self.am
        n.pm.remove_ports_of_actor = Mock(return_value = [])

    def tearDown(self):
        pass

    def _new_actor(self, a_type, a_args, **kwargs):
        a_id = self.am.new(a_type, a_args, **kwargs)
        a = self.am.actors.get(a_id, None)
        self.assertTrue(a)
        return a, a_id

    def test_new_actor(self):
        # Test basic actor creation
        a_type = 'std.Constantify'
        constant = 42
        a, _ = self._new_actor(a_type, {'constant':constant})
        self.assertEqual(a.constant, constant)

    def test_actor_state_get(self):
        # Test basic actor state retrieval
        a_type = 'std.Constantify'
        constant = 42
        a, a_id = self._new_actor(a_type, {'constant':constant})
        s = a.serialize()

        self.assertEqual(s['managed']['constant'], constant)
        self.assertEqual(s['private']['_id'], a_id)

    def test_new_actor_from_state(self):
        # Test basic actor state manipulation
        a_type = 'std.Constantify'
        constant = 42
        a, a_id = self._new_actor(a_type, {'constant':constant})
        a.constant = 43
        s = a.serialize()
        self.am.destroy(a_id)
        self.assertEqual(len(self.am.actors), 0)

        b, b_id = self._new_actor(a_type, None, state = s)

        self.assertEqual(a.constant, 43)
        # Assert id is preserved
        self.assertEqual(a.id, a_id)
        # Assert actor database is consistent
        self.assertTrue(self.am.actors[a_id])
        self.assertEqual(len(self.am.actors), 1)

    @patch('calvin.runtime.north.storage.Storage.delete_actor')
    def test_destroy_actor(self, delete_actor):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42})
        self.am.destroy(actor_id)

        assert actor_id not in self.am.actors
        assert self.am.node.storage.delete_actor.call_args[0][0] == actor_id
        self.am.node.control.log_actor_destroy.assert_called_with(actor_id)

    def test_enable_actor(self):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42})

        actor.enable = Mock()
        self.am.enable(actor_id)
        assert actor.enable.called

    def test_disable_actor(self):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42})

        actor.disable = Mock()
        self.am.disable(actor_id)
        assert actor.disable.called

    def test_migrate_to_same_node_does_nothing(self):
        callback_mock = Mock()
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42})
        actor.will_migrate = Mock()

        self.am.migrate(actor_id, self.am.node.id, callback_mock)
        assert not actor.will_migrate.called
        assert callback_mock.called
        args, kwargs = callback_mock.call_args
        self.assertEqual(kwargs['status'].status, 200)

    def test_migrate_non_existing_actor_returns_false(self):
        callback_mock = Mock()

        self.am.migrate("123", self.am.node.id, callback_mock)
        assert callback_mock.called
        args, kwargs = callback_mock.call_args
        self.assertEqual(kwargs['status'].status, 500)

    def test_migrate(self):
        callback_mock = Mock()

        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42})
        actor.outports['out'].set_queue(queue.fanout_fifo.FanoutFIFO({'queue_length': 4, 'direction': "out"}, {}))
        actor.inports['in'].set_queue(queue.fanout_fifo.FanoutFIFO({'queue_length': 4, 'direction': "in"}, {}))
        peer_node = DummyNode()

        actor.will_migrate = Mock()

        self.am.migrate(actor_id, peer_node.id, callback_mock)

        assert actor.will_migrate.called
        assert self.am.node.pm.disconnect.called

        args, kwargs = self.am.node.pm.disconnect.call_args
        self.assertEqual(kwargs['actor_id'], actor_id)

        cb = kwargs['callback']
        self.assertEqual(cb.kwargs['actor'], actor)
        self.assertEqual(cb.kwargs['actor_type'], actor._type)
        self.assertEqual(cb.kwargs['callback'], callback_mock)
        self.assertEqual(cb.kwargs['node_id'], peer_node.id)
        self.assertEqual(cb.kwargs['ports'], actor.connections(self.am.node.id))
        self.am.node.control.log_actor_migrate.assert_called_once_with(actor_id, peer_node.id)

    def test_connect(self):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42})
        connection_list = [['1', '2', '3', '4'], ['5', '6', '7', '8']]
        callback_mock = Mock()

        self.am.connect(actor_id, connection_list, callback_mock)

        self.assertEqual(self.am.node.pm.connect.call_count, 2)
        calls = self.am.node.pm.connect.call_args_list
        for index, (args, kwargs) in enumerate(calls):
            self.assertEqual(kwargs['port_id'], connection_list[index][1])
            self.assertEqual(kwargs['peer_node_id'], connection_list[index][2])
            self.assertEqual(kwargs['peer_port_id'], connection_list[index][3])
            callback = kwargs['callback'].kwargs
            self.assertEqual(callback['peer_port_id'], connection_list[index][3])
            self.assertEqual(callback['actor_id'], actor_id)
            self.assertEqual(callback['peer_port_ids'], ['4', '8'])
            self.assertEqual(callback['_callback'], callback_mock)

    def test_connections_returns_actor_connections_for_current_node(self):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42, 'name': 'actor'})
        actor.outports['out'].set_queue(queue.fanout_fifo.FanoutFIFO({'queue_length': 4, 'direction': "out"}, {}))
        actor.inports['in'].set_queue(queue.fanout_fifo.FanoutFIFO({'queue_length': 4, 'direction': "in"}, {}))

        expected = {
            'actor_name': 'actor',
            'actor_id': actor_id,
            'inports': {actor.inports['in'].id: actor.inports['in'].get_peers()},
            'outports': {actor.outports['out'].id: actor.outports['out'].get_peers()}
        }
        self.assertEqual(self.am.connections(actor_id), expected)

    def test_missing_actor(self):
        test_functions = [("report", ({},)), ("destroy", ()), ("enable", ()), ("disable", ()),
                          ("connect", ([], None)), ("connections", ()), ("dump", ()),
                          ("get_port_state", (None, ))]
        for func, args in test_functions:
            with pytest.raises(Exception) as excinfo:
                print func
                getattr(self.am, func)('123', *args)
            assert "Actor '123' not found" in str(excinfo.value)

    def test_actor_type(self):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42, 'name': 'actor'})
        self.assertEqual(self.am.actor_type(actor_id), 'std.Constantify')

    def test_actor_type_of_missing_actor(self):
        self.assertEqual(self.am.actor_type("123"), 'BAD ACTOR')

    def test_enabled_actors(self):
        actor, actor_id = self._new_actor('std.Constantify', {'constant': 42, 'name': 'actor'})
        enabled_actor, enabled_actor_id = self._new_actor('std.Constantify', {'constant': 42, 'name': 'actor'})
        enabled_actor.enable()
        self.assertEqual(self.am.enabled_actors(), [enabled_actor])

    def test_list_actors(self):
        actor_1, actor_1_id = self._new_actor('std.Constantify', {'constant': 42, 'name': 'actor'})
        actor_2, actor_2_id = self._new_actor('std.Constantify', {'constant': 42, 'name': 'actor'})
        actors = self.am.list_actors()
        assert actor_1_id in actors
        assert actor_2_id in actors

if __name__ == '__main__':
    import unittest
    suite = unittest.TestLoader().loadTestsFromTestCase(ActorManagerTests)
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
package org.parboiled.examples.time;

import org.parboiled.BaseParser;
import org.parboiled.Rule;
import org.parboiled.annotations.BuildParseTree;

/**
 * Parser for very relaxed time literals. Demonstrates usage of the value stack with default values for unmatched rules.
 */
@BuildParseTree
public class TimeParser extends BaseParser<Object> {

    public Rule Time() {
        return FirstOf(Time_HH_MM_SS(), Time_HHMMSS(), Time_HMM());
    }

    // h(h)?:mm(:ss)?
    Rule Time_HH_MM_SS() {
        return Sequence(
                OneOrTwoDigits(), ':',
                TwoDigits(),
                FirstOf(Sequence(':', TwoDigits()), push(0)),
                EOI,
                swap3() && push(convertToTime(popAsInt(), popAsInt(), popAsInt()))
        );
    }

    // hh(mm(ss)?)?
    Rule Time_HHMMSS() {
        return Sequence(
                TwoDigits(),
                FirstOf(
                        Sequence(
                                TwoDigits(),
                                FirstOf(TwoDigits(), push(0))
                        ),
                        pushAll(0, 0)
                ),
                EOI,
                swap3() && push(convertToTime(popAsInt(), popAsInt(), popAsInt()))
        );
    }

    // h(mm)?
    Rule Time_HMM() {
        return Sequence(
                OneDigit(),
                FirstOf(TwoDigits(), push(0)),
                EOI,
                swap() && push(convertToTime(popAsInt(), popAsInt()))
        );
    }

    Rule OneOrTwoDigits() {
        return FirstOf(TwoDigits(), OneDigit());
    }

    Rule OneDigit() {
        return Sequence(Digit(), push(Integer.parseInt(matchOrDefault("0"))));
    }

    Rule TwoDigits() {
        return Sequence(Sequence(Digit(), Digit()), push(Integer.parseInt(matchOrDefault("0"))));
    }

    Rule Digit() {
        return CharRange('0', '9');
    }

    // ************************* ACTIONS *****************************

    protected Integer popAsInt() {
        return (Integer) pop();
    }

    protected String convertToTime(Integer hours, Integer minutes) {
        return convertToTime(hours, minutes, 0);
    }

    protected String convertToTime(Integer hours, Integer minutes, Integer seconds) {
        return String.format("%s h, %s min, %s s",
                hours != null ? hours : 0,
                minutes != null ? minutes : 0,
                seconds != null ? seconds : 0);
    }

}


text:
body {
  font-family: 'Lato', 'Helvetica Neue', Helvetica, Arial, sans-serif;
  overflow-x: hidden; }

p {
  font-size: 20px; }

p.small {
  font-size: 16px; }

a,
a:hover,
a:focus,
a:active,
a.active {
  color: #18BC9C;
  outline: none; }

h1,
h2,
h3,
h4,
h5,
h6 {
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  text-transform: uppercase;
  font-weight: 700; }

hr.star-light,
hr.star-primary {
  padding: 0;
  border: none;
  border-top: solid 5px;
  text-align: center;
  max-width: 250px;
  margin: 25px auto 30px; }

hr.star-light:after,
hr.star-primary:after {
  content: "\f005";
  font-family: FontAwesome;
  display: inline-block;
  position: relative;
  top: -0.8em;
  font-size: 2em;
  padding: 0 0.25em; }

hr.star-light {
  border-color: #2B2B2B; }

hr.star-light:after {
  background-color: #2B2B2B;
  color: white; }

hr.star-primary {
  border-color: #2B2B2B; }

hr.star-primary:after {
  background-color: white;
  color: #2B2B2B; }

.img-centered {
  margin: 0 auto; }

header {
  text-align: center;
  background: #2B2B2B;
  color: white; }
  header .container {
    padding-top: 100px;
    padding-bottom: 50px; }
  header img {
    display: block;
    margin: 0 auto 20px; }
  header .intro-text .name {
    display: block;
    font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-weight: 700;
    font-size: 2em; }
  header .intro-text .skills {
    font-size: 1.25em;
    font-weight: 300; }

@media (min-width: 768px) {
  header .container {
    padding-top: 200px;
    padding-bottom: 100px; }
  header .intro-text .name {
    font-size: 2.50em; }
  header .intro-text .skills {
    font-size: 1.75em; } }

#mainNav {
  background: #FFFFFF;
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: 700;
  border: none; }
  #mainNav a:focus {
    outline: none; }
  #mainNav .navbar-brand {
    color: #2B2B2B; }
    #mainNav .navbar-brand:hover, #mainNav .navbar-brand:focus, #mainNav .navbar-brand:active, #mainNav .navbar-brand.active {
      color: white; }
  #mainNav .navbar-nav {
    letter-spacing: 1px; }
    #mainNav .navbar-nav li.nav-item a.nav-link {
      color: #2B2B2B; }
      #mainNav .navbar-nav li.nav-item a.nav-link:hover {
        color: #2B2B2B;
        text-decoration:  none;
        outline: none; }
      #mainNav .navbar-nav li.nav-item a.nav-link:focus, #mainNav .navbar-nav li.nav-item a.nav-link:active {
        color: white; }
    #mainNav .navbar-nav li.nav-item.active a {
      color: white;
      background: #18BC9C; }
      #mainNav .navbar-nav li.nav-item.active a:hover, #mainNav .navbar-nav li.nav-item.active a:focus, #mainNav .navbar-nav li.nav-item.active a:active {
        color: white;
        background: #18BC9C; }
  #mainNav .navbar-toggler {
    color: grey;
    font-size: 14px;
    border-color: white;
    padding: 11px; }
    #mainNav .navbar-toggler:hover, #mainNav .navbar-toggler:focus {
      background-color: #2B2B2B;
      color: white;
      border-color: #2B2B2B; }

@media (min-width: 992px) {
  #mainNav {
    padding: 0 0;
    -webkit-transition: padding 0.3s;
    -moz-transition: padding 0.3s;
    transition: padding 0.3s; }
    #mainNav .navbar-brand {
      font-size: 2em;
      -webkit-transition: all 0.3s;
      -moz-transition: all 0.3s;
      transition: all 0.3s; }
  #mainNav.navbar-shrink {
    padding: 0 0; }
    #mainNav.navbar-shrink .navbar-brand {
      font-size: 1.5em; } }

section {
  padding: 50px 0; }
  section h2 {
    margin: 0;
    font-size: 3em; }

section.success {
  background: #FFFFFF;
  color: #2B2B2B; }

@media (max-width: 767px) {
  section {
    padding: 75px 0; }
  section.first {
    padding-top: 75px; } }

#website .portfolio-item {
  margin: 0 0 15px;
  right: 0; }
  #website .portfolio-item .portfolio-link {
    display: block;
    position: relative;
    max-width: 400px;
    margin: 0 auto; }
    #website .portfolio-item .portfolio-link .caption {
      background: rgba(221, 221, 221, 0.9);
      position: absolute;
      width: 100%;
      height: 100%;
      opacity: 0;
      transition: all ease 0.5s;
      -webkit-transition: all ease 0.5s;
      -moz-transition: all ease 0.5s; }
      #website .portfolio-item .portfolio-link .caption:hover {
        opacity: 1; }
      #website .portfolio-item .portfolio-link .caption .caption-content {
        position: absolute;
        width: 100%;
        height: 20px;
        font-size: 20px;
        text-align: center;
        top: 50%;
        margin-top: -12px;
        color: white; }
        #website .portfolio-item .portfolio-link .caption .caption-content i {
          margin-top: -12px; }
        #website .portfolio-item .portfolio-link .caption .caption-content h3,
        #website .portfolio-item .portfolio-link .caption .caption-content h4 {
          margin: 0; }

#website * {
  z-index: 2;
}

@media (min-width: 767px) {
  #website .portfolio-item {
    margin: 0 0 30px; } }

    #graphic .portfolio-item {
      margin: 0 0 15px;
      right: 0; }
      #graphic .portfolio-item .portfolio-link {
        display: block;
        position: relative;
        max-width: 400px;
        margin: 0 auto; }
        #graphic .portfolio-item .portfolio-link .caption {
          background: rgba(221, 221, 221, 0.9);
          position: absolute;
          width: 100%;
          height: 100%;
          opacity: 0;
          transition: all ease 0.5s;
          -webkit-transition: all ease 0.5s;
          -moz-transition: all ease 0.5s; }
          #graphic .portfolio-item .portfolio-link .caption:hover {
            opacity: 1; }
          #graphic .portfolio-item .portfolio-link .caption .caption-content {
            position: absolute;
            width: 100%;
            height: 20px;
            font-size: 20px;
            text-align: center;
            top: 50%;
            margin-top: -12px;
            color: white; }
            #graphic .portfolio-item .portfolio-link .caption .caption-content i {
              margin-top: -12px; }
            #graphic .portfolio-item .portfolio-link .caption .caption-content h3,
            #graphic .portfolio-item .portfolio-link .caption .caption-content h4 {
              margin: 0; }

    #graphic * {
      z-index: 2;
    }

    @media (min-width: 767px) {
      #graphic .portfolio-item {
        margin: 0 0 30px; } }

        #photo .portfolio-item {
          margin: 0 0 15px;
          right: 0; }
          #photo .portfolio-item .portfolio-link {
            display: block;
            position: relative;
            max-width: 400px;
            margin: 0 auto; }
            #photo .portfolio-item .portfolio-link .caption {
              background: rgba(221, 221, 221, 0.9);
              position: absolute;
              width: 100%;
              height: 100%;
              opacity: 0;
              transition: all ease 0.5s;
              -webkit-transition: all ease 0.5s;
              -moz-transition: all ease 0.5s; }
              #photo .portfolio-item .portfolio-link .caption:hover {
                opacity: 1; }
              #photo .portfolio-item .portfolio-link .caption .caption-content {
                position: absolute;
                width: 100%;
                height: 20px;
                font-size: 20px;
                text-align: center;
                top: 50%;
                margin-top: -12px;
                color: white; }
                #photo .portfolio-item .portfolio-link .caption .caption-content i {
                  margin-top: -12px; }
                #photo .portfolio-item .portfolio-link .caption .caption-content h3,
                #photo .portfolio-item .portfolio-link .caption .caption-content h4 {
                  margin: 0; }

        #photo * {
          z-index: 2;
        }

        @media (min-width: 767px) {
          #photo .portfolio-item {
            margin: 0 0 30px; } }

            #video .portfolio-item {
              margin: 0 0 15px;
              right: 0; }
              #video .portfolio-item .portfolio-link {
                display: block;
                position: relative;
                max-width: 400px;
                margin: 0 auto; }
                #video .portfolio-item .portfolio-link .caption {
                  background: rgba(221, 221, 221, 0.9);
                  position: absolute;
                  width: 100%;
                  height: 100%;
                  opacity: 0;
                  transition: all ease 0.5s;
                  -webkit-transition: all ease 0.5s;
                  -moz-transition: all ease 0.5s; }
                  #video .portfolio-item .portfolio-link .caption:hover {
                    opacity: 1; }
                  #video .portfolio-item .portfolio-link .caption .caption-content {
                    position: absolute;
                    width: 100%;
                    height: 20px;
                    font-size: 20px;
                    text-align: center;
                    top: 50%;
                    margin-top: -12px;
                    color: white; }
                    #video .portfolio-item .portfolio-link .caption .caption-content i {
                      margin-top: -12px; }
                    #video .portfolio-item .portfolio-link .caption .caption-content h3,
                    #video .portfolio-item .portfolio-link .caption .caption-content h4 {
                      margin: 0; }

            #video * {
              z-index: 2;
            }

            @media (min-width: 767px) {
              #video .portfolio-item {
                margin: 0 0 30px; } }
.floating-label-form-group {
  position: relative;
  margin-bottom: 0;
  padding-bottom: 0.5em;
  border-bottom: 1px solid #eeeeee; }
  .floating-label-form-group input,
  .floating-label-form-group textarea {
    z-index: 1;
    position: relative;
    padding-right: 0;
    padding-left: 0;
    border: none;
    border-radius: 0;
    font-size: 1.5em;
    background: none;
    box-shadow: none !important;
    resize: none; }
  .floating-label-form-group label {
    display: block;
    z-index: 0;
    position: relative;
    top: 2em;
    margin: 0;
    font-size: 0.85em;
    line-height: 1.764705882em;
    vertical-align: middle;
    vertical-align: baseline;
    opacity: 0;
    -webkit-transition: top 0.3s ease, opacity 0.3s ease;
    -moz-transition: top 0.3s ease, opacity 0.3s ease;
    -ms-transition: top 0.3s ease, opacity 0.3s ease;
    transition: top 0.3s ease, opacity 0.3s ease; }
  .floating-label-form-group:not(:first-child) {
    padding-left: 14px;
    border-left: 1px solid #eeeeee; }

.floating-label-form-group-with-value label {
  top: 0;
  opacity: 1; }

.floating-label-form-group-with-focus label {
  color: #18BC9C; }

form .row:first-child .floating-label-form-group {
  border-top: 1px solid #eeeeee; }

footer {
  color: white; }
  footer h3 {
    margin-bottom: 30px; }
  footer .footer-above {
    padding-top: 50px;
    background-color: #2C3E50; }
  footer .footer-col {
    margin-bottom: 50px; }
  footer .footer-below {
    padding: 25px 0;
    background-color: #2c3e50; }

.btn-outline {
  color: white;
  font-size: 20px;
  border: solid 2px white;
  background: transparent;
  transition: all 0.3s ease-in-out;
  margin-top: 15px; }
  .btn-outline:hover, .btn-outline:focus, .btn-outline:active, .btn-outline.active {
    color: #18BC9C;
    background: white;
    border: solid 2px white; }

.btn-primary {
  color: white;
  background-color: #2C3E50;
  border-color: #2C3E50;
  font-weight: 700; }
  .btn-primary:focus, .btn-primary.focus {
    color: white;
    background-color: #1a252f;
    border-color: black; }
  .btn-primary:hover {
    color: white;
    background-color: #1a252f;
    border-color: #161f29; }
  .btn-primary:active, .btn-primary.active,
  .open > .btn-primary.dropdown-toggle {
    color: white;
    background-color: #1a252f;
    border-color: #161f29; }
    .btn-primary:active:hover, .btn-primary:active:focus, .btn-primary:active.focus, .btn-primary.active:hover, .btn-primary.active:focus, .btn-primary.active.focus,
    .open > .btn-primary.dropdown-toggle:hover,
    .open > .btn-primary.dropdown-toggle:focus,
    .open > .btn-primary.dropdown-toggle.focus {
      color: white;
      background-color: #0d1318;
      border-color: black; }
  .btn-primary:active, .btn-primary.active,
  .open > .btn-primary.dropdown-toggle {
    background-image: none; }
  .btn-primary.disabled:hover, .btn-primary.disabled:focus, .btn-primary.disabled.focus, .btn-primary[disabled]:hover, .btn-primary[disabled]:focus, .btn-primary[disabled].focus,
  fieldset[disabled] .btn-primary:hover,
  fieldset[disabled] .btn-primary:focus,
  fieldset[disabled] .btn-primary.focus {
    background-color: #2C3E50;
    border-color: #2C3E50; }
  .btn-primary .badge {
    color: #2C3E50;
    background-color: white; }

.btn-success {
  color: white;
  background-color: #2B2B2B;
  border-color: #2B2B2B;
  font-weight: 700; }
  .btn-success:focus, .btn-success.focus {
    color: white;
    background-color: #2B2B2B;
    border-color: #2B2B2B;
    box-shadow: none;}
  .btn-success:hover {
    color: #2B2B2B;
    background-color: #efefef;
    border-color: #efefef; }
  .btn-success:active, .btn-success.active,
  .open > .btn-success.dropdown-toggle {
    color: white;
    background-color: #2B2B2B;
    border-color: #2B2B2B; }
    .btn-success:active:hover, .btn-success:active:focus, .btn-success:active.focus, .btn-success.active:hover, .btn-success.active:focus, .btn-success.active.focus,
    .open > .btn-success.dropdown-toggle:hover,
    .open > .btn-success.dropdown-toggle:focus,
    .open > .btn-success.dropdown-toggle.focus {
      color: white;
      background-color: #2B2B2B;
      border-color: #2B2B2B; }
  .btn-success:active, .btn-success.active,
  .open > .btn-success.dropdown-toggle {
    background-image: none; }
  .btn-success.disabled:hover, .btn-success.disabled:focus, .btn-success.disabled.focus, .btn-success[disabled]:hover, .btn-success[disabled]:focus, .btn-success[disabled].focus,
  fieldset[disabled] .btn-success:hover,
  fieldset[disabled] .btn-success:focus,
  fieldset[disabled] .btn-success.focus {
    background-color: #18BC9C;
    border-color: #18BC9C; }
  .btn-success .badge {
    color: #18BC9C;
    background-color: white; }

.btn-social {
  display: inline-block;
  height: 50px;
  width: 50px;
  border: 2px solid white;
  border-radius: 100%;
  text-align: center;
  font-size: 20px;
  line-height: 45px; }

.btn:focus,
.btn:active,
.btn.active {
  outline: none; }

.scroll-top {
  position: fixed;
  right: 2%;
  bottom: 2%;
  width: 50px;
  height: 50px;
  z-index: 1049; }
  .scroll-top .btn {
    font-size: 16px;
    width: 50px;
    height: 50px;
    border-radius: 100%;
    line-height: 28px;
    text-align: center; }
    .scroll-top .btn:focus {
      outline: none; }

.portfolio-modal .modal-dialog {
  border-radius: 0;
  background-clip: border-box;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: none;
  min-height: 100%;
  text-align: center;
  max-width: 100%;
  margin: 0;
  padding: 0; }
  .portfolio-modal .modal-dialog .modal-content {
    padding: 100px 0;
    border-radius: 0;
    border: 0; }
    .portfolio-modal .modal-dialog .modal-content h2 {
      margin: 0;
      font-size: 3em; }
    .portfolio-modal .modal-dialog .modal-content img {
      margin-bottom: 30px; }
    .portfolio-modal .modal-dialog .modal-content .item-details {
      margin: 30px 0; }

.portfolio-modal .close-modal {
  position: absolute;
  width: 75px;
  height: 75px;
  background-color: transparent;
  top: 25px;
  right: 25px;
  cursor: pointer; }
  .portfolio-modal .close-modal:hover {
    opacity: 0.3; }
  .portfolio-modal .close-modal .lr {
    height: 75px;
    width: 1px;
    margin-left: 35px;
    background-color: #2C3E50;
    transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    /* IE 9 */
    -webkit-transform: rotate(45deg);
    /* Safari and Chrome */
    z-index: 1051; }
    .portfolio-modal .close-modal .lr .rl {
      height: 75px;
      width: 1px;
      background-color: #2C3E50;
      transform: rotate(90deg);
      -ms-transform: rotate(90deg);
      /* IE 9 */
      -webkit-transform: rotate(90deg);
      /* Safari and Chrome */
      z-index: 1052; }

.portfolio-modal .modal-backdrop {
  opacity: 0;
  display: none; }

.navbar-collapse>ul>li>.dropdown-menu{

}
.nav-item.custom-dropdown{
  text-align: center;
  width: 160px;
  margin: 0 auto;
}

/*
.nav-item.dropdown-1:hover{
  color: #FFFFFF !important;
  background-color: #E37222;
}

.nav-item.dropdown-2:hover{
  color: #FFFFFF !important;
  background-color: #E37222;
}

.nav-item.dropdown-3:hover{
  color: #FFFFFF !important;
  background-color: #66B9BF;
}*/
.navbar-collapse li{
  height: 44px;
}

.dropdown-2:active{
  color: #FFFFFF;
}

.navbar-collapse>ul>li>.dropdown-menu li {
  text-align: center;
  color: white;
}

.navbar-collapse>ul>li>.dropdown-menu a {
  color: #2B2B2B !important;
}
.navbar-collapse>ul>li>.dropdown-menu .item-1{
  background-color: #F6F6F6;
}
.navbar-collapse>ul>li>.dropdown-menu .item-2{
  background-color: #EEEEEE;
}
.navbar-collapse>ul>li>.dropdown-menu .item-3{
  background-color: #F6F6F6;
}
.navbar-collapse>ul>li>.dropdown-menu .item-4{
  background-color: #EEEEEE;
}

.navbar-collapse>ul>li>.dropdown-menu {
  border-radius: 0;
  border: 0;
  margin: 0;
  padding: 0;
}

.img-glass {
width: 256px;
}
.section-header {
  display : inline-flex;
  align-items : center;
  height: 48px;
  margin-bottom:100px;
}

.section-text{
  font-family: "Montserrat", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-weight: 500;
  font-size: 2.0em;
  margin-bottom: 50px;
}

.img-line {
  display: inline-flex;
  height: 0.10em;
  margin-bottom: 3px;
  margin-left: 5px;
  margin-right: 5px;
}

#mainNav .navbar-nav {
  position:relative;
}

#website {
  background-color: #F6F6F6;
}
#graphic {
  background-color: #EEEEEE;
}
#photo {
  background-color: #F6F6F6;
}
#video {
  background-color: #EEEEEE;
}

.linkable a:hover{
  text-decoration: none;
}

ul.nonStatic-dropdown-menu {
  position: absolute !important;
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import MemoryGame from './MemoryGame';

ReactDOM.render(<MemoryGame />, document.getElementById('root'));


text:
namespace nuPickers.Shared.LuceneDataSource
{
    using System.Collections.Generic;
    using System.Linq;
    using Umbraco.Web.Editors;
    using Umbraco.Web.Mvc;
    using UmbracoExamine;

    [PluginController("nuPickers")]
    public class LuceneDataSourceApiController : UmbracoAuthorizedJsonController
    {
        public IEnumerable<object> GetExamineSearchers()
        {
            return Examine.ExamineManager.Instance.SearchProviderCollection.OfType<UmbracoExamineSearcher>().Select(x => x.Name);
        }
    }
}


text:
using FluentAssertions;
using System;
using Xunit;

namespace FluentUri.Test
{
    public class Fragment
    {
        [Fact]
        public void FragmentCannotBeNull()
        {
            FluentUriBuilder.Create()
                .Invoking(b => b.Fragment(null))
                .ShouldThrow<ArgumentNullException>();
        }

        [Fact]
        public void FragmentIsUsedIfSpecified()
        {
            var fragment = "fragment";
            var exampleUriWithoutFragment =
                "http://user:password@example.com:888/path/to?somekey=some%2bvalue&otherkey=some%2bvalue";

            FluentUriBuilder.From(exampleUriWithoutFragment)
                .Fragment(fragment)
                .ToUri()
                .Fragment
                .Should().Be("#" + fragment);
        }

        [Fact]
        public void ExistingFragmentIsUpdated()
        {
            var fragment = "test";

            FluentUriBuilder.From(TestData.Uri)
                .Fragment(fragment)
                .ToUri()
                .Fragment
                .Should().Be("#" + fragment);
        }

        [Fact]
        public void ExistingFragmentIsDeletedIfEmptyFragmentSpecified()
        {
            FluentUriBuilder.From(TestData.Uri)
                .Fragment(string.Empty)
                .ToUri()
                .Fragment
                .Should().Be(string.Empty);
        }

        [Fact]
        public void ExistingFragmentIsDeletedIfRemoveFragmentIsCalled()
        {
            FluentUriBuilder.From(TestData.Uri)
                .RemoveFragment()
                .ToUri()
                .Fragment
                .Should().Be(string.Empty);
        }
    }
}


text:
DigiLib
=======

Cloud Based Digital Library


text:
import { AsyncStorage } from 'react-native';
import RNFetchBlob from 'rn-fetch-blob';

const SHA1 = require('crypto-js/sha1');

/**
 * Primary class responsible with all operations required to communicate with Offline Store!
 *
 */
class OfflineImageStore {

  // TODOs
  // A component should only subscribe only once
  // Check necessities of using async functions instead of normal ones

  constructor(name, storeImageTimeout) {
    if (!OfflineImageStore.instance) {
      OfflineImageStore.instance = this;
      this.entries = {};

      this.store = {
        name,// Application should set their own application store name.
        // Offline Image removed after given time in seconds.
        // Default: 3 days
        storeImageTimeout,
        debugMode: false,
      };
      // If it is `true` then we will remove expired images after given `storeImageTimeout`
      this.handlers = {};

      this.restore = this.restore.bind(this);
    }

    return OfflineImageStore.instance;
  }

  /**
   * Gives the Offline store cache base directory
   */
  getBaseDir = () => {
    return RNFetchBlob.fs.dirs.CacheDir + '/' + this.store.name;
  };

  /**
   * This would be the method to be called on app start so that you could prepare application offline
   * image dictionary with existing image uris and its local store path.
   *
   * Pass onCompletion callback function to get the restore completion state.
   */
  async restore (config, onRestoreCompletion) {
    if (config.name === undefined || config.name.length === 0) {
      throw 'Offline image store name is missing';
    }

    this.store.name = config.name;

    if (config.imageRemoveTimeout) {
      this.store.storeImageTimeout = config.imageRemoveTimeout;
    }

    if (config.debugMode === true) {
      this.store.debugMode = true;
    }

    // Restore existing entries:
    AsyncStorage.getItem(`@${this.store.name}:uris`, (err, uris) => { // On `getItems` completion

      if (this.store.debugMode) {
        console.log('Restored offline images entry dictionary');
      }
      // Assign uris to entry list cache(`this.entries`)
      Object.assign(this.entries, JSON.parse(uris));

      // Remove Expired images from offline store and then call user given callback completion method !
      this._removeExpiredImages(onRestoreCompletion);
    });

  };

  /**
   * Removes all the images in the offline store.
   */
  clearStore = (onRestoreCompletion) => {

    // Check if the folder exists
    return RNFetchBlob.fs.exists(this.getBaseDir())
      .then((exists) => {
        // If folder does not exists, no need to unlink it
        if (!exists) {
          return;
        }
        // Remove from offline store
        return RNFetchBlob.fs.unlink(this.getBaseDir())
      })
      .then(() => { // On completion
        if (this.store.debugMode) {
          console.log('Removed offline image store completely!');
        }
        // Empty all entries so that we should update offline Async storage
        Object.keys(this.entries).forEach(key => delete this.entries[key]);

        // Update offline Async storage
        this._updateAsyncStorage(onRestoreCompletion);
        return null;
      })
      .catch((err) => {
        if (this.store.debugMode) {
          console.log('unable to remove offline store', err);
        }

        // Call callback with the error
        onRestoreCompletion(err);
      });
  };

  /**
   * This method expects one or more list of image uris as a array to preload them.
   * This is very useful specially if your application want to support offline.
   * Note: We recommend call this method after `restore`
   */
  preLoad = async (uris) => {
    if (uris === undefined && !Array.isArray(uris)) {
      throw 'uris should not be undefined and should be array type';
    }
    uris.forEach((uri) => {
      // If image not exist already, then download
      if (!this.entries[uri]) {
        this._downloadImage({ 'uri': uri });
        return;
      }

      // Exists but Base Dir changed , may be due to update new app version or whatever
      if (this.entries[uri]) {
        const entry = this.entries[uri];
        // Only exist if base directory matches
        if (entry.basePath !== this.getBaseDir()) {
          this._downloadImage({ 'uri': uri });
        }
      }
    });
  };

  subscribe = async (source, handler, reloadImage) => {
    const { uri } = source;

    if (!this.handlers[uri]) {
      this.handlers[uri] = [handler];
    } else {
      this.handlers[uri].push(handler);
    }

    // Get the image if already exist else download and notify!
    this._getImage(source, reloadImage);
  };

  // Un subscribe all the handlers for the given source uri
  unsubscribe = async (source) => {
    const { uri } = source;

    if (this.handlers[uri]) {
      delete this.handlers[uri];
    }
  };

  /**
   * Check whether given uri already exist in our offline cache!
   * @param uri uri to check in offline cache list
   */
  isImageExistOffline = (uri) => {
    return this.entries[uri] !== undefined;
  };

  _getExpiredImages = () => {
    const toBeRemovedImages = [];
    const uriList = Object.keys(this.entries);
    uriList.forEach((uri) => {
      const createdPlusDaysDate = this._addTime(this.entries[uri].createdOn, this.store.storeImageTimeout);
      // Image created date + EXPIRED_AFTER_DAYS is < current Date, then remove the image
      if (createdPlusDaysDate < new Date()) {
        toBeRemovedImages.push(uri);
      }
    });

    return toBeRemovedImages;
  };

  /**
   * Removes the downloaded offline images which are greater then given 'storeImageTimeout' in the config.
   */
  _removeExpiredImages = (onRestoreCompletion) => {
    const toBeRemovedImagePromises = [];
    const uriListToRemove = this._getExpiredImages();
    if (this.store.debugMode) {
      console.log('uris to remove from offline store', uriListToRemove);
    }
    uriListToRemove.forEach((uri) => {
      // Remove image from cache
      const unlinkPromise = RNFetchBlob.fs.unlink(this.entries[uri].basePath + '/' + this.entries[uri].localUriPath)
        .then(() => {
          // Delete entry from cache so that we should remove from offline Async storage
          delete this.entries[uri];
        })
        .catch((err) => {
          if (this.store.debugMode) {
            console.log('unable to remove image', uri, err);
          }
        });
      toBeRemovedImagePromises.push(unlinkPromise);
    });

    if (toBeRemovedImagePromises.length > 0) {
      if (this.store.debugMode) {
        console.log('Found images to remove:');
      }
      Promise.all(toBeRemovedImagePromises)
        .then((results) => {
          if (this.store.debugMode) {
            console.log('removeExpiredImages completed callback');
          }

          // Update AsyncStorage with removed entries
          this._updateAsyncStorage(onRestoreCompletion);
          return null;
        })
        .catch((err) => {
          if (this.store.debugMode) {
              console.log('removeExpiredImages error');
          }
          onRestoreCompletion(err);
        });
    } else { // Nothing to remove so just trigger callback!
      if (this.store.debugMode) {
        console.log('No images to remove:');
      }
      onRestoreCompletion();
    }
  };

  /**
   * Update AsyncStorage with entries cache and trigger callback.
   */
  _updateAsyncStorage = (onRestoreCompletionCallback) => {
    AsyncStorage.setItem(`@${this.store.name}:uris`, JSON.stringify(this.entries), (err) => {
      if (onRestoreCompletionCallback) {
        err ? onRestoreCompletionCallback(err) : onRestoreCompletionCallback();
      }
    });
  };

  getImageOfflinePath = (uri) => {
    if (this.entries[uri]) {
      const entry = this.entries[uri];
      // Only exist if base directory matches
      if (entry.basePath === this.getBaseDir()) {
        if (this.store.debugMode) {
          console.log('Image exist offline', this.entries[uri].localUriPath);
        }
        return this.entries[uri].basePath + '/' + this.entries[uri].localUriPath;
      }
    }
    if (this.store.debugMode) {
      console.log('Image not exist offline', uri);
    }
    return undefined;
  };

  _getImage = (source, reloadImage) => {
    // Image already exist
    if (this.entries[source.uri]) {
      const entry = this.entries[source.uri];
      // Only exist if base directory matches
      if (entry.basePath === this.getBaseDir()) {
        if (this.store.debugMode) {
          console.log('Image exist offline', source.uri);
        }
        // Notify subscribed handler
        this._notify(source.uri);

        // Reload image:
        // Update existing image in offline store as server side image could have updated!
        if (reloadImage) {
          if (this.store.debugMode) {
            console.log('reloadImage is set to true for uri:', source.uri);
          }
          this._downloadImage(source);
        }
      } else {
        this._downloadImage(source);
      }
      return;
    }

    if (this.store.debugMode) {
      console.log('Image not exist offline', source.uri);
    }
    this._downloadImage(source);
  };

  _downloadImage = (source) => {
    if (!source.uri) return
    const method = source.method ? source.method : 'GET';
    const imageFilePath = this._getImageFileName(source.uri);
    if (!imageFilePath) return
    RNFetchBlob
      .config({
        path: this.getBaseDir() + '/' + imageFilePath
      })
      .fetch(method, source.uri, source.headers)
      .then(() => {
        // Add entry to entry list!!
        this._addEntry(source.uri, imageFilePath);
        // Notify subscribed handler AND Persist entries to AsyncStorage for offline
        this._updateOfflineStore(source.uri).done();
        return null;
      }).catch(() => {
      if (this.store.debugMode) {
        console.log('Failed to download image', source.uri);
      }
    });
  };

  _notify = (uri) => {
    const handlers = this.handlers[uri];
    if (handlers && handlers.length > 0) {
      handlers.forEach(handler => {
        if (this.store.debugMode) {
          console.log('Notify handler called', uri);
        }
        handler(uri, this.entries[uri].basePath + '/' + this.entries[uri].localUriPath);
      });
    }
  };

  _getImageFileName = (uri) => {
    if (!uri || !uri.substring) return
    let path = uri.substring(uri.lastIndexOf('/'));
    path = path.indexOf('?') === -1 ? path : path.substring(path.lastIndexOf('.'), path.indexOf('?'));
    const imageExtension = path.indexOf('.') === -1 ? '.jpg' : path.substring(path.indexOf('.'));

    const localFilePath = SHA1(uri) + imageExtension;
    //console.log('getImageFilePath: ', localFilePath);

    return localFilePath;
  };

  _addEntry = (uri, imageFilePath) => {
    // Save Downloaded date when image downloads for first time
    if (this.entries[uri] === undefined) {
      this.entries[uri] = {
        createdOn: new Date().toString(),
        basePath: this.getBaseDir(),
        localUriPath: imageFilePath,
      };
    } else {
      const imageUri = this.entries[uri];
      this.entries[uri] = {
        ...imageUri,
        basePath: this.getBaseDir(),
        localUriPath: imageFilePath,
      };
    }
  };

  _updateOfflineStore = async (uri) => {
    try {
      await AsyncStorage.setItem(`@${this.store.name}:uris`, JSON.stringify(this.entries));
      // Notify subscribed handler
      this._notify(uri);
    } catch (error) {
      if (this.store.debugMode) {
        // Error saving data
        console.log(' Offline image entry update failed', error);
      }
    }
  };

  _addTime = (date, seconds) => {
    var result = new Date(date);
    result.setSeconds(result.getSeconds() + seconds);
    return result;
  };
}

const instance = new OfflineImageStore('RN_Default_ImageStore', 259200);

Object.freeze(instance);

export default instance;


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

<container xmlns="http://symfony.com/schema/dic/services"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>

        <service id="vich_uploader.file_injector" class="Vich\UploaderBundle\Injector\FileInjector">
            <argument type="service" id="vich_uploader.property_mapping_factory" />
        </service>

    </services>

</container>


text:
Copyright (C) 2013-2018 Draios Inc dba Sysdig.

This file is part of sysdig.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

--]]

view_info =
{
	id = "kubernetes_namespaces",
	name = "K8s Namespaces",
	description = "List all Kubernetes namespaces running on this machine, and the resources that each of them uses.",
	tips = {"Select a namespace and click enter to drill down into it. At that point, you will be able to access several views that will show you the details of the selected namespace."},
	view_type = "table",
	applies_to = {"", "evt.res", "k8s.pod.id", "k8s.rc.id", "k8s.rs.id", "k8s.svc.id"},
	filter = "k8s.ns.id != ''",
	use_defaults = true,
	drilldown_target = "kubernetes_pods",
	columns =
	{
		{
			name = "NA",
			field = "thread.tid",
			is_key = true
		},
		{
			name = "CPU",
			field = "thread.cpu",
			description = "Amount of CPU used by the namespace.",
			colsize = 8,
			aggregation = "AVG",
			groupby_aggregation = "SUM",
			is_sorting = true
		},
		{
			name = "VIRT",
			field = "thread.vmsize.b",
			description = "Total virtual memory for the namespace.",
			aggregation = "MAX",
			groupby_aggregation = "SUM",
			colsize = 9
		},
		{
			name = "RES",
			field = "thread.vmrss.b",
			description = "Resident non-swapped memory for the namespace.",
			aggregation = "MAX",
			groupby_aggregation = "SUM",
			colsize = 9
		},
		{
			name = "FILE",
			field = "evt.buflen.file",
			description = "Total (input+output) file I/O bandwidth generated by the namespace, in bytes per second.",
			colsize = 8,
			aggregation = "TIME_AVG",
			groupby_aggregation = "SUM"
		},
		{
			name = "NET",
			field = "evt.buflen.net",
			description = "Total (input+output) network bandwidth generated by the namespace, in bytes per second.",
			colsize = 8,
			aggregation = "TIME_AVG",
			groupby_aggregation = "SUM"
		},
		{
			name = "NA",
			field = "k8s.ns.id",
			is_groupby_key = true
		},
		{
			name = "ID",
			field = "k8s.ns.id",
			description = "Namespace id.",
			colsize = 38
		},
		{
			name = "NAME",
			field = "k8s.ns.name",
			description = "Namespace name.",
			colsize = 25
		},
		{
			name = "LABELS",
			field = "k8s.ns.labels",
			description = "Namespace labels.",
			colsize = 0
		},
	},
	actions =
	{
		{
			hotkey = "d",
			command = "kubectl --namespace=%k8s.ns.name describe namespaces %k8s.ns.name",
			description = "describe"
		},
		{
			hotkey = "x",
			command = "kubectl --namespace=%k8s.ns.name delete namespaces %k8s.ns.name",
			description = "delete"
		}
	}
}


text:
<!DOCTYPE html>

	<meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Login</title>

	<link rel="stylesheet" type= "text/css" href = "<?php echo base_url(); ?>css/theme.css">

    <link href="<?php echo base_url(); ?>dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="<?php echo base_url(); ?>dist/css/bootstrap-theme.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">

Login

			<form id="loginForm">

						    Username
						    <input type="text" class="form-control" id="username" name="username" placeholder="Username">

						    Password
						    <input type="password" class="form-control" id="password" name="password" placeholder="Password">

						<button type="button" class = "btn btn-default btn-lg" onclick="formFunction()">Login</button>

			</form>


text:
/*
//
//  Purpose:
//     Cryptography Primitive.
//     Initialization of AES
//
//  Contents:
//        ippsAESSetKey()
//
*/

#include "owndefs.h"
#include "owncp.h"
#include "pcpaesm.h"
#include "pcprij128safe.h"
#include "pcptool.h"

/*F*
//    Name: ippsAESSetKey
//
// Purpose: Set/reset new secret key for future usage.
//
// Returns:                Reason:
//    ippStsNullPtrErr        pCtx == NULL
//    ippStsLengthErr         keyLen != 16
//                            keyLen != 24
//                            keyLen != 32
//    ippStsContextMatchErr   !VALID_AES_ID()
//    ippStsNoErr             no errors
//
// Parameters:
//    pKey        security key
//    keyLen      length of the secret key (in bytes)
//    pCtx        pointer to AES initialized context
//
// Note:
//    if pKey==NULL, then zero value key being setup
//
*F*/
IPPFUN(IppStatus, ippsAESSetKey,(const Ipp8u* pKey, int keyLen, IppsAESSpec* pCtx))
{
   /* test pointers */
   IPP_BAD_PTR1_RET(pCtx);

   /* test the context ID */
   IPP_BADARG_RET(!VALID_AES_ID(pCtx), ippStsContextMatchErr);

   /* make sure in legal keyLen */
   IPP_BADARG_RET(keyLen!=16 && keyLen!=24 && keyLen!=32, ippStsLengthErr);

   return ippsAESInit(pKey, keyLen, pCtx, sizeof(IppsAESSpec));
}


text:
package main

import (
	"flag"
	"fmt"
	"net/http"

	"github.com/prometheus/client_golang/prometheus/promhttp"
	log "github.com/sirupsen/logrus"
	"github.com/superfly/wormhole"
	"github.com/superfly/wormhole/config"
)

func main() {
	serverMode := flag.Bool("server", false, "Run the wormhole in server mode.")
	versionFlag := flag.Bool("version", false, "Display wormhole version.")
	helpFlag := flag.Bool("help", false, "Show help")
	flag.BoolVar(helpFlag, "h", false, "Show help")
	flag.Parse()

	if *helpFlag {
		fmt.Printf(
			`Wormhole v%s

Usage
=====

  - First, set the required environment variables. (details below)
  - Second, choose a mode to run. (more details below)

    (supervisor)
    wormhole path/to/executable

    (sidecar)
    wormhole

Environment Variables
=====================

  (required)
    FLY_TOKEN: Token for your backend, found on your fly.io backend's page

  (optional)
    FLY_LOCAL_ENDPOINT: Local server to tunnel for. (defaults to "127.0.0.1:5000")
      or
    FLY_PORT: Local port to tunnel. (defaults to 5000)

    FLY_REMOTE_ENDPOINT: Wormhole server instance. Defaults to Fly.io's servers.
    FLY_RELEASE_ID_VAR: ENV var with current released version of your web server (inferred from git if available)
    FLY_RELEASE_DESC_VAR: ENV name with commit message of the current released version of your web server (inferred from git if available)

Modes
=====

  Supervisor (preferred)
  ----------

    Wormhole will start your application (the specified executable) and supervise the process.

    Examples:

      export FLY_TOKEN=x # Always set this.

      # Rails, setting a port
      export FLY_PORT=3000 # Defaults to: 5000
      wormhole bundle exec rails server -p 3000

      # Go, setting a full endpoint
      export FLY_LOCAL_ENDPOINT=127.0.0.1:3000 # Defaults to: 127.0.0.1:5000
      wormhole path/to/app

  Sidecar
  -------

    Wormhole assumes your server is already running.
    You need to set the proper environment variables.

    Examples:

      export FLY_TOKEN=x # Always set this.

      # Setting a port
      export FLY_PORT=3000 # Defaults to: 5000
      wormhole

      # Setting a full endpoint
      export FLY_LOCAL_ENDPOINT=127.0.0.1:3000 # Defaults to: 127.0.0.1:5000
      wormhole

Other commands
==============

  -v, --version: Prints the version for wormhole.
  -h, --help:    Prints this help information.
      --server:  Starts wormhole in server mode. You probably don't want this.

`, config.Version())
		return
	}

	if *versionFlag {
		fmt.Printf("wormhole %s\n", config.Version())
		return
	}

	if *serverMode {
		config, err := config.NewServerConfig()
		if err != nil {
			log.Fatalf("config error: %s", err.Error())
		}

		// Expose the registered metrics via HTTP.
		go func() {
			http.Handle("/metrics", promhttp.Handler())
			config.Logger.Fatal(http.ListenAndServe(":"+config.MetricsAPIPort, nil))
		}()

		wormhole.StartRemote(config)
	} else {
		config, err := config.NewClientConfig()
		if err != nil {
			log.Fatalf("config error: %s", err.Error())
		}
		wormhole.StartLocal(config)
	}
}


text:
/** @author John Hann */

var buster = require('buster');
var assert = buster.assert;
var refute = buster.refute;
var fail = buster.referee.fail;

var raveExtension = require('../rave');

// TODO: use gent.js to generate better plugin-based module names

buster.testCase('rave-amd-plugins', {

	'create': {

		'should return an object with a pipeline function': function () {
			var extension = raveExtension.create({});
			assert.isFunction(extension.pipeline);
		},

		'// should test more things': function () {

		}

	},

	'createNormalize': {

		'should create a function': function () {
			var normalize = raveExtension.createNormalize();
			assert.isFunction(normalize);
		},

		'// should test more things': function () {

		}

	},

	'locate': {

		'should return name property': function () {
			var name = raveExtension.locate({ name: 'foo' });
			assert.same(name, 'foo');
		}

	},

	'fetch': {

		'should be a noop': function () {
			var nada = raveExtension.fetch();
			assert.same(nada, void 0);
		}

	},

	'translate': {

		'should return source property': function () {
			var source = raveExtension.locate({ source: 'foo' });
			assert.same(source, 'foo');
		}

	},

	'createInstantiate': {

		'// should be tested': function () {}

	},

	'parsePluginName': {

		'should split plugin name from module name': function () {
			var parsed = raveExtension.parsePluginName('foo!bar');
			assert.equals('foo', parsed.plugin);
			assert.equals('bar', parsed.resource);
		},

		'should return module name if not using plugin syntax': function () {
			var parsed = raveExtension.parsePluginName('bar');
			assert.equals('bar', parsed.resource);
			assert.equals(undefined, parsed.plugin);
		}

	},

	'createPluginRequire': {

		'// should be tested': function () {}

	},

	'createPluginMapper': {

		'// should be tested': function () {}

	},

	'createFactory': {

		'// should be tested': function () {}

	},

	'createPluginPredicate': {

		'// should detect plugin syntax in a string': function () {
			assert(raveExtension.pluginFilter('foo!bar'));
			assert(raveExtension.pluginFilter('blah@foo#0.8.1!bar'));
			assert(raveExtension.pluginFilter('foo!blah@bar#0.8.1'));
		},

		'// should not falsely detect a plugin syntax in non-plugin id string': function () {
			assert(raveExtension.pluginFilter('foo/bar'));
			assert(raveExtension.pluginFilter('blah@foo#0.8.1/bar'));
			assert(raveExtension.pluginFilter('foo/blah@bar#0.8.1'));
		},

		'// should detect plugin syntax in a load object': function () {
			assert(raveExtension.pluginFilter({ name: 'foo!bar' }));
			assert(raveExtension.pluginFilter({ name: 'blah@foo#0.8.1!bar' }));
			assert(raveExtension.pluginFilter({ name: 'foo!blah@bar#0.8.1' }));
		},

		'// should not falsely detect a plugin syntax in non-plugin load object': function () {
			assert(raveExtension.pluginFilter({ name: 'foo/bar' }));
			assert(raveExtension.pluginFilter({ name: 'blah@foo#0.8.1/bar' }));
			assert(raveExtension.pluginFilter({ name: 'foo/blah@bar#0.8.1' }));
		}

	}

});


text:
package pl.grzeslowski.jsupla.protocoljava.api.entities.sdc;

import pl.grzeslowski.jsupla.protocoljava.api.types.FromServerEntity;
import pl.grzeslowski.jsupla.protocoljava.api.types.ToClientEntity;
import pl.grzeslowski.jsupla.protocoljava.api.types.ToDeviceEntity;

public interface ServerDeviceClientEntity extends FromServerEntity, ToDeviceEntity, ToClientEntity {
}


text:
package com.factoring.web.service.common;

import java.util.List;
import java.util.Map;

import com.factoring.core.generic.GenericService;
import com.factoring.web.model.Role;
import com.factoring.web.model.User;

/**
 * 角色 业务接口
 *
 * @author
 *
 **/
public interface RoleService extends GenericService<Role, String> {

	/**
     * 插入
     * @param record
     * @return
     */
    int insertSelective(Role role);

    /**
     * 通过用户id 查询用户 拥有的角色
     *
     * @param userId
     * @return
     */
    List<Role> selectRolesByUserId(String userId);

    /**
     * 查询所有的Role
     * @return
     */
    List<Role> selectAllRole();

    /**
     * 更新
     * @param record
     * @return
     */
    int updateByPrimaryKeySelective(Role record);

    /**
     * 删除
     * @param record
     * @return
     */
    int deleteByPrimaryKey(String id);

    /**
     *
     * @param record
     * @return
     */
    Role selectByPrimaryKey(String id);

    //插入role_permission表
    int insertPermissionsByRoleId(List<Map> listdata);

    //获取所有角色权限
    List<Map> selectAllRolePermission();

  //根据roleid删除权限
    int deletePermissionByRoleId(String id);
}