text:
#ifndef lint
static char *svnid = "$Id: mpiP-hash.c 457 2010-03-10 20:58:43Z chcham $";
#endif

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>

#include "mpiP-hash.h"

#define Abort(str) {printf("HASH: ABORTING (%s:%d): %s\n",__FILE__,__LINE__,str); exit(-1);}

h_t *
h_open (int size, h_HashFunct hf, h_Comparator hc)
{
  h_t *ht;
  ht = (h_t *) malloc (sizeof (h_t));
  if (ht == NULL)
    Abort ("malloc error");
  if (size < 2)
    Abort ("size too small for hash table");
  ht->size = size;
  ht->count = 0;
  if (hf == NULL)
    Abort ("hash key function not defined");
  ht->hf = hf;
  if (hc == NULL)
    Abort ("hash comparator function not defined");
  ht->hc = hc;
  ht->table = (h_entry_t **) malloc (sizeof (h_entry_t *) * size);
  if (ht->table == NULL)
    Abort ("malloc error");
  bzero (ht->table, sizeof (h_entry_t *) * size);
  return ht;
}

void
h_close (h_t * ht)
{
  if (ht == NULL)
    Abort ("hash table uninitialized");
#if 0
  if (ht->count > 0)
    printf ("Hash table not empty (%d elements) on h_close\n", ht->count);
#endif
  free (ht->table);
  free (ht);
}

int
h_count (h_t * ht)
{
  if (ht == NULL)
    Abort ("hash table uninitialized");
  return ht->count;
}

int
h_insert (h_t * ht, void *ptr)
{
  unsigned tableIndex;
  h_entry_t *het = NULL;
  h_entry_t *het_index = NULL;
  if (ht == NULL)
    Abort ("hash table uninitialized");
  het = (h_entry_t *) malloc (sizeof (h_entry_t));
  if (het == NULL)
    Abort ("hash table entry malloc error");
  if (ptr == NULL)
    Abort ("h_insert: ptr == NULL");
  het->ptr = ptr;
  het->next = NULL;
  tableIndex = (ht->hf (ptr));
  tableIndex %= (ht->size);
  if (ht->table[tableIndex] != NULL)
    {
      /* search list for similar key, if not, append it to list */
      /* OPTIMIZATION: remove this and let users deal with it :) */
      for (het_index = ht->table[tableIndex];
	   het_index != NULL; het_index = het_index->next)
	{
	  if (ht->hc (het_index->ptr, ptr) == 0)
	    {
	      printf
		("hash: warning: tried to insert identical entry again\n");
	      return 1;
	    }
	}
      het->next = ht->table[tableIndex];
      ht->table[tableIndex] = het;
    }
  else
    {
      ht->table[tableIndex] = het;
    }
  ht->count++;
  return 0;
}

void *
h_search (h_t * ht, void *key, void **ptr)
{
  unsigned tableIndex;
  h_entry_t *het_index = NULL;
  if (ht == NULL)
    Abort ("hash table uninitialized");
  if (key == NULL)
    Abort ("h_search: key == NULL");
  if (ptr == NULL)
    Abort ("h_search: ptr == NULL");
  *ptr = NULL;
  tableIndex = (ht->hf (key));
  tableIndex %= (ht->size);
  if (ht->table[tableIndex] != NULL)
    {
      /* search list for similar key  */
      for (het_index = ht->table[tableIndex];
	   het_index != NULL; het_index = het_index->next)
	{
	  if (ht->hc (het_index->ptr, key) == 0)
	    {
	      *ptr = het_index->ptr;
	      return *ptr;
	    }
	}
    }
  return NULL;
}

void *
h_delete (h_t * ht, void *key, void **ptr)
{
  unsigned tableIndex;
  h_entry_t *het_index = NULL;
  h_entry_t **next_addr = NULL;
  if (ht == NULL)
    Abort ("hash table uninitialized");
  if (ptr == NULL)
    Abort ("h_insert: ptr == NULL");
  if (key == NULL)
    Abort ("h_insert: key == NULL");
  *ptr = NULL;
  tableIndex = (ht->hf (key));
  tableIndex %= (ht->size);
  if (ht->table[tableIndex] != NULL)
    {
      /* search list for similar key  */
      for (het_index = ht->table[tableIndex],
	   next_addr = &(ht->table[tableIndex]);
	   het_index != NULL; het_index = het_index->next)
	{
	  if (ht->hc (het_index->ptr, key) == 0)
	    {
	      /* match */
	      *ptr = het_index->ptr;
	      *next_addr = het_index->next;
	      free (het_index);
	      ht->count--;
	      return *ptr;
	    }

	  next_addr = &(het_index->next);
	}
    }
  return NULL;
}

int
h_gather_data (h_t * ht, int *ac, void ***ptr)
{
  int i;
  h_entry_t *het_index = NULL;
  if (ht == NULL)
    Abort ("hash table uninitialized");
  if (ptr == NULL)
    Abort ("h_insert: ptr == NULL");

  *ac = 0;
  *ptr = (void **) malloc (sizeof (void *) * ht->count);
  for (i = 0; i < ht->size; i++)
    {
      if (ht->table[i] != NULL)
	{
	  for (het_index = ht->table[i];
	       het_index != NULL; het_index = het_index->next)
	    {
	      (*ptr)[*ac] = het_index->ptr;
	      (*ac)++;
	    }
	}
    }
  return *ac;
}

#define TESTING 0
#if TESTING

typedef struct _SampleRecord_t
{
  int id;
  int size;
  int order;
}
SampleRecord_t;

int
computeKey (void *p)
{
  SampleRecord_t *srp = (SampleRecord_t *) p;
  return 37941685 ^ srp->id ^ (srp->size << 7) ^ (srp->order << 11);
}

int
compareRecs (void *p1, void *p2)
{
  SampleRecord_t *sr1 = (SampleRecord_t *) p1;
  SampleRecord_t *sr2 = (SampleRecord_t *) p2;

#define express(field) {if(sr1->field < sr2->field) return -1; if(sr1->field > sr2->field) return 1;}
  express (id);
  express (size);
  express (order);
#undef express
  return 0;
}

main ()
{
  h_t *ht;
  SampleRecord_t sr[20];
  int i;
  srand (0);
  for (i = 0; i < 20; i++)
    {
      sr[i].id = rand ();
      sr[i].size = i;
      sr[i].order = i * 10;
    }
  ht = h_open (4, computeKey, compareRecs);
  for (i = 0; i < 20; i++)	/* insert some elements */
    {
      if (NULL != h_insert (ht, &sr[i]))
	{
	  printf ("%5d: inserted %d\n", i, sr[i].id);
	}
    }
  printf ("-----\n");
  {
    int dc;
    SampleRecord_t **dv;
    h_gather_data (ht, &dc, (void ***) &dv);	/* gather elements and print */
    for (i = 0; i < dc; i++)
      {
	printf ("%5d: %d %d %d\n", i, dv[i]->id, dv[i]->size, dv[i]->order);
      }
    free (dv);			/* remember to release return vector */
  }
  printf ("-----\n");
  for (i = 0; i < 10; i++)	/* delete half elements */
    {
      SampleRecord_t *d;
      if (NULL != h_delete (ht, &sr[i], (void **) &d))
	{
	  printf ("%5d: deleted %d\n", i, sr[i].id);
	}
    }

  printf ("-----\n");
  {
    int dc;
    SampleRecord_t **dv;
    h_gather_data (ht, &dc, (void ***) &dv);	/* gather elements and print */
    for (i = 0; i < dc; i++)
      {
	printf ("%5d: %d %d %d\n", i, dv[i]->id, dv[i]->size, dv[i]->order);
      }
    free (dv);			/* remember to release return vector */
  }

  printf ("-----\n");
  for (i = 10; i < 20; i++)	/* delete half elements */
    {
      SampleRecord_t *d;
      if (NULL != h_delete (ht, &sr[i], (void **) &d))
	{
	  printf ("%5d: deleted %d\n", i, sr[i].id);
	}
    }

  h_close (ht);
}

#endif

/*

<license>

Copyright (c) 2006, The Regents of the University of California.
Produced at the Lawrence Livermore National Laboratory
Written by Jeffery Vetter and Christopher Chambreau.
UCRL-CODE-223450.
All rights reserved.

This file is part of mpiP.  For details, see http://mpip.sourceforge.net/.

Redistribution and use 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 disclaimer below.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the disclaimer (as noted below) in
the documentation and/or other materials provided with the
distribution.

* Neither the name of the UC/LLNL nor the names of its 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 REGENTS OF
THE UNIVERSITY OF CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR
CONTRIBUTORS 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.

Additional BSD Notice

1. This notice is required to be provided under our contract with the
U.S. Department of Energy (DOE).  This work was produced at the
University of California, Lawrence Livermore National Laboratory under
Contract No. W-7405-ENG-48 with the DOE.

2. Neither the United States Government nor the University of
California nor any of their employees, makes any warranty, express or
implied, or assumes any liability or responsibility for the accuracy,
completeness, or usefulness of any information, apparatus, product, or
process disclosed, or represents that its use would not infringe
privately-owned rights.

3.  Also, reference herein to any specific commercial products,
process, or services by trade name, trademark, manufacturer or
otherwise does not necessarily constitute or imply its endorsement,
recommendation, or favoring by the United States Government or the
University of California.  The views and opinions of authors expressed
herein do not necessarily state or reflect those of the United States
Government or the University of California, and shall not be used for
advertising or product endorsement purposes.

</license>

*/

/* eof */


text:
namespace TraktApiSharp.Tests.Objects.Basic.Json.Writer
{
    using FluentAssertions;
    using Newtonsoft.Json;
    using System;
    using System.IO;
    using System.Threading.Tasks;
    using Traits;
    using TraktApiSharp.Objects.Basic;
    using TraktApiSharp.Objects.Basic.Json.Writer;
    using Xunit;

    [Category("Objects.Basic.JsonWriter")]
    public partial class NetworkObjectJsonWriter_Tests
    {
        [Fact]
        public void Test_NetworkObjectJsonWriter_WriteObject_JsonWriter_Exceptions()
        {
            var traktJsonWriter = new NetworkObjectJsonWriter();
            ITraktNetwork traktNetwork = new TraktNetwork();
            Func<Task> action = () => traktJsonWriter.WriteObjectAsync(default(JsonTextWriter), traktNetwork);
            action.Should().Throw<ArgumentNullException>();
        }

        [Fact]
        public async Task Test_NetworkObjectJsonWriter_WriteObject_JsonWriter_Complete()
        {
            ITraktNetwork traktNetwork = new TraktNetwork
            {
                Network = "network"
            };

            using (var stringWriter = new StringWriter())
            using (var jsonWriter = new JsonTextWriter(stringWriter))
            {
                var traktJsonWriter = new NetworkObjectJsonWriter();
                await traktJsonWriter.WriteObjectAsync(jsonWriter, traktNetwork);
                stringWriter.ToString().Should().Be(@"{""network"":""network""}");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * My own me-page to start with.
 */
include("config.php");

// Get small bits and pieces from various views.

$asfoByline  = file_get_contents(__DIR__."/incl/byline.html");

// Create the data array which is to be used in the template file.
$data['title'] = "Min me-sida med HTML5Boilerplate";
$data['meta_description'] = "Min egna me-sida, skapad för kursen phpmvc med HTML5Boilerplate.";
$data['main'] = <<<EOD

Åsa Forss

Jag heter Åsa och jag tycker att det är spännande och lärorikt att läsa kurspaketet.
    Våren 2011 tog jag en kandidatexamen i Data- och systemvetenskap på
    Stockholms universitet. Det jag fastnade mest för där var databaser och programmering.
    Människa- datorinteraktion var också kul.
    Sen jag gick ut har jag fått mitt tredje barn, varit föräldraledig och jobbat lite deltid.
    Nu vill jag lära mig webbutveckling för att kunna hitta något roligt jobb till våren.
    Jag har erfarenhet av C# och ASP.NET och skulle verkligen vilja lära mig de tekniker som
    gås igenom i paketet så att jag kan arbeta bredare inom webbutveckling.

    Jag bor i Gustavsberg och på fritiden springer jag bland annat. I somras spran jag tjejmilen
    för första gången  och det var riktigt kul! Jag har redan anmält mig till tjejmilen nästa år.

EOD;

// Hand over to the template engine.
include(__DIR__."/theme/template.php");


text:
package com.nanovash.wikishort;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedHashMap;

public class UIWindow extends JFrame {

	JPanel contentPane = new JPanel(),
			searchBar = new JPanel(),
			buttons = new JPanel();
	JTextField field = new JTextField();
	JScrollPane pane = new JScrollPane();
	JTextArea data = new JTextArea();
	JList<String> list = new JList<>();
	LinkedHashMap<String, String> links = new LinkedHashMap<>();

	public UIWindow() {
		setTitle("WikiShort");
		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setBounds(100, 100, 450, 300);
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		contentPane.setBackground(Color.WHITE);
		setContentPane(contentPane);

		contentPane.add(searchBar, BorderLayout.NORTH);
		field.setColumns(10);
		searchBar.setLayout(new BorderLayout(0, 0));
		searchBar.add(field, BorderLayout.CENTER);
		searchBar.add(buttons, BorderLayout.WEST);
		buttons.setLayout(new GridLayout(1, 2));

		final JButton search = new JButton("Search");
		search.setFocusPainted(false);
		search.addActionListener(e -> {
			CustomThread.t.search = WikiShort.window.field.getText().trim().toLowerCase();
			wakeThread();
		});
		contentPane.add(search, BorderLayout.SOUTH);

		data.setEditable(false);
		data.setLineWrap(true);
		data.setWrapStyleWord(true);
		contentPane.add(pane, BorderLayout.CENTER);
		pane.setViewportView(data);

		JButton left = createButton("\u21E6");
		JButton right = createButton("\u21E8");
		left.addActionListener(e -> {
			CustomThread.t.hm.goBack();
			wakeThread();
		});
		right.addActionListener(e -> {
			CustomThread.t.hm.goForward();
			wakeThread();
		});

		list.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2 && list.getSelectedIndex() != 0) {
					field.setText(CustomThread.t.search = links.get(list.getSelectedValue()));
					wakeThread();
				}
			}
		});

		field.addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				if (e.getKeyCode() == KeyEvent.VK_ENTER)
					search.doClick();
			}
		});
	}

	public JButton createButton(String s) {
		JButton button = new JButton(s);
		button.setPreferredSize(new Dimension(50, 0));
		button.setFont(button.getFont().deriveFont(15f));
		button.setFocusPainted(false);
		buttons.add(button);
		return button;
	}

	public void wakeThread() {
		synchronized (CustomThread.t) {
			CustomThread.t.notify();
		}
	}
}


text: from tpe_parking.tpe_parking_lot import ParkingLotInfoProvider


text:
package io.joynr.messaging.bounceproxy.controller;

import static org.junit.Assert.assertEquals;
import io.joynr.messaging.bounceproxy.controller.directory.BounceProxyDirectory;
import io.joynr.messaging.bounceproxy.controller.directory.ChannelDirectory;
import io.joynr.messaging.bounceproxy.controller.exception.JoynrProtocolException;
import io.joynr.messaging.bounceproxy.controller.strategy.ChannelAssignmentStrategy;
import io.joynr.messaging.info.Channel;
import io.joynr.messaging.info.ControlledBounceProxyInformation;

import java.net.URI;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

@RunWith(MockitoJUnitRunner.class)
public class ChannelServiceImplTest {

    private ChannelServiceImpl channelService;

    @Mock
    ChannelDirectory channelDirectoryMock;

    @Mock
    BounceProxyDirectory bpDirectoryMock;

    @Mock
    ChannelAssignmentStrategy channelAssignmentStrategyMock;

    @Mock
    RemoteBounceProxyFacade bpMock;

    @Before
    public void setUp() {

        Injector injector = Guice.createInjector(new AbstractModule() {

            @Override
            protected void configure() {
                bind(ChannelDirectory.class).toInstance(channelDirectoryMock);
                bind(ChannelAssignmentStrategy.class).toInstance(channelAssignmentStrategyMock);
                bind(BounceProxyDirectory.class).toInstance(bpDirectoryMock);
                bind(RemoteBounceProxyFacade.class).toInstance(bpMock);
            }

        });

        channelService = injector.getInstance(ChannelServiceImpl.class);
    }

    @Test
    public void testCreateChannel() throws JoynrProtocolException {

        ControlledBounceProxyInformation bpInfo = new ControlledBounceProxyInformation("X.Y",
                                                                                URI.create("http://bpX.de"));
        Mockito.when(channelAssignmentStrategyMock.calculateBounceProxy("channel-123")).thenReturn(bpInfo);
        Mockito.when(bpMock.createChannel(bpInfo, "channel-123", "trackingId-xyz"))
               .thenReturn(URI.create("http://bpX.de/channels/channel-123"));

        Channel channel = channelService.createChannel("channel-123", "trackingId-xyz");

        assertEquals("channel-123", channel.getChannelId());
        assertEquals("X.Y", channel.getBounceProxy().getId());
        assertEquals("http://bpX.de", channel.getBounceProxy().getLocation().toString());
        assertEquals("http://bpX.de/channels/channel-123", channel.getLocation().toString());
        Mockito.verify(channelDirectoryMock, Mockito.times(1)).addChannel(channel);
        Mockito.verify(bpDirectoryMock).updateChannelAssignment("channel-123", bpInfo);
    }

}


text:
<?php defined('BLUDIT') or die('Bludit CMS.');

class Pages extends dbJSON {

	protected $parentKeyList = array();
	protected $dbFields = array(
		'title'=>'',
		'description'=>'',
		'username'=>'',
		'tags'=>array(),
		'type'=>'published', // published, static, draft, sticky, scheduled
		'date'=>'',
		'dateModified'=>'',
		'position'=>0,
		'coverImage'=>'',
		'category'=>'',
		'md5file'=>'',
		'uuid'=>'',
		'allowComments'=>true,
		'template'=>'',
		'noindex'=>false,
		'nofollow'=>false,
		'noarchive'=>false,
		'custom'=>array()
	);

	function __construct()
	{
		parent::__construct(DB_PAGES);
	}

	public function getDefaultFields()
	{
		return $this->dbFields;
	}

	// Return an array with the database for a page, FALSE otherwise
	public function getPageDB($key)
	{
		if ($this->exists($key)) {
			return $this->db[$key];
		}

		return false;
	}

	// Return TRUE if the page exists, FALSE otherwise
	public function exists($key)
	{
		return isset( $this->db[$key] );
	}

	// Create a new page
	// This function returns the key of the new page
	public function add($args)
	{
		$row = array();

		// Predefined values
		foreach ($this->dbFields as $field=>$value) {
			if ($field=='tags') {
				$tags = '';
				if (isset($args['tags'])) {
					$tags = $args['tags'];
				}
				$finalValue = $this->generateTags($tags);
			} elseif (isset($args[$field])) {
				// Sanitize if will be stored on database
				$finalValue = Sanitize::html($args[$field]);
			} else {
				// Default value for the field if not defined
				$finalValue = $value;
			}
			settype($finalValue, gettype($value));
			$row[$field] = $finalValue;
		}

		// Content
		// This variable is not belong to the database so is not defined in $row
		$contentRaw = (empty($args['content'])?'':$args['content']);

		// Parent
		// This variable is not belong to the database so is not defined in $row
		$parent = (empty($args['parent'])?'':$args['parent']);

		// Slug from the title or the content
		// This variable is not belong to the database so is not defined in $row
		if (empty($args['slug'])) {
			if (!empty($row['title'])) {
				$slug = $this->generateSlug($row['title']);
			} else {
				$slug = $this->generateSlug($contentRaw);
			}
		} else {
			$slug = $args['slug'];
		}

		// Generate key
		// This variable is not belong to the database so is not defined in $row
		$key = $this->generateKey($slug, $parent);

		// Generate UUID
		if (empty($row['uuid'])) {
			$row['uuid'] = $this->generateUUID();
		}

		// Validate date
		if (!Valid::date($row['date'], DB_DATE_FORMAT)) {
			$row['date'] = Date::current(DB_DATE_FORMAT);
		}

		// Schedule page
		if (($row['date']>Date::current(DB_DATE_FORMAT)) && ($row['type']=='published')) {
			$row['type'] = 'scheduled';
		}

		// Create the directory
		if (Filesystem::mkdir(PATH_PAGES.$key, true) === false) {
			Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to create the directory ['.PATH_PAGES.$key.']',LOG_TYPE_ERROR);
			return false;
		}

		// Create the index.txt and save the file
		if (file_put_contents(PATH_PAGES.$key.DS.FILENAME, $contentRaw) === false) {
			Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to create the content in the file ['.FILENAME.']',LOG_TYPE_ERROR);
			return false;
		}

		// Checksum MD5
		$row['md5file'] = md5_file(PATH_PAGES.$key.DS.FILENAME);

		// Insert in database
		$this->db[$key] = $row;

		// Sort database
		$this->sortBy();

		// Save database
		$this->save();

		return $key;
	}

	// Edit a page
	// This function do not edit the current row from the table -
	// - instead of that the function creates a new row and is completed by the current -
	// - values of the page and then the old row is deleted and the new row is inserted.
	public function edit($args)
	{
		// This is the new row for the table and is going to replace the old row
		$row = array();

		// Current key
		// This variable is not belong to the database so is not defined in $row
		$key = $args['key'];

		// Check values from the arguments ($args)
		// If some field is missing the current value is taken
		foreach ($this->dbFields as $field=>$value) {
			if ( ($field=='tags') && isset($args['tags'])) {
				$finalValue = $this->generateTags($args['tags']);
			} elseif (isset($args[$field])) {
				// Sanitize if will be stored on database
				$finalValue = Sanitize::html($args[$field]);
			} else {
				// Default value from the current row
				$finalValue = $this->db[$key][$field];
			}
			settype($finalValue, gettype($value));
			$row[$field] = $finalValue;
		}

		// Parent
		// This variable is not belong to the database so is not defined in $row
		$parent = (empty($args['parent'])?'':$args['parent']);

		// Slug
		// If the user change the slug the page key changes
		// If the user send an empty slug the page key doesn't change
		// This variable is not belong to the database so is not defined in $row
		if (empty($args['slug'])) {
			$explode = explode('/', $key);
			$slug = end($explode);
		} else {
			$slug = $args['slug'];
		}

		// New key
		// The key of the page can change if the user change the slug or the parent, -
		// - if the user doesn't change the slug or the parent the key is going to be the same -
		// - as the current key.
		// This variable is not belong to the database so is not defined in $row
		$newKey = $this->generateKey($slug, $parent, false, $key);

		// If the page is draft then the created date is the current
		if ($row['type']=='draft') {
			$row['date'] = Date::current(DB_DATE_FORMAT);
		} elseif (!Valid::date($row['date'], DB_DATE_FORMAT)) {
			// if the date in the arguments is not valid, take the value from the old row
			$row['date'] = $this->db[$key]['date'];
		}

		// Modified date
		$row['dateModified'] = Date::current(DB_DATE_FORMAT);

		// Schedule page
		if (($row['date']>Date::current(DB_DATE_FORMAT)) && ($row['type']=='published')) {
			$row['type'] = 'scheduled';
		}

		// Move the directory from old key to new key only if the keys are different
		if ($newKey!==$key) {
			if (Filesystem::mv(PATH_PAGES.$key, PATH_PAGES.$newKey) === false) {
				Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to move the directory to '.PATH_PAGES.$newKey);
				return false;
			}
		}

		// If the content was passed via arguments replace the content
		if (isset($args['content'])) {
			// Make the index.txt and save the file.
			if (file_put_contents(PATH_PAGES.$newKey.DS.FILENAME, $args['content'])===false) {
				Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to put the content in the file '.FILENAME);
				return false;
			}
		}

		// Remove the old row
		unset($this->db[$key]);

		// Reindex Orphan Children
		$this->reindexChildren($key, $newKey);

		// Checksum MD5
		$row['md5file'] = md5_file(PATH_PAGES.$newKey.DS.FILENAME);

		// Insert in database the new row
		$this->db[$newKey] = $row;

		// Sort database
		$this->sortBy();

		// Save database
		$this->save();

		return $newKey;
	}

	// This function reindex the orphan children with the new parent key
	// If a page has subpages and the page change his key is necesarry check the children key
	public function reindexChildren($oldParentKey, $newParentKey) {
		if ($oldParentKey==$newParentKey){
			return false;
		}
		$tmp = $this->db;
		foreach ($tmp as $key=>$fields) {
			if (Text::startsWith($key, $oldParentKey.'/')) {
				$newKey = Text::replace($oldParentKey.'/', $newParentKey.'/', $key);
				$this->db[$newKey] = $this->db[$key];
				unset($this->db[$key]);
			}
		}
	}

	public function delete($key)
	{
		// This is need it, because if the key is empty the Filesystem::deleteRecursive is going to delete PATH_PAGES
		if (empty($key)) {
			return false;
		}

		// Page doesn't exist in database
		if (!$this->exists($key)) {
			Log::set(__METHOD__.LOG_SEP.'The page does not exist. Key: '.$key);
		}

		// Delete directory and files
		if (Filesystem::deleteRecursive(PATH_PAGES.$key) === false) {
			Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to delete the directory '.PATH_PAGES.$key);
		}

		// Delete page images directory; The function already check if exists the directory
		Filesystem::deleteRecursive(PATH_UPLOADS_PAGES.$this->db[$key]['uuid']);

		// Remove from database
		unset($this->db[$key]);

		// Save the database.
		if ($this->save()===false) {
			Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
		}

		return true;
	}

	// Delete all pages from a user
	public function deletePagesByUser($args)
	{
		$username = $args['username'];

		foreach ($this->db as $key=>$fields) {
			if ($fields['username']===$username) {
				$this->delete($key);
			}
		}

		return true;
	}

	// Link all pages to a new user
	public function transferPages($args)
	{
		$oldUsername = $args['oldUsername'];
		$newUsername = isset($args['newUsername']) ? $args['newUsername'] : 'admin';

		foreach ($this->db as $key=>$fields) {
			if ($fields['username']===$oldUsername) {
				$this->db[$key]['username'] = $newUsername;
			}
		}

		return $this->save();
	}

	// Set field = value
	public function setField($key, $field, $value)
	{
		if ($this->exists($key)) {
			settype($value, gettype($this->dbFields[$field]));
			$this->db[$key][$field] = $value;
			return $this->save();
		}
		return false;
	}

	// Returns a database with all pages
	// $onlyKeys = true; Returns only the pages keys
	// $onlyKeys = false; Returns part of the database, I do not recommend use this
	public function getDB($onlyKeys=true)
	{
		$tmp = $this->db;
		if ($onlyKeys) {
			return array_keys($tmp);
		}
		return $tmp;
	}

	// Returns a database with published pages
	// $onlyKeys = true; Returns only the pages keys
	// $onlyKeys = false; Returns part of the database, I do not recommend use this
	public function getPublishedDB($onlyKeys=true)
	{
		$tmp = $this->db;
		foreach ($tmp as $key=>$fields) {
			if ($fields['type']!='published') {
				unset($tmp[$key]);
			}
		}
		if ($onlyKeys) {
			return array_keys($tmp);
		}
		return $tmp;
	}

	// Returns an array with a list of keys/database of static pages
	// By default the static pages are sort by position
	public function getStaticDB($onlyKeys=true)
	{
		$tmp = $this->db;
		foreach ($tmp as $key=>$fields) {
			if ($fields['type']!='static') {
				unset($tmp[$key]);
			}
		}
		uasort($tmp, array($this, 'sortByPositionLowToHigh'));
		if ($onlyKeys) {
			return array_keys($tmp);
		}
		return $tmp;
	}

	// Returns an array with a list of keys/database of draft pages
	public function getDraftDB($onlyKeys=true)
	{
		$tmp = $this->db;
		foreach ($tmp as $key=>$fields) {
			if($fields['type']!='draft') {
				unset($tmp[$key]);
			}
		}
		if ($onlyKeys) {
			return array_keys($tmp);
		}
		return $tmp;
	}

	// Returns an array with a list of keys/database of scheduled pages
	public function getScheduledDB($onlyKeys=true)
	{
		$tmp = $this->db;
		foreach ($tmp as $key=>$fields) {
			if($fields['type']!='scheduled') {
				unset($tmp[$key]);
			}
		}
		if ($onlyKeys) {
			return array_keys($tmp);
		}
		return $tmp;
	}

	// Returns an array with a list of keys of sticky pages
	public function getStickyDB($onlyKeys=true)
	{
		$tmp = $this->db;
		foreach ($tmp as $key=>$fields) {
			if($fields['type']!='sticky') {
				unset($tmp[$key]);
			}
		}
		if ($onlyKeys) {
			return array_keys($tmp);
		}
		return $tmp;
	}

	// Returns the next number of the bigger position
	public function nextPositionNumber()
	{
		$tmp = 1;
		foreach ($this->db as $key=>$fields) {
			if ($fields['position']>$tmp) {
				$tmp = $fields['position'];
			}
		}
		return ++$tmp;
	}

	// Returns the next page key of the current page key
	public function nextPageKey($currentKey)
	{
		if ($this->db[$currentKey]['type']=='published') {
			$keys = array_keys($this->db);
			$position = array_search($currentKey, $keys) - 1;
			if (isset($keys[$position])) {
				$nextKey = $keys[$position];
				if ($this->db[$nextKey]['type']=='published') {
					return $nextKey;
				}
			}
		}
		return false;
	}

	// Returns the previous page key of the current page key
	public function previousPageKey($currentKey)
	{
		if ($this->db[$currentKey]['type']=='published') {
			$keys = array_keys($this->db);
			$position = array_search($currentKey, $keys) + 1;
			if (isset($keys[$position])) {
				$prevKey = $keys[$position];
				if ($this->db[$prevKey]['type']=='published') {
					return $prevKey;
				}
			}
		}
		return false;
	}

	// Returns an array with a list of key of pages, FALSE if out of range
	// The database is sorted by date or by position
	// (int) $pageNumber, the page number
	// (int) $numberOfItems, amount of items to return, if -1 returns all the items
	// (boolean) $onlyPublished, TRUE to return only published pages
	public function getList($pageNumber, $numberOfItems, $published=true, $static=false, $sticky=false, $draft=false, $scheduled=false)
	{
		$list = array();
		foreach ($this->db as $key=>$fields) {
			if ($published && $fields['type']=='published') {
				array_push($list, $key);
			} elseif ($static && $fields['type']=='static') {
				array_push($list, $key);
			} elseif ($sticky && $fields['type']=='sticky') {
				array_push($list, $key);
			} elseif ($draft && $fields['type']=='draft') {
				array_push($list, $key);
			} elseif ($scheduled && $fields['type']=='scheduled') {
				array_push($list, $key);
			}
		}

		if ($numberOfItems==-1) {
			return $list;
		}

		// The first page number is 1, so the real is 0
		$realPageNumber = $pageNumber - 1;

		$total = count($list);
		$init = (int) $numberOfItems * $realPageNumber;
		$end  = (int) min( ($init + $numberOfItems - 1), $total );
		$outrange = $init<0 ? true : $init>$end;
		if (!$outrange) {
			return array_slice($list, $init, $numberOfItems, true);
		}

		return false;
	}

	// Returns the amount of pages
	// (boolean) $total, TRUE returns the total of pages
	// (boolean) $total, FALSE returns the total of published pages (without draft and scheduled)
	public function count($onlyPublished=true)
	{
		if ($onlyPublished) {
			$db = $this->getPublishedDB(false);
			return count($db);
		}

		return count($this->db);
	}

	// Returns an array with all parents pages key. A parent page is not a child
	public function getParents()
	{
		$db = $this->getPublishedDB();
		foreach ($db as $key=>$pageKey) {
			// if the key has slash then is a child
			if (Text::stringContains($pageKey, '/')) {
				unset($db[$key]);
			}
		}
		return $db;
	}

	public function getChildren($parentKey)
	{
		$tmp = $this->db;
		$list = array();
		foreach ($tmp as $key=>$fields) {
			if (Text::startsWith($key, $parentKey.'/')) {
				array_push($list, $key);
			}
		}
		return $list;
	}

	public function sortBy()
	{
		if (ORDER_BY=='date') {
			return $this->sortByDate(true);
		}
		return $this->sortByPosition(false);
	}

	// Sort pages by position
	public function sortByPosition($HighToLow=false)
	{
		if($HighToLow) {
			uasort($this->db, array($this, 'sortByPositionHighToLow'));
		} else {
			uasort($this->db, array($this, 'sortByPositionLowToHigh'));
		}
		return true;
	}

	private function sortByPositionLowToHigh($a, $b)
	{
		return $a['position']>$b['position'];
	}
	private function sortByPositionHighToLow($a, $b)
	{
		return $a['position']<$b['position'];
	}

	// Sort pages by date
	public function sortByDate($HighToLow=true)
	{
		if($HighToLow) {
			uasort($this->db, array($this, 'sortByDateHighToLow'));
		} else {
			uasort($this->db, array($this, 'sortByDateLowToHigh'));
		}
		return true;
	}

	private function sortByDateLowToHigh($a, $b)
	{
		return $a['date']>$b['date'];
	}
	private function sortByDateHighToLow($a, $b)
	{
		return $a['date']<$b['date'];
	}

	function generateUUID() {
		return md5( uniqid().time() );
	}

	// Returns the UUID of a page, by the page key
	function getUUID($key)
	{
		if ($this->exists($key)) {
			return $this->db[$key]['uuid'];
		}
		return false;
	}

	// Returns the page key by the uuid
	// if the UUID doesn't exits returns FALSE
	function getByUUID($uuid)
	{
		foreach ($this->db as $key=>$value) {
			if ($value['uuid']==$uuid) {
				return $key;
			}
		}
		return false;
	}

	// Returns string without HTML tags and truncated
	private function generateSlug($text, $truncateLength=60)
	{
		$tmpslug = Text::removeHTMLTags($text);
		$tmpslug = Text::removeLineBreaks($tmpslug);
		$tmpslug = Text::truncate($tmpslug, $truncateLength, '');
		return $tmpslug;
	}

	// Returns TRUE if there are new pages published, FALSE otherwise
	public function scheduler()
	{
		// Get current date
		$currentDate = Date::current(DB_DATE_FORMAT);
		$saveDatabase = false;

		// The database need to be sorted by date
		foreach($this->db as $pageKey=>$fields) {
			if($fields['type']=='scheduled') {
				if($fields['date']<=$currentDate) {
					$this->db[$pageKey]['type'] = 'published';
					$saveDatabase = true;
				}
			}
			elseif( ($fields['type']=='published') && (ORDER_BY=='date') ) {
				break;
			}
		}

		if($saveDatabase) {
			if( $this->save() === false ) {
				Log::set(__METHOD__.LOG_SEP.'Error occurred when trying to save the database file.');
				return false;
			}

			Log::set(__METHOD__.LOG_SEP.'New pages published from the scheduler.');
			return true;
		}

		return false;
	}

	// Generate a valid Key/Slug
	public function generateKey($text, $parent=false, $returnSlug=false, $oldKey='')
	{
		global $L;
		global $site;

		if (Text::isEmpty($text)) {
			$text = $L->g('empty');
		}

		if (Text::isEmpty($parent)) {
			$newKey = Text::cleanUrl($text);
		} else {
			$newKey = Text::cleanUrl($parent).'/'.Text::cleanUrl($text);
		}

		// cleanURL can return empty string
		if (Text::isEmpty($newKey)) {
			$newKey = $L->g('empty');
		}

		if ($newKey!==$oldKey) {
			// Verify if the key is already been used
			if (isset($this->db[$newKey])) {
				$i = 0;
				while (isset($this->db[$newKey.'-'.$i])) {
					$i++;
				}
				$newKey = $newKey.'-'.$i;
			}
		}

		if ($returnSlug) {
			$explode = explode('/', $newKey);
			if (isset($explode[1])) {
				return $explode[1];
			}
			return $explode[0];
		}

		return $newKey;
	}

	// Returns an Array, array('tagSlug'=>'tagName')
	// (string) $tags, tag list separated by comma.
	public function generateTags($tags)
	{
		$tmp = array();
		$tags = trim($tags);
		if (empty($tags)) {
			return $tmp;
		}

		$tags = explode(',', $tags);
		foreach ($tags as $tag) {
			$tag = trim($tag);
			$tagKey = Text::cleanUrl($tag);
			$tmp[$tagKey] = $tag;
		}
		return $tmp;
	}

	// Change all pages with the old category key to the new category key
	public function changeCategory($oldCategoryKey, $newCategoryKey)
	{
		foreach ($this->db as $key=>$value) {
			if ($value['category']===$oldCategoryKey) {
				$this->db[$key]['category'] = $newCategoryKey;
			}
		}
		return $this->save();
	}

}


text:
require 'spec_helper'

describe ActsAsStream::StreamActivity do

  before :each do
    @user = Factory :user
    @widget = Factory :widget
    @admin = Factory :admin
    @time = Time.now.to_i
    @valid_options = {:who => @user,
                      :action => "Tested StreamActivity!",
                      :time => Time.at(@time),
                      :object => @widget}
    @valid_json = "{\"time\":#{@time},\"who\":{\"user\":{\"id\":#{@user.id}}},\"action\":\"Tested StreamActivity!\",\"object\":{\"widget\":{\"id\":#{@widget.id}}}}"
  end

  describe "parse" do
    before :each do
      invalid_user_id = User.last.id + 1
      invalid_widget_id = Widget.last.id + 1
      user_id = @valid_options[:who].id
      widget_id = @valid_options[:object].id
      @bad_who = package(@valid_options).gsub("\"id\":#{user_id}", "\"id\":#{invalid_user_id}")
      @bad_object = package(@valid_options).gsub("\"id\":#{widget_id}", "\"id\":#{invalid_widget_id}")
    end
    it "should probably parse JSON to a hash with symbol keys" do
      hash = ActsAsStream.parse(package(@valid_options))
      @valid_options.keys.each{|k| hash[k].should == @valid_options[k]}
    end

    it "should return nil with a RecordNotFound exception" do
      hash = ActsAsStream.parse(@bad_who)
      hash.should be_nil
    end
    it "should return nil with a RecordNotFound exception" do
      hash = ActsAsStream.parse(@bad_object)
      hash.should be_nil
    end
  end

  describe "time" do
    it "should create a valid package with all valid options" do
      package(@valid_options).should == @valid_json
    end

    it "should create a valid package without a time" do
      options = @valid_options.dup
      options.delete(:time)
      #Making an assumption this won't block on time!
      time = Time.now.to_i

      json = "{\"time\":#{time},\"who\":{\"user\":{\"id\":#{@user.id}}},\"action\":\"Tested StreamActivity!\",\"object\":{\"widget\":{\"id\":#{@widget.id}}}}"
      package(options).should == json
    end

    it "should create a valid package with a Time object" do
      options = @valid_options.dup
      time = Time.now
      options[:time] = time
      #Making an assumption this won't block on time!
      json = "{\"time\":#{time.to_i},\"who\":{\"user\":{\"id\":#{@user.id}}},\"action\":\"Tested StreamActivity!\",\"object\":{\"widget\":{\"id\":#{@widget.id}}}}"
      decode(package(options)).should == decode(json)
    end
  end

  describe "stream_hash" do
    it "should correctly create a stream hash" do
      json = {:widget =>{ :id => @widget.id}}
      @widget.to_stream_hash.should == json
    end
    it "should correctly create a stream hash with a non-id attribute" do
      json = {:admin =>{ :id => @admin.id, :guid => @admin.guid}}
      @admin.to_stream_hash.should == json
    end

    it "should respond correctly with an object that does not" do
      class TestObject;end
      options = @valid_options.dup
      options[:object] = TestObject.new
      lambda {package(options)}.should raise_error
    end
  end

  describe ActsAsStream::StreamableObject do
    it "should create a package with the instance method" do
      options = @valid_options.dup
      time = Time.now.to_i
      options[:time] = time
      decode(@user.package(:action => "Tested StreamActivity!", :object => @widget)).should == decode(package(options))
    end
  end

  private

  def decode json
    ActiveSupport::JSON.decode(json)
  end
  def package(options={})
    ActsAsStream.package options
  end
end


text:
<?php

namespace Pace;

use Pace\Soap\Factory as SoapFactory;
use Illuminate\Support\ServiceProvider;

class PaceServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config/pace.php' => config_path('pace.php'),
        ]);
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(Client::class, function ($app) {
            $config = $app['config']['pace'];

            return new Client(
                new SoapFactory(),
                $config['host'],
                $config['login'],
                $config['password'],
                $config['scheme']
            );
        });
    }
}


text:
Deface::Override.new(:virtual_path => 'spree/admin/products/_form',
  :name => 'add_maker_to_admin_product',
  :insert_top => "[data-hook='admin_product_form_additional_fields']",
  :text => "
    <%= f.field_container :add_on_makers do %>
      <%= f.label :add_on_maker_ids, t('add_on.add_on_maker') %>
      <%= f.collection_select(:add_on_maker_ids, Spree::AddOnMaker.all, :id, :name, { :include_blank => Spree.t('match_choices.none') }, { :class => 'select2' }) %>
      <%= f.error_message_on :add_on_makers %>
    <% end %>
  ")


text:
set -e
URL="${1}"

if [ -z "${1}" ]; then
    echo "usage: $(basename ${0}) <url>"
    echo ""
    echo "examples:"
    echo "  - $(basename ${0}) http://test-images.fr-1.storage.online.net/scw-distrib-ubuntu-trusty.tar"
    echo "  - VOLUME_SIZE=50GB $(basename ${0}) http://test-images.fr-1.storage.online.net/scw-distrib-ubuntu-trusty.tar"
    exit 1
fi

NAME=$(basename "${URL}")
SNAPSHOT_NAME=${NAME%.*}-$(date +%Y-%m-%d_%H:%M)
IMAGE_NAME=${IMAGE_NAME:-$SNAPSHOT_NAME}
IMAGE_BOOTSCRIPT=${IMAGE_BOOTSCRIPT:stable}
SCW_COMMERCIAL_TYPE=${SCW_COMMERCIAL_TYPE:-VC1S}
VOLUME_SIZE=${VOLUME_SIZE:-50GB}
SCW_TARGET_ARCH=x86_64
if [ "$SCW_COMMERCIAL_TYPE" = "C1" ]; then
    SCW_TARGET_ARCH=arm
fi
KEY=$(cat ~/.ssh/id_rsa.pub | awk '{ print $1" "$2 }' | tr ' ' '_')

echo "[+] URL of the tarball: ${URL}"
echo "[+] Target name: ${NAME}"

echo "[+] Creating new server in rescue mode with a secondary volume..."
SERVER=$(SCW_TARGET_ARCH="$SCW_TARGET_ARCH" scw run --commercial-type="${SCW_COMMERCIAL_TYPE}" -d --env="AUTHORIZED_KEY=${KEY} boot=none INITRD_DROPBEAR=1" --name="image-writer-${NAME}" "${VOLUME_SIZE}")
echo "[+] Server created: ${SERVER}"

echo "[+] Booting..."
scw exec -w "${SERVER}" 'uname -a'
echo "[+] Server is booted"

if [ -n "${SCW_GATEWAY_HTTP_PROXY}" ]; then
    echo "[+] Configuring HTTP proxy"
    # scw exec "${SERVER}" "echo proxy=${SCW_GATEWAY_HTTP_PROY} >> .curlrc"
    (
        set +x
        scw exec "${SERVER}" "echo export http_proxy=${SCW_GATEWAY_HTTP_PROXY} > /proxy-env" >/dev/null 2>/dev/null || (echo "Failed to configure HTTP proxy"; exit 1) || exit 1
    )
fi

echo "[+] Formating and mounting disk..."
# FIXME: make disk dynamic between /dev/vda and /dev/nbd1
scw exec "${SERVER}" '/sbin/mkfs.ext4 /dev/vda && mkdir -p /mnt && mount /dev/vda /mnt'
echo "[+] /dev/nbd1 formatted in ext4 and mounted on /mnt"

echo "[+] Download tarball and write it to /mnt"
scw exec "${SERVER}" "touch /proxy-env; . /proxy-env; wget -qO - ${URL} | tar -C /mnt/ -xf - && sync"
echo "[+] Tarball extracted on disk"

echo "[+] Stopping the server"
scw stop "${SERVER}" >/dev/null
scw wait "${SERVER}"
echo "[+] Server stopped"

echo "[+] Creating a snapshot of disk 1"
SNAPSHOT=$(scw commit --volume=0 "${SERVER}" "${SNAPSHOT_NAME}")
echo "[+] Snapshot ${SNAPSHOT} created"

echo "[+] Creating an image based of the snapshot"
if [ -n "${IMAGE_ARCH}" ]; then
    IMAGE=$(scw tag --arch="${IMAGE_ARCH}" --bootscript="${IMAGE_BOOTSCRIPT}" "${SNAPSHOT}" "${IMAGE_NAME}")
else
    IMAGE=$(scw tag --bootscript="${IMAGE_BOOTSCRIPT}" "${SNAPSHOT}" "${IMAGE_NAME}")
fi
echo "[+] Image created: ${IMAGE}"

echo "[+] Deleting temporary server"
scw rm "${SERVER}" >/dev/null
echo "[+] Server deleted"


text:
package javarepl.console.commands;

import javarepl.Evaluator;
import javarepl.completion.CommandCompleter;
import javarepl.console.ConsoleLogger;

import static com.googlecode.totallylazy.predicates.Predicates.equalTo;

public final class QuitApplication extends Command {
    private static final String COMMAND = ":quit";
    private final Evaluator evaluator;
    private final ConsoleLogger logger;

    public QuitApplication(Evaluator evaluator, ConsoleLogger logger) {
        super(COMMAND + " - quit application", equalTo(COMMAND).or(equalTo(null)), new CommandCompleter(COMMAND));
        this.evaluator = evaluator;
        this.logger = logger;
    }

    public void execute(String expression) {
        logger.success("Terminating...");
        evaluator.clearOutputDirectory();
        System.exit(0);
    }
}


text:
package badger

import (
	"encoding/binary"
	"math/rand"
	"os"
	"path/filepath"
	"sort"
	"sync"
	"time"

	"golang.org/x/net/trace"

	"github.com/dgraph-io/badger/table"
	"github.com/dgraph-io/badger/y"
	"github.com/pkg/errors"
)

type levelsController struct {
	elog trace.EventLog

	// The following are initialized once and const.
	levels []*levelHandler
	clog   compactLog
	kv     *KV

	// Atomic.
	maxFileID    uint64 // Next ID to be used.
	maxCompactID uint64

	// For ending compactions.
	compactWorkersDone chan struct{}
	compactWorkersWg   sync.WaitGroup

	cstatus compactStatus
}

var (
	// This is for getting timings between stalls.
	lastUnstalled time.Time
)

func newLevelsController(kv *KV) (*levelsController, error) {
	y.AssertTrue(kv.opt.NumLevelZeroTablesStall > kv.opt.NumLevelZeroTables)
	s := &levelsController{
		kv:     kv,
		elog:   kv.elog,
		levels: make([]*levelHandler, kv.opt.MaxLevels),
	}
	s.cstatus.levels = make([]*levelCompactStatus, kv.opt.MaxLevels)

	for i := 0; i < kv.opt.MaxLevels; i++ {
		s.levels[i] = newLevelHandler(kv, i)
		if i == 0 {
			// Do nothing.
		} else if i == 1 {
			// Level 1 probably shouldn't be too much bigger than level 0.
			s.levels[i].maxTotalSize = kv.opt.LevelOneSize
		} else {
			s.levels[i].maxTotalSize = s.levels[i-1].maxTotalSize * int64(kv.opt.LevelSizeMultiplier)
		}
		s.cstatus.levels[i] = new(levelCompactStatus)
	}

	// Replay compact log. Check against files in directory.
	clogName := filepath.Join(kv.opt.Dir, "clog")
	_, err := os.Stat(clogName)
	if err == nil {
		kv.elog.Printf("Replaying compact log: %s\n", clogName)
		compactLogReplay(clogName, kv.opt.Dir, getIDMap(kv.opt.Dir))

		if err := os.Remove(clogName); err != nil { // Everything is ok. Clear compact log.
			return nil, errors.Wrapf(err, "Removing compaction log: %q", clogName)
		}
	}

	// Some files may be deleted. Let's reload.
	tables := make([][]*table.Table, kv.opt.MaxLevels)
	for fileID := range getIDMap(kv.opt.Dir) {
		fname := table.NewFilename(fileID, kv.opt.Dir)
		fd, err := y.OpenSyncedFile(fname, true)
		if err != nil {
			closeAllUnmodifiedTables(tables)
			return nil, errors.Wrapf(err, "Opening file: %q", fname)
		}

		t, err := table.OpenTable(fd, kv.opt.MapTablesTo)
		if err != nil {
			closeAllUnmodifiedTables(tables)
			return nil, errors.Wrapf(err, "Opening table: %q", fname)
		}

		// Check metadata for level information.
		tableMeta := t.Metadata()
		y.AssertTruef(len(tableMeta) == 2, "len(tableMeta). Expected=2. Actual=%d", len(tableMeta))

		level := int(binary.BigEndian.Uint16(tableMeta))
		y.AssertTruef(level < kv.opt.MaxLevels, "max(level). Expected=%d. Actual=%d",
			kv.opt.MaxLevels, level)
		tables[level] = append(tables[level], t)

		if fileID > s.maxFileID {
			s.maxFileID = fileID
		}
	}
	s.maxFileID++
	for i, tbls := range tables {
		s.levels[i].initTables(tbls)
	}

	// Make sure key ranges do not overlap etc.
	if err := s.validate(); err != nil {
		_ = s.cleanupLevels()
		return nil, errors.Wrap(err, "Level validation")
	}

	// Create new compact log.
	if err := s.clog.init(clogName); err != nil {
		_ = s.cleanupLevels()
		return nil, errors.Wrap(err, "Compaction Log")
	}

	// Sync directory (because we have at least removed/created compaction log files)
	if err := syncDir(kv.opt.Dir); err != nil {
		_ = s.close()
		return nil, errors.Wrap(err, "Directory entry for compaction log")
	}

	return s, nil
}

// Closes the tables, for cleanup in newLevelsController.  (We Close() instead of using DecrRef()
// because that would delete the underlying files.)  We ignore errors when closing the table, which
// is OK because we haven't modified the table.  (It's an LSM tree, but we do hypothetically modify
// the file with SetMetadata.)  (Even then, we open the files with O_DSYNC, so the only plausible
// error on Close() would have been from writing file metadata.)
func closeAllUnmodifiedTables(tables [][]*table.Table) {
	for _, tableSlice := range tables {
		for _, table := range tableSlice {
			_ = table.Close()
		}
	}
}

func (s *levelsController) cleanupLevels() error {
	var firstErr error
	for _, l := range s.levels {
		if err := l.close(); err != nil && firstErr == nil {
			firstErr = err
		}
	}
	return firstErr
}

func (s *levelsController) startCompact(lc *y.LevelCloser) {
	n := s.kv.opt.NumCompactors
	lc.AddRunning(int32(n - 1))
	for i := 0; i < n; i++ {
		go s.runWorker(lc)
	}
}

func (s *levelsController) runWorker(lc *y.LevelCloser) {
	defer lc.Done()
	if s.kv.opt.DoNotCompact {
		return
	}

	time.Sleep(time.Duration(rand.Int31n(1000)) * time.Millisecond)
	timeChan := time.Tick(time.Second)

	for {
		select {
		// Can add a done channel or other stuff.
		case <-timeChan:
			prios := s.pickCompactLevels()
			for _, p := range prios {
				if s.doCompact(p) {
					break
				}
			}
		case <-lc.HasBeenClosed():
			return
		}
	}
}

type compactionPriority struct {
	level int
	score float64
}

// pickCompactLevel determines which level to compact. Return -1 if not found.
// Based on: https://github.com/facebook/rocksdb/wiki/Leveled-Compaction
func (s *levelsController) pickCompactLevels() (prios []compactionPriority) {
	if !s.cstatus.overlapsWith(0, infRange) && // already being compacted.
		s.levels[0].numTables() >= s.kv.opt.NumLevelZeroTables {
		pri := compactionPriority{
			level: 0,
			score: float64(s.levels[0].numTables()) / float64(s.kv.opt.NumLevelZeroTables),
		}
		prios = append(prios, pri)
	}

	for i, l := range s.levels[1:] {
		// Don't consider those tables that are being compacted right now.
		delSize := s.cstatus.delSize(i + 1)

		if l.getTotalSize()-delSize >= l.maxTotalSize {
			pri := compactionPriority{
				level: i + 1,
				score: float64(l.getTotalSize()-delSize) / float64(l.maxTotalSize),
			}
			prios = append(prios, pri)
		}
	}
	sort.Slice(prios, func(i, j int) bool {
		return prios[i].score > prios[j].score
	})
	return prios
}

// compactBuildTables merge topTables and botTables to form a list of new tables.
func (s *levelsController) compactBuildTables(
	l int, cd compactDef, c *compaction) ([]*table.Table, func() error) {

	topTables := cd.top
	botTables := cd.bot

	// Create iterators across all the tables involved first.
	var iters []y.Iterator
	if l == 0 {
		iters = appendIteratorsReversed(iters, topTables, false)
	} else {
		y.AssertTrue(len(topTables) == 1)
		iters = []y.Iterator{topTables[0].NewIterator(false)}
	}

	// Next level has level>=1 and we can use ConcatIterator as key ranges do not overlap.
	iters = append(iters, table.NewConcatIterator(botTables, false))
	it := y.NewMergeIterator(iters, false)
	defer it.Close() // Important to close the iterator to do ref counting.

	it.Rewind()

	// Start generating new tables.
	newTables := make([]*table.Table, len(c.toInsert))
	che := make(chan error, len(c.toInsert))
	var i int
	newIDMin, newIDMax := c.toInsert[0], c.toInsert[len(c.toInsert)-1]
	newID := newIDMin
	for ; it.Valid(); i++ {
		y.AssertTruef(i < len(newTables), "Rewriting too many tables: %d %d", i, len(newTables))
		timeStart := time.Now()
		builder := table.NewTableBuilder()
		for ; it.Valid(); it.Next() {
			if builder.ReachedCapacity(s.kv.opt.MaxTableSize) {
				break
			}
			y.Check(builder.Add(it.Key(), it.Value()))
		}
		// It was true that it.Valid() at least once in the loop above, which means we
		// called Add() at least once, and builder is not Empty().
		y.AssertTrue(!builder.Empty())

		cd.elog.LazyPrintf("LOG Compact. Iteration to generate one table took: %v\n", time.Since(timeStart))

		y.AssertTruef(newID <= newIDMax, "%d %d", newID, newIDMax)
		go func(idx int, fileID uint64, builder *table.TableBuilder) {
			defer builder.Close()

			fd, err := y.OpenSyncedFile(table.NewFilename(fileID, s.kv.opt.Dir), true)
			if err != nil {
				che <- errors.Wrapf(err, "While opening new table: %d", fileID)
				return
			}

			// Encode the level number as table metadata.
			var levelNum [2]byte
			binary.BigEndian.PutUint16(levelNum[:], uint16(l+1))
			if _, err := fd.Write(builder.Finish(levelNum[:])); err != nil {
				che <- errors.Wrapf(err, "Unable to write to file: %d", fileID)
				return
			}

			newTables[idx], err = table.OpenTable(fd, s.kv.opt.MapTablesTo)
			// decrRef is added below.
			che <- errors.Wrapf(err, "Unable to open table: %q", fd.Name())

		}(i, newID, builder)
		newID++
	}

	// Wait for all table builders to finish.
	var firstErr error
	for x := 0; x < i; x++ {
		if err := <-che; err != nil && firstErr == nil {
			firstErr = err
		}
	}

	if firstErr == nil {
		// Ensure created files' directory entries are visible.  We don't mind the extra latency
		// from not doing this ASAP after all file creation has finished because this is a
		// background operation.
		firstErr = syncDir(s.kv.opt.Dir)
	}

	if firstErr != nil {
		// An error happened.  Delete all the newly created table files (by calling DecrRef
		// -- we're the only holders of a ref).
		for _, table := range newTables[:i] {
			if table != nil {
				_ = table.DecrRef()
			}
		}
		errorReturn := errors.Wrapf(firstErr, "While running compaction for: %+v", c)
		return nil, func() error { return errorReturn }
	}

	out := newTables[:i]
	return out, func() error {
		for _, t := range out {
			// replaceTables will increment reference.
			if err := t.DecrRef(); err != nil {
				return err
			}
		}
		return nil
	}
}

type compactDef struct {
	elog trace.Trace

	thisLevel *levelHandler
	nextLevel *levelHandler

	top []*table.Table
	bot []*table.Table

	thisRange keyRange
	nextRange keyRange

	thisSize int64
}

func (cd *compactDef) lockLevels() {
	cd.thisLevel.RLock()
	cd.nextLevel.RLock()
}

func (cd *compactDef) unlockLevels() {
	cd.nextLevel.RUnlock()
	cd.thisLevel.RUnlock()
}

func (s *levelsController) fillTablesL0(cd *compactDef) bool {
	cd.lockLevels()
	defer cd.unlockLevels()

	cd.top = make([]*table.Table, len(cd.thisLevel.tables))
	copy(cd.top, cd.thisLevel.tables)
	if len(cd.top) == 0 {
		return false
	}
	cd.thisRange = infRange

	kr := getKeyRange(cd.top)
	left, right := cd.nextLevel.overlappingTables(kr)
	cd.bot = make([]*table.Table, right-left)
	copy(cd.bot, cd.nextLevel.tables[left:right])

	if len(cd.bot) == 0 {
		cd.nextRange = kr
	} else {
		cd.nextRange = getKeyRange(cd.bot)
	}

	if !s.cstatus.compareAndAdd(*cd) {
		return false
	}

	return true
}

func (s *levelsController) fillTables(cd *compactDef) bool {
	cd.lockLevels()
	defer cd.unlockLevels()

	tbls := make([]*table.Table, len(cd.thisLevel.tables))
	copy(tbls, cd.thisLevel.tables)
	if len(tbls) == 0 {
		return false
	}

	// Find the biggest table, and compact that first.
	// TODO: Try other table picking strategies.
	sort.Slice(tbls, func(i, j int) bool {
		return tbls[i].Size() > tbls[j].Size()
	})

	for _, t := range tbls {
		cd.thisSize = t.Size()
		cd.thisRange = keyRange{
			left:  t.Smallest(),
			right: t.Biggest(),
		}
		if s.cstatus.overlapsWith(cd.thisLevel.level, cd.thisRange) {
			continue
		}
		cd.top = []*table.Table{t}
		left, right := cd.nextLevel.overlappingTables(cd.thisRange)

		cd.bot = make([]*table.Table, right-left)
		copy(cd.bot, cd.nextLevel.tables[left:right])

		if len(cd.bot) == 0 {
			cd.bot = []*table.Table{}
			cd.nextRange = cd.thisRange
			if !s.cstatus.compareAndAdd(*cd) {
				continue
			}
			return true
		}
		cd.nextRange = getKeyRange(cd.bot)

		if s.cstatus.overlapsWith(cd.nextLevel.level, cd.nextRange) {
			continue
		}

		if !s.cstatus.compareAndAdd(*cd) {
			continue
		}
		return true
	}
	return false
}

func (s *levelsController) runCompactDef(l int, cd compactDef) {
	timeStart := time.Now()
	var readSize int64
	for _, tbl := range cd.top {
		readSize += tbl.Size()
	}
	for _, tbl := range cd.bot {
		readSize += tbl.Size()
	}

	thisLevel := cd.thisLevel
	nextLevel := cd.nextLevel

	if thisLevel.level >= 1 && len(cd.bot) == 0 {
		y.AssertTrue(len(cd.top) == 1)

		nextLevel.replaceTables(cd.top)
		thisLevel.deleteTables(cd.top)

		tbl := cd.top[0]
		tbl.UpdateLevel(l + 1)
		cd.elog.LazyPrintf("\tLOG Compact-Move %d->%d smallest:%s biggest:%s took %v\n",
			l, l+1, string(tbl.Smallest()), string(tbl.Biggest()), time.Since(timeStart))
		return
	}

	c := s.buildCompactionLogEntry(&cd)
	//			if s.kv.opt.Verbose {
	//				y.Printf("Compact start: %v\n", c)
	//			}
	s.clog.add(c)
	newTables, decr := s.compactBuildTables(l, cd, c)
	if newTables == nil {
		err := decr()
		// This compaction couldn't be done successfully.
		cd.elog.LazyPrintf("\tLOG Compact FAILED with error: %+v: %+v %+v", err, cd, c)
		return
	}
	defer decr()

	nextLevel.replaceTables(newTables)
	thisLevel.deleteTables(cd.top) // Function will acquire level lock.

	// Note: For level 0, while doCompact is running, it is possible that new tables are added.
	// However, the tables are added only to the end, so it is ok to just delete the first table.

	// Write to compact log.
	c.done = 1
	s.clog.add(c)

	cd.elog.LazyPrintf("LOG Compact %d->%d, del %d tables, add %d tables, took %v\n",
		l, l+1, len(cd.top)+len(cd.bot), len(newTables), time.Since(timeStart))
}

// doCompact picks some table on level l and compacts it away to the next level.
func (s *levelsController) doCompact(p compactionPriority) bool {
	l := p.level
	y.AssertTrue(l+1 < s.kv.opt.MaxLevels) // Sanity check.

	cd := compactDef{
		elog:      trace.New("Badger", "Compact"),
		thisLevel: s.levels[l],
		nextLevel: s.levels[l+1],
	}
	cd.elog.SetMaxEvents(100)
	defer cd.elog.Finish()

	cd.elog.LazyPrintf("Got compaction priority: %+v", p)

	// While picking tables to be compacted, both levels' tables are expected to
	// remain unchanged.
	if l == 0 {
		if !s.fillTablesL0(&cd) {
			cd.elog.LazyPrintf("fillTables failed for level: %d\n", l)
			return false
		}

	} else {
		if !s.fillTables(&cd) {
			cd.elog.LazyPrintf("fillTables failed for level: %d\n", l)
			return false
		}
	}

	cd.elog.LazyPrintf("Running for level: %d\n", cd.thisLevel.level)
	s.cstatus.toLog(cd.elog)
	s.runCompactDef(l, cd)

	// Done with compaction. So, remove the ranges from compaction status.
	s.cstatus.delete(cd)
	s.cstatus.toLog(cd.elog)
	cd.elog.LazyPrintf("Compaction for level: %d DONE", cd.thisLevel.level)
	return true
}

func (s *levelsController) addLevel0Table(t *table.Table) {
	for !s.levels[0].tryAddLevel0Table(t) {
		// Stall. Make sure all levels are healthy before we unstall.
		var timeStart time.Time
		{
			s.elog.Printf("STALLED STALLED STALLED STALLED STALLED STALLED STALLED STALLED: %v\n",
				time.Since(lastUnstalled))
			s.cstatus.RLock()
			for i := 0; i < s.kv.opt.MaxLevels; i++ {
				s.elog.Printf("level=%d. Status=%s Size=%d\n",
					i, s.cstatus.levels[i].debug(), s.levels[i].getTotalSize())
			}
			s.cstatus.RUnlock()
			timeStart = time.Now()
		}
		// Before we unstall, we need to make sure that level 0 and 1 are healthy. Otherwise, we
		// will very quickly fill up level 0 again and if the compaction strategy favors level 0,
		// then level 1 is going to super full.
		for {
			// fmt.Printf("level zero size=%d\n", s.levels[0].getTotalSize())
			// fmt.Printf("level one size=%d/%d\n", s.levels[1].getTotalSize(), s.levels[1].maxTotalSize)
			if s.levels[0].getTotalSize() == 0 && s.levels[1].getTotalSize() < s.levels[1].maxTotalSize {
				break
			}
			time.Sleep(10 * time.Millisecond)
		}
		{
			s.elog.Printf("UNSTALLED UNSTALLED UNSTALLED UNSTALLED UNSTALLED UNSTALLED: %v\n",
				time.Since(timeStart))
			lastUnstalled = time.Now()
		}
	}
}

func (s *levelsController) close() error {
	cleanupErr := s.cleanupLevels()
	err := s.clog.close()
	if cleanupErr != nil {
		err = cleanupErr
	}
	return errors.Wrap(err, "levelsController.Close")
}

// get returns the found value if any. If not found, we return nil.
func (s *levelsController) get(key []byte) (y.ValueStruct, error) {
	// No need to lock anything as we just iterate over the currently immutable levelHandlers.
	for _, h := range s.levels {
		vs, err := h.get(key)
		if err != nil {
			return y.ValueStruct{}, errors.Wrapf(err, "get key: %q", key)
		}
		if vs.Value == nil && vs.Meta == 0 {
			continue
		}
		return vs, nil
	}
	return y.ValueStruct{}, nil
}

func appendIteratorsReversed(out []y.Iterator, th []*table.Table, reversed bool) []y.Iterator {
	for i := len(th) - 1; i >= 0; i-- {
		// This will increment the reference of the table handler.
		out = append(out, th[i].NewIterator(reversed))
	}
	return out
}

// appendIterators appends iterators to an array of iterators, for merging.
// Note: This obtains references for the table handlers. Remember to close these iterators.
func (s *levelsController) appendIterators(
	iters []y.Iterator, reversed bool) []y.Iterator {
	for _, level := range s.levels {
		iters = level.appendIterators(iters, reversed)
	}
	return iters
}


text:
import type AceEditor from './components/ace-editor';

declare module '@glint/environment-ember-loose/registry' {
  export default interface Registry {
    AceEditor: typeof AceEditor;
    'ace-editor': typeof AceEditor;
  }
}


text:
package org.apache.hadoop.hive.common.metrics.common;

/**
 * Metrics Scope to represent duration of an event.
 *
 * Implementation can capture information like the average duration of open scopes,
 * number of open scopes, number of completed scopes.
 *
 * Scopes are created via the Metrics framework (see Metrics#createScope or Metrics$createStoredScope)
 *
 * Scope may be stored by the Metrics framework via 'storedScope' concept for further reference.
 *
 * In either case, it is the caller's responsibility to end the scope via the Metrics framework (see Metrics#endScope)
 */
public interface MetricsScope {
}


text:
using Bridge.Test.NUnit;

namespace Bridge.ClientTest.Batch3.BridgeIssues
{
    // Bridge[#777]
    [Category(Constants.MODULE_ISSUES)]
    [TestFixture(TestNameFormat = "#777 - {0}")]
    public class Bridge777
    {
        private static object SomeProperty
        {
            get;
            set;
        }

        private static object P1
        {
            get;
            set;
        }

        private static object P2
        {
            get;
            set;
        }

        private static object Method(object o)
        {
            return null;
        }

        [Test(ExpectedCount = 4)]
        public static void TestUseCase()
        {
            object o = new { };
            lock (o)
            {
                int i = 555;
                Assert.AreEqual(555, i, "Bridge777 i");
            }

            lock (Method(SomeProperty = o))
            {
                Assert.NotNull(SomeProperty, "Bridge777 SomeProperty");
            }

            lock (P1 = P2 = o)
            {
                Assert.NotNull(P1, "Bridge777 P1");
                Assert.NotNull(P2, "Bridge777 P2");
            }
        }
    }
}


text:
package org.bsworks.x2.resource;

import java.util.Collection;
import java.util.Deque;
import java.util.Map;

/**
 * Resource properties container, such as a resource or a nested object.
 *
 * @author Lev Himmelfarb
 */
public interface ResourcePropertiesContainer {

	/**
	 * Get persistent property handlers chain.
	 *
	 *
An exception is made for the {@link TypePropertyHandler} of a
	 * persistent polymorphic nested object property - it does not have to be
	 * persistent.
	 *
	 *
If a polymorphic object property needs to be accessed, the concrete
	 * type name is used as a pseudo-property between the polymorphic object
	 * property name and the nested property name in the path. In the resulting
	 * chain, both polymorphic object property handler, and the concrete type
	 * property handler are included.
	 *
	 * @param propPath Property path relative to the container. Nested
	 * properties separated with dots.
	 *
	 * @return Unmodifiable chain of property handlers. The first element is
	 * handler for one of this container's property. The last element is handler
	 * for the property identified by the path.
	 *
	 * @throws InvalidSpecificationException If the path is invalid or any of
	 * the properties in the chain is not persistent.
	 */
	Deque<? extends ResourcePropertyHandler> getPersistentPropertyChain(
			String propPath);

	/**
	 * Get handlers for all properties in the container.
	 *
	 * @return Unmodifiable map of property handlers by property names.
	 */
	Map<String, ? extends ResourcePropertyHandler> getProperties();

	/**
	 * Get handler for the container record id property.
	 *
	 * @return Record id property handler, or {@code null} if the container does
	 * not define a record id property.
	 */
	IdPropertyHandler getIdProperty();

	/**
	 * Get handlers for all simple properties in the container.
	 *
	 * @return Unmodifiable collection of property handlers.
	 */
	Collection<? extends SimplePropertyHandler> getSimpleProperties();

	/**
	 * Get handlers for all nested object properties in the container.
	 *
	 * @return Unmodifiable collection of property handlers.
	 */
	Collection<? extends ObjectPropertyHandler> getObjectProperties();

	/**
	 * Get handlers for all persistent resource reference properties in the
	 * container.
	 *
	 * @return Unmodifiable collection of property handlers.
	 */
	Collection<? extends RefPropertyHandler> getRefProperties();
}