text:
<Record>
<Term>General Anesthetics</Term>
<SemanticType>Pharmacologic Substance</SemanticType>
<ParentTerm>Anesthetics</ParentTerm>
<ClassificationPath>Chemical Actions and Uses/Pharmacologic Actions/Physiological Effects of Drugs/Central Nervous System Depressants/Anesthetics/Anesthetics, General</ClassificationPath>
<ClassificationPath>Chemical Actions and Uses/Pharmacologic Actions/Therapeutic Uses/Central Nervous System Agents/Central Nervous System Depressants/Anesthetics/Anesthetics, General</ClassificationPath>
<BroaderTerm>Therapeutic Uses</BroaderTerm>
<BroaderTerm>Pharmacologic Actions</BroaderTerm>
<BroaderTerm>Anesthetics, General</BroaderTerm>
<BroaderTerm>Anesthetics</BroaderTerm>
<BroaderTerm>Central Nervous System Depressants</BroaderTerm>
<BroaderTerm>Chemical Actions and Uses</BroaderTerm>
<BroaderTerm>Central Nervous System Agents</BroaderTerm>
<BroaderTerm>Physiological Effects of Drugs</BroaderTerm>
<ChildTerm>Anesthetics, Intravenous</ChildTerm>
<ChildTerm>Anesthetics, Inhalation</ChildTerm>
<Synonym>General Anesthetics</Synonym>
<Description>Agents that induce various degrees of analgesia; depression of consciousness, circulation, and respiration; relaxation of skeletal muscle; reduction of reflex activity; and amnesia. There are two types of general anesthetics, inhalation and intravenous. With either type, the arterial concentration of drug required to induce anesthesia varies with the condition of the patient, the desired depth of anesthesia, and the concomitant use of other drugs. (From AMA Drug Evaluations Annual, 1994, p.173)</Description>
<Source>MeSH</Source>
</Record>


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/menu_icon"
        android:layout_gravity="center"
        android:layout_width="18dp"
        android:layout_height="18dp"
        android:layout_marginTop="7dp"
        android:layout_marginBottom="3dp"
        android:src="@drawable/learn" />

    <TextView
        android:id="@+id/menu_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp"
        android:layout_marginBottom="7dp"
        android:layout_gravity="center"/>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
function fields() {
  $('.js-options input').change(function() {
    var check, type;
    type = $(this).attr('type');
    check = $(this).parent('label');
    if (type === 'checkbox') {
      check.toggleClass('checked');
    } else if (type === 'radio') {
      check.siblings('label').removeClass('checked');
      check.addClass('checked');
    }
  });
};


text:
package system

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"runtime"
	"testing"
	"time"

	"github.com/docker/docker/pkg/mount"
)

func TestEnsureRemoveAllNotExist(t *testing.T) {
	// should never return an error for a non-existent path
	if err := EnsureRemoveAll("/non/existent/path"); err != nil {
		t.Fatal(err)
	}
}

func TestEnsureRemoveAllWithDir(t *testing.T) {
	dir, err := ioutil.TempDir("", "test-ensure-removeall-with-dir")
	if err != nil {
		t.Fatal(err)
	}
	if err := EnsureRemoveAll(dir); err != nil {
		t.Fatal(err)
	}
}

func TestEnsureRemoveAllWithFile(t *testing.T) {
	tmp, err := ioutil.TempFile("", "test-ensure-removeall-with-dir")
	if err != nil {
		t.Fatal(err)
	}
	tmp.Close()
	if err := EnsureRemoveAll(tmp.Name()); err != nil {
		t.Fatal(err)
	}
}

func TestEnsureRemoveAllWithMount(t *testing.T) {
	if runtime.GOOS == "windows" {
		t.Skip("mount not supported on Windows")
	}

	dir1, err := ioutil.TempDir("", "test-ensure-removeall-with-dir1")
	if err != nil {
		t.Fatal(err)
	}
	dir2, err := ioutil.TempDir("", "test-ensure-removeall-with-dir2")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(dir2)

	bindDir := filepath.Join(dir1, "bind")
	if err := os.MkdirAll(bindDir, 0755); err != nil {
		t.Fatal(err)
	}

	if err := mount.Mount(dir2, bindDir, "none", "bind"); err != nil {
		t.Fatal(err)
	}

	done := make(chan struct{})
	go func() {
		err = EnsureRemoveAll(dir1)
		close(done)
	}()

	select {
	case <-done:
		if err != nil {
			t.Fatal(err)
		}
	case <-time.After(5 * time.Second):
		t.Fatal("timeout waiting for EnsureRemoveAll to finish")
	}

	if _, err := os.Stat(dir1); !os.IsNotExist(err) {
		t.Fatalf("expected %q to not exist", dir1)
	}
}


text:
package com.ryantenney.metrics.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * An annotation requesting that a metric be injected or registered.
 *
 *

 * Given a field like this:
 *

 *     {@literal @}Metric
 *     public Histogram histogram;
 *

 *

 * A meter of the field's type will be created and injected into Spring-managed beans after construction
 * but before initialization. It will be up to the user to interact with the metric. This annotation
 * can be used on fields of type Meter, Timer, Counter, and Histogram.
 *
 *

 * This may also be used to register a metric, which is useful for creating a histogram with
 * a custom Reservoir.
 *

 *

 *     {@literal @}Metric
 *     public Histogram uniformHistogram = new Histogram(new UniformReservoir());
 *

 *
 */
@Deprecated
@com.codahale.metrics.annotation.Metric
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Metric {

	/**
	 * The name of the metric.
	 */
	String name() default "";

	/**
	 * If {@code true}, use the given name as an absolute name. If {@code false}, use the given name
	 * relative to the annotated class.
	 */
	boolean absolute() default false;

}


text:
<?php

namespace app\models;

use Yii;
use yii\web\Controller;
use yii\web\HttpException;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use app\models\Posts;
use app\models\LoginForm;

/**
 * This is the model class for table "posts".
 *
 * @property integer $id
 * @property string $title
 * @property string $data
 * @property integer $create_time
 * @property integer $update_time
 */
class Posts extends \yii\db\ActiveRecord
{
    public $verifyCode;

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    ActiveRecord::EVENT_BEFORE_INSERT => ['create_time', 'update_time'],
                    ActiveRecord::EVENT_BEFORE_UPDATE => ['update_time'],
                ],
            ],
        ];
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'posts';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['title', 'data'], 'required'],
            [['data'], 'string'],
            [['create_time', 'update_time'], 'integer'],
            [['title'], 'string', 'max' => 255],
            // verifyCode needs to be entered correctly
            ['verifyCode', 'captcha'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', 'Title'),
            'data' => Yii::t('app', 'Data'),
            'create_time' => Yii::t('app', 'Create Time'),
            'update_time' => Yii::t('app', 'Update Time'),
            'verifyCode' => Yii::t('app', 'Verification Code'),
        ];
    }

}


text:
import $ from 'jquery';
require('jquery-ui');
require('geonames-server-jquery-plugin/jquery.geonames.js');
const geonames = {

        init: function ($field, options) {
            var geocompleter = $field.geocompleter(options);

            // On focus add select-state
            geocompleter.geocompleter('autocompleter', 'on', 'autocompletefocus', function (event, ui) {
                $('li', $(event.originalEvent.target)).closest('li').removeClass('selected');
                $('a.ui-state-active, a.ui-state-hover, a.ui-state-focus', $(event.originalEvent.target)).closest('li').addClass('selected');
            });

            // On search request add loading-state
            geocompleter.geocompleter('autocompleter', 'on', 'autocompletesearch', function (event, ui) {
                $(this).attr('autocomplete', 'false');
                $(this).addClass('input-loading');
                $(this).removeClass('input-error');
            });

            // On response remove loading-state
            geocompleter.geocompleter('autocompleter', 'on', 'autocompleteresponse', function (event, ui) {
                $(this).removeClass('input-loading');
            });

            // On close menu remove loading-state
            geocompleter.geocompleter('autocompleter', 'on', 'autocompleteclose', function (event, ui) {
                $(this).removeClass('input-loading');
            });

            // On request error add error-state
            geocompleter.geocompleter('autocompleter', 'on', 'geotocompleter.request.error', function (jqXhr, status, error) {
                $(this).removeClass('input-loading');
                $(this).addClass('input-error');
            });

            return geocompleter;
        }

};

export default geonames;


text:
/*
 * Generated by XDoclet - Do not edit!
 */
package org.dcm4chex.archive.ejb.interfaces;

/**
 * Local home interface for MWLItem.
 * @xdoclet-generated at ${TODAY}
 * @copyright The XDoclet Team
 * @author XDoclet
 * @version 2.19.0-SNAPSHOT
 */
public interface MWLItemLocalHome
   extends javax.ejb.EJBLocalHome
{
   public static final String COMP_NAME="java:comp/env/ejb/MWLItemLocal";
   public static final String JNDI_NAME="ejb/MWLItem";

   public org.dcm4chex.archive.ejb.interfaces.MWLItemLocal create(org.dcm4che.data.Dataset ds , org.dcm4chex.archive.ejb.interfaces.PatientLocal patient)
      throws javax.ejb.CreateException;

   public java.util.Collection findAll()
      throws javax.ejb.FinderException;

   public org.dcm4chex.archive.ejb.interfaces.MWLItemLocal findByRpIdAndSpsId(java.lang.String rpid, java.lang.String spsid)
      throws javax.ejb.FinderException;

   public java.util.Collection findByStudyIuid(java.lang.String suid)
      throws javax.ejb.FinderException;

   public org.dcm4chex.archive.ejb.interfaces.MWLItemLocal findByPrimaryKey(java.lang.Long pk)
      throws javax.ejb.FinderException;

}


text:
Jenkins-dummy: just a dummy project to test different functionalities of Jenkins.

## TODO

* Back-end continuous test (OK)
* Front-end continuous test
* Deployment
* Code coverage
* API doc generation


text:
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <freerdp/log.h>
#include <freerdp/codec/dsp.h>
#include "shadow.h"

#include "shadow_audin.h"
#include <freerdp/server/server-common.h>

#define TAG SERVER_TAG("shadow")

/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT AudinServerOpening(audin_server_context* context)
{
	AUDIO_FORMAT* agreed_format = NULL;
	size_t i = 0, j = 0;

	for (i = 0; i < context->num_client_formats; i++)
	{
		for (j = 0; j < context->num_server_formats; j++)
		{
			if (audio_format_compatible(&context->server_formats[j], &context->client_formats[i]))
			{
				agreed_format = &context->server_formats[j];
				break;
			}
		}

		if (agreed_format != NULL)
			break;
	}

	if (agreed_format == NULL)
	{
		WLog_ERR(TAG, "Could not agree on a audio format with the server\n");
		return CHANNEL_RC_OK;
	}

	return IFCALLRESULT(ERROR_CALL_NOT_IMPLEMENTED, context->SelectFormat, context, i);
}
/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT AudinServerOpenResult(audin_server_context* context, UINT32 result)
{
	WLog_INFO(TAG, "AUDIN open result %"PRIu32".\n", result);
	return CHANNEL_RC_OK;
}
/**
 * Function description
 *
 * @return 0 on success, otherwise a Win32 error code
 */
static UINT AudinServerReceiveSamples(audin_server_context* context, const AUDIO_FORMAT* format,
                                      wStream* buf, size_t nframes)
{
	rdpShadowClient* client = (rdpShadowClient*)context->data;
	rdpShadowSubsystem* subsystem = client->server->subsystem;

	if (!client->mayInteract)
		return CHANNEL_RC_OK;

	if (!IFCALLRESULT(TRUE, subsystem->AudinServerReceiveSamples, subsystem, client, format, buf,
	                  nframes))
		return ERROR_INTERNAL_ERROR;

	return CHANNEL_RC_OK;
}

BOOL shadow_client_audin_init(rdpShadowClient* client)
{
	audin_server_context* audin;
	audin = client->audin = audin_server_context_new(client->vcm);

	if (!audin)
		return FALSE;

	audin->data = client;

	if (client->subsystem->audinFormats)
	{
		size_t x;
		audin->server_formats = audio_formats_new(client->subsystem->nAudinFormats);

		if (!audin->server_formats)
			goto fail;

		for (x = 0; x < client->subsystem->nAudinFormats; x++)
		{
			if (!audio_format_copy(&client->subsystem->audinFormats[x], &audin->server_formats[x]))
				goto fail;
		}

		audin->num_server_formats = client->subsystem->nAudinFormats;
	}
	else
	{
		audin->num_server_formats = server_audin_get_formats(&audin->server_formats);
	}

	if (audin->num_server_formats < 1)
		goto fail;

	audin->dst_format = &audin->server_formats[0];
	audin->Opening = AudinServerOpening;
	audin->OpenResult = AudinServerOpenResult;
	audin->ReceiveSamples = AudinServerReceiveSamples;
	return TRUE;
fail:
	audin_server_context_free(audin);
	client->audin = NULL;
	return FALSE;
}

void shadow_client_audin_uninit(rdpShadowClient* client)
{
	if (client->audin)
	{
		audin_server_context_free(client->audin);
		client->audin = NULL;
	}
}


text:
/*
 * This library is distributed under a modified BSD license.  See the included
 * LICENSE file for details.
 */
package org.fife.ui.rtextarea;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * Unit tests for the {@link RTextAreaEditorKit.BeepAction} class.
 *
 * @author Robert Futrell
 * @version 1.0
 */
class RTextAreaEditorKitBeepActionTest {

	@Test
	void testActionPerformedImpl() {
		new RTextAreaEditorKit.BeepAction().actionPerformedImpl(null, null);
	}

	@Test
	void testGetMacroID() {
		Assertions.assertEquals(RTextAreaEditorKit.beepAction, new RTextAreaEditorKit.BeepAction().getMacroID());
	}
}


text:
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->

- [Documentation](#documentation)
  - [Reliability section rough draft](#reliability-section-rough-draft)
- [Prover](#prover)
- [Guidelines](#guidelines)
- [Research](#research)

<!-- END doctoc generated TOC please keep comment here to allow auto update -->

# Documentation
- Clarify/document at-least-once versus at-most-once decrement reliability guarantees.
- Documentation builder with TOC generator, reponame substituter?.
	- Where to keep the canonical sources of truth?
- Various inline TODOs in documentation.
- Hyperlink amqp operations to the spec.
- Typocheck.
- "See also" section additions.
- Github local-repo anchors?s.

## Reliability section rough draft

Existing lock implementations rely on message delivery to the client. This causes problems if the network connection is broken between the client and RabbitMQ; without heartbeats or other AMQP operations on the connection, a client cannot easily verify that its lock is still held.

Using [amqp-locks](https://github.com/zbentley/amqp-locks) implementations, it is possible to ensure that, given a single RabbitMQ broker (not necessarily a clustered HA set; that's a [[separate can of worms]]), a lock is relinquished on the server when  (or shortly after) the server realizes that it has lost connection to the client, and will be relinquished on the client the next time it polls the availability of the lock, unless the connection is restored before the server has registered the client's absence.

Note that these assertions should be considered *speculative* so long as [amqp-locks](https://github.com/zbentley/amqp-locks) and its associated spec and proof tool are considered a work in progress. Distributed computing/locking is fraught, and until I've tested these assertions more thoroughly with [[jepsen]] or something, skepticism should be the default assumption.

# Prover
- Make prover.
	- What platform? Language doesn't matter, but ability to coordinate tests in a concurrent way does. Node is out (it DGAF when backgrounded things happen, so long as they do). Java? Clojure? Basically anything that supports the old-college-try approach to "make these two executions happen as close to simultaneously as possible".
- Jepsen? Or similar? Might just be able to repurpose the one from the rabbitmq-semaphore evisceration.

# Guidelines
- Optimized mutex with publish-then-consume on a single queue, rather than publish-then-declare-another-exclusive-queue.
- Transactions instead of publish confirms, then update doc to be generic AMQP.

# Research
- Play with old-style semaphore operations using a passive queue declare (to check consumer counts) followed by an exclusive consume to acquire a lock; one per queue.
- Play with old-style semaphore operations using a decrement lock with AUTODELETE set, such that publish-then-consume holders of the decrement lock can crash after decrementing without risking multiple decrements (in exchange for risking failed decrements; you have to choose one).
- Given a recv-based semaphore, what happens if the connection is dropped and reconnected without heartbeats?
- What happens if a consumed queue is deleted with/without heartbeats? What does the client see? Add whatever frame gets sent into the OOB examples in the parenthetical inthe "Verify problems" section.
- Are queue.declares (passive or not) more or less expensive than basic.publishes as lock-still-exists queries? If more expensive, add 'It is also marginally more expensive than the verification mechanism of [amqp-locks](https://github.com/zbentley/amqp-locks) implementations (basic.publish and confirm).' to the "Verify problems" section.
- Expirations can maybe be used to indicate to the server that a lock is no longer held?
- What happens if a connection drops, server deletes B queue, new holder acquires it, connection resumes, lock holder tries to publish to B queue? Add a UID queue? Or a consume?
- Check hard to measure assertion: if a client fills up its QoS, does it always immediately dissapear from the consumer count in queue.declare?
- Play with the LVE plugin to make last-acquired-lock data available to future semaphore acquirers to speed up acquiry in the future (this is an optimization; fallback must be available).


text:
/******************************************************************************
 * random.h
 *
 * A really simple random-number generator. Crappy linear congruential
 * taken from glibc, but has at least a 2^32 period.
 */

#ifndef __RANDOM_H__
#define __RANDOM_H__

typedef unsigned long rand_t;

#define rand_init(_ptst) \
    ((_ptst)->rand = RDTICK())

#define rand_next(_ptst) \
    ((_ptst)->rand = ((_ptst)->rand * 1103515245) + 12345)

#endif /* __RANDOM_H__ */


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>com.cyc.baseclient.exception (Core Client Implementation 1.1.1 API)</title>
<meta name="date" content="2018-01-24">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Cyc Core Client Implementation

Prev Package

Next Package

Frames

No Frames

All Classes

Package com.cyc.baseclient.exception

Base Client exception hierarchy; this code is not supported for external developers.

See: Description

Exception Summary

Exception
Description

CfaslInputStreamClosedException

Class CfaslInputStreamClosedException indicates that the peer (usually the Cyc server)
 closed the socket connection.

CommException

CycApiClosedConnectionException

CycApiInvalidObjectException

Class CycApiInvalidObjectException indicates that an invalid object of
 some sort was detected during a Cyc API call that occurred on the Cyc
 server.

CycApiServerSideException

Class CycApiServerException indicates an error condition during
 a Cyc API call that occurred on the Cyc server.

CycIoException

Class CycApiException indicates an error condition during a Cyc API call.

CycKbContentException

Class CycKBContentException indicates that there is some problem with
 the knowledge currently stored in the KB.

CycParseException

ParseException is designed to...

CycTaskInterruptedException

Implements an exception class for notification when a Cyc server
 communication has timed out.

CycUnknownHostException

Class CycApiException indicates an error condition during a Cyc API call.

ExportException

General class for exceptions thrown during export.

Package com.cyc.baseclient.exception Description

Base Client exception hierarchy; this code is not supported for external developers.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Cyc Core Client Implementation

Prev Package

Next Package

Frames

No Frames

All Classes

Copyright © 2013–2018 Cycorp, Inc. All rights reserved.


text:
'use strict';

var debug = require('../debug');

/**
 * Set options. This is the API-equivalent of calling `app.option('foo', 'bar')`.
 *
 * ```sh
 * $ app --option=foo:bar
 * ```
 * @name option
 * @api public
 */

module.exports = function(app) {
  return function(val, key, config, next) {
    debug.field(key, val);
    app.option(val);
    next();
  };
};


text:
{{{
  "title": "CenturyLink Cloud Public Blueprint Packages",
  "date": "04-24-2015",
  "author": "Bryan Friedman",
  "attachments": [],
  "contentIsHTML": false
}}}

### Description
Below is a list of public packages that have been made available on the CenturyLink Cloud. For information on deploying them, follow the instructions for [Using Group Tasks to Install Software and Run Scripts on Groups](../Servers/using-group-tasks-to-install-software-and-run-scripts-on-groups.md). In some cases, the package listing below links to another article with more details on how to use that specific package. If you have a package that might be useful for public consumption, please refer to [Creating Public Blueprint Packages](../Blueprints/creating-public-blueprint-packages.md) for more information on how to do this.

### Windows Packages
- Install .NET Framework 4.5 on Windows
- [Install Active Directory on Windows 2012 (1 of 2) \[Primary Node\]](../Blueprints/deploy-microsoft-windows-2012-active-directory-domain-services.md)
- [Install Active Directory on Windows 2012 (2 of 2) \[Secondary Node\]](../Blueprints/deploy-microsoft-windows-2012-active-directory-domain-services.md)
- Install Active Directory on Windows 2008 (1 of 2) [Primary Node]
- Install Active Directory on Windows 2008 (2 of 2) [Secondary Node]
- [Install File and iSCSI Services on Windows](../Blueprints/Install-File-and-iSCSI-Services-on-Windows.md)
- [Install IIS 7.5 on Windows](../Blueprints/Install-IIS-on-Windows.md)
- [Install IIS 8 on Windows](../Blueprints/Install-IIS-on-Windows.md)
- Install SQL 2012 Client Connectivity Tools on Windows
- [Install SQL Server on Windows](../Blueprints/deploy-microsoft-sql-server-using-blueprint.md)
- [Perform Active Directory Domain Join on Windows](../Blueprints/perform-active-directory-domain-join-on-windows.md)
- Perform PowerShell Remoting Enablement on Windows

### Linux Packages
- Install Cassandra on Linux (1 of 3) [Base Install]
- Install Cassandra on Linux (2 of 3) [Node 0]
- Install Cassandra on Linux (3 of 3) [Join Cluster]
- [Install CoreOS (1 of 2) \[Configure PXE-DHCP\]](../Servers/building-coreos-server-cluster-on-the-centurylink-cloud.md)
- [Install CoreOS (2 of 2) \[Base Install\]](../Servers/building-coreos-server-cluster-on-the-centurylink-cloud.md)
- [Install CoreOS (2 of 2) \[With Panamax\]](../Servers/building-coreos-server-cluster-on-the-centurylink-cloud.md)
- [Install Docker on CentOS](../Blueprints/using-docker-on-centurylink-cloud-servers.md)
- [Install Docker on Ubuntu](../Blueprints/using-docker-on-centurylink-cloud-servers.md)
- [Install Google PerfKit Benchmarker on Ubuntu](../Blueprints/installing-google-perfkit-benchmarker.md)
- Install Gerrit on Linux
- Install Jenkins on Linux
- [Install LAMP Stack on Ubuntu/Debian](../Blueprints/installing-lamp-stack-on-centurylink-cloud-servers.md)
- [Install LAMP Stack on CentOS/RedHat](../Blueprints/installing-lamp-stack-on-centurylink-cloud-servers.md)
- Install Riak on Linux (1 of 2) [Base Install]
- Install Riak on Linux (2 of 2) [Join Cluster]
- Perform General Availability Update on RedHat-CentOS
- Perform General Availability Update on Ubuntu-Debian


text:
    template <typename _Object\
>

#define CStateChimeraHuntingMoveToCoverAbstract CStateChimeraHuntingMoveToCover<_Object>

TEMPLATE_SPECIALIZATION
CStateChimeraHuntingMoveToCoverAbstract::CStateChimeraHuntingMoveToCover(_Object* obj)
    : inherited(obj) {}

TEMPLATE_SPECIALIZATION
bool CStateChimeraHuntingMoveToCoverAbstract::check_start_conditions() { return true; }

TEMPLATE_SPECIALIZATION
bool CStateChimeraHuntingMoveToCoverAbstract::check_completion() { return false; }

TEMPLATE_SPECIALIZATION
void CStateChimeraHuntingMoveToCoverAbstract::reselect_state() {
    if (prev_substate == u32(-1))
        select_state(eStateMoveToCover);
    else if (prev_substate == eStateMoveToCover)
        select_state(eStateComeOut);
    else
        select_state(eStateMoveToCover);
}

#undef TEMPLATE_SPECIALIZATION
#undef CStateChimeraHuntingMoveToCoverAbstract


text:
/* Index management handlers. */
package v3

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"
)

func Index(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	var col, path string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "path", &path) {
		return
	}
	V3Sync.Lock()
	defer V3Sync.Unlock()
	dbcol := V3DB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	if err := dbcol.Index(strings.Split(path, ",")); err != nil {
		http.Error(w, fmt.Sprint(err), 400)
		return
	}
	w.WriteHeader(201)
}

func Indexes(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	var col string
	if !Require(w, r, "col", &col) {
		return
	}
	V3Sync.Lock()
	defer V3Sync.Unlock()
	dbcol := V3DB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	indexes := make([]string, 0)
	for path := range dbcol.SecIndexes {
		indexes = append(indexes, path)
	}
	resp, err := json.Marshal(indexes)
	if err != nil {
		http.Error(w, fmt.Sprint("Server error."), 500)
		return
	}
	w.Write(resp)
}

func Unindex(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Cache-Control", "must-revalidate")
	w.Header().Set("Content-Type", "application/json")
	var col, path string
	if !Require(w, r, "col", &col) {
		return
	}
	if !Require(w, r, "path", &path) {
		return
	}
	V3Sync.Lock()
	defer V3Sync.Unlock()
	dbcol := V3DB.Use(col)
	if dbcol == nil {
		http.Error(w, fmt.Sprintf("Collection '%s' does not exist.", col), 400)
		return
	}
	if err := dbcol.Unindex(strings.Split(path, ",")); err != nil {
		http.Error(w, fmt.Sprint(err), 400)
		return
	}
}


text:
package hudson.security.csrf;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import org.jvnet.hudson.test.Bug;
import org.jvnet.hudson.test.HudsonTestCase;

/**
 *
 * @author dty
 */
public class DefaultCrumbIssuerTest extends HudsonTestCase {
    protected void setUp() throws Exception {
        super.setUp();
        assertNotNull(jenkins);
        CrumbIssuer issuer = new DefaultCrumbIssuer(false);
        assertNotNull(issuer);
        jenkins.setCrumbIssuer(issuer);
    }

    private static final String[] testData = {
        "10.2.3.1",
        "10.2.3.1,10.20.30.40",
        "10.2.3.1,10.20.30.41",
        "10.2.3.3,10.20.30.40,10.20.30.41"
    };
    private static final String HEADER_NAME = "X-Forwarded-For";

    @Bug(3854)
    public void testClientIPFromHeader() throws Exception {
        WebClient wc = new WebClient();

        wc.addRequestHeader(HEADER_NAME, testData[0]);
        HtmlPage p = wc.goTo("configure");
        submit(p.getFormByName("config"));
    }

    @Bug(3854)
    public void testHeaderChange() throws Exception {
        WebClient wc = new WebClient();

        wc.addRequestHeader(HEADER_NAME, testData[0]);
        HtmlPage p = wc.goTo("configure");

        wc.removeRequestHeader(HEADER_NAME);
        try {
            // The crumb should no longer match if we remove the proxy info
            submit(p.getFormByName("config"));
        }
        catch (FailingHttpStatusCodeException e) {
            assertEquals(403,e.getStatusCode());
        }
    }

    @Bug(3854)
    public void testProxyIPChanged() throws Exception {
        WebClient wc = new WebClient();

        wc.addRequestHeader(HEADER_NAME, testData[1]);
        HtmlPage p = wc.goTo("configure");

        wc.removeRequestHeader(HEADER_NAME);
        wc.addRequestHeader(HEADER_NAME, testData[2]);

        // The crumb should be the same even if the proxy IP changes
        submit(p.getFormByName("config"));
    }

    @Bug(3854)
    public void testProxyIPChain() throws Exception {
        WebClient wc = new WebClient();

        wc.addRequestHeader(HEADER_NAME, testData[3]);
        HtmlPage p = wc.goTo("configure");
        submit(p.getFormByName("config"));
    }

    @Bug(7518)
    public void testProxyCompatibilityMode() throws Exception {
        CrumbIssuer issuer = new DefaultCrumbIssuer(true);
        assertNotNull(issuer);
        jenkins.setCrumbIssuer(issuer);

        WebClient wc = new WebClient();
        wc.addRequestHeader(HEADER_NAME, testData[0]);
        HtmlPage p = wc.goTo("configure");

        wc.removeRequestHeader(HEADER_NAME);
        // The crumb should still match if we remove the proxy info
        submit(p.getFormByName("config"));
   }
}


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

namespace StackOverflowData.Models
{
    public partial class UserBadge
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int UserId { get; set; }
        public System.DateTime Date { get; set; }
    }
}


text:
layout: post
title: on behavioural economics
description: a very very very incomplete definition
date: 2017-11-03
comments: true
---

***this post is incomplete***

### Problem: People repeatedly make decisions that undermine their own long term well being.

### Solution: Give people the satisfaction they need in the short term *and* the outcomes that want in the long term.

Human don't make good decisions.

1. Health
	- Stop smoking
	- Exercise more
2. Education
	- Study better
	- Teach better
	- Learn better
3. Personal Finance
	- Save more money

Example:
- The Nudge Unit in the UK government.

Leading People:
- Danny Kahneman
- Amos Tversky
- Richard Thaler
- Nassim Taleb


text:
namespace chrome {

WindowOpenDisposition DispositionFromEventFlags(int event_flags) {
  return disposition_utils::DispositionFromClick(
      (event_flags & ui::EF_MIDDLE_MOUSE_BUTTON) != 0,
      (event_flags & ui::EF_ALT_DOWN) != 0,
      (event_flags & ui::EF_CONTROL_DOWN) != 0,
      (event_flags & ui::EF_COMMAND_DOWN) != 0,
      (event_flags & ui::EF_SHIFT_DOWN) != 0);
}

}  // namespace chrome


text:
/**
 * @file This file initializes a simple trace unit which listens to
 * a probe point in the fetch and commit stage of the O3 pipeline
 * and simply outputs those events as a dissassembled instruction stream
 * to the trace output.
 */
#ifndef __CPU_O3_PROBE_SIMPLE_TRACE_HH__
#define __CPU_O3_PROBE_SIMPLE_TRACE_HH__

#include "cpu/o3/dyn_inst_ptr.hh"
#include "params/SimpleTrace.hh"
#include "sim/probe/probe.hh"

namespace gem5
{

namespace o3
{

class SimpleTrace : public ProbeListenerObject
{

  public:
    SimpleTrace(const SimpleTraceParams &params) :
        ProbeListenerObject(params)
    {
    }

    /** Register the probe listeners. */
    void regProbeListeners() override;

    std::string
    name() const override
    {
        return ProbeListenerObject::name() + ".trace";
    }

  private:
    void traceFetch(const DynInstConstPtr& dynInst);
    void traceCommit(const DynInstConstPtr& dynInst);

};

} // namespace o3
} // namespace gem5

#endif//__CPU_O3_PROBE_SIMPLE_TRACE_HH__


text:
@interface PodsDummy_JYCarousel : NSObject
@end
@implementation PodsDummy_JYCarousel
@end


text:
package fr.insee.stamina.utils;

import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.rdf.model.Resource;

/**
 * Vocabulary definition for the CSPA ontology.
 */
public class CSPAOnto {
	/**
	 * The RDF model that holds the CSPA entities
	 */
	public static Model model = ModelFactory.createDefaultModel();
	/**
	 * The namespace of the CSPA vocabulary as a string
	 */
	public static final String uri = "http://rdf.unece.org/ontologies/hlg#";
	/**
	 * Returns the namespace of the CSPA vocabulary as a string.
	 *
	 * @return The namespace of the CSPA vocabulary.
	 */
	public static String getURI() {
		return uri;
	}
	/**
	 * The namespace of the CSPA vocabulary
	 */
	public static final Resource NAMESPACE = model.createResource(uri);

	/* #################### *
	 * Defines CSPA Classes *
	 * #################### */

	public static final Resource StatisticalActivity = model.createResource(uri + "StatisticalActivity");
	public static final Resource StatisticalActivityArea = model.createResource(uri + "StatisticalActivityArea");

}


text:
import java.util.Stack;

public class GraphicalCombiningTree {
	Node[] leaf;

	public GraphicalCombiningTree(int width) {
		Node[] nodes = new Node[width - 1];
		nodes[0] = new Node();
		for (int i = 1; i < nodes.length; i++)
			nodes[i] = new Node(nodes[(i - 1) / 2]);

		leaf = new Node[(width + 1) / 2];
		for (int i = 0; i < leaf.length; i++)
			leaf[i] = nodes[nodes.length - i - 1];
	}

	public int getAndIncrement() throws PanicException {
		Stack<Node> nodeStack = new Stack<Node>();
		Node myLeaf = leaf[((CountingThread) Thread.currentThread())
				.getThreadId() / 2];
		Node node = myLeaf;

		/* pre-combining phase */
		while(node.precombine())
			node = node.parent;

		Node stopNode = node;

		/* combining phase */
		node = myLeaf;
		int combined = 1;
		while(node != stopNode) {
			combined = node.combine(combined);
			nodeStack.push(node);
			node = node.parent;
		}

		/* operation phase */
		int prior = stopNode.op(combined);

		/* distribution phase */
		while(!nodeStack.isEmpty()) {
			node = nodeStack.pop();
			node.distribute(prior);
		}

		return prior;
	}
}


text:
var Backbone = require('backbone');
var _ = require('underscore');

var ItemView = require('./item-view');

var ResultsView = Backbone.View.extend({
	tagName: 'div',
	className: 'bb-autocomplete-results',
	initialize: function initialize(options) {
		this.views = [];
		this.viewsByModel = {};
		this.searchField = options.searchField;
		this.collection = options.collection;
		this.parentView = options.parentView;
		this.noResultsText = options.noResultsText || 'No results';
		this.on('show', this.show, this);
		this.on('hide', this.hide, this);

		var moveUp = _.bind(this.moveHighlight, this, -1);
		var moveDown = _.bind(this.moveHighlight, this, 1);
		this.on('up', moveUp);
		this.on('down', moveDown);
		this.on('highlight', this.highlight, this);
		this.on('chosen', function(model) {
			this.parentView.trigger('chosen', model);
		}, this);
		this.collection.on('reset', this.render, this);
	},

	show: function show() {
		this.$el.removeClass('hidden');
	},
	hide: function hide() {
		this.$el.addClass('hidden');
	},
	resetHighlightIndex: function resetHighlightIndex() {
		this.removeHighlights();
		this.highlightIndex = false;
		if (this.collection.length === 0) {
			var localisedWarning = this.noResultsText;
			this.$el.html('' + localisedWarning + '');
		}
	},
	removeHighlights: function removeHighlights() {
		this.$el.find('.highlight').removeClass('highlight');
	},
	highlight: function(model) {
		this.removeHighlights();
		model = model || this.collection.at(this.highlightIndex);
		var viewToHighlight = this._getViewByModel(model);
		if (viewToHighlight) {
			viewToHighlight.$el.addClass('highlight');
			this.highlightIndex = this.collection.indexOf(model);
			this.parentView.trigger('highlight', model);
		}
	},
	moveHighlight: function(direction) {
		if (this.collection.length === 0) {
			// do nothing as we have no results
			return;
		}

		if (this.highlightIndex === false) {
			if (direction < 0) {
				this.highlightIndex = this.collection.length - 1;
			} else if (direction > 0) {
				this.highlightIndex = 0;
			}
		} else {

			this.highlightIndex += direction;

			if (this.highlightIndex < 0) {
				this.highlightIndex = this.collection.length - 1;
			} else if (this.highlightIndex >= this.collection.length) {
				this.highlightIndex = 0;
			}

		}

		this.highlight();
	},
	_getViewByModel: function(model) {
		return this.viewsByModel[model.cid];
	},
	_createItemView: function(model) {
		var itemView = new ItemView({
			searchField: this.searchField,
			model: model,
			parentView: this
		});
		this.viewsByModel[model.cid] = itemView;
		return itemView;
	},
	_removeItemView: function() {

	},
	render: function render() {
		this.resetHighlightIndex();
		var views = this.views;
		_.invoke(views, 'remove');
		this.$el.empty();
		var frag = document.createDocumentFragment();

		this.collection.each(function(model) {
			var result = this._createItemView(model);
			result.render();
			frag.appendChild(result.el);
			this.views.push(result);
		}.bind(this));
		this.$el.append(frag);

	}
});

module.exports = ResultsView;


text:
[![Build Status](https://travis-ci.org/mg6maciej/parcelable-test-support.svg?branch=master)](https://travis-ci.org/mg6maciej/parcelable-test-support)

Small library to help with testing Parcelable classes.

Testing `Parcelable` classes is simple. You just need to write your object to `Parcel` and then recreate it.

It looks like this:

```
MyUberParcelable original = ...
Parcel parcel = Parcel.obtain();
original.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
MyUberParcelable reparceled = MyUberParcelable.CREATOR.createFromParcel(parcel);
// assert that reparceled is equal to original
```

## So why would I need a library for this?

First of all, the code above is boilerplate. And if you are like me, you might not like writing boilerplate.

Next thing, assertion code is omitted in this example. You would have to provide `equals` implementation.
For simple objects, it's not a problem, but what if you have a `Map<String, List<OtherParcelable>`? Moar boilerplate!
And what if you already have `equals` implementation used in production ocde that is only comparing on `id` field?
Reflection would be your friend. Fortunatelly there are libraries using reflection to check for equality.

This library uses reflection to check for equality for you.

Now if you already have in your `test` or `androidTest` directory factory classes, which are used by API stubs for functional testing,
you may think of not creating new objects and instead using objects returned from these factories.

Let's look at simple example of such factory:

```
public class SimpleFactory {

    public static Simple withZero() {
        return new Simple(0);
    }

    public static Simple withPerfectNumber() {
        return new Simple(6);
    }

    public static Simple withMaxValue() {
        return new Simple(Integer.MAX_VALUE);
    }
}
```

To reuse them in `Parcelable` implementation tests, you would have to call each method, save returned object in a list
and then loop over them with the code at the top of this page. Sounds like boilerplate? Bleh!

Not to mention, when someone adds new function here, it won't be used in tests. Again reflection would be your friend.

This library has all this: hidden boilerplate and reflection, so you don't have to write or see it again.

## OK, I'm in. What's the API?

When you want to test a single object:

```
// given
Simple simple = new Simple(6);
// when
ReparcelingResult<Simple> result = new Reparceler().reparcel(simple);
// then
assertTrue(result.areEqual());
```

When you have a factory like the `SimpleFactory` above:

```
// when
ReparcelingResultList<Simple> resultList = new FactoryReparceler().reparcel(SimpleFactory.class);
// then
assertTrue(resultList.areAllEqual());
```

Want more? Check [tests](https://github.com/mg6maciej/parcelable-test-support/tree/master/src/androidTest/java/pl/mg6/testsupport).

### Assertion failed. What's next?

`ReparcelingResult` has all the useful information to find out the cause of the issue:
* original `Parcelable`; might be useful if you use `FactoryReparceler` and not creating objects on your own,
* reparceled `Parcelable`; always useful to see the differences,
* method name; in case when `FactoryReparceler` is used, you know where to look,
* and error; for when parceling totally failed, e.g. `CREATOR` field is missing, `writeToParcel` or `createFromParcel` thrown an exception.

`ReparcelingResultList` allows you to get a subset of `ReparcelingResult`s where something wrong happened:

```
for (ReparcelingResult<Simple> issue : resultList.getIssues()) {
    String methodName = issue.getMethodName();
    // ...
}
```

## How do I add it to my project?

```
dependencies {
    androidTestCompile 'TODO: put it somewhere'
}
```

## License

Parcelable Test Support is a free software and may be used under the terms specified in the [LICENSE](LICENSE) file.


text:
package com.mystruts;

import java.io.File;
import org.apache.commons.io.FileUtils;
import java.io.IOException;

import com.opensymphony.xwork2.ActionSupport;

public class upload extends ActionSupport{
	   /**
	 *
	 */
	private static final long serialVersionUID = 1L;
		private File myFile;
	   private String myFileContentType;
	   private String myFileFileName;
	   private String destPath;

	   public String execute()
	   {
	      /* Copy file to a safe location */
	      destPath = "D:/Struts2/apache-tomcat-7.0.65/work/";

	      try{
	     	 System.out.println("Dst File name: " + myFileFileName);

	     	 File destFile  = new File(destPath, myFileFileName);
	    	 FileUtils.copyFile(myFile, destFile);

	      }catch(IOException e){
	         e.printStackTrace();
	         return ERROR;
	      }

	      return SUCCESS;
	   }

	   public File getMyFile() {
		return myFile;
	}

	   public String getMyFileContentType() {
		return myFileContentType;
	}

	   public String getMyFileFileName() {
		return myFileFileName;
	}

	   public String getDestPath() {
		return destPath;
	}

	   public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	   public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}
	   public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}

	   public void setDestPath(String destPath) {
		this.destPath = destPath;
	}

	}


text:
""" Average Gradient Optimizer
    - Accumulates a certain number of gradients, average them and then applies them to the variables
"""
import sys
assert 'tensorflow' in sys.modules, 'You need to import TF before importing this module.'

from diplomacy_research.utils.tensorflow import ops
from diplomacy_research.utils.tensorflow import clip_ops
from diplomacy_research.utils.tensorflow import control_flow_ops, gen_control_flow_ops
from diplomacy_research.utils.tensorflow import data_flow_ops
from diplomacy_research.utils.tensorflow import array_ops, gen_array_ops
from diplomacy_research.utils.tensorflow import ensure_finite
from diplomacy_research.utils.tensorflow import dtypes
from diplomacy_research.utils.tensorflow import math_ops, gen_math_ops
from diplomacy_research.utils.tensorflow import optimizer
from diplomacy_research.utils.tensorflow import state_ops
from diplomacy_research.utils.tensorflow import variable_scope

class AvgGradOptimizer(optimizer.Optimizer):
    """ Class to aggregate gradients and then apply them (by passing them to the optimizer.)

        The following accumulators/queue are created:

        * N `gradient accumulators`, one per variable to train. Gradients are pushed to them and will be averaged
            before being applied to variables.

        The optimizer adds nodes to the graph to collect gradients.

        For the Parameter Server job:

        1. An accumulator is created for each variable, and each replica pushes the gradients into the accumulators
            instead of directly applying them to the variables.
        2. Each accumulator averages all gradients when the chief requests the optimizer to apply the gradients.
        3. The global step is increased every time a gradient is pushed on the accumulator

        For the replicas:

        1. Start a step: fetch variables and compute gradients.
        2. Once the gradients have been computed, push them into gradient accumulators.
    """

    def __init__(self, opt, num_workers, is_chief, use_locking=False, max_gradient_norm=None,
                 name='avg_grad_optimizer'):
        """ Constructor
            :param opt: The actual optimizer that will be used to compute and apply the gradients
            :param num_workers: The number of workers sending gradients to the average accumulator.
            :param is_chief: Boolean that indicates if the current worker is the chief.
            :param use_locking: Boolean. If True use locks for update operation.
            :param max_gradient_norm: If set, the average gradients are also clipped by global norm.
            :param average_locally: Boolean. If set, only the workers variables are averaged.
            :param name: Optional name of the returned operation.
            :type opt: optimizer.Optimizer
        """
        super(AvgGradOptimizer, self).__init__(use_locking=use_locking, name=name)
        self._optimizer = opt
        self._num_workers = num_workers
        self._is_chief = is_chief or num_workers == 1
        self._use_locking = use_locking
        self._max_gradient_norm = max_gradient_norm
        self._accumulators = {}                         # var_name: (var, accumulator, device)
        self._finalized = False

        self._local_step = None
        self._global_step = None
        self._sync_token_queue = None

        self.local_step_init_op = None                  # Does local_step = global_step
        self.chief_init_op = None
        self._apply_grad_op = None                      # Chief - Applies gradient

    def compute_gradients(self, *args, **kwargs):
        """ Compute gradients of 'loss' for the variables in 'var_list'

            This simply wraps the compute_gradients() from the real optimizer. The gradients will be aggregated in
            the apply_gradients() so that user can modify the gradients like clipping with per replica global norm
            if needed. The global norm with aggregated gradients can be bad as one replica's huge gradients can hurt
            the gradients from other replicas.

            :return: A list of (gradient, variable) pairs
        """
        # pylint: disable=arguments-differ
        return self._optimizer.compute_gradients(*args, **kwargs)

    def apply_gradients(self, grads_and_vars, global_step=None, name=None):
        """ Accumulates gradients for the variables and stores them in the accumulator

            Note: This does not update the variables, it just accumulate the gradients

            :param grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients()
            :param global_step: Optional variable to increment by one after the variables have been updated.
            :param name: Optional name for the returned op. Default to name passed to the optimizer constructor.
            :return: The training operation to be run by each replica

            Raises - ValueError if the grads_and_vars is empty
                   - ValueError if global step is not provided
                   - ValueError if update() has already been called
        """
        # Making sure grads_and_var and global_step are provided
        if not grads_and_vars:
            raise ValueError('Must supply at least one variable.')
        if not global_step:
            raise ValueError('You must provide a global_step variable')
        if self._finalized:
            raise ValueError('The optimizer has been finalized. You cannot call this method after update().')

        train_ops = []
        accumulated_grad = []
        var_list = []
        chief_init_ops = []
        self._global_step = global_step

        # Colocating local step to prevent it from being placed on the parameter server
        local_anchor = gen_control_flow_ops.no_op()
        with ops.device(local_anchor.device):
            self._local_step = variable_scope.variable(initial_value=0,
                                                       trainable=False,
                                                       collections=[ops.GraphKeys.LOCAL_VARIABLES],
                                                       dtype=global_step.dtype.base_dtype,
                                                       name='sync_rep_local_step')

        # Setting initial step
        self.local_step_init_op = state_ops.assign(self._local_step, global_step)
        chief_init_ops += [self.local_step_init_op]

        with ops.name_scope(None, self._name):

            # Creating accumulators
            for grad, var in grads_and_vars:
                var_list += [var]
                with ops.device(var.device):

                    # No gradient - Pass-Through
                    if grad is None:
                        accumulated_grad += [None]
                        continue

                    # Sparse Variable - Accumulating over the dense shape
                    elif isinstance(grad, ops.IndexedSlices):
                        grad_accum = self._create_sparse_accumulator(var, grad)
                        train_ops += [grad_accum.apply_indexed_slices_grad(grad, local_step=self._local_step)]
                        accumulated_grad += [self._take_sparse_grad(grad_accum, grad)]
                        chief_init_ops += [grad_accum.set_global_step(global_step, name='SetGlobalStep')]

                    # Dense Variable
                    elif isinstance(grad, ops.Tensor):
                        grad_accum = self._create_dense_accumulator(var, grad)
                        train_ops += [grad_accum.apply_grad(grad, local_step=self._local_step)]
                        accumulated_grad += [self._take_dense_grad(grad_accum, grad)]
                        chief_init_ops += [grad_accum.set_global_step(global_step, name='SetGlobalStep')]

                    # Unknown
                    else:
                        raise RuntimeError('Unsupported gradient type.')

            # Building update_op
            with ops.device(self._global_step.device), ops.name_scope(''):
                accumulated_grad = [ensure_finite(gradient) for gradient in accumulated_grad]
                if self._max_gradient_norm:
                    accumulated_grad, _ = clip_ops.clip_by_global_norm(accumulated_grad, self._max_gradient_norm)
                self._apply_grad_op = self._optimizer.apply_gradients(zip(accumulated_grad, var_list), global_step)

            # Building chief init ops
            self.chief_init_op = control_flow_ops.group(*chief_init_ops)

            # Building train_op
            return control_flow_ops.group(*train_ops)

    def update(self, version_step=None):
        """ Performs the gradient averaging, updates the variables, and the global step
            :param version_step: A variable that represents the model's version
            :return: The update operation to be run by the chief

            Raises - ValueError if apply_gradients has not been calculated.
                   - ValueError if reset() has already been called.
        """
        if not self._accumulators or not self._global_step:
            raise ValueError('Should be called after apply_gradients().')
        if self._finalized:
            raise ValueError('The optimizer has been finalized. You cannot call this method after update().')

        self._finalized = True
        if self._num_workers == 1:
            return self._update_standalone(version_step=version_step)
        if self._is_chief:
            return self._update_distributed_as_chief(version_step=version_step)
        return self._update_distributed_as_worker()

    def init(self):
        """ Returns the operation to run to initialize the avg grad optimizer """
        return self.chief_init_op if self._is_chief else self.local_step_init_op

    def _update_standalone(self, version_step=None):
        """ Performs the gradient averaging, updates the variables, and the global step
            :param version_step: A variable that represents the model's version
            :return: The update operation to run

            Note: This method is called when there are no workers (no synchronization)
        """
        with ops.device(self._global_step.device), ops.name_scope(''):
            with ops.control_dependencies([self._apply_grad_op]):
                update_ops = [state_ops.assign(self._local_step, self._global_step)]

                # Increasing version step
                if version_step is not None:
                    update_ops += [state_ops.assign_add(version_step, 1)]

                # Returning
                return control_flow_ops.group(*update_ops)

    def _update_distributed_as_chief(self, version_step=None):
        """ Performs the gradient averaging, updates the variables, and the global step
            :param version_step: A variable that represents the model's version
            :return: The update operation to run

            Note: This method is called by the chief when synchronization is required.
        """
        # Creating sync_token queue
        with ops.device(self._global_step.device), ops.name_scope(''):
            self._sync_token_queue = data_flow_ops.FIFOQueue(capacity=-1,
                                                             dtypes=self._global_step.dtype.base_dtype,
                                                             shapes=(),
                                                             name='sync_token_q',
                                                             shared_name='sync_token_q')

            # Applying grads, then adding tokens to queue
            with ops.control_dependencies([self._apply_grad_op]):
                tokens = gen_array_ops.fill([self._num_workers], self._global_step)
                sync_op = self._sync_token_queue.enqueue_many((tokens,))

                # Waiting for token in queue (sync point)
                with ops.control_dependencies([sync_op]):
                    token = self._sync_token_queue.dequeue()
                    update_ops = [state_ops.assign(self._local_step, token)]

                    # Increasing version step
                    if version_step is not None:
                        update_ops += [state_ops.assign_add(version_step, 1)]

                    # Returning
                    return control_flow_ops.group(*update_ops)

    def _update_distributed_as_worker(self):
        """ Performs the gradient averaging, updates the variables, and the global step
            :param version_step: A variable that represents the model's version
            :return: The update operation to run

            Note: This method is called by a worker when synchronization is required.
        """
        # Creating sync_token queue
        with ops.device(self._global_step.device), ops.name_scope(''):
            self._sync_token_queue = data_flow_ops.FIFOQueue(capacity=-1,
                                                             dtypes=self._global_step.dtype.base_dtype,
                                                             shapes=(),
                                                             name='sync_token_q',
                                                             shared_name='sync_token_q')

            # Waiting for token in queue (sync point)
            token = self._sync_token_queue.dequeue()
            return state_ops.assign(self._local_step, token)

    def _create_dense_accumulator(self, var, grad):
        """ Creates a dense accumulator for the specified variable """
        assert var.name not in self._accumulators, 'Variable %s has already an accumulator' % var.name
        shared_name = None if self._num_workers == 1 else var.name + '/grad_accum'
        grad_accum = data_flow_ops.ConditionalAccumulator(grad.dtype,
                                                          shape=var.get_shape(),
                                                          shared_name=shared_name)
        self._accumulators[var.name] = (var, grad_accum, var.device)
        return grad_accum

    def _create_sparse_accumulator(self, var, grad):
        """ Creates a sparse accumulator for the specified variable """
        assert var.name not in self._accumulators, 'Variable %s has already an accumulator' % var.name
        shared_name = None if self._num_workers == 1 else var.name + '/grad_accum'
        grad_accum = data_flow_ops.SparseConditionalAccumulator(grad.dtype,
                                                                shape=(),
                                                                shared_name=shared_name)
        self._accumulators[var.name] = (var, grad_accum, var.device)
        return grad_accum

    @staticmethod
    def _take_dense_grad(grad_accum, grad):
        """ Computes the gradient for a ConditionalAccumulator
            :param grad_accum: The gradient accumulator where gradients are stored
            :param grad: An instance of the gradient stored in the accumulator
            :return: The avg gradient to apply (or a zero-like object if no gradients are stored)
            :type grad_accum: data_flow_ops.ConditionalAccumulator
        """
        def _take_grad():
            """ Computes the gradient from the accumulator """
            avg_grad = grad_accum.take_grad(num_required=1)
            with ops.control_dependencies([avg_grad]):
                return array_ops.identity(avg_grad)

        def _zero_grad():
            """ Returns a zeroed-out gradient """
            zero_like_grad = array_ops.zeros_like(grad)
            with ops.control_dependencies([zero_like_grad]):
                return array_ops.identity(zero_like_grad)

        return control_flow_ops.cond(gen_math_ops.equal(grad_accum.num_accumulated(), 0),
                                     true_fn=_zero_grad,
                                     false_fn=_take_grad)

    @staticmethod
    def _take_sparse_grad(grad_accum, grad):
        """ Computes the gradient for a SparseConditionalAccumulator
            :param grad_accum: The gradient accumulator where gradients are stored
            :param grad: An instance of the gradient stored in the accumulator
            :return: The avg gradient to apply (or a zero-like object if no gradients are stored)
            :type grad_accum: data_flow_ops.SparseConditionalAccumulator
        """
        def _take_grad():
            """ Computes the gradient from the accumulator """
            avg_grad = grad_accum.take_indexed_slices_grad(num_required=1)
            with ops.control_dependencies([avg_grad]):
                return ops.IndexedSlices(values=array_ops.identity(avg_grad.values),
                                         indices=avg_grad.indices,
                                         dense_shape=avg_grad.dense_shape)

        def _zero_grad():
            """ Returns a zeroed-out gradient """
            zero_values = array_ops.zeros_like(grad.values)
            with ops.control_dependencies([zero_values]):
                return ops.IndexedSlices(values=array_ops.identity(zero_values),
                                         indices=math_ops.cast(grad.indices, dtypes.int64),
                                         dense_shape=math_ops.cast(grad.dense_shape, dtypes.int64))

        return control_flow_ops.cond(gen_math_ops.equal(grad_accum.num_accumulated(), 0),
                                     true_fn=_zero_grad,
                                     false_fn=_take_grad)

    def get_slot(self, var, name):
        """ Returns a slot named 'name' created by 'var' by the Optimizer """
        return self._optimizer.get_slot(var, name)

    def get_slot_names(self):
        """ Returns a list of the names of slots created by the Optimizer """
        return self._optimizer.get_slot_names()

    def variables(self):
        """ Fetches a list of optimizer variables in the default graph (excluding the local step) """
        return self._optimizer.variables()

    def _apply_dense(self, grad, var):
        """ Add ops to apply dense gradients to `var`. """
        raise NotImplementedError()

    def _apply_sparse(self, grad, var):
        """ Add ops to apply sparse gradients to `var`. """
        raise NotImplementedError()

    def _resource_apply_dense(self, grad, handle):
        """ Add ops to apply dense gradients to the variable `handle`. """
        raise NotImplementedError()

    def _resource_apply_sparse(self, grad, handle, indices):
        """ Add ops to apply sparse gradients to the variable `handle`. """
        raise NotImplementedError()


text:
@implementation SKTask

//---create task with its execution block and set completion block
+(SKTask*)taskWithBlock:(BlockTask)blockTask{

    SKTask *task=[[SKTask alloc] init];
    task.blockTask=blockTask;
    return task;
}
@end


text:
package eu.artemis.demanes.lib.impl.coapParameterization.client;

import java.net.URISyntaxException;
import java.nio.ByteBuffer;

import eu.artemis.demanes.datatypes.ANES_URN;
import eu.artemis.demanes.exceptions.ParameterizationException;
import eu.artemis.demanes.exceptions.ParameterizationLinkException;
import eu.artemis.demanes.lib.ParameterizationProxy;
import eu.artemis.demanes.lib.impl.communication.PayloadParsingException;
import eu.artemis.demanes.lib.impl.communication.CommUtils;
import eu.artemis.demanes.lib.services.RESTService;
import eu.artemis.demanes.lib.services.ServiceException;
import eu.artemis.demanes.lib.services.URNTranslator;

/**
 * CoapParameterizationClientProxy
 *
 * @author leeuwencjv
 * @version 0.1
 * @since 30 jun. 2014
 *
 */
public class CoapParameterizationClientProxy implements ParameterizationProxy {

	private final RESTService listService;

	private final RESTService parameterizationService;

	private final URNTranslator translator;

	/**
	 * @param resolve
	 * @param resolve2
	 */
	public CoapParameterizationClientProxy(RESTService par, RESTService list,
			URNTranslator ut) {
		this.parameterizationService = par;
		this.listService = list;
		this.translator = ut;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * eu.artemis.demanes.lib.ParameterizationProxy#getParameter(eu.artemis.
	 * demanes.datatypes.ANES_URN)
	 */
	@Override
	public byte[] getParameter(ANES_URN urn) throws ParameterizationException {
		ByteBuffer args;
		if (this.translator != null && this.translator.URNToByte(urn) != null) {
			args = ByteBuffer.allocate(1);
			args.put(this.translator.URNToByte(urn));
		} else {
			String paramName = urn.toString();
			args = ByteBuffer.allocate(paramName.length() + 1);
			args.put((byte) paramName.length());
			args.put(paramName.getBytes());
		}

		args.flip();

		try {
			ByteBuffer response = parameterizationService.get(args);

			if (response == null)
				throw new ParameterizationLinkException();

			response.mark();
			byte firstByte = response.get();
			if (this.translator != null && this.translator.byteToURN(firstByte) != null) {
				ANES_URN returnURN = translator.byteToURN(response.get());
				assert(returnURN == urn);

				return CommUtils.readBytes(response, 4);
			} else {
				response.reset();
				ANES_URN returnURN = new ANES_URN(CommUtils.ReadStringFromByteBuffer(response));
				assert(returnURN == urn);

				return CommUtils.readBytes(response);
			}

		} catch (ServiceException e) {
			throw new ParameterizationLinkException(e);
		} catch (PayloadParsingException e) {
			throw new ParameterizationLinkException("Exception parsing COAP payload", e);
		} catch (URISyntaxException e) {
			throw new ParameterizationLinkException("Invalid Parameter URN", e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see eu.artemis.demanes.lib.ParameterizationProxy#listParameters()
	 */
	@Override
	public byte[] listParameters() throws ParameterizationException {
		try {
			ByteBuffer response = listService.get(null);

			byte[] buf = new byte[response.remaining()];
			response.get(buf, 0, response.remaining());

			return buf;
		} catch (ServiceException e) {
			throw new ParameterizationLinkException(e);
		}
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see
	 * eu.artemis.demanes.lib.ParameterizationProxy#setParameter(eu.artemis.
	 * demanes.datatypes.ANES_URN, byte[])
	 */
	@Override
	public void setParameter(ANES_URN urn, byte[] value)
			throws ParameterizationException {

		ByteBuffer args;
		if (this.translator != null && this.translator.URNToByte(urn) != null) {
			args = ByteBuffer.allocate(5);
			args.put(this.translator.URNToByte(urn));
			args.put(value);
		} else {
			String paramName = urn.toString();
			args = ByteBuffer.allocate(paramName.length() + value.length
					+ 2);

			args.put((byte) paramName.length());
			args.put(paramName.getBytes());
			args.put((byte) value.length);
			args.put(value);
		}

		args.flip();

		try {
			parameterizationService.put(args);
		} catch (ServiceException e) {
			throw new ParameterizationLinkException(e);
		}
	}
}


text:
package fm.common.rich

import java.util.Optional

class RichOptional[T](val self: Optional[T]) extends AnyVal {
  /** Implements asScala method similar to collection.JavaConverters._ for java Optional class */
  def asScala: Option[T] = if (self.isPresent) Some(self.get) else None
}


text:
require "rscons"
require "optparse"

module Rscons
  # Command-Line Interface functionality.
  class Cli

    # Default files to look for to execute if none specified.
    DEFAULT_RSCONSCRIPTS = %w[Rsconscript Rsconscript.rb]

    # Run the Rscons CLI.
    #
    # @param argv [Array]
    #   Command-line parameters.
    #
    # @return [void]
    def run(argv)
      argv = argv.dup
      begin
        exit run_toplevel(argv)
      rescue OptionParser::InvalidOption => io
        $stderr.puts io.message
        $stderr.puts usage
        exit 2
      end
    end

    private

    def parse_task_params(task, argv)
      task_params = {}
      while argv.size > 0
        if argv[0] =~ /^--(\S+?)(?:=(.*))?$/
          param_name, param_value = $1, $2
          param_value ||= true
          task_params[param_name] = param_value
          argv.slice!(0)
        else
          break
        end
      end
      task_params
    end

    def parse_tasks_and_params(argv)
      tasks_and_params = {}
      while argv.size > 0
        task = argv.shift
        tasks_and_params[task] = parse_task_params(task, argv)
      end
      tasks_and_params
    end

    def run_toplevel(argv)
      rsconscript = nil
      show_tasks = false
      all_tasks = false
      enabled_variants = ""

      OptionParser.new do |opts|

        opts.on("-A", "--all") do
          all_tasks = true
        end

        opts.on("-b", "--build DIR") do |build_dir|
          Rscons.application.build_dir = build_dir
        end

        opts.on("-e", "--variants VS") do |variants|
          enabled_variants = variants
        end

        opts.on("-f FILE") do |f|
          rsconscript = f
        end

        opts.on("-F", "--show-failure") do
          Rscons.application.show_failure
          return 0
        end

        opts.on("-h", "--help") do
          puts usage
          return 0
        end

        opts.on("-j NTHREADS") do |n_threads|
          Rscons.application.n_threads = n_threads.to_i
        end

        opts.on("-r", "--color MODE") do |color_mode|
          case color_mode
          when "off"
            Rscons.application.do_ansi_color = false
          when "force"
            Rscons.application.do_ansi_color = true
          end
        end

        opts.on("-T", "--tasks") do
          show_tasks = true
        end

        opts.on("-v", "--verbose") do
          Rscons.application.verbose = true
        end

        opts.on("--version") do
          puts "Rscons version #{Rscons::VERSION}"
          return 0
        end

      end.order!(argv)

      # Parse the rest of the command line.
      tasks_and_params = parse_tasks_and_params(argv)

      # Find the build script.
      if rsconscript
        unless File.exist?(rsconscript)
          $stderr.puts "Cannot read #{rsconscript}"
          return 1
        end
      else
        rsconscript = DEFAULT_RSCONSCRIPTS.find do |f|
          File.exist?(f)
        end
      end

      # Anything else requires a build script, so complain if we didn't find
      # one.
      unless rsconscript
        $stderr.puts "Could not find the Rsconscript to execute."
        $stderr.puts "Looked for: #{DEFAULT_RSCONSCRIPTS.join(", ")}"
        return 1
      end

      begin
        Rscons.application.run(rsconscript, tasks_and_params, show_tasks, all_tasks, enabled_variants)
      rescue RsconsError => e
        Ansi.write($stderr, :red, e.message, :reset, "\n")
        1
      end
    end

    def usage
      <<EOF
Usage: #{$0} [global options] [[task] [task options] ...]

Global options:
  -A, --all
    Show all tasks (even those without descriptions) in task list. Use in
    conjunction with the -T argument.

  -b BUILD, --build=BUILD
    Set build directory (default: build).

  -e VS, --variants=VS
    Enable or disable variants. VS is a comma-separated list of variant
    entries. If the entry begins with "-" the variant is disabled instead of
    enabled. If the full list begins with "+" or "-" then it modifies the
    variants that are enabled by default by only enabling or disabling the
    listed variants. Otherwise, the enabled set of variants is as given and
    any variants not listed are disabled. The set of enabled variants is
    remembered from when the project is configured.

  -f FILE
    Use FILE as Rsconscript.

  -F, --show-failure
    Show failed command log from previous build and exit (does not load build
    script).

  -h, --help
    Show rscons help and exit (does not load build script).

  -j N, --nthreads=N
    Set number of threads (local default: #{Rscons.application.n_threads}).

  -r COLOR, --color=COLOR
    Set color mode (off, auto, force).

  -T, --tasks
    Show task list and parameters and exit (loads build script). By default
    only tasks with a description are listed. Use -AT to show all tasks whether
    they have a description or not.

  -v, --verbose
    Run verbosely. This causes Rscons to print the full build command used by
    each builder.

  --version
    Show rscons version and exit (does not load build script).
EOF
    end

  end
end


text:
<?php

namespace Phlexible\Component\MediaTemplate\File;

use Phlexible\Bundle\GuiBundle\Locator\PatternResourceLocator;
use Phlexible\Component\MediaTemplate\File\Loader\LoaderInterface;
use Phlexible\Component\MediaTemplate\Model\TemplateCollection;

/**
 * Template loader
 *
 * @author Stephan Wentz <sw@brainbits.net>
 */
class TemplateLoader
{
    /**
     * @var PatternResourceLocator
     */
    private $locator;

    /**
     * @var LoaderInterface[]
     */
    private $loaders = [];

    /**
     * @param PatternResourceLocator $locator
     */
    public function __construct(PatternResourceLocator $locator)
    {
        $this->locator = $locator;
    }

    /**
     * @param LoaderInterface $loader
     *
     * @return $this
     */
    public function addLoader(LoaderInterface $loader)
    {
        $this->loaders[$loader->getExtension()] = $loader;

        return $this;
    }

    /**
     * @return TemplateCollection
     */
    public function loadTemplates()
    {
        $templates = new TemplateCollection();

        foreach ($this->loaders as $extension => $loader) {
            $files = $this->locator->locate("*.$extension", 'mediatemplates', false);

            foreach ($files as $file) {
                $templates->add($loader->load($file));
            }
        }

        return $templates;
    }
}


text:
#ifndef _cimple_Meta_Repository_h
#define _cimple_Meta_Repository_h

#include "config.h"
#include "Meta_Class.h"

CIMPLE_NAMESPACE_BEGIN

struct Meta_Repository
{
    const Meta_Class* const* meta_classes;
    size_t num_meta_classes;
};

CIMPLE_CIMPLE_LINKAGE
const Meta_Class* find_meta_class(
    const Meta_Repository* meta_repository,
    const char* class_name);

/* Returns 0 if #sub# is a subclass of #super# and 1 if not. Returns -1 if
   unable to find either of the named classes in the meta repository or if
   any of the pointers are null.
*/
CIMPLE_CIMPLE_LINKAGE
int is_subclass(
    const Meta_Repository* meta_repository,
    const char* super,
    const char* sub);

CIMPLE_NAMESPACE_END

#endif /* _cimple_Meta_Repository_h */


text:
{-# LANGUAGE OverloadedStrings #-}

module OutputSpec
  ( outputSpec
  ) where

import DarkSky.App.Output
import DarkSky.Response
import qualified DarkSky.Response.DataBlock as DB
import qualified DarkSky.Response.DataPoint as DP
import DarkSky.Types
import Data.Text (Text)
import Test.Hspec

outputSpec :: IO ()
outputSpec =
  hspec $
  describe "Output" $
  describe "creating" $
  do it "from a full response" $ makeOutput fullResponse `shouldBe` fullOutput
     it "from an empty response" $
       makeOutput emptyResponse `shouldBe` emptyOutput

fullResponse :: Response
fullResponse =
  Response
  { coordinate = Coordinate 1 2
  , timezone = "timezone"
  , currently = Just $ dataPoint 12.3 "current summary"
  , minutely = Nothing
  , hourly = Just $ dataBlock "next 48 hours summary"
  , daily = Just $ dataBlock "week summary"
  , alerts = []
  , flags = Nothing
  }

fullOutput :: Output
fullOutput =
  Output
  { currentTemperature = "12.3°"
  , currentSummary = "current summary"
  , next48HoursSummary = "next 48 hours summary"
  , weekSummary = "week summary"
  }

emptyResponse :: Response
emptyResponse =
  Response
  { coordinate = Coordinate 1 2
  , timezone = "timezone"
  , currently = Nothing
  , minutely = Nothing
  , hourly = Nothing
  , daily = Nothing
  , alerts = []
  , flags = Nothing
  }

emptyOutput :: Output
emptyOutput =
  Output
  { currentTemperature = "No temperature available"
  , currentSummary = "No summary available"
  , next48HoursSummary = "No summary available"
  , weekSummary = "No summary available"
  }

dataPoint :: Temperature -> Text -> DP.DataPoint
dataPoint temperature summary =
  DP.emptyDataPoint
  { DP.temperature = Just temperature
  , DP.summary = Just summary
  }

dataBlock :: Text -> DB.DataBlock
dataBlock summary =
  DB.emptyDataBlock
  { DB.summary = Just summary
  }


text:
<!DOCTYPE html>

<title>Employee Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet"
	th:href="@{/webjars/bootstrap/3.3.6/css/bootstrap.min.css}" />

Cardinals Banking

My Dashboard

Logout

Employee Dashboard

View External User Accounts

My Profile

Request Access

New External User Requests

Pending Transfers

Pending Transactions

Successfuly approved/rejected internal user request

Successfuly deleted internal user request

			Filter <input id="filter"
				type="text" class="form-control" placeholder="Type here..." />

					Username
					First Name
					Last Name
					Role

					View
					Delete


text:
set -e
set -u

mkdir -p build
cd build
cp ../cmake/config.cmake .

echo set\(USE_CUBLAS ON\) >> config.cmake
echo set\(USE_CUDNN ON\) >> config.cmake
echo set\(USE_CUDA ON\) >> config.cmake
echo set\(USE_OPENGL ON\) >> config.cmake
echo set\(USE_MICRO ON\) >> config.cmake
echo set\(USE_MICRO_STANDALONE_RUNTIME ON\) >> config.cmake
echo set\(USE_STANDALONE_CRT ON\) >> config.cmake
echo set\(USE_LLVM llvm-config-9\) >> config.cmake
echo set\(USE_NNPACK ON\) >> config.cmake
echo set\(NNPACK_PATH /NNPACK/build/\) >> config.cmake
echo set\(USE_RPC ON\) >> config.cmake
echo set\(USE_SORT ON\) >> config.cmake
echo set\(USE_GRAPH_RUNTIME ON\) >> config.cmake
echo set\(USE_STACKVM_RUNTIME ON\) >> config.cmake
echo set\(USE_GRAPH_RUNTIME_DEBUG ON\) >> config.cmake
echo set\(USE_VM_PROFILER ON\) >> config.cmake
echo set\(USE_ANTLR ON\) >> config.cmake
echo set\(USE_VTA_TSIM ON\) >> config.cmake
echo set\(USE_VTA_FSIM ON\) >> config.cmake
echo set\(USE_BLAS openblas\) >> config.cmake
echo set\(CMAKE_CXX_COMPILER g++\) >> config.cmake
echo set\(CMAKE_CXX_FLAGS -Werror\) >> config.cmake
echo set\(USE_TENSORRT_CODEGEN ON\) >> config.cmake


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

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>net.sourceforge.pmd.lang.cpp (PMD C++ 5.5.1 API)</title>
<meta name="date" content="2016-07-27">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

net.sourceforge.pmd.lang.cpp

Classes

ContinuationReader

CppHandler

CppLanguageModule

CppParser

CppTokenManager


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Archimedes.Localisation.MessageSources
{
    public class MemoryMessageSource : IMessageSource
    {
        private readonly IDictionary<CultureInfo, IDictionary<string, string>> _memoryCache = new Dictionary<CultureInfo, IDictionary<string, string>>();

        public MemoryMessageSource()
        {

        }

        /// <summary>
        /// Add a property to this memory property source
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public MemoryMessageSource AddMessage(CultureInfo culture, string key, string value)
        {
            if (!_memoryCache.ContainsKey(culture))
            {
                _memoryCache.Add(culture, new Dictionary<string, string>());
            }

            if (!_memoryCache[culture].ContainsKey(key))
            {
                _memoryCache[culture].Add(key, value);
            }
            else
            {
                _memoryCache[culture][key] = value;
            }
            return this;
        }

        public IDictionary<string, string> Load(CultureInfo culture)
        {
            if (_memoryCache.ContainsKey(culture))
            {
                return _memoryCache[culture];
            }
            else
            {
                return new Dictionary<string, string>();
            }
        }

        public ISet<CultureInfo> GetAvailableCultures()
        {
            return new HashSet<CultureInfo>(_memoryCache.Keys);
        }

    }
}


text:
package randoop.test.mst;

/**
 * A Java implementation of the <tt>mst</tt> Olden benchmark.  The Olden
 * benchmark computes the minimum spanning tree of a graph using
 * Bentley's algorithm.
 *

 * J. Bentley. "A Parallel Algorithm for Constructing Minimum Spanning Trees"
 * J. of Algorithms, 1:51-59, 1980.
 *
 *

 * As with the original C version, this one uses its own implementation
 * of hashtable.
 **/
public class MST {
  /**
   * The number of vertices in the graph.
   **/
  private static int vertices = 0;
  /**
   * Set to true to print the final result.
   **/
  private static boolean printResult = false;
  /**
   * Set to true to print information messages and timing values
   **/
  private static boolean printMsgs = false;

  public static void main(String args[]) {
    parseCmdLine(args);

    if (printMsgs) System.out.println("Making graph of size " + vertices);
    long start0 = System.currentTimeMillis();
    Graph graph = new Graph(vertices);
    long end0 = System.currentTimeMillis();

    if (printMsgs) System.out.println("About to compute MST");
    long start1 = System.currentTimeMillis();
    int dist = computeMST(graph, vertices);
    long end1 = System.currentTimeMillis();

    if (printResult || printMsgs) System.out.println("MST has cost " + dist);

    if (printMsgs) {
      System.out.println("Build graph time " + (end0 - start0) / 1000.0);
      System.out.println("Compute time " + (end1 - start1) / 1000.0);
      System.out.println("Total time " + (end1 - start0) / 1000.0);
    }

    System.out.println("Done!");
  }

  /**
   * The method to compute the minimum spanning tree.
   * @param graph the graph data structure
   * @param numvert the number of vertices in the graph
   * @return the minimum spanning tree cost
   **/
  public static int computeMST(Graph graph, int numvert) {
    int cost = 0;

    // Insert first node
    Vertex inserted = graph.firstNode();
    Vertex tmp = inserted.next();
    MyVertexList = tmp;
    numvert--;

    // Annonunce insertion and find next one
    while (numvert != 0) {
      //System.out.println("numvert= " +numvert);
      BlueReturn br = doAllBlueRule(inserted);
      inserted = br.vert();
      int dist = br.dist();
      numvert--;
      cost += dist;
    }
    return cost;
  }

  private static BlueReturn BlueRule(Vertex inserted, Vertex vlist) {
    BlueReturn retval = new BlueReturn();

    if (vlist == null) {
      retval.setDist(999999);
      return retval;
    }

    Vertex prev = vlist;
    retval.setVert(vlist);
    retval.setDist(vlist.mindist());
    Hashtable hash = vlist.neighbors();
    Object o = hash.get(inserted);
    if (o != null) {
      int dist = ((Integer) o).intValue();
      if (dist < retval.dist()) {
        vlist.setMindist(dist);
        retval.setDist(dist);
      }
    } else System.out.println("Not found");

    int count = 0;
    // We are guaranteed that inserted is not first in list
    for (Vertex tmp = vlist.next(); tmp != null; prev = tmp, tmp = tmp.next()) {
      count++;
      if (tmp == inserted) {
        Vertex next = tmp.next();
        prev.setNext(next);
      } else {
        hash = tmp.neighbors();
        int dist2 = tmp.mindist();
        o = hash.get(inserted);
        if (o != null) {
          int dist = ((Integer) o).intValue();
          if (dist < dist2) {
            tmp.setMindist(dist);
            dist2 = dist;
          }
        } else System.out.println("Not found");

        if (dist2 < retval.dist()) {
          retval.setVert(tmp);
          retval.setDist(dist2);
        }
      } // else
    } // for
    return retval;
  }

  private static Vertex MyVertexList = null;

  private static BlueReturn doAllBlueRule(Vertex inserted) {
    if (inserted == MyVertexList) MyVertexList = MyVertexList.next();
    return BlueRule(inserted, MyVertexList);
  }

  /**
   * Parse the command line options.
   * @param args the command line options.
   **/
  private static final void parseCmdLine(String args[]) {
    int i = 0;
    String arg;

    while (i < args.length && args[i].startsWith("-")) {
      arg = args[i++];

      if (arg.equals("-v")) {
        if (i < args.length) {
          vertices = new Integer(args[i++]).intValue();
        } else throw new RuntimeException("-v requires the number of vertices");
      } else if (arg.equals("-p")) {
        printResult = true;
      } else if (arg.equals("-m")) {
        printMsgs = true;
      } else if (arg.equals("-h")) {
        usage();
      }
    }
    if (vertices == 0) usage();
  }

  /**
   * The usage routine which describes the program options.
   **/
  private static final void usage() {
    System.err.println("usage: java MST -v <levels> [-p] [-m] [-h]");
    System.err.println("    -v the number of vertices in the graph");
    System.err.println("    -p (print the result>)");
    System.err.println("    -m (print informative messages)");
    System.err.println("    -h (this message)");
    System.exit(0);
  }
}

/**
 * Not really sure what this is for?
 **/
class BlueReturn {
  private Vertex vert;
  private int dist;

  public Vertex vert() {
    return vert;
  }

  public void setVert(Vertex v) {
    vert = v;
  }

  public int dist() {
    return dist;
  }

  public void setDist(int d) {
    dist = d;
  }
}


text:
# Roles And Permissions For Laravel 5

## Fork of romanbican/roles to make compatible with MongoDB laravel package jenssegers/laravel-mongodb see package for details now roles and permissions are fully compatible with mongodbo

Powerful package for handling roles and permissions in Laravel 5 (5.1 and also 5.0).

- [Installation](#installation)
    - [Composer](#composer)
    - [Service Provider](#service-provider)
    - [Config File And Migrations](#config-file-and-migrations)
    - [HasRoleAndPermission Trait And Contract](#hasroleandpermission-trait-and-contract)
- [Usage](#usage)
    - [Creating Roles](#creating-roles)
    - [Attaching And Detaching Roles](#attaching-and-detaching-roles)
    - [Checking For Roles](#checking-for-roles)
    - [Levels](#levels)
    - [Creating Permissions](#creating-permissions)
    - [Attaching And Detaching Permissions](#attaching-and-detaching-permissions)
    - [Checking For Permissions](#checking-for-permissions)
    - [Permissions Inheriting](#permissions-inheriting)
    - [Entity Check](#entity-check)
    - [Blade Extensions](#blade-extensions)
    - [Middleware](#middleware)
- [Config File](#config-file)
- [More Information](#more-information)
- [License](#license)

## Installation

This package is very easy to set up. There are only couple of steps.

### Composer

Pull this package in through Composer (file `composer.json`).

```js
{
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.1.*",
        "bican/roles": "2.1.*"
    }
}
```

> If you are still using Laravel 5.0, you must pull in version `1.7.*`.

Run this command inside your terminal.

    composer update

### Service Provider

Add the package to your application service providers in `config/app.php` file.

```php
'providers' => [

    /*
     * Laravel Framework Service Providers...
     */
    Illuminate\Foundation\Providers\ArtisanServiceProvider::class,
    Illuminate\Auth\AuthServiceProvider::class,
    ...

    /**
     * Third Party Service Providers...
     */
    Bican\Roles\RolesServiceProvider::class,

],
```

### Config File And Migrations

Publish the package config file and migrations to your application. Run these commands inside your terminal.

    php artisan vendor:publish --provider="Bican\Roles\RolesServiceProvider" --tag=config
    php artisan vendor:publish --provider="Bican\Roles\RolesServiceProvider" --tag=migrations

And also run migrations.

    php artisan migrate

> This uses the default users table which is in Laravel. You should already have the migration file for the users table available and migrated.

### HasRoleAndPermission Trait And Contract

Include `HasRoleAndPermission` trait and also implement `HasRoleAndPermission` contract inside your `User` model.

```php
use Bican\Roles\Traits\HasRoleAndPermission;
use Bican\Roles\Contracts\HasRoleAndPermission as HasRoleAndPermissionContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract
{
    use Authenticatable, CanResetPassword, HasRoleAndPermission;
```

And that's it!

## Usage

### Creating Roles

```php
use Bican\Roles\Models\Role;

$adminRole = Role::create([
    'name' => 'Admin',
    'slug' => 'admin',
    'description' => '', // optional
    'level' => 1, // optional, set to 1 by default
]);

$moderatorRole = Role::create([
    'name' => 'Forum Moderator',
    'slug' => 'forum.moderator',
]);
```

> Because of `Slugable` trait, if you make a mistake and for example leave a space in slug parameter, it'll be replaced with a dot automatically, because of `str_slug` function.

### Attaching And Detaching Roles

It's really simple. You fetch a user from database and call `attachRole` method. There is `BelongsToMany` relationship between `User` and `Role` model.

```php
use App\User;

$user = User::find($id);

$user->attachRole($adminRole); // you can pass whole object, or just an id
```

```php
$user->detachRole($adminRole); // in case you want to detach role
$user->detachAllRoles(); // in case you want to detach all roles
```

### Checking For Roles

You can now check if the user has required role.

```php
if ($user->is('admin')) { // you can pass an id or slug
    // or alternatively $user->hasRole('admin')
}
```

You can also do this:

```php
if ($user->isAdmin()) {
    //
}
```

And of course, there is a way to check for multiple roles:

```php
if ($user->is('admin|moderator')) {
    /*
    | Or alternatively:
    | $user->is('admin, moderator'), $user->is(['admin', 'moderator']),
    | $user->isOne('admin|moderator'), $user->isOne('admin, moderator'), $user->isOne(['admin', 'moderator'])
    */

    // if user has at least one role
}

if ($user->is('admin|moderator', true)) {
    /*
    | Or alternatively:
    | $user->is('admin, moderator', true), $user->is(['admin', 'moderator'], true),
    | $user->isAll('admin|moderator'), $user->isAll('admin, moderator'), $user->isAll(['admin', 'moderator'])
    */

    // if user has all roles
}
```

### Levels

When you are creating roles, there is optional parameter `level`. It is set to `1` by default, but you can overwrite it and then you can do something like this:

```php
if ($user->level() > 4) {
    //
}
```

> If user has multiple roles, method `level` returns the highest one.

`Level` has also big effect on inheriting permissions. About it later.

### Creating Permissions

It's very simple thanks to `Permission` model.

```php
use Bican\Roles\Models\Permission;

$createUsersPermission = Permission::create([
    'name' => 'Create users',
    'slug' => 'create.users',
    'description' => '', // optional
]);

$deleteUsersPermission = Permission::create([
    'name' => 'Delete users',
    'slug' => 'delete.users',
]);
```

### Attaching And Detaching Permissions

You can attach permissions to a role or directly to a specific user (and of course detach them as well).

```php
use App\User;
use Bican\Roles\Models\Role;

$role = Role::find($roleId);
$role->attachPermission($createUsersPermission); // permission attached to a role

$user = User::find($userId);
$user->attachPermission($deleteUsersPermission); // permission attached to a user
```

```php
$role->detachPermission($createUsersPermission); // in case you want to detach permission
$role->detachAllPermissions(); // in case you want to detach all permissions

$user->detachPermission($deleteUsersPermission);
$user->detachAllPermissions();
```

### Checking For Permissions

```php
if ($user->can('create.users') { // you can pass an id or slug
    //
}

if ($user->canDeleteUsers()) {
    //
}
```

You can check for multiple permissions the same way as roles. You can make use of additional methods like `canOne`, `canAll` or `hasPermission`.

### Permissions Inheriting

Role with higher level is inheriting permission from roles with lower level.

There is an example of this `magic`:

You have three roles: `user`, `moderator` and `admin`. User has a permission to read articles, moderator can manage comments and admin can create articles. User has a level 1, moderator level 2 and admin level 3. It means, moderator and administrator has also permission to read articles, but administrator can manage comments as well.

> If you don't want permissions inheriting feature in you application, simply ignore `level` parameter when you're creating roles.

### Entity Check

Let's say you have an article and you want to edit it. This article belongs to a user (there is a column `user_id` in articles table).

```php
use App\Article;
use Bican\Roles\Models\Permission;

$editArticlesPermission = Permission::create([
    'name' => 'Edit articles',
    'slug' => 'edit.articles',
    'model' => 'App\Article',
]);

$user->attachPermission($editArticlesPermission);

$article = Article::find(1);

if ($user->allowed('edit.articles', $article)) { // $user->allowedEditArticles($article)
    //
}
```

This condition checks if the current user is the owner of article. If not, it will be looking inside user permissions for a row we created before.

```php
if ($user->allowed('edit.articles', $article, false)) { // now owner check is disabled
    //
}
```

### Blade Extensions

There are four Blade extensions. Basically, it is replacement for classic if statements.

```php
@role('admin') // @if(Auth::check() && Auth::user()->is('admin'))
    // user is admin
@endrole

@permission('edit.articles') // @if(Auth::check() && Auth::user()->can('edit.articles'))
    // user can edit articles
@endpermission

@level(2) // @if(Auth::check() && Auth::user()->level() >= 2)
    // user has level 2 or higher
@endlevel

@allowed('edit', $article) // @if(Auth::check() && Auth::user()->allowed('edit', $article))
    // show edit button
@endallowed

@role('admin|moderator', 'all') // @if(Auth::check() && Auth::user()->is('admin|moderator', 'all'))
    // user is admin and also moderator
@else
    // something else
@endrole
```

### Middleware

This package comes with `VerifyRole`, `VerifyPermission` and `VerifyLevel` middleware. You must add them inside your `app/Http/Kernel.php` file.

```php
/**
 * The application's route middleware.
 *
 * @var array
 */
protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'role' => \Bican\Roles\Middleware\VerifyRole::class,
    'permission' => \Bican\Roles\Middleware\VerifyPermission::class,
    'level' => \Bican\Roles\Middleware\VerifyLevel::class,
];
```

Now you can easily protect your routes.

```php
$router->get('/example', [
    'as' => 'example',
    'middleware' => 'role:admin',
    'uses' => 'ExampleController@index',
]);

$router->post('/example', [
    'as' => 'example',
    'middleware' => 'permission:edit.articles',
    'uses' => 'ExampleController@index',
]);

$router->get('/example', [
    'as' => 'example',
    'middleware' => 'level:2', // level >= 2
    'uses' => 'ExampleController@index',
]);
```

It throws `\Bican\Roles\Exceptions\RoleDeniedException`, `\Bican\Roles\Exceptions\PermissionDeniedException` or `\Bican\Roles\Exceptions\LevelDeniedException` exceptions if it goes wrong.

You can catch these exceptions inside `app/Exceptions/Handler.php` file and do whatever you want.

```php
/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $e
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $e)
{
    if ($e instanceof \Bican\Roles\Exceptions\RoleDeniedException) {
        // you can for example flash message, redirect...
        return redirect()->back();
    }

    return parent::render($request, $e);
}
```

## Config File

You can change connection for models, slug separator, models path and there is also a handy pretend feature. Have a look at config file for more information.

## More Information

For more information, please have a look at [HasRoleAndPermission](https://github.com/romanbican/roles/blob/master/src/Bican/Roles/Contracts/HasRoleAndPermission.php) contract.

## License

This package is free software distributed under the terms of the MIT license.