text:
package org.apache.accumulo.test.gc.replication;

import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.accumulo.core.client.BatchWriter;
import org.apache.accumulo.core.client.BatchWriterConfig;
import org.apache.accumulo.core.client.Connector;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.conf.AccumuloConfiguration;
import org.apache.accumulo.core.conf.ConfigurationCopy;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.conf.SiteConfiguration;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Mutation;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.metadata.MetadataTable;
import org.apache.accumulo.core.metadata.schema.MetadataSchema.ReplicationSection;
import org.apache.accumulo.core.protobuf.ProtobufUtil;
import org.apache.accumulo.core.replication.ReplicationSchema.StatusSection;
import org.apache.accumulo.core.replication.ReplicationTable;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.TablePermission;
import org.apache.accumulo.gc.replication.CloseWriteAheadLogReferences;
import org.apache.accumulo.server.AccumuloServerContext;
import org.apache.accumulo.server.conf.ServerConfigurationFactory;
import org.apache.accumulo.server.replication.StatusUtil;
import org.apache.accumulo.server.replication.proto.Replication.Status;
import org.apache.accumulo.test.functional.ConfigurableMacBase;
import org.apache.hadoop.io.Text;
import org.easymock.EasyMock;
import org.easymock.IAnswer;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.google.common.collect.Iterables;

public class CloseWriteAheadLogReferencesIT extends ConfigurableMacBase {

  private WrappedCloseWriteAheadLogReferences refs;
  private Connector conn;

  private static class WrappedCloseWriteAheadLogReferences extends CloseWriteAheadLogReferences {
    public WrappedCloseWriteAheadLogReferences(AccumuloServerContext context) {
      super(context);
    }

    @Override
    protected long updateReplicationEntries(Connector conn, Set<String> closedWals) {
      return super.updateReplicationEntries(conn, closedWals);
    }
  }

  @Before
  public void setupInstance() throws Exception {
    conn = getConnector();
    conn.securityOperations().grantTablePermission(conn.whoami(), ReplicationTable.NAME, TablePermission.WRITE);
    conn.securityOperations().grantTablePermission(conn.whoami(), MetadataTable.NAME, TablePermission.WRITE);
    ReplicationTable.setOnline(conn);
  }

  @Before
  public void setupEasyMockStuff() {
    Instance mockInst = createMock(Instance.class);
    SiteConfiguration siteConfig = EasyMock.createMock(SiteConfiguration.class);
    expect(mockInst.getInstanceID()).andReturn(testName.getMethodName()).anyTimes();
    expect(mockInst.getZooKeepers()).andReturn("localhost").anyTimes();
    expect(mockInst.getZooKeepersSessionTimeOut()).andReturn(30000).anyTimes();
    final AccumuloConfiguration systemConf = new ConfigurationCopy(new HashMap<String,String>());
    ServerConfigurationFactory factory = createMock(ServerConfigurationFactory.class);
    expect(factory.getConfiguration()).andReturn(systemConf).anyTimes();
    expect(factory.getInstance()).andReturn(mockInst).anyTimes();
    expect(factory.getSiteConfiguration()).andReturn(siteConfig).anyTimes();

    // Just make the SiteConfiguration delegate to our AccumuloConfiguration
    // Presently, we only need get(Property) and iterator().
    EasyMock.expect(siteConfig.get(EasyMock.anyObject(Property.class))).andAnswer(new IAnswer<String>() {
      @Override
      public String answer() {
        Object[] args = EasyMock.getCurrentArguments();
        return systemConf.get((Property) args[0]);
      }
    }).anyTimes();
    EasyMock.expect(siteConfig.getBoolean(EasyMock.anyObject(Property.class))).andAnswer(new IAnswer<Boolean>() {
      @Override
      public Boolean answer() {
        Object[] args = EasyMock.getCurrentArguments();
        return systemConf.getBoolean((Property) args[0]);
      }
    }).anyTimes();

    EasyMock.expect(siteConfig.iterator()).andAnswer(new IAnswer<Iterator<Entry<String,String>>>() {
      @Override
      public Iterator<Entry<String,String>> answer() {
        return systemConf.iterator();
      }
    }).anyTimes();

    replay(mockInst, factory, siteConfig);
    refs = new WrappedCloseWriteAheadLogReferences(new AccumuloServerContext(factory));
  }

  @Test
  public void unclosedWalsLeaveStatusOpen() throws Exception {
    Set<String> wals = Collections.emptySet();
    BatchWriter bw = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
    Mutation m = new Mutation(ReplicationSection.getRowPrefix() + "file:/accumulo/wal/tserver+port/12345");
    m.put(ReplicationSection.COLF, new Text("1"), StatusUtil.fileCreatedValue(System.currentTimeMillis()));
    bw.addMutation(m);
    bw.close();

    refs.updateReplicationEntries(conn, wals);

    Scanner s = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
    s.fetchColumnFamily(ReplicationSection.COLF);
    Entry<Key,Value> entry = Iterables.getOnlyElement(s);
    Status status = Status.parseFrom(entry.getValue().get());
    Assert.assertFalse(status.getClosed());
  }

  @Test
  public void closedWalsUpdateStatus() throws Exception {
    String file = "file:/accumulo/wal/tserver+port/12345";
    Set<String> wals = Collections.singleton(file);
    BatchWriter bw = conn.createBatchWriter(MetadataTable.NAME, new BatchWriterConfig());
    Mutation m = new Mutation(ReplicationSection.getRowPrefix() + file);
    m.put(ReplicationSection.COLF, new Text("1"), StatusUtil.fileCreatedValue(System.currentTimeMillis()));
    bw.addMutation(m);
    bw.close();

    refs.updateReplicationEntries(conn, wals);

    Scanner s = conn.createScanner(MetadataTable.NAME, Authorizations.EMPTY);
    s.fetchColumnFamily(ReplicationSection.COLF);
    Entry<Key,Value> entry = Iterables.getOnlyElement(s);
    Status status = Status.parseFrom(entry.getValue().get());
    Assert.assertTrue(status.getClosed());
  }

  @Test
  public void partiallyReplicatedReferencedWalsAreNotClosed() throws Exception {
    String file = "file:/accumulo/wal/tserver+port/12345";
    Set<String> wals = Collections.singleton(file);
    BatchWriter bw = ReplicationTable.getBatchWriter(conn);
    Mutation m = new Mutation(file);
    StatusSection.add(m, "1", ProtobufUtil.toValue(StatusUtil.ingestedUntil(1000)));
    bw.addMutation(m);
    bw.close();

    refs.updateReplicationEntries(conn, wals);

    Scanner s = ReplicationTable.getScanner(conn);
    Entry<Key,Value> entry = Iterables.getOnlyElement(s);
    Status status = Status.parseFrom(entry.getValue().get());
    Assert.assertFalse(status.getClosed());
  }

}


text:
from __future__ import print_function
from builtins import input

import platform

import utils

fallback = True

# Check if platform is Linux and required packages are installed
# else fallback to console mode
if platform.system() == 'Linux':
    try:
        import dbus
        import dbus.mainloop.glib
        import time
        fallback = False
    except:
        pass

#--------------------------------------------------------------------

# BLE client (Linux Only) using Bluez and DBus
class BLE_Bluez_Client:
    def connect(self, devname, iface, srv_uuid):
        self.devname = devname
        self.srv_uuid = srv_uuid
        self.device = None
        self.adapter = None
        self.adapter_props = None
        self.services = None

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SystemBus()
        manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
        objects = manager.GetManagedObjects()

        for path, interfaces in objects.items():
            adapter = interfaces.get("org.bluez.Adapter1")
            if adapter != None:
                if path.endswith(iface):
                    self.adapter = dbus.Interface(bus.get_object("org.bluez", path), "org.bluez.Adapter1")
                    self.adapter_props = dbus.Interface(bus.get_object("org.bluez", path), "org.freedesktop.DBus.Properties")
                    break

        if self.adapter == None:
            raise RuntimeError("Bluetooth adapter not found")

        self.adapter_props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(1))
        self.adapter.StartDiscovery()

        retry = 10
        while (retry > 0):
            try:
                if self.device == None:
                    print("Connecting...")
                    # Wait for device to be discovered
                    time.sleep(5)
                    self._connect_()
                    print("Connected")
                print("Getting Services...")
                # Wait for services to be discovered
                time.sleep(5)
                self._get_services_()
                return True
            except Exception as e:
                print(e)
                retry -= 1
                print("Retries left", retry)
                continue
        self.adapter.StopDiscovery()
        return False

    def _connect_(self):
        bus = dbus.SystemBus()
        manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
        objects = manager.GetManagedObjects()
        dev_path = None
        for path, interfaces in objects.items():
            if "org.bluez.Device1" not in interfaces.keys():
                continue
            if interfaces["org.bluez.Device1"].get("Name") == self.devname:
                dev_path = path
                break

        if dev_path == None:
            raise RuntimeError("BLE device not found")

        try:
            self.device = bus.get_object("org.bluez", dev_path)
            self.device.Connect(dbus_interface='org.bluez.Device1')
        except Exception as e:
            print(e)
            self.device = None
            raise RuntimeError("BLE device could not connect")

    def _get_services_(self):
        bus = dbus.SystemBus()
        manager = dbus.Interface(bus.get_object("org.bluez", "/"), "org.freedesktop.DBus.ObjectManager")
        objects = manager.GetManagedObjects()
        srv_path = None
        for path, interfaces in objects.items():
            if "org.bluez.GattService1" not in interfaces.keys():
                continue
            if path.startswith(self.device.object_path):
                service = bus.get_object("org.bluez", path)
                uuid = service.Get('org.bluez.GattService1', 'UUID',
                            dbus_interface='org.freedesktop.DBus.Properties')
                if uuid == self.srv_uuid:
                    srv_path = path
                    break

        if srv_path == None:
            raise RuntimeError("Provisioning service not found")

        self.characteristics = dict()
        for path, interfaces in objects.items():
            if "org.bluez.GattCharacteristic1" not in interfaces.keys():
                continue
            if path.startswith(srv_path):
                chrc = bus.get_object("org.bluez", path)
                uuid = chrc.Get('org.bluez.GattCharacteristic1', 'UUID',
                            dbus_interface='org.freedesktop.DBus.Properties')
                self.characteristics[uuid] = chrc

    def has_characteristic(self, uuid):
        if uuid in self.characteristics.keys():
            return True
        return False

    def disconnect(self):
        if self.device:
            self.device.Disconnect(dbus_interface='org.bluez.Device1')
            if self.adapter:
                self.adapter.RemoveDevice(self.device)
        if self.adapter_props:
            self.adapter_props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(0))

    def send_data(self, characteristic_uuid, data):
        try:
            path = self.characteristics[characteristic_uuid]
        except KeyError:
            raise RuntimeError("Invalid characteristic : " + characteristic_uuid)
        path.WriteValue([ord(c) for c in data], {}, dbus_interface='org.bluez.GattCharacteristic1')
        return ''.join(chr(b) for b in path.ReadValue({}, dbus_interface='org.bluez.GattCharacteristic1'))

#--------------------------------------------------------------------

# Console based BLE client for Cross Platform support
class BLE_Console_Client:
    def connect(self, devname, iface, srv_uuid):
        print("BLE client is running in console mode")
        print("\tThis could be due to your platform not being supported or dependencies not being met")
        print("\tPlease ensure all pre-requisites are met to run the full fledged client")
        print("BLECLI >> Please connect to BLE device `" + devname + "` manually using your tool of choice")
        resp = input("BLECLI >> Was the device connected successfully? [y/n] ")
        if resp != 'Y' and resp != 'y':
            return False
        print("BLECLI >> List available attributes of the connected device")
        resp = input("BLECLI >> Is the service UUID '" + srv_uuid + "' listed among available attributes? [y/n] ")
        if resp != 'Y' and resp != 'y':
            return False
        return True

    def has_characteristic(self, uuid):
        resp = input("BLECLI >> Is the characteristic UUID '" + uuid + "' listed among available attributes? [y/n] ")
        if resp != 'Y' and resp != 'y':
            return False
        return True

    def disconnect(self):
        pass

    def send_data(self, characteristic_uuid, data):
        print("BLECLI >> Write following data to characteristic with UUID '" + characteristic_uuid + "' :")
        print("\t>> " + utils.str_to_hexstr(data))
        print("BLECLI >> Enter data read from characteristic (in hex) :")
        resp = input("\t<< ")
        return utils.hexstr_to_str(resp)

#--------------------------------------------------------------------

# Function to get client instance depending upon platform
def get_client():
    if fallback:
        return BLE_Console_Client()
    return BLE_Bluez_Client()

redpajama_set_name: RedPajamaGithub


text:
import hail as hl

from .resources import *
from .utils import benchmark
import gzip

def read_gunzip(path):
    with gzip.open(path) as f:
        for line in f:
            pass

@benchmark(args=many_ints_table.handle('tsv'))
def sentinel_read_gunzip_1(path):
    read_gunzip(path)

@benchmark(args=many_ints_table.handle('tsv'))
def sentinel_read_gunzip_2(path):
    read_gunzip(path)

@benchmark(args=many_ints_table.handle('tsv'))
def sentinel_read_gunzip_3(path):
    read_gunzip(path)

def iter_hash(m, n):
    x = 0
    for i in range(m):
        y = 0
        for j in range(n):
            y = hash(y + j)
        x += y

@benchmark()
def sentinel_cpu_hash_1():
    iter_hash(10000, 25000)

@benchmark()
def sentinel_cpu_hash_2():
    iter_hash(10000, 25000)

@benchmark()
def sentinel_cpu_hash_3():
    iter_hash(10000, 25000)


text:
<?php

class classes_archive_restore_sql extends classes_archive_restore
{

	public function __construct()
	{
		/* Make registry objects */
		$this->registry		=  ipsRegistry::instance();
		$this->DB			=  $this->registry->DB();
		$this->settings		=& $this->registry->fetchSettings();
		$this->request		=& $this->registry->fetchRequest();
		$this->lang			=  $this->registry->getClass('class_localization');
		$this->member		=  $this->registry->member();
		$this->memberData	=& $this->registry->member()->fetchMemberData();
		$this->cache		=  $this->registry->cache();
		$this->caches		=& $this->registry->cache()->fetchCaches();

		/* Do we have a remote DB? */
		if ( $this->settings['archive_remote_sql_database'] && $this->settings['archive_remote_sql_user'] )
		{
			if ( ! is_object( $this->registry->dbFunctions()->getDB('remoteArchive') ) )
			{

				$this->registry->dbFunctions()->setDB( 'mysql', 'remoteArchive', array(  'sql_database'	        => $this->settings['archive_remote_sql_database'],
																						 'sql_user'		        => $this->settings['archive_remote_sql_user'],
																						 'sql_pass'		        => $this->settings['archive_remote_sql_pass'],
																						 'sql_host'		        => $this->settings['archive_remote_sql_host'],
																						 'sql_charset'	        => $this->settings['archive_remote_sql_charset'],
																						 'sql_tbl_prefix'       => $this->settings['sql_tbl_prefix'],
																						 'catchConnectionError' => true ) );

				$this->remoteDB = $this->registry->dbFunctions()->getDB('remoteArchive');

				/* Check for connection issue */
				if ( $this->remoteDB->error )
				{
					$this->connectError = $this->remoteDB->error;
					$this->remoteDB     = null;

					$this->registry->dbFunctions()->unsetDB('remoteArchive');
				}
			}
			else
			{
				$this->remoteDB = $this->registry->dbFunctions()->getDB('remoteArchive');

				/* Check for connection issue */
				if ( $this->remoteDB->error )
				{
					$this->connectError = $this->remoteDB->error;
					$this->remoteDB     = null;

					$this->registry->dbFunctions()->unsetDB('remoteArchive');
				}
			}
		}
		else
		{
			$this->remoteDB = $this->DB;
		}
	}

	/**
	 * Get max PID in a TID
	 */
	public function getMaxPidInTid( $tid )
	{
		$max = $this->remoteDB->buildAndFetch( array( 'select' => 'MAX(archive_id) as i', 'from' => 'forums_archive_posts', 'where' => 'archive_topic_id=' . intval( $tid ) ) );

		return $max['i'];
	}

	/**
	 * Fetch by TIDS
	 */
	public function getPidsInTids( array $tids, $limit=50 )
	{
		$pids = array();

		/* Select remaining Pids */
		$this->remoteDB->build( array( 'select' => 'archive_id',
									   'from'   => 'forums_archive_posts',
									   'where'  => 'archive_topic_id IN(' . implode( ',', $tids ) . ') AND archive_restored=0',
									   'order'  => 'archive_topic_id ASC, archive_id ASC',
									   'limit'  => array( 0, $limit ) ) );

		$o = $this->remoteDB->execute();

		while( $post = $this->remoteDB->fetch( $o ) )
		{
			$pids[ $post['archive_id'] ] = $post['archive_id'];
		}

		return $pids;
	}

	/**
	 * Fetch between TIDS and date
	 *
	 */
	public function getPidsBetweenTidsAndDate( $min, $max, $date=0, $limit=50 )
	{
		$this->remoteDB->build( array( 'select' => 'archive_id',
									   'from'   => 'forums_archive_posts',
								 	   'where'  => 'archive_restored = 0 AND archive_content_date > ' . $date . ' AND archive_topic_id BETWEEN ' . intval( $min ) . ' AND ' . intval( $max ),
								 	   'order'  => 'archive_topic_id ASC, archive_id ASC',
								 	   'limit'  => array( 0, $limit ) ) );

		$o = $this->remoteDB->execute();

		while( $post = $this->remoteDB->fetch( $o ) )
		{
			$pids[ $post['archive_id'] ] = $post['archive_id'];
		}

		return $pids;
	}

	/**
	 * Remove posts by TIDs
	 * @param	array TIDS
	 */
	public function removePostsByTids( array $tids )
	{
		if ( count( $tids ) )
		{
			$this->remoteDB->delete( 'forums_archive_posts', 'archive_topic_id IN(' . implode( ',', $tids ) . ')' );
		}
	}

	/**
	 * Remove posts by PIDs
	 * @param	array PIDs
	 */
	public function setAsRestoredByPids( array $pids )
	{
		if ( count( $pids ) )
		{
			$this->remoteDB->update( 'forums_archive_posts', array( 'archive_restored' => 1 ), 'archive_id IN (' . implode( ',', $pids ) .')' );
		}
	}

	/**
	 * Write single entry to DB
	 * @param	array	INTS
	 */
	public function set( $data=array() )
	{
		if ( ! count( $data ) )
		{
			return null;
		}

		$this->DB->replace( 'posts', $this->archiveToNativeFields( $data ), array( 'pid' ) );
	}

}


text:
<?php

namespace Gopro\MainBundle\Controller;

use Gopro\MainBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Gopro\MainBundle\Entity\Archivo;
use Gopro\MainBundle\Form\ArchivoType;

/**
 * Archivo controller.
 *
 * @Route("/archivo")
 */
class ArchivoController extends BaseController
{

    /**
     * Lists all Archivo entities.
     *
     * @Route("/", name="gopro_main_archivo")
     * @Method("GET")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('GoproMainBundle:Archivo')->findAll();

        return array(
            'entities' => $entities,
        );
    }
    /**
     * Creates a new Archivo entity.
     *
     * @Route("/create", name="gopro_main_archivo_create")
     * @Method("POST")
     * @Template("GoproMainBundle:Archivo:new.html.twig")
     */
    public function createAction(Request $request)
    {
        $entity = new Archivo();
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()||$request->isXMLHttpRequest()) {
            $entity->setUser($this->getUser());
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();
            if ($request->isXMLHttpRequest()){
                return new JsonResponse([
                    'mensaje'=>['exito'=>'si','titulo'=>'Exito','texto'=>'El archivo se ha agregado'],
                    'archivo'=>[
                        'id'=>$entity->getId(),
                        'nombre'=>$entity->getNombre(),
                        'creado'=>$entity->getCreado(),
                        'procesarRoute'=>$this->get('router')->generate('gopro_'.$entity->getOperacion(), array('archivoEjecutar' => $entity->getId())),
                        'borrarRoute'=>$this->get('router')->generate('gopro_main_archivo_delete', array('id' => $entity->getId())),
                    ]
                ]);
            }
            return $this->redirect($this->generateUrl('gopro_main_archivo_show', array('id' => $entity->getId())));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
    * Creates a form to create a Archivo entity.
    *
    * @param Archivo $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createCreateForm(Archivo $entity)
    {
        $form = $this->createForm(ArchivoType::class, $entity, array(
            'action' => $this->generateUrl('gopro_main_archivo_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Crear'));

        return $form;
    }

    /**
     * Displays a form to create a new Archivo entity.
     *
     * @Route("/new", name="gopro_main_archivo_new")
     * @Method("GET")
     * @Template()
     */
    public function newAction()
    {
        $entity = new Archivo();
        $form   = $this->createCreateForm($entity);

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Finds and displays a Archivo entity.
     *
     * @Route("/{id}", name="gopro_main_archivo_show")
     * @Method("GET")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GoproMainBundle:Archivo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se encuentra o no tiene permiso sobre el archivo.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to edit an existing Archivo entity.
     *
     * @Route("/{id}/edit", name="gopro_main_archivo_edit")
     * @Method("GET")
     * @Template()
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GoproMainBundle:Archivo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se encuentra o no tiene permiso sobre el archivo.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
    * Creates a form to edit a Archivo entity.
    *
    * @param Archivo $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Archivo $entity)
    {
        $form = $this->createForm(ArchivoType::class, $entity, array(
            'action' => $this->generateUrl('gopro_main_archivo_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Actualizar'));

        return $form;
    }
    /**
     * Edits an existing Archivo entity.
     *
     * @Route("/{id}", name="gopro_main_archivo_update")
     * @Method("PUT")
     * @Template("GoproMainBundle:Archivo:edit.html.twig")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('GoproMainBundle:Archivo')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('No se encuentra o no tiene permiso sobre el archivo.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('gopro_main_archivo_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }
    /**
     * Deletes a Archivo entity.
     *
     * @Route("/{id}", name="gopro_main_archivo_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, $id)
    {

        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()||$request->isXMLHttpRequest()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('GoproMainBundle:Archivo')->findOneBy(['id'=>$id,'user'=>$this->getUser()]);

            if(!$entity&&$request->isXMLHttpRequest()){
                return new JsonResponse(['mensaje'=>['exito'=>'no','titulo'=>'Fallo','texto'=>'No existe el archivo']]);
            }elseif (!$entity) {
                throw $this->createNotFoundException('No se encuentra o no tiene permiso sobre el archivo.');
            }

            $em->remove($entity);
            $em->flush();

            if ($request->isXMLHttpRequest()){
                return new JsonResponse(['mensaje'=>['exito'=>'si','titulo'=>'Exito','texto'=>'Se ha eliminado el archivo']]);
            }
        }
        return $this->redirect($this->generateUrl('gopro_main_archivo'));
    }

    /**
     * Creates a form to delete a Archivo entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->get('form.factory')->createNamedBuilder(
            'deleteForm',
            'form',
            null,
            [
                'action'=>$this->generateUrl('gopro_main_archivo_delete', ['id' => $id]),
                'method'=>'DELETE',
                'attr'=>['id'=>'deleteForm']
            ])
            ->add('submit', 'submit', array('label' => 'Borrar'))
            ->getForm();
    }
}


text:
package model

import (
	"net/http"
	"time"

	"github.com/mholt/binding"
)

//Assignment ...
type Assignment struct {
	ID       string    `gorethink:"id,omitempty" json:"id"`
	Name     string    `gorethink:"name,omitempty" json:"name"`
	ClassID  string    `gorethink:"classId,omitempty" json:"classId"`
	TermID   string    `gorethink:"termId,omitempty" json:"termId"`
	GroupID  string    `gorethink:"groupId,omitempty" json:"groupId"`
	MaxScore int16     `gorethink:"maxScore,omitempty" json:"maxScore"`
	DueDate  time.Time `gorethink:"dueDate,omitempty" json:"dueDate"`
	TimeStamp
}

// FieldMap ...
func (a *Assignment) FieldMap(req *http.Request) binding.FieldMap {
	return binding.FieldMap{
		&a.ID:       "id",
		&a.Name:     "name",
		&a.GroupID:  "groupId",
		&a.ClassID:  "classId",
		&a.MaxScore: "maxScore",
		&a.TermID:   "termId",
		&a.DueDate:  "dueDate",
	}
}

type AssignmentAPIRes struct {
	Assignment
	Group AssignmentGroup `gorethink:"group,omitempty" json:"group"`
}

func (a Assignment) Validate(req *http.Request, errs binding.Errors) binding.Errors {
	if a.Name == "" {
		errs = append(errs, RequiredErr("name"))
	}
	if a.ClassID == "" {
		errs = append(errs, RequiredErr("classId"))
	}
	if a.TermID == "" {
		errs = append(errs, RequiredErr("termId"))
	}
	if a.GroupID == "" {
		errs = append(errs, RequiredErr("groupId"))
	}
	if a.MaxScore <= 0 {
		errs = append(errs, RequiredErr("maxScore"))
	}
	return errs
}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.contrib.auth.models import User

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding field 'UserDetail.activated'
        db.add_column('gratitude_userdetail', 'activated',
                      self.gf('django.db.models.fields.DateTimeField')(null=True),
                      keep_default=False)
        if not db.dry_run:
            for userDetail in orm.UserDetail.objects.all():
                user = User.objects.all().filter(id = userDetail.user.id)[0]
                userDetail.activated = user.date_joined
                userDetail.save()

    def backwards(self, orm):
        # Deleting field 'UserDetail.activated'
        db.delete_column('gratitude_userdetail', 'activated')

    models = {
        'auth.group': {
            'Meta': {'object_name': 'Group'},
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        'auth.permission': {
            'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'gratitude.action': {
            'Meta': {'object_name': 'Action'},
            'action': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'gratitude': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['gratitude.Gratitude']", 'null': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        },
        'gratitude.gratitude': {
            'Meta': {'object_name': 'Gratitude'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'stash_id': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100'}),
            'stashed': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'text': ('django.db.models.fields.CharField', [], {'max_length': '5000'}),
            'user_id': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'gratitude.setting': {
            'Meta': {'object_name': 'Setting'},
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'description': ('django.db.models.fields.CharField', [], {'max_length': '500'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '200'}),
            'value': ('django.db.models.fields.CharField', [], {'max_length': '500'})
        },
        'gratitude.userdetail': {
            'Meta': {'object_name': 'UserDetail'},
            'activated': ('django.db.models.fields.DateTimeField', [], {'null': 'True'}),
            'created': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'modified': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'blank': 'True'}),
            'no_messages': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['auth.User']"})
        }
    }

    complete_apps = ['gratitude']


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>Markdown</title>
    <link rel="stylesheet" href="../css/style.css" />
    <link rel="stylesheet" href="../css/editormd.css" />
    <link rel="stylesheet" href="../lib/amaran/css/amaran.min.css" media="screen" title="no title" charset="utf-8">
    <link rel="stylesheet" href="../lib/amaran/css/animate.min.css" media="screen" title="no title" charset="utf-8">

    <input type="file" class="dialog" id="open" accept=".md">
    <input type="file" class="dialog" id="save" nwsaveas="markdown.md">
    <input type="file" class="dialog" id="saveas" nwsaveas="markdown.md">
    <input type="file" class="dialog" id="exportHTML" nwdirectory>
    <input type="file" class="dialog" id="exportPDF" nwdirectory>


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

namespace SqlServerValidationToolkit.Configurator.Controls
{
    class ValidationFinishedMessage
    {
    }
}


text:
package com.amazon.ask.module;

import com.amazon.ask.attributes.persistence.PersistenceAdapter;
import com.amazon.ask.builder.SkillConfiguration;
import com.amazon.ask.dispatcher.request.handler.HandlerInput;
import com.amazon.ask.exception.AskSdkException;
import com.amazon.ask.model.Response;
import com.amazon.ask.model.services.ApiClient;
import com.amazon.ask.request.exception.mapper.GenericExceptionMapper;
import com.amazon.ask.request.handler.adapter.GenericHandlerAdapter;
import com.amazon.ask.request.interceptor.GenericRequestInterceptor;
import com.amazon.ask.request.interceptor.GenericResponseInterceptor;
import com.amazon.ask.request.mapper.GenericRequestMapper;
import com.amazon.ask.response.template.TemplateFactory;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * Context object passed to {@link SdkModule} implementations during module setup.
 * Allows modules to configure themselves against the skill instance.
 */
public class SdkModuleContext {

    /**
     * Skill configuration builder.
     */
    protected final SkillConfiguration.Builder skillConfigBuilder;

    /**
     * Constructor for SdkModuleContext.
     * @param skillConfigBuilder Skill configuration builder.
     */
    public SdkModuleContext(final SkillConfiguration.Builder skillConfigBuilder) {
        this.skillConfigBuilder = skillConfigBuilder;
    }

    /**
     * Adds multiple request mappers to SkillConfiguration Builder.
     * @param requestMapper request mappers.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext addRequestMappers(final List<GenericRequestMapper<HandlerInput, Optional<Response>>> requestMapper) {
        requestMapper.forEach(skillConfigBuilder::addRequestMapper);
        return this;
    }

    /**
     * Adds request mapper to SkillConfiguration Builder.
     * @param requestMapper request mapper.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext addRequestMapper(final GenericRequestMapper<HandlerInput, Optional<Response>> requestMapper) {
        skillConfigBuilder.addRequestMapper(requestMapper);
        return this;
    }

    /**
     * Getter for Request Mappers.
     * @return list of {@link GenericRequestMapper}.
     */
    public List<GenericRequestMapper<HandlerInput, Optional<Response>>> getRequestMappers() {
        return Collections.unmodifiableList(skillConfigBuilder.getRequestMappers());
    }

    /**
     * Adds multiple handler adapters to SkillConfiguration Builder.
     * @param handlerAdapter handler adapters.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext addHandlerAdapters(final List<GenericHandlerAdapter<HandlerInput, Optional<Response>>> handlerAdapter) {
        handlerAdapter.forEach(skillConfigBuilder::addHandlerAdapter);
        return this;
    }

    /**
     * Adds handler adapter to SkillConfiguration Builder.
     * @param handlerAdapter handler adapter.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext addHandlerAdapter(final GenericHandlerAdapter<HandlerInput, Optional<Response>> handlerAdapter) {
        skillConfigBuilder.addHandlerAdapter(handlerAdapter);
        return this;
    }

    /**
     * Getter for Handler Adapters.
     * @return list of {@link GenericHandlerAdapter}.
     */
    public List<GenericHandlerAdapter<HandlerInput, Optional<Response>>> getHandlerAdapter() {
        return skillConfigBuilder.getHandlerAdapters() == null
                ? null
                : Collections.unmodifiableList(skillConfigBuilder.getHandlerAdapters());
    }

    /**
     * Adds Request interceptor to SkillConfiguration Builder.
     * @param requestInterceptor request interceptor.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext addRequestInterceptor(final GenericRequestInterceptor<HandlerInput> requestInterceptor) {
        skillConfigBuilder.addRequestInterceptor(requestInterceptor);
        return this;
    }

    /**
     * Getter for Request interceptors.
     * @return list of {@link GenericRequestInterceptor}.
     */
    public List<GenericRequestInterceptor<HandlerInput>> getRequestInterceptors() {
        return skillConfigBuilder.getRequestInterceptors() == null
                ? null
                : Collections.unmodifiableList(skillConfigBuilder.getRequestInterceptors());
    }

    /**
     * Adds Response interceptor to SkillConfiguration Builder.
     * @param responseInterceptor response interceptor.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext addResponseInterceptor(final GenericResponseInterceptor<HandlerInput, Optional<Response>> responseInterceptor) {
        skillConfigBuilder.addResponseInterceptor(responseInterceptor);
        return this;
    }

    /**
     * Getter for Response interceptors.
     * @return list of {@link GenericResponseInterceptor}.
     */
    public List<GenericResponseInterceptor<HandlerInput, Optional<Response>>> getResponseInterceptors() {
        return skillConfigBuilder.getResponseInterceptors() == null
                ? null
                : Collections.unmodifiableList(skillConfigBuilder.getResponseInterceptors());
    }

    /**
     * Adds exception mapper to SkillConfiguration Builder.
     * @param exceptionMapper exception mapper.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext setExceptionMapper(final GenericExceptionMapper<HandlerInput, Optional<Response>> exceptionMapper) {
        skillConfigBuilder.withExceptionMapper(exceptionMapper);
        return this;
    }

    /**
     * Adds Persistence Adapter to SkillConfiguration Builder.
     * @param persistenceAdapter Store skill attributes to a persistence layer.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext setPersistenceAdapter(final PersistenceAdapter persistenceAdapter) {
        if (skillConfigBuilder.getPersistenceAdapter() != null) {
            throw new AskSdkException("Conflicting persistence adapter configuration: "
                    + "module attempting to override previously set value.");
        }
        skillConfigBuilder.withPersistenceAdapter(persistenceAdapter);
        return this;
    }

    /**
     * Adds Api client to SkillConfiguration Builder.
     * @param apiClient client to make API calls.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext setApiClient(final ApiClient apiClient) {
        if (skillConfigBuilder.getApiClient() != null) {
            throw new AskSdkException("Conflicting API client configuration: "
                    + "module attempting to override previously set value.");
        }
        skillConfigBuilder.withApiClient(apiClient);
        return this;
    }

    /**
     * Adds TemplateFactory to SkillConfiguration Builder.
     * @param templateFactory Interface to process template and data to generate skill response.
     * @return {@link SdkModuleContext}.
     */
    public SdkModuleContext setTemplateFactory(final TemplateFactory templateFactory) {
        if (skillConfigBuilder.getTemplateFactory() != null) {
            throw new AskSdkException("Conflicting Template factory configuration: "
                    + "module attempting to override previously set value.");
        }
        skillConfigBuilder.withTemplateFactory(templateFactory);
        return this;
    }

}


text:
import TreeNode from '../Domain/TreeNode';
import Level from '../Domain/Level';

export interface TreeNodeEvaluation {
    treeNode: TreeNode;
    level: Level|null;
    score: number|null;
    feedback: string;
}

export interface TreeNodeExt {
    treeNode: TreeNode;
    levels: Level[];
    choices: any[];
    showDefaultFeedback: boolean;
}

export interface EvaluatorEvaluation {
    evaluator: any;
    treeNodeEvaluation: TreeNodeEvaluation;
}

export interface TreeNodeResult {
    treeNode: TreeNode,
    evaluations: EvaluatorEvaluation[];
}


text:
//-----------------------------------------------------------------------
// <copyright file="EventSourceSpec.cs" company="Akka.NET Project">
//     Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.TestKit;
using Xunit;
using Xunit.Abstractions;

namespace Akka.Streams.Tests.Dsl
{
    public class EventSourceSpec : AkkaSpec
    {
        private event EventHandler<int> _event;

        private readonly ActorMaterializer _materializer;
        public EventSourceSpec(ITestOutputHelper helper) : base(helper)
        {
            _materializer = ActorMaterializer.Create(Sys);
        }

        [Fact]
        public void EventSource_must_emit_received_event_to_the_stream()
        {
            var s = this.CreateManualSubscriberProbe<int>();
            Source.FromEvent<EventHandler<int>, int>(
                conversion: onNext => (sender, e) => onNext(e),
                addHandler: h => _event += h,
                removeHandler: h => _event -= h)
                .To(Sink.FromSubscriber(s))
                .Run(_materializer);
            var sub = s.ExpectSubscription();

            sub.Request(2);
            _event?.Invoke(this, 1);
            s.ExpectNext(1);
            _event?.Invoke(this, 2);
            s.ExpectNext(2);
            _event?.Invoke(this, 3);
            sub.Request(1);
            s.ExpectNext(3);
            sub.Cancel();
        }

        [Fact]
        public void EventSource_must_work_with_event_handlers()
        {
            var s = this.CreateManualSubscriberProbe<int>();
            Source.FromEvent<int>(h => _event += h, h => _event -= h)
                .To(Sink.FromSubscriber(s))
                .Run(_materializer);
            var sub = s.ExpectSubscription();

            sub.Request(2);
            _event?.Invoke(this, 1);
            s.ExpectNext(1);
            _event?.Invoke(this, 2);
            s.ExpectNext(2);
            _event?.Invoke(this, 3);
            sub.Request(1);
            s.ExpectNext(3);

            sub.Cancel();
        }

        [Fact]
        public void EventSource_must_be_reusable()
        {
            var source = Source.FromEvent<int>(h => _event += h, h => _event -= h);
            var s1 = this.CreateManualSubscriberProbe<int>();
            var s2 = this.CreateManualSubscriberProbe<int>();

            source.To(Sink.FromSubscriber(s1)).Run(_materializer);
            source.To(Sink.FromSubscriber(s2)).Run(_materializer);

            var sub1 = s1.ExpectSubscription();
            sub1.Request(2);
            var sub2 = s2.ExpectSubscription();
            sub2.Request(2);

            _event?.Invoke(this, 123);

            s1.ExpectNext(123);
            s2.ExpectNext(123);
            sub1.Cancel();
            sub2.Cancel();
        }

        [Fact]
        public void EventSource_must_fail_downstream_in_Fail_overflow_mode()
        {
            var s = this.CreateManualSubscriberProbe<int>();
            Source.FromEvent<int>(h => _event += h, h => _event -= h, 1, OverflowStrategy.Fail)
                .To(Sink.FromSubscriber(s))
                .Run(_materializer);

            s.ExpectSubscription();

            _event?.Invoke(this, 1);
            _event?.Invoke(this, 2);

            s.ExpectError();
        }

        [Fact]
        public void EventSource_must_detach_from_event()
        {
            var s = this.CreateManualSubscriberProbe<int>();
            Source.FromEvent<int>(h => _event += h, h => _event -= h)
                .To(Sink.FromSubscriber(s))
                .Run(_materializer);
            var sub = s.ExpectSubscription();
            sub.Request(2);

            _event?.Invoke(this, 1);
            s.ExpectNext(1);

            sub.Cancel();

            _event?.Invoke(this, 2);
            s.ExpectNoMsg();
        }
    }
}


text:
# BEGIN-INTERNAL-SCRIPT-BLOCK
# Script:
# 	PS - Get Current IOS Image

# Script-Description:
# 	'Get the current IOS image from a "show version" and update a custom field called "IOS Image"'

# END-INTERNAL-SCRIPT-BLOCK

# BEGIN-SCRIPT-BLOCK
#
# Script-Filter:
#     $vendor eq "Cisco" and $sysdescr like /IOS/
#
# END-SCRIPT-BLOCK

use strict;
use warnings;

use NetMRI_Easy;

# Connect to the NetMRI
my $easy = new NetMRI_Easy;
my $system_image;

# Create the custom field called IOS Image if it does not already exist
$easy->broker->custom_fields->create_field({
	model => 'Device',
	name  => 'IOS Image',
	type  => 'string'
});

foreach my $output_line (split /\r?\n/, $easy->send_command("show version"))
{
#	For each line in the ourput we will search and until we match a line that starts with "System image file is"
	if ($output_line =~ m/System image file is/) {
		$easy->log_message('info', $output_line);
		# This is a regex that will parse the line and puting the location and image into the 2nd slot of the array
		my @system_image = split (/(?<=System image file is\s\\")(.*)(?=\\")|(?<=System image file is ")(.*)(?=")/, $output_line);
		# This will generate the Custom Log Message to confim that it's capturing the correct data in the array slot 1
		$easy->log_message('info', , "[+] Updated Custom Field IOS Image : $system_image[1]");
   	  	# This will send update the custom field we created called "IOS Image"
   	  	### NOTE ### the fact it's all lower case with "_" for the space
		$easy->device->set_custom_field(ios_image => $system_image[1]);
	}
}


text:
package io.github.davepkennedy.bark.state

import java.util.concurrent.TimeUnit

import akka.actor.{ActorLogging, FSM, ActorRef}
import io.github.davepkennedy.bark.TimeSource
import io.github.davepkennedy.bark.ui.Displayable

import scala.concurrent.duration.FiniteDuration
import scala.util.Random

sealed trait RaftState
object BootState extends RaftState
object FollowerState extends RaftState
object CandidateState extends RaftState
object LeaderState extends RaftState

sealed trait RaftData {
  val currentTerm: Int
  val votedFor: Option[Int]
  val log: Log
}

final case class FollowerData (lastTick: Long,
                               currentTerm: Int = 0,
                               votedFor: Option[Int] = None,
                               peers: Map[Int,ActorRef] = Map.empty,
                               log: Log = new Log) extends RaftData

final case class CandidateData (lastTick: Long,
                                currentTerm: Int,
                                votesGranted: Int = 0,
                                votedFor: Option[Int] = None,
                                peers: Map[Int,ActorRef],
                                log: Log = new Log) extends RaftData

final case class LeaderData (lastTick: Long,
                             currentTerm: Int,
                             peers: Map[Int,ActorRef],
                             log: Log = new Log,
                             nextIndex: Map[Int,Int],
                             matchIndex: Map[Int,Int]) extends RaftData {
  val votedFor = None
}

case object Tick
final case class RequestVote (term: Int,
                               candidateId: Int,
                               lastLogIndex: Int,
                               lastLogTerm: Int)
final case class Vote (id: Int,
                       term: Int,
                       granted: Boolean)

final case class AppendEntries (term: Int,
                                 leaderId: Int,
                                 prevLogIndex: Int,
                                 prevLogTerm: Int,
                                 entries: Seq[LogEntry],
                                 leaderCommit: Int)
final case class EntriesAccepted (id: Int,
                                  term: Int,
                                  lastEntry: Int,
                                  success: Boolean)

object RaftActor {
  val StateTimeout: Long = 250
  val random = new Random
  def randomInterval: FiniteDuration = FiniteDuration (100 + random.nextInt(100), TimeUnit.MILLISECONDS)
}

trait RaftActor extends FSM[RaftState,RaftData] with ActorLogging {
  this: Displayable with TimeSource =>
  def id: Int
  def shouldRetire: Boolean
  def shouldAcceptEntries (appendEntries: AppendEntries, raftData: RaftData): Boolean = {
    if (appendEntries.term >= raftData.currentTerm &&
      raftData.log.hasEntryAt(appendEntries.prevLogIndex, appendEntries.prevLogTerm)) {
      true
    } else {
      false
    }
  }

  def appendEntriesToLog (appendEntries: AppendEntries, raftData: RaftData): Unit = {
    raftData.log.append(appendEntries.entries)
    if (appendEntries.leaderCommit > raftData.log.lastCommitted) {
      raftData.log.commitTo(math.min(appendEntries.leaderCommit, raftData.log.lastApplied))
    }
  }

  def shouldAcceptVote (requestVote: RequestVote, raftData: RaftData): Boolean = {
    if (requestVote.term >= raftData.currentTerm &&
      requestVote.lastLogIndex >= raftData.log.lastApplied &&
      raftData.votedFor.getOrElse(requestVote.candidateId) == requestVote.candidateId
    ) true
    else false
  }

  def acceptVote (term: Int) = Vote(id, term, granted = true)
  def rejectVote (term: Int) = Vote(id, term, granted = false)

  def acceptEntries (term: Int, lastEntry: Int) = EntriesAccepted (id, term, lastEntry = lastEntry, success = true)
  def rejectEntries (term: Int, lastEntry: Int) = EntriesAccepted (id, term, lastEntry = lastEntry, success = false)
}


text:
package io.tracee.contextlogger.contextprovider;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.tracee.contextlogger.contextprovider.api.ImplicitContextData;
import io.tracee.contextlogger.contextprovider.api.WrappedContextData;

/**
 * Class to store class to wrapper mappings.
 */
public final class TypeToWrapper {

    private static List<TypeToWrapper> typeToWrapperList;
    private static final Logger logger = LoggerFactory.getLogger(TypeToWrapper.class);

    private final Class wrappedInstanceType;
    private final Class wrapperType;

    public TypeToWrapper(final Class wrappedInstanceType, final Class wrapperType) {
        this.wrappedInstanceType = wrappedInstanceType;
        this.wrapperType = wrapperType;
    }

    public Class getWrappedInstanceType() {
        return wrappedInstanceType;
    }

    public Class getWrapperType() {
        return wrapperType;
    }

    public static Set<Class> getAllWrappedClasses() {

        final List<TypeToWrapper> localTypeToWrapperList = getTypeToWrapper();

        Set<Class> resultList = new HashSet<Class>();

        if (localTypeToWrapperList != null) {
            for (TypeToWrapper typeToWrapper : localTypeToWrapperList) {
                resultList.add(typeToWrapper.getWrappedInstanceType());
            }
        }

        return resultList;

    }

    public static List<TypeToWrapper> getTypeToWrapper() {
        if (typeToWrapperList == null) {
            typeToWrapperList = getAvailableWrappers();
        }
        return typeToWrapperList;
    }

    /**
     * Gets a list with all wrapper classes.
     *
     * @return a list with all wrapper classes
     */
    public static Set<Class> findWrapperClasses() {

        final List<TypeToWrapper> localTypeToWrapperList = getTypeToWrapper();

        Set<Class> resultList = new HashSet<Class>();

        if (localTypeToWrapperList != null) {
            for (TypeToWrapper typeToWrapper : localTypeToWrapperList) {
                resultList.add(typeToWrapper.getWrapperType());
            }
        }

        return resultList;

    }

    /**
     * Generic function to get a implicit data provider classes from resource files.
     *
     * @return a set that contains all context provider type the were found
     */
    public static Set<ImplicitContextData> getImplicitContextDataProviders() {
        final Set<ImplicitContextData> result = new HashSet<ImplicitContextData>();

        for (Class clazz : ContextProviderServiceLoader.getServiceLocator().getImplicitContextProvider()) {

            try {
                if (ImplicitContextData.class.isAssignableFrom(clazz)) {
                    ImplicitContextData instance = (ImplicitContextData)(clazz.newInstance());
                    result.add(instance);
                }
            }
            catch (Throwable e) {
                // to be ignored
            }

        }

        return result;
    }

    /**
     * Method to get all available wrappers.
     *
     * @return all wrapping between wrapper classes and their wrapped types.
     */
    public static List<TypeToWrapper> getAvailableWrappers() {

        final List<TypeToWrapper> result = new ArrayList<TypeToWrapper>();

        for (Class clazz : ContextProviderServiceLoader.getServiceLocator().getContextProvider()) {

            try {
                if (WrappedContextData.class.isAssignableFrom(clazz)) {
                    // try to create instance to get the wrapped type
                    final WrappedContextData instance = (WrappedContextData)clazz.newInstance();
                    result.add(new TypeToWrapper(instance.getWrappedType(), clazz));
                }
            }
            catch (Throwable e) {
                // to be ignored
            }

        }

        return result;
    }

    private static void logError(final String message, final Throwable e) {
        logger.error(message, e);
    }

    private static void logWarn(final String message) {
        logger.warn(message);
    }
}


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="BehaviorRuleFlowControlBaseTest.cs" company="Kephas Software SRL">
//   Copyright (c) Kephas Software SRL. All rights reserved.
//   Licensed under the MIT license. See LICENSE file in the project root for full license information.
// </copyright>
// <summary>
//   Implements the behavior rule flow control base test class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Kephas.Core.Tests.Behaviors
{
    using Kephas.Behaviors;
    using Kephas.Runtime;
    using Kephas.Services;
    using NUnit.Framework;

    [TestFixture]
    public class BehaviorRuleFlowControlBaseTest
    {
        [Test]
        public void PriorityOrder_default()
        {
            var behavior = new DefaultBehaviorRuleFlowControl();
            Assert.AreEqual(0, behavior.ProcessingPriority);
        }

        [Test]
        public void PriorityOrder_attribute()
        {
            var behavior = new PriorityBehaviorRuleFlowControl();
            Assert.AreEqual(12, behavior.ProcessingPriority);
        }

        [Test]
        public void IsEndRule_default()
        {
            var behavior = new DefaultBehaviorRuleFlowControl();
            Assert.IsFalse(behavior.IsEndRule);
        }

        [Test]
        public void IsEndRule_attribute()
        {
            var behavior = new EndRuleBehaviorRuleFlowControl();
            Assert.IsTrue(behavior.IsEndRule);
        }

        private class DefaultBehaviorRuleFlowControl : BehaviorRuleFlowControlBase
        {
        }

        [ProcessingPriority(12)]
        private class PriorityBehaviorRuleFlowControl : BehaviorRuleFlowControlBase
        {
        }

        [EndRule]
        private class EndRuleBehaviorRuleFlowControl : BehaviorRuleFlowControlBase
        {
        }
    }
}


text:
namespace ExcelColumns
{
    using System;

    public class ExcelColumns
    {
        public static void Main(string[] args)
        {
            int n = int.Parse(Console.ReadLine());
            string column = string.Empty;

            for (int i = 0; i < n; i++)
            {
                column += Console.ReadLine();
            }

            int power = column.Length - 1;
            long result = 0;
            for (int i = 0; i < column.Length; i++)
            {
                result += (column[i] - 'A' + 1) * (long)Math.Pow(26, power);
                power--;
            }

            Console.WriteLine(result);
        }
    }
}


text:
<?php
namespace app\models;

use yii\base\Object;

/**
 * Unregistered contributor model
 */
class UnregisteredContributor extends Object implements ContributorInterface
{
    /**
     * @var string Contributor name
     */
    public $contributorName;

    /**
     * @var string Contributor e-mail
     */
    public $contributorEmail;

    /**
     * Unregistered contributor has no identifiers
     *
     * @return null
     */
    public function getContributorId()
    {
        // has no identifier
        return null;
    }

    /**
     * Contributor e-mail
     *
     * @return string
     */
    public function getContributorEmail()
    {
        return $this->contributorEmail;
    }

    /**
     * Contributor user name
     *
     * @return string
     */
    public function getContributorName()
    {
        return $this->contributorName;
    }

    /**
     * Get avatar URL
     *
     * @return null
     */
    public function getAvatarUrl()
    {
        return null;
    }

    /**
     * Get default reviewer id
     *
     * @return null
     */
    public function getDefaultViewerId()
    {
        return null;
    }
}


text:
"""
Our linter engine needs to run in 3 different scenarios:
 * Linting all files (python and js)
 * Linting only python files (--python)
 * Linting only js files (--js)

For the js only path, we should not depend on any packages outside the
python stdlib to prevent the need to install the world just to run eslint.

This also means imports should be done lazily/inside of function calls for
dependencies such as flake8/pep8.
"""
from __future__ import absolute_import

import os
import sys
from subprocess import Popen

os.environ['PYFLAKES_NODOCTEST'] = '1'

def register_checks():
    import pycodestyle
    from sentry.lint.absolute_import_check import AbsoluteImportCheck
    from sentry.lint.mock_check import MockCheck

    pycodestyle.register_check(MockCheck, codes=[MockCheck.code])
    pycodestyle.register_check(AbsoluteImportCheck, codes=[AbsoluteImportCheck.code])

register_checks()

def get_files(path):
    results = []
    for root, _, files in os.walk(path):
        for name in files:
            results.append(os.path.join(root, name))
    return results

def get_files_for_list(file_list):
    if file_list is None:
        files_to_check = get_files('.')

    else:
        files_to_check = []
        for path in file_list:
            if os.path.isdir(path):
                files_to_check.extend(get_files(path))
            else:
                files_to_check.append(os.path.abspath(path))
    return files_to_check

def py_lint(file_list):
    from flake8.engine import get_style_guide

    if file_list is None:
        file_list = ['src/sentry', 'tests']
    file_list = get_files_for_list(file_list)

    # remove non-py files and files which no longer exist
    file_list = filter(lambda x: x.endswith('.py'), file_list)

    flake8_style = get_style_guide(parse_argv=True)
    report = flake8_style.check_files(file_list)

    return report.total_errors != 0

def js_lint(file_list=None):
    project_root = os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
                                os.pardir)
    eslint_path = os.path.join(project_root, 'node_modules', '.bin', 'eslint')

    if not os.path.exists(eslint_path):
        print('!! Skipping JavaScript linting because eslint is not installed.')
        return False

    if file_list is None:
        file_list = ['tests/js', 'src/sentry/static/sentry/app']
    file_list = get_files_for_list(file_list)

    eslint_config = os.path.join(project_root, '.eslintrc')

    has_errors = False
    file_list = [
        x for x in file_list
        if x.endswith(('.js', '.jsx'))
    ]

    if file_list:
        status = Popen([eslint_path, '--config', eslint_config, '--ext', '.jsx']
                       + file_list).wait()
        has_errors = status != 0

    return has_errors

def check_files(file_list=None, js=True, py=True):
    # pep8.py uses sys.argv to find setup.cfg
    old_sysargv = sys.argv
    sys.argv = [
        os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir)
    ]

    linters = []
    if py:
        linters.append(py_lint(file_list))
    if js:
        linters.append(js_lint(file_list))

    try:
        if any(linters):
            return 1
        return 0
    finally:
        sys.argv = old_sysargv


text:
"""
Test that the 2->3 upgrader for Composer constructs a FromAddress item out of
the login credentials in the database and sets Composer.fromAddress to point
to the item
"""

from axiom.test.historic.stubloader import StubbedTest

from axiom.userbase import LoginMethod
from xquotient.compose import Composer
from xquotient.smtpout import FromAddress

class ComposerUpgradeTestCase(StubbedTest):
    def testUpgrade(self):
        composer = self.store.findUnique(Composer)


text:
/**
 Contains the main {@link org.jsoup.Jsoup} class, which provides convenient static access to the jsoup functionality.
 */
package de.machmireinebook.epubeditor.jsoup;


text:
The deriveCompare function is a maintainable and fast way to implement fast Less functions.

Given the following input:

```go
package compare

import "sort"

type MyStruct struct {
	Int64     int64
	StringPtr *string
}

func sortStructs(ss []*MyStruct) {
	sort.Slice(ss, func(i, j int) bool {
		return deriveCompare(ss[i], ss[j]) < 0
	})
}
```

goderive will generate the following code:

```go
// Code generated by goderive DO NOT EDIT.

package compare

import (
	"strings"
)

// deriveCompare returns:
//   * 0 if this and that are equal,
//   * -1 is this is smaller and
//   * +1 is this is bigger.
func deriveCompare(this, that *MyStruct) int {
	if this == nil {
		if that == nil {
			return 0
		}
		return -1
	}
	if that == nil {
		return 1
	}
	if c := deriveCompare_(this.Int64, that.Int64); c != 0 {
		return c
	}
	if c := deriveCompare_1(this.StringPtr, that.StringPtr); c != 0 {
		return c
	}
	return 0
}

// deriveCompare_ returns:
//   * 0 if this and that are equal,
//   * -1 is this is smaller and
//   * +1 is this is bigger.
func deriveCompare_(this, that int64) int {
	if this != that {
		if this < that {
			return -1
		} else {
			return 1
		}
	}
	return 0
}

// deriveCompare_1 returns:
//   * 0 if this and that are equal,
//   * -1 is this is smaller and
//   * +1 is this is bigger.
func deriveCompare_1(this, that *string) int {
	if this == nil {
		if that == nil {
			return 0
		}
		return -1
	}
	if that == nil {
		return 1
	}
	return deriveCompare_s(*this, *that)
}

// deriveCompare_s returns:
//   * 0 if this and that are equal,
//   * -1 is this is smaller and
//   * +1 is this is bigger.
func deriveCompare_s(this, that string) int {
	return strings.Compare(this, that)
}
```


text:
extern const struct ManagedAlbumAttributes {
	__unsafe_unretained NSString *albumId;
	__unsafe_unretained NSString *artworkURL;
	__unsafe_unretained NSString *releaseDate;
	__unsafe_unretained NSString *title;
} ManagedAlbumAttributes;

extern const struct ManagedAlbumRelationships {
	__unsafe_unretained NSString *artist;
} ManagedAlbumRelationships;

@class ManagedArtist;

@interface ManagedAlbumID : NSManagedObjectID {}
@end

@interface _ManagedAlbum : NSManagedObject {}
+ (id)insertInManagedObjectContext:(NSManagedObjectContext*)moc_;
+ (NSString*)entityName;
+ (NSEntityDescription*)entityInManagedObjectContext:(NSManagedObjectContext*)moc_;
@property (nonatomic, readonly, strong) ManagedAlbumID* objectID;

@property (nonatomic, strong) NSNumber* albumId;

@property (atomic) int32_t albumIdValue;
- (int32_t)albumIdValue;
- (void)setAlbumIdValue:(int32_t)value_;

//- (BOOL)validateAlbumId:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSString* artworkURL;

//- (BOOL)validateArtworkURL:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSDate* releaseDate;

//- (BOOL)validateReleaseDate:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) NSString* title;

//- (BOOL)validateTitle:(id*)value_ error:(NSError**)error_;

@property (nonatomic, strong) ManagedArtist *artist;

//- (BOOL)validateArtist:(id*)value_ error:(NSError**)error_;

@end

@interface _ManagedAlbum (CoreDataGeneratedPrimitiveAccessors)

- (NSNumber*)primitiveAlbumId;
- (void)setPrimitiveAlbumId:(NSNumber*)value;

- (int32_t)primitiveAlbumIdValue;
- (void)setPrimitiveAlbumIdValue:(int32_t)value_;

- (NSString*)primitiveArtworkURL;
- (void)setPrimitiveArtworkURL:(NSString*)value;

- (NSDate*)primitiveReleaseDate;
- (void)setPrimitiveReleaseDate:(NSDate*)value;

- (NSString*)primitiveTitle;
- (void)setPrimitiveTitle:(NSString*)value;

- (ManagedArtist*)primitiveArtist;
- (void)setPrimitiveArtist:(ManagedArtist*)value;

@end


text:
import java.util.Scanner;

public class DayOfWeek {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

        int a = Integer.parseInt(scanner.nextLine());

        try {
            System.out.println(days[a - 1]);
        } catch (Exception ex) {
            System.out.println("error");
        }
    }
}


text:
package de.sambalmueslie.quiz_game.data;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Model {
	public void add(final Index index) {
		if (index == null) {
			return;
		}
		indexs.add(index);
		indexs.sort((o1, o2) -> Integer.compare(o2.getNumber(), o1.getNumber()));
	}

	public void add(final LifeLine lifeLine) {
		if (lifeLine == null) {
			return;
		}
		lifeLines.add(lifeLine);
	}

	public void add(final Question question) {
		if (question == null) {
			return;
		}
		questions.add(question);
	}

	public Index getIndexByLevel(final int currentQuestionLevel) {
		if (indexs.isEmpty()) {
			return null;
		}
		if (currentQuestionLevel <= 0) {
			return indexs.get(indexs.size() - 1);
		} else if (currentQuestionLevel >= indexs.size()) {
			return indexs.get(0);
		} else {
			return indexs.get(indexs.size() - currentQuestionLevel);
		}
	}

	public List<Index> getIndexs() {
		return Collections.unmodifiableList(indexs);
	}

	public List<LifeLine> getLifeLines() {
		return Collections.unmodifiableList(lifeLines);
	}

	public Question getQuestionByLevel(final int level) {
		if (questions.isEmpty()) {
			return null;
		}
		final Stream<Question> stream = questions.stream();
		final List<Question> result = stream.filter(q -> q.getLevel() <= level).filter(q -> !q.isAnswered()).collect(Collectors.toList());
		final Random r = new Random();
		if (result.isEmpty()) {
			final int index = r.nextInt(questions.size() - 1);
			return questions.get(index);
		}
		if (result.size() == 1) {
			return result.get(0);
		}
		final int index = r.nextInt(result.size() - 1);
		return result.get(index);
	}

	/** the {@link Index} {@link List}. */
	private final List<Index> indexs = new ArrayList<>();

	/** the {@link LifeLine}s. */
	private final List<LifeLine> lifeLines = new LinkedList<>();

	/** the {@link Question}s. */
	private final List<Question> questions = new LinkedList<>();
}


text:
namespace tpie {

namespace pipelining {

namespace bits {

enum node_relation {
	pushes,
	pulls,
	depends,
	no_forward_depends,
	memory_share_depends
};

class node_map {
public:
	typedef uint64_t id_t;
	typedef node * val_t;

	typedef std::map<id_t, val_t> map_t;
	typedef map_t::const_iterator mapit;

	typedef std::multimap<id_t, std::pair<id_t, node_relation> > relmap_t;
	typedef relmap_t::const_iterator relmapit;

	typedef std::unordered_map<std::string, std::pair<memory_size_type, any_noncopyable> > datastructuremap_t;

	typedef boost::optional<any_noncopyable &> maybeany_t;
	typedef std::unordered_map<std::string, any_noncopyable> forwardmap_t;

	typedef boost::intrusive_ptr<node_map> ptr;

	struct pipe_base_forward_t {
		id_t from;
		std::string key;
		any_noncopyable value;
	};

	static  ptr create() {
		return ptr(new node_map);
	}

	id_t add_token(val_t token) {
		id_t id = nextId++;
		set_token(id, token);
		return id;
	}

	void set_token(id_t id, val_t token) {
		assert_authoritative();
		m_tokens[id] = token;
	}

	// union-find link
	void link(ptr target);

	void union_set(ptr target) {
		find_authority()->link(target->find_authority());
	}

	val_t get(id_t id) const {
		mapit i = m_tokens.find(id);
		if (i == m_tokens.end()) return 0;
		return i->second;
	}

	mapit begin() const {
		return m_tokens.begin();
	}

	mapit end() const {
		return m_tokens.end();
	}

	size_t size() const {
		return m_tokens.size();
	}

	// union-find
	ptr find_authority();

	void add_relation(id_t from, id_t to, node_relation rel);

	const relmap_t & get_relations() const {
		return m_relations;
	}

	const datastructuremap_t & get_datastructures() const {
		return m_datastructures;
	}

	datastructuremap_t & get_datastructures() {
		return m_datastructures;
	}

	size_t in_degree(id_t from, node_relation rel) const {
		return out_degree(m_relationsInv, from, rel);
	}

	size_t out_degree(id_t from, node_relation rel) const {
		return out_degree(m_relations, from, rel);
	}

	size_t out_degree(id_t from) const {
		return out_degree(m_relations, from);
	}

	void assert_authoritative() const {
		if (m_authority) throw non_authoritative_node_map();
	}

	void dump(std::ostream & os = std::cout) const;

	///////////////////////////////////////////////////////////////////////////
	/// \brief  Compute the set of nodes within k distance of the given node in
	/// the item flow graph.
	///////////////////////////////////////////////////////////////////////////
	void get_successors(id_t from, std::vector<id_t> & successors, memory_size_type k, bool forward_only=false);

	void forward(std::string key, any_noncopyable value) {
		m_pipelineForwards[key] = std::move(value);
	}

	maybeany_t fetch_maybe(std::string key) {
		auto it = m_pipelineForwards.find(key);
		if (it == m_pipelineForwards.end()) {
			return maybeany_t();
		}
		return maybeany_t(it->second);
	}

	void forward_from_pipe_base(id_t from, std::string key, any_noncopyable value) {
		m_pipeBaseForwards.push_back({from, key, std::move(value)});
	}

	void forward_pipe_base_forwards();

	friend void intrusive_ptr_add_ref(node_map * m) {
		m->m_refCnt++;
	}

	friend void intrusive_ptr_release(node_map * m) {
		m->m_refCnt--;
		if (m->m_refCnt == 0) delete m;
	}
private:
	map_t m_tokens;
	size_t m_refCnt;
	relmap_t m_relations;
	relmap_t m_relationsInv;
	datastructuremap_t m_datastructures;
	forwardmap_t m_pipelineForwards;
	std::vector<pipe_base_forward_t> m_pipeBaseForwards;

	size_t out_degree(const relmap_t & map, id_t from, node_relation rel) const;
	size_t out_degree(const relmap_t & map, id_t from) const;

	// union rank structure
	ptr m_authority;
	size_t m_rank;

	node_map()
		: m_refCnt(0)
		, m_rank(0)
	{
	}

	inline node_map(const node_map &);
	inline node_map & operator=(const node_map &);

	static id_t nextId;
};

} // namespace bits

class node_token {
public:
	typedef bits::node_map::id_t id_t;
	typedef bits::node_map::val_t val_t;

	// Use for the simple case in which a node owns its own token
	explicit node_token(val_t owner)
		: m_tokens(bits::node_map::create())
		, m_id(m_tokens->add_token(owner))
		, m_free(false)
	{
	}

	// This copy constructor has two uses:
	// 1. Simple case when a node is copied (freshToken = false)
	// 2. Advanced case when a node is being constructed with a specific token (freshToken = true)
	inline node_token(const node_token & other, val_t newOwner, bool freshToken = false)
		: m_tokens(other.m_tokens->find_authority())
		, m_id(other.id())
		, m_free(false)
	{
		if (freshToken) {
			if (!other.m_free)
				throw exception("Trying to take ownership of a non-free token");
			if (m_tokens->get(m_id) != 0)
				throw exception("A token already has an owner, but m_free is true - contradiction");
		} else {
			if (other.m_free)
				throw exception("Trying to copy a free token");
		}
		m_tokens->set_token(m_id, newOwner);
	}

	// Use for the advanced case when a node_token is allocated before the node
	inline node_token()
		: m_tokens(bits::node_map::create())
		, m_id(m_tokens->add_token(0))
		, m_free(true)
	{
	}

	inline id_t id() const { return m_id; }

	inline bits::node_map::ptr map_union(const node_token & with) {
		if (m_tokens != with.m_tokens)
			m_tokens->union_set(with.m_tokens);
		return m_tokens = m_tokens->find_authority();
	}

	inline bits::node_map::ptr get_map() const {
		return m_tokens;
	}

	inline val_t get() const {
		return m_tokens->get(m_id);
	}

private:
	bits::node_map::ptr m_tokens;
	id_t m_id;
	bool m_free;
};

} // namespace pipelining

} // namespace tpie

#endif // __TPIE_PIPELINING_TOKENS_H__


text:
MDE_CONFIG_MANAGER_URL='http://localhost' # format: 'http://<ip-or-dns>'
MDE_CONFIG_MANAGER_PORT='8080'            # format: [0-65536]

# Set magic variables for current file, directory, os, etc.
__dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
__file="${__dir}/$(basename "${BASH_SOURCE[0]}")"
__base="$(basename "${__file}" .sh)"

###############################################################################
# Import
###############################################################################
# shellcheck source=/dev/null
source "${__dir}/../tools/utils.sh"

###############################################################################
# Functions
###############################################################################
help() {
    echo "Usage: configure_mde [ -p | --port ]
               [ -u | --url   ]
               [ -h | --help  ]"
    exit 2
}

# START callConfigManagerAPI
function callConfigManagerAPI() {
    log "******** ${1} configuration ********"
    createCounter=0
    for FILE in "${__dir}/${2}"/*; do
        createCounter=$((createCounter + 1))
        log "File #${createCounter}: ${FILE}" '5'
        curl -X POST "${MDE_CONFIG_MANAGER_URL}:${MDE_CONFIG_MANAGER_PORT}/api/v1${3}" \
            -H 'Content-Type: application/json' \
            -H "Accept:application/json" \
            -d "@${FILE}"
        log "File #${createCounter} DONE" '5'
    done
    log "******** ${1} configuration DONE ********\n"
}
# END callConfigManagerAPI

###############################################################################
# Argument Parsing
###############################################################################
while :; do
    case "$1" in
    -p | --port)
        MDE_CONFIG_MANAGER_PORT="$2"
        shift
        shift
        ;;
    -u | --url)
        MDE_CONFIG_MANAGER_URL="$2"
        shift
        shift
        ;;
    -h | --help)
        help
        exit
        ;;
    --)
        shift
        break
        ;;
    '') # end of options
        break
        ;;
    *)
        echo "Unexpected option: $1"
        help
        ;;
    esac
done

###############################################################################
# Main
###############################################################################
log "Using URL: ${MDE_CONFIG_MANAGER_URL} on port: ${MDE_CONFIG_MANAGER_PORT}"

callConfigManagerAPI "TYPES" "types" "/types"
callConfigManagerAPI "BUCKETS" "buckets" "/metadata/bucket"
callConfigManagerAPI "SCHEMAS" "schemas" "/schema"
callConfigManagerAPI "SCHEMAS TO BUCKETS" "schema_to_buckets" "/metadata/bucket/schema"
callConfigManagerAPI "INGESTIONS" "ingestions" "/ingestions"
callConfigManagerAPI "PAYLOADS" "payloads" "/payloads"
callConfigManagerAPI "PARSERS" "parsers" "/pipelines"
callConfigManagerAPI "TAGS" "tags" "/tags"

# START customer logic for metadata instances
log "******** METATDATA VALUE TO TAGS configuration ********"
createCounter=0
for FILE in "${__dir}/metadata_instances"/*; do
    createCounter=$((createCounter + 1))
    log "File #${createCounter}: ${FILE}" '5'
    IFS='/' read -r -a filename <<<"${FILE}"       #remove folder
    IFS='.' read -r -a tagname <<<"${filename[1]}" #remove extension

    curl -X POST "${MDE_CONFIG_MANAGER_URL}:${MDE_CONFIG_MANAGER_PORT}/api/v1/tags/${tagname[0]}/metadata" \
        -H 'Content-Type: application/json' \
        -H "Accept:application/json" \
        -d "@${FILE}"

    log "File #${createCounter} DONE" '5'
done
log "******** ${1} configuration DONE ********\n"
# END customer logic for metadata instances


text:
'use babel';

/* @flow*/

import { Observable } from 'rxjs';
import { STOP_TEST, errorAction } from '../actions';
import type { Store, Tester, TesterAction } from '../../types';

export default function stopTest(action$: Observable<TesterAction>, store: Store): Observable<TesterAction> {
  return action$.ofType(STOP_TEST)
    .switchMap(() => Observable.from(store.getState().testers)
        .do((tester: Tester) => tester.stop())
        .switchMap(() => Observable.empty()))
    .catch(err => Observable.of(errorAction(err)));
}


text:
<!DOCTYPE html>

<TITLE>Manpage of tftpd_selinux</TITLE>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/main.css" type="text/css">

linux manpages

{"type":"documentation"}

tftpd_selinux

Section: tftpd SELinux Policy documentation (8)
Updated: tftpd
Index
Return to Main Contents

NAME

tftpd_selinux - Security Enhanced Linux Policy for the tftpd processes

DESCRIPTION

SHARING FILES

If you want to share files with multiple domains (Apache, FTP, rsync, Samba), you can set a file context of public_content_t and public_content_rw_t.  These context allow any of the above domains to read the content.  If you want a particular domain to write to the public_content_rw_t domain, you must set the appropriate boolean.

Allow tftpd servers to read the /var/tftpd directory by adding the public_content_t file type to the directory and by restoring the file type.

semanage fcontext -a -t public_content_t "/var/tftpd(/.*)?"

restorecon -F -R -v /var/tftpd

Allow tftpd servers to read and write /var/tmp/incoming by adding the public_content_rw_t type to the directory and by restoring the file type.  This also requires the allow_tftpd_anon_write boolean to be set.

semanage fcontext -a -t public_content_rw_t "/var/tftpd/incoming(/.*)?"

restorecon -F -R -v /var/tftpd/incoming

If you want to allow tftp to modify public files used for public file transfer services., you must turn on the tftp_anon_write boolean.

setsebool -P tftp_anon_write 1

FILE CONTEXTS

SELinux requires files to have an extended attribute to define the file type.

You can see the context of a file using the -Z option to lsP
Policy governs the access confined processes have to these files.
SELinux tftpd policy is very flexible allowing users to setup their tftpd processes in as secure a method as possible.

The following file types are defined for tftpd:

tftpd_exec_t

- Set files with the tftpd_exec_t type, if you want to transition an executable to the tftpd_t domain.

Paths:

/usr/sbin/in.tftpd, /usr/sbin/atftpd

tftpd_var_run_t

- Set files with the tftpd_var_run_t type, if you want to store the tftpd files under the /run directory.

tftpdir_rw_t

- Set files with the tftpdir_rw_t type, if you want to treat the files as tftpdir read/write content.

tftpdir_t

- Set files with the tftpdir_t type, if you want to treat the files as tftpdir data.

Paths:

/tftpboot/.*, /tftpboot

Note: File context can be temporarily modified with the chcon command.  If you want to permanently change the file context you need to use the
semanage fcontext

command.  This will modify the SELinux labeling database.  You will need to use
restorecon

to apply the labels.

PORT TYPES

SELinux defines port types to represent TCP and UDP ports.

You can see the types associated with a port by using the following command:

semanage port -l

Policy governs the access confined processes have to these ports.
SELinux tftpd policy is very flexible allowing users to setup their tftpd processes in as secure a method as possible.

The following port types are defined for tftpd:

tftp_port_t

Default Defined Ports:
tcp 8021

PROCESS TYPES

SELinux defines process types (domains) for each process running on the system

You can see the context of a process using the -Z option to psP
Policy governs the access confined processes have to files.
SELinux tftpd policy is very flexible allowing users to setup their tftpd processes in as secure a method as possible.

The following process types are defined for tftpd:

tftpd_t

Note:
semanage permissive -a PROCESS_TYPE

can be used to make a process type permissive. Permissive process types are not denied access by SELinux. AVC messages will still be generated.

COMMANDS

semanage fcontext

can also be used to manipulate default file context mappings.

semanage permissive

can also be used to manipulate whether or not a process type is permissive.

semanage module

can also be used to enable/disable/install/remove policy modules.

semanage port

can also be used to manipulate the port definitions

system-config-selinux

is a GUI tool available to customize SELinux policy settings.

AUTHOR<TT>  </TT>

This manual page was autogenerated by genman.py.

SEE ALSO

selinux(8), tftpd(8), semanage(8), restorecon(8), chcon(1)

Index

NAME

DESCRIPTION

SHARING FILES

FILE CONTEXTS

PORT TYPES

PROCESS TYPES

COMMANDS

AUTHOR<TT>  </TT>

SEE ALSO

This document was created by
man2html,
using the manual pages.

Time: 05:34:30 GMT, December 24, 2015


text:
static ClassRegister<InputInterface, InputManager> RegisterXinput([]() { return new XInputInterface(); });
XInputInterface::XInputInterface()
{
	CreateController();
}

XInputInterface::~XInputInterface()
{}

void XInputInterface::Tick()
{
	for (int i = 0; i < controllers.size(); i++)
	{
		controllers[i]->Update();
	}
}

InputController* XInputInterface::GetController(int Index)
{
	return (InputController*)controllers[Index];
}

int XInputInterface::GetNumOfControllers() const
{
	return (int)controllers.size();
}

void XInputInterface::ShutDown()
{

}
void XInputInterface::CreateController()
{
	controllers.push_back(new XInputController());
}
#endif


text:
@class NSArray, NSString, UIPickerView, WCAddressStageDataStruct;

@interface WCPOIAddressPickerItem : WCBaseTextFieldItem <UIPickerViewDataSource, UIPickerViewDelegate, WCBizPickerViewDelegate>
{
    NSArray *m_arrStage;
    WCAddressStageDataStruct *m_selectProvince;
    WCAddressStageDataStruct *m_selectCity;
    WCAddressStageDataStruct *m_selectDistrict;
    long long m_uiCurProvince;
    long long m_uiCurCity;
    long long m_uiCurDistrict;
    UIPickerView *m_pickerView;
    _Bool m_bLockProvince;
    _Bool m_bLockCity;
    _Bool m_bLockDistrict;
    _Bool m_bLockProviceAndCity;
}

@property(nonatomic) _Bool lockProviceAndCity; // @synthesize lockProviceAndCity=m_bLockProviceAndCity;
- (void).cxx_destruct;
- (void)UIPickerViewDidFinish;
- (void)UIPickerViewDidCancel;
- (void)pickerView:(id)arg1 didSelectRow:(long long)arg2 inComponent:(long long)arg3;
- (id)pickerView:(id)arg1 viewForRow:(long long)arg2 forComponent:(long long)arg3 reusingView:(id)arg4;
- (id)pickerView:(id)arg1 titleForRow:(long long)arg2 forComponent:(long long)arg3;
- (double)pickerView:(id)arg1 widthForComponent:(long long)arg2;
- (long long)pickerView:(id)arg1 numberOfRowsInComponent:(long long)arg2;
- (long long)numberOfComponentsInPickerView:(id)arg1;
- (void)SetText;
- (void)becomeFirstResponder;
- (void)dealloc;
- (void)initView:(struct CGRect)arg1;
- (void)resetSelectedAddress;
- (id)getSelectDistrict;
- (id)getSelectCity;
- (id)getSelectProvice;
- (_Bool)selectCityInDistrict:(id)arg1;
- (void)setSelectStageProvince:(id)arg1 City:(id)arg2 District:(id)arg3;
- (void)setAllAddressStageData:(id)arg1;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
@interface WFCalorimeterConnection : WFSensorConnection
{
}

- (id)getCalorieData;
- (id)init;

@end