text:
var keystone = require('../../'),
	_ = require('underscore'),
	async = require('async');

exports = module.exports = function(req, res) {

	req.list.model.findById(req.params.item).exec(function(err, item) {

		if (!item) {
			req.flash('error', 'Item ' + req.params.item + ' could not be found.');
			return res.redirect('/keystone/' + req.list.path);
		}

		var viewLocals = {
			validationErrors: {}
		};

		var renderView = function() {

			var relationships = _.values(_.compact(_.map(req.list.relationships, function(i) {
				if (i.isValid) {
					return _.clone(i);
				} else {
				    keystone.console.err('Relationship Configuration Error', 'Relationship: ' + i.path + ' on list: ' + req.list.key + ' links to an invalid list: ' + i.ref);
					return null;
				}
			})));

			var drilldown = {
				def: req.list.get('drilldown'),
				data: {},
				items: []
			};

			var loadDrilldown = function(cb) {

				if (!drilldown.def)
					return cb();

				// step back through the drilldown list and load in reverse order to support nested relationships
				// TODO: proper support for nested relationships in drilldown
				drilldown.def = drilldown.def.split(' ').reverse();

				async.eachSeries(drilldown.def, function(path, done) {

					var field = req.list.fields[path];

					if (!field || field.type !== 'relationship')
						throw new Error('Drilldown for ' + req.list.key + ' is invalid: field at path ' + path + ' is not a relationship.');

					var refList = field.refList;

					if (field.many) {
						if (!item.get(field.path).length) {
							return done();
						}
						refList.model.find().where('_id').in(item.get(field.path)).limit(4).exec(function(err, results) {
							if (err || !results) {
								done(err);
							}
							var more = (results.length === 4) ? results.pop() : false;
							if (results.length) {
								drilldown.data[path] = results;
								drilldown.items.push({
									list: refList,
									items: _.map(results, function(i) { return {
										label: refList.getDocumentName(i),
										href: '/keystone/' + refList.path + '/' + i.id
									};}),
									more: (more) ? true : false
								});
							}
							done();
						});
					} else {
						if (!item.get(field.path)) {
							return done();
						}
						refList.model.findById(item.get(field.path)).exec(function(err, result) {
							if (result) {
								drilldown.data[path] = result;
								drilldown.items.push({
									list: refList,
									label: refList.getDocumentName(result),
									href: '/keystone/' + refList.path + '/' + result.id
								});
							}
							done();
						});
					}

				}, function(err) {
					// put the drilldown list back in the right order
					drilldown.def.reverse();
					drilldown.items.reverse();
					cb(err);
				});
			};

			var loadRelationships = function(cb) {

				async.each(relationships, function(rel, done) {

					// TODO: Handle invalid relationship config
					rel.list = keystone.list(rel.ref);
					rel.sortable = (rel.list.get('sortable') && rel.list.get('sortContext') === req.list.key + ':' + rel.path);

					// TODO: Handle relationships with more than 1 page of results
					var q = rel.list.paginate({ page: 1, perPage: 100 })
						.where(rel.refPath).equals(item.id)
						.sort(rel.list.defaultSort);

					// rel.columns = _.reject(rel.list.defaultColumns, function(col) { return (col.type == 'relationship' && col.refList == req.list) });
					rel.columns = rel.list.defaultColumns;
					rel.list.selectColumns(q, rel.columns);

					q.exec(function(err, results) {
						rel.items = results;
						done(err);
					});

				}, cb);
			};

			var	loadFormFieldTemplates = function(cb){
				var onlyFields = function(item) { return item.type === 'field'; };
				var compile = function(item, callback) { item.field.compile('form',callback); };
				async.eachSeries(req.list.uiElements.filter(onlyFields), compile , cb);
			};

			/** Render View */

			async.parallel([
				loadDrilldown,
				loadRelationships,
				loadFormFieldTemplates
			], function(err) {

				// TODO: Handle err

				var showRelationships = _.some(relationships, function(rel) {
					return rel.items.results.length;
				});

				keystone.render(req, res, 'item', _.extend(viewLocals, {
					section: keystone.nav.by.list[req.list.key] || {},
					title: 'Keystone: ' + req.list.singular + ': ' + req.list.getDocumentName(item),
					page: 'item',
					list: req.list,
					item: item,
					relationships: relationships,
					showRelationships: showRelationships,
					drilldown: drilldown,
					_csrf: req.csrfToken ? req.csrfToken() : false
				}));

			});

		};

		if (req.method === 'POST' && req.body.action === 'updateItem' && !req.list.get('noedit')) {

			item.getUpdateHandler(req).process(req.body, { flashErrors: true, logErrors: true }, function(err) {
				if (err) {
					return renderView();
				}
				req.flash('success', 'Your changes have been saved.');
				return res.redirect('/keystone/' + req.list.path + '/' + item.id);
			});

		} else {
			renderView();
		}

	});

};


text:
CKEDITOR.plugins.setLang( 'uploadwidget', 'cs', {
	abort: 'Nahrávání zrušeno uživatelem.',
	doneOne: 'Soubor úspěšně nahrán.',
	doneMany: 'Úspěšně nahráno %1 souborů.',
	uploadOne: 'Nahrávání souboru ({percentage}%)...',
	uploadMany: 'Nahrávání souborů, {current} z {max} hotovo ({percentage}%)...'
} );

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace AppBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use AppBundle\Entity\Task;
use AppBundle\Form\TaskType;

/**
 * Task controller.
 *
 * @Route("/{_locale}/task", defaults={"_locale": "es"}, requirements={"_locale": "es|en"})
 */
class TaskController extends Controller
{
    /**
     * Lists all Task entities.
     *
     * @Route("/", name="task")
     * @Method("GET")
     * @Template()
     */
    public function indexAction(Request $request)
    {
        $entities = $this->get('app.task')->findAllTasks();

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

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

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

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

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

        $form->add('submit', 'submit', array('label' => 'Crear tarea', 'attr' => array('class' => 'btn btn-success pull-left')));

        return $form;
    }

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

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

    /**
     * @Route("/hoursbiggerthan/{hours}", name="task_bigger")
     * @Method("GET")
     * @Template("AppBundle:Task:index.html.twig")
     */
    public function biggerThanAction($hours)
    {
        $entities = $this->get('app.task')->findTasksByDurationBiggerThan($hours);

        return array(
            'entities'    => $entities
        );
    }

    /**
     * @Route("/hoursequalsto/{hours}", name="task_equals")
     * @Method("GET")
     * @Template("AppBundle:Task:index.html.twig")
     */
    public function equalsToAction($hours)
    {
        $entities = $this->get('app.task')->findTasksByDurationEqualsTo($hours);

        return array(
            'entities'    => $entities
        );
    }

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

        $entity = $em->getRepository('AppBundle:Task')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Task entity.');
        }

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

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

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

        $entity = $em->getRepository('AppBundle:Task')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Task entity.');
        }

        $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 Task entity.
    *
    * @param Task $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Task $entity)
    {
        $form = $this->createForm(new TaskType(), $entity, array(
            'action' => $this->generateUrl('task_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Actualizar', 'attr' => array('class' => 'btn btn-success pull-left')));

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

        $entity = $em->getRepository('AppBundle:Task')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Task entity.');
        }

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

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

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

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

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('AppBundle:Task')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Task entity.');
            }

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

        return $this->redirect($this->generateUrl('task'));
    }

    /**
     * Creates a form to delete a Task entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('task_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Borrar', 'attr' => array('class' => 'btn btn-danger')))
            ->getForm()
        ;
    }

}


text:
A Small MVC Framework.

This framework was done during a school session.
The subject was to create a website using JavaScript, a Database like MySQL,
CSS (with @media), and some Ajax request using jquery...
To did it, I needed one night :).

So we (me & two friend), decided to create your own framework. In fact, it's
a small framework inspired from differents anothers frameworks (CakePHP, Laravel, ...).
I did the design of this application and wrote a good part of it. Then, me and Quentin
adjusted it to be what we needed and wanted.

The purpose was to design and write a MVC Framework instead of write some PHP
in some files as I did when I was 14 years old. Moreover, one of my friend was
not good in MVC design, so this Framework was quite rewarding for him.

The name of the framework is not important, it came from a joke between us :)

Jason BOURLARD

Quentin DOUZIECH

## How can i use it ?

Download this skeleton : https://github.com/rapsspider/merci-ki-skeleton

After download, just go on the repository with a command line and write : composer install.

## Licence MIT

See the LICENSE file for more informations.

## Thanks

First, thanks for the open source community ! Without it, I can't be curious,
I can't learn, I can't be better. Without the open source, I will know nothing.

Thanks for Quentin Douziech & Bastien Gibrat, my mates.

Thanks for Xavier Mouly to accept your request to do more than a small website which
meet his expectations.


text:
use parser::Parser;
use parser::ast::*;

#[test]
fn parse_database_command() {
    let command = "database warehouse.";
    let mut parser = Parser::new(command.chars());
    let expected = vec![
        Command::Database("warehouse".to_string())
    ];
    let actual = parser.parse();

    assert_eq!(expected, actual);
}

#[test]
fn parse_base_command() {
    let command = "base name (A50).";
    let mut parser = Parser::new(command.chars());
    let expected = vec![
        Command::Base("name".to_string(), Domain {
            domain_type: DomainType::Text,
            length: 50,
        })
    ];
    let actual = parser.parse();

    assert_eq!(expected, actual);
}


text:
ABAP-Utils
==========

ABAP utilities to make my live easier

LCL_ISU_STRUCTURE_READ.abap
===========================
contains a class that wraps the function module ISU_STRUCTURE_READ.
Using this class you don't need to create loads of local variables when using the function module.

```abap
data: lr_error type ref to lcx_error,
      ls_anlage type v_eanl
      .
try.
    create object gr_structure_read.

    perform get_installation using ls_anlage-anlage. "or whatever you need.

    gr_structure_read->add_eanl( ls_anlage ).

    gr_structure_read->add_step(
      iv_tabfrom = 'EANL'
      iv_tabto = 'EVER'
    ).
    gr_structure_read->add_step(
      iv_tabfrom = 'EVER'
      iv_tabto = 'FKKVKP'
    ).
    gr_structure_read->add_step(
      iv_tabfrom = 'FKKVKP'
      iv_tabto = 'EKUN'
    ).

    gr_structure_read->add_step(
      iv_tabfrom = 'EANL'
      iv_tabto = 'EVBS'
    ).

    gr_structure_read->read(
      iv_ab = sy-datum
      iv_bis = sy-datum
    ).

    lt_install[] = gr_structure_read->mt_eanl[].
  catch lcx_error into lr_error.
    mac_print_cancel lr_error->msgty lr_error->msgno lr_error->msgid
                     lr_error->msgv1 lr_error->msgv2 lr_error->msgv3 lr_error->msgv4.
endtry.
```


text:
package io.notoh.rankedcvc.server.matchmaking;

import io.notoh.rankedcvc.server.main.CvCSocket;
import io.notoh.rankedcvc.server.main.RankedCvCServer;
import io.notoh.rankedcvc.server.util.RankUtils;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;

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

/**
 * Manages the queues for matchmaking
 * @author Notoh
 */
public final class QueueManager {

    /** Queue for 0-1000 elo */
    private static final Set<Player> queue1k = new HashSet<>();
    /** Queue for 1001-1500 elo */
    private static final Set<Player> queue1pt5k = new HashSet<>();
    /** Queue for 1501-2000 elo */
    private static final Set<Player> queue2k = new HashSet<>();
    /** Queue for 2000-2500 elo */
    private static final Set<Player> queue2pt5k = new HashSet<>();
    /** Queue for 2501+ elo */
    private static final Set<Player> queue3k = new HashSet<>();

    private static ArrayList<Game> activeGames = new ArrayList<>();

    static void removeGame(Game game) {
        activeGames.remove(game);
    }

    /**
     * Queues a specified player into the appriopriate elo queue.
     * @param player to queue in appropriate elo range.
     * @return {@code String} used for return values.
     */
    @NotNull
    public static String queue(Player player) {
        for (Game game : activeGames) {
            for(Player p : game.getTeamone()) {
                if(p.equals(player)) return "You are already in a game!";
            }
            for(Player p : game.getTeamtwo()) {
                if(p.equals(player)) return "You are already in a game!";
            }
        }
        if(player.getElo() <= 1000) {
            synchronized(queue1k) {
                queue1k.add(player);
                if (queue1k.size() == 12) {
                    HashSet<Player> set = new HashSet<>();
                    set.addAll(queue1k);
                    queue1k.clear();
                    return initiateGame(set);
                } else if (queue1k.size() > 12) {
                    queue1k.clear();
                    return "A bug has occured in queuing for queue 0-1000. The queue will be cleared now.";
                }
            }
        } else if(player.getElo() > 1000 && player.getElo() <= 1500) {
            synchronized(queue1pt5k) {
                queue1pt5k.add(player);
                if (queue1pt5k.size() == 12) {
                    HashSet<Player> set = new HashSet<>();
                    set.addAll(queue1pt5k);
                    queue1pt5k.clear();
                    return initiateGame(set);
                } else if (queue1pt5k.size() > 12) {
                    queue1pt5k.clear();
                    return "A bug has occured in queuing for queue 1001-1500. The queue will be cleared now.";
                }
            }
        } else if(player.getElo() > 1500 && player.getElo() <= 2000) {
            synchronized(queue2k) {
                queue2k.add(player);
                if(queue2k.size() == 12) {
                    HashSet<Player> set = new HashSet<>();
                    set.addAll(queue2k);
                    queue2k.clear();
                    return initiateGame(set);
                } else if(queue2k.size() > 12) {
                    queue2k.clear();
                    return "A bug has occured in queuing for queue 1501-2000. The queue will be cleared now.";
                }
            }
        } else if(player.getElo() > 2000 && player.getElo() <= 2500) {
            synchronized(queue2pt5k) {
                queue2pt5k.add(player);
                if(queue2pt5k.size() == 12) {
                    HashSet<Player> set = new HashSet<>();
                    set.addAll(queue2pt5k);
                    queue2pt5k.clear();
                    return initiateGame(set);
                } else if(queue2pt5k.size() > 12) {
                    queue2pt5k.clear();
                    return "A bug has occured in queuing for queue 2001-2500. The queue will be cleared now.";
                }
            }
        } else if(player.getElo() > 2500) {
            synchronized(queue3k) {
                queue3k.add(player);
                if(queue3k.size() == 12) {
                    HashSet<Player> set = new HashSet<>();
                    set.addAll(queue3k);
                    queue3k.clear();
                    return initiateGame(set);
                } else if(queue3k.size() > 12) {
                    queue3k.clear();
                    return "A bug has occured in queuing for queue 2501+. The queue will be cleared now.";
                }
            }
        }
        return "A player was added to the queue " + findPlayerQueue(player) + ".";
    }

    /**
     * Initiates the specified game with teams.
     * @param queue - Queue that contains all players for the match required.
     * @return {@code String} that returns appropriate return message for players from server.
     */
    @Contract(pure = true)
    @NotNull
    private static String initiateGame(Set<Player> queue) {
        Set<Player> t1;
        Set<Player> t2;
        Iterator<Player> iterator = queue.iterator();
        int each = queue.size() / 2;
        assert(each == 6): "Queue mismatched size";
        t1 = new HashSet<>(each + 1);
        t2 = new HashSet<>(each + 1);
        for(int i = 0; i < each && iterator.hasNext();i++) {
            t1.add(iterator.next());
        }
        for(int i = 0; i < each && iterator.hasNext(); i++) {
            t2.add(iterator.next());
        }
        Game game = new Game(t1,t2);
        activeGames.add(game);
        String ret = "The game has started! " + game.getPlayers() + "with PUG moderators of " + game.getPugs() + "." + " If" +
                " you are a PUG moderator, make sure to use the report command to report the result. The map is " +
                RankUtils.randomMap() + ".";
        for(Player player : queue) {
            if(RankedCvCServer.getInstance().getFromWaiting(player.getName()) != null) {
                CvCSocket.sendTo(RankedCvCServer.getInstance().getFromWaiting(player.getName()),ret);
            }
        }
        return ret;
    }

    /**
     * Returns the appropriate queue's name based on the players elo.
     * @return {@code String} representing name of queue
     * @see #queue(Player)
     */
    @NotNull
    private static String findPlayerQueue(Player player) {
        if (queue1k.contains(player)) {
            return "0-1000 Queue";
        }
        if(queue1pt5k.contains(player)) {
            return "1001-1500 Queue";
        }
        if(queue2k.contains(player)) {
            return "1501-2000 Queue";
        }
        if(queue2pt5k.contains(player)) {
            return "2001-2500 Queue";
        }
        if(queue3k.contains(player)) {
            return "2501+ Queue";
        }
        return "Not Queued.";
    }

    /**
     * Reports a match's results.
     * @param score1 Score of team one.
     * @param score2 Score of team two.
     * @param reporter Player reporting the scores.
     * @return String to be passed up the call stack as a return value for the input.
     */
    @NotNull
    @Contract(pure = true)
    public static String report(int score1, int score2, Player reporter) {
        for(Game game : activeGames) {
            for(Player player : game.getTeamone()) {
                if(player.equals(reporter)) {
                    game.report(reporter, new Score(score1,score2));
                    return "Game successfully reported as " + score1 + "-" + score2 + ".";
                }
            }
            for(Player player : game.getTeamtwo()) {
                if(player.equals(reporter)) {
                    game.report(reporter,new Score(score1,score2));
                    return "Game successfully reported as " + score1 + "-" + score2 + ".";
                }
            }
        }
        return "No game was found to report";
    }

    /**
     * Makes a player leave from the queue.
     * @param playername Name of player to leave the queue.
     * @return A message for the player leaving to confirm input passed up the call stack.
     */
    @SuppressWarnings("Duplicates")
    @NotNull
    @Contract(pure = true)
    public static synchronized String leaveQueue(String playername) {
        for(Player player : queue1k) {
            if(player.getName().equalsIgnoreCase(playername)) {
                queue1k.remove(player);
                String ret = player.getName() + " left the queue!";
                for(Player p : queue1k) {
                    if(RankedCvCServer.getInstance().getFromWaiting(p.getName()) != null) {
                        CvCSocket.sendTo(RankedCvCServer.getInstance().getFromWaiting(p.getName()),ret);
                    }
                }
                return ret;
            }
        }
        for(Player player : queue1pt5k) {
            if(player.getName().equalsIgnoreCase(playername)) {
                queue1pt5k.remove(player);
                String ret = player.getName() + " left the queue!";
                for(Player p : queue1pt5k) {
                    if(RankedCvCServer.getInstance().getFromWaiting(p.getName()) != null) {
                        CvCSocket.sendTo(RankedCvCServer.getInstance().getFromWaiting(p.getName()),ret);
                    }
                }
                return ret;
            }
        }
        for(Player player : queue2k) {
            if(player.getName().equalsIgnoreCase(playername)) {
                queue2k.remove(player);
                String ret = player.getName() + " left the queue!";
                for(Player p : queue2k) {
                    if(RankedCvCServer.getInstance().getFromWaiting(p.getName()) != null) {
                        CvCSocket.sendTo(RankedCvCServer.getInstance().getFromWaiting(p.getName()),ret);
                    }
                }
                return ret;
            }
        }
        for(Player player : queue2pt5k) {
            if(player.getName().equalsIgnoreCase(playername)) {
                queue2pt5k.remove(player);
                String ret = player.getName() + " left the queue!";
                for(Player p : queue2pt5k) {
                    if(RankedCvCServer.getInstance().getFromWaiting(p.getName()) != null) {
                        CvCSocket.sendTo(RankedCvCServer.getInstance().getFromWaiting(p.getName()),ret);
                    }
                }
                return ret;
            }
        }
        for(Player player : queue3k) {
            if(player.getName().equalsIgnoreCase(playername)) {
                queue3k.remove(player);
                String ret = player.getName() + " left the queue!";
                for(Player p : queue3k) {
                    if(RankedCvCServer.getInstance().getFromWaiting(p.getName()) != null) {
                        CvCSocket.sendTo(RankedCvCServer.getInstance().getFromWaiting(p.getName()),ret);
                    }
                }
                return ret;
            }
        }

        return "You aren't in a queue!";
    }

}


text:
<?php

// Variable setup and checking
if(!isset($nav_item))
{
    $nav_item = false;
    if(!isset($form_class))
    {
        $form_class = 'form';
    }
}
if(!isset($context))
{
    $context = 'searchbox';
}
if(!isset($link))
{
    echo("You must set a link for a searchbox!");
}
if(!isset($response_target))
{
    echo("You must set a response_target for a searchbox!");
}
if(!isset($coltype))
{
    $coltype = 'col-sm-3';
}
if(!isset($suggest))
{
    $suggest = false;
}
if(!isset($placeholder))
{
    $placeholder = 'Search...';
}

?>

<form class="<?php if($nav_item === true) { ?>navbar-form navbar-left<?php } else { echo($form_class); } ?>">
    <div class="form-group"<?php if($context === true) { echo(' data-suggest'); } ?> data-widget="searchbox" data-context="<?php echo($context); ?>">

            <input class="form-control <?php echo($coltype);?><?php if($suggest === true){ echo(' typeahead'); } ?>" placeholder="<?php echo($placeholder); ?>" type="text" />

                <button class="btn btn-default" data-link="<?php echo($link); ?>" data-response_target="<?php echo($response_target); ?>">

                </button>

</form>


text:
import * as _ from 'lodash';
import * as ByteBuffer from "bytebuffer";

import {DevicePolicyEnum} from "./device-policy-enum";
import {CoinName} from "./coin-name";
import {CoinTypeConfiguration} from "./coin-type";
import {CoinType} from "./coin-type";

export interface DeviceCapabilities {
  firmwareImageAvailable: boolean;
  defaultMnemonicSeedLength: number;
  supportsCipheredKeyRecovery: boolean;
  supportsSecureAccountTransfer: boolean;
  hasPagedCoinTable: boolean;
  supportsRecoveryDryRun: boolean;
}

export interface BootloaderInfo {
  hash: string;
  upgradable: boolean;
  upgradeSkipable: boolean;
  tag: string;
}

export interface Policy {
  policy_name: string;
  enabled: boolean;
}

export interface IFeatureCoin {
  coin_name: string;
  coin_shortcut: string;
  address_type: number;
  maxfee_kb: string;
  address_type_p2sh: number;
  address_type_p2wpkh: number;
  address_type_p2wsh: number;
  signed_message_header: string;
  bip44_account_path: number;
  forkid: number;
  decimals: number;
  contract_address: ByteBuffer;
  gas_limit: ByteBuffer;
}

export interface DeviceProfile {
  identity: Object;
  capabilities: DeviceCapabilities;
}

export interface IFeatures {
  available_firmware_versions: Array<string>;
  bootloader_hash: ByteBuffer;
  bootloader_mode: any;
  coins: Array<IFeatureCoin>;
  device_id: string;
  initialized: boolean;
  label: string;
  language: string;
  major_version: number;
  minor_version: number;
  passphrase_cached: boolean;
  passphrase_protection: boolean;
  patch_version: number;
  pin_cached: boolean;
  pin_protection: boolean;
  policies: Array<Policy>;
  revision: string;
  vendor: string;
  coin_metadata: Array<CoinTypeConfiguration>;
  deviceCapabilities: DeviceCapabilities;
  bootloaderInfo: BootloaderInfo;
  model: string;
  version: string;
}

export interface ICoinTable {
  table: Array<IFeatureCoin>;
  num_coins: number;
  chunk_size: number;
}

export class Features {
  public get version(): string {
    return [
      this.data.major_version.toString(),
      this.data.minor_version.toString(),
      this.data.patch_version.toString()
    ].join('.');
  }

  public get initialized(): boolean {
    return this.data.initialized;
  }

  public get bootloaderMode(): boolean {
    return this.data.bootloader_mode;
  }

  public get supportsCipheredKeyRecovery(): boolean {
    return _.get(this.data, 'deviceCapabilities.supportsCipheredKeyRecovery');
  }

  public get defaultMnemonicSeedLength(): number {
    return _.get(this.data, 'deviceCapabilities.defaultMnemonicSeedLength');
  }

  public get usesShapeshiftResponseV2(): boolean {
    return _.get(this.data, 'deviceCapabilities.usesShapeshiftResponseV2');
  }

  public get raw(): IFeatures {
    return this.data;
  }

  constructor(private data: IFeatures) {};

  public supportsPolicy(policy: DevicePolicyEnum): boolean {
    return !!(this.findPolicy(policy));
  }

  public policyEnabled(policy: DevicePolicyEnum): boolean {
    return _.get(this.findPolicy(policy), 'enabled');
  }

  public supportsCoinType(coin: CoinName): boolean {
    var coinName: string = CoinName[coin];
    return !!(_.find(this.data.coin_metadata, {name: coinName}));
  }

  public getTokenList(): Array<IFeatureCoin> {
    return this.data.coins.filter((coin: IFeatureCoin) => !!coin.contract_address);
  }

  public get model(): string {
    return this.data.model;
  }

  private findPolicy(policy: DevicePolicyEnum) {
    return _.find(this.data.policies, {
      policy_name: DevicePolicyEnum[policy]
    });
  }
}


text:
<?php

/**
 * @covers puzzle_event_CompleteEvent
 */
class puzzle_test_event_CompleteEventTest extends PHPUnit_Framework_TestCase
{
    public function testHasValues()
    {
        $c = new puzzle_Client();
        $r = new puzzle_message_Request('GET', '/');
        $res = new puzzle_message_Response(200);
        $t = new puzzle_adapter_Transaction($c, $r);
        $e = new puzzle_event_CompleteEvent($t);
        $e->intercept($res);
        $this->assertTrue($e->isPropagationStopped());
        $this->assertSame($res, $e->getResponse());
    }
}


text:
# Compiler Manual

Welcome to the compiler manual. It details the compiler implementation
and its philosophy. Because it focusses on implementation, it's
necessarily out-of-date and incomplete. Also, in this version, I
totally make guesses about things I'm not sure about.

## Overview

The basic data structures used by the compiler (and elsewhere) are
**Node**, **Symbol** and **Type**.

### Node

The parser produces nodes in the form of an Abstract Syntax Tree
(AST). Nodes track syntax kind, location, and children. For example,
`a + 1` produces a BinaryExpression with three children: an
Identifier(a), a PlusToken and a LiteralExpression(1).

### Symbol

The binder produces symbols in the form of a symbol table. A symbol
tracks the declaration(s) of an identifier. The declaration is a
**Node**. In the example below, when the binder encounters `let a = 1`,
it creates a symbol `a`. Then when the checker wants to find the type
of `a * 2`, it can request the symbol for the identifier `a`,
go to `a`'s declaration
and look for an initial value (`1`, in this case) or a type annotation.

```ts
let a = 1
a * 2
```

### Type

The checker produces types. Lots of these types have their own caches,
but types aren't part of some general structure. Types fall into three
categories: primitive types, structured types and type parameters.
(Type parameters could be called type variables.)

1. Primitive types: number, string, etc.
2. Structured types: object types, classes, unions, intersections, etc.
3. Type parameters: um ... type variables that are parameter to
functions or other types?

Primitives don't track much of anything. They are mainly used for
identity. If you call `getApparentType` on `numberType`, you get
`globalNumberType`, which is an *object* type that represents
`Number`. `Number` has methods like `toFixed` et al.

Structured types are types that have or potentially could have
properties. Classes, interfaces and type literals are pretty obvious;
their properties are the ones declared in their respective
declarations.

Structured types like unions, intersections, index types and spread
types represent a type that *will* have properties ... once the type
parameters that they contain are instantiated. For example `T & {
__brand }` will definitely have properties once `T` is provided. At
that point the newer structured types collapse into a normal object
type, so something like `{ ...{ a: string } }` immediately converts to
just `{ a: string }`.

If you need the currently known properties of a structured type, you
can call `getApparentType`. `getApparentType(T & { __brand })` gives
you just `__brand`.

Note that structured types also have call/construct signatures and
numeric/string index signatures. These 4 things are stored and checked
separately from the properties.

TODO: Discuss type parameters.

## Organisation

The compiler implementation is organised into phases: scanner, parser,
binder, checker, and transformer. Each phase has more or less one file
except the transformer, which puts each transformation in its own file
(so, for example, the ESNext transform is in `transforms/esnext.ts`).

This means that big phases have big files, especially the checker. And
each phase is one big namespace with lots of functions inside. In
fact, the files are so big, with so many functions, that the best way
to work is just to search for the function name you need and then jump
from definition to usage and back again. Unfortunately this means that
it's difficult to get started in an area you don't yet understand
because you'll have to guess the names of the functions that implement
the thing you want to work on. I hope that this document will help a
bit with that problem.

## Scanner

The scanner reads individual characters and produces tokens. It can be
configured to ignore spaces and to ignore comments. The default is to
ignore both.

### Comments

The scanner can also produce leading and trailing comments.
However, the definition is not quite right. Sometimes what appear to
be leading comments are parsed as trailing comments. Unfortunately, I
didn't take notes when I tried to fix the code, but here's what I
remember. Sometimes `getLeadingCommentRanges` will not return what
appears to be a leading comment. In this case you will have to call
`getTrailingCommentRanges` as well. For example,
`getJSDocCommentRanges` has a list of nodes that need to call both. It
just concats the results.

The core algorithm that is broken is in `iterateCommentRange`. At one
point I fixed it, but it churned the emitter and services code so much
that I discarded the fix.

## Parser

It's a recursive descent parser. It's pretty resilient, so if you
search for functions matching the thing you want to change, you can
probably get away with just adding the code to parse. There aren't any
surprises in the general implementation style here.

TODO: More here later.

### JSDoc

The parser parses JSDoc half-heartedly. You have to explicitly call
`addJSDocComment` after calling `finishNode` — it's not part of
`finishNode` itself because so many nodes can not have JSDoc on them.

Then once it starts parsing it uses a completely different tokeniser,
`nextJSDocToken()`, from the normal parser. (It doesn't ignore
whitespace and returns way fewer SyntaxKinds). And it parses
everything, even things that exist in Typescript, into completely
separate AST nodes like JSDocArrayType for parsing `T[]`. There are a
few exceptions to this: type literals call back into the normal
parser.

JSDoc is stored in the **jsDocComments** property of the node that
it's associated with. Each JSDoc then contains a top-level **comment**
and a list of **tags**. There are various kinds of tags, but they all
have an associated string **comment** as well. For example:

```js
/**
 * simple function
 * @returns nothing
 */
function f() { }
```

Attaches a JSDoc to `f` with `comment = "simple function"` and a
JSDocReturnTag that has `comment = "nothing"`.

Since JSDoc supports non-local annotations — parameter
information usually occurs on a `@param` tag on the containing
function, for example — retrieval becomes complicated.
Typescript chooses to stitch the information back together when it's
needed, usually while the checker is running. More on that in the
checker section.

## Binder

It gathers symbols from files. There's one created when you start the
compiler, and that's it. It creates symbols for
declarations so that the checker can stick types on them.

TODO: This is woefully incomplete.

TODO: It also sets up some data structures that the checker uses, like
control flow.

TODO: It also marks nodes with their language for the emitter. For
example, all types are typescript syntax, exponentiation is ES2016
syntax and `class` is ES2015 syntax.

## Checker

The checker makes sure the types are right. 'Nuff said!

Actually, it's 20,000 lines long, and does almost everything that's
not syntactic. Surprisingly, a checker gets created every time the
language service requests information because it tries to present an
immutable interface. This works because the checker is very lazy.

Here's a table of contents:

1. Type references and instantiation
2. Control Flow
3. Type inference
4. JSDoc
5. Other topics

### Type references

The life cycle of a generic type is complicated. TODO: Fill in and
correct the details here.

First, when checking a generic declaration like `class A<T> { a: T }`,
the compiler creates an InterfaceType with a property named
typeParameters. Next, when checking a declaration that uses the
generic type, like `let an: A<number>`, the compiler creates a
TypeReference, which has a property named typeParameters (`[T]`) and a
property named typeArguments (`[number]`).

Up to this point, little work has been done. Nothing has caused the
checker to go look for members of `A<number>` or their types. Just a
couple of types have been created with only a few properties on each.
The actual work doesn't start until some code refers to members of
`an`.

For example, when you write `return an.a`, the checker calls
`checkPropertyAccessExpression`. This first gets the type of `an`,
which creates the type reference `A<number>` that I just talked about.
Next it asks for the type of property `a` on `A<number>` with `getPropertyOfType`. This kicks
off the real work.

1. `getPropertyOfType(A<number>, 'a')` calls
2. `resolveStructuredTypeMembers(A<number>)` calls
3. `resolveTypeReferenceMembers` calls `resolveObjectTypeMembers` which then calls
4. `resolveObjectTypeMembers` calls
5. `createTypeMapper` to create a function that takes `T -> number`.
6. Then it calls `createInstantiatedSymbolTable` with the mapper for
each symbol (and call/construct/index signatures).

which calls `instantiateSymbol` on each symbol in `A<T>`. This doesn't actually
*call* the type mapper, it just creates a Symbol with the Instantiated
flag that has a pointer to the original symbol and the mapper.
However, this means that `A<number>` has a `members` table of its own
symbols now. We just haven't figured out what the types of the members are yet.

Now `checkPropertyAccessExpression` can get a symbol for `A<number>.a`, it
calls `getTypeOfSymbol` on it. This kicks off the second half of the
work:

7. `getTypeOfSymbol` calls `getTypeOfInstantiatedSymbol`, which first calls
8. `getTypeOfSymbol` on `A<T>.a`, which checks the declaration of `a` to return `T`
9. then `getTypeOfInstantiatedSymbol` calls
10. `instantiateType`, which calls `mapper(T)`

Which finally returns `number`, since `mapper` got created back in
step 5 to map `T -> number`. Finally, we know that `an.a` has the type
`number`.

Notice that we don't calculate the type of any other members of
`A<number>` (if there were any). They would have to go through steps
(7) to (10) to produce their type.

### Control Flow

The binder sets up backpointers for control flow analysis using only
syntactic information. Then the checker uses these backpointers to
trace control flow from usage to declaration in
`getFlowTypeOfReference`. *Without* control flow, the type of a
variable would always be the type it was declared with. *With* control
flow, usage can *narrow* the type of a variable. That means that the
checker now has two concepts: declared type and flow type (or assigned
type, or computed type). The computed type should always be a
narrowing of the declared type (except for instanceof).

Control flow analysis works by, at each reference of a variable,
starting with the declared type and walking back up the control flow
chain looking at uses of the variable that might change the type. For
example, the assignment `sn = 12` in

```ts
let sn: string | number
sn = 12
sn
```

Makes the flow type of `sn: number` on the last line.

Control flow analysis runs on each reference to a variable. There is
some caching but I believe it's active only within a call to
`getFlowTypeOfReference`. So it's safe to assume each call to
`getFlowTypeOfReference` is independent.

Note: 'declared type' here is different than the type/declared type
distinction that corresponds to static/instance type of classes, and
really only makes sense there. `getDeclaredTypeOfSymbol` and friends
refer to this distinction, but work on any type.

#### Contextual typing

Control flow can run into circularities whenever it calls back into the
normal type-checking code. The normal checking code may end up
requesting the control flow type, which may iterate through control
flow nodes until it requests the type of a node, which may end up
requesting the control flow type....

For example, when you assign to an evolving array, control flow
analysis needs to know the type of the expression being inserted into
the array:

```ts
let x = []
x[0] = { p: 11 }
```

However, to find the type of this particular expression, an object
literal, the checker first asks for the contextual type. The
contextual type is the element type of `x`. And the element type of
`x` is ... determined by control flow analysis. Oops.

### Type Inference

Type inference is basically the hairiest thing the compiler does. Here
are some notes from my latest brush with it; I make no claim that
these are complete, just useful.

Type inference is a triple-nested loop. The outer loop checks
overloads in order. The middle loop initially ignores
context-sensitive parameters, then enables them one at a time. And the
inner loop infers from parameters one at a time (skipping context-sensitive
parameters that haven't been enabled yet).

The outer two loops are in `chooseOverload`, called from inside
`resolveCall` and the inner loop is in `inferTypeArguments`.

The
actual inference rules are in `inferFromTypes` and are pretty
straightforward. Basically, inference recurs through various types
until it reaches a `target` that is a type parameter. Then it adds
whatever the `source` is to the list of inferences. Each inference is
added with a specific priority that is determined by context, such as
`InferencePriority.ReturnType` which is used when looking at the
return type of a function. The
algorithm looks a bit like the assignability algorith, but is more
permissive — for example, it often ignores problems that would
make `isTypeRelatedTo` return false and continues looking for more inferences.

After the structure of the types has been explored, the algorithm
looks at the collected inferences and discards everything but the
highest priority inferences. For example, if any normal inferences
(`inference.priority === 0`) are found, like from arguments to a
function, then inferences from the return type of that same function
(`inference.priority === InferencePriority.ReturnType`) are completely
ignored. To get the final inferred type, `getInferredType` calls
`getCommonSupertype` (unless it was asked to infer a return type, in
which case it calls `getUnionType` instead).

#### Contextual Typing

Contextual typing is especially tricky because it can **fix** type
parameters. When the compiler decides that a parameter is contextually
typed and tries to determine the contextual type, it *must* also fix the type
parameters. That's because the contextual type needs to be the
instantiated type. But getting the instantiated type means that the
compiler has to know how to map the type parameter to the instantiated
type — which is exactly the task of type inference!

What's more, neither assigning a contextual type nor fixing a type
parameter is reversible. So once the contextual type has forced us to
fix a type parameter, we're stuck with both decisions.

That's why contextual types are always processed last; the other
parameters already have types, so type inference is not destructive.
But type inference of contextually typed things actually causes the
types to be added to them **permanently**.

#### Other Notes

* The inner loop (parameters) actually always infers from normal
parameters first. Then it infers from context-sensitive parameters,
but only the ones that have been enabled in the middle loop.

* The outer loop (overloads) throws away the inference context each
time. But the type of parameters may be set if they are context
sensitive. This is occasionally, unfortunately observable.

### JSDoc

JSDoc is handled half-heartedly in the checker as well. That's largely
for historical reasons; the checker didn't care about JSDoc at all
until Typescript was able to handle Javascript because it didn't
contribute types or even symbols to the compilation. (That's right:
JSDoc types in Typescript are *ignored*. It only uses the documentation.)

That's different now because JSDoc is the only way to specify types in
Javascript. But the checker still handles it in a very ad-hoc way
— everywhere you might get some information from a type
annotation, you also need to remember to call `getJSDocType` if you
are checking a Javascript file.

Alas, since JSDoc stores information non-locally, retrieving type
information for a specific node is not that easy. The worst example is
parameters: type information can be stored as a comment for the
parameter, for the function or for the variable that the function is
assigned to:

```js
var /** @param {number} x - a */f =
  /** @param {number} x - b */ function (/** c */x) {
  }
```

Typescript delays the work needed to stitch together this information
until it's needed (as usual), hoping that (1) it won't be needed and
(2) it won't be that hard to retrieve in the common case and (3) that
once cached it will be needed again.

Fortunately, `getJSDocType` conceals this work from you
pretty well. If you're in the checker, that's probably all you'll
need, except perhaps related functions like `getJSDocReturnTag` (to
get the return type of a Javascript function) or `getJSDocTemplateTag`
(to get the type parameters of a Javascript function).

### Other Topics

#### Optionality

Optionality is represented two different ways. The original way is a
flag on `Symbol`. The second way is as a union type that includes
`undefined`.

If you are running with `strictNullChecks: true` then adding '?' after
a property does two things: it marks the symbol as optional and it
adds `| undefined` to the type of the property. You have to remember
to do these two things yourself whenever you synthesise a property
inside the compiler.

Conversely, the compiler actually throws away `| undefined` if
`strictNullChecks: false`. So you can't use *just* `maybeTypeOfKind(t,
TypeFlags.Undefined)` to check for optionality. You also have to check
`symbol.flags & SymbolFlags.Optional`.

#### Literal widening

Literal widening is different from nullable widening. It
doesn't happen in the same place, and it widens a subtype (the literal
type) to a supertype (string, number or boolean). Nullable widening
widens `undefined` and `null` to `any`. It probably wouldn't exist if
`null` and `undefined` had been denotable types before 2.0.

You can widen literals using two different functions,
`getWidenedLiteralType` and `getBaseTypeOfLiteralType`.

The difference is that `getBaseTypeOfLiteralType` unconditionally
widens whereas `getWidenedLiteralType` only widens if the literal type
is fresh. For full discussion of freshness,
[see the PR that implemented it](https://github.com/Microsoft/TypeScript/pull/10676).

Briefly, literal types start fresh if they arise from a literal
expression. Fresh literal types widen when they are assigned to a
non-cost/readonly location. Non-fresh literal types do not widen. For
example,

```ts
const fresh = 1
type notFresh = 1
let f = fresh // f is mutable, so '1' widens to 'number'
let i: notFresh = 1 // even though i is mutable, it has type '1'
```

#### Own-enumerability in spread/rest

Object spread and rest are supposed to skip non-own, non-enumerable
members. However, the compiler doesn't track these two properties. So
it fakes them. The most common non-own non-enumerable member is a
class method, so those are removed.

## Transformer

The transformer recently replaced the emitter, which translated
TypeScript to JavaScript. The *transformer* transforms TypeScript or
JavaScript (various versions) to JavaScript (various versions) using
various module systems. The input and output are basically both trees
from the same AST type, just using different features.

The emitter is now a fairly small AST printer that can print
any TypeScript or JavaScript AST.

### Overview

The binder sets up information for the transformer since it
makes a complete pass over the AST anyway. Primarily, it marks
individual nodes with their associated dialect. In the example below,
`...x` is marked as ES2015, and `any[]` and `void` are marked as
Typescript.

```ts
function f(...x: any[]): void {
}
```

Then each transformer runs on the AST. The Typescript transformer
mostly just throws away annotations. The ES2015 transformation
actually has to emit ES5 code that implements the rest parameter.
The transforms progressively convert Typescript into older and older
Javascript dialects. The transformer will run until the AST is valid
ES3, or it will stop earlier if the target is something newer like
ES2015. Then the emitter pretty-prints the AST.

TODO: This leaves out module transformers.

## Branded Types

Two branded types exist within the compiler, `Path` and `__String`. These
are both branded strings with different shapes and different purposes.

`Path` is used to represent an absolute, normalized, canonical folder path
or file name. If you have a `Path`, it should already be all of the above.
You may get a path from a path-looking string via `toPath`, and a `Path` may
be safely used anywhere a string is requested.

`__String` is used to represent a string whose leading underscore have been
escaped (if present) or a string representing an internal compiler symbol name,
such as `"__call"`. To escape a string in this way, call `escapeLeadingUnderscores`.
To unescape such a string, call `unescapeLeadingUnderscores`. Strings of this kind
are used to represent symbol names and identifier text, to allow for internal symbol
names to cohabitate the same symbol table as normal members without being in conflict.
The brand on this type is structured such that it is castable and comparable with
normal strings, but a normal string cannot be used in its place and it can not
be used in place of a normal string (to prevent escaped text from leaking out via
diagnostic messages and the like). The union member enabling this is the member intersected
with `void`, which makes it incompatible with anything asking for a string.

## Services

I don't know anything about services. And besides, this readme is for
the compiler.

## Other files

This is an unsorted inventory. Some of these deserve an in-depth
explanation, or at least a big overview of what they mean.

1. core
2. utilities
3. program
4. scanner
5. sourcemap
6. sys
7. tsc
8. types
8. commandLineParser
9. declarationEmitter


text:
using namespace arangodb;
using namespace arangodb::rest;

RestExportHandler::RestExportHandler(GeneralRequest* request,
                                     GeneralResponse* response)
    : RestVocbaseBaseHandler(request, response), _restrictions() {}

RestStatus RestExportHandler::execute() {
  if (ServerState::instance()->isCoordinator()) {
    generateError(rest::ResponseCode::NOT_IMPLEMENTED,
                  TRI_ERROR_CLUSTER_UNSUPPORTED,
                  "'/_api/export' is not yet supported in a cluster");
    return RestStatus::DONE;
  }

  // extract the sub-request type
  auto const type = _request->requestType();

  if (type == rest::RequestType::POST) {
    createCursor();
    return RestStatus::DONE;
  }

  if (type == rest::RequestType::PUT) {
    modifyCursor();
    return RestStatus::DONE;
  }

  if (type == rest::RequestType::DELETE_REQ) {
    deleteCursor();
    return RestStatus::DONE;
  }

  generateError(rest::ResponseCode::METHOD_NOT_ALLOWED,
                TRI_ERROR_HTTP_METHOD_NOT_ALLOWED);
  return RestStatus::DONE;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief build options for the query as JSON
////////////////////////////////////////////////////////////////////////////////

VPackBuilder RestExportHandler::buildOptions(VPackSlice const& slice) {
  VPackBuilder options;
  options.openObject();

  VPackSlice count = slice.get("count");
  if (count.isBool()) {
    options.add("count", count);
  } else {
    options.add("count", VPackValue(false));
  }

  VPackSlice batchSize = slice.get("batchSize");
  if (batchSize.isNumber()) {
    if ((batchSize.isInteger() && batchSize.getUInt() == 0) ||
        (batchSize.isDouble() && batchSize.getDouble() == 0.0)) {
      THROW_ARANGO_EXCEPTION_MESSAGE(
          TRI_ERROR_TYPE_ERROR, "expecting non-zero value for 'batchSize'");
    }
    options.add("batchSize", batchSize);
  } else {
    options.add("batchSize", VPackValue(1000));
  }

  VPackSlice limit = slice.get("limit");
  if (limit.isNumber()) {
    options.add("limit", limit);
  }

  VPackSlice flush = slice.get("flush");
  if (flush.isBool()) {
    options.add("flush", flush);
  } else {
    options.add("flush", VPackValue(false));
  }

  VPackSlice ttl = slice.get("ttl");
  if (ttl.isNumber()) {
    options.add("ttl", ttl);
  } else {
    options.add("ttl", VPackValue(30));
  }

  VPackSlice flushWait = slice.get("flushWait");
  if (flushWait.isNumber()) {
    options.add("flushWait", flushWait);
  } else {
    options.add("flushWait", VPackValue(10));
  }
  options.close();

  // handle "restrict" parameter
  VPackSlice restrct = slice.get("restrict");
  if (!restrct.isObject()) {
    if (!restrct.isNone()) {
      THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_TYPE_ERROR,
                                     "expecting object for 'restrict'");
    }
  } else {
    // "restrict"."type"
    VPackSlice type = restrct.get("type");
    if (!type.isString()) {
      THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
                                     "expecting string for 'restrict.type'");
    }
    std::string typeString = type.copyString();

    if (typeString == "include") {
      _restrictions.type = CollectionExport::Restrictions::RESTRICTION_INCLUDE;
    } else if (typeString == "exclude") {
      _restrictions.type = CollectionExport::Restrictions::RESTRICTION_EXCLUDE;
    } else {
      THROW_ARANGO_EXCEPTION_MESSAGE(
          TRI_ERROR_BAD_PARAMETER,
          "expecting either 'include' or 'exclude' for 'restrict.type'");
    }

    // "restrict"."fields"
    VPackSlice fields = restrct.get("fields");
    if (!fields.isArray()) {
      THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_BAD_PARAMETER,
                                     "expecting array for 'restrict.fields'");
    }
    for (auto const& name : VPackArrayIterator(fields)) {
      if (name.isString()) {
        _restrictions.fields.emplace(name.copyString());
      }
    }
  }

  return options;
}

////////////////////////////////////////////////////////////////////////////////
/// @brief was docuBlock JSF_post_api_export
////////////////////////////////////////////////////////////////////////////////

void RestExportHandler::createCursor() {
  std::vector<std::string> const& suffixes = _request->suffixes();

  if (!suffixes.empty()) {
    generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
                  "expecting POST /_api/export");
    return;
  }

  // extract the cid
  bool found;
  std::string const& name = _request->value("collection", found);

  if (!found || name.empty()) {
    generateError(rest::ResponseCode::BAD,
                  TRI_ERROR_ARANGO_COLLECTION_PARAMETER_MISSING,
                  "'collection' is missing, expecting " + EXPORT_PATH +
                      "?collection=<identifier>");
    return;
  }

  bool parseSuccess = true;
  std::shared_ptr<VPackBuilder> parsedBody =
      parseVelocyPackBody(&VPackOptions::Defaults, parseSuccess);

  if (!parseSuccess) {
    return;
  }
  VPackSlice body = parsedBody.get()->slice();

  VPackBuilder optionsBuilder;

  if (!body.isNone()) {
    if (!body.isObject()) {
      generateError(rest::ResponseCode::BAD, TRI_ERROR_QUERY_EMPTY);
      return;
    }
    optionsBuilder = buildOptions(body);
  } else {
    // create an empty options object
    optionsBuilder.openObject();
    optionsBuilder.close();
  }

  VPackSlice options = optionsBuilder.slice();

  uint64_t waitTime = 0;
  bool flush = arangodb::basics::VelocyPackHelper::getBooleanValue(
      options, "flush", false);

  if (flush) {
    // flush the logfiles so the export can fetch all documents
    int res =
        arangodb::wal::LogfileManager::instance()->flush(true, true, false);

    if (res != TRI_ERROR_NO_ERROR) {
      THROW_ARANGO_EXCEPTION(res);
    }

    double flushWait =
        arangodb::basics::VelocyPackHelper::getNumericValue<double>(
            options, "flushWait", 10.0);

    waitTime = static_cast<uint64_t>(
        flushWait * 1000 *
        1000);  // flushWait is specified in s, but we need ns
  }

  size_t limit = arangodb::basics::VelocyPackHelper::getNumericValue<size_t>(
      options, "limit", 0);

  // this may throw!
  auto collectionExport =
      std::make_unique<CollectionExport>(_vocbase, name, _restrictions);
  collectionExport->run(waitTime, limit);

  size_t batchSize =
      arangodb::basics::VelocyPackHelper::getNumericValue<size_t>(
          options, "batchSize", 1000);
  double ttl = arangodb::basics::VelocyPackHelper::getNumericValue<double>(
      options, "ttl", 30);
  bool count = arangodb::basics::VelocyPackHelper::getBooleanValue(
      options, "count", false);

  auto cursors = _vocbase->cursorRepository();
  TRI_ASSERT(cursors != nullptr);

  // create a cursor from the result
  arangodb::ExportCursor* cursor = cursors->createFromExport(
      collectionExport.get(), batchSize, ttl, count);
  collectionExport.release();

  resetResponse(rest::ResponseCode::CREATED);

  try {
    VPackBuffer<uint8_t> buffer;
    VPackBuilder builder(buffer);
    builder.openObject();
    builder.add("error", VPackValue(false));
    builder.add("code", VPackValue((int)_response->responseCode()));
    cursor->dump(builder);
    builder.close();

    _response->setContentType(rest::ContentType::JSON);
    generateResult(rest::ResponseCode::CREATED, builder.slice());

    cursors->release(cursor);
  } catch (...) {
    cursors->release(cursor);
    throw;
  }
}

void RestExportHandler::modifyCursor() {
  std::vector<std::string> const& suffixes = _request->suffixes();

  if (suffixes.size() != 1) {
    generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
                  "expecting PUT /_api/export/<cursor-id>");
    return;
  }

  std::string const& id = suffixes[0];

  auto cursors = _vocbase->cursorRepository();
  TRI_ASSERT(cursors != nullptr);

  auto cursorId = static_cast<arangodb::CursorId>(
      arangodb::basics::StringUtils::uint64(id));
  bool busy;
  auto cursor = cursors->find(cursorId, Cursor::CURSOR_EXPORT, busy);

  if (cursor == nullptr) {
    if (busy) {
      generateError(GeneralResponse::responseCode(TRI_ERROR_CURSOR_BUSY),
                    TRI_ERROR_CURSOR_BUSY);
    } else {
      generateError(GeneralResponse::responseCode(TRI_ERROR_CURSOR_NOT_FOUND),
                    TRI_ERROR_CURSOR_NOT_FOUND);
    }
    return;
  }

  try {
    resetResponse(rest::ResponseCode::OK);

    VPackBuffer<uint8_t> buffer;
    VPackBuilder builder(buffer);
    builder.openObject();
    builder.add("error", VPackValue(false));
    builder.add("code", VPackValue((int)_response->responseCode()));
    cursor->dump(builder);
    builder.close();

    _response->setContentType(rest::ContentType::JSON);
    generateResult(rest::ResponseCode::OK, builder.slice());

    cursors->release(cursor);
  } catch (...) {
    cursors->release(cursor);
    throw;
  }
}

void RestExportHandler::deleteCursor() {
  std::vector<std::string> const& suffixes = _request->suffixes();

  if (suffixes.size() != 1) {
    generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_BAD_PARAMETER,
                  "expecting DELETE /_api/export/<cursor-id>");
    return;
  }

  std::string const& id = suffixes[0];

  auto cursors = _vocbase->cursorRepository();
  TRI_ASSERT(cursors != nullptr);

  auto cursorId = static_cast<arangodb::CursorId>(
      arangodb::basics::StringUtils::uint64(id));
  bool found = cursors->remove(cursorId, Cursor::CURSOR_EXPORT);

  if (!found) {
    generateError(rest::ResponseCode::NOT_FOUND, TRI_ERROR_CURSOR_NOT_FOUND);
    return;
  }

  VPackBuilder result;
  result.openObject();
  result.add("id", VPackValue(id));
  result.add("error", VPackValue(false));
  result.add("code",
             VPackValue(static_cast<int>(rest::ResponseCode::ACCEPTED)));
  result.close();

  generateResult(rest::ResponseCode::ACCEPTED, result.slice());
}


text:
ALTER TABLE movies ADD status_tags VARCHAR;

-- Down


text:
public class HashSet implements Iteravel {
	public boolean add(Object element) {
		// adiciona um elemento
		return true;
	}

	public void remove(Object element) {
		// remove um elemento
	}

	public boolean contains(Object element) {
		// verifica se um elemento esta na classe
		return false;
	}

	public int size() {
		// calcula todos os elementos da colecao
		return 0;
	}

	public void clear() {
		// apaga todos os elementos da colecao
	}

	public Object get(int chaveMaluca) {
		// recupera o elemento na posicao i
		return null;
	}

	@Override
	public Iterador percorrerColecao() {
		// TODO Auto-generated method stub
		return null;
	}
}


text:
**Namespace:** [OfficeDevPnP.Core.UPAWebService](OfficeDevPnP.Core.UPAWebService.md)
**Assembly:** OfficeDevPnP.Core.dll
## Syntax
```C#
public MembershipData[] Memberships { get; set; }
```

### Property Value
Type: [OfficeDevPnP.Core.UPAWebService.MembershipData[]](OfficeDevPnP.Core.UPAWebService.MembershipData.md)

## See also
- [GetUserProfileByIndexResult](OfficeDevPnP.Core.UPAWebService.GetUserProfileByIndexResult.md)
- [OfficeDevPnP.Core.UPAWebService](OfficeDevPnP.Core.UPAWebService.md)


text:
namespace Tralus.Framework.Migration.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class InitForDevDb : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(InitForDevDb));

        string IMigrationMetadata.Id
        {
            get { return "201509291318026_InitForDevDb"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
package com.gotye.sdk.utils;

import java.util.HashMap;
import java.util.Set;

import android.content.Context;
import android.net.Uri;
import android.util.Log;

import com.gotye.api.GotyeStatusCode;
import com.gotye.api.bean.GotyeUser;
import com.gotye.api.net.GotyeRequestFuture;
import com.gotye.sdk.InnerConstants;

/**
 * Primary {@link UserInfoManager} implementation used by {@link MessagingApplication}.
 *

 * Public methods should only be used from a single thread (typically the UI
 * thread). Callbacks will be invoked on the thread where the ThumbnailManager
 * was instantiated.
 *

 * Uses a thread-pool ExecutorService instead of AsyncTasks since clients may
 * request lots of pdus around the same time, and AsyncTask may reject tasks
 * in that case and has no way of bounding the number of threads used by those
 * tasks.
 *

 * ThumbnailManager is used to asynchronously load pictures and create thumbnails. The thumbnails
 * are stored in a local cache with SoftReferences. Once a thumbnail is loaded, it will call the
 * passed in callback with the result. If a thumbnail is immediately available in the cache,
 * the callback will be called immediately as well.
 *
 * Based on BooksImageManager by Virgil King.
 */
public class UserInfoManager extends BackgroundLoaderManager {
    private static final String TAG = "ResManager";

    private final static int TIMEOUT = 120000;
    private final Context mContext;
    private static UserInfoManager instance;
    private HashMap<String, TimeUser> mCache;

    public static synchronized UserInfoManager getInstance(Context context){
    	if(instance == null){
    		instance = new UserInfoManager(context.getApplicationContext());
    	}
    	return instance;
    }

    public UserInfoManager(final Context context) {
        super(context);
        mContext = context;
        mCache = new HashMap<String, TimeUser>();
    }

    /**
     * getThumbnail must be called on the same thread that created ThumbnailManager. This is
     * normally the UI thread.
     * @param uri the uri of the image
     * @param width the original full width of the image
     * @param height the original full height of the image
     * @param callback the callback to call when the thumbnail is fully loaded
     * @return
     */
    public ItemLoadedFuture getThumbnail(GotyeUser user,
            final ItemLoadedCallback<UserLoaded> callback, Object tag) {

        return getThumbnail(user, Uri.parse(user.getUsername()), false, callback, tag);
    }

    private ItemLoadedFuture getThumbnail(GotyeUser user, Uri uri, boolean isVideo,
            final ItemLoadedCallback<UserLoaded> callback, Object tag) {
        if (uri == null) {
            throw new NullPointerException();
        }

        TimeUser item = mCache.get(user.getUsername());
        boolean thumbnailExists = (item != null);

        final boolean taskExists = mPendingTaskUris.contains(uri);
        final boolean newTaskRequired = !thumbnailExists && !taskExists;
        final boolean callbackRequired = (callback != null);

        if (callbackRequired) {
            addCallback(uri, callback);
        }

        if (thumbnailExists) {
        	NullItemLoadedFuture f = new NullItemLoadedFuture();;
        	boolean timeout = ((System.currentTimeMillis() - item.putTime) > TIMEOUT) ? true : false;
        	final GotyeUser thumbnail = item.user;
            if (callbackRequired) {
            	UserLoaded imageLoaded = new UserLoaded(tag, thumbnail, f);
//                callback.onItemLoaded(imageLoaded, null);
                final Set<ItemLoadedCallback> callbacks = mCallbacks.get(uri);
                if (callbacks != null) {

                    // Make a copy so that the callback can unregister itself
                    for (final ItemLoadedCallback<UserLoaded> c : asList(callbacks)) {
                    	Log.d("", "call back " + imageLoaded.user.getUsername() + " " + imageLoaded.user.getNickName());
                        c.onItemLoaded(imageLoaded, null);
                    }
                }
            }
            if(timeout){
       		 	mCache.remove(user.getUsername());
            }
            if(!timeout){
            	mCallbacks.remove(uri);
            	Log.d(TAG, "find userinfo");
            	return f;
            }else {
            	Log.d(TAG, "find userinfo timeout");
            }
        }

        ItemLoadedFuture f =  new ItemLoadedFuture() {
            private boolean mIsDone;

            @Override
            public void cancel(Uri uri) {
                cancelCallback(callback);
//                removeThumbnail(uri);   // if the thumbnail is half loaded, force a reload next time
            }

            @Override
            public void setIsDone(boolean done) {
                mIsDone = done;
            }

            @Override
            public boolean isDone() {
                return mIsDone;
            }
        };

        if (newTaskRequired) {
            mPendingTaskUris.add(uri);
            Runnable task = new LoadResTask(tag, user, uri, f);
            mExecutor.execute(task);
        }
        return f;
    }

    @Override
    public synchronized void clear() {
        super.clear();

        mCache.clear();
    }

    @Override
    public String getTag() {
        return TAG;
    }

    public class LoadResTask implements Runnable {
        private final Uri mUri;
        private final ItemLoadedFuture mIsVideo;
        private final GotyeUser user;
        private final Object tag;

        public LoadResTask(Object tag, GotyeUser user, Uri uri, ItemLoadedFuture isVideo) {
            if (uri == null) {
                throw new NullPointerException();
            }
            this.user = user;
            mUri = uri;
            mIsVideo = isVideo;
            this.tag = tag;
        }

        /** {@inheritDoc} */
        @Override
        public void run() {

        	Exception exception = null;

           //download res
        	try {
        		GotyeRequestFuture fu = InnerConstants.getAPI(mContext).getUserInfo(user);
				fu.get();
				if(fu.getCode() == GotyeStatusCode.STATUS_OK){

	        		TimeUser item = new TimeUser();
	        		item.putTime = System.currentTimeMillis();
	        		item.user = user;
	        		mCache.put(user.getUsername(), item);
	        	}
			} catch (Exception e1) {
				e1.printStackTrace();
				exception = e1;
			}

        	final Exception e = exception;
            mCallbackHandler.post(new Runnable() {
                @Override
                public void run() {
                    final Set<ItemLoadedCallback> callbacks = mCallbacks.get(mUri);
                    if (callbacks != null) {

                        // Make a copy so that the callback can unregister itself
                        for (final ItemLoadedCallback<UserLoaded> callback : asList(callbacks)) {
                        	 UserLoaded imageLoaded = new UserLoaded(tag, user, mIsVideo);
                             callback.onItemLoaded(imageLoaded, e);
                        }
                    }

                    // Add the bitmap to the soft cache if the load succeeded. Don't cache the
                    // stand-ins for empty bitmaps.

                    mCallbacks.remove(mUri);
                    mPendingTaskUris.remove(mUri);

                }
            });
        }

    }

    public static class UserLoaded {
        public final GotyeUser user;
        public final ItemLoadedFuture fu;
        public final Object tag;

		public UserLoaded(Object tag, GotyeUser user, ItemLoadedFuture fu) {
			super();
			this.user = user;
			this.fu = fu;
			this.tag = tag;
		}

    }

    private static class TimeUser {
    	long putTime;
    	GotyeUser user;
    }
}


text:
// Copyright © 2010 onwards, Andrew Whewell
// All rights reserved.
//
// Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
//    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
//    * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Globalization;

namespace VirtualRadar.Interface.Settings
{
    /// <summary>
    /// The class that holds the settings for the plugins. These are loaded and saved via <see cref="IPluginSettingsStorage"/>.
    /// </summary>
    /// <remarks><para>
    /// It is important to note that this object will contain every setting for every plugin, not just the plugin that
    /// loaded it. When writing settings out you should read the old settings first and amend them rather than create
    /// new settings and save them, otherwise you will obliterate the settings for all of the other plugins.
    /// </para><para>
    /// The settings are stored as strings in the <see cref="Values"/> collection. The collection is indexed by a key
    /// which must be unique. If you use the supplied Read and Write methods then the <see cref="IPlugin.Id"/> property
    /// is joined to the key supplied to the method to form a full key that should be unique to your plugin. The Read
    /// and Write methods also ensure that when ValueTypes are converted to and from strings they use the invariant
    /// culture, e.g. the same string is written for the floating point value 1.234 regardless of the region setting
    /// that Windows is configured for.
    /// </para></remarks>
    /// <example>
    /// To load a setting from within an <see cref="IPlugin"/>:
    /// <code>
    /// IPluginSettingsStorage storage = Factory.Singleton.Resolve<IPluginSettingsStorage>().Singleton;
    /// PluginSettings settings = storage.Load();
    ///
    /// bool mySetting = ReadBool(this, "Key", true);
    /// </code>
    /// To save a setting from within an <see cref="IPlugin"/>:
    /// IPluginSettingsStorage storage = Factory.Singleton.Resolve<IPluginSettingsStorage>().Singleton;
    /// PluginSettings settings = storage.Load();
    /// settings.Write(this, "Key", false);
    /// storage.Save(settings);
    /// </example>
    public class PluginSettings
    {
        /// <summary>
        /// Gets a collection of property names and their values. Plugins should ensure the keys for the values
        /// are unique across all plugins.
        /// </summary>
        /// <remarks>
        /// This collection is shared by all plugins. The keys should be prefaced by a string unique to each plugin,
        /// for example by the plugin ID string.
        /// </remarks>
        public NameValueCollection Values { get; private set; }

        /// <summary>
        /// Creates a new object.
        /// </summary>
        public PluginSettings()
        {
            Values = new NameValueCollection();
        }

        /// <summary>
        /// Creates a nicely formed key name from the plugin ID and key passed across.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private string FormKey(IPlugin plugin, string key)
        {
            return String.Format("{0}.{1}", plugin.Id, key);
        }

        /// <summary>
        /// Returns a string from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string ReadString(IPlugin plugin, string key)
        {
            return Values[FormKey(plugin, key)];
        }

        /// <summary>
        /// Returns a nullable bool from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool? ReadBool(IPlugin plugin, string key)
        {
            var text = ReadString(plugin, key);
            bool? result = text == "1" ? true : text == "0" ? false : (bool?)null;

            return result;
        }

        /// <summary>
        /// Returns a bool from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public bool ReadBool(IPlugin plugin, string key, bool defaultValue)
        {
            return ReadBool(plugin, key) ?? defaultValue;
        }

        /// <summary>
        /// Returns a nullable int from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public int? ReadInt(IPlugin plugin, string key)
        {
            int? result = null;

            var text = ReadString(plugin, key);
            if(text != null) {
                int value;
                if(int.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) result = value;
            }

            return result;
        }

        /// <summary>
        /// Returns an integer from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public int ReadInt(IPlugin plugin, string key, int defaultValue)
        {
            return ReadInt(plugin, key) ?? defaultValue;
        }

        /// <summary>
        /// Returns a nullable long from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public long? ReadLong(IPlugin plugin, string key)
        {
            long? result = null;

            var text = ReadString(plugin, key);
            if(text != null) {
                long value;
                if(long.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) result = value;
            }

            return result;
        }

        /// <summary>
        /// Returns a long from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public long ReadLong(IPlugin plugin, string key, long defaultValue)
        {
            return ReadLong(plugin, key) ?? defaultValue;
        }

        /// <summary>
        /// Returns a nullable double from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public double? ReadDouble(IPlugin plugin, string key)
        {
            double? result = null;

            var text = ReadString(plugin, key);
            if(text != null) {
                double value;
                if(double.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out value)) result = value;
            }

            return result;
        }

        /// <summary>
        /// Returns a double from <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public double ReadDouble(IPlugin plugin, string key, double defaultValue)
        {
            return ReadDouble(plugin, key) ?? defaultValue;
        }

        /// <summary>
        /// Returns a nullable DateTime from <see cref="Values"/>. The DateTimeKind is local.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public DateTime? ReadDateTime(IPlugin plugin, string key)
        {
            DateTime? result = null;

            var text = ReadString(plugin, key);
            if(text != null) {
                DateTime value;
                if(DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out value)) result = value;
            }

            return result;
        }

        /// <summary>
        /// Returns a DateTime from <see cref="Values"/>. The DateTimeKind is local.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public DateTime ReadDateTime(IPlugin plugin, string key, DateTime defaultValue)
        {
            return ReadDateTime(plugin, key) ?? defaultValue;
        }

        /// <summary>
        /// Writes a bool into <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write(IPlugin plugin, string key, bool value)
        {
            Values[FormKey(plugin, key)] = value ? "1" : "0";
        }

        /// <summary>
        /// Writes an int into <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write(IPlugin plugin, string key, int value)
        {
            Values[FormKey(plugin, key)] = value.ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Writes a long into <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write(IPlugin plugin, string key, long value)
        {
            Values[FormKey(plugin, key)] = value.ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Writes a double into <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write(IPlugin plugin, string key, double value)
        {
            Values[FormKey(plugin, key)] = value.ToString(CultureInfo.InvariantCulture);
        }

        /// <summary>
        /// Writes a DateTime into <see cref="Values"/>.
        /// </summary>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write(IPlugin plugin, string key, DateTime value)
        {
            Values[FormKey(plugin, key)] = value.ToUniversalTime().ToString("u");
        }

        /// <summary>
        /// Writes a value into <see cref="Values"/>.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="plugin"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void Write<T>(IPlugin plugin, string key, T value)
        {
            Values[FormKey(plugin, key)] = value == null ? null : value.ToString();
        }
    }
}


text:
package org.apache.skywalking.oap.server.core.alarm.provider;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import org.apache.skywalking.oap.server.core.alarm.AlarmCallback;
import org.apache.skywalking.oap.server.core.alarm.AlarmMessage;
import org.joda.time.LocalDateTime;
import org.joda.time.Minutes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Alarm core includes metrics values in certain time windows based on alarm settings. By using its internal timer
 * trigger and the alarm rules to decide whether send the alarm to database and webhook(s)
 */
public class AlarmCore {
    private static final Logger LOGGER = LoggerFactory.getLogger(AlarmCore.class);

    private LocalDateTime lastExecuteTime;
    private AlarmRulesWatcher alarmRulesWatcher;

    AlarmCore(AlarmRulesWatcher alarmRulesWatcher) {
        this.alarmRulesWatcher = alarmRulesWatcher;
    }

    public List<RunningRule> findRunningRule(String metricsName) {
        return alarmRulesWatcher.getRunningContext().get(metricsName);
    }

    public void start(List<AlarmCallback> allCallbacks) {
        LocalDateTime now = LocalDateTime.now();
        lastExecuteTime = now;
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                final List<AlarmMessage> alarmMessageList = new ArrayList<>(30);
                LocalDateTime checkTime = LocalDateTime.now();
                int minutes = Minutes.minutesBetween(lastExecuteTime, checkTime).getMinutes();
                boolean[] hasExecute = new boolean[]{false};
                alarmRulesWatcher.getRunningContext().values().forEach(ruleList -> ruleList.forEach(runningRule -> {
                    if (minutes > 0) {
                        runningRule.moveTo(checkTime);
                        /*
                         * Don't run in the first quarter per min, avoid to trigger false alarm.
                         */
                        if (checkTime.getSecondOfMinute() > 15) {
                            hasExecute[0] = true;
                            alarmMessageList.addAll(runningRule.check());
                        }
                    }
                }));
                // Set the last execute time, and make sure the second is `00`, such as: 18:30:00
                if (hasExecute[0]) {
                    lastExecuteTime = checkTime.withSecondOfMinute(0).withMillisOfSecond(0);
                }

                if (!alarmMessageList.isEmpty()) {
                    if (!alarmRulesWatcher.getCompositeRules().isEmpty()) {
                        List<AlarmMessage> messages = alarmRulesWatcher.getCompositeRuleEvaluator().evaluate(alarmRulesWatcher.getCompositeRules(), alarmMessageList);
                        alarmMessageList.addAll(messages);
                    }
                    List<AlarmMessage> filteredMessages = alarmMessageList.stream().filter(msg -> !msg.isOnlyAsCondition()).collect(Collectors.toList());
                    if (!filteredMessages.isEmpty()) {
                        allCallbacks.forEach(callback -> callback.doAlarm(filteredMessages));
                    }
                }
            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
        }, 10, 10, TimeUnit.SECONDS);
    }
}


text:
package com.amazonaws.services.ec2.model;

/**
 *

 * Describes an Amazon EC2 key pair, including the private key material.
 *

 *

 * The public key portion is stored by Amazon EC2 and the private key is returned only once, in this type, when the key is initially created.
 *

 */
public class KeyPair {

    /**
     * The name of the key pair.
     */
    private String keyName;

    /**
     * The SHA-1 digest of the DER encoded private key.
     */
    private String keyFingerprint;

    /**
     * The unencrypted PEM encoded RSA private key.
     */
    private String keyMaterial;

    /**
     * The name of the key pair.
     *
     * @return The name of the key pair.
     */
    public String getKeyName() {
        return keyName;
    }

    /**
     * The name of the key pair.
     *
     * @param keyName The name of the key pair.
     */
    public void setKeyName(String keyName) {
        this.keyName = keyName;
    }

    /**
     * The name of the key pair.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param keyName The name of the key pair.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public KeyPair withKeyName(String keyName) {
        this.keyName = keyName;
        return this;
    }

    /**
     * The SHA-1 digest of the DER encoded private key.
     *
     * @return The SHA-1 digest of the DER encoded private key.
     */
    public String getKeyFingerprint() {
        return keyFingerprint;
    }

    /**
     * The SHA-1 digest of the DER encoded private key.
     *
     * @param keyFingerprint The SHA-1 digest of the DER encoded private key.
     */
    public void setKeyFingerprint(String keyFingerprint) {
        this.keyFingerprint = keyFingerprint;
    }

    /**
     * The SHA-1 digest of the DER encoded private key.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param keyFingerprint The SHA-1 digest of the DER encoded private key.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public KeyPair withKeyFingerprint(String keyFingerprint) {
        this.keyFingerprint = keyFingerprint;
        return this;
    }

    /**
     * The unencrypted PEM encoded RSA private key.
     *
     * @return The unencrypted PEM encoded RSA private key.
     */
    public String getKeyMaterial() {
        return keyMaterial;
    }

    /**
     * The unencrypted PEM encoded RSA private key.
     *
     * @param keyMaterial The unencrypted PEM encoded RSA private key.
     */
    public void setKeyMaterial(String keyMaterial) {
        this.keyMaterial = keyMaterial;
    }

    /**
     * The unencrypted PEM encoded RSA private key.
     *

     * Returns a reference to this object so that method calls can be chained together.
     *
     * @param keyMaterial The unencrypted PEM encoded RSA private key.
     *
     * @return A reference to this updated object so that method calls can be chained
     *         together.
     */
    public KeyPair withKeyMaterial(String keyMaterial) {
        this.keyMaterial = keyMaterial;
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and
     * debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (keyName != null) sb.append("KeyName: " + keyName + ", ");
        if (keyFingerprint != null) sb.append("KeyFingerprint: " + keyFingerprint + ", ");
        if (keyMaterial != null) sb.append("KeyMaterial: " + keyMaterial + ", ");
        sb.append("}");
        return sb.toString();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getKeyName() == null) ? 0 : getKeyName().hashCode());
        hashCode = prime * hashCode + ((getKeyFingerprint() == null) ? 0 : getKeyFingerprint().hashCode());
        hashCode = prime * hashCode + ((getKeyMaterial() == null) ? 0 : getKeyMaterial().hashCode());
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;

        if (obj instanceof KeyPair == false) return false;
        KeyPair other = (KeyPair)obj;

        if (other.getKeyName() == null ^ this.getKeyName() == null) return false;
        if (other.getKeyName() != null && other.getKeyName().equals(this.getKeyName()) == false) return false;
        if (other.getKeyFingerprint() == null ^ this.getKeyFingerprint() == null) return false;
        if (other.getKeyFingerprint() != null && other.getKeyFingerprint().equals(this.getKeyFingerprint()) == false) return false;
        if (other.getKeyMaterial() == null ^ this.getKeyMaterial() == null) return false;
        if (other.getKeyMaterial() != null && other.getKeyMaterial().equals(this.getKeyMaterial()) == false) return false;
        return true;
    }

}


text:
<?php

namespace BD\pdf\elements;

use BD\pdf\Document;
use BD\pdf\exceptions\InvalidConfigException;

class Page implements Render
{
    /**
     * @var Document
     */
    protected $context;
    /**
     * @var array
     */
    protected $sections = [];

    /**
     * @var Section[]
     */
    private $_sections = [];
    /**
     * @var Tag[]
     */
    private $_tags = [];
    /**
     * @var int
     */
    private $_page;

    /**
     * Page constructor.
     *
     * @param Document $context
     * @param array $sections
     */
    public function __construct(Document $context, $sections = [])
    {
        $this->context = $context;
        $this->sections = $sections;
        $this->_page = $this->context->pdf->newPage();
        $this->buildSections();
    }

    /**
     * @return int
     */
    public function getPage()
    {
        return $this->_page;
    }

    /**
     * @throws InvalidConfigException
     */
    public function buildSections()
    {
        $data = $this->context->data;
        foreach ($this->sections as $section) {
            $section = array_merge(
                [
                    'container' => [],
                    'type' => 'once',
                ],
                (array) $section
            );

            if (!isset($section['section'])) {
                throw new InvalidConfigException(sprintf('$section[\'%s\'] must be set.'), 'section');
            }

            if ($section['type'] == 'loop') {
                if (!isset($section['dataIdx'])) {
                    throw new InvalidConfigException(sprintf('$section[\'%s\'] must be set. because it is an loop section.'), 'dataIdx');
                }

                $items = isset($data[$section['dataIdx']]) ? $data[$section['dataIdx']] : [];
                $container = new Area($section['container']);
                $section['container'] = clone $container;
                foreach ($items as $item) {
                    $tmp = new Section($this->context, $this, $section, $item);
                    $container->y += $tmp->getArea()->h;
                    $section['container'] = clone $container;
                }
            } else {
                if (isset($section['dataIdx'])) {
                    $data = isset($data[$section['dataIdx']]) ? $data[$section['dataIdx']] : [];
                }
                new Section($this->context, $this, $section, $data);
            }
        }
    }

    /**
     * Add tag to the tag stacks of this page.
     *
     * @param Tag $tag
     */
    public function addTag(Tag $tag)
    {
        $this->_tags[] = $tag;
    }

    /**
     * Add section to the section stacks of this page.
     *
     * @param Section $section
     */
    public function addSection(Section $section)
    {
        $this->_sections[] = $section;
    }

    /**
     * @inheritdoc
     */
    public function render()
    {
        $this->context->pdf->setCurrentPage($this->_page);

        foreach ($this->_sections as $section) {
            $section->render();
        }

        foreach ($this->_tags as $tag) {
            $tag->render();
        }
    }
}


text:
using System;

namespace Turtle
{
    public abstract class RetryStrategyBase
    {
        internal TimeSpan NextRetryDelay(IRetryContext context)
        {
            return GetRetryDelay(context);
        }

        protected abstract TimeSpan GetRetryDelay(IRetryContext context);
    }
}