text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Hello World!</title>

  <link rel="stylesheet" href="css/style.css"/>

Hello World!

We are using node.js

.

Directory Listing

Flash test

Exit

redpajama_set_name: RedPajamaGithub


text:
package org.apache.shardingsphere.sql.parser.sql.common.constant;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

/**
 * Transaction access type enum.
 */
@RequiredArgsConstructor
@Getter
public enum TransactionAccessType {

    READ_ONLY("READ_ONLY"),
    READ_WRITE("READ_WRITE");

    private final String accessType;
}


text:
typedef struct {
  ShovelerUniform* uniform;
  GLint location;
} ShovelerUniformAttachment;

ShovelerUniformAttachment* shovelerUniformAttachmentCreate(
    ShovelerUniform* uniform, GLint location);
bool shovelerUniformAttachmentUse(
    ShovelerUniformAttachment* uniformAttachment, GLuint* textureUnitIndexCounter);
void shovelerUniformAttachmentFree(ShovelerUniformAttachment* uniformAttachment);

#endif


text:
package net.snowflake.client.log;

import static org.junit.Assert.assertTrue;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import org.junit.Before;
import org.junit.Test;

public class SFFormatterTest {
  // Change these numbers if necessary
  /** The maximum time difference in millisecond allowed for timestamp and now */
  private static final long TIME_DIFFERENCE_BOUNDARY = 600000; // 10 minutes
  /** Number of iterations for the stress test */
  private static final int STRESS_TEST_ITERATION = 2000;

  /** Log record generator */
  private LRGenerator recordGenerator;

  @Before
  public void setUp() {
    recordGenerator = new LRGenerator(SFFormatter.CLASS_NAME_PREFIX + "TestClass", "TestMethod");
    recordGenerator.setFormatter(new SFFormatter());
  }

  /**
   * This test intends to check if the timestamp generated in the SFFormatter is in UTC timezone
   *
   *
It would extract the timestamp from a log record using the SFFormatter and compare it
   * against now;
   *
   *
Since the time difference between the log record's generated time and the current time is
   * small, their difference would be limited within TIME_DIFFERENCE_BOUNDARY if the log record's
   * timestamp is in UTC timezone
   *
   * @throws ParseException Will be thrown if date extraction fails
   */
  @Test
  public void testUTCTimeStampSimple() throws ParseException {
    TimeZone originalTz = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
    try {
      String record = recordGenerator.generateLogRecordString(Level.INFO, "TestMessage");

      Date date = extractDate(record);
      long nowInMs = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis();
      assertTrue(
          "Time difference boundary should be less than " + TIME_DIFFERENCE_BOUNDARY + "ms",
          nowInMs - date.getTime() < TIME_DIFFERENCE_BOUNDARY);
    } finally {
      TimeZone.setDefault(originalTz);
    }
  }

  /**
   * The bulk version test of testUTCTimeStampSimple()
   *
   * @throws ParseException Will be thrown if timestamp parsing fails
   */
  @Test
  public void testUTCTimeStampStress() throws ParseException {
    for (int i = 0; i < STRESS_TEST_ITERATION; i++) {
      testUTCTimeStampSimple();
    }
  }

  /**
   * A log generator could generate log record directly and fill in necessary field specified by
   * constructor
   */
  private class LRGenerator {
    // Required by SFFormatter as a log record without these fields would cause NullPointerException
    // in
    // our SF formatter
    // add more fields to plug in the log record if required for testing
    private String srcClassName;
    private String srcMethodName;

    private Formatter formatter;

    public LRGenerator(String srcClassName, String srcMethodName) {
      this.srcClassName = srcClassName;
      this.srcMethodName = srcMethodName;
      formatter = null;
    }

    /**
     * No formatter is needed
     *
     * @param level level of log record priority
     * @param message message of log record
     * @return A LogRecord instance
     */
    public LogRecord generateLogRecord(Level level, String message) {
      LogRecord record = new LogRecord(Level.INFO, "null");
      record.setSourceClassName(this.srcClassName);
      record.setSourceMethodName(this.srcMethodName);
      return record;
    }

    /**
     * Generate the string representation of the log record formatter is required to be not null!!
     *
     * @param level level of log record priority
     * @param message message of log record
     * @return A LogRecord instance
     */
    public String generateLogRecordString(Level level, String message) {
      return formatter.format(this.generateLogRecord(level, message));
    }

    /**
     * Formatter setter
     *
     * @param formatter The formatter to use for the log record generator
     */
    public void setFormatter(Formatter formatter) {
      this.formatter = formatter;
    }
  }

  /**
   * Helper function to extract the date from the log record
   *
   * @param string log record representation
   * @return a date specified by the log record
   * @throws ParseException Will be thrown if parsing fails
   */
  private Date extractDate(String string) throws ParseException {
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
    df.setCalendar(cal);
    Date date = df.parse(string);
    return date;
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/MaterialViewPagerIndicator.iml" filepath="$PROJECT_DIR$/MaterialViewPagerIndicator.iml" />
      <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" />
      <module fileurl="file://$PROJECT_DIR$/material-viewpagerindicator/material-viewpagerindicator.iml" filepath="$PROJECT_DIR$/material-viewpagerindicator/material-viewpagerindicator.iml" />
    </modules>
  </component>
</project>


text:
function [ x, y ] = transformtoxy( self, A, B, force )
if nargin == 4
    fitting = force;
else
    fitting = self.dataFitting;
end
x = interp2( ...
    self.inputMatrixA, ...
    self.inputMatrixB, ...
    self.inputMatrixX, ...
    A, B, fitting);
y = interp2( ...
    self.inputMatrixA, ...
    self.inputMatrixB, ...
    self.inputMatrixY, ...
    A, B, fitting);
end


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
//require APPPATH . '/libraries/Common_Controller.php';

class Management extends NG_Controller {
    function __construct () {
        parent::__construct();
        $this->load->helper('url');
    }

    function get_admin_users () {
        $this->load->model('user_model');

        $users = $this->user_model->get_admin_users();

        $this->__get_partial_view('Partial/user_list',
            array ('users' => $users));
    }
}


text:
namespace CSRunner
{
    namespace
    {
        const std::string k_saveDataPath = "SavedData.json";
        const std::string k_saveDataBestTimeKey = "BestTime";
    }
    //------------------------------------------------------------
    GameoverState::GameoverState(f32 timeSurvived) noexcept
    : m_timeSurvived((u32)timeSurvived)
    {

    }
    //------------------------------------------------------------
    void GameoverState::CreateSystems() noexcept
    {
        m_transitionSystem = CreateSystem<TransitionSystem>(0.0f, 1.0f);
        m_gestureSystem = CreateSystem<CS::GestureSystem>();
    }

    //------------------------------------------------------------
    void GameoverState::OnInit() noexcept
    {
        GetMainScene()->SetClearColour(CS::Colour(0.137f, 0.203f, 0.098f));

        auto gameoverViewDef = CS::Application::Get()->GetResourcePool()->LoadResource<CS::WidgetTemplate>(CS::StorageLocation::k_package, "GUI/Gameover.csui");
        CS::WidgetSPtr gameoverView = CS::Application::Get()->GetWidgetFactory()->Create(gameoverViewDef);
        GetUICanvas()->AddWidget(gameoverView);

        //Grab the current best time
        Json::Value root;
        u32 bestTimeSurvived = 0;
        if(CS::JsonUtils::ReadJson(CS::StorageLocation::k_saveData, k_saveDataPath, root) == true)
        {
            bestTimeSurvived = root.get(k_saveDataBestTimeKey, 0u).asUInt();
        }

        auto timeSurvivedLabel = gameoverView->GetWidgetRecursive("LastTime")->GetComponent<CS::TextUIComponent>();
        timeSurvivedLabel->SetText("You survived for " + CS::ToString(m_timeSurvived) + " seconds");

        std::string bestTimePrefix;
        if(m_timeSurvived > bestTimeSurvived)
        {
            bestTimeSurvived = m_timeSurvived;
            bestTimePrefix = "NEW ";
            root[k_saveDataBestTimeKey] = bestTimeSurvived;
            CS::JsonUtils::WriteJson(CS::StorageLocation::k_saveData, k_saveDataPath, root);
        }

        auto bestTimeLabel = gameoverView->GetWidgetRecursive("BestTime")->GetComponent<CS::TextUIComponent>();
        bestTimeLabel->SetText(bestTimePrefix + "Best time " + CS::ToString(bestTimeSurvived) + " seconds");

        auto tapGesture = std::make_shared<CS::TapGesture>();
        m_tapEventConnection = tapGesture->GetTappedEvent().OpenConnection([this](const CS::TapGesture* gesture, const CS::Vector2& pos)
        {
            m_transitionSystem->Transition(std::make_shared<MainMenuState>());
            m_tapEventConnection.reset();
        });
        m_gestureSystem->AddGesture(tapGesture);

        auto gamepadSystem = CS::Application::Get()->GetSystem<CS::GamepadSystem>();
        if(gamepadSystem != nullptr)
        {
            m_gamepadButtonEventConnection = gamepadSystem->GetButtonPressureChangedEvent().OpenConnection([this](const CS::Gamepad& gamepad, f64 timestamp, u32 buttonIndex, f32 pressure)
            {
                if(pressure >= 0.5f)
                {
                    m_transitionSystem->Transition(std::make_shared<MainMenuState>());
                    m_gamepadButtonEventConnection.reset();
                }
            });
        }
    }
}


text:
package org.jclouds.openstack.swift.domain.internal;

import java.net.URI;
import java.util.Date;
import java.util.Map;

import org.jclouds.io.payloads.BaseMutableContentMetadata;
import org.jclouds.openstack.swift.domain.MutableObjectInfoWithMetadata;
import org.jclouds.openstack.swift.domain.ObjectInfo;

public class DelegatingMutableObjectInfoWithMetadata extends BaseMutableContentMetadata implements
         MutableObjectInfoWithMetadata {

   private final MutableObjectInfoWithMetadata delegate;

   public DelegatingMutableObjectInfoWithMetadata(MutableObjectInfoWithMetadata delegate) {
      this.delegate = delegate;
   }

   @Override
   public Long getContentLength() {
      return delegate.getBytes();
   }

   @Override
   public String getContentType() {
      return delegate.getContentType();
   }

   @Override
   public byte[] getContentMD5() {
      return delegate.getHash();
   }

   @Override
   public int hashCode() {
      return delegate.hashCode();
   }

   @Override
   public void setContentLength(Long bytes) {
      if (bytes != null)
         delegate.setBytes(bytes);
   }

   @Override
   public void setContentType(String contentType) {
      delegate.setContentType(contentType);
   }

   @Override
   public void setContentMD5(byte[] hash) {
      delegate.setHash(hash);
   }

   public MutableObjectInfoWithMetadata getDelegate() {
      return delegate;
   }

   @Override
   public Map<String, String> getMetadata() {
      return delegate.getMetadata();
   }

   @Override
   public void setBytes(Long bytes) {
      delegate.setBytes(bytes);
   }

   @Override
   public void setHash(byte[] hash) {
      delegate.setHash(hash);
   }

   @Override
   public void setLastModified(Date lastModified) {
      delegate.setLastModified(lastModified);
   }

   @Override
   public void setName(String name) {
      delegate.setName(name);
   }

   @Override
   public Long getBytes() {
      return delegate.getBytes();
   }

   @Override
   public byte[] getHash() {
      return delegate.getHash();
   }

   @Override
   public Date getLastModified() {
      return delegate.getLastModified();
   }

   @Override
   public String getName() {
      return delegate.getName();
   }

   @Override
   public int compareTo(ObjectInfo o) {
      return delegate.compareTo(o);
   }

   @Override
   public void setContainer(String container) {
      delegate.setContainer(container);
   }

   @Override
   public String getContainer() {
      return delegate.getContainer();
   }

   @Override
   public void setUri(URI uri) {
      delegate.setUri(uri);
   }

   @Override
   public URI getUri() {
      return delegate.getUri();
   }

   @Override
   public void setObjectManifest(String objectManifest) {
      delegate.setObjectManifest(objectManifest);
   }

   @Override
   public String getObjectManifest() {
      return delegate.getObjectManifest();
   }
}


text:
![Imgur](http://i.imgur.com/wXQbebg.png)
*Demo URL: [https://medup.herokuapp.com]*

70% of Americans regularly take prescription drugs, with more than half with at least two prescriptions.  Taking the right drug at the correct time is difficult without a plan and daily reminders. With our cross-platform application MedUp, we help users stay on track with their dosages through notifications.

## Software Engineers of MedUp

**Product Owner, Front End Software Engineer:** Kayla Dowling

**Scrum Master, Front End Software Engineer:** Jefri Vanegas

**Front End Software Engineer, DevOps:** Dave Meidlinger

**Full Stack Software Engineer:** Robert Lin

**Full Stack Software Engineer:** Brian Tedder

## Table of Contents

1. [Usage](#Usage)
2. [Development](#development)
  1. [Requirements](#requirements)
  2. [Installing Dependencies](#installing-dependencies)
4. [Contributing](#contributing)

## Usage

##### Register/Login

An email and password is required for sign up and sign in. All information provided by the user is encrypted for privacy.

##### Dashboard - View Medications

Users have a quick access to view their medications with features to add, delete, and edit their medications.

##### Add Medications

With a simple form, users can quickly submit medication name, dose, instructions, and set up reminder notifications.

##### Edit Medications

From an editable view of their current medication, users can quickly make changes.

##### Delete Medications

From View Medications screen, users can quickly  delete medications.

##### Notifications

# Development

### Requirements
**Tech Stack:** *Ionic, Hapi.js, MongoDB, AngularJS, node.js, Gulp, Protractor, Mocha, Chai, ES2015/ES5 *
```
     angular:^1.4.9,
     angular-component:0.0.6,
     angular-ui-bootstrap:^1.1.2,
     angular-ui-router:^0.2.17,
     bcrypt-nodejs:0.0.3,
     crypto-js:^3.1.6,
     dogwater:^1.1.0,
     ejs:^2.4.1,
     glob:^6.0.4,
     glue:^3.1.0,
     good:^6.4.0,
     good-console:^5.2.0,
     hapi:^12.1.0,
     hapi-auth-jwt2:^5.3.2,
     hapi-sass:^2.0.0,
     inert:^3.2.0,
     joi:^7.2.2,
     jsonwebtoken:^5.5.4,
     node-neat:^1.7.2,
     path:^0.12.7,
     plugo:^0.3.1,
     sails-mongo:^0.12.0,
     vinyl-source-stream:^1.1.0,
     vision:^4.0.1,
     shortID:^ 2.2.4
```

##### Development Dependencies
```
     babel-cli: ^6.4.5,
     babel-core: ^6.4.5,
     babel-loader: ^6.2.1,
     babel-preset-es2015: ^6.3.13,
     blipp: ^2.3.0,
     chai: ^3.4.1,
     gulp: ^3.9.0/^3.5.6,
     gulp-angular-protractor: 0.0.7,
     gulp-clean: ^0.3.1,
     gulp-concat: ^2.6.0,
     gulp-sass: ^2.0.4,
     gulp-filesize: 0.0.6,
     gulp-jshint: ^2.0.0,
     gulp-minify-css: ^0.3.0,
     gulp-live-server: 0.0.29,
     gulp-load-plugins: ^1.2.0,
     gulp-mocha: ^2.2.0,
     gulp-nodemon: ^2.0.6,
     gulp-rename: ^1.2.2,
     gulp-shell: ^0.5.2,
     gulp-tape: 0.0.7,
     gulp-uglify: ^1.5.1,
     gulp-util: ^3.0.7,
     gulp-angular-protractor: 0.0.7,
     jasmine-given: ^2.6.4,
     jshint: ^2.9.1,
     jshint-stylish: ^2.1.0,
     mocha: ^2.3.4,
     raw: ^0.1.4,
     raw-loader: ^0.5.1,
     sails-memory: ^0.10.5,
     supertest: ^1.1.0,
     tap-colorize: ^1.2.0,
     tape: ^4.4.0,
     webpack: ^1.12.1,
     bower: ^1.3.3,
     shelljs: ^0.3.0,

   cordovaPlugins
   cordova-plugin-device,
   cordova-plugin-console,
   cordova-plugin-whitelist,
   cordova-plugin-splashscreen,
   cordova-plugin-statusbar,
   ionic-plugin-keyboard,
   cordovaPlatforms - ios,
   cordovaPlatforms - android
   locator: https://github.com/katzer/cordova-plugin-local-notifications.git,
   id: de.appplant.cordova.plugin.local-notification
```

### Installing Dependencies

From within the root directory of MedUp:

```
npm install
```
*This will install all npm managed dependencies and then run bower install to manage bower dependencies.*

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidelines. -->


text:
package br.ufg.inf.homeshop.holder;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;

public class MarketHolder extends RecyclerView.ViewHolder {

    public ImageView picture;

    public MarketHolder(View itemView) {
        super(itemView);
    }

}


text:
@cd ..
@call mvn clean:clean
@call mvn eclipse:clean
@pause


text:
using System;
using System.ComponentModel;

namespace Azure.ResourceManager.LabServices.Models
{
    /// <summary> The unit details. </summary>
    public readonly partial struct LabServicesUsageUnit : IEquatable<LabServicesUsageUnit>
    {
        private readonly string _value;

        /// <summary> Initializes a new instance of <see cref="LabServicesUsageUnit"/>. </summary>
        /// <exception cref="ArgumentNullException"> <paramref name="value"/> is null. </exception>
        public LabServicesUsageUnit(string value)
        {
            _value = value ?? throw new ArgumentNullException(nameof(value));
        }

        private const string CountValue = "Count";

        /// <summary> Count. </summary>
        public static LabServicesUsageUnit Count { get; } = new LabServicesUsageUnit(CountValue);
        /// <summary> Determines if two <see cref="LabServicesUsageUnit"/> values are the same. </summary>
        public static bool operator ==(LabServicesUsageUnit left, LabServicesUsageUnit right) => left.Equals(right);
        /// <summary> Determines if two <see cref="LabServicesUsageUnit"/> values are not the same. </summary>
        public static bool operator !=(LabServicesUsageUnit left, LabServicesUsageUnit right) => !left.Equals(right);
        /// <summary> Converts a string to a <see cref="LabServicesUsageUnit"/>. </summary>
        public static implicit operator LabServicesUsageUnit(string value) => new LabServicesUsageUnit(value);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override bool Equals(object obj) => obj is LabServicesUsageUnit other && Equals(other);
        /// <inheritdoc />
        public bool Equals(LabServicesUsageUnit other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase);

        /// <inheritdoc />
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override int GetHashCode() => _value?.GetHashCode() ?? 0;
        /// <inheritdoc />
        public override string ToString() => _value;
    }
}


text:
package govaluate

/*
  Contains test cases for all the expression examples given in the README.
  While all of the functionality for these cases should be covered in other tests,
  this is really just a sanity check.
*/
import (
	"testing"
)

func TestBasicEvaluation(test *testing.T) {

	expression, _ := NewEvaluableExpression("10 > 0")
	result, _ := expression.Evaluate(nil)

	if result != true {
		test.Logf("Expected 'true', got '%v'\n", result)
		test.Fail()
	}
}

func TestParameterEvaluation(test *testing.T) {

	expression, _ := NewEvaluableExpression("foo > 0")

	parameters := make(map[string]interface{}, 8)
	parameters["foo"] = -1

	result, _ := expression.Evaluate(parameters)

	if result != false {
		test.Logf("Expected 'false', got '%v'\n", result)
		test.Fail()
	}
}

func TestModifierEvaluation(test *testing.T) {

	expression, _ := NewEvaluableExpression("(requests_made * requests_succeeded / 100) >= 90")

	parameters := make(map[string]interface{}, 8)
	parameters["requests_made"] = 100
	parameters["requests_succeeded"] = 80

	result, _ := expression.Evaluate(parameters)

	if result != false {
		test.Logf("Expected 'false', got '%v'\n", result)
		test.Fail()
	}
}

func TestStringEvaluation(test *testing.T) {

	expression, _ := NewEvaluableExpression("http_response_body == 'service is ok'")

	parameters := make(map[string]interface{}, 8)
	parameters["http_response_body"] = "service is ok"

	result, _ := expression.Evaluate(parameters)

	if result != true {
		test.Logf("Expected 'false', got '%v'\n", result)
		test.Fail()
	}
}

func TestFloatEvaluation(test *testing.T) {

	expression, _ := NewEvaluableExpression("(mem_used / total_mem) * 100")

	parameters := make(map[string]interface{}, 8)
	parameters["total_mem"] = 1024
	parameters["mem_used"] = 512

	result, _ := expression.Evaluate(parameters)

	if result != 50.0 {
		test.Logf("Expected '50.0', got '%v'\n", result)
		test.Fail()
	}
}

func TestDateComparison(test *testing.T) {

	expression, _ := NewEvaluableExpression("'2014-01-02' > '2014-01-01 23:59:59'")
	result, _ := expression.Evaluate(nil)

	if result != true {
		test.Logf("Expected 'true', got '%v'\n", result)
		test.Fail()
	}
}

func TestMultipleEvaluation(test *testing.T) {
	expression, _ := NewEvaluableExpression("response_time <= 100")
	parameters := make(map[string]interface{}, 8)

	for i := 0; i < 64; i++ {
		parameters["response_time"] = i
		result, _ := expression.Evaluate(parameters)

		if result != true {
			test.Logf("Expected 'true', got '%v'\n", result)
			test.Fail()
		}
	}
}


text:
import $ from 'cheerio';

module.exports = function (input) {
	var page = $.load(input);
	var formFields = page('input[type="hidden"]');

	var data = {};

	formFields.each(function(i, elem) {
		data[$(this).attr('name')] = $(this).attr('value');
	});

	return data;
};


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

using System;
using System.Runtime.InteropServices;

namespace OpenLiveWriter.Interop.Windows
{
    internal static class OleAut32
    {
        [DllImport("OleAut32.dll", PreserveSig = true)] // psa is actually returned, not hresult
        internal extern static IntPtr SafeArrayCreateVector(ushort vt, int lowerBound, uint cElems);

        [DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
        internal extern static IntPtr SafeArrayAccessData(IntPtr psa);

        [DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
        internal extern static void SafeArrayUnaccessData(IntPtr psa);

        [DllImport("OleAut32.dll", PreserveSig = true)] // retuns uint32
        internal extern static uint SafeArrayGetDim(IntPtr psa);

        [DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
        internal extern static int SafeArrayGetLBound(IntPtr psa, uint nDim);

        [DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
        internal extern static int SafeArrayGetUBound(IntPtr psa, uint nDim);

        // This decl for SafeArrayGetElement is only valid for cDims==1!
        [DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
        [return: MarshalAs(UnmanagedType.IUnknown)]
        internal extern static object SafeArrayGetElement(IntPtr psa, ref int rgIndices);
    }
}


text:
package och.api.model.user;

import och.util.model.HasIntCode;

public enum UserStatus implements HasIntCode {

	NEW(0),
	ACTIVATED(1),
	BANNED(2)

	;

	public final int code;

	private UserStatus(int code) {
		this.code = code;
	}

	@Override
	public int getCode() {
		return code;
	}

}


text:
require_relative 'ciscotest'
require_relative '../lib/cisco_node_utils/domain_name'

# TestDomainName - Minitest for DomainName node utility.
class TestDomainName < CiscoTestCase
  @skip_unless_supported = 'dnsclient'

  def setup
    # setup runs at the beginning of each test
    super
    @backup_resolve = backup_resolv_file
    no_domainname_test_xyz
  end

  def teardown
    # teardown runs at the end of each test
    no_domainname_test_xyz
    restore_resolv_file(@backup_resolve)
    super
  end

  def no_domainname_test_xyz
    # Turn the feature off for a clean test.
    if platform == :ios_xr
      config('no domain name test.abc',
             'no domain name test.xyz',
             'no vrf test')
    else
      config('no ip domain-name test.abc',
             'no ip domain-name test.xyz',
             'no vrf context test')
    end
  end

  # TESTS

  def test_create_replace_destroy
    name1 = 'test.abc'
    name2 = 'test.xyz'
    refute_includes(Cisco::DomainName.domainnames, name1)
    refute_includes(Cisco::DomainName.domainnames, name2)

    domain = Cisco::DomainName.new(name1)
    assert_includes(Cisco::DomainName.domainnames, name1)
    refute_includes(Cisco::DomainName.domainnames, name2)
    assert_equal(Cisco::DomainName.domainnames[name1], domain)

    domain = Cisco::DomainName.new(name2)
    refute_includes(Cisco::DomainName.domainnames, name1)
    assert_includes(Cisco::DomainName.domainnames, name2)
    assert_equal(Cisco::DomainName.domainnames[name2], domain)

    domain.destroy
    refute_includes(Cisco::DomainName.domainnames, name1)
    refute_includes(Cisco::DomainName.domainnames, name2)
  end

  def test_create_replace_destroy_vrf
    name1 = 'test.abc'
    name2 = 'test.xyz'
    vrf = 'test'
    refute_includes(Cisco::DomainName.domainnames(vrf), name1)
    refute_includes(Cisco::DomainName.domainnames(vrf), name2)

    domain = Cisco::DomainName.new(name1, vrf)
    assert_includes(Cisco::DomainName.domainnames(vrf), name1)
    refute_includes(Cisco::DomainName.domainnames(vrf), name2)
    assert_equal(Cisco::DomainName.domainnames(vrf)[name1], domain)

    domain = Cisco::DomainName.new(name2, vrf)
    refute_includes(Cisco::DomainName.domainnames(vrf), name1)
    assert_includes(Cisco::DomainName.domainnames(vrf), name2)
    assert_equal(Cisco::DomainName.domainnames(vrf)[name2], domain)

    domain.destroy
    refute_includes(Cisco::DomainName.domainnames(vrf), name1)
    refute_includes(Cisco::DomainName.domainnames(vrf), name2)
  end
end


text:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>About me on Il y a du thé renversé au bord de la table !</title>
    <link>https://yoric.github.io/about/</link>
    <description>Recent content in About me on Il y a du thé renversé au bord de la table !</description>
    <generator>Hugo -- gohugo.io</generator>
    <language>en</language>
    <copyright>© This post is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License,please give source if you wish to quote or reproduce.</copyright>
    <lastBuildDate>Sat, 18 Feb 2017 16:06:26 +0100</lastBuildDate><atom:link href="https://yoric.github.io/about/index.xml" rel="self" type="application/rss+xml" />
  </channel>
</rss>


text:
>  *What database models do you know?*
### Database models

#### Hierarchical (tree)
In a hierarchical model, data is organized into a tree-like structure, implying a single parent for each record. The root element doesn't have parent.

#### Network / graph
The network model expands upon the hierarchical structure, allowing many-to-many relationships in a tree-like structures like graphs that allows multiple parents.

#### Relational (table)
The basic data structure of the relational model is the table, where information about a particular entity (say, an employee) is represented in rows (also called tuples) and columns. Thus, the "relation" in "relational database" refers to the various tables in the database; a relation is a set of tuples.

* Represent a bunch of tables together with the relationships between them.
* Rely on a strong mathematical foundation: the relational algebra.
* Relation is a relation between a column in a table to a column in other table.

#### Object-oriented
In the 1990s, the object-oriented programming paradigm was applied to database technology, creating a new database model known as object databases. This aims to avoid the object-relational impedance mismatch - the overhead of converting information between its representation in the database (for example as rows in tables) and its representation in the application program (typically as objects).

>*Which are the main functions performed by a Relational Database Management System (RDBMS)?*
### Main functions performed by a Relational Database Management System (RDBMS)
Relational Database Management Systems (RDBMS) manage data stored in tables. The tables consists of rows and columns.

**RDBMS systems typically implement**

* Creating / altering / deleting tables and relationships between them (database schema)
* Adding, changing, deleting, searching and retrieving of data stored in the tables
* Support for the SQL language
* Transaction management (optional)

**RDBMS systems are also known as:**

* Database management servers
* Or just database servers

> *Define what is "table" in database terms.*
### "Table" in database terms

Database tables consist of data, arranged in rows and columns. For example (table Persons):

|Id	| First Name | Last Name | Employer

|1	|	Steve	|	Jobs	|	Apple

|2	|	Bill	|	Gates	|	Microsoft

|3	|	Jeff	|	Bezos	|	Amazon

* All rows have the same structure
* Columns have name and type (number, string, date, image, or other)
* **Table** have **schema**. The **schema of a table** is an ordered sequence of column specifications (name and type). In the example above the schema of the Persons table is:

		Persons (
		  Id: number,
		  FirstName: string,
		  LastName: string,
		  Employer: string
		)

> *Explain the difference between a primary and a foreign key.*
### Difference between a primary and a foreign key

**Primary key** is a column of the table that uniquely identifies its rows (usually its is a number). Two records (rows) are different if and only if their primary keys are different. The primary key can be composed by several columns (**composite primary key**).

**Foreign key** is a column (or collection of columns) in one table that uniquely identifies a row of another table. We can say that the foreign key is defined in a second table, but it refers to the primary key in the first table.

Example:
![](one-to-many-ralation.png)

> *Explain the different kinds of relationships between tables in relational databases.*
### Kinds of relationships between tables in relational databases

By using **relationships** we avoid repeating data in the database. In the last example the name of the country is not repeated for each town (its number is used instead). Relationships have multiplicity:

* **One-to-many** – e.g. country / towns.
	* A single record in the first table has many corresponding records in the second table.
	* Used very often(see the example above).
* **Many-to-many** – e.g. student / course.
	* Records in the first table have many corresponding records in the second one and vice versa.
	* Implemented through additional table

![](many-to-many-ralation.png)
In this example the StudentId column of StudentsCourses table is a foreign key to Students table primary key, which is Id column of Students table. In the same way CourseId column of StudentsCourses table is a foreign key to the primary key of Courses table. The primary key of Courses table is Id column.

* **One-to-one** – e.g. example human / student
	* A single record in a table corresponds to a single record in the other table
	* Used to model inheritance between tables.

![](one-to-one-ralation.png)
In this example the Id columns of the tables are primary and foreign keys in the same time.

* **Self-Relationships**
	* The primary / foreign key relationships can point to one and the same table
	* Represents some hierarchy like trees and graphs.

![](self-relationships.png)

> *When is a certain database schema normalized? What are the advantages of normalized databases?*
### Normalizing database schema
* Normalization of the relational schema enters primary key.
* Normalization of the relational schema removes repeating data.
* Non-normalized schemas can contain many data repetitions, doesn't have primary key e.g. Example for non-normalized schema:

![](non-normalized.png)

Example for full-normalized schema of the above table:

![](full-normalized.png)

> *What are database integrity constraints and when are they used?*
### Use of database integrity constraints

**Integrity constraints** ensure data integrity in the relational database tables. Enforce data rules which cannot be violated. This is main difference between relational and non-relational database. There are several kinds of Integrity constraints:

* **Primary key constrain**t
	* Ensures that the primary key of a table has unique value for each table row
* **Unique key constraint**
	* Ensures that all values in a certain column (or a group of columns) are unique
* **Foreign key constraint**
	* Ensures that the value in given column is a key from another table
*** Check constraint**
	* Ensures that values in a certain column meet some predefined condition. Examples:

			(hour >= 0) AND (hour < 24)
or

			name = UPPER(name)

> *Point out the pros and cons of using indexes in a database.*
### Pros and Cons of using indexes in a database
**Indexes** are usually implemented as B-trees. Indexes can be built-in the table (**clustered**) or stored externally (**non-clustered**).
**Clustered** indexes are those who exist together with the main data in the b-tree structure.
**Non-clustered** indexes exist in apart structure, from the main data b-tree structure and have additional relation to the main data.

* Pros
	* Indexes speed up(exponentially) searching of values in a certain column or group of columns

* Cons
	* Adding and deleting records in indexed tables is slower.
	* Working with **non-clustered** indexes is a little bit slower, because of the need of updating the indexes structure.
	* Costs resources(for memory on HDD, for processing on periodically refreshing)
	* Indexes should be used for big tables only (e.g. 50 000 rows)

> *What's the main purpose of the SQL language?*
### SQL language main purpose

**SQL** (Structured Query Language) is the main tool to work with databases. It is **Standardized declarative language** for manipulation of relational databases. SQL-99 is currently in use in most databases.

[Wikipedia Link to SQL article](https://en.wikipedia.org/wiki/SQL)

**SQL** language supports:

* Creating, altering, deleting tables and other objects in the database
* Searching, retrieving, inserting, modifying and deleting table data (rows)

**SQL** language consists of:

* DDL – Data Definition Language - defining the meta-data information(name of the field, type etc.)
	* Commands: CREATE, ALTER, DROP
* DML – Data Manipulation Language - manipulating the data via queries
	* Commands: SELECT, INSERT, UPDATE, DELETE

Example of SQL SELECT query:

			SELECT Towns.Name, Countries.Name
			FROM Towns, Countries
			WHERE Towns.CountryId = Countries.Id

> *What are transactions used for? Give an example.*
### Use of transactions
**Transactions** are a sequence of database operations which are executed as a single unit. They care for the data consistency. Either all of the operations in them execute successfully or none of them is executed at all.

**Example:**
A bank transfer from one account into another (withdrawal + deposit). If either the withdrawal or the deposit succeed and the entire operation succeeds or if they both fail the entire operation should be canceled.

**Transaction life-cycle:**
![](transaction-lifecycle.png)

* Transactions guarantee the consistency and the integrity of the database
	* All changes in a transaction are temporary
	* Changes become final when COMMIT is successfully executed
	* At any time all changes done in the transaction can be canceled by executing ROLLBACK
* All operations are executed as a single unit
	* Either all of them pass or none of them

> *What is a NoSQL database?*
### NoSQL database
**NoSQL** term comes from "No SQL" or "Not Only SQL" abbreviation.

**NoSQL** database is non-relational data base model. The data is stored in classical JavaScript Object Notation(JSON) format.

**NoSQL** (originally referring to "non SQL" or "non relational") database provides a mechanism for storage and retrieval of data that is modeled in means other than the tabular relations used in relational databases. Such databases have existed since the late 1960s, but did not obtain the "NoSQL" moniker until a surge of popularity in the early twenty-first century, triggered by the needs of Web 2.0 companies such as Facebook, Google and Amazon.com.

Motivations for this approach include: simplicity of design, simpler "horizontal" scaling to clusters of machines, which is a problem for relational databases, and finer control over availability. The data structures used by NoSQL databases (e.g. key-value, graph, or document) differ slightly from those used by default in relational databases, making some operations faster in NoSQL and others faster in relational databases. The particular suitability of a given NoSQL database depends on the problem it must solve. Sometimes the data structures used by noSQL databases are also viewed as "more flexible" than relational database tables.

NoSQL databases are increasingly used in big data and real-time web applications. NoSQL systems are also sometimes called "Not only SQL" to emphasize that they may support SQL-like query languages.

Many NoSQL stores compromise consistency (in the sense of the CAP theorem) in favor of availability, partition tolerance, and speed. Barriers to the greater adoption of NoSQL stores include the use of low-level query languages (instead of SQL, for instance the lack of ability to perform ad-hoc JOIN's across tables), lack of standardized interfaces, and huge previous investments in existing relational databases. Most NoSQL stores lack true ACID transactions, although a few recent systems, such as FairCom c-treeACE, Google Spanner (though technically a NewSQL database), FoundationDB, Symas LMDB and OrientDB have made them central to their designs. (See ACID and JOIN Support.) Instead they offer a concept of "eventual consistency" in which database changes are propagated to all nodes "eventually" (typically within milliseconds) so queries for data might not return updated data immediately.

Not all NoSQL systems live up to the promised "eventual consistency" and partition tolerance, but in experiments with network partitioning often exhibited lost writes and other forms of data loss.[11] Fortunately, some NoSQL systems provide concepts such as "Write Ahead Logging" to avoid data loss. Current relational databases also "do not allow referential integrity constraints to span databases" as well.

> *Explain the classical non-relational data models.*
### Classical non-relational data models

Basic classification based on data model, with examples:

* **Column(or Wide-column) model**: Accumulo, Cassandra, Druid, HBase, Vertica
	* Key-value model with schema
* **Document**: Clusterpoint, Apache CouchDB, Couchbase, DocumentDB, HyperDex, Lotus Notes, MarkLogic, MongoDB, OrientDB, Qizx
	* Works with set of documents, e.g. JSON strings
* **Key-value**: CouchDB, Oracle NoSQL Database, Dynamo, FoundationDB, HyperDex, MemcacheDB, Redis, Riak, FairCom c-treeACE, Aerospike, OrientDB, MUMPS
	* Works with set of key-value pairs
* **Graph(or Hierarchical key-value model**: Allegro, Neo4J, InfiniteGraph, OrientDB, Virtuoso, Stardog
	* Hierarchy of key-value pairs
* **Multi-model**: OrientDB, FoundationDB, ArangoDB, Alchemy Database, CortexDB

> *Give few examples of NoSQL databases and their pros and cons.*
### NoSQL database examples

In the above question are given examples for NoSQL databases. The Pors and Cons are:

* Pros
	* Still support CRUD operations
	* Create, Read, Update, Delete
	* Still support indexing and querying
	* Still supports concurrency and transactions
	* Highly optimized for append / retrieve
	* Great performance and scalability

* Cons
	* No data consistency
	* No database relations


text:
"""Main entry point for all experiments."""

import os
import sys
import anna.model.premade as models
import anna.data.dataset.reuters21578 as reuters
import anna.data.dataset.fullrcv1 as rcv1
import anna.data.dataset.bioasq as bioasq

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: main.py DATA_FOLDER [reuters|rcv1|bioasq]")
        exit(1)

    dataset = "reuters"
    if len(sys.argv) == 3:
        dataset = sys.argv[2]

    if dataset == "reuters":
        data = reuters
        folder = "model"
        val_size = 777
        epochs = 40
        shuffle = 10000
        eval_every = 100
    elif dataset == "rcv1":
        data = rcv1
        folder = "model-rcv1"
        val_size = 75000
        epochs = 5
        shuffle = 750000
        eval_every = 10000
    elif dataset == "bioasq":
        data = bioasq
        folder = "model-bioasq"
        val_size = 100000
        epochs = 2
        shuffle = 1000000
        eval_every = 100000
    else:
        raise ValueError("Unknown dataset: {}".format(dataset))

    # Resolve data folders
    data_dir = os.path.abspath(sys.argv[1])

    # Fetch and preprocess dataset
    train_docs, test_docs, unused_docs, labels = data.fetch_and_parse(data_dir)

    for builder in models.BEST:
        # Create default trainer
        model = builder(data_dir, labels, folder_name=folder)

        # Train and evaluate
        print("Model: {}".format(model))
        model.train(train_docs,
                    test_docs,
                    val_size=val_size,
                    epochs=epochs,
                    shuffle=shuffle,
                    eval_every=eval_every)

        # Delete to save memory
        del model


text:
module Api
  class CombatantsController < ApplicationController
    respond_to :json
    before_action :authenticate_user!
    skip_before_action :verify_authenticity_token

    expose :combatant

    def update
      combatant.update(combatant_params)
      respond_with :api, combatant
    end

    def destroy
      combatant.active = false
      combatant.save
      respond_with :api, combatant
    end

    def order
      order_params[:order].each do |order_param|
        combatant = Combatant.where(id: order_param[:id], user_id: current_user.id, active: true).first
        combatant&.update_attribute(:display_order, order_param[:display_order])
      end
      render json: { status: :ok, message: :success }
    end

    private

    def combatant_params
      params.require(:combatant).permit(:id, :user_id, :hit_points, :notes, :display_order, :active)
    end

    def order_params
      params[:combatants][:order] ||= []
      params.require(:combatants).permit(order: %i[id display_order])
    end
  end
end


text:
require "spec_helper"

describe "Setlistfm.artist" do
  let(:setlistfm) { Setlistfm.new }
  let(:mbid) { "65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab" }
  context "success" do
    let(:res) { setlistfm.artist mbid }
    it "has a request url" do
      expect(res.env.url.to_s).to eq "https://api.setlist.fm/rest/0.1/artist/65f4f0c5-ef9e-490c-aee3-909e7ae6b2ab.json"
    end
    it "is status code 200" do
      expect(res.status).to eq 200
    end
    context "body" do
      it "is a Hash class" do
        expect(res.body.class).to eq Hash
      end
      it "has artist key" do
        expect(res.body).to include "artist"
      end
    end
  end
  context "fail" do
    let(:setlistfm) { Setlistfm.new }
    it "mbid is nil" do
      expect{ setlistfm.artist() }.to raise_error ArgumentError
    end
    it "when invalid mbid" do
      expect{ setlistfm.artist("aaa") }.to raise_error Faraday::ParsingError
    end
    it "mbid is not found" do
      expect{ setlistfm.artist("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa") }.to raise_error Faraday::ParsingError
    end
  end
end


text:
/*
 * libChEBIj (c) University of Manchester 2015
 *
 * libChEBIj is licensed under the MIT License.
 *
 * To view a copy of this license, visit <http://opensource.org/licenses/MIT/>.
 */
package uk.ac.manchester.libchebi;

import java.io.*;
import java.text.*;
import java.util.*;

/**
 * @author neilswainston
 */
class CommentsParser extends FileParser
{
	/**
	 *
	 */
	private static CommentsParser parser;

	/**
	 *
	 */
	private List<List<Comment>> comments;

	/**
	 *
	 * @return singleton CommentsParser
	 * @throws IOException
	 */
	synchronized static CommentsParser getInstance() throws IOException
	{
		if( parser == null )
		{
			final File file = Downloader.getInstance().getFile( "comments.tsv" ); //$NON-NLS-1$
			parser = new CommentsParser( file );
		}

		return parser;
	}

	/**
	 *
	 * @param file
	 */
	private CommentsParser( final File file )
	{
		super( file );
	}

	/**
	 *
	 * @param chebiId
	 * @return comments
	 * @throws IOException
	 * @throws ParseException
	 */
	synchronized List<Comment> getComments( final int chebiId ) throws IOException, ParseException
	{
		return chebiId > -1 && chebiId < getComments().size() ? comments.get( chebiId ) : new ArrayList<Comment>();
	}

	/**
	 *
	 * @param chebiIds
	 * @return comments
	 * @throws IOException
	 * @throws ParseException
	 */
	synchronized List<Comment> getComments( final int[] chebiIds ) throws IOException, ParseException
	{
		final List<Comment> allComments = new ArrayList<>();

		for( int chebiId : chebiIds )
		{
			allComments.addAll( getComments( chebiId ) );
		}

		return allComments;
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see libchebi.parser.Parser#init()
	 */
	@Override
	protected void init() throws IOException, ParseException
	{
		// final int ID = 0;
		final int COMPOUND_ID = 1;
		final int CREATED_ON = 2;
		final int DATATYPE_ID = 3;
		final int DATATYPE = 4;
		final int TEXT = 5;

		final TreeMap<Integer,List<Comment>> commentsMap = new TreeMap<>();

		try ( BufferedReader reader = new BufferedReader( new FileReader( file ) ) )
		{
			String line = reader.readLine(); // Read header

			while( ( line = reader.readLine() ) != null )
			{
				final String[] tokens = line.split( "\\t" ); //$NON-NLS-1$
				ParserUtils.add( Integer.valueOf( tokens[ COMPOUND_ID ] ), commentsMap, new Comment( tokens[ DATATYPE_ID ], tokens[ DATATYPE ], tokens[ TEXT ], ParserUtils.parseDate( tokens[ CREATED_ON ] ) ) );
			}
		}

		comments = ParserUtils.mapToList( commentsMap );
	}

	/**
	 *
	 * @return List of comments, indexed by ChEBI id
	 * @throws IOException
	 * @throws ParseException
	 */
	private synchronized List<List<Comment>> getComments() throws IOException, ParseException
	{
		checkInit();
		return comments;
	}
}


text:
import json
from datetime import datetime

from puppetboard import app
from test import MockDbQuery

def test_json_daily_reports_chart_ok(client, mocker,
                                     mock_puppetdb_environments,
                                     mock_puppetdb_default_nodes):
    query_data = {
        'reports': [
            [{'status': 'changed', 'count': 1}]
            for i in range(app.app.config['DAILY_REPORTS_CHART_DAYS'])
        ]
    }

    dbquery = MockDbQuery(query_data)

    mocker.patch.object(app.puppetdb, '_query', side_effect=dbquery.get)

    rv = client.get('/daily_reports_chart.json')
    result_json = json.loads(rv.data.decode('utf-8'))

    assert 'result' in result_json
    assert (len(result_json['result']) ==
            app.app.config['DAILY_REPORTS_CHART_DAYS'])
    day_format = '%Y-%m-%d'
    cur_day = datetime.strptime(result_json['result'][0]['day'], day_format)
    for day in result_json['result'][1:]:
        next_day = datetime.strptime(day['day'], day_format)
        assert cur_day < next_day
        cur_day = next_day

    assert rv.status_code == 200


text:
/**
 * Autogenerated by Thrift Compiler (0.8.0)
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
package org.apache.hadoop.hbase.thrift2.generated;

import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;

import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * if no Result is found, row and columnValues will not be set.
 */
public class TResult implements org.apache.thrift.TBase<TResult, TResult._Fields>, java.io.Serializable, Cloneable {
  private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("TResult");

  private static final org.apache.thrift.protocol.TField ROW_FIELD_DESC = new org.apache.thrift.protocol.TField("row", org.apache.thrift.protocol.TType.STRING, (short)1);
  private static final org.apache.thrift.protocol.TField COLUMN_VALUES_FIELD_DESC = new org.apache.thrift.protocol.TField("columnValues", org.apache.thrift.protocol.TType.LIST, (short)2);

  private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
  static {
    schemes.put(StandardScheme.class, new TResultStandardSchemeFactory());
    schemes.put(TupleScheme.class, new TResultTupleSchemeFactory());
  }

  public ByteBuffer row; // optional
  public List<TColumnValue> columnValues; // required

  /** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
  public enum _Fields implements org.apache.thrift.TFieldIdEnum {
    ROW((short)1, "row"),
    COLUMN_VALUES((short)2, "columnValues");

    private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();

    static {
      for (_Fields field : EnumSet.allOf(_Fields.class)) {
        byName.put(field.getFieldName(), field);
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, or null if its not found.
     */
    public static _Fields findByThriftId(int fieldId) {
      switch(fieldId) {
        case 1: // ROW
          return ROW;
        case 2: // COLUMN_VALUES
          return COLUMN_VALUES;
        default:
          return null;
      }
    }

    /**
     * Find the _Fields constant that matches fieldId, throwing an exception
     * if it is not found.
     */
    public static _Fields findByThriftIdOrThrow(int fieldId) {
      _Fields fields = findByThriftId(fieldId);
      if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
      return fields;
    }

    /**
     * Find the _Fields constant that matches name, or null if its not found.
     */
    public static _Fields findByName(String name) {
      return byName.get(name);
    }

    private final short _thriftId;
    private final String _fieldName;

    _Fields(short thriftId, String fieldName) {
      _thriftId = thriftId;
      _fieldName = fieldName;
    }

    public short getThriftFieldId() {
      return _thriftId;
    }

    public String getFieldName() {
      return _fieldName;
    }
  }

  // isset id assignments
  private _Fields optionals[] = {_Fields.ROW};
  public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
  static {
    Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
    tmpMap.put(_Fields.ROW, new org.apache.thrift.meta_data.FieldMetaData("row", org.apache.thrift.TFieldRequirementType.OPTIONAL,
        new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING        , true)));
    tmpMap.put(_Fields.COLUMN_VALUES, new org.apache.thrift.meta_data.FieldMetaData("columnValues", org.apache.thrift.TFieldRequirementType.REQUIRED,
        new org.apache.thrift.meta_data.ListMetaData(org.apache.thrift.protocol.TType.LIST,
            new org.apache.thrift.meta_data.StructMetaData(org.apache.thrift.protocol.TType.STRUCT, TColumnValue.class))));
    metaDataMap = Collections.unmodifiableMap(tmpMap);
    org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(TResult.class, metaDataMap);
  }

  public TResult() {
  }

  public TResult(
    List<TColumnValue> columnValues)
  {
    this();
    this.columnValues = columnValues;
  }

  /**
   * Performs a deep copy on <i>other</i>.
   */
  public TResult(TResult other) {
    if (other.isSetRow()) {
      this.row = org.apache.thrift.TBaseHelper.copyBinary(other.row);
;
    }
    if (other.isSetColumnValues()) {
      List<TColumnValue> __this__columnValues = new ArrayList<TColumnValue>();
      for (TColumnValue other_element : other.columnValues) {
        __this__columnValues.add(new TColumnValue(other_element));
      }
      this.columnValues = __this__columnValues;
    }
  }

  public TResult deepCopy() {
    return new TResult(this);
  }

  @Override
  public void clear() {
    this.row = null;
    this.columnValues = null;
  }

  public byte[] getRow() {
    setRow(org.apache.thrift.TBaseHelper.rightSize(row));
    return row == null ? null : row.array();
  }

  public ByteBuffer bufferForRow() {
    return row;
  }

  public TResult setRow(byte[] row) {
    setRow(row == null ? (ByteBuffer)null : ByteBuffer.wrap(row));
    return this;
  }

  public TResult setRow(ByteBuffer row) {
    this.row = row;
    return this;
  }

  public void unsetRow() {
    this.row = null;
  }

  /** Returns true if field row is set (has been assigned a value) and false otherwise */
  public boolean isSetRow() {
    return this.row != null;
  }

  public void setRowIsSet(boolean value) {
    if (!value) {
      this.row = null;
    }
  }

  public int getColumnValuesSize() {
    return (this.columnValues == null) ? 0 : this.columnValues.size();
  }

  public java.util.Iterator<TColumnValue> getColumnValuesIterator() {
    return (this.columnValues == null) ? null : this.columnValues.iterator();
  }

  public void addToColumnValues(TColumnValue elem) {
    if (this.columnValues == null) {
      this.columnValues = new ArrayList<TColumnValue>();
    }
    this.columnValues.add(elem);
  }

  public List<TColumnValue> getColumnValues() {
    return this.columnValues;
  }

  public TResult setColumnValues(List<TColumnValue> columnValues) {
    this.columnValues = columnValues;
    return this;
  }

  public void unsetColumnValues() {
    this.columnValues = null;
  }

  /** Returns true if field columnValues is set (has been assigned a value) and false otherwise */
  public boolean isSetColumnValues() {
    return this.columnValues != null;
  }

  public void setColumnValuesIsSet(boolean value) {
    if (!value) {
      this.columnValues = null;
    }
  }

  public void setFieldValue(_Fields field, Object value) {
    switch (field) {
    case ROW:
      if (value == null) {
        unsetRow();
      } else {
        setRow((ByteBuffer)value);
      }
      break;

    case COLUMN_VALUES:
      if (value == null) {
        unsetColumnValues();
      } else {
        setColumnValues((List<TColumnValue>)value);
      }
      break;

    }
  }

  public Object getFieldValue(_Fields field) {
    switch (field) {
    case ROW:
      return getRow();

    case COLUMN_VALUES:
      return getColumnValues();

    }
    throw new IllegalStateException();
  }

  /** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
  public boolean isSet(_Fields field) {
    if (field == null) {
      throw new IllegalArgumentException();
    }

    switch (field) {
    case ROW:
      return isSetRow();
    case COLUMN_VALUES:
      return isSetColumnValues();
    }
    throw new IllegalStateException();
  }

  @Override
  public boolean equals(Object that) {
    if (that == null)
      return false;
    if (that instanceof TResult)
      return this.equals((TResult)that);
    return false;
  }

  public boolean equals(TResult that) {
    if (that == null)
      return false;

    boolean this_present_row = true && this.isSetRow();
    boolean that_present_row = true && that.isSetRow();
    if (this_present_row || that_present_row) {
      if (!(this_present_row && that_present_row))
        return false;
      if (!this.row.equals(that.row))
        return false;
    }

    boolean this_present_columnValues = true && this.isSetColumnValues();
    boolean that_present_columnValues = true && that.isSetColumnValues();
    if (this_present_columnValues || that_present_columnValues) {
      if (!(this_present_columnValues && that_present_columnValues))
        return false;
      if (!this.columnValues.equals(that.columnValues))
        return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    HashCodeBuilder builder = new HashCodeBuilder();

    boolean present_row = true && (isSetRow());
    builder.append(present_row);
    if (present_row)
      builder.append(row);

    boolean present_columnValues = true && (isSetColumnValues());
    builder.append(present_columnValues);
    if (present_columnValues)
      builder.append(columnValues);

    return builder.toHashCode();
  }

  public int compareTo(TResult other) {
    if (!getClass().equals(other.getClass())) {
      return getClass().getName().compareTo(other.getClass().getName());
    }

    int lastComparison = 0;
    TResult typedOther = (TResult)other;

    lastComparison = Boolean.valueOf(isSetRow()).compareTo(typedOther.isSetRow());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetRow()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.row, typedOther.row);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    lastComparison = Boolean.valueOf(isSetColumnValues()).compareTo(typedOther.isSetColumnValues());
    if (lastComparison != 0) {
      return lastComparison;
    }
    if (isSetColumnValues()) {
      lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.columnValues, typedOther.columnValues);
      if (lastComparison != 0) {
        return lastComparison;
      }
    }
    return 0;
  }

  public _Fields fieldForId(int fieldId) {
    return _Fields.findByThriftId(fieldId);
  }

  public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
    schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
  }

  public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
    schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
  }

  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder("TResult(");
    boolean first = true;

    if (isSetRow()) {
      sb.append("row:");
      if (this.row == null) {
        sb.append("null");
      } else {
        org.apache.thrift.TBaseHelper.toString(this.row, sb);
      }
      first = false;
    }
    if (!first) sb.append(", ");
    sb.append("columnValues:");
    if (this.columnValues == null) {
      sb.append("null");
    } else {
      sb.append(this.columnValues);
    }
    first = false;
    sb.append(")");
    return sb.toString();
  }

  public void validate() throws org.apache.thrift.TException {
    // check for required fields
    if (columnValues == null) {
      throw new org.apache.thrift.protocol.TProtocolException("Required field 'columnValues' was not present! Struct: " + toString());
    }
  }

  private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
    try {
      write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
    try {
      read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
    } catch (org.apache.thrift.TException te) {
      throw new java.io.IOException(te);
    }
  }

  private static class TResultStandardSchemeFactory implements SchemeFactory {
    public TResultStandardScheme getScheme() {
      return new TResultStandardScheme();
    }
  }

  private static class TResultStandardScheme extends StandardScheme<TResult> {

    public void read(org.apache.thrift.protocol.TProtocol iprot, TResult struct) throws org.apache.thrift.TException {
      org.apache.thrift.protocol.TField schemeField;
      iprot.readStructBegin();
      while (true)
      {
        schemeField = iprot.readFieldBegin();
        if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
          break;
        }
        switch (schemeField.id) {
          case 1: // ROW
            if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
              struct.row = iprot.readBinary();
              struct.setRowIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          case 2: // COLUMN_VALUES
            if (schemeField.type == org.apache.thrift.protocol.TType.LIST) {
              {
                org.apache.thrift.protocol.TList _list0 = iprot.readListBegin();
                struct.columnValues = new ArrayList<TColumnValue>(_list0.size);
                for (int _i1 = 0; _i1 < _list0.size; ++_i1)
                {
                  TColumnValue _elem2; // required
                  _elem2 = new TColumnValue();
                  _elem2.read(iprot);
                  struct.columnValues.add(_elem2);
                }
                iprot.readListEnd();
              }
              struct.setColumnValuesIsSet(true);
            } else {
              org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
            }
            break;
          default:
            org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
        }
        iprot.readFieldEnd();
      }
      iprot.readStructEnd();

      // check for required fields of primitive type, which can't be checked in the validate method
      struct.validate();
    }

    public void write(org.apache.thrift.protocol.TProtocol oprot, TResult struct) throws org.apache.thrift.TException {
      struct.validate();

      oprot.writeStructBegin(STRUCT_DESC);
      if (struct.row != null) {
        if (struct.isSetRow()) {
          oprot.writeFieldBegin(ROW_FIELD_DESC);
          oprot.writeBinary(struct.row);
          oprot.writeFieldEnd();
        }
      }
      if (struct.columnValues != null) {
        oprot.writeFieldBegin(COLUMN_VALUES_FIELD_DESC);
        {
          oprot.writeListBegin(new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, struct.columnValues.size()));
          for (TColumnValue _iter3 : struct.columnValues)
          {
            _iter3.write(oprot);
          }
          oprot.writeListEnd();
        }
        oprot.writeFieldEnd();
      }
      oprot.writeFieldStop();
      oprot.writeStructEnd();
    }

  }

  private static class TResultTupleSchemeFactory implements SchemeFactory {
    public TResultTupleScheme getScheme() {
      return new TResultTupleScheme();
    }
  }

  private static class TResultTupleScheme extends TupleScheme<TResult> {

    @Override
    public void write(org.apache.thrift.protocol.TProtocol prot, TResult struct) throws org.apache.thrift.TException {
      TTupleProtocol oprot = (TTupleProtocol) prot;
      {
        oprot.writeI32(struct.columnValues.size());
        for (TColumnValue _iter4 : struct.columnValues)
        {
          _iter4.write(oprot);
        }
      }
      BitSet optionals = new BitSet();
      if (struct.isSetRow()) {
        optionals.set(0);
      }
      oprot.writeBitSet(optionals, 1);
      if (struct.isSetRow()) {
        oprot.writeBinary(struct.row);
      }
    }

    @Override
    public void read(org.apache.thrift.protocol.TProtocol prot, TResult struct) throws org.apache.thrift.TException {
      TTupleProtocol iprot = (TTupleProtocol) prot;
      {
        org.apache.thrift.protocol.TList _list5 = new org.apache.thrift.protocol.TList(org.apache.thrift.protocol.TType.STRUCT, iprot.readI32());
        struct.columnValues = new ArrayList<TColumnValue>(_list5.size);
        for (int _i6 = 0; _i6 < _list5.size; ++_i6)
        {
          TColumnValue _elem7; // required
          _elem7 = new TColumnValue();
          _elem7.read(iprot);
          struct.columnValues.add(_elem7);
        }
      }
      struct.setColumnValuesIsSet(true);
      BitSet incoming = iprot.readBitSet(1);
      if (incoming.get(0)) {
        struct.row = iprot.readBinary();
        struct.setRowIsSet(true);
      }
    }
  }

}


text:
__tiny__ is an in-process document/object store for node.js.

It is largely inspired by [nStore](https://github.com/creationix/nstore),
however, its goal was to implement real querying which goes easy on the memory.

Tiny is very simple, there are no schemas, just store your objects. It supports
mongo-style querying, or alternatively a "mapreduce-like" interface similar to
CouchDB's views.

## Install

``` bash
$ npm install tiny
```

## How Tiny works...

Tiny takes advantage of the fact that, normally, when you query for records in
a database, you're only comparing small properties (<128b) in the query itself.
For example, when you query for articles on a weblog, you'll usually only be
comparing the timestamp of the article, the title, the author, the category,
the tags, etc. - pretty much everything except the content of the article
itself.

Tiny stores each document/object's property individually in the DB file and
caches all the small properties into memory when the DB loads, leaving anything
above 128b behind. When a query is performed, Tiny only lets you compare the
properties stored in memory, which is what you were going to do anyway. Once
the query is complete, Tiny will perform lookups on the FD to grab the large
properties and put them in their respective objects before results are returned
to you.

This my attempt at combining what I think the best aspects of nStore and
node-dirty are. node-dirty is incredibly fast and simple (everything is
in-memory), and nStore is very memory effecient, (but this only lasts until you
perform a query). node-tiny allows for queries that perform lookups on the db
file, and it selectively caches properties as well, so it's fast and easier on
memory.

## Example Querying

``` js
var Tiny = require('./tiny');
Tiny('articles.tiny', function(err, db) {
  var time = Date.now()
    , low = time - (60*60*1000)
    , high = time - (30*60*1000);

  // mongo-style query
  db.find({$or: [
    { timestamp: { $lte: low } },
    { timestamp: { $gte: high } }
  ]})
  .desc('timestamp')
  .limit(3)(function(err, results) {
    console.log('Results:', results);
  });

  // is equivalent to...
  db.fetch({
    desc: 'timestamp',
    limit: 3
  }, function(doc, key) {
    if (doc.timestamp <= low
        || doc.timestamp >= high) {
      console.log('Found:', key);
      return true;
    }
  }, function(err, results) {
    console.log('Results:', results);
  });
});
```

The mongo-style querying should be fairly self-explanatory. The second query is
supposed to be similar to a mapreduce interface, but it's the rough equivalent
of a `.filter` function.

Note: there is a `shallow` parameter for `.fetch`, `.find`, and `.get`, wherein
it will __only__ lookup properties that are under 128b in size. This is to go
easy on the memory. `.each` and `.all` are shallow by default, but they do have
a `deep` parameter, (which I don't recommend using).

## Other Usage

``` js
// save a document
db.set('myDocument', {
  title: 'a document',
  content: 'hello world'
}, function(err) {
  console.log('set!');
});

// .each will iterate through
// every object in the database
// it is shallow by default
db.each(function(doc) {
  console.log(doc.title);
});

// returns every object in the DB
// in an array, this is shallow
// by default
db.all(function(err, docs) {
  console.log(docs.length);
});

// remove a doc
db.remove('myDocument', function(err) {
  console.log('deleted');
});

// retrieve an object from the database
db.get('someOtherThing', function(err, data) {
  // data._key is a property which
  // holds the key of every object
  console.log('found:', data._key);
});

// updates the object
// without overwriting its other properties
db.update('article_1', {
  title: 'new title'
}, function(err) {
  console.log('done');
});

// close the file descriptor
db.close(function(err) {
  console.log('db closed');
});

// clean up the mess
db.compact(function(err) {
  console.log('done');
});

// dump the entire database to a JSON file
// in the same directory as the DB file
// (with an optional pretty-print parameter)
db.dump(true, function(err) {
  console.log('dump complete');
});
```

## Making data more memory efficient

Because of the way Tiny works, there are ways to alter your data to make it
more memory efficient. For example, if you have several properties on your
objects that aren't necessary to for queries, its best to nest them in an
object.

``` js
user: {
  name: 'joe',
  prop1: 'data',
  prop2: 'data',
  prop3: 'data'
}

user: {
  name: 'joe',
  data: {
    prop1: 'data',
    prop2: 'data',
    prop3: 'data'
  }
}
```

That way, the data will not be cached if it exceeds 128b collectively.
Eventually there may be an `ignore` method or an `index` method, which will be
explicitly inclusive or exclusive to which properties are cached and which
properties are able to be referenced within a query.

## Documentation

### Database
- [Construction](#construction)
- [dump](#dump)
- [close](#close)
- [kill](#kill)

### Querying
- [set](#set)
- [each](#each)
- [all](#all)

## Database

### Tiny(name, callback)
Creates and returns a database with the given name.

__Arguments__

- name - filename to store and load the Tiny database
- callback(err, db) - Called after the database file is opened and loaded

__Example__

``` js
var db;
Tiny('./articles.tiny', function(err, db_) {
  if (err) throw err;
  db = db_;
  ...
});
```

---------------------------------------

### dump(pretty, func) or dump(func)

Dumps the a database to a JSON file with the name as name.json. Pretty
specifies whether to indent each line with two spaces or not. Alternatively,
dump(func) can be called.

__Arguments__

- pretty - if true, the JSON file will be indented with two spaces
- func(err) - called after the dump is complete.

__Example__

``` js
db.dump(true, function(err) {
  console.log('dump complete');
});
```

---------------------------------------

### close(func)

Closes the Tiny database file handle. A new Tiny object must be made to reopen
the file.

__Arguments__

- func() - callback function after the database has been closed

__Example__

``` js
db.close(function(err) {
  console.log('db closed');
});
```

---------------------------------------

### kill(func)

Closes the Tiny database file, deletes the file and all the data in the
database, and then creates a new database with the same name and file.

__Arguments__

- func() - callback function after the database has been reloaded

__Example__

``` js
db.kill(function(err) {
  console.log('db has been destroyed and a new db has been loaded');
});
```

## Querying

### set(docKey, doc, func)

Saves a object `doc` to database under the key `docKey`. Ideally, docKey should
be 128b or smaller.

__Arguments__

- docKey - a key to search the database for
- doc - an object to save to the database under the given key
- func - callback function after the doc object has been saved to the database

__Example__

``` js
db.set('myDocument', {
  title: 'a document',
  content: 'hello world'
}, function(err) {
  console.log('set!');
});
```

---------------------------------------

### each(func, deep) or each(func)

Iterates through every object in the database.

__Arguments__

- func(doc) - Callback function that is called with every iterated object `doc`
  from the database
- done() - Callback to be executed after the iterations complete.
- deep - `true` if every object should be returned, `false` or unset if only
  cacheable objects should be returned (ones smaller than 128b)

__Example__

``` js
db.each(function(doc) {
  console.log(doc.title);
}, function() {
  console.log('done');
});
```

### Contribution and License Agreement

If you contribute code to this project, you are implicitly allowing your code
to be distributed under the MIT license. You are also implicitly verifying that
all code is your original work. `</legalese>`

## License

Copyright (c) 2011-2014, Christopher Jeffrey. (MIT License)

See LICENSE for more info.