text:
copyright:
  years: 2016
lastupdated: "2016-10-21"

---

{:new_window: target="blank"}
{:shortdesc: .shortdesc}
{:screen: .screen}
{:codeblock: .codeblock}
{:pre: .pre}

# Sécurité {{site.data.keyword.iot_short_notm}}
{: #sec-index}
Dernière mise à jour : 21 octobre 2016
{: .last-updated}

En tant que service hébergé dans un cloud, {{site.data.keyword.iot_full}} intègre la sécurité en tant qu'aspect important de son architecture.
{: shortdesc}

Le document suivant répond à certaines questions courantes relatives à la façon dont les données d'une organisation sont protégées, en mettant l'accent sur certaines aspects :

* Conformité : Normes externes qui définissent des tests de performances pour la sécurité.
* Authentification : Vérifier l'identité des utilisateurs, des terminaux ou des applications qui tentent d'accéder aux informations de votre organisation.
* Autorisation : Vérifier que les utilisateurs, les terminaux et les applications sont autorisés à accéder aux informations de l'organisation.
* Chiffrement : Vérifier que les données ne peuvent être lues que par des parties autorisées et ne peuvent pas être interceptées.

## {{site.data.keyword.iot_short_notm}} et {{site.data.keyword.Bluemix_notm}}
{: #iot-bluemix-sec}

{{site.data.keyword.iot_short_notm}} s'exécute dans la plateforme {{site.data.keyword.Bluemix_notm}} et s'appuie donc à la fois sur {{site.data.keyword.Bluemix_notm}} et sur {{site.data.keyword.BluSoftlayer_full}} pour l'accès et la connectivité. La dépendance à {{site.data.keyword.Bluemix_notm}} et à {{site.data.keyword.BluSoftlayer}} rend la sécurité et la fiabilité de {{site.data.keyword.Bluemix_notm}} et d'{{site.data.keyword.BluSoftlayer}} essentielles pour les utilisateurs de {{site.data.keyword.iot_short_notm}}.

Pour plus d'informations sur la sécurité de {{site.data.keyword.Bluemix_notm}}, voir [Sécurité de la plateforme {{site.data.keyword.Bluemix_notm}}](https://console.ng.bluemix.net/docs/security/index.html#platform-security).

## Conformité à la sécurité {{site.data.keyword.iot_short_notm}}
{: #compliance}
![Icône ISO 27K](../../images/icon_iso27k1.png "ISO 27K icon")
{{site.data.keyword.iot_short_notm}} est certifié aux normes ISO (International Organization for Standardization) 27001, qui définissent le code de bonne pratique pour les processus de gestion de la sécurité des informations. La norme ISO 27001 spécifie les exigences en matière d'établissement, de mise en oeuvre et de documentation des systèmes de management de la sécurité de l'information (SMSI) et les exigences relatives à la mise en oeuvre des contrôles de sécurité, en fonction des besoins des organisations individuelles. La famille de normes ISO 27000 intègre un processus d'évaluation des risques et d'estimation des ressources, dans le but de protéger la confidentialité, l'intégrité et l'accessibilité des informations écrites, orales et électroniques.

{{site.data.keyword.iot_short_notm}} fait l'objet d'un audit par une firme indépendante et répond à toutes les exigences de la norme ISO 27001 : {{site.data.keyword.iot_short_notm}} ISO 27001:2013 Certificate of Registration.

## Terminologie {{site.data.keyword.iot_short_notm}}
{: #terminology}

![image](terminology_platform.svg)

## Comment sécurisons-nous la gestion des informations IoT au sein de votre organisation ?
{: #secure-org}

L'interface graphique reposant sur un navigateur et les API REST sont protégées par HTTPS, avec un certificat signé par DigiCert qui vous permet de vous assurer que vous vous connectez réellement au service {{site.data.keyword.iot_short_notm}} habilité. L'accès à l'interface graphique reposant sur le Web est authentifié par votre IBMid ou via la fonction {{site.data.keyword.ssoshort}} {{site.data.keyword.Bluemix_notm}}. L'utilisation de l'API REST requiert une clé d'API, générée via l'interface graphique. Vous pouvez utiliser cette clé pour effectuer des appels d'API REST authentifiés vers votre organisation.

![image](management_platform.svg)

## Comment sécurisons-nous les données d'identification de votre terminal ou de votre application ?
{: #secure-credentials}

Lorsque des terminaux sont enregistrés ou que des clés d'API sont générées, le jeton d'authentification est soumis à une opération de hachage et de salage. Cela signifie que les données d'identification de votre organisation ne peuvent jamais être récupérées depuis nos systèmes, même dans l'éventualité peu probable que {{site.data.keyword.iot_short_notm}} soit compromis.

Les données d'identification de terminal et les clés d'API peuvent être révoquées de manière individuelle si elles sont compromises.

![image](authentication_platform.svg)

## Comment vérifions-nous que vos terminaux se connectent en toute sécurité à {{site.data.keyword.iot_short_notm}} ?
{: #secure-device-connection}

Les terminaux connectés utilisent une combinaison clientId/jeton d'authentification qui est générée au moment de l'ajout des terminaux à votre plateforme. MQTT v3.1.1 permet une interopérabilité simple entre plusieurs plateformes et plusieurs langues. {{site.data.keyword.iot_short_notm}} prend en charge la connectivité via TLS v1.2.

![image](connectivity_platform.svg)

Pour plus d'informations sur les exigences relatives à TLS et aux suites de chiffrement, voir la section [Exigences TLS](https://console.ng.bluemix.net/docs/services/IoT/reference/security/connect_devices_apps_gw.html#tls_requirements) dans la documentation `Connexions d'application, de terminal et de passerelle à Watson IoT Platform`.

## Comment évitons-nous la fuite des données entre des terminaux IoT ?
{: #prevent-leak-devices}

Les structures de messagerie sécurisée sont intégrées. Une fois authentifiés, les terminaux sont autorisés uniquement à publier des données et à s'abonner à un espace de sujet limité :

* '/iot-2/evt/<event_id>/fmt/<format_string>'
* '/iot-2/cmd/<command_id>/fmt/<format_string>'

Tous les terminaux fonctionnent avec le même espace de sujet. Les données d'authentification fournies par le client déterminent le terminal auquel {{site.data.keyword.iot_short_notm}}  affecte cet espace de sujet.  Cela empêche les terminaux de pouvoir simuler les droits d'accès d'un autre terminal.

Le seul moyen de simuler les droits d'accès d'un autre terminal est d'obtenir les données d'identification de sécurité compromises du terminal.

![image](device_scope_platform.svg)

Les applications peuvent s'abonner et publier des données dans les sujets d'événement et de commande de tous les terminaux de l'organisation. Les applications peuvent analyser simultanément les données de nombreux terminaux et simuler ou représenter des terminaux, en plus de la formation de la partie complémentaire de la boucle de communication en mode duplex intégral.

## Comment évitons-nous la fuite des données IoT entre des organisations ?
{: #prevent-leak-org}

L'espace de sujet dans lequel les terminaux et les applications fonctionnent est défini au sein d'une organisation unique. Une fois l'authentification effectuée, {{site.data.keyword.iot_short_notm}} transforme la structure du sujet à l'aide d'un ID d'organisation provenant de l'authentification du client. Ce mécanisme rend impossible l'accès aux données d'une organisation à partir d'une autre organisation.

![image](org_scope_platform.svg)

# Liens connexes
{: #rellinks}
## Liens connexes
{: #general}
* [Initiation à {{site.data.keyword.iot_short_notm}}](https://console.ng.bluemix.net/docs/services/IoT/index.html)
* [Sécurité {{site.data.keyword.Bluemix_notm}}](https://console.ng.bluemix.net/docs/security/index.html#security){:new_window}
* [Sécurité de la plateforme {{site.data.keyword.Bluemix_notm}}](https://console.ng.bluemix.net/docs/security/index.html#platform-security){:new_window}
* [Conformité {{site.data.keyword.Bluemix_notm}}](https://console.ng.bluemix.net/docs/security/index.html#compliance){:new_window}
* [Sécurité {{site.data.keyword.BluSoftlayer}}](http://www.softlayer.com/security){:new_window}
* [Conformité {{site.data.keyword.BluSoftlayer}}](http://www.softlayer.com/compliance){:new_window}


text:
A strongly-typed representation of the App Container schema. Each entity in the schema has functions
to convert to and from JSON as well as a validate() function that checks the values against the
constraints outlined in the App Container specification. Parsing the JSON schema is exception-free
(JSON library exceptions are trapped). Neither parsing nor validation fail-fast in an attempt to
collate all errors (still immature).

# Specification Compliance

Currently ~ 0.2.0. This is very fuzzy at the moment but this will converge as the specification
matures.

## Top-Level Entities

- Image Manifest: ```appc/schema/image.h```
- Container Runtime Manifest ```appc/schema/container.h```

## TODO

- [ ] spec-compliant validate() for all types
- [ ] breadcrumbs in error messages ("container/volumes: error text")

redpajama_set_name: RedPajamaGithub


text:
package fi.csc.chipster.comp.resourcemonitor;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import fi.csc.chipster.comp.resourcemonitor.singleshot.SingleShotResourceMonitor.SingleShotProcessProvider;

public class StorageResourceMonitor {

	@SuppressWarnings("unused")
	private static Logger logger = LogManager.getLogger();

	private File jobDataDir;
	private Long maxStorage;
	private Long currentStorage;

	private SingleShotProcessProvider processProvider;

	public StorageResourceMonitor(File jobDataDir, SingleShotProcessProvider processProvider) {
		this.jobDataDir = jobDataDir;
		this.processProvider = processProvider;
	}
	public Long getMaxStorage() {
		return maxStorage;
	}

	public Long getCurrentStorage() {
		return currentStorage;
	}

	public void update() throws IOException {

		this.currentStorage = FileUtils.sizeOfDirectory(this.jobDataDir);

		if (this.maxStorage == null || currentStorage > this.maxStorage) {
			this.maxStorage = currentStorage;

			this.processProvider.maxStorageChanged(maxStorage);
		}
	}
}


text:
namespace gcm {

// Message data consisting of key-value pairs.
using MessageData = std::map<std::string, std::string>;

// Message to be delivered to the other party.
struct GCM_DRIVER_EXPORT OutgoingMessage {
  OutgoingMessage();
  OutgoingMessage(const OutgoingMessage& other);
  ~OutgoingMessage();

  // Message ID.
  std::string id;
  // In seconds.
  int time_to_live = kMaximumTTL;
  MessageData data;

  static const int kMaximumTTL;
};

// Message being received from the other party.
struct GCM_DRIVER_EXPORT IncomingMessage {
  IncomingMessage();
  IncomingMessage(const IncomingMessage& other);
  IncomingMessage(IncomingMessage&& other);
  ~IncomingMessage();

  IncomingMessage& operator=(const IncomingMessage& other);
  IncomingMessage& operator=(IncomingMessage&& other);

  MessageData data;
  std::string collapse_key;
  std::string sender_id;
  std::string message_id;
  std::string raw_data;

  // Whether the contents of the message have been decrypted, and are
  // available in |raw_data|.
  bool decrypted = false;
};

}  // namespace gcm

#endif  // COMPONENTS_GCM_DRIVER_COMMON_GCM_MESSAGE_H_


text:
Installs [mosh](http://mosh.mit.edu/) via homebrew

[![Build Status](https://travis-ci.org/davidbanham/puppet-mosh.png?branch=master)](https://travis-ci.org/davidbanham/puppet-mosh)

## Usage

```puppet
include mosh
```

## Required Puppet Modules

* `boxen`
* `homebrew`

## Development

Write code. Run `script/cibuild` to test it. Check the `script`
directory for other useful tools.


text:
int main( int argc, char** argv )
{
  bites::Config config("wabbit.conf");
  auto memc = memcached( config["memcached"].c_str(), config["memcached"].size() );
  if( memc == NULL ){
    std::cout << "Failed to allocate." << std::endl;
    return 1;
  }
  const char* title = "Memcached image";
  cv::namedWindow( title, CV_WINDOW_NORMAL );
  while( true ){
    uint32_t flags;
    memcached_return_t rc;
    size_t value_length;
    auto value = memcached_get( memc, "image", strlen("image"), &value_length, &flags, &rc );
    std::vector<char> buffer( value, value + value_length );
    cv::Mat image = cv::imdecode( buffer, CV_LOAD_IMAGE_COLOR );
    cv::imshow( title, image );
    cv::waitKey( 1 );
  }
}


text:
#nullable enable
using Content.Server.GameObjects.Components.Mobs;
using Content.Server.Utility;
using Content.Shared.GameObjects.Components;
using Content.Shared.Interfaces;
using Content.Shared.Interfaces.GameObjects.Components;
using Content.Shared.Preferences.Appearance;
using Robust.Server.GameObjects.Components.UserInterface;
using Robust.Server.Interfaces.GameObjects;
using Robust.Shared.GameObjects;
using Robust.Shared.Localization;
using Robust.Shared.Maths;
using Robust.Shared.ViewVariables;

namespace Content.Server.GameObjects.Components
{
    [RegisterComponent]
    [ComponentReference(typeof(IActivate))]
    public class MagicMirrorComponent : SharedMagicMirrorComponent, IActivate
    {
        [ViewVariables] private BoundUserInterface? UserInterface => Owner.GetUIOrNull(MagicMirrorUiKey.Key);

        public override void Initialize()
        {
            base.Initialize();

            if (UserInterface != null)
            {
                UserInterface.OnReceiveMessage += OnUiReceiveMessage;
            }
        }

        public override void OnRemove()
        {
            if (UserInterface != null)
            {
                UserInterface.OnReceiveMessage -= OnUiReceiveMessage;
            }

            base.OnRemove();
        }

        private static void OnUiReceiveMessage(ServerBoundUserInterfaceMessage obj)
        {
            if (obj.Session.AttachedEntity == null)
            {
                return;
            }

            if (!obj.Session.AttachedEntity.TryGetComponent(out HumanoidAppearanceComponent? looks))
            {
                return;
            }

            switch (obj.Message)
            {
                case HairSelectedMessage msg:
                    var map =
                        msg.IsFacialHair ? HairStyles.FacialHairStylesMap : HairStyles.HairStylesMap;
                    if (!map.ContainsKey(msg.HairName))
                        return;

                    if (msg.IsFacialHair)
                    {
                        looks.Appearance = looks.Appearance.WithFacialHairStyleName(msg.HairName);
                    }
                    else
                    {
                        looks.Appearance = looks.Appearance.WithHairStyleName(msg.HairName);
                    }

                    break;

                case HairColorSelectedMessage msg:
                    var (r, g, b) = msg.HairColor;
                    var color = new Color(r, g, b);

                    if (msg.IsFacialHair)
                    {
                        looks.Appearance = looks.Appearance.WithFacialHairColor(color);
                    }
                    else
                    {
                        looks.Appearance = looks.Appearance.WithHairColor(color);
                    }

                    break;
            }
        }

        public void Activate(ActivateEventArgs eventArgs)
        {
            if (!eventArgs.User.TryGetComponent(out IActorComponent? actor))
            {
                return;
            }

            if (!eventArgs.User.TryGetComponent(out HumanoidAppearanceComponent? looks))
            {
                Owner.PopupMessage(eventArgs.User, Loc.GetString("You can't have any hair!"));
                return;
            }

            UserInterface?.Toggle(actor.playerSession);

            var msg = new MagicMirrorInitialDataMessage(looks.Appearance.HairColor, looks.Appearance.FacialHairColor, looks.Appearance.HairStyleName,
                looks.Appearance.FacialHairStyleName);

            UserInterface?.SendMessage(msg, actor.playerSession);
        }
    }
}


text:
Browse Selections

My Music

Downloads

Queue

Entertainment

           ADD PLAYLIST


text:
package cz.kamenitxan.jakon.webui.functions

import java.util
import com.mitchellbosecke.pebble.extension.Function
import com.mitchellbosecke.pebble.template.{EvaluationContext, PebbleTemplate}
import cz.kamenitxan.jakon.core.database.DBHelper
import cz.kamenitxan.jakon.core.model.{BasicJakonObject, JakonObject}

import java.sql.Connection

class LinkFun extends Function {
	val URL_BY_ID_SQL = "SELECT url FROM JakonObject WHERE id = ?"

	override def execute(args: util.Map[String, AnyRef], self: PebbleTemplate, context: EvaluationContext, lineNumber: Int): AnyRef = {
		val id = args.get("id").asInstanceOf[Long].toInt
		implicit val conn: Connection = DBHelper.getConnection
		try {
			val stmt = conn.prepareStatement(URL_BY_ID_SQL)
			stmt.setInt(1, id)
			val jo = DBHelper.selectSingle(stmt, classOf[BasicJakonObject]).entity.asInstanceOf[JakonObject]
			if (jo == null) {
				return ""
			}
			"" + jo.createUrl + ""
		} finally {
			conn.close()
		}
	}

	override def getArgumentNames: util.ArrayList[String] = {
		val names = new util.ArrayList[String]
		names.add("id")
		names
	}
}


text:
package eu.chargetime.ocpp.model;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Calendar;

/**
 * Test model used to check conversion of different field types.
 * Used for tests.
 */
@XmlRootElement
public class TestModel {
    private String stringTest;
    private Calendar calendarTest;
    private Integer integerTest;
    private int intTest;
    private Long longTest;
    private long genericLongTest;
    private Double doubleTest;
    private double genericDoubleTest;
    private Boolean booleanTest;
    private boolean genericBoleanTest;
    private TestModel objectTest;
    private Integer[] arrayTest;

    public Integer[] getArrayTest() {
        return arrayTest;
    }

    @XmlElement
    public void setArrayTest(Integer[] arrayTest) {
        this.arrayTest = arrayTest;
    }

    public TestModel getObjectTest() {
        return objectTest;
    }

    @XmlElement
    public void setObjectTest(TestModel objectTest) {
        this.objectTest = objectTest;
    }

    public boolean isGenericBoleanTest() {
        return genericBoleanTest;
    }

    @XmlElement
    public void setGenericBoleanTest(boolean genericBoleanTest) {
        this.genericBoleanTest = genericBoleanTest;
    }

    public Boolean getBooleanTest() {
        return booleanTest;
    }

    @XmlElement
    public void setBooleanTest(Boolean booleanTest) {
        this.booleanTest = booleanTest;
    }

    public double getGenericDoubleTest() {
        return genericDoubleTest;
    }

    @XmlElement
    public void setGenericDoubleTest(double genericDoubleTest) {
        this.genericDoubleTest = genericDoubleTest;
    }

    public Double getDoubleTest() {
        return doubleTest;
    }

    @XmlElement
    public void setDoubleTest(Double doubleTest) {
        this.doubleTest = doubleTest;
    }

    public long getGenericLongTest() {
        return genericLongTest;
    }

    @XmlElement
    public void setGenericLongTest(long genericLongTest) {
        this.genericLongTest = genericLongTest;
    }

    public Long getLongTest() {
        return longTest;
    }

    @XmlElement
    public void setLongTest(Long longTest) {
        this.longTest = longTest;
    }

    public int getIntTest() {
        return intTest;
    }

    @XmlElement
    public void setIntTest(int intTest) {
        this.intTest = intTest;
    }

    public Integer getIntegerTest() {
        return integerTest;
    }

    @XmlElement
    public void setIntegerTest(Integer integerTest) {
        this.integerTest = integerTest;
    }

    public Calendar getCalendarTest() {
        return calendarTest;
    }

    @XmlElement
    public void setCalendarTest(Calendar calendarTest) {
        this.calendarTest = calendarTest;
    }

    public String getStringTest() {
        return stringTest;
    }

    @XmlElement
    public void setStringTest(String stringTest) {
        this.stringTest = stringTest;
    }
}


text:
package com.deleidos.rtws.commons.monitor.process;

import com.deleidos.rtws.commons.monitor.core.ProcessMonitor;
import com.deleidos.rtws.commons.net.listener.process.ZookeeperProcess;

public class ZookeeperMonitor extends ProcessMonitor {

	ZookeeperProcess zookeeperProcess = ZookeeperProcess.newInstance();

	public ZookeeperMonitor(String name) {
		super(name);

		/*
		 * Give the process 5 minutes to start and
		 * only monitor at 5 minute intervals
		 */
		setStartupPeriod(1000 * 60 * 5);
		setMonitorInterval(1000 * 60 * 5);
	}

	@Override
	protected void monitor() {
		switch (zookeeperProcess.getStatus()) {
			case Running:
				setStatus(MonitorStatus.OK);
				break;
			case Stopped:
				addError("Zookeeper server is not running.");
				zookeeperProcess.start();
				break;
			default:
				addError("Zookeeper server status is currently unknown.");
				break;
		}
	}

}


text:
from twilio.rest import Client

# Your Account Sid and Auth Token from twilio.com/console
# DANGER! This is insecure. See http://twil.io/secure
account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)

sim = client.supersim.sims('HSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX') \
                     .update(account_sid='ACbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb')

print(sim.account_sid)


text:
package client_test

import (
	"fmt"
	"testing"

	"github.com/influxdata/usage-client/v1"
	"github.com/stretchr/testify/require"
)

func Test_Client_RegistrationURL(t *testing.T) {
	r := require.New(t)
	c := client.New("foo")
	u, _ := c.RegistrationURL(client.Registration{
		ClusterID:   "clus1",
		Product:     "chronograf",
		RedirectURL: "http://example.com",
	})
	r.Equal("https://usage.influxdata.com/start?cluster_id=clus1&product=chronograf&redirect_url=http%3A%2F%2Fexample.com", u)
}

func Test_Registration_IsValid(t *testing.T) {
	r := require.New(t)
	reg := client.Registration{}
	err := reg.IsValid()
	r.Error(err)

	reg.ClusterID = "clus1"
	err = reg.IsValid()
	r.Error(err)

	reg.ClusterID = ""
	reg.Product = "foo"
	err = reg.IsValid()
	r.Error(err)

	reg.ClusterID = "clus1"
	reg.Product = "foo"
	err = reg.IsValid()
	r.NoError(err)
}

// Example of getting a registration URL for a product
func Example_registrationURL() {
	c := client.New("")
	r := client.Registration{
		ClusterID:   "clus1",
		Product:     "chronograf",
		RedirectURL: "http://example.com",
	}

	s, _ := c.RegistrationURL(r)
	fmt.Printf("s: %s\n", s)
	// https://usage.influxdata.com/start?cluster_id=clus1&product=chronograf&redirect_url=http%3A%2F%2Fexample.com
}


text:
package org.glowroot.agent.plugin.api.util;

import java.util.Collection;
import java.util.List;

import org.glowroot.agent.plugin.api.internal.PluginService;
import org.glowroot.agent.plugin.api.internal.PluginServiceHolder;

public class ImmutableList {

    private static final PluginService service = PluginServiceHolder.get();

    private ImmutableList() {}

    public static <E> List<E> copyOf(Collection<E> elements) {
        return service.toImmutableList(elements);
    }
}


text:
<?php

namespace NetSuite\Classes;

class GetSelectValueFilter {
    public $filterValue;
    public $operator;
    static $paramtypesmap = array(
        "filterValue" => "string",
        "operator" => "GetSelectValueFilterOperator",
    );
}


text:
import React from 'react';
import { Form } from 'src/components/Form';

import { recurseReactClone } from './utils';
import Field from './Field';

interface FieldsetProps {
  children: React.ReactNode;
  onChange: Function;
  item: Record<string, any>;
  title: React.ReactNode;
  compact: boolean;
}

type fieldKeyType = string | number;

export default class Fieldset extends React.PureComponent<FieldsetProps> {
  static defaultProps = {
    compact: false,
    title: null,
  };

  constructor(props: FieldsetProps) {
    super(props);
    this.onChange = this.onChange.bind(this);
  }

  onChange(fieldKey: fieldKeyType, val: any) {
    return this.props.onChange({
      ...this.props.item,
      [fieldKey]: val,
    });
  }

  render() {
    const { title } = this.props;
    const propExtender = (field: { props: { fieldKey: fieldKeyType } }) => ({
      onChange: this.onChange,
      value: this.props.item[field.props.fieldKey],
      compact: this.props.compact,
    });
    return (
      <Form className="CRUD" layout="vertical">
        {title && <legend>{title}</legend>}
        {recurseReactClone(this.props.children, Field, propExtender)}
      </Form>
    );
  }
}


text:
<?php

namespace UCSC\TimeTableBundle\Controller;

use UCSC\DatabaseBundle\Entity\ExamHall;

use UCSC\DatabaseBundle\Entity\Course;

use UCSC\DatabaseBundle\Entity\ExamTimeTable;

use Symfony\Component\HttpFoundation\Request;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

use Symfony\Component\HttpFoundation\Response;

class ExamTimeTableController extends Controller
{

	public function selectsemesterAction(Request $request)
	{
		$form = $this->createFormBuilder()
		->add('semester', 'choice', array('choices' => array('1' => '1', '2' => '2'),'multiple'  => false,'expanded'=>true))
		->getForm();

		if ($request && $request->getMethod() == 'POST') {

			$form->bindRequest($request);

			$data = $form->getData();

			$repository = $this->getDoctrine()->getRepository('UCSCDatabaseBundle:Course');
			$courses = $repository->findBy(array('sem' => $data['semester']));

			foreach ($courses as $course){

				$cid=$course->getCourseID();
				$c[$cid]=$cid;
			}

			$repository = $this->getDoctrine()->getRepository('UCSCDatabaseBundle:ExamHall');
			$halls = $repository->findAll();

			foreach($halls as $hall) {

				$hid=$hall->getHallId();
				$h[$hid]=$hid;

			}

			if($type == 'update') {

				$repository = $this->getDoctrine()->getRepository('UCSCDatabaseBundle:ExamTimeTable');
				$table = $repository->findOneBy(array('sem' => $data['semester']));

				$form1 = $this->createForm(new TimeTableType($c,$h), $table);

				return $this->render('UCSCTimeTableBundle:ExamTimeTable:update_examtimetable.html.twig',array('form' => $form->createView(),
						'form1' => $form1->createView(),'method'=>'post','type'=>$type,'degree' => $data['degree'], 'sem' => $data['semester']));
			}

			else {

				$repository = $this->getDoctrine()->getRepository('UCSCDatabaseBundle:ExamTimeTable');
				$table = $repository->findBy(array('sem' => $data['semester']));

				if ($table == NULL ){
					$timetable = new TimeTable();

					}

					$timetable->setSem($data['semester']);
					$timetable->setDegree($data['degree']);

					$form1 = $this->createForm(new TimeTableType($c,$h), $timetable);

					return $this->render('UCSCTimeTableBundle:ExamTimeTable:enter_examtimetable.html.twig', array('form' => $form->createView(),
							'form1' => $form1->createView(), 'method'=>'post','type'=>$type,'degree' => $data['degree'], 'sem' => $data['semester']));

				}
				else{

					return new Response('The student registation is valid! ');

				}
			}

		}

		return $this->render('UCSCTimeTableBundle:ExamTimeTable:enter_examtimetable.html.twig', array('form' => $form->createView(), 'method'=>'get','type'=>$type));
	}

	public function submittableAction(Request $request,$type,$degree,$sem)
	{
		if($type == 'update') {
			$em = $this->getDoctrine()->getEntityManager();
			$repository = $em->getRepository('UCSCDatabaseBundle:TimeTable');
			$table = $repository->findOneBy(array('sem' => $sem,'degree' => $degree));
			//throw $this->createNotFoundException($sem);
			$form = $this->createForm(new TimeTableType(array(),array()), $table);

			if ($request->getMethod() == 'POST') {
				$form->bindRequest($request);

				if($form->isValid()) {

					$em->flush();
				}
				else {
					throw $this->createNotFoundException("form is not valid");
				}

			}
		}
		else {

			$timetable = new TimeTable();

			for($i=0;$i<10;$i++){
				$tslot[$i] = new TimeSlot();
				$tslot[$i]->setPeriod($i);
				$timetable->getSlots()->add($tslot[$i]);

			}

			$form = $this->createForm(new TimeTableType(array(),array()), $timetable);

			if ($request->getMethod() == 'POST') {
				$form->bindRequest($request);

				if($form->isValid()) {

					$em = $this->getDoctrine()->getEntityManager();
					$em->persist($timetable);

					for($i=0;$i<10;$i++) {
						$tslot[$i]->setTimetable($timetable);
						$em->persist($tslot[$i]);
					}

					$em->flush();
				}
				else {
					throw $this->createNotFoundException("form is not valid");
				}

			}
		}

		return $this->redirect($this->generateUrl('homepage'));

	}

}


text:
  class AccountsController < ApplicationController
  def index
    @accounts = Account.all
  end

  def deposit_form
    @account = Account.find_by_name params[:id]
    @deposit = Account::DepositCommand.new
  end

  def deposit
    @account = Account.find_by_name params[:id]
    @deposit = @account.deposit params[:deposit]

    if @deposit.success?
      redirect_to root_path, :notice => "Deposited #{@deposit.amount} to #{@account.name}'s account."
    else
      render "deposit_form"
    end
  end

  def withdraw_form
    @account = Account.find_by_name params[:id]
    @withdraw = Account::WithdrawCommand.new
  end

  def withdraw
    @account = Account.find_by_name params[:id]
    @withdraw = @account.withdraw params[:withdraw]

    if @withdraw.success?
      redirect_to root_path, :notice => "Withdrew #{@withdraw.amount} from #{@account.name}'s account."
    else
      render "withdraw_form"
    end
  end

  def transfer_form
    @accounts = Account.all
    @transfer = Account::TransferCommand.new
  end

  def transfer
    @transfer = Account::TransferCommand.new(params[:transfer])

    if @transfer.call.success?
      redirect_to root_path, :notice => "Transferred #{@transfer.amount} from #{@transfer.from.name}'s account to #{@transfer.to.name}'s account."
    else
      @accounts = Account.all
      render "transfer_form"
    end
  end
end


text:
package main

import "testing"

func TestEx16(t *testing.T) {
	actual := join("?", "a", "b", "c")
	expected := "a?b?c"
	if actual != expected {
		t.Fatalf("actual %s expected %s", actual, expected)
	}

	actual = join("", "a", "b", "c")
	expected = "abc"
	if actual != expected {
		t.Fatalf("actual %s expected %s", actual, expected)
	}
}


text:
<?php
declare(strict_types = 1);

namespace App\Services\Auth\Exceptions;

use App\Exceptions\DomainException;

class UserDoesNotExistException extends DomainException
{
    public function __construct($criteria = null)
    {
        if (!empty($criteria)) {
            $criteria = "User [{$criteria}] does not exist";
        }

        parent::__construct($criteria, 0, null);
    }
}


text:
from abc import ABCMeta, abstractmethod, abstractproperty
from ..decorators import task
from ..errors import NoTaskFoundError, TaskError
from ..utils import METHOD_GET, METHOD_POST
import ipdb, inspect

#The AbstractTask superclass is inheritable for crowdwork implementations.
#Every AbstractTask has a get() and post() method that mirrors the rendering and validating activities
#that are associated with every crowd task, respectively. Subclasses may extend this definition as necessary.
class AbstractTask:
    __metaclass__ = ABCMeta
    workflow = None #Parent WorkFlow.
    auth_required = False

    def __init__(self, workflow):
        self.workflow = workflow

    def execute(self, crowd_request, **kwargs):
        method = crowd_request.get_method()
        if method == METHOD_GET:
            return self.get(crowd_request, **kwargs)
        elif method == METHOD_POST:
            return self.post(crowd_request, **kwargs)
        raise NoTaskFoundError(value="No/Invalid Method (%s) found in CrowdRequest." % method)

    #This boolean authentication function needs to be implemented if class decorator is declared.
    #Define authentication protocol for Task here.
    def is_authenticated(self):
        raise NotImplementedError

    def get_name(self):
        return self.__class__.__name__

    @abstractmethod
    @task
    def get(self, crowd_request, data, **kwargs):
        raise NotImplementedError

    @abstractmethod
    @task
    def post(self, crowd_request, form, **kwargs):
        raise NotImplementedError

    def __repr__(self):
        return "<Task: %s>" % (self.__class__.__name__)


text:
'use strict';

var EventEmitter = require('events').EventEmitter;
var inherits = require('inherits');

function Stream() {
  EventEmitter.call(this);
}

inherits(Stream, EventEmitter);

module.exports = Stream;

Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
Stream.Stream = Stream;


text:
<?php

namespace Koalamon\IncidentDashboardBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use KoalamonCom\Plattform\HelpBundle\Entity\SupportHint;

/**
 * Event
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Koalamon\IncidentDashboardBundle\Entity\IncidentRepository")
 */
class Incident implements HistoryAwareEntity, \JsonSerializable
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\ManyToOne(targetEntity="EventIdentifier", inversedBy="events")
     * @ORM\JoinColumn(name="event_identifier_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     **/
    private $eventIdentifier;

    /**
     * @ORM\ManyToOne(targetEntity="Event", inversedBy="events")
     * @ORM\JoinColumn(name="event_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     **/
    private $firstEvent;

    /**
     * @var User
     *
     * @ORM\ManyToOne(targetEntity="User", inversedBy="acknowledged")
     * @ORM\JoinColumn(name="acknowledge_by", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     **/
    private $acknowledgedBy;

    /**
     ** @ORM\OneToMany(targetEntity="KoalamonCom\Plattform\HelpBundle\Entity\SupportHint", mappedBy="incident")
     */
    private $supportHints;

    /**
     * @ORM\Column(name="time_to_acknowledge", type="integer", nullable=true)
     */
    private $timeToAcknowledge;

    /**
     * @ORM\Column(name="time_to_recover", type="integer", nullable=true)
     */
    private $timeToRecover;

    /**
     * @ORM\Column(type="datetime")
     */
    private $startDate;

    /**
     * @ORM\Column(type="datetime", nullable=true)
     */
    private $endDate;

    /**
     * @ORM\Column(type="integer")
     */
    private $eventCount = 1;

    public function __construct(Event $firstEvent)
    {
        $this->firstEvent = $firstEvent;
        $this->startDate = new \DateTime("now");
    }

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

    /**
     * @return EventIdentifier
     */
    public function getEventIdentifier()
    {
        return $this->eventIdentifier;
    }

    /**
     * @param EventIdentifier $eventIdentifier
     */
    public function setEventIdentifier(EventIdentifier $eventIdentifier)
    {
        $this->eventIdentifier = $eventIdentifier;
    }

    /**
     * @return User
     */
    public function getAcknowledgedBy()
    {
        return $this->acknowledgedBy;
    }

    /**
     * @param User $acknowledgedBy
     */
    public function setAcknowledgedBy(User $acknowledgedBy = null)
    {
        if (!$this->getAcknowledgedBy()) {
            $this->timeToAcknowledge = abs((time() - $this->getStartDate()->getTimestamp()) / 60);
        }
        $this->acknowledgedBy = $acknowledgedBy;
    }

    /**
     * @return \DateTime
     */
    public function getStartDate()
    {
        return $this->startDate;
    }

    /**
     * @return \DateTime
     */
    public function getEndDate()
    {
        return $this->endDate;
    }

    public function getDuration()
    {
        if (is_null($this->endDate)) {
            $endDate = new \DateTime('now');
        } else {
            $endDate = $this->endDate;
        }

        return round((($endDate->getTimestamp() - $this->startDate->getTimestamp()) / 60));
    }

    /**
     * @return Event
     */
    public function getFirstEvent()
    {
        return $this->firstEvent;
    }

    /**
     * @param Event $firstEvent
     */
    public function setFirstEvent($firstEvent)
    {
        $this->firstEvent = $firstEvent;
    }

    /**
     * @param \DateTime $endDate
     */
    public function close()
    {
        $this->timeToRecover = abs((time() - $this->getStartDate()->getTimestamp()) / 60);
        $this->endDate = new \DateTime("now");
    }

    public function isClosed()
    {
        return !is_null($this->endDate);
    }

    public function getEventCount()
    {
        return $this->eventCount;
    }

    public function increaseEventCount()
    {
        ++$this->eventCount;
    }

    /**
     * @return SupportHint[]
     */
    public function getSupportHints()
    {
        return $this->supportHints;
    }

    /**
     * @return HistoryEvent
     */
    public function toHistoryElement()
    {
        if ($this->endDate) {
            $duration = $this->getDuration();
        } else {
            $duration = null;
        }

        if ($this->getFirstEvent()) {
            $message = $this->getFirstEvent()->getMessage();
        } else {
            $message = "";
        }

        $historyEvent = new HistoryEvent(
            $this,
            'incident',
            'i' . $this->getId(),
            $message,
            $this->getStartDate(),
            $duration
        );

        $historyEvent->setSystem($this->getEventIdentifier()->getSystem());
        $historyEvent->setTool($this->getEventIdentifier()->getTool());
        return $historyEvent;
    }

    public function jsonSerialize($withFirstEvent = true)
    {
        $jsonArray = [
            'id' => $this->getId(),
            'startDate' => $this->getStartDate()->format('Y-m-d H:i:s'),
            'tool' => $this->getEventIdentifier()->getTool()->jsonSerialize(),
            'system' => $this->getEventIdentifier()->getSystem()->jsonSerialize(false, false),
            'knownIssue' => $this->getEventIdentifier()->isKnownIssue(),
            'ignored' => $this->getEventIdentifier()->isIgnoredIssue(),
            'eventIdentifier' => [
                'id' => $this->getEventIdentifier()->getId(),
                'isNonStrict' => $this->getEventIdentifier()->isNonStrict(),
            ],
        ];

        if ($this->getEventIdentifier()->getComponent()) {
            $jsonArray['component'] = [
                'name' => $this->getEventIdentifier()->getComponent()->getName(),
                'url' => $this->getEventIdentifier()->getComponent()->getUrl()
            ];
        }

        if ($this->getFirstEvent() && $withFirstEvent) {
            $jsonArray['firstEvent'] = $this->getFirstEvent()->jsonSerialize(false, false);
        }

        if ($this->acknowledgedBy) {
            $jsonArray['acknowledgedBy'] = $this->acknowledgedBy->jsonSerialize();
        }

        return $jsonArray;
    }
}


text:
oK
==

oK is a toy interpreter for a dialect of the [K programming language](http://en.wikipedia.org/wiki/K_(programming_language)) which aims to be an implementation of [K5](http://kparc.com), the still-evolving bleeding edge version of the language. Expect oK to be buggy, incomplete and occasionally flat-out wrong, but slowly improving over time. Read the [oK Manual](https://github.com/JohnEarnest/ok/blob/gh-pages/Manual.md) for an overview of oK's operators and syntax.

If you are interested in learning more about K, consider downloading the free version of [kdb](http://kx.com/software-download.php) from Kx Systems, the fine makers of K. Alternatively, [Kona](https://github.com/kevinlawler/kona) is an open-source reimplementation of K3/K4.

oK does not intend to be particularly fast or suitable for any practical purpose beyond learning, instead emphasizing simplicity of implementation. JavaScript was chosen as an implementation language because it is familar to many programmers and has first-class functions.

Trying oK
---------
The easiest way to run oK is using the [Browser-based REPL](http://johnearnest.github.io/ok/index.html). This REPL features a few special commands which can be issued at the beginning of a line:

- `\\` (while entering a multiline expression) cancel this expression.
- `\e` toggle the scratchpad editor pane. This editor's content is persisted via localstorage (in case your browser crashes or is closed accidentally).
- `\r` run the contents of the editor pane. Alternately, press shift+enter with the editor focused.
- `\c` clear the output log.
- `\t` time executing the remainder of the line.
- `\x` execute the remainder of the line and show a step-by-step trace.
- `\f` list all presently defined functions.
- `\v` list all presently defined variables.
- `\u` generates a code url from the remainder of the line, as described below.

oK provides several numbered IO verbs:

- dyadic `0:` takes a symbol as its left argument and writes the right argument to that destination as text. Currently the symbol is ignored and output is always sent to the console. Use the empty symbol as a left argument.
- monadic `0:` takes a string as its right argument and performs a synchronous HTTP request to that URL. The result will be a tuple containing the HTTP status code followed by the response, if any. You can use this in conjunction with pastebins to load code from elsewhere or access RESTful web APIs. Note that most web browsers restrict cross-site HTTP requests from javascript under the [same-origin policy](http://en.wikipedia.org/wiki/Same-origin_policy)- you'll need a server which responds with an Access-Control-Allow-Origin header. GitHub gists will do:

		  url: "https://gist.githubusercontent.com/anonymous/cc0ef05c00940044eb0a/raw/"
		"https://gist.githubusercontent.com/anonymous/cc0ef05c00940044eb0a/raw/"
		  0:url
		(200
		 "/ generate a times table\nt*/:t:!10\n")
		  .*|0:url
		(0 0 0 0 0 0 0 0 0 0
		 0 1 2 3 4 5 6 7 8 9
		 0 2 4 6 8 10 12 14 16 18
		 0 3 6 9 12 15 18 21 24 27
		 0 4 8 12 16 20 24 28 32 36
		 0 5 10 15 20 25 30 35 40 45
		 0 6 12 18 24 30 36 42 48 54
		 0 7 14 21 28 35 42 49 56 63
		 0 8 16 24 32 40 48 56 64 72
		 0 9 18 27 36 45 54 63 72 81)

- monadic `1:` works just like monadic 0: except it expects the response to be JSON rather than arbitrary text, and it attempts to parse it into a K data structure you can then manipulate:

		  url:"http://api.openweathermap.org/data/2.5/weather?q=London,uk"
		"http://api.openweathermap.org/data/2.5/weather?q=London,uk"
		  t:1:url
		(200;[coord:[lon:-0.13;lat:51.51];sys:[type:1;id:5091;message:0.0224;country:"GB";sunrise:1425709902;sunset:1425750674];weather:,[id:800;main:"Clear";description:"Sky is Clear";icon:"01d"];base:"cmc stations";main:[temp:288.11;pressure:1024;humidity:44;temp_min:286.85;temp_max:289.82];wind:[speed:6.2;deg:230];clouds:[all:0];dt:1425736003;id:2643743;name:"London";cod:200])
		  t[1;`weather;0;`description]
		"Sky is Clear"

If you visit the page with a `?run=` URL parameter, the remainder of the URL will be URI decoded and executed. The `\u` command can create a link for you based on an expression. You can combine this feature with monadic `0:` to run larger programs:

	  \u 1+2
	oK code url:
	http://johnearnest.github.io/ok/index.html?run=%201%2B2

	  \u .*|0:"https://gist.githubusercontent.com/anonymous/cc0ef05c00940044eb0a/raw/"
	oK code url:
	http://johnearnest.github.io/ok/index.html?run=%20.*%7C0%3A%22https%3A%2F%2Fgist.githubusercontent.com%2Fanonymous%2Fcc0ef05c00940044eb0a%2Fraw%2F%22

Command Line Mode
-----------------
Alternatively, you can run oK via the command line with  [Node.js](http://nodejs.org). `test.js` runs a series of automated tests:

	je@indigo$ node test.js

You can also try out oK from the included REPL. Note that at the time of writing, the release version of Node.js does not portably support blocking reads from stdin- the REPL has been tested with Node v0.11.14 on OSX.

	je@indigo$ node repl.js
	oK v0.1

	  +/4 5 6
	15

	  1 2 3+2 5
	length error.

	  a:"some text"
	"some text"

	  "t"=a
	0 0 0 0 0 1 0 0 1

This REPL is very simplistic compared to the CLI provided in a complete K interpreter and lacks interactive debugging facilities. When you're done, type `\\` to exit. If you supply a filename as an argument to the REPL, it will instead execute that file:

	je@indigo$ node repl.js examples/hangman.k
	_____ > p
	_pp__ > e
	_pp_e > a
	app_e > l
	apple

How Does It Work?
-----------------
oK's interpreter centers around trees of objects (called k-values) which represent K datatypes. Every k-value has a field `t` which indicates the object type and a `v` field containing JavaScript value(s) such as arrays or numbers. Some k-values do not correspond to K types but instead represent nodes of an abstract syntax tree (AST) comprising a program, and may contain additional fields.

The section titled _Primitive Verbs_ contains implementations of the wide range of primitive operators in K which operate on and return k-values. In these implementations the overloaded variations of K primitives which operate on different datatypes have often been split into several distinct functions.

The section titled _Primitive Adverbs_ is similar, providing implementations of K adverbs which manipulate k-values. One way that oK deviates from other K interpreters is that it does not internally discriminate between lists and unitype vectors, which forces adverbs to perform dynamic dispatch of the verb they apply every time they iterate. This simplifies the implementation but comes with substantial overhead.

The _Interpreter_ provides a verb dispatch table (organized between monadic/dyadic forms and variations between verb forms applied to combinations of list and non-list (atomic) datatypes) and mechanisms for walking k-value trees to evaluate expressions. The functions `am`, `ad`, `ar` and `al` generalize the process of "conforming" datatypes to feed into primitive functions. This section also contains the functions which implement the `.`, `@` and `amend`/`dmend` primitives as they are more tightly connected to and used by the interpreter than most others. This section also contains a class called Environment which represents a linked-dictionary structure used for variable lookup and scope management. To execute a k-value tree, use the `run()` function and provide a reference to a global Environment to reference.

The _Tokenizer_ uses regular expressions to identify and consume lexical tokens from K source text. Presently the tokenizer maintains some global state so that it is not necessary to thread tokenizer state throughout the parser.

The _Parser_ uses an ad-hoc left-to-right recursive-descent approach. This gets a bit hairy and is likely to change substantially over time. As it breaks a program into tokens and assembles a k-value AST, it also desugars some special syntactic forms to avoid complexity in the interpreter. For example, a compound assignment of the form

	t[x]+:y

Is rewritten into an application of the form `dmend`:

	..[`t;x;+:;y]

To convert a JavaScript string into a k-value tree, use the `parse()` function.

The _Prettyprinter_ reverses the work of the Parser, turning a k-value back into a human-comprehensible, properly indented form. oK's prettyprinter output of a function or verb chain represents the desugared form of expressions and thus during debugging can help clarify whether a problem occurs at the parser or interpreter level. Formatting is very similar to that used by other K interpreters but may differ in small ways, generally erring on the side of longer, more explicit output. Invoke the prettyprinter by using the `format()` function on a k-value or JavaScript array of k-values.


text:
Rails.application.routes.draw do
  mount Cms::Engine => "/cms"
end


text:
'use strict';
var assert = require('assert');
var solution = require('./Brackets');

it('should be properly nested', function() {
    assert.deepEqual(solution(''), 1);
});

it('should be properly nested', function() {
    assert.deepEqual(solution('{[()()]}'), 1);
});

it('should be properly nested', function() {
    assert.deepEqual(solution('()()'), 1);
});

it('should be properly nested', function() {
    assert.deepEqual(solution('()(){}'), 1);
});

it('should be properly nested', function() {
    assert.deepEqual(solution('{[()()]}()'), 1);
});

it('should not be properly nested', function() {
    assert.deepEqual(solution('([)()]'), 0);
});


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package v.i.p_software;

import java.awt.Color;
import java.awt.Toolkit;

/**
 *
 * @author chokayg3
 */
public class WELCOME_INTERFACE extends javax.swing.JFrame {

    /**
     * Creates new form WELCOME_INTERFACE
     */
    public WELCOME_INTERFACE() {
        this.getContentPane().setBackground(Color.darkGray);
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        newbooking_button = new javax.swing.JButton();
        admin_button = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("WELCOME");
        setIconImage(Toolkit.getDefaultToolkit ( ).getImage(getClass().getResource("vip-48.png")));
        setType(java.awt.Window.Type.UTILITY);

        jPanel1.setLayout(null);

        jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\fred\\Desktop\\VIP_PROJECT\\VIP_PROJECT\\src\\v\\i\\p_software\\vipwelcome.png")); // NOI18N
        jPanel1.add(jLabel1);
        jLabel1.setBounds(-10, 0, 700, 380);

        newbooking_button.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        newbooking_button.setIcon(new javax.swing.ImageIcon("C:\\Users\\fred\\Pictures\\add_user-48.png")); // NOI18N
        newbooking_button.setMnemonic('N');
        newbooking_button.setText("New Booking");
        newbooking_button.setToolTipText("Create a new booking by entering your details");
        newbooking_button.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newbooking_button.setRolloverEnabled(true);
        newbooking_button.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newbooking_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newbooking_buttonActionPerformed(evt);
            }
        });
        jPanel1.add(newbooking_button);
        newbooking_button.setBounds(70, 150, 110, 80);

        admin_button.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N
        admin_button.setIcon(new javax.swing.ImageIcon("C:\\Users\\fred\\Pictures\\administrator2-48.png")); // NOI18N
        admin_button.setMnemonic('A');
        admin_button.setText("Administrator");
        admin_button.setToolTipText("Restricted to only admin only");
        admin_button.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        admin_button.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        admin_button.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                admin_buttonActionPerformed(evt);
            }
        });
        jPanel1.add(admin_button);
        admin_button.setBounds(500, 150, 118, 80);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 683, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 379, Short.MAX_VALUE)
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void newbooking_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newbooking_buttonActionPerformed
        // TODO add your handling code here:
        new BOOKING_VIEW().setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_newbooking_buttonActionPerformed

    private void admin_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_admin_buttonActionPerformed
        // TODO add your handling code here:
        new ADMIN_LOGIN().setVisible(true);
        this.setVisible(false);
    }//GEN-LAST:event_admin_buttonActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(WELCOME_INTERFACE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(WELCOME_INTERFACE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(WELCOME_INTERFACE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(WELCOME_INTERFACE.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new WELCOME_INTERFACE().setVisible(true);
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton admin_button;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton newbooking_button;
    // End of variables declaration//GEN-END:variables
}


text:
<?php
/**
 * Created by Slava Basko <basko.slava@gmail.com>
 * Date: 9/2/16
 */

namespace Yandex\Action;

use Yandex\Auth\Token;

interface ActionInterface
{
    /**
     * @return string
     */
    public function getUrl();

    /**
     * @return string
     */
    public function getHttpMethod();

    /**
     * @return Token
     */
    public function getToken();
}


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

public class WordDictionary
{
    public static void Main()
    {
        Dictionary<string, string> dictionary = new Dictionary<string, string>();
        dictionary.Add(".NET", "platform for applications from Microsoft");
        dictionary.Add("CLR", "managed execution environment for .NET");
        dictionary.Add("namespace", "hierarchical organization of classes");

        // For additional check
        // ENTER the length of the divitionary
        //  int length=int.Parse(Console.ReadLine());
        //  for (int i=0;i<length;i++)
        //  {
        //      Console.Write("Enter string index: ");
        //      string index=Console.ReadLine();
        //      Console.Write("Enter string meaning: ");
        //      string meaning = Console.ReadLine();
        //      dictionary.Add(index,meaning);
        //  }
        bool isChecking = true;
        while (isChecking)
        {
            Console.WriteLine("Enter string index for check from the dictionary: ");
            Console.WriteLine("(if you want to end the cycle type END):");
            string index = Console.ReadLine();
            if (dictionary.ContainsKey(index))
            {
                Console.WriteLine(dictionary[index]);
                Console.WriteLine();
            }
            else if (index == "END")
            {
                isChecking = false;
            }
        }
    }
}


text:
export SRCROOT="<%= compileDir %>" &&
mkdir -p $SRCROOT &&
cd $SRCROOT &&

### Set versions and directories
export PVERSION_SW="<%= softwareVersion %>" &&

### Install
cd $SRCROOT && . ../build_functions.sh &&
export PNAME="mcelog" &&
export PVERSION="$PVERSION_SW" &&
export PDIR="$PNAME-$PVERSION" &&
export PFILE="$PDIR.tar.bz2" &&
export PURI="http://slackbuilds.org/mirror/slackware/slackware64-14.0/source/a/mcelog/$PFILE" &&

rm -rf $PDIR &&
GetUnpackCd &&

make &&
make install &&

cd $SRCROOT &&
rm -rf $PDIR &&

true


text:
@implementation UIColor (Additions)

/// 字符串转颜色
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    if ([cString length] < 6)
        return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return DEFAULT_VOID_COLOR;

    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((CGFloat) r / 255.0f)
                           green:((CGFloat) g / 255.0f)
                            blue:((CGFloat) b / 255.0f)
                           alpha:1.0f];
}

/// 字符串转颜色,带alpha
+ (UIColor *)colorWithHexString:(NSString *)stringToConvert withAlpha:(CGFloat)alpha
{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];

    if ([cString length] < 6)
        return DEFAULT_VOID_COLOR;
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return DEFAULT_VOID_COLOR;

    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];

    range.location = 2;
    NSString *gString = [cString substringWithRange:range];

    range.location = 4;
    NSString *bString = [cString substringWithRange:range];

    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];

    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:alpha];
}

UIColor *UIColorWithRGB(NSUInteger rgb) {
    return UIColorWithRGBA(rgb, 1.0f);
}

UIColor *UIColorWithRGBA(NSUInteger rgb, CGFloat alpha) {
    UIColor *normalColor = [UIColor colorWithRed:((float)((rgb & 0xFF0000) >> 16))/255.0 green:((float)((rgb & 0xFF00) >> 8))/255.0 blue:((float)(rgb & 0xFF))/255.0 alpha:alpha];
    return normalColor;
}

+ (UIColor *)randomColor
{
    CGFloat hue = ( arc4random() % 256 / 256.0 ); //0.0 to 1.0
    CGFloat saturation = ( arc4random() % 128 / 256.0 ) + 0.5; // 0.5 to 1.0,away from white
    CGFloat brightness = ( arc4random() % 128 / 256.0 ) + 0.5; //0.5 to 1.0,away from black
    return [UIColor colorWithHue:hue saturation:saturation brightness:brightness alpha:1];
}

- (UIColor *)addDarkerColorWithValue:(CGFloat)value {
    size_t totalComponents = CGColorGetNumberOfComponents(self.CGColor);
    BOOL isGreyscale = (totalComponents == 2);

    CGFloat const * oldComponents = (CGFloat *)CGColorGetComponents(self.CGColor);
    CGFloat newComponents[4];

    CGFloat (^actionBlock)(CGFloat component) = ^CGFloat(CGFloat component) {

        CGFloat newComponent = component * (1.0 - value);
        return newComponent;
    };

    if (isGreyscale) {
        newComponents[0] = actionBlock(oldComponents[0]);
        newComponents[1] = actionBlock(oldComponents[0]);
        newComponents[2] = actionBlock(oldComponents[0]);
        newComponents[3] = oldComponents[1];
    } else {
        newComponents[0] = actionBlock(oldComponents[0]);
        newComponents[1] = actionBlock(oldComponents[1]);
        newComponents[2] = actionBlock(oldComponents[2]);
        newComponents[3] = oldComponents[3];
    }

    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef newColor = CGColorCreate(colorSpace, newComponents);
    CGColorSpaceRelease(colorSpace);

    UIColor *retColor = [UIColor colorWithCGColor:newColor];
    CGColorRelease(newColor);

    return retColor;
}

- (UIColor *)blendedColorWithFraction: (CGFloat)fraction ofColor: (UIColor *)color2 {
    UIColor *color1 = self;

    CGFloat r1 = 0, g1 = 0, b1 = 0, a1 = 0;
    CGFloat r2 = 0, g2 = 0, b2 = 0, a2 = 0;

    [color1 getRed: &r1 green: &g1 blue: &b1 alpha: &a1];
    [color2 getRed: &r2 green: &g2 blue: &b2 alpha: &a2];

    CGFloat r = r1 * (1 - fraction) + r2 * fraction;
    CGFloat g = g1 * (1 - fraction) + g2 * fraction;
    CGFloat b = b1 * (1 - fraction) + b2 * fraction;
    CGFloat a = a1 * (1 - fraction) + a2 * fraction;

    return [UIColor colorWithRed: r green: g blue: b alpha: a];
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/picker_container"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom">

        <View
            android:id="@+id/picker_top_border"
            style="@style/AppWidget.DeepLine"
            android:layout_alignParentTop="true" />

        <RelativeLayout
            android:id="@+id/picker_opt_container"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/picker_top_border"
            android:background="?attr/widgetBackground"
            android:gravity="center_vertical"
            android:paddingBottom="4.0dip"
            android:paddingTop="4.0dip">

            <Button
                android:id="@+id/btCancel"
                android:layout_width="48.0dip"
                android:layout_height="30.0dip"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="10.0dip"
                android:background="@drawable/red_btn"
                android:gravity="center"
                android:text="@string/picker_cancel"
                android:textColor="?android:textColorSecondary"
                android:textSize="15.0sp" />

            <Button
                android:id="@+id/btFirst"
                android:layout_width="48.0dip"
                android:layout_height="30.0dip"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="20dp"
                android:layout_toRightOf="@+id/btCancel"
                android:background="@drawable/purple_btn"
                android:gravity="center"
                android:text="@string/picker_first"
                android:textColor="?android:textColorSecondary"
                android:textSize="15.0sp" />

            <Button
                android:id="@+id/btLast"
                android:layout_width="48.0dip"
                android:layout_height="30.0dip"
                android:layout_centerHorizontal="true"
                android:layout_marginRight="20dp"
                android:layout_toLeftOf="@+id/btJump"
                android:background="@drawable/purple_btn"
                android:gravity="center"
                android:text="@string/picker_end"
                android:textColor="?android:textColorSecondary"
                android:textSize="15.0sp" />

            <Button
                android:id="@+id/btJump"
                android:layout_width="48.0dip"
                android:layout_height="30.0dip"
                android:layout_alignParentRight="true"
                android:layout_marginRight="10.0dip"
                android:background="@drawable/real_blue_btn"
                android:gravity="center"
                android:text="@string/picker_jump"
                android:textColor="?android:textColorSecondary"
                android:textSize="15.0sp" />
        </RelativeLayout>

        <View
            android:id="@+id/picker_bottom_border"
            style="@style/AppWidget.DeepLine"
            android:layout_below="@+id/picker_opt_container" />

        <com.gzsll.hupu.widget.MaterialNumberPicker
            android:id="@+id/picker"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/picker_bottom_border"
            app:npBackground="?attr/widgetBackground"
            app:npSeparatorColor="@color/colorAccent"
            app:npTextColor="@color/colorPrimary"
            app:npTextSize="16sp"
            app:npWrapValue="true" />

    </RelativeLayout>
</FrameLayout>


text:
// Type definitions for koa-cookie 1.0
// Project: https://github.com/varunpal/koa-cookie
// Definitions by: John Hou <https://github.com/dancon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3

/* =================== USAGE ===================

    import cookie = require("koa-cookie");
    import Koa = require('koa');

    const app = new Koa();
    app.use(cookie());

 =============================================== */

import { Middleware } from 'koa';

declare module 'koa' {
    interface BaseContext {
        cookie: Record<string, any>;
    }
}

declare function cookie(): Middleware;

export = cookie;


text:
/*jshint node: true, expr: true */
"use strict";

var url     = require('url');
var util    = require('util');
var  _      = require('lodash');
var crypto  = require('crypto');
var Chance  = require('chance');
var request = require('request');

var chance = new Chance();

var API_10_BASE_PATH = "/rest/api/1.0";
var API_10_AUTH_PATH = API_10_BASE_PATH + "/users/";

function StashClient(options, log) {
    this.log = log;
    this.url   = options.repository_host;
    this.repositoryUser = { username: options.repository_user, password: options.repository_password };

    this.log.info("configured for " + this.url);

    this.encryptionKey = options.token_encryption_key;
    this.loginTokenTTL = options.login_token_ttl;
    this.setReadAuthorizationPolicy(options.read_authorization_policy);

    this.httpOptions = options.http_client_options;
    this.httpOptions.json = true; // always expect JSON data
}

StashClient.prototype.currentTime = function() {
  return Date.now();
}

StashClient.prototype.setReadAuthorizationPolicy = function(policyName) {
  switch (policyName) {
    case 'repository-read-permission':
      this.readAuthorizer = this.hasRepositoryReadPermission;
      break;
    case 'authenticated':
      this.readAuthorizer = this.isAuthenticated;
      break;
    default:
      throw new Error("unsupported read authorization policy: " + policyName);
      break;
  }
  this.log.info("read authorization policy set to: " + policyName);
}

StashClient.prototype.basicAuth = function(username, password, cb) {
  var self = this;

  request.get(this.url + API_10_AUTH_PATH + username, this.httpOptions, function (err, response, data) {
    if (err) {
      return cb(err);
    }
    if (!data || data == null) {
      self.log.warn("empty response from server to authentication request for " + username);
      return cb(new Error("no data from server (" + response.statusCode + ")"));
    }

    // 200 OK --> SUCCESS, IF ALSO USER DATA MATCHES
    if (response.statusCode == 200) {
        if (!data.active) {
          self.log.info("npm login for %s rejected as user is not active", username);
          cb(new Error("User is inactive"));
          return;
        }
        var token;
        try {
          token = self._buildBasicToken(username);
          cb(null, data, token); // SUCCESS
        } catch (e) {
          self.log.error("failed to generate login token for %s: %s", username, e.message);
          cb(e);
        }
    } else {
        var msg = (data.errors && data.errors.length > 0) ? data.errors[0].message : 'unknown error (' + response.statusCode + ')';
        self.log.warn("login error for %s: %s", username, msg);
        cb(new Error(msg));
    }
  })
  .auth(username, password, true);
}

// TODO: move token handling to own file and implemnent session handler that automatically
//       extends token TTL when it is used...
StashClient.prototype._buildBasicToken = function(username) {
  var expiresAt = this.currentTime() + (this.loginTokenTTL * 1000);
  return this._encodeToken({mode: 'http-basic', username: username, expiresAt: expiresAt });
};

StashClient.prototype._encodeToken = function(data) {
  data.hash     = chance.guid(); // randomizing data  a bit more...
  var cipher    = crypto.createCipher('aes256', this.encryptionKey);
  var encrypted = cipher.update(JSON.stringify(data), 'utf8', 'hex') + cipher.final('hex');
  return new Buffer(encrypted).toString();
}

StashClient.prototype._decodeToken = function(token) {
  var decipher = crypto.createDecipher('aes256',this.encryptionKey);
  var decoded  = decipher.update(token,'hex','utf8') + decipher.final('utf8');
  return JSON.parse(decoded);
}

StashClient.prototype.validateToken = function (token, cb) {
  var tokenData;
  try {
    tokenData = this._decodeToken(token);
    if (!tokenData.expiresAt || tokenData.expiresAt < this.currentTime()) {
      this.log.warn("login token expired for user %s", tokenData.username);
      cb(null, null);
    } else {
      this.log.debug("login token successfully validated for user %s", tokenData.username);
      cb(null, tokenData);
    }
  } catch (err) {
    this.log.error("failed to decode login token data: " + err.message);
    cb(err);
  }
}

StashClient.prototype.hasPublishPermission = function(token, packageDescriptor, cb) {
  var self = this;
  this.validateToken(token, function (err, data) {
    if (err) return cb(err);
    if (data == null) return cb(null, false);
    self.hasAnyPermission(data.username, packageDescriptor, ['REPO_WRITE','REPO_ADMIN'], cb);
  });
}

StashClient.prototype.hasReadPermission = function(token, packageDescriptor, cb) {
  this.readAuthorizer(token, packageDescriptor, cb);
}

StashClient.prototype.hasRepositoryReadPermission = function(token, packageDescriptor, cb) {
  var self = this;
  this.validateToken(token, function (err, data) {
    if (err) return cb(err);
    if (data == null) return cb(null, false);
    self.hasAnyPermission(data.username, packageDescriptor, ['REPO_WRITE','REPO_ADMIN','REPO_READ'], cb);
  });
}

StashClient.prototype.isAuthenticated = function(token, packageDescriptor, cb) {
  var self = this;
  this.validateToken(token, function (err, data) {
    if (err) {
      self.log.warn("failed to decode login token: " + err);
      cb(new Error("user token is not valid, relogin required"));
      return;
    };
    cb(null, (data != null));
  });
}

StashClient.prototype.hasAnyPermission = function(username, packageDescriptor, permissions, cb) {
  var self = this;
  this.log.debug("checking permissions for user %s to any of %s", username, permissions.join(','));

  if (packageDescriptor.repository.type !== 'git') {
    this.log.warn(packageDescriptor, "repository type in package.json from user %s not set to 'git', rejecting", username);
    cb(new Error('only Git repositories are supported. Ensure that repoitory.type is set to \'git\''));
  }

  var repoURL  = url.parse(packageDescriptor.repository.url);
  var repoPath = repoURL.pathname.replace(/\.git/,'');

  var apiHost = url.parse(this.url).hostname;
  if (apiHost !== repoURL.hostname) {
    this.log.warn('repository host mismatch (%s != %s), rejecting authorization for %s',apiHost, repoURL.hostname, packageDescriptor['_id']);
    return cb(new Error(util.format('repository host mismatch (%s != %s)',apiHost, repoURL.hostname)), false);
  }

  this.log.info("checking permission for %s to repository %s", username, repoPath);
  // check repository permission
  var permissionAPI = API_10_BASE_PATH + repoPath + "/permissions/users?filter=" + username;

  try {
    request.get(this.url + permissionAPI, this.httpOptions, function (err, response, data) {
      if (err) {
         self.log.error('error from permission check: ' + err);
         return cb(err);
      }

      if (response.statusCode !== 200) {
        var errorMessage;
        if (data && data.errors && data.errors.length > 0) {
          errorMessage = data.errors[0].message;
        } else {
           errorMessage = "no valid response data received to a failed request";
        }

        if (response.statusCode === 401) {
          self.log.warn("wrong credentials to Stash API: %s", errorMessage);
        } else if (response.statusCode === 404) {
          self.log.warn("repository not found from Stash: %s", errorMessage);
        } else {
           self.log.error("non-success response to repository permissions check (%s): %s (data: %s)", response.statusCode, errorMessage, JSON.stringify(data));
        }
        return cb(new Error(errorMessage), false);
      }

      self.log.debug(data, 'permission check response data received for user %s', username);
      var hasPermission = false;
      var value = _.find(data.values, function (entry) { return entry.user.name === username; });
      if (value) {
        if (!value.user.active) {
          self.log.info("user %s not active, not authorizing", username);
          return cb(null, false);
        }
        hasPermission = _.contains(permissions, value.permission);
      }
      self.log.info('permission check result for %s: %s', username, hasPermission);
      cb(null, hasPermission);
    })
    .auth(this.repositoryUser.username, this.repositoryUser.password, true);
  } catch (error) {
    this.log.error("failed to query permission status!", err.stack);
    cb(error);
  }
}
module.exports = StashClient;


text:
describe XingApi::Group::Forum::Post do
  describe '.list' do
    it_behaves_like 'a Xing API call'

    it 'invokes the correct API call' do
      expect_request(:get, '/v1/groups/forums/some_id/posts', {})

      described_class.list('some_id')
    end
  end

  describe '.create' do
    it_behaves_like 'a Xing API call'

    it 'invokes the correct API call' do
      expected_options = { title: 'title', content: 'content' }
      expect_request(:post, '/v1/groups/forums/some_id/posts', expected_options)

      described_class.create('some_id', 'title', 'content')
    end
  end
end


text:
/**
 * Support and FAQ: visit Atmel Support
 */

#ifndef CONF_TEST_H
#define CONF_TEST_H

/** UART Interface */
#define CONF_TEST_UART       CONSOLE_UART
/** Baudrate setting */
#define CONF_TEST_BAUDRATE   115200
/** Parity setting */
#define CONF_TEST_PARITY     UART_MR_PAR_NO

#endif /* CONF_TEST_H_INCLUDED */


text:
package fr.upem.user;

import java.util.HashMap;

public class UserManager {

	/**
	 * List of the registered users
	 */
	private final HashMap<String, User> users;

	/**
	 * Default constructor
	 */
	public UserManager() {
		users = new HashMap<>();
		users.put("bcrochez", new User("bcrochez", "abc"));
		users.put("mdamis", new User("mdamis", "123"));
		users.put("mperou", new User("mperou", "abc123"));
	}

	/**
	 * Function to register an user
	 *
	 * @param user name of the user
	 * @param password user's password
	 * @return true if the user has been correctly registered, false otherwise
	 */
	public boolean registerUser(String user, String password) {
		System.out.println(users.keySet());
		if (users.containsKey(user)) {
			return false;
		} else {
			User newUser = new User(user, password);
			users.put(user, newUser);
			newUser.setConnected(true);
			return true;
		}
	}

	/**
	 * Tests if an user exist
	 *
	 * @param user name to test
	 * @return true if the user exists, false otherwise
	 */
	public boolean exist(String user) {
		return users.containsKey(user);
	}

	/**
	 * Connects an user
	 *
	 * @param user user's name
	 * @param password user's password
	 * @return true if the user has been correctly connected, false otherwise
	 */
	public boolean connect(String user, String password) {
		if (!users.containsKey(user)) {
			return false;
		}
		User u = users.get(user);
		if (!u.getPassword().equals(password)) {
			return false;
		} else if (u.isConnected()) {
			return false;
		} else {
			u.setConnected(true);
			return true;
		}
	}

	/**
	 * Disconnects an user
	 *
	 * @param user user's name
	 * @return true if the user has been correctly disconnected, false otherwise
	 */
	public boolean disconnect(String user) {
		if (!users.containsKey(user)) {
			return false;
		}
		User u = users.get(user);
		if (!u.isConnected()) {
			return false;
		} else {
			u.setConnected(false);
			return true;
		}
	}

}


text:
<title>HTML Frames Example - Menu 1</title>

Menu 1

White Page

More Examples:

Example 1

Example 2

Example 3

Example 4

Example 5

iFrames Example


text:
const hasNavigator = typeof navigator !== 'undefined';
const ie_upto10 = hasNavigator && /MSIE \d/.test(navigator.userAgent)
const ie_11up = hasNavigator && /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent)
module.exports = {
  mac: hasNavigator && /Mac/.test(navigator.platform),
  ie: ie_upto10 || !!ie_11up,
  ie_version: ie_upto10 ? document.documentMode || 6 : ie_11up && +ie_11up[1],
  gecko: hasNavigator && /gecko\/\d/i.test(navigator.userAgent),
  ios: hasNavigator && /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent)
}


text:
class ImplicitToString3 {

  void testStringBuilder() {
    StringBuilder sb<caret> = new StringBuilder();
    System.out.println("Hello " + sb);
  }
}


text:
using Microsoft.Extensions.Logging;
using System.Linq;
using uGovernor.Domain;

namespace uGovernor.Commands
{
    class ListCommand : IServerCommand
    {
        readonly Execution _executionLevel;
        private readonly ILogger<ListCommand> _logger;

        public ListCommand(Execution executionLevel, ILogger<ListCommand> logger)
        {
            _executionLevel = executionLevel;
            _logger = logger;
        }

        public void Run(TorrentServer server)
        {
            var torrents = server.GetAllTorrents();

            switch (_executionLevel)
            {
                case Execution.Private:
                    torrents = torrents.Where(x => x.Private);
                    break;

                case Execution.Public:
                    torrents = torrents.Where(x => !x.Private);
                    break;
            }

            if (!torrents.Any())
            {
                _logger.LogInformation("No relevant torrents found...");
                return;
            }

            var longestName = torrents.Max(x => x.Name.Length);
            var hashLength = torrents.Max(x => x.Hash.Length);

            var alignment = " | {0,-" + longestName + "}";

            _logger.LogInformation(" ♦");
            _logger.LogInformation(" | Listing torrents...");

            var line = " ♦" + new string('-', longestName + hashLength + 5) + "♦";
            _logger.LogInformation(line);

            foreach (var torrent in torrents)
            {
                _logger.LogInformation($"{string.Format(alignment, torrent.Name)} : {torrent.Hash} |");
                _logger.LogInformation(line);
            }
        }
    }
}


text:
package com.htbest2000.v2ex.ui;

import roboguice.activity.RoboActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import com.htbest2000.v2ex.R;

public class ActivityHome extends RoboActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_home);
	}

	public void onLatestTopicsClick(View v) {
		Intent i = new Intent(this, TopicListActivity.class);
		startActivity(i);
	}

	public void onAllNodesClick(View v) {
		Intent i = new Intent(this, AllNodesActivity.class);
		startActivity(i);
	}

	public void onNewFoundtopicsClick(View v) {
		Intent i = new Intent(this, AllNodesActivity.class);
		startActivity(i);
	}
}


text:
Node modules which helps call python code in node

Use JSONRPC to communicate nodejs and python.

Can work now.

But libs hasn't published to npm and pypi.

This is still a alpha version. I will use it in my work, and it should get better in the future.

## Install
```
npm i --save node-python-rpc

pip install node-python-rpc
```

## Usage
Start the python rpc server

```
python -mnodepythonrpc --port 8000
```

Nodejs code

```
// python
var python = require('node-python-rpc')({host: 'localhost', port: 28642});
var os = python.import('os')

// nodejs
var path = require('path')

assert(os.path.basename(os.getcwd()) == path.basename(process.cwd()))
```

## Reference
* <https://github.com/JeanSebTr/node-python>
* <http://stackoverflow.com/questions/16586640/node-js-async-to-sync>

## LICENSE
[MIT](LICENSE)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Aspergillus africanus Durieu & Mont.

### Remarks
null


text:
layout: post
title: "Http Security Headers explained"
date: "2016-02-17 17:07:01 +0100"
category: blog
link:
filename:
thumbnail:
---
Web sites are everywhere and get powned within seconds. Http headers
will not protect you against rudimentary flaws within the code of your
side. However they serve two purposes. They add an extra level of
security to your side on two levels: technical and psychological.
While the technical may seem more appealing at a first glance, the
psychological carries even weight. Most script kiddies are looking for
the low hanging fruits. By employing Http security headers on your
site you show that you care about good programming hygiene which implies
that your side may be programmed very carefully and with security in mind
as well. Just remember the sign at your neighbor's door warning you about
the (tiny, lovely, always in a mood to  . . .) dog.

So what am I talking about? There are six headers to care about:

Strict-Transport-Security
-------------------------
You already serve your site via https? Why not tell the browser of your
visitors to enforce TLS on any communication with you? Besides this header
also protects your visitors against SSL-Man-In-The-Middle attacks.
It should look as follows:

```html
Strict-Transport-Security: max-age=31536000; includeSubDomains
```

It has been specified within [RFC 6797](https://tools.ietf.org/html/rfc6797).
You may find additional information from OWASP
[here](https://www.owasp.org/index.php/HTTP_Strict_Transport_Security).

Content-Security-Policy
-----------------------
This is a rather complex header that offers you various protections.
The full documentation can be found [here]( https://w3c.github.io/webappsec/specs/content-security-policy/)
On the one hand you can specify which sources you include may execute
scripts or load additional content. You may as well control if your side
should be embeddable within an iFrame. So it offers a protection against
clickjacking as well. In this case it should look like this:

```html
Content-Security-Policy: frame-ancestors 'none'
```

Besides frame-ancestors you should as well take a look at these options:

* default-src
* sandbox (read more on my post about [iFrames](/iframes/) )
* report-uri

The default-src options allows you to restrict where your site can load
resources like images, css, fonts or scripts from. Report-uri is a very
interesting option. It specifies where the browser visiting your site
should report policy violations to. Clearly this means you need to implement
more code - but it may be worth it. You will find additional information about
Content-Security-Policy headers at
[OWASP](https://www.owasp.org/index.php/Content_Security_Policy_Cheat_Sheet).

Public-Key-Pins
---------------
Public-Key Pinning was first introduced by [RFC 7469](https://tools.ietf.org/html/rfc7469).
It offers you the possibility to send the hash of your certificate as well as
a max-age information. With these two the client, a.k.a. browser is able to verify
that the certificate received is:

a) the certificate it should expect to receive from you

b) still valid independent of its expiry date and the certificate authority

An example for this header looks as follows:

```html
Public-Key-Pins:
pin-sha256="d6qzRu9zOECb90Uez27xWltNsj0e1Md7GkYYkVoZWmM=";
pin-sha256="E9CZ9INDbd+2eRQozYqqbQ2yXLVKB9+xcprMF+44U1g=";
pin-sha256="LPJNul+wow4m6DsqxbninhsWHlwfp0JecwQzYpOLmCQ=";
max-age=10000; includeSubDomains; report-uri="my-domain.com"
```

Like the content-security-policy header you can specify a report-uri to
receive information about browsers encountering problems while validating
your certificate.

Certificate authorities (CA) had some really bad press during the last years. By
delivering a checksum for your certificate you partially mitigate a
compromised CA. Still the person visiting your site has to trust you - however
she is now able to verify that the received certificate is the intended one.
And as you already expected OWASP has a [cheat-sheet](https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning)
for this header as well.

X-Frame-Options
---------------
The x-frame-options allows you to ensure that your page cannot be
embedded into an iFrame and thereby stops clickjacking attacks. The default
setting for this is:

```html
X-Frame-Options: SAMEORIGIN
```

Clearly, x-frame-options are not the only header to avoid clickjacking and
it is not implemented in all browsers. You should combine it with the
content-security-policy header. For more details check
out the OWASP clickjacking [article](https://www.owasp.org/index.php/Clickjacking).

X-XSS-Protection
----------------
Modern browsers do bring their own xss-protection. Clearly, it is far from perfect - but
still better than nothing. So, I recommend you set this header as well:

```html
X-XSS-Protection: 1; mode=block
```

For more information on anti-xss mechanisms see the OWASP [cheat-sheet](https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet).

X-Content-Type-Options
----------------------
X-Content-Type and X-Content-Type-Options are two interesting headers. They tell the
browser how to interpret the received file / content. By mislabelling you can get very
interesting results - e.g. "code" gets executed that is actually not meant to be code :)
Anyhow please do always set these two headers correctly. For the X-Content-Type-Options
you should use:

```html
X-Content-Type-Options: nosniff
```

This will stop any browser from trying to guess the content-type of a response. Thereby
you will reduce the effectiveness of drive-by-downloads as well as unwanted code execution.
For more information on content-type headers take a look at Microsoft's [page](https://blogs.msdn.microsoft.com/ie/2008/09/02/ie8-security-part-vi-beta-2-update/).

Finally, I stumbled about three pages that may be of interest to you:

* caniuse.com - see what browser in which version has implemented which header. Go to: [http://caniuse.com](http://caniuse.com)
* securityheaders.io - you may be aware of Qualys and their SSL-Labs. There is a new site similar to it and fully dedicated to HTTP-Headers: [https://securityheaders.io](https://securityheaders.io)
* owasp.org - they offer a nice short write-up on http security headers [here](https://www.owasp.org/index.php/List_of_useful_HTTP_headers).

So, to keep it sweet an simple: Set these http headers!!

Cheers :)


text: Rails.application.config.session_store :cookie_store, key: '_createlink_session'


text:
package anubis.ast;

/**
 * @author SiroKuro
 */
public class BinaryExpression extends Expression {
	private final Expression left;
	private final BinaryOperator operator;
	private final Expression right;

	public BinaryExpression(BinaryOperator operator, Expression left, Expression right) {
		assert operator != null;
		assert left != null;
		assert right != null;
		this.operator = operator;
		this.left = left;
		this.right = right;
	}

	/**
	* @return the left
	*/
	public Expression getLeft() {
		return left;
	}

	/**
	 * @return the operator
	 */
	public BinaryOperator getOperator() {
		return operator;
	}

	/**
	 * @return the right
	 */
	public Expression getRight() {
		return right;
	}

	@Override
	public <Arg, Ret> Ret visit(AstVisitor<Arg, Ret> visitor, Arg object) {
		return visitor.accept(this, object);
	}

}


text:
Adds an AWS::Budgets::Budget.CostTypes resource property to the template.
The types of cost that are included in a COST budget, such as tax and subscriptions.

## SYNTAX

```
Add-VSBudgetsBudgetCostTypes [[-IncludeSupport] <Object>] [[-IncludeOtherSubscription] <Object>]
 [[-IncludeTax] <Object>] [[-IncludeSubscription] <Object>] [[-UseBlended] <Object>]
 [[-IncludeUpfront] <Object>] [[-IncludeDiscount] <Object>] [[-IncludeCredit] <Object>]
 [[-IncludeRecurring] <Object>] [[-UseAmortized] <Object>] [[-IncludeRefund] <Object>] [<CommonParameters>]
```

## DESCRIPTION
Adds an AWS::Budgets::Budget.CostTypes resource property to the template.
The types of cost that are included in a COST budget, such as tax and subscriptions.

USAGE, RI_UTILIZATION, RI_COVERAGE, SAVINGS_PLANS_UTILIZATION, and SAVINGS_PLANS_COVERAGE budgets do not have CostTypes.

## PARAMETERS

### -IncludeSupport
Specifies whether a budget includes support subscription fees.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includesupport
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 1
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeOtherSubscription
Specifies whether a budget includes non-RI subscription costs.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includeothersubscription
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 2
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeTax
Specifies whether a budget includes taxes.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includetax
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 3
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeSubscription
Specifies whether a budget includes subscriptions.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includesubscription
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 4
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -UseBlended
Specifies whether a budget uses a blended rate.
The default value is false.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-useblended
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 5
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeUpfront
Specifies whether a budget includes upfront RI costs.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includeupfront
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 6
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeDiscount
Specifies whether a budget includes discounts.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includediscount
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 7
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeCredit
Specifies whether a budget includes credits.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includecredit
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 8
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeRecurring
Specifies whether a budget includes recurring fees such as monthly RI fees.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includerecurring
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 9
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -UseAmortized
Specifies whether a budget uses the amortized rate.
The default value is false.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-useamortized
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 10
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### -IncludeRefund
Specifies whether a budget includes refunds.
The default value is true.

Documentation: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html#cfn-budgets-budget-costtypes-includerefund
PrimitiveType: Boolean
UpdateType: Mutable

```yaml
Type: Object
Parameter Sets: (All)
Aliases:

Required: False
Position: 11
Default value: None
Accept pipeline input: False
Accept wildcard characters: False
```

### CommonParameters
This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216).

## INPUTS

## OUTPUTS

### Vaporshell.Resource.Budgets.Budget.CostTypes
## NOTES

## RELATED LINKS

[http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-budgets-budget-costtypes.html)


text:
package libfuse

// VolIconFileName is the name of the special icon file in macOS for
// the mount.
const VolIconFileName = ".VolumeIcon.icns"

// ExtendedAttributeSelfFileName is the name of an extended attribute
// file (on macOS) for the current (.) directory.
// This is used to tell the root mount to look for a volume icon file.
const ExtendedAttributeSelfFileName = "._."