text:
import click

from globus_cli.login_manager import LoginManager
from globus_cli.parsing import command, endpoint_id_arg, security_principal_opts
from globus_cli.termio import display

@command(
    "create",
    short_help="Add a role to an endpoint",
    adoc_output=(
        "Textual output is a simple success message in the absence of errors, "
        "containing the ID of the created role."
    ),
    adoc_examples="""Grant 'demo@globus.org' the 'activity_monitor' role on
'ddb59aef-6d04-11e5-ba46-22000b92c6ec':

[source,bash]
----
$ globus endpoint role create 'ddb59aef-6d04-11e5-ba46-22000b92c6ec' \
    --identity 'demo@globus.org' --role activity_monitor
----
""",
)
@endpoint_id_arg
@security_principal_opts(allow_provision=True)
@click.option(
    "--role",
    required=True,
    type=click.Choice(
        ("administrator", "access_manager", "activity_manager", "activity_monitor"),
        case_sensitive=False,
    ),
    help="A role to assign.",
)
@LoginManager.requires_login(LoginManager.AUTH_RS, LoginManager.TRANSFER_RS)
def role_create(*, login_manager: LoginManager, role, principal, endpoint_id):
    """
    Create a role on an endpoint.
    You must have sufficient privileges to modify the roles on the endpoint.

    Either *--group* or *--identity* is required. You may not pass both.
    Which one of these options you use will determine the 'Principal Type' on the
    role, and the value given will be the 'Principal' of the resulting role.
    The term "Principal" is used in the sense of "a security principal", an entity
    which has some privileges associated with it.
    """
    from globus_cli.services.transfer import assemble_generic_doc

    principal_type, principal_val = principal

    transfer_client = login_manager.get_transfer_client()
    auth_client = login_manager.get_auth_client()

    if principal_type == "identity":
        principal_val = auth_client.maybe_lookup_identity_id(principal_val)
        if not principal_val:
            raise click.UsageError(
                "Identity does not exist. "
                "Use --provision-identity to auto-provision an identity."
            )
    elif principal_type == "provision-identity":
        principal_val = auth_client.maybe_lookup_identity_id(
            principal_val, provision=True
        )
        principal_type = "identity"

    role_doc = assemble_generic_doc(
        "role", principal_type=principal_type, principal=principal_val, role=role
    )

    res = transfer_client.add_endpoint_role(endpoint_id, role_doc)
    display(res, simple_text="ID: {}".format(res["id"]))


text:
package org.elasticsearch.xpack.ccr.action;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.master.AcknowledgedResponse;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;

final class ResponseHandler {

    private final AtomicInteger counter;
    private final AtomicReferenceArray<Object> responses;
    private final ActionListener<AcknowledgedResponse> listener;

    ResponseHandler(int numRequests, ActionListener<AcknowledgedResponse> listener) {
        this.counter = new AtomicInteger(numRequests);
        this.responses = new AtomicReferenceArray<>(numRequests);
        this.listener = listener;
    }

    <T> ActionListener<T> getActionListener(final int requestId) {
        return new ActionListener<T>() {

            @Override
            public void onResponse(T response) {
                responses.set(requestId, response);
                finalizeResponse();
            }

            @Override
            public void onFailure(Exception e) {
                responses.set(requestId, e);
                finalizeResponse();
            }
        };
    }

    private void finalizeResponse() {
        Exception error = null;
        if (counter.decrementAndGet() == 0) {
            for (int j = 0; j < responses.length(); j++) {
                Object response = responses.get(j);
                if (response instanceof Exception) {
                    if (error == null) {
                        error = (Exception) response;
                    } else {
                        error.addSuppressed((Exception) response);
                    }
                }
            }

            if (error == null) {
                listener.onResponse(AcknowledgedResponse.TRUE);
            } else {
                listener.onFailure(error);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.twitter.finagle.memcachedx.protocol.text.client

import org.jboss.netty.buffer.ChannelBuffer
import org.jboss.netty.channel._

import com.twitter.finagle.memcachedx.util.ChannelBufferUtils._
import com.twitter.finagle.memcachedx.protocol.ServerError
import com.twitter.finagle.memcachedx.util.ParserUtils
import com.twitter.finagle.memcachedx.protocol.text._
import com.twitter.finagle.netty3.ChannelBufferBuf
import com.twitter.util.StateMachine

object Decoder {
  private val END   = "END": ChannelBuffer
  private val ITEM  = "ITEM": ChannelBuffer
  private val STAT  = "STAT": ChannelBuffer
  private val VALUE = "VALUE": ChannelBuffer
}

class Decoder extends AbstractDecoder with StateMachine {
  import Decoder._

  case class AwaitingResponse()                                                  extends State
  case class AwaitingResponseOrEnd(valuesSoFar: Seq[TokensWithData])             extends State
  case class AwaitingStatsOrEnd(valuesSoFar: Seq[Tokens])                        extends State
  case class AwaitingData(valuesSoFar: Seq[TokensWithData], tokens: Seq[ChannelBuffer], bytesNeeded: Int) extends State

  final protected[memcachedx] def start() {
    state = AwaitingResponse()
  }

  def decode(ctx: ChannelHandlerContext, channel: Channel, buffer: ChannelBuffer): Decoding = {
    state match {
      case AwaitingResponse() =>
        decodeLine(buffer, needsData(_)) { tokens =>
          if (isEnd(tokens)) {
            ValueLines(Seq[TokensWithData]())
          } else if (isStats(tokens)) {
            awaitStatsOrEnd(Seq(Tokens(tokens.map { ChannelBufferBuf(_) } )))
            needMoreData
          } else {
            Tokens(tokens.map { ChannelBufferBuf(_) })
          }
        }
      case AwaitingStatsOrEnd(linesSoFar) =>
        decodeLine(buffer, needsData(_)) { tokens =>
          if (isEnd(tokens)) {
            StatLines(linesSoFar)
          } else if (isStats(tokens)) {
            awaitStatsOrEnd(linesSoFar ++ Seq(Tokens(tokens.map { ChannelBufferBuf(_) })))
            needMoreData
          } else {
            throw new ServerError("Invalid reply from STATS command")
          }
        }
      case AwaitingData(valuesSoFar, tokens, bytesNeeded) =>
        decodeData(bytesNeeded, buffer) { data =>
          awaitResponseOrEnd(
            valuesSoFar ++
            Seq(TokensWithData(tokens.map { ChannelBufferBuf(_) }, ChannelBufferBuf(data))))
          needMoreData
        }
      case AwaitingResponseOrEnd(valuesSoFar) =>
        decodeLine(buffer, needsData(_)) { tokens =>
          if (isEnd(tokens)) {
            ValueLines(valuesSoFar)
          } else needMoreData
        }
    }
  }

  final protected[memcachedx] def awaitData(tokens: Seq[ChannelBuffer], bytesNeeded: Int) = {
    state match {
      case AwaitingResponse() =>
        awaitData(Nil, tokens, bytesNeeded)
      case AwaitingResponseOrEnd(valuesSoFar) =>
        awaitData(valuesSoFar, tokens, bytesNeeded)
    }
  }

  private[this] def awaitData(valuesSoFar: Seq[TokensWithData], tokens: Seq[ChannelBuffer], bytesNeeded: Int) {
    state = AwaitingData(valuesSoFar, tokens, bytesNeeded)
  }

  private[this] def awaitResponseOrEnd(valuesSoFar: Seq[TokensWithData]) {
    state = AwaitingResponseOrEnd(valuesSoFar)
  }

  private[this] def awaitStatsOrEnd(valuesSoFar: Seq[Tokens]) {
    state = AwaitingStatsOrEnd(valuesSoFar)
  }

  private[this] val needMoreData = null: Decoding

  private[this] def isEnd(tokens: Seq[ChannelBuffer]) =
    (tokens.length == 1 && tokens.head == END)

  private[this] def isStats(tokens: Seq[ChannelBuffer]) =
    (tokens.length > 0 && (tokens.head == STAT || tokens.head == ITEM))

  private[this] def needsData(tokens: Seq[ChannelBuffer]) = {
    val responseName = tokens.head
    if (responseName == VALUE) {
      validateValueResponse(tokens)
      Some(tokens(3).toInt)
    } else None
  }

  private[this] def validateValueResponse(args: Seq[ChannelBuffer]) {
    if (args.length < 4) throw new ServerError("Too few arguments")
    if (args.length > 5) throw new ServerError("Too many arguments")
    if (args.length == 5 && !ParserUtils.isDigits(args(4))) throw new ServerError("CAS must be a number")
    if (!ParserUtils.isDigits(args(3))) throw new ServerError("Bytes must be number")
  }
}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<title>Thread Management</title>
<title>CMSIS-RTOS: Thread Management</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="cmsis.css" rel="stylesheet" type="text/css" />

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="stylsheetf" rel="stylesheet" type="text/css" />

CMSIS-RTOS
    Version 1.02

CMSIS-RTOS API: Generic RTOS interface for Cortex-M processor-based devices.

Main Page

Usage and Description

Reference

Macros |
Enumerations |
Functions

Thread Management

CMSIS-RTOS API

Define, create, and control thread functions.
More...

Macros

#define 	osThreadDef(name, priority, instances, stacksz)

 	Create a Thread Definition with function, priority, and stack requirements.

#define 	osThread(name)   &os_thread_def_##name

 	Access a Thread definition.

Enumerations

enum  	osPriority {

  osPriorityIdle = -3,

  osPriorityLow = -2,

  osPriorityBelowNormal = -1,

  osPriorityNormal = 0,

  osPriorityAboveNormal = +1,

  osPriorityHigh = +2,

  osPriorityRealtime = +3,

  osPriorityError = 0x84

 }

Functions

osThreadId 	osThreadCreate (const osThreadDef_t *thread_def, void *argument)

 	Create a thread and add it to Active Threads and set it to state READY.

osThreadId 	osThreadGetId (void)

 	Return the thread ID of the current running thread.

osStatus 	osThreadTerminate (osThreadId thread_id)

 	Terminate execution of a thread and remove it from Active Threads.

osStatus 	osThreadSetPriority (osThreadId thread_id, osPriority priority)

 	Change priority of an active thread.

osPriority 	osThreadGetPriority (osThreadId thread_id)

 	Get current priority of an active thread.

osStatus 	osThreadYield (void)

 	Pass control to next thread that is in state READY.

Description

The Thread Management function group allows defining, creating, and controlling thread functions in the system. The function main is a special thread function that is started at system initialization and has the initial priority osPriorityNormal.

Threads can be in the following states:

RUNNING: The thread that is currently running is in the RUNNING state. Only one thread at a time can be in this state.

READY: Threads which are ready to run are in the READY state. Once the RUNNING thread has terminated or is WAITING, the next READY thread with the highest priority becomes the RUNNING thread.

WAITING: Threads that are waiting for an event to occur are in the WAITING state.

INACTIVE: Threads that are not created or terminated are in the INACTIVE state. These threads typically consume no system resources.

Thread State and State Transitions

 A CMSIS-RTOS assumes that threads are scheduled as shown in the figure Thread State and State Transitions. The thread states change as follows:

A thread is created using the function osThreadCreate. This puts the thread into the READY or RUNNING state (depending on the thread priority).

CMSIS-RTOS is pre-emptive. The active thread with the highest priority becomes the RUNNING thread provided it does not wait for any event. The initial priority of a thread is defined with the osThreadDef but may be changed during execution using the function osThreadSetPriority.

The RUNNING thread transfers into the WAITING state when it is waiting for an event.

Active threads can be terminated any time using the function osThreadTerminate. Threads can terminate also by just returning from the thread function. Threads that are terminated are in the INACTIVE state and typically do not consume any dynamic memory resources.

Macro Definition Documentation

          #define osThread
          (

          name	)
             &os_thread_def_##name

Access to the thread definition for the function osThreadCreate.

Parameters

name	name of the thread definition object.

Note

CAN BE CHANGED: The parameter to osThread shall be consistent but the macro body is implementation specific in every CMSIS-RTOS.

          #define osThreadDef
          (

          name,

          priority,

          instances,

          stacksz

          )

Define the attributes of a thread functions that can be created by the function osThreadCreate using osThread.

Parameters

name	name of the thread function.

priority	initial priority of the thread function.

instances	number of possible thread instances.

stacksz	stack size (in bytes) requirements for the thread function.

Note

CAN BE CHANGED: The parameters to osThreadDef shall be consistent but the macro body is implementation specific in every CMSIS-RTOS.

Enumeration Type Documentation

          enum osPriority

Note

MUST REMAIN UNCHANGED: osPriority shall be consistent in every CMSIS-RTOS.

The osPriority value specifies the priority for a thread. The default thread priority should be osPriorityNormal. If a Thread is active that has a higher priority than the currently executing thread, then a thread switch occurs immediately to execute the new task.

To prevent from a priority inversion, a CMSIS-RTOS complained OS may optionally implement a priority inheritance method. A priority inversion occurs when a high priority thread is waiting for a resource or event that is controlled by a thread with a lower priority.

Enumerator:

osPriorityIdle

priority: idle (lowest)

osPriorityLow

priority: low

osPriorityBelowNormal

priority: below normal

osPriorityNormal

priority: normal (default)

osPriorityAboveNormal

priority: above normal

osPriorityHigh

priority: high

osPriorityRealtime

priority: realtime (highest)

osPriorityError

system cannot determine priority or thread has illegal priority

Function Documentation

          osThreadId osThreadCreate
          (
          const osThreadDef_t *
          thread_def,

          void *
          argument

          )

Parameters

[in]	thread_def	thread definition referenced with osThread.

[in]	argument	pointer that is passed to the thread function as start argument.

Returns

thread ID for reference by other functions or NULL in case of error.

Note

MUST REMAIN UNCHANGED: osThreadCreate shall be consistent in every CMSIS-RTOS.

Start a thread function by adding it to the Active Threads list and set it to state READY. The thread function receives the argument pointer as function argument when the function is started. When the priority of the created thread function is higher than the current RUNNING thread, the created thread function starts instantly and becomes the new RUNNING thread.

Code Example

#include "cmsis_os.h"

void Thread_1 (void const *arg);                           // function prototype for Thread_1

osThreadDef (Thread_1, osPriorityNormal, 1, 0);            // define Thread_1

void ThreadCreate_example (void) {

  osThreadId id;

  id = osThreadCreate (osThread (Thread_1), NULL);         // create the thread

  if (id == NULL) {                                        // handle thread creation

    // Failed to create a thread

  }

  :

  osThreadTerminate (id);                                  // stop the thread

}

          osThreadId osThreadGetId
          (
          void
          	)

Returns

thread ID for reference by other functions or NULL in case of error.

Note

MUST REMAIN UNCHANGED: osThreadGetId shall be consistent in every CMSIS-RTOS.

Get the thread ID of the current running thread.

Code Example

void ThreadGetId_example (void)  {

  osThreadId id;                                           // id for the currently running thread

  id = osThreadGetId ();

  if (id == NULL) {

    // Failed to get the id; not in a thread

  }

}

          osPriority osThreadGetPriority
          (
          osThreadId
          thread_id	)

Parameters

[in]	thread_id	thread ID obtained by osThreadCreate or osThreadGetId.

Returns

current priority value of the thread function.

Note

MUST REMAIN UNCHANGED: osThreadGetPriority shall be consistent in every CMSIS-RTOS.

Get the priority of an active thread. In case of a failure the value osPriorityError is returned.

Code Example

#include "cmsis_os.h"

void Thread_1 (void const *arg)  {                         // Thread function

  osThreadId id;                                           // id for the currently running thread

  osPriority priority;                                     // thread priority

  id = osThreadGetId ();                                   // Obtain ID of current running thread

  if (id != NULL)  {

    priority = osThreadGetPriority (id);

  }

  else  {

    // Failed to get the id

  }

}

          osStatus osThreadSetPriority
          (
          osThreadId
          thread_id,

          osPriority
          priority

          )

Parameters

[in]	thread_id	thread ID obtained by osThreadCreate or osThreadGetId.

[in]	priority	new priority value for the thread function.

Returns

status code that indicates the execution status of the function.

Note

MUST REMAIN UNCHANGED: osThreadSetPriority shall be consistent in every CMSIS-RTOS.

Change the priority of an active thread.

Status and Error Codes

osOK: the priority of the specified thread has been successfully changed.

osErrorParameter: thread_id is incorrect.

osErrorValue: incorrect priority value.

osErrorResource: thread_id refers to a thread that is not an active thread.

osErrorISR: osThreadSetPriority cannot be called from interrupt service routines.

Code Example

#include "cmsis_os.h"

void Thread_1 (void const *arg)  {                         // Thread function

  osThreadId id;                                           // id for the currently running thread

  osPriority pr;                                           // thread priority

  osStatus   status;                                       // status of the executed function

  :

  id = osThreadGetId ();                                   // Obtain ID of current running thread

  if (id != NULL) {

    status = osThreadSetPriority (id, osPriorityBelowNormal);

    if (status == osOK)  {

      // Thread priority changed to BelowNormal

    }

    else {

      // Failed to set the priority

    }

  }

  else  {

    // Failed to get the id

  }

  :

}

          osStatus osThreadTerminate
          (
          osThreadId
          thread_id	)

Parameters

[in]	thread_id	thread ID obtained by osThreadCreate or osThreadGetId.

Returns

status code that indicates the execution status of the function.

Note

MUST REMAIN UNCHANGED: osThreadTerminate shall be consistent in every CMSIS-RTOS.

Remove the thread function from the active thread list. If the thread is currently RUNNING the execution will stop.

Note

In case that osThreadTerminate terminates the currently running task, the function never returns and other threads that are in the READY state are started.

Status and Error Codes

osOK: the specified thread has been successfully terminated.

osErrorParameter: thread_id is incorrect.

osErrorResource: thread_id refers to a thread that is not an active thread.

osErrorISR: osThreadTerminate cannot be called from interrupt service routines.

Code Example

#include "cmsis_os.h"

void Thread_1 (void const *arg);                           // function prototype for Thread_1

osThreadDef (Thread_1, osPriorityNormal, 1, 0);            // define Thread_1

void ThreadTerminate_example (void) {

  osStatus status;

  osThreadId id;

  id = osThreadCreate (osThread (Thread_1), NULL);         // create the thread

  :

  status = osThreadTerminate (id);                         // stop the thread

  if (status == osOK) {

    // Thread was terminated successfully

  }

  else {

    // Failed to terminate a thread

  }

}

          osStatus osThreadYield
          (
          void
          	)

Returns

status code that indicates the execution status of the function.

Note

MUST REMAIN UNCHANGED: osThreadYield shall be consistent in every CMSIS-RTOS.

Pass control to the next thread that is in state READY. If there is no other thread in the state READY, the current thread continues execution and no thread switching occurs.

Status and Error Codes

osOK: the function has been correctly executed.

osErrorISR: osThreadYield cannot be called from interrupt service routines.

Code Example

#include "cmsis_os.h"

void Thread_1 (void const *arg)  {                         // Thread function

  osStatus   status;                                       // status of the executed function

  :

  while (1)  {

    status = osThreadYield();                              //

    if (status != osOK)  {

      // thread switch not occurred, not in a thread function

    }

  }

}

Generated on Fri Mar 20 2015 14:58:59 for CMSIS-RTOS by ARM Ltd. All rights reserved.


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>Effect Off-Canvas Menu</title>

		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
		<link rel="stylesheet" href="css/off-canvas.css">

Effect For Offcanvas

						<form class="form-horizontal">

						    Choose Option Effect

						    	<select id="effect" class="form-control">
								  <option value="effect-1">1. Side in on Top</option>
								  <option value="effect-2">2. Reveal</option>
								  <option value="effect-3">3. Push</option>
								  <option value="effect-4">4. Slide along</option>
								  <option value="effect-5">5. Reverse slide out</option>
								  <option value="effect-6">6. Rotate pusher</option>
								  <option value="effect-7">7. 3D rotate in</option>
								  <option value="effect-8">8. 3D rotate out</option>
								  <option value="effect-9">9. Scale down pusher</option>
								  <option value="effect-10">10. Scale Up</option>
								  <option value="effect-11">11. Scale & rotate pusher</option>
								  <option value="effect-12">12. Open door</option>
								  <option value="effect-13">13. Fall down</option>
								  <option value="effect-14">14. Delayed 3D Rotate</option>
								</select>

						    	<button type="button" class="btn-effect btn btn-success">Effect Offcanvas</button>

						</form>

				<button type="button" class="btn btn-danger close-menu pull-right">x</button>

Cras justo odio

Dapibus ac facilisis in

Morbi leo risus

Porta ac consectetur ac

Vestibulum at eros


text:
import logging

from .base import BaseDownloadAdapter

logger = logging.getLogger(__name__)

class MysqldumpAdapter(BaseDownloadAdapter):

    def set_args(self, schema_name, table_name, data_only=False):
        self.args = ['mysqldump']
        if data_only:
            self.args += ['--compact', '--skip-extended-insert']

        if 'USER' in self.database_config and self.database_config['USER']:
            self.args.append('--user=%(USER)s' % self.database_config)

        if 'PASSWORD' in self.database_config and self.database_config['PASSWORD']:
            self.args.append('--password=%(PASSWORD)s' % self.database_config)

        if 'HOST' in self.database_config and self.database_config['HOST']:
            self.args.append('--host=%(HOST)s' % self.database_config)

        if 'PORT' in self.database_config and self.database_config['PORT']:
            self.args.append('--port=%(PORT)s' % self.database_config)

        self.args.append(schema_name)
        self.args.append(table_name)


text:
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <asm/types.h>
#include <linux/netlink.h>
#include <linux/socket.h>
#include <errno.h>

#define NETLINK_TEST 25
#define MAX_PAYLOAD 1024 // maximum payload size

int sock_fd;
struct sockaddr_nl src_addr, dest_addr;
struct nlmsghdr *nlh = NULL;
struct iovec iov;
struct msghdr msg;

void init_netlink()
{
    // Create a socket
    sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TEST);
    if(sock_fd == -1) {
        printf("error getting socket: %s", strerror(errno));
        return;
    }
    // To prepare binding
    memset(&msg,0,sizeof(msg));
    memset(&src_addr, 0, sizeof(src_addr));
    //src_address
    src_addr.nl_family = AF_NETLINK;
    src_addr.nl_pid = getpid(); // self pid
    src_addr.nl_groups = 0; // multi cast
    bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));

    //dest_address
    memset(&dest_addr, 0, sizeof(dest_addr));
    dest_addr.nl_family = AF_NETLINK;
    dest_addr.nl_pid = 0; /* For Linux Kernel */
    dest_addr.nl_groups = 0; /* unicast */

    /* Fill the netlink message header */
    nlh=(struct nlmsghdr *)malloc(NLMSG_SPACE(MAX_PAYLOAD));
    nlh->nlmsg_len = NLMSG_SPACE(MAX_PAYLOAD);
    nlh->nlmsg_pid = getpid(); /* self pid */
    nlh->nlmsg_flags = 0;

    /* Fill in the netlink message payload */
    strcpy(NLMSG_DATA(nlh), "connect to kernel");
    iov.iov_base = (void *)nlh;
    iov.iov_len = nlh->nlmsg_len;
    //iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);
    memset(&msg, 0, sizeof(msg));
    msg.msg_name = (void *)&dest_addr;
    msg.msg_namelen = sizeof(dest_addr);
    msg.msg_iov = &iov;
    msg.msg_iovlen = 1;
}

int main(int argc, char* argv[])
{
    int state;
    int state_smg = 0;

    init_netlink();
    printf(" Sending message. ...\n");
    state_smg = sendmsg(sock_fd,&msg,0);
    if(state_smg == -1) {
        printf("get error sendmsg = %s\n",strerror(errno));
    }

    memset(nlh,0,NLMSG_SPACE(MAX_PAYLOAD));
    printf(" Waiting message. ...\n");
    // Read message from kernel

    while(1) {
        printf("In while recvmsg\n");
        state = recvmsg(sock_fd, &msg, 0);
        if(state<0) {
            printf("state<1");
        }
        printf("In while\n");
        printf("Received message: %s\n",(char *) NLMSG_DATA(nlh));
    }

    close(sock_fd);

    return 0;
}


text:
// <file>
//     <copyright see="prj:///doc/copyright.txt"/>
//     <license see="prj:///doc/license.txt"/>
//     <owner name="David Srbecký" email="dsrbecky@gmail.com"/>
//     <version>$Revision$</version>
// </file>

using System.Reflection;

//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("IKVM.NET JDWP Debugger Library")]
[assembly: AssemblyDescription("Library for debugging .NET applications from JDWP")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyCopyright("2005-2008 David Srbecký 2016 Douglas Miles")]
[assembly: AssemblyVersion("3.0.0.0")]


text:
import urllib3.request
import urllib3.exceptions

def isServerOn(f):
    def wrapper(*args):
        cls  = args[0]
        uri = 'http://%(host)s:%(port)s/solr' % cls.__dict__
        try:
            response = urllib3.request.urlopen(uri)
            if response.getcode() == 200:
                print('Bingo')
            else:
                print('The response code was not 200, but: {}'.format(
                    response.get_code()))
        except urllib3.exceptions.HTTPError as e:
            print('''An error occurred: {}
            The response code was {}'''.format(e, e.getcode()))

    return wrapper


text:
odoo.define('web.ajax', function (require) {
"use strict";

var core = require('web.core');
var time = require('web.time');
var utils = require('web.utils');

function genericJsonRpc (fct_name, params, fct) {
    var data = {
        jsonrpc: "2.0",
        method: fct_name,
        params: params,
        id: Math.floor(Math.random() * 1000 * 1000 * 1000)
    };
    var xhr = fct(data);
    var result = xhr.pipe(function(result) {
        if (result.error !== undefined) {
            if (result.error.data.arguments[0] !== "bus.Bus not available in test mode") {
                console.error("Server application error", JSON.stringify(result.error));
            }
            return $.Deferred().reject("server", result.error);
        } else {
            return result.result;
        }
    }, function() {
        //console.error("JsonRPC communication error", _.toArray(arguments));
        var def = $.Deferred();
        return def.reject.apply(def, ["communication"].concat(_.toArray(arguments)));
    });
    // FIXME: jsonp?
    result.abort = function () { if (xhr.abort) xhr.abort(); };
    return result;
}

function jsonRpc(url, fct_name, params, settings) {
    return genericJsonRpc(fct_name, params, function(data) {
        return $.ajax(url, _.extend({}, settings, {
            url: url,
            dataType: 'json',
            type: 'POST',
            data: JSON.stringify(data, time.date_to_utc),
            contentType: 'application/json'
        }));
    });
};

function jsonpRpc(url, fct_name, params, settings) {
    settings = settings || {};
    return genericJsonRpc(fct_name, params, function(data) {
        var payload_str = JSON.stringify(data, time.date_to_utc);
        var payload_url = $.param({r:payload_str});
        var force2step = settings.force2step || false;
        delete settings.force2step;
        var session_id = settings.session_id || null;
        delete settings.session_id;
        if (payload_url.length < 2000 && ! force2step) {
            return $.ajax(url, _.extend({}, settings, {
                url: url,
                dataType: 'jsonp',
                jsonp: 'jsonp',
                type: 'GET',
                cache: false,
                data: {r: payload_str, session_id: session_id}
            }));
        } else {
            var args = {session_id: session_id, id: data.id};
            var ifid = _.uniqueId('oe_rpc_iframe');
            var html = "<iframe src='javascript:false;' name='" + ifid + "' id='" + ifid + "' style='display:none'></iframe>";
            var $iframe = $(html);
            var nurl = 'jsonp=1&' + $.param(args);
            nurl = url.indexOf("?") !== -1 ? url + "&" + nurl : url + "?" + nurl;
            var $form = $('<form>')
                        .attr('method', 'POST')
                        .attr('target', ifid)
                        .attr('enctype', "multipart/form-data")
                        .attr('action', nurl)
                        .append($('<input type="hidden" name="r" />').attr('value', payload_str))
                        .hide()
                        .appendTo($('body'));
            var cleanUp = function() {
                if ($iframe) {
                    $iframe.unbind("load").remove();
                }
                $form.remove();
            };
            var deferred = $.Deferred();
            // the first bind is fired up when the iframe is added to the DOM
            $iframe.bind('load', function() {
                // the second bind is fired up when the result of the form submission is received
                $iframe.unbind('load').bind('load', function() {
                    $.ajax({
                        url: url,
                        dataType: 'jsonp',
                        jsonp: 'jsonp',
                        type: 'GET',
                        cache: false,
                        data: {session_id: session_id, id: data.id}
                    }).always(function() {
                        cleanUp();
                    }).done(function() {
                        deferred.resolve.apply(deferred, arguments);
                    }).fail(function() {
                        deferred.reject.apply(deferred, arguments);
                    });
                });
                // now that the iframe can receive data, we fill and submit the form
                $form.submit();
            });
            // append the iframe to the DOM (will trigger the first load)
            $form.after($iframe);
            if (settings.timeout) {
                realSetTimeout(function() {
                    deferred.reject({});
                }, settings.timeout);
            }
            return deferred;
        }
    });
};

// helper
function realSetTimeout (fct, millis) {
    var finished = new Date().getTime() + millis;
    var wait = function() {
        var current = new Date().getTime();
        if (current < finished) {
            setTimeout(wait, finished - current);
        } else {
            fct();
        }
    };
    setTimeout(wait, millis);
}

function loadCSS(url) {
    if (!$('link[href="' + url + '"]').length) {
        $('head').append($('<link>', {
            'href': url,
            'rel': 'stylesheet',
            'type': 'text/css'
        }));
    }
};

function loadJS(url) {
    var def = $.Deferred();
    if ($('script[src="' + url + '"]').length) {
        def.resolve();
    } else {
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;
        script.onload = script.onreadystatechange = function() {
            if ((script.readyState && script.readyState != "loaded" && script.readyState != "complete") || script.onload_done) {
                return;
            }
            script.onload_done = true;
            def.resolve(url);
        };
        script.onerror = function () {
            console.error("Error loading file", script.src);
            def.reject(url);
        };
        var head = document.head || document.getElementsByTagName('head')[0];
        head.appendChild(script);
    }
    return def;
};

/**
 * Cooperative file download implementation, for ajaxy APIs.
 *
 * Requires that the server side implements an httprequest correctly
 * setting the `fileToken` cookie to the value provided as the `token`
 * parameter. The cookie *must* be set on the `/` path and *must not* be
 * `httpOnly`.
 *
 * It would probably also be a good idea for the response to use a
 * `Content-Disposition: attachment` header, especially if the MIME is a
 * "known" type (e.g. text/plain, or for some browsers application/json
 *
 * @param {Object} options
 * @param {String} [options.url] used to dynamically create a form
 * @param {Object} [options.data] data to add to the form submission. If can be used without a form, in which case a form is created from scratch. Otherwise, added to form data
 * @param {HTMLFormElement} [options.form] the form to submit in order to fetch the file
 * @param {Function} [options.success] callback in case of download success
 * @param {Function} [options.error] callback in case of request error, provided with the error body
 * @param {Function} [options.complete] called after both ``success`` and ``error` callbacks have executed
 */
function get_file(options) {
    // need to detect when the file is done downloading (not used
    // yet, but we'll need it to fix the UI e.g. with a throbber
    // while dump is being generated), iframe load event only fires
    // when the iframe content loads, so we need to go smarter:
    // http://geekswithblogs.net/GruffCode/archive/2010/10/28/detecting-the-file-download-dialog-in-the-browser.aspx
    var timer, token = new Date().getTime(),
        cookie_name = 'fileToken', cookie_length = cookie_name.length,
        CHECK_INTERVAL = 1000, id = _.uniqueId('get_file_frame'),
        remove_form = false;

    // iOS devices doesn't allow iframe use the way we do it,
    // opening a new window seems the best way to workaround
    if (navigator.userAgent.match(/(iPod|iPhone|iPad)/)) {
        var params = _.extend({}, options.data || {}, {token: token});
        var url = options.session.url(options.url, params);
        if (options.complete) { options.complete(); }

        return window.open(url);
    }

    var $form, $form_data = $('<div>');

    var complete = function () {
        if (options.complete) { options.complete(); }
        clearTimeout(timer);
        $form_data.remove();
        $target.remove();
        if (remove_form && $form) { $form.remove(); }
    };
    var $target = $('<iframe style="display: none;">')
        .attr({id: id, name: id})
        .appendTo(document.body)
        .load(function () {
            try {
                if (options.error) {
                    var body = this.contentDocument.body;
                    var nodes = body.children.length === 0 ? body.childNodes : body.children;
                    var node = nodes[1] || nodes[0];
                    options.error(JSON.parse(node.textContent));
                }
            } finally {
                complete();
            }
        });

    if (options.form) {
        $form = $(options.form);
    } else {
        remove_form = true;
        $form = $('<form>', {
            action: options.url,
            method: 'POST'
        }).appendTo(document.body);
    }
    if (core.csrf_token) {
        $('<input type="hidden" name="csrf_token">')
                .val(core.csrf_token)
                .appendTo($form_data);
    }

    var hparams = _.extend({}, options.data || {}, {token: token});
    _.each(hparams, function (value, key) {
            var $input = $form.find('[name=' + key +']');
            if (!$input.length) {
                $input = $('<input type="hidden" name="' + key + '">')
                    .appendTo($form_data);
            }
            $input.val(value);
        });

    $form
        .append($form_data)
        .attr('target', id)
        .get(0).submit();

    var waitLoop = function () {
        var cookies = document.cookie.split(';');
        // setup next check
        timer = setTimeout(waitLoop, CHECK_INTERVAL);
        for (var i=0; i<cookies.length; ++i) {
            var cookie = cookies[i].replace(/^\s*/, '');
            if (!cookie.indexOf(cookie_name === 0)) { continue; }
            var cookie_val = cookie.substring(cookie_length + 1);
            if (parseInt(cookie_val, 10) !== token) { continue; }

            // clear cookie
            document.cookie = _.str.sprintf("%s=;expires=%s;path=/",
                cookie_name, new Date().toGMTString());
            if (options.success) { options.success(); }
            complete();
            return;
        }
    };
    timer = setTimeout(waitLoop, CHECK_INTERVAL);
};

function post (controller_url, data) {

    var progressHandler = function (deferred) {
        return function (state) {
            if(state.lengthComputable) {
                deferred.notify({
                    h_loaded: utils.human_size(state.loaded),
                    h_total : utils.human_size(state.total),
                    loaded  : state.loaded,
                    total   : state.total,
                    pcent   : Math.round((state.loaded/state.total)*100)
                });
            }
        };
    };

    var Def = $.Deferred();
    var postData = new FormData();

    $.each(data, function(i,val) {
        postData.append(i, val);
    });
    if (core.csrf_token) {
        postData.append('csrf_token', core.csrf_token);
    }

    var xhr = new XMLHttpRequest();
    if(xhr.upload) xhr.upload.addEventListener('progress', progressHandler(Def), false);

    var ajaxDef = $.ajax(controller_url, {
        xhr: function() {return xhr;},
        data:           postData,
        processData:    false,
        contentType:    false,
        type:           'POST'
    }).then(function (data) {Def.resolve(data);})
    .fail(function (data) {Def.reject(data);});

    return Def;
}

var loadXML = (function () {
    var loading = false;
    var urls = [];
    var qwebs = [];
    var templates_def = $.Deferred();

    var load = function loadXML(url, qweb) {
        if (url) {
            urls.push(url);
            qwebs.push(qweb);
        }

        if (!loading && urls.length) {
            if (templates_def.state() === "resolved") {
                templates_def = $.Deferred();
            }

            loading = true;
            qwebs.shift().add_template(urls.shift(), function () {
                loading = false;
                if (!urls.length) {
                    templates_def.resolve();
                }
                load(null);
            });
        }

        return templates_def;
    };

    return load;
})();

return {
    jsonRpc: jsonRpc,
    jsonpRpc: jsonpRpc,
    loadCSS: loadCSS,
    loadJS: loadJS,
    loadXML: loadXML,
    get_file: get_file,
    post: post,
};

});


text:
<?php

namespace Igniter\Flame\Database;

use Doctrine\DBAL\Types\Type;
use Igniter\Flame\Database\Connectors\ConnectionFactory;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\DatabaseServiceProvider as BaseDatabaseServiceProvider;
use Illuminate\Database\DatabaseTransactionsManager;
use Illuminate\Support\Facades\Schema;

class DatabaseServiceProvider extends BaseDatabaseServiceProvider
{
    /**
     * Bootstrap the application events.
     *
     * @return void
     */
    public function boot()
    {
        Model::setConnectionResolver($this->app['db']);

        Model::setEventDispatcher($this->app['events']);

        Schema::defaultStringLength(128);
    }

    /**
     * Register the service provider.
     * @return void
     */
    public function register()
    {
        Model::clearBootedModels();

        Model::clearExtendedClasses();

        $this->registerEloquentFactory();

        $this->registerQueueableEntityResolver();

        $this->registerConnectionServices();

        $this->registerDoctrineTypes();
    }

    /**
     * Register the primary database bindings.
     *
     * @return void
     */
    protected function registerConnectionServices()
    {
        // The connection factory is used to create the actual connection instances on
        // the database. We will inject the factory into the manager so that it may
        // make the connections while they are actually needed and not of before.
        $this->app->singleton('db.factory', function ($app) {
            return new ConnectionFactory($app);
        });

        // The database manager is used to resolve various connections, since multiple
        // connections might be managed. It also implements the connection resolver
        // interface which may be used by other components requiring connections.
        $this->app->singleton('db', function ($app) {
            return new DatabaseManager($app, $app['db.factory']);
        });

        $this->app->bind('db.connection', function ($app) {
            return $app['db']->connection();
        });

        $this->app->singleton('db.transactions', function ($app) {
            return new DatabaseTransactionsManager;
        });
    }

    /**
     * Register custom types with the Doctrine DBAL library.
     *
     * @return void
     */
    protected function registerDoctrineTypes()
    {
        if (!class_exists(Type::class)) {
            return;
        }

        $types = $this->app['config']->get('database.dbal.types', [
            'timestamp' => \Illuminate\Database\DBAL\TimestampType::class,
        ]);

        foreach ($types as $name => $class) {
            if (!Type::hasType($name)) {
                Type::addType($name, $class);
            }
        }
    }
}


text:
#ifndef _RMT_MIRRORING_INTERNAL_H
#define _RMT_MIRRORING_INTERNAL_H

#include <p4_sim/mirroring.h>

void mirroring_init(void);

struct phv_data_t;
int mirroring_receive(phv_data_t *phv, int *metadata_recirc, void *pkt, int len,
                      uint64_t packet_id, pkt_instance_type_t instance_type);
#endif


text:
#ifndef STOCKTICKERSB_STOCKTICKER_H_
#define STOCKTICKERSB_STOCKTICKER_H_

#include "Consumer.h"
#include "Publisher.h"
#include "Producer.h"
#include "StockProductAdvanced.h"
#include "StockTickerSubscriber.h"
#include "SynchronizedQueue.h"
#include "TraceLogger.h"
#include <array>
#include <list>
#include <regex>
#include <vector>

namespace stocktickersb {
using namespace std;

class StockTicker {
 public:
  // pass pointers to queue and input to producer and consumer upon construction
 StockTicker(void) {
   StockTicker(nullptr);
 }
  explicit StockTicker(Logger* stock_logger) :all_logger_(stock_logger), stock_ticker_container_(), producer_(&engine_queue_, &input_container_), consumer_(&engine_queue_,&stock_ticker_container_,&publisher_) {
    Clear();
  }
  StockTicker(const StockTicker&) = delete;
  ~StockTicker(void);
  void Clear(void) {
    engine_queue_.Clear();
    input_container_.clear();
    random_input_ = true;
  }
  vector<StockProductAdvanced>& get_input_container(void) { return input_container_;}
  bool SetInputFiles(array<StockTickerSubscriber*, kMaxSubscribers>* subscriber_list);
  bool Start(bool random_input);
  bool Stop(void);
  bool WaitFileInputIsDone(array<StockTickerSubscriber*, kMaxSubscribers>* subscriber_list);
  bool AddSubscriber(StockTickerSubscriber* stock_subscriber) {
    return(publisher_.AddSubscriber(stock_subscriber));
    return true;
  }
  bool RemoveSubscription(StockTickerSubscriber* stock_subscriber) {
    return(publisher_.RemoveSubscriber(stock_subscriber));
    return true;
  }

 private:
  SynchronizedQueue<StockProductAdvanced> engine_queue_;
  bool random_input_;
  vector<StockProductAdvanced> input_container_;
  Producer producer_;
  Consumer consumer_;
  DBStockTickerContainer stock_ticker_container_;
  Publisher publisher_;
  StockTickerConfiguration &config_ = Singleton<StockTickerConfiguration>::get_instance();
  Logger* all_logger_;
};

///////////////////stockTicker implementation///////////////////////////////////////
// replacing random input to producer (of stock prices) to input from files (last state of output files)
bool StockTicker::SetInputFiles(array<StockTickerSubscriber*, kMaxSubscribers>* subscriber_list) {
  StockProductAdvanced stock;
  //regex pat("(\\w{1}),(\\d{1,5}[.]*\\d*),(\\d{1,5}[.]*\\d*)"); // assume input line is like: "a,  34.4,  67.23,";
  regex pat("(\\w{1}),(\\d{1,5}[.]*\\d*),(\\d{1,5}[.]*\\d*),(\\w{1,10}),(\\w{1,10})");
  smatch matches;

  if (subscriber_list == nullptr)
    return false;
  // stop producing and consuming random stock prices
  Stop();
  Clear();
  array<StockTickerSubscriber*, kMaxSubscribers> sts = (*subscriber_list);
  for (int subscriber_id = 0; subscriber_id < config_.get_number_of_subscribers(); subscriber_id++) {
    if (all_logger_ != nullptr)
      all_logger_->Stop(subscriber_id);
    sts[subscriber_id]->Stop();

    // there may be some updates that some subscribers did not work on yet inside the thread
    sts[subscriber_id]->WorkOnUpdates();

  }

  if (all_logger_ != nullptr)
    all_logger_->LogUpdates();

  input_container_.reserve(5000);
  for (int subscriber_id = 0; subscriber_id < config_.get_number_of_subscribers(); subscriber_id++) {
    string line;
    string f;
    f = sts[subscriber_id]->get_file_name();
    ifstream ifile(f);
    getline(ifile, line); // header
    while (!ifile.eof()) {
      getline(ifile, line);
      // remove whitespace: erase-remove_if idiom because remove does not erase what it removes but "appends" it to after the "end"
      line.erase(std::remove_if(line.begin(), line.end(),
        [](char c) { return (c == '\r' || c == '\t' || c == ' ' || c == '\n');}), line.end());
      // search for input line like: "a,  34.4,  67.23," with 3 sub-patterns
      if (regex_search(line, matches, pat) && (matches.size() == 6)) {
        // break line into symbol, buy Tick, sell tick
        string str2 = matches[1]; // symbol
        stock.set_symbol(str2);
        str2 = matches[2]; // buy tick
        double d = stod(str2);
        stock.set_buy_tick(d);
        str2 = matches[3]; // sell tick
        d = stod(str2);
        stock.set_sell_tick(d);
        str2 = matches[4]; // company size
        if (str2 == "small")
          stock.set_company_size(CompanySize::small_cap);
        else if (str2 == "medium")
          stock.set_company_size(CompanySize::mid_cap);
        else if (str2 == "large")
          stock.set_company_size(CompanySize::large_cap);
        else
          stock.set_company_size(CompanySize::undefined);
        str2 = matches[5]; // stock type
        if (str2 == "preferred")
          stock.set_stock_type(StockType::preferred);
        else if (str2 == "common")
          stock.set_stock_type(StockType::common);
        else
          stock.set_stock_type(StockType::undefined);
        input_container_.push_back(stock);
      }
    }
    ifile.close();
    // truncate the output file after it was read in
    sts[subscriber_id]->CreateOutputFile(0, "", &f);
  }
  // start all threads again but the mode is not random but instead it is coming from files
  random_input_ = false;
  Start(random_input_);

  for (int subscriber_id = 0; subscriber_id < config_.get_number_of_subscribers(); subscriber_id++) {
    if (all_logger_ != nullptr)
      all_logger_->Start(subscriber_id);
    sts[subscriber_id]->Start();
  }
  return true;
}

bool StockTicker::Start(bool random_input) {

  engine_queue_.SetWaitingState(false);
  publisher_.dbg_published_count_ = 0;
  publisher_.dbg_subscibers_count_.fill(0);
  producer_.StartProducer(random_input);
  consumer_.StartConsumer(random_input);
  return true;
}

bool StockTicker::Stop(void) {
  engine_queue_.SetWaitingState(true);
  consumer_.StopConsumer();
  producer_.StopProducer();
  return true;
}

bool StockTicker::WaitFileInputIsDone(array<StockTickerSubscriber*, kMaxSubscribers>* subscriber_list) { // called by unit test so I dont implement it as condition variables..
  producer_.WaitFileInputIsDone();
  consumer_.WaitFileInputIsDone();
  // stop all the subscribers
  array<StockTickerSubscriber*, kMaxSubscribers> sts = (*subscriber_list);
  for (int subscriber_id = 0; subscriber_id < config_.get_number_of_subscribers(); subscriber_id++) {
      sts[subscriber_id]->Stop();
      // there may be some updates that some subscribers did not work on yet inside the thread
      sts[subscriber_id]->WorkOnUpdates();
  }
 for (int subscriber_id = 0; subscriber_id < config_.get_number_of_subscribers(); subscriber_id++)
   all_logger_->Stop(subscriber_id);

 if (all_logger_ != nullptr)
    all_logger_->LogUpdates();
  return true;
}

StockTicker::~StockTicker(void) {
  producer_.StopProducer();
  consumer_.StopConsumer();
  Clear();
}

} //namespace StockTickerSB
#endif


text:
define([
    'underscore'
], function (_) {
    var CoreViewsDefaultConfig = function () {
        var self = this;
        this.gridConfig = {
            header: {
                title: {
                    cssClass: 'blue',
                    icon: '',
                    iconCssClass: 'blue'
                },
                icon: false,
                defaultControls: {
                    collapseable: false,
                    exportable: true,
                    refreshable: true,
                    searchable: true,
                    columnPickable: false,
                    groupDeleteable: false
                },
                customControls: false
            },
            columnHeader: {
                columns: {}
            },
            body: {
                options: {
                    actionCell: false,
                    autoHeight: true,
                    autoRefresh: false,
                    checkboxSelectable: true,
                    forceFitColumns: true,
                    detail: {
                        template: '<pre>{{{formatJSON2HTML this.data this.ignoreKeys}}}</pre>'
                    },
                    enableCellNavigation: true,
                    enableColumnReorder: false,
                    enableTextSelectionOnCells: true,
                    fullWidthRows: true,
                    multiColumnSort: true,
                    rowHeight: 30,
                    fixedRowHeight: false,
                    gridHeight: 500,
                    rowSelectable: false,
                    sortable: true,
                    lazyLoading: true,
                    defaultDataStatusMessage: true,
                    actionCellPosition: 'end', //actionCellPosition indicates position of the settings icon whether it should be on row start and end
                    multiRowSelection: true, //This property will enable/disable selecting multiple rows of the grid, but the checkbox in the header should be removed by the client because as of now, we don't have way in api to remove the checkbox in header
                    disableRowsOnLoading: false,
                    rowDelete: false
                },
                dataSource: {
                    remote: null,
                    data: null,
                    events: {}
                },
                statusMessages: {
                    loading: {
                        type: 'status',
                        iconClasses: '',
                        text: 'Loading...'
                    },
                    empty: {
                        type: 'status',
                        iconClasses: '',
                        text: 'No data available.'
                    },
                    error: {
                        type: 'error',
                        iconClasses: 'fa fa-exclamation-triangle',
                        text: 'Error in getting data.'
                    }
                }
            },
            footer: {
                pager: {
                    options: {
                        pageSize: 50,
                        pageSizeSelect: [10, 50, 100, 200]
                    }
                }
            }
        };

        this.lineWithFocusChartConfig = {
            margin: {top: 10, right: 30, bottom: 50, left: 65},
            margin2: {top: 0, right: 30, bottom: 40, left: 65},
            axisLabelDistance: 5,
            height: 300,
            xAxisLabel: 'Time',
            yAxisLabel: 'Traffic',
            y2AxisLabel: '',
            forceY: [0, 60],
            showXAxisMaxMin:false,
            defaultDataStatusMessage: true,
            statusMessageHandler: cowm.getRequestMessage,
            xFormatter: function(d) { return d3.time.format('%H:%M:%S')(new Date(d)); },
            x2Formatter: function(d) { return d3.time.format('%H:%M:%S')(new Date(d)); },
            yFormatter: function(d) { return cowu.addUnits2Bytes(d, false, false, 1, 60); },
            y2Formatter: function(d) { return cowu.addUnits2Bytes(d, false, false, 1, 60); }
        };

        this.lineBarWithFocusChartConfig = {
            margin: {top: 20, right: 70, bottom: 50, left: 70},
            margin2: {top: 0, right: 70, bottom: 40, left: 70},
            height: 300,
            axisLabelDistance: 5,
            y1AxisLabel: 'CPU Utilization (%)',
            y2AxisLabel: 'Memory Usage',
            forceY1: [0, 5],
            forceY2: [0, 5],
            defaultDataStatusMessage: true,
            statusMessageHandler: cowm.getRequestMessage,
            y2Formatter: function (y2Value) {
                var formattedValue = formatBytes(y2Value * 1024, true);
                return formattedValue;
            },
            // y1Formatter: d3.format(".01f"),
            y1Formatter: function(number) {
                number.toFixed(1);
            },
            showLegend: true,
            focusEnable: true
        };

        self.getToolbarViewConfig = function() {
            var toolBarItems =  {
                    settings: [{
                        id: cowc.COLOR_PALETTE,
                        title: "Dashboard Colors",
                        view: 'js/views/SettingsColorView',
                        model: 'js/models/SettingsColorModel'
                    }, {
                        id: cowc.FULL_SCREEN,
                        title: "Toggle Full Screen",
                        // view: 'js/views/SettingsColorView',
                        // model: 'js/models/SettingsColorModel'
                    },{
                        id: cowc.CHART_SETTINGS,
                        title: "Chart Settings",
                        view: "js/views/ChartSettingsView",
                        model: "js/models/ChartSettingsModel"
                    }]
             }
            if (cowc.panelLayout) {
                toolBarItems['settings'].push({
                    id: cowc.ADD_WIDGET,
                    title: "Add Widget",
                    // view: 'js/views/SettingsColorView',
                    // model: 'js/models/SettingsColorModel'
                });
            }
            return toolBarItems;
        };
    };

    return CoreViewsDefaultConfig;
});


text:
var exptemplate = require('./exptemplate'),
    log = require('./log'),
    config = require('./config'),
    updateExptemplateUseCount = require('./updateExptemplateUseCount');

// Retrieves latest version if 'version' is null.
function getExptemplate(client, username, name, version, callback) {
    client.query(
        { name: 'getExptemplatesInDb-1-' + (typeof(version) == 'number'),
          text: "SELECT info, $1::integer FROM exptemplates " +
                "WHERE " + (typeof(version) == 'number' ? "version::integer = $1 AND" : "") + " name = $2 AND ibexuser_name = $3 " +
                "ORDER BY version DESC " +
                "LIMIT 1",
          values: [version || 0, name, username]
        },
        function (err, result) {
            if (err)
                return callback(err);

            if (result.rows.length == 0)
                return callback(null, null);
            if (result.rows.length != 1)
                throw new Error("WTF?! [100] getExptemplate.js");

            // Update stats on number of times this exptemplate was accessed.
            var timenow = new Date().toISOString();
            updateExptemplateUseCount(client, timenow, name, username, function (err) {
                if (err)
                    log.error("Error updating exptemplate stats");
            });

            return callback(null, result.rows[0].info);
        }
    );
}

function getExptemplateFiles(client, username, name, version, callback) {
    client.query(
        { name: 'getExptemplateFiles-1',
          text: "SELECT original_upload, original_upload_mime_type FROM exptemplates " +
                "WHERE name = $1 AND ibexuser_name = $2 AND version = $3",
          values: [ name, username, version ]
        },
        function (err, result) {
            if (err)
                return callback(err);

            if (result.rows.length == 0)
                return callback(null, null);
            if (result.rows.length != 1)
                throw new Error("WTF?! [200] getExptemplate.js");

            return callback(null, result.rows[0].original_upload, result.rows[0].original_upload_mime_type);
        }
    );
};

function getTrendyExptemplates(client, n, callback) {
    // MAX is applied to ibexuser_name and exptemplate_name in the 'trendiest'
    // query only because postgres insists. Since results for this query are
    // grouped by these two columns, the choice of row is arbitrary.
    client.query(
        {
            name: 'getTrendyExptemplates-1',
            text: "WITH trendiest AS (SELECT SUM(count) AS total, MAX(ibexuser_name) AS ibexuser_name, MAX(exptemplate_name) AS exptemplate_name " +
                  "                   FROM exptemplate_stats " +
                  "                   GROUP BY (ibexuser_name, exptemplate_name) " +
                  "                   ORDER BY total DESC " +
                  "                   LIMIT $1)" +
                  "SELECT DISTINCT ON (exptemplates.ibexuser_name, exptemplates.name) exptemplates.ibexuser_name, exptemplates.name, version, info " +
                  "FROM exptemplates " +
                  "INNER JOIN trendiest ON (exptemplates.ibexuser_name = trendiest.ibexuser_name AND exptemplates.name = trendiest.exptemplate_name) " +
                  "ORDER BY exptemplates.ibexuser_name, exptemplates.name, exptemplates.version DESC",
            values: [n]
        },
        function (err, result) {
            if (err)
                return callback(err);

            var templates = [ ];
            for (var i = 0; i < result.rows.length; ++i) {
                templates.push(result.rows[i].info);
            }

            callback(null, templates);
        }
    );
}

exports.getExptemplate = getExptemplate;
exports.getExptemplateFiles = getExptemplateFiles;
exports.getTrendyExptemplates = getTrendyExptemplates;


text:
/* css Zen Garden submission 138 - 'DJ Style', by Masanori Kawachi, http://www.804case.com/ */
/* css released under Creative Commons License - http://creativecommons.org/licenses/by-nc-sa/1.0/  */
/* All associated graphics copyright 2004, Masanori Kawachi */
/* Added: Nov. 29th, 2004 */

/* IMPORTANT */
/* This design is not a template. You may not reproduce it elsewhere without the
   designer's written permission. However, feel free to study the CSS and use
   techniques you learn from it elsewhere. */

body { margin: 0px; padding: 0px; background: url(images/cubegarden/body_bg.gif) left top repeat-y #fff; }
p { font-size: 10px; !important;font-size: 70%; line-height: 133%; font-family: Arial, Helvetica, sans-serif; color: #666; }
h1,h2,h3 { margin: 0px; padding: 0px; }
a { color: #336633; }
acronym { background-color: #FFF7D2; }

#extraDiv1 { position: absolute; left: 0px; top: 0px; z-index: 1; width: 100%; height: 51px; background: url(images/cubegarden/header_bg.gif) left top repeat-x; }
#pageHeader h1 { position: absolute; left: 0px; top: 0px; z-index: 2; width: 237px; height: 176px; margin: 0px; padding: 0px; background: url(images/cubegarden/logo.gif) left top no-repeat; }
#pageHeader h1 span,#pageHeader h2 { position: absolute; left: -9999px; }

#container { background: url(images/cubegarden/rightside_top.gif) 0px 0px no-repeat; width: 510px; margin: 51px 0px 0px 237px; padding-top: 24px; }

#quickSummary { margin-left: 34px; padding-left: 30px; width: 425px !important;width /**/:455px; background: url(images/cubegarden/arrow.gif) left top no-repeat; }
#quickSummary p { margin: 0px 0px 5px 0px; padding: 0px; }

#preamble { margin: 40px 0px 0px 30px; width: 458px; }
#preamble h3 { width: 458px; height: 0px !important;height /**/:24px; padding-top: 24px; background: url(images/cubegarden/tit_01.gif) left top no-repeat; display: block; overflow: hidden; }
#preamble p { margin: 5px 0px 5px 20px; padding: 0px; }

#supportingText { margin: 25px 0px 0px 30px; width: 458px; background: url(images/cubegarden/leaf.gif) right top no-repeat; }

#explanation { margin-bottom: 20px; }
#explanation h3 { width: 458px; height: 0px !important;height /**/:24px; padding: 24px 0px 0px 0px; background: url(images/cubegarden/tit_02.gif) left top no-repeat; display: block; overflow: hidden; }
#explanation p { margin: 5px 0px 5px 20px; padding: 0px; }

#participation { margin-bottom: 20px; }
#participation h3 { width: 458px; height: 0px !important;height /**/:24px; padding-top: 24px; background: url(images/cubegarden/tit_03.gif) left top no-repeat; display: block; overflow: hidden; }
#participation p { margin: 5px 0px 5px 20px; padding: 0px; }

#benefits { margin-bottom: 20px; }
#benefits h3 { width: 458px; height: 0px !important;height /**/:24px; padding-top: 24px; background: url(images/cubegarden/tit_04.gif) left top no-repeat; display: block; overflow: hidden; }
#benefits p { margin: 5px 0px 5px 20px; padding: 0px; }

#requirements { margin-bottom: 20px; }
#requirements h3 { width: 458px; height: 0px !important;height /**/:24px; padding-top: 24px; background: url(images/cubegarden/tit_05.gif) left top no-repeat; display: block; overflow: hidden; }
#requirements p { margin: 5px 0px 5px 20px; padding: 0px; }

#footer { margin: 0px 0px 20px 20px; font-size: 10px; !important;font-size: 70%; font-family: Arial, Helvetica, sans-serif;  }

#linkList { position: absolute; left: 13px; top: 176px; width: 212px; background: url(images/cubegarden/leftside_bg.gif) left top repeat-x; }

#lselect { width: 212px; background: url(images/cubegarden/list_bg.gif) left top repeat-y; }
#lselect h3 { background: url(images/cubegarden/select_tit.gif) left top no-repeat; width: 212px; height: 0px !important;height /**/:35px; padding-top: 35px; display: block; overflow: hidden; }
#lselect ul { margin: 0px; padding: 0px 0px 0px 4px; list-style-type: none; font-size: 10px; !important;font-size: 70%; font-family: Arial, Helvetica, sans-serif; }
#lselect li { padding: 13px 5px 13px 5px; margin: 0px; width: 196px !important;width /**/:206px; text-align: center; border-top-width: 1px; border-bottom-width: 1px; border-top-style: solid; border-bottom-style: solid; border-top-color: #e9e9e9; border-bottom-color: #FFFFFF; display: block; }
#lselect li:hover { background-color: #fff; }

#larchives { width: 212px; background: url(images/cubegarden/list_bg.gif) left top repeat-y; display: block; }
#larchives h3 { background: url(images/cubegarden/archives_tit.gif) left top no-repeat; width: 212px; height: 0px !important;height /**/:26px; padding-top: 26px; display: block; overflow: hidden; }
#larchives ul { margin: 0px; padding: 0px 0px 0px 4px; list-style-type: none; font-size: 10px; !important;font-size: 70%; font-family: Arial, Helvetica, sans-serif; }
#larchives li { padding: 13px 5px 13px 5px; margin: 0px; width: 196px !important;width /**/:206px; text-align: center; border-top-width: 1px; border-bottom-width: 1px; border-top-style: solid; border-bottom-style: solid; border-top-color: #e9e9e9; border-bottom-color: #FFFFFF; display: block; }
#larchives li:hover { background-color: #fff; }

#lresources { width: 212px; background: url(images/cubegarden/list_bg.gif) left top repeat-y; display: block; }
#lresources h3 { background: url(images/cubegarden/archives_tit.gif) left top no-repeat; width: 212px; height: 0px !important;height /**/:26px; padding-top: 26px; display: block; overflow: hidden; }
#lresources ul { margin: 0px; padding: 0px 0px 0px 4px; list-style-type: none; font-size: 10px; !important;font-size: 70%; font-family: Arial, Helvetica, sans-serif; }
#lresources li { padding: 13px 5px 13px 5px; margin: 0px; width: 196px !important;width /**/:206px; text-align: center; border-top-width: 1px; border-bottom-width: 1px; border-top-style: solid; border-bottom-style: solid; border-top-color: #e9e9e9; border-bottom-color: #FFFFFF; display: block; }
#lresources li:hover { background-color: #fff; }


text:
#pragma once

//==============================================================================
struct ColourPropertyComponent  : public PropertyComponent
{
    ColourPropertyComponent (UndoManager* undoManager, const String& name, const Value& colour,
                             Colour defaultColour, bool canResetToDefault)
        : PropertyComponent (name),
          colourEditor (undoManager, colour, defaultColour, canResetToDefault)
    {
        addAndMakeVisible (colourEditor);
    }

    void resized() override
    {
        colourEditor.setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
    }

    void refresh() override {}

private:
    /**
        A component that shows a colour swatch with hex ARGB value, and which pops up
        a colour selector when you click it.
    */
    struct ColourEditorComponent    : public Component,
                                      private Value::Listener
    {
        ColourEditorComponent (UndoManager* um, const Value& colour,
                               Colour defaultCol, const bool canReset)
            : undoManager (um), colourValue (colour), defaultColour (defaultCol),
              canResetToDefault (canReset)
        {
            colourValue.addListener (this);
        }

        void paint (Graphics& g) override
        {
            const Colour colour (getColour());

            g.fillAll (Colours::grey);
            g.fillCheckerBoard (getLocalBounds().reduced (2).toFloat(),
                                10.0f, 10.0f,
                                Colour (0xffdddddd).overlaidWith (colour),
                                Colour (0xffffffff).overlaidWith (colour));

            g.setColour (Colours::white.overlaidWith (colour).contrasting());
            g.setFont (Font ((float) getHeight() * 0.6f, Font::bold));
            g.drawFittedText (colour.toDisplayString (true), getLocalBounds().reduced (2, 1),
                              Justification::centred, 1);
        }

        Colour getColour() const
        {
            if (colourValue.toString().isEmpty())
                return defaultColour;

            return Colour::fromString (colourValue.toString());
        }

        void setColour (Colour newColour)
        {
            if (getColour() != newColour)
            {
                if (newColour == defaultColour && canResetToDefault)
                    colourValue = var();
                else
                    colourValue = newColour.toDisplayString (true);
            }
        }

        void resetToDefault()
        {
            setColour (defaultColour);
        }

        void refresh()
        {
            const Colour col (getColour());

            if (col != lastColour)
            {
                lastColour = col;
                repaint();
            }
        }

        void mouseDown (const MouseEvent&) override
        {
            if (undoManager != nullptr)
                undoManager->beginNewTransaction();

            CallOutBox::launchAsynchronously (std::make_unique<PopupColourSelector> (colourValue,
                                                                                defaultColour,
                                                                                canResetToDefault),
                                              getScreenBounds(),
                                              nullptr);
        }

    private:
        void valueChanged (Value&) override
        {
            refresh();
        }

        UndoManager* undoManager;
        Value colourValue;
        Colour lastColour;
        const Colour defaultColour;
        const bool canResetToDefault;

        JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ColourEditorComponent)
    };

    //==============================================================================
    struct PopupColourSelector   : public Component,
                                   private ChangeListener,
                                   private Value::Listener
    {
        PopupColourSelector (const Value& colour,
                             Colour defaultCol,
                             const bool canResetToDefault)
            : defaultButton ("Reset to Default"),
              colourValue (colour),
              defaultColour (defaultCol)
        {
            addAndMakeVisible (selector);
            selector.setName ("Colour");
            selector.setCurrentColour (getColour());
            selector.addChangeListener (this);

            if (canResetToDefault)
            {
                addAndMakeVisible (defaultButton);
                defaultButton.onClick = [this]
                {
                    setColour (defaultColour);
                    selector.setCurrentColour (defaultColour);
                };
            }

            colourValue.addListener (this);
            setSize (300, 400);
        }

        void resized() override
        {
            if (defaultButton.isVisible())
            {
                selector.setBounds (0, 0, getWidth(), getHeight() - 30);
                defaultButton.changeWidthToFitText (22);
                defaultButton.setTopLeftPosition (10, getHeight() - 26);
            }
            else
            {
                selector.setBounds (getLocalBounds());
            }
        }

        Colour getColour() const
        {
            if (colourValue.toString().isEmpty())
                return defaultColour;

            return Colour::fromString (colourValue.toString());
        }

        void setColour (Colour newColour)
        {
            if (getColour() != newColour)
            {
                if (newColour == defaultColour && defaultButton.isVisible())
                    colourValue = var();
                else
                    colourValue = newColour.toDisplayString (true);
            }
        }

    private:
        void changeListenerCallback (ChangeBroadcaster*) override
        {
            if (selector.getCurrentColour() != getColour())
                setColour (selector.getCurrentColour());
        }

        void valueChanged (Value&) override
        {
            selector.setCurrentColour (getColour());
        }

        StoredSettings::ColourSelectorWithSwatches selector;
        TextButton defaultButton;
        Value colourValue;
        Colour defaultColour;
    };

    ColourEditorComponent colourEditor;
};


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Http;
using Microsoft.Framework.DependencyInjection;

namespace StartupConventions
{
    public class Startup
    {

        public void ConfigureDevelopment(IApplicationBuilder app)
        {
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Development :D");
            });
        }

        public void ConfigureStaging(IApplicationBuilder app)
        {
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Staging :D ");
            });
        }

        public void ConfigureProduction(IApplicationBuilder app)
        {
            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Production :D");
            });
        }
    }
}


text:
package org.openehealth.ipf.commons.xml;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.io.IOException;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;

public class SchematronTransmogrifierTest {

    private SchematronTransmogrifier<String> svi;

    @Before
    public void setUp() throws Exception {
        svi = new SchematronTransmogrifier<String>(String.class);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void testConvert() throws IOException {
        Source testXml = new StreamSource(new ClassPathResource(
                "schematron/schematron-test.xml").getInputStream());
        String result = svi
                .zap(testXml, "schematron/schematron-test-rules.xml");
        assertFalse(result.contains("svrl:failed-assert"));
    }

    @Test
    public void testConvertFail() throws IOException {
        Source testXml = new StreamSource(new ClassPathResource(
                "schematron/schematron-test-fail.xml").getInputStream());
        String result = svi
                .zap(testXml, "schematron/schematron-test-rules.xml");
        assertTrue(result.contains("<svrl:failed-assert")); // 3 occurrences
    }
}


text:
title: Sankey from Scratch
author: Timely Portfolio
github: {user: timelyportfolio, repo: rCharts_d3_horizon, branch: "gh-pages"}
framework: bootstrap
mode: selfcontained
highlighter: prettify
hitheme: twitter-bootstrap
widgets: "d3_sankey"
assets:
  css:
    - "http://fonts.googleapis.com/css?family=Raleway:300"
    - "http://fonts.googleapis.com/css?family=Oxygen"
---

# Sankey from Scratch using `rCharts`, `d3.js`, and `igraph`

## Introduction

This example will walk through the steps of using the `R` package [`igraph`](http://igraph.sourceforge.net/) to create a tree network for a [sankey diagram](http://econ.st/JwNX8s).  This is a great exercise to learn some basics of `igraph`, explore the construction of a sankey, and determine the conditions for a network to be drawn properly as a sankey. After all of this, we will plot our network with the [`rCharts`](http://rcharts.io/site) implementation of the [d3.js sankey plugin](https://github.com/d3/d3-plugins/blob/master/sankey/sankey.js).

## Build a Network
Let's first start by loading the `igraph` and `rCharts` packages.  Then we will use `graph.tree` to build a tree network with 40 vertices with 4 children.

```r
require(igraph)
require(rCharts)

g <- graph.tree(40, children = 4)
```

For fun, we will assign a weight of 1 `E(g)$weight = 1` for each edge and then draw a Sankey diagram using `rCharts`.  Going forward I will try to explain the `R` code through comments in the code block.

## Plot Our Sankey to Find a Problem

```r
E(g)$weight = 1

edgelist <- get.data.frame(g) #this will give us a data frame with from,to,weight
colnames(edgelist) <- c("source","target","value")
#make character rather than numeric for proper functioning
edgelist$source <- as.character(edgelist$source)
edgelist$target <- as.character(edgelist$target)

sankeyPlot <- rCharts$new()
sankeyPlot$setLib('libraries/widgets/d3_sankey')
sankeyPlot$setTemplate(script = "libraries/widgets/d3_sankey/layouts/chart.html")

sankeyPlot$set(
  data = edgelist,
  nodeWidth = 15,
  nodePadding = 10,
  layout = 32,
  width = 960,
  height = 500
)

sankeyPlot$print(chartId = 'sankey1')
```

Interact with the sankey plot a little, and try to find the problem in our hastily constructed network.  Hovering over the vertex 4 will reveal our issue.  The edge from 1 to 4 is not as big as the sum of the edges going out from 4.  For this to make sense, unless 4 is magically creating something, the sum of the inflow should equal the sum of the outflow.  Since 4 has four children each with weight of 1 (outflow = 1 + 1 + 1 + 1 = 4), we would expect the inflow to also be 4.  It is only 1 though since we made all our edges' weights = 1 `E(g)$weight = 1`.  How then would we build our network with edge weights so that for each vertex, the sum of in equals the sum of out.

## Fix Our Problem For a Beautiful Sankey
I am a network novice, so while the code below works, I am sure there are better ways of accomplishing the desired result.  I heavily commented the code, but I will quickly describe the steps.  The code starts at the lowest level of the heirarchy, or those vertexes where there is nothing going out (out degree = 0).  In our network, these are 11 through 40.  With `igraph` we can identify these by `V(g2)[degree(g2,mode="out")==0]`.  For these we will assign a weight.  Then we will loop through all of the edges summing all of the weights of the out until we have reached the top of the heirarchy.

```r
g2 <- graph.tree(40, children=4)
#to construct a sankey the weight of each vertex should be the sum
#of its outgoing edges
#I believe the first step in creating a network that satisfies this condition
#is define a vertex weight for all vertexes with out degree = 0
#but first let's define 0 for all
V(g2)$weight = 0
#now for all vertexes with out degree = 0
V(g2)[degree(g2,mode="out")==0]$weight <- runif(n=length(V(g2)[degree(g2,mode="out")==0]),min=0,max=100)
#the lowest level of the heirarchy is defined with a random weight
#with the lowest level defined we should now be able to sum the vertex weights
#to define the edge weight
#E(g2)$weight = 0.1 #define all weights small to visually see as we build sankey
E(g2)[to(V(g2)$weight>0)]$weight <- V(g2)[V(g2)$weight>0]$weight
#and to find the neighbors to the 0 out degree vertex
#we could do V(g2)[nei(degree(g2,mode="out")==0)]
#we have everything we need to build the rest by summing
#these edge weights if there are edges still undefined
#so set up a loop to run until all edges have a defined weight
while(max(is.na(E(g2)$weight))) {
  #get.data.frame gives us from, to, and weight
  #we will get this to make an easier reference later
  df <- get.data.frame(g2)
  #now go through each edge and find the sum of all its subedges
  #we need to check to make sure out degree of its "to" vertex is not 0
  #or we will get 0 since there are no edges for vertex with out degree 0
  for (i in 1:nrow(df)) {
    x = df[i,]
    #sum only those with out degree > 0 or sum will be 0
    if(max(df$from==x$to)) {
      E(g2)[from(x$from) & to(x$to)]$weight = sum(E(g2)[from(x$to)]$weight)
    }
  }
}

edgelistWeight <- get.data.frame(g2)
colnames(edgelistWeight) <- c("source","target","value")
edgelistWeight$source <- as.character(edgelistWeight$source)
edgelistWeight$target <- as.character(edgelistWeight$target)

sankeyPlot2 <- rCharts$new()
sankeyPlot2$setLib('libraries/widgets/d3_sankey')
sankeyPlot2$setTemplate(script = 'libraries/widgets/d3_sankey/layouts/chart.html')

sankeyPlot2$set(
  data = edgelistWeight,
  nodeWidth = 15,
  nodePadding = 10,
  layout = 32,
  width = 960,
  height = 500
)

sankeyPlot2
```

## Another Look at Our Network
There are very [good examples](http://rulesofreason.wordpress.com/tag/plot-igraph/) illustrating the use of `igraph` to plot a network.  This is not one of these examples.  For fun though, let's plot the network with igraph using just the defaults to compare it to our Sankey output from above.

```r
plot(g2)
```

![plot of chunk unnamed-chunk-5](assets/fig/unnamed-chunk-5.png)

## Lots More Sankey
Believe it or not, there is an entire site devoted to sankey diagrams.  For all the sankey you can handle, check out http://sankey-diagrams.com.  Here are a couple more sankeys generated from `rCharts`:  http://rcharts.io/viewer/?6001601#.UeWfuY3VCSo, http://rcharts.io/viewer/?6003605, http://rcharts.io/viewer/?6003575.


text:
package io.gravitee.rest.api.service;

import io.gravitee.rest.api.model.configuration.identity.SocialIdentityProviderEntity;
import io.gravitee.rest.api.service.configuration.identity.IdentityProviderActivationService;
import java.util.Set;

/**
 * @author David BRASSELY (david.brassely at graviteesource.com)
 * @author GraviteeSource Team
 */
public interface SocialIdentityProviderService {
    Set<SocialIdentityProviderEntity> findAll(IdentityProviderActivationService.ActivationTarget target);

    SocialIdentityProviderEntity findById(String id, IdentityProviderActivationService.ActivationTarget target);
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.10 at 01:21:49 오후 KST
//

package org.onem2m.xml.protocols;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <extension base="{http://www.onem2m.org/xml/protocols}mgmtResource">
 *       <sequence>
 *         <element name="activeCmdhPolicyLink" type="{http://www.onem2m.org/xml/protocols}ID"/>
 *       </sequence>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
    "activeCmdhPolicyLink"
})
@XmlRootElement(name = "activeCmdhPolicy")
public class ActiveCmdhPolicy
    extends MgmtResource
{

    @XmlElement(required = true)
    protected String activeCmdhPolicyLink;

    /**
     * Gets the value of the activeCmdhPolicyLink property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    public String getActiveCmdhPolicyLink() {
        return activeCmdhPolicyLink;
    }

    /**
     * Sets the value of the activeCmdhPolicyLink property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    public void setActiveCmdhPolicyLink(String value) {
        this.activeCmdhPolicyLink = value;
    }

}


text:
<?php

/**
 * Created by PhpStorm.
 * plan: Administrator
 * Date: 14-6-6
 * Time: 下午4:29
 */
class Plan extends CActiveRecord
{

    public static function model($className = __CLASS__)
    {

        return parent::model($className);
    }

    public function tableName()
    {

        return '{{plan}}';
    }

    /**
     * 如果要设置场景,那么每个规则都应该设置场景,否则就会出现验证出错
     *
     */
    public function rules()
    {

        return array(
            array(
                'destination,startDate,endDate,images,city,startCity',
                'required',
                'on' => 'publish',
                'message' => Yii::t('PlanModule.plan', '{attribute} should  not  be black')
            ),
            array(
                'together,purpose,type,flight,vehicle,postscript,zone,laitude,longitude',
                'safe'
            ),
            array(
                'planId',
                'required',
                'on' => 'detail',
                'message' => Yii::t('PlanModule.plan','{attribute} should  not  be black')
            ),
            array(
                'userId',
                'required',
                'on' => 'list',
                'message' => Yii::t('PlanModule.plan','{attribute} should  not  be black')
            ),
        );
    }

    public function attributeLabels()
    {
        return array(
            'planId' => Yii::t('PlanModule.plan', 'planId'),
            'destination' => Yii::t('PlanModule.plan', 'destination'),
            'startDate' => Yii::t('PlanModule.plan', 'startDate'),
            'endDate' => Yii::t('PlanModule.plan', 'endDate'),
            'together' => Yii::t('PlanModule.plan', 'together'),
            'purpose' =>  Yii::t('PlanModule.plan', 'purpose'),
            'type' =>     Yii::t('PlanModule.plan', 'type'),
            'flight' => Yii::t('PlanModule.plan', 'flight'),
            'vehicle' => Yii::t('PlanModule.plan', 'vehicle'),
            'startCity' => Yii::t('PlanModule.plan', 'startCity'),
            'postscript' => Yii::t('PlanModule.plan', 'postscript')
        );
    }

    public function relations()
    {
        return array(
            'user' => array(self::BELONGS_TO,   'User',   'userId'),
            'state'=>array(self::BELONGS_TO,   'UserState',   'userId'),
        );
    }

    public function behaviors()
    {
        return array(
                'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'createAttribute' => 'createTime',
            ),
                'NearScopeBehavior' => array(
                'class' => 'ext.behavior.NearScopeBehavior',
                'latitude' => Yii::app()->user->latitude,
                'longitude' => Yii::app()->user->longitude,

            )
        );
    }
    public function scopes()
    {

        return array(
            'unexpired' => array(
                'condition' => 'DATEDIFF(endDate,' . '\'' .date('Y-m-d') . '\''.')>=0',
                'order' => 'planId DESC'
            ),
            'local'=>array(
                'condition' => 'city=:currentCity  AND  startCity=:currentCity',
                'params'=>array(':currentCity'=>Yii::app()->user->currentCity),
            ),
            'startThis'=>array(
                'condition' => 'startCity=:currentCity',
                'params'=>array(':currentCity'=>Yii::app()->user->currentCity),

            ),
        );
    }

    /**
     *      如果景点未知。那么城市就未知。
     *      但是城市未知,显示在客户端就很别扭
     *
     *
     */
    protected function beforeSave()
    {

        if (parent::beforeSave()) {
            $this->userId = Yii::app()->user->userId;

        }
        return true;
    }
    private function search(CFormModel & $condition)
    {
        $criteria = new CDbCriteria();
        $criteria->compare('destination', $condition->location, true);
        $criteria->compare('gender', $condition->gender, false);
        if ($condition->residence == '0' || $condition->residence == '1') {
            switch ($condition->residence) {
                case '0':
                   $criteria->compare('residence',Yii::app()->user->currentCity,true);
                    break;

               case '1':
                   $criteria->compare('residence','<>'.Yii::app()->user->currentCity,true);
                   break;

                default:
                    break;
            }
        }

        return $criteria;
    }

    /**
     *
     * 改进:使用延迟绑定,将这个函数写在父类里面
     *返回某个用户所发布的所有计划列表
     *          主页默认显示的是只在本地的。
     *
     *

     * @return CActiveDataProvider $dataProvider  返回CActiveDataProvider对象
     */
    public function getDataProvider(CFormModel & $condition)
    {
//      $e=  array_filter($condition->attributes);
      $model=Plan::model()->unexpired()->near();
        if(empty($condition->location)){
            $model=$model->local()->with(array('user','state'));
        }
       else{
           $model=$model->startThis()->with(array('user','state'));
       }
        $model=$model->with(array('user','state'));
        $dataProvider = new CActiveDataProvider($model, array(
        'pagination' => array(
            'pageSize' => 20,
        ),
    ));

        $dataProvider->setCriteria($this->search($condition));

        return $dataProvider;
    }

    public function getList($planId)
    {
        $dataProvider = new CActiveDataProvider(Plan::model(), array(
            'criteria' => array(
                'condition' => 'planId=' . $planId,
                'order' => 'planId DESC',
            ),
            'pagination' => array(
                'pageSize' => 20,
            ),
        ));

        return $dataProvider;
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: nikunjbansal
 * Date: 8/6/17
 * Time: 3:14 PM
 */

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;

class SecurityController extends Controller
{

    /**
     * @Route("/login", name="login")
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function loginAction(Request $request)
    {

        if($this->isGranted('ROLE_USER')) {
            return $this->redirectToRoute('read_blog');
        }

        /** @var AuthenticationUtils $authUtils */
        $authUtils = $this->get('security.authentication_utils');

        // get the login error if there is one
        $error = $authUtils->getLastAuthenticationError();

        // last username entered by the user
        $lastUsername = $authUtils->getLastUsername();

        return $this->render('security/login.html.twig', array(
            'last_username' => $lastUsername,
            'error'         => $error,
        ));
    }

    /**
     * @Route("login_check", name="login_check")
     * @param Request $request
     * @return Boolean
     */
    public function login_check(Request $request)
    {
        return true;
    }

}


text:
        Cliente
        Nuevo

                        <?php if($this->session->flashdata('error')):?>

                                <button class="close" type="button" data-dismiss='alert' aria-hideen='true'>
                                    ×

                                        <?php echo $this->session->flashdata('error'); ?>

                                </button>

                        <?php endif; ?>
                        <form action="<?php echo base_url();?>mantenimiento/clientes/store" method="POST">
                                 <div class="form-group <?php echo form_error('nombre') != false ? 'has-error': '';?>">

                                        Nombre:

                                            <input name="nombre"  class="form-control input-md" id="nombre" value="<?php echo set_value('nombre');?>">

                                    <?php echo form_error("nombre","",""); ?>

                                        Tipo Cliente:
                                        <div class="input-group col-xs-12 col-md-12 <?php echo form_error('tipoCliente') != false ? 'has-error': '';?>">
                                            <select name="tipoCliente"  class="form-control input-md" id="tipoCliente">
                                            <option value="">Selecciones un tipo de cliente</option>
                                            <?php foreach ($tipoClientes as $tipoCliente):?>
                                                <option value="<?php echo $tipoCliente->tipo_cliente;?>" <?php echo set_select('tipoCliente',$tipoCliente->tipo_cliente);?>><?php echo $tipoCliente->nombre;?></option>
                                            <?php endforeach;?>
                                            </select>
                                            <?php echo form_error("tipoCliente","",""); ?>

                                    <div class="col-xs-12 col-md-6 col-lg-6 <?php echo form_error('tipoDocumento') != false ? 'has-error':'';?>">
                                        Tipo Documento:

                                            <select name="tipoDocumento"  class="form-control input-md" id="tipoDocumento">
                                            <option value="">Selecciones un tipo de Documento</option>
                                            <?php foreach ($tipoDocumentos as $tipoDocumento):?>
                                                <option value="<?php echo $tipoDocumento->tipo_documento;?>"><?php echo $tipoDocumento->nombre;?></option>
                                            <?php endforeach; ?>
                                            </select>
                                            <?php echo form_error("tipoDocumento","",""); ?>

                                    <div class="col-xs-12 col-md-4 col-lg-4 <?php echo form_error('numDocumento') != false ? 'has-error': '';?>">
                                        Numero de Documento:

                                            <input name="numDocumento"  class="form-control input-md" id="numDocumento" value="<?php echo set_value("numDocumento");?>">

                                        <?php echo form_error("numDocumento","",""); ?>

                                        Direccion:

                                            <input name="direccion"  class="form-control input-md" id="direccion">

                                        Telefono:

                                            <input name="telefono"  class="form-control input-md" id="telefono">

                                        <button type="submit" class="btn btn-success btn-flat">Guardar</button>
                                        <a class="btn btn-danger btn-flat" href="<?php echo base_url();?>mantenimiento/clientes">Cancelar

                        </form>


text:
export SCRIPT_DIR=$(dirname $(realpath $0))
source ${SCRIPT_DIR}/settings.sh

syncrepo() {
  REPONAME=$1
  sudo reposync -n -m -l -p ${REPO_STORAGE}/${REPONAME}/ -r ${REPONAME} | grep -v Skipping
  repomanage -k 2 --old ${REPO_STORAGE}/${REPONAME} | xargs sudo rm
  sudo createrepo_c --workers 2 --update -g ${REPO_STORAGE}/${REPONAME}/${REPONAME}/comps.xml ${REPO_STORAGE}/${REPONAME}/
}

cleanrepos() {
  sudo yum clean all
}

cleanrepos

syncrepo rhel-7-server-rpms
syncrepo rhel-7-server-extras-rpms
syncrepo rhel-7-server-ose-3.2-rpms
syncrepo rhel-ha-for-rhel-7-server-rpms

cleanrepos

exit 0


text:
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com

#ifndef _GLOBAL_H_
#define _GLOBAL_H_

class CJS_GlobalData;

struct js_global_data
{
	js_global_data()
	{
		nType = 0;
		dData = 0;
		bData = FALSE;
		sData = "";
		bPersistent = FALSE;
		bDeleted = FALSE;
	}

	~js_global_data()
	{
		pData.Reset();
	}
	int					nType; //0:int 1:bool 2:string 3:obj
	double				dData;
	bool				bData;
	CFX_ByteString		sData;
	v8::Persistent<v8::Object>  pData;
	bool				bPersistent;
	bool				bDeleted;
};

class global_alternate : public CJS_EmbedObj
{
public:
	global_alternate(CJS_Object* pJSObject);
	virtual ~global_alternate();

public:
	FX_BOOL						setPersistent(OBJ_METHOD_PARAMS);

public:
	FX_BOOL						QueryProperty(FX_LPCWSTR propname);
	FX_BOOL						DoProperty(IFXJS_Context* cc, FX_LPCWSTR propname, CJS_PropValue & vp, JS_ErrorString & sError);
	FX_BOOL						DelProperty(IFXJS_Context* cc, FX_LPCWSTR propname, JS_ErrorString & sError);

	void						Initial(CPDFDoc_Environment* pApp);

private:
	void						UpdateGlobalPersistentVariables();
	void						CommitGlobalPersisitentVariables();
	void						DestroyGlobalPersisitentVariables();
	FX_BOOL						SetGlobalVariables(FX_LPCSTR propname, int nType,
									double dData, bool bData, const CFX_ByteString& sData, JSObject pData, bool bDefaultPersistent);

	void						ObjectToArray(v8::Handle<v8::Object> pObj, CJS_GlobalVariableArray& array);
	void						PutObjectProperty(v8::Handle<v8::Object> obj, CJS_KeyValue* pData);

private:
	CFX_MapByteStringToPtr		m_mapGlobal;
	CFX_WideString				m_sFilePath;
	CJS_GlobalData*				m_pGlobalData;
	CPDFDoc_Environment*				m_pApp;
};

class CJS_Global : public CJS_Object
{
public:
	CJS_Global(JSFXObject pObject) : CJS_Object(pObject) {};
	virtual ~CJS_Global(void){};

	virtual FX_BOOL	InitInstance(IFXJS_Context* cc);

	DECLARE_SPECIAL_JS_CLASS(CJS_Global);

	JS_SPECIAL_STATIC_METHOD(setPersistent, global_alternate, global);

};

#endif //_GLOBAL_H_