text:
namespace blink {
namespace {

using css_parsing_utils::AtDelimiter;
using css_parsing_utils::AtIdent;
using css_parsing_utils::ConsumeAngle;
using css_parsing_utils::ConsumeIdSelector;
using css_parsing_utils::ConsumeIfDelimiter;
using css_parsing_utils::ConsumeIfIdent;

CSSParserContext* MakeContext() {
  return MakeGarbageCollected<CSSParserContext>(
      kHTMLStandardMode, SecureContextMode::kInsecureContext);
}

TEST(CSSParsingUtilsTest, BasicShapeUseCount) {
  auto dummy_page_holder =
      std::make_unique<DummyPageHolder>(gfx::Size(800, 600));
  Page::InsertOrdinaryPageForTesting(&dummy_page_holder->GetPage());
  Document& document = dummy_page_holder->GetDocument();
  WebFeature feature = WebFeature::kCSSBasicShape;
  EXPECT_FALSE(document.IsUseCounted(feature));
  document.documentElement()->setInnerHTML(
      "<style>span { shape-outside: circle(); }</style>");
  EXPECT_TRUE(document.IsUseCounted(feature));
}

TEST(CSSParsingUtilsTest, Revert) {
  EXPECT_TRUE(css_parsing_utils::IsCSSWideKeyword(CSSValueID::kRevert));
  EXPECT_TRUE(css_parsing_utils::IsCSSWideKeyword("revert"));
}

TEST(CSSParsingUtilsTest, ConsumeIdSelector) {
  {
    String text = "#foo";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_EQ("#foo", ConsumeIdSelector(range)->CssText());
  }
  {
    String text = "#bar  ";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_EQ("#bar", ConsumeIdSelector(range)->CssText());
    EXPECT_TRUE(range.AtEnd())
        << "ConsumeIdSelector cleans up trailing whitespace";
  }

  {
    String text = "#123";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    ASSERT_TRUE(range.Peek().GetType() == kHashToken &&
                range.Peek().GetHashTokenType() == kHashTokenUnrestricted);
    EXPECT_FALSE(ConsumeIdSelector(range))
        << "kHashTokenUnrestricted is not a valid <id-selector>";
  }
  {
    String text = "#";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_FALSE(ConsumeIdSelector(range));
  }
  {
    String text = " #foo";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_FALSE(ConsumeIdSelector(range))
        << "ConsumeIdSelector does not accept preceding whitespace";
    EXPECT_EQ(kWhitespaceToken, range.Peek().GetType());
  }
  {
    String text = "foo";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_FALSE(ConsumeIdSelector(range));
  }
  {
    String text = "##";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_FALSE(ConsumeIdSelector(range));
  }
  {
    String text = "10px";
    auto tokens = CSSTokenizer(text).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_FALSE(ConsumeIdSelector(range));
  }
}

double ConsumeAngleValue(String target) {
  auto tokens = CSSTokenizer(target).TokenizeToEOF();
  CSSParserTokenRange range(tokens);
  return ConsumeAngle(range, *MakeContext(), absl::nullopt)->ComputeDegrees();
}

double ConsumeAngleValue(String target, double min, double max) {
  auto tokens = CSSTokenizer(target).TokenizeToEOF();
  CSSParserTokenRange range(tokens);
  return ConsumeAngle(range, *MakeContext(), absl::nullopt, min, max)
      ->ComputeDegrees();
}

TEST(CSSParsingUtilsTest, ConsumeAngles) {
  const double kMaxDegreeValue = 2867080569122160;

  EXPECT_EQ(10.0, ConsumeAngleValue("10deg"));
  EXPECT_EQ(-kMaxDegreeValue, ConsumeAngleValue("-3.40282e+38deg"));
  EXPECT_EQ(kMaxDegreeValue, ConsumeAngleValue("3.40282e+38deg"));

  EXPECT_EQ(kMaxDegreeValue, ConsumeAngleValue("calc(infinity * 1deg)"));
  EXPECT_EQ(-kMaxDegreeValue, ConsumeAngleValue("calc(-infinity * 1deg)"));
  EXPECT_EQ(kMaxDegreeValue, ConsumeAngleValue("calc(NaN * 1deg)"));

  // Math function with min and max ranges

  EXPECT_EQ(-100, ConsumeAngleValue("calc(-3.40282e+38deg)", -100, 100));
  EXPECT_EQ(100, ConsumeAngleValue("calc(3.40282e+38deg)", -100, 100));
}

TEST(CSSParsingUtilsTest, AtIdent_Range) {
  String text = "foo,bar,10px";
  auto tokens = CSSTokenizer(text).TokenizeToEOF();
  CSSParserTokenRange range(tokens);
  EXPECT_FALSE(AtIdent(range.Consume(), "bar"));  // foo
  EXPECT_FALSE(AtIdent(range.Consume(), "bar"));  // ,
  EXPECT_TRUE(AtIdent(range.Consume(), "bar"));   // bar
  EXPECT_FALSE(AtIdent(range.Consume(), "bar"));  // ,
  EXPECT_FALSE(AtIdent(range.Consume(), "bar"));  // 10px
  EXPECT_FALSE(AtIdent(range.Consume(), "bar"));  // EOF
}

TEST(CSSParsingUtilsTest, AtIdent_Stream) {
  String text = "foo,bar,10px";
  CSSTokenizer tokenizer(text);
  CSSParserTokenStream stream(tokenizer);
  EXPECT_FALSE(AtIdent(stream.Consume(), "bar"));  // foo
  EXPECT_FALSE(AtIdent(stream.Consume(), "bar"));  // ,
  EXPECT_TRUE(AtIdent(stream.Consume(), "bar"));   // bar
  EXPECT_FALSE(AtIdent(stream.Consume(), "bar"));  // ,
  EXPECT_FALSE(AtIdent(stream.Consume(), "bar"));  // 10px
  EXPECT_FALSE(AtIdent(stream.Consume(), "bar"));  // EOF
}

TEST(CSSParsingUtilsTest, ConsumeIfIdent_Range) {
  String text = "foo,bar,10px";
  auto tokens = CSSTokenizer(text).TokenizeToEOF();
  CSSParserTokenRange range(tokens);
  EXPECT_TRUE(AtIdent(range.Peek(), "foo"));
  EXPECT_FALSE(ConsumeIfIdent(range, "bar"));
  EXPECT_TRUE(AtIdent(range.Peek(), "foo"));
  EXPECT_TRUE(ConsumeIfIdent(range, "foo"));
  EXPECT_EQ(kCommaToken, range.Peek().GetType());
}

TEST(CSSParsingUtilsTest, ConsumeIfIdent_Stream) {
  String text = "foo,bar,10px";
  CSSTokenizer tokenizer(text);
  CSSParserTokenStream stream(tokenizer);
  EXPECT_TRUE(AtIdent(stream.Peek(), "foo"));
  EXPECT_FALSE(ConsumeIfIdent(stream, "bar"));
  EXPECT_TRUE(AtIdent(stream.Peek(), "foo"));
  EXPECT_TRUE(ConsumeIfIdent(stream, "foo"));
  EXPECT_EQ(kCommaToken, stream.Peek().GetType());
}

TEST(CSSParsingUtilsTest, AtDelimiter_Range) {
  String text = "foo,<,10px";
  auto tokens = CSSTokenizer(text).TokenizeToEOF();
  CSSParserTokenRange range(tokens);
  EXPECT_FALSE(AtDelimiter(range.Consume(), '<'));  // foo
  EXPECT_FALSE(AtDelimiter(range.Consume(), '<'));  // ,
  EXPECT_TRUE(AtDelimiter(range.Consume(), '<'));   // <
  EXPECT_FALSE(AtDelimiter(range.Consume(), '<'));  // ,
  EXPECT_FALSE(AtDelimiter(range.Consume(), '<'));  // 10px
  EXPECT_FALSE(AtDelimiter(range.Consume(), '<'));  // EOF
}

TEST(CSSParsingUtilsTest, AtDelimiter_Stream) {
  String text = "foo,<,10px";
  CSSTokenizer tokenizer(text);
  CSSParserTokenStream stream(tokenizer);
  EXPECT_FALSE(AtDelimiter(stream.Consume(), '<'));  // foo
  EXPECT_FALSE(AtDelimiter(stream.Consume(), '<'));  // ,
  EXPECT_TRUE(AtDelimiter(stream.Consume(), '<'));   // <
  EXPECT_FALSE(AtDelimiter(stream.Consume(), '<'));  // ,
  EXPECT_FALSE(AtDelimiter(stream.Consume(), '<'));  // 10px
  EXPECT_FALSE(AtDelimiter(stream.Consume(), '<'));  // EOF
}

TEST(CSSParsingUtilsTest, ConsumeIfDelimiter_Range) {
  String text = "<,=,10px";
  auto tokens = CSSTokenizer(text).TokenizeToEOF();
  CSSParserTokenRange range(tokens);
  EXPECT_TRUE(AtDelimiter(range.Peek(), '<'));
  EXPECT_FALSE(ConsumeIfDelimiter(range, '='));
  EXPECT_TRUE(AtDelimiter(range.Peek(), '<'));
  EXPECT_TRUE(ConsumeIfDelimiter(range, '<'));
  EXPECT_EQ(kCommaToken, range.Peek().GetType());
}

TEST(CSSParsingUtilsTest, ConsumeIfDelimiter_Stream) {
  String text = "<,=,10px";
  CSSTokenizer tokenizer(text);
  CSSParserTokenStream stream(tokenizer);
  EXPECT_TRUE(AtDelimiter(stream.Peek(), '<'));
  EXPECT_FALSE(ConsumeIfDelimiter(stream, '='));
  EXPECT_TRUE(AtDelimiter(stream.Peek(), '<'));
  EXPECT_TRUE(ConsumeIfDelimiter(stream, '<'));
  EXPECT_EQ(kCommaToken, stream.Peek().GetType());
}

TEST(CSSParsingUtilsTest, ConsumeAnyValue) {
  struct {
    // The input string to parse as <any-value>.
    const char* input;
    // The expected result from ConsumeAnyValue.
    bool expected;
    // The serialization of the tokens remaining in the range.
    const char* remainder;
  } tests[] = {
      {"1", true, ""},
      {"1px", true, ""},
      {"1px ", true, ""},
      {"ident", true, ""},
      {"(([ident]))", true, ""},
      {" ( ( 1 ) ) ", true, ""},
      {"rgb(1, 2, 3)", true, ""},
      {"rgb(1, 2, 3", true, ""},
      {"!!!;;;", true, ""},
      {"asdf)", false, ")"},
      {")asdf", false, ")asdf"},
      {"(ab)cd) e", false, ") e"},
      {"(as]df) e", false, " e"},
      {"(a b [ c { d ) e } f ] g h) i", false, " i"},
      {"a url(() b", false, "url(() b"},
  };

  for (const auto& test : tests) {
    String input(test.input);
    SCOPED_TRACE(input);
    auto tokens = CSSTokenizer(input).TokenizeToEOF();
    CSSParserTokenRange range(tokens);
    EXPECT_EQ(test.expected, css_parsing_utils::ConsumeAnyValue(range));
    EXPECT_EQ(String(test.remainder), range.Serialize());
  }
}

}  // namespace
}  // namespace blink


text:
category: faq
faqtype: jail-support
published: true
title: When will they be released?
---
Generally, arrestees must be processed within 48 hours or within a "reasonable amount of time" of their arrest. [Cleveland Municipal Court](https://clevelandmunicipalcourt.org/) has [cleared their dockets and extended their hours](http://www.clevelandmunicipalcourt.org/rnc-week-special-instructions) from 8:30am to 4:30pm and 5:00am to 1:00am in order to speed up the processing of RNC arrestees. However, processing time still depends on how quickly the police and prosecutors complete the arrestees' charging paperwork.

**Please notify us if arrestees are being held for longer than 48 hours**. Upon being retained by the arrestees, we may be able fight in court to have them released.

redpajama_set_name: RedPajamaGithub


text:
#if DEVICE_ITM

#include "hal/itm_api.h"

void itm_init(void)
{
    /**
     * Initialization moved to system_nrf52840.c due to SoftDevice incompatibility.
     */
}

#endif


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Duss, Enum. Champ. Guadeloupe (Lons-le-Saunier) 65 (1903)

#### Original name
Sarcoscypha hirta (Schumach.)

### Remarks
null


text:
lua-live
========

This is a proof-of-concept modification of the [Lua programming
language](https://www.lua.org/).

It allows updating the behavior of a program while the program is executing.
Functions can even be updated if they contain loops which are currently
executing, or coroutines which are suspended in them.

Updates in this system are performed by sending the updated program source file
to the running virtual machine using ZeroMQ. The virtual machine then suspends
the executing program, and executes the updated version. Annotations in the
source code are used to record which functions are eligible for patching. After
the changes are recorded, the original program resumes executing. While it is
executing, on all backwards jumps the virtual machine attempts to transition
the current frame to an updated version of the function.

Note that as a proof-of-concept the system has several limitations. For
example, new constants cannot be used in the updated version of the function.

Example usage:

After installing ZeroMQ headers and building the system using make, load (`src/lua example/hello1.lua`) this program, which should output `Hello` repeatedly.

`hello1.lua:`
```lua
function main()
  while true do
    print('Hello')
  end
end

live.patch('main', main)

live.start(main)
```

Then, patch the program to version 2 (run `src/patch.py example/hello2.lua`).

`hello2.lua:`
```lua
world = ' World'

function main()
  while true do
    print('Hello' .. world)
  end
end

live.patch('main', main)

live.start(main)
```

The program should start outputing `Hello World`, after all buffers clear.


text:
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc

class ScoreScatterPNTestHarness(PyAPITestHarness):
    def _build_inputs(self):
        filt = openmc.Filter(type='cell', bins=(21, ))
        t1 = openmc.Tally(tally_id=1)
        t1.add_filter(filt)
        t1.add_score('scatter-0')
        t1.add_score('scatter-1')
        t1.add_score('scatter-2')
        t1.add_score('scatter-3')
        t1.add_score('scatter-4')
        t1.estimator = 'analog'
        t2 = openmc.Tally(tally_id=2)
        t2.add_filter(filt)
        t2.add_score('scatter-p4')
        self._input_set.tallies = openmc.TalliesFile()
        self._input_set.tallies.add_tally(t1)
        self._input_set.tallies.add_tally(t2)

        super(ScoreScatterPNTestHarness, self)._build_inputs()

    def _cleanup(self):
        super(ScoreScatterPNTestHarness, self)._cleanup()
        f = os.path.join(os.getcwd(), 'tallies.xml')
        if os.path.exists(f): os.remove(f)

if __name__ == '__main__':
    harness = ScoreScatterPNTestHarness('statepoint.10.*', True)
    harness.main()


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="array_report_reason">
        <item>@string/report_porn</item>
        <item>@string/report_violence</item>
        <item>@string/report_abuse</item>
        <item>@string/report_advertisement</item>
        <item>@string/report_politics</item>
        <item>@string/report_other</item>
    </string-array>
    <string-array name="array_upload_avatar">
        <item>@string/upload_avatar_local</item>
        <item>@string/upload_avatar_camera</item>
    </string-array>
    <string-array name="array_user_sex">
        <item>@string/male</item>
        <item>@string/female</item>
    </string-array>
    <string-array name="array_follow_tip">
        <item>@string/follow_tip_1</item>
        <item>@string/follow_tip_2</item>
    </string-array>
    <string-array name="array_share_tip">
        <item>@string/share_tip_1</item>
        <item>@string/share_tip_2</item>
    </string-array>
</resources>


text:
var ReactPDF = require('./react-pdf');

var pdfjs = require('pdfjs-dist');
require('pdfjs-dist/web/compatibility');

pdfjs.PDFJS.disableWorker = true;

module.exports = ReactPDF;


text:
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;
using System.Globalization;

public partial class Raport : Page
{
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        Settings settings = new Settings(this);
        this.Title = settings.TitleOnPage;
        titleLabel.Text = settings.TitleOnScreen;
    }
}


text:
var express = require('express')
  , h = require('../modules/application_helpers')
  , baseRoutes = require('./base')
  , user = require('./user')
  , blog = require('./blog')
  , survey = require('./survey')
  , landing = require('./landing')
  , surveyApp = require('./app/survey')
  , campaign = require('./app/campaign')
  , post = require('./app/post')
  , postcat = require('./app/post_category')
  , surveyAPI = require('./api/survey')
  , userAPI = require('./api/user')
  , postAPI = require('./api/post')
  , app = express();

var ApiToken = require('../modules/ApiToken');

// Preset for all Response
app.use('/', function(req, res, next) {
  res.locals.isMobile =  h.isMobile(req);
  res.locals.path = req.path;
  app.locals.user = req.user;
  next()
});

app.use('/', baseRoutes);
app.use('/account', user);

app.use('/blog', blog);
app.use('/s', survey);
app.use('/l', landing);

// Account Logged In Varify
app.use('/campaign', ensureAuthenticated);

app.use('/campaign', surveyApp);
app.use('/campaign', campaign);
app.use('/campaign', post);
app.use('/campaign', postcat);

// API Token Varify
app.use('/api', function(req, res, next) {
  var token = req.body.session_token || req.query.session_token || req.headers['session-token'];

  if (ApiToken.verify(token))  {
    if (req.isAuthenticated()) { return next() }
    return res.status(403).send({message: "Not Logged In."});
  } else {
    return res.status(403).send({
      success: false,
      message: 'Failed to authenticate token.'
    });
  }
});
app.use('/api', surveyAPI);
app.use('/api', userAPI);
app.use('/api', postAPI);

function ensureAuthenticated(req, res, next) {
  if (req.isAuthenticated()) {
    app.locals.token = ApiToken.generate();
    return next();
  }
  req.flash('error', "Please login!");
  res.redirect('/account/login')
}

module.exports = app;


text:
@interface LZEditTextTableViewController : UITableViewController
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) NSManagedObjectModel *currentModel;
@property (nonatomic, copy) NSString *keyString;
@end


text:
import base58
import json
from pygments import highlight
from pygments.lexers.data import JsonLexer
from pygments.formatters.terminal import TerminalFormatter

def dump(obj):
    j = json.dumps(stringify_refs(obj), indent=2)
    print highlight(j, JsonLexer(), TerminalFormatter())

def stringify_refs(obj):
    res = {}
    for k, v in obj.iteritems():
        if isinstance(v, dict):
            v = stringify_refs(v)
        if k == u'@link' and isinstance(v, basestring):
            try:
                v = base58.b58encode(v)
            except (ValueError, AttributeError, TypeError):
                pass
        res[k] = v
    return res


text:
Hej {USERNAME},

Ditt konto på "{SITENAME}" har inaktiverats, troligen på grund av ändringar som gjorts i din profil. För att kunna återaktivera ditt konto måste du klicka på länken nedan:

{U_ACTIVATE}

{EMAIL_SIG}


text:
package ml.dmlc.tvm;

import org.junit.Test;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

public class FunctionTest {
  @Test
  public void test_reg_sum_number() {
    Function.register("sum_number", new Function.Callback() {
      @Override public Object invoke(TVMValue... args) {
        long res = 0L;
        for (TVMValue arg : args) {
          res += arg.asLong();
        }
        return res;
      }
    });
    Function func = Function.getFunction("sum_number");
    TVMValue res = func.pushArg(10).pushArg(20).invoke();
    assertEquals(30, res.asLong());
    res.release();
    func.release();
  }

  @Test
  public void test_add_string() {
    Function func = Function.convertFunc(new Function.Callback() {
      @Override public Object invoke(TVMValue... args) {
        String res = "";
        for (TVMValue arg : args) {
          res += arg.asString();
        }
        return res;
      }
    });
    TVMValue res = func.pushArg("Hello").pushArg(" ").pushArg("World!").invoke();
    assertEquals("Hello World!", res.asString());
    res.release();
    func.release();
  }

  @Test
  public void test_sum_first_byte() {
    Function func = Function.convertFunc(new Function.Callback() {
      @Override public Object invoke(TVMValue... args) {
        byte[] bt = new byte[1];
        for (TVMValue arg : args) {
          bt[0] += arg.asBytes()[0];
        }
        return bt;
      }
    });
    TVMValue res = func.pushArg(new byte[]{1}).pushArg(new byte[]{2, 3}).invoke();
    assertArrayEquals(new byte[]{3}, res.asBytes());
    res.release();
    func.release();
  }

  @Test
  public void test_sum_ndarray() {
    final long[] shape = new long[]{2, 1};
    Function func = Function.convertFunc(new Function.Callback() {
      @Override public Object invoke(TVMValue... args) {
        double sum = 0.0;
        for (TVMValue arg : args) {
          NDArray arr = NDArray.empty(shape, new TVMType("float32"));
          arg.asNDArray().copyTo(arr);
          float[] nativeArr = arr.asFloatArray();
          for (int i = 0; i < nativeArr.length; ++i) {
            sum += nativeArr[i];
          }
          arr.release();
        }
        return sum;
      }
    });
    NDArray arr = NDArray.empty(shape, new TVMType("float32"));
    arr.copyFrom(new float[]{2f, 3f});
    TVMValue res = func.pushArg(arr).pushArg(arr).invoke();
    assertEquals(10.0, res.asDouble(), 1e-3);
    res.release();
    func.release();
  }

  @Test
  public void test_return_function() {
    Function myFunc = Function.convertFunc(new Function.Callback() {
      @Override public Object invoke(TVMValue... args) {
        final long y = args[0].asLong();
        return Function.convertFunc(new Function.Callback() {
          @Override public Object invoke(TVMValue... args) {
            final long x = args[0].asLong();
            return x + y;
          }
        });
      }
    });
    Function func = myFunc.pushArg(10).invoke().asFunction();
    TVMValue res = func.pushArg(20).invoke();
    assertEquals(30, res.asLong());
    func.release();
    myFunc.release();
  }
}


text:
#ifndef	_DB_TXN_H_
#define	_DB_TXN_H_

#if defined(__cplusplus)
extern "C" {
#endif

/* Operation parameters to the delayed commit processing code. */
typedef enum {
	TXN_CLOSE,		/* Close a DB handle whose close had failed. */
	TXN_REMOVE,		/* Remove a file. */
	TXN_TRADE,		/* Trade lockers. */
	TXN_TRADED		/* Already traded; downgrade lock. */
} TXN_EVENT_T;

struct __db_txnregion;	typedef struct __db_txnregion DB_TXNREGION;
struct __txn_logrec;	typedef struct __txn_logrec DB_TXNLOGREC;

/*
 * !!!
 * TXN_MINIMUM = (DB_LOCK_MAXID + 1) but this makes compilers complain.
 */
#define	TXN_MINIMUM	0x80000000
#define	TXN_MAXIMUM	0xffffffff	/* Maximum number of txn ids. */
#define	TXN_INVALID	0		/* Invalid transaction ID. */

#define	DEF_MAX_TXNS	100		/* Default max transactions. */
#define	TXN_NSLOTS	4		/* Initial slots to hold DB refs */

#define	TXN_PRIORITY_DEFAULT	DB_LOCK_DEFPRIORITY

/*
 * Internal data maintained in shared memory for each transaction.
 */
typedef struct __txn_detail {
	u_int32_t txnid;		/* current transaction id
					   used to link free list also */
	pid_t pid;			/* Process owning txn */
	db_threadid_t tid;		/* Thread owning txn */

	DB_LSN	last_lsn;		/* Last LSN written for this txn. */
	DB_LSN	begin_lsn;		/* LSN of begin record. */
	roff_t	parent;			/* Offset of transaction's parent. */
	roff_t	name;			/* Offset of txn name. */

	u_int32_t	nlog_dbs;	/* Number of databases used. */
	u_int32_t	nlog_slots;	/* Number of allocated slots. */
	roff_t		log_dbs;	/* Databases used. */

	DB_LSN	read_lsn;		/* Read LSN for MVCC. */
	DB_LSN	visible_lsn;		/* LSN at which this transaction's
					   changes are visible. */
	db_mutex_t	mvcc_mtx;	/* Version mutex. */
	u_int32_t	mvcc_ref;	/* Number of buffers created by this
					   transaction still in cache.  */

	u_int32_t	priority;	/* Deadlock resolution priority. */

	SH_TAILQ_HEAD(__tdkids)	kids;	/* Linked list of child txn detail. */
	SH_TAILQ_ENTRY		klinks;

	/* TXN_{ABORTED, COMMITTED PREPARED, RUNNING} */
	u_int32_t status;		/* status of the transaction */

#define	TXN_DTL_COLLECTED	0x1	/* collected during txn_recover */
#define	TXN_DTL_RESTORED	0x2	/* prepared txn restored */
#define	TXN_DTL_INMEMORY	0x4	/* uses in memory logs */
#define	TXN_DTL_SNAPSHOT	0x8	/* On the list of snapshot txns. */
	u_int32_t flags;

	SH_TAILQ_ENTRY	links;		/* active/free/snapshot list */

	u_int8_t gid[DB_GID_SIZE];	/* global transaction id */
	roff_t slots[TXN_NSLOTS];	/* Initial DB slot allocation. */
} TXN_DETAIL;

/*
 * DB_TXNMGR --
 *	The transaction manager encapsulates the transaction system.
 */
struct __db_txnmgr {
	/*
	 * These fields need to be protected for multi-threaded support.
	 *
	 * Lock list of active transactions (including the content of each
	 * TXN_DETAIL structure on the list).
	 */
	db_mutex_t mutex;
					/* List of active transactions. */
	TAILQ_HEAD(_chain, __db_txn)	txn_chain;

	u_int32_t n_discards;		/* Number of txns discarded. */

	/* These fields are never updated after creation, so not protected. */
	ENV	*env;			/* Environment. */
	REGINFO	 reginfo;		/* Region information. */
};

/* Macros to lock/unlock the transaction region as a whole. */
#define	TXN_SYSTEM_LOCK(env)						\
	MUTEX_LOCK(env, ((DB_TXNREGION *)				\
	    (env)->tx_handle->reginfo.primary)->mtx_region)
#define	TXN_SYSTEM_UNLOCK(env)						\
	MUTEX_UNLOCK(env, ((DB_TXNREGION *)				\
	    (env)->tx_handle->reginfo.primary)->mtx_region)

/*
 * DB_TXNREGION --
 *	The primary transaction data structure in the shared memory region.
 */
struct __db_txnregion {
	db_mutex_t	mtx_region;	/* Region mutex. */

	u_int32_t	maxtxns;	/* maximum number of active TXNs */
	u_int32_t	last_txnid;	/* last transaction id given out */
	u_int32_t	cur_maxid;	/* current max unused id. */

	db_mutex_t	mtx_ckp;	/* Single thread checkpoints. */
	DB_LSN		last_ckp;	/* lsn of the last checkpoint */
	time_t		time_ckp;	/* time of last checkpoint */

	DB_TXN_STAT	stat;		/* Statistics for txns. */

#define	TXN_IN_RECOVERY	 0x01		/* environment is being recovered */
	u_int32_t	flags;
					/* active TXN list */
	SH_TAILQ_HEAD(__active) active_txn;
	SH_TAILQ_HEAD(__mvcc) mvcc_txn;
};

/*
 * DB_COMMIT_INFO --
 *	Meta-data uniquely describing a transaction commit across a replication
 *	group.
 */
struct __db_commit_info {
	u_int32_t	version;	/* Stored format version. */
	u_int32_t	gen;		/* Replication master generation. */
	u_int32_t	envid;		/* Unique env ID of master. */
	DB_LSN		lsn;		/* LSN of commit log record. */
};

/*
 * DB_TXNLOGREC --
 *	An in-memory, linked-list copy of a log record.
 */
struct __txn_logrec {
	STAILQ_ENTRY(__txn_logrec) links;/* Linked list. */

	u_int8_t data[1];		/* Log record. */
};

/*
 * Log record types.  Note that these are *not* alphabetical.  This is
 * intentional so that we don't change the meaning of values between
 * software upgrades.
 *
 * EXPECTED, UNEXPECTED, IGNORE, and OK are used in the txnlist functions.
 * Here is an explanation of how the statuses are used.
 *
 * TXN_OK
 *	BEGIN records for transactions found on the txnlist during
 *	OPENFILES (BEGIN records are those with a prev_lsn of 0,0)
 *
 * TXN_COMMIT
 *	Transaction committed and should be rolled forward.
 *
 * TXN_ABORT
 *	This transaction's changes must be undone.  Either there was
 *	never a prepare or commit record for this transaction OR there
 *	was a commit, but we are recovering to a timestamp or particular
 *	LSN and that point is before this transaction's commit.
 *
 * TXN_PREPARE
 *	Prepare record, but no commit record is in the log.
 *
 * TXN_IGNORE
 *	Generic meaning is that this transaction should not be
 *	processed during later recovery passes.  We use it in a
 *	number of different manners:
 *
 *	1. We never saw its BEGIN record.  Therefore, the logs have
 *	   been reclaimed and we *know* that this transaction doesn't
 *	   need to be aborted, because in order for it to be
 *	   reclaimed, there must have been a subsequent checkpoint
 *	   (and any dirty pages for this transaction made it to
 *	   disk).
 *
 *	2. This is a child transaction that created a database.
 *	   For some reason, we don't want to recreate that database
 *	   (i.e., it already exists or some other database created
 *	   after it exists).
 *
 *	3. During recovery open of subdatabases, if the master check fails,
 *	   we use a TXN_IGNORE on the create of the subdb in the nested
 *	   transaction.
 *
 *	4. During a remove, the file with the name being removed isn't
 *	   the file for which we are recovering a remove.
 *
 * TXN_EXPECTED
 *	After a successful open during recovery, we update the
 *	transaction's status to TXN_EXPECTED.  The open was done
 *	in the parent, but in the open log record, we record the
 *	child transaction's ID if we also did a create.  When there
 *	is a valid ID in that field, we use it and mark the child's
 *	status as TXN_EXPECTED (indicating that we don't need to redo
 *	a create for this file).
 *
 *	When recovering a remove, if we don't find or can't open
 *	the file, the child (which does the remove) gets marked
 *	EXPECTED (indicating that we don't need to redo the remove).
 *
 * TXN_UNEXPECTED
 *	During recovery, we attempted an open that should have succeeded
 *	and we got ENOENT, so like with the EXPECTED case, we indicate
 *	in the child that we got the UNEXPECTED return so that we do redo
 *	the creating/deleting operation.
 *
 */
#define	TXN_OK		0
#define	TXN_COMMIT	1
#define	TXN_PREPARE	2
#define	TXN_ABORT	3
#define	TXN_IGNORE	4
#define	TXN_EXPECTED	5
#define	TXN_UNEXPECTED	6

#if defined(__cplusplus)
}
#endif

#include "dbinc_auto/txn_auto.h"
#include "dbinc_auto/txn_ext.h"
#endif /* !_DB_TXN_H_ */


text:
package com.mingzuozhibi.modules.core;

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface VarableRepository extends JpaRepository<Varable, Long> {

    Optional<Varable> findByKey(String key);

}


text:
(function($) {
  var uniqueId = (function() {
    var count = 0;
    return function() {
      return count++;
    };
  }());

  var isArray = window.Array.isArray || function(obj) {
    return window.toString.call(obj) == '[object Array]';
  };

  var isString = window.String.isString || function(obj) {
    return window.toString.call(obj) == '[object String]';
  };

  /**
   * Create our colorPicker function
  **/
  $.fn.colorPicker = function(options) {
    if (options === 'destroy') {
      return this.each(function() {
        var picker = $(this).data('colorPicker');
        if (picker) {
          picker.destroy();
          $(this).removeData('colorPicker');
        }
      });
    }

    return this.each(function() {
      var $elem = $(this);
      if (!$elem.data('colorPicker')) {
        $elem.data('colorPicker', new ColorPicker(this, options));
      }
    });
  };

  var ColorPicker = function(input, options) {

    var self = this;

    // Setup time. Clone new elements from our templates, set some IDs, make shortcuts, jazzercise.
    this.element = $(input);
    this.options = $.extend({}, this.defaults, options);
    this.initialColor = this.toHex(this.element.val() || this.options.pickerDefault);
    this.container = this.templates.container.clone();
    this.control = this.templates.control.clone();
    this.palette = this.templates.palette.clone();
    this.hexField = this.templates.hexField.clone();
    this.addSwatchButton = this.templates.addSwatchButton.clone();
    this.id = 'colorPicker-palette-' + uniqueId();

    if (this.options.customColors !== undefined) {
      //if customColors were explicitly supplied, assume that there is some external system persisting the colors and disable localStorage
      this.localStorageEnabled = false;
      this.customColors = this.options.customColors;
    }

    this.customColors = this.customColors.slice();

    this.buildPalette(this.options.colors);

    this.palette.attr('id', this.id);

    this.hexField.attr({
      id: 'colorPicker-addSwatchInput-' + uniqueId(),
      value: this.initialColor
    });

    this.hexField.on("keydown.colorPicker", $.proxy(this.hexFieldKeydown, this));
    this.hexField.on("keyup.colorPicker", $.proxy(this.hexFieldKeyup, this));

    this.addSwatchButton.on("click.colorPicker", $.proxy(this.addSwatchClick, this));

    this.element.on("change.colorPicker", $.proxy(this.inputChange, this));

    this.control.on("click.colorPicker", $.proxy(this.controlClick, this));

    $(window).on('colorPicker:addSwatch.' + this.id, $.proxy(this.addSwatch, this));

    this.container.append(this.hexField);
    this.container.append(this.addSwatchButton);
    this.container.appendTo(this.palette);

    this.changeColor(this.initialColor);

    $(document.body).append(this.palette);

    this.element.before(this.control);
  };

  ColorPicker.prototype.destroy = function() {
    this.element.off('.colorPicker');
    $(window).off('colorPicker:addSwatch.' + this.id);
    this.palette.find('.colorPicker-swatch-container a').off('.colorPicker');
    this.palette.remove();
    this.control.remove();
  };

  ColorPicker.prototype.hexFieldKeydown = function(event) {
    if (event.keyCode === 13) {
      var hexColor = this.toHex($(event.currentTarget).val());
      this.changeColor(hexColor ? hexColor: this.element.val());
    }
    if (event.keyCode === 27) {
      this.hidePalette();
    }
  };

  ColorPicker.prototype.hexFieldKeyup = function(event) {
    var hexColor = this.toHex($(event.currentTarget).val()) || this.element.val();
    this.previewColor(hexColor, false);
  };

  ColorPicker.prototype.createSwatch = function(color) {
    var swatchContainer = this.templates.swatch.clone();
    var swatchLink = swatchContainer.find('a');
    var swatch = swatchContainer.find('.colorPicker-swatch');

    if (color === 'transparent') {
      swatch.text('X');
    }
    else
      color = this.toHex(color);

    swatchContainer.attr('data-color', color);
    swatch.css('background', color);
    swatchLink.on('click.colorPicker', $.proxy(this.swatchLinkClick, this));

    return swatchContainer;
  };

  ColorPicker.prototype.swatchLinkClick = function(event) {
    event.preventDefault();
    $(event.currentTarget).trigger('colorPicker:swatchClick');
    return false;
  };

  ColorPicker.prototype.addSwatchClick = function(event) {
    var value = this.toHex(this.hexField.val());
    this.addSwatch(event, value);
  };

  ColorPicker.prototype.addSwatch = function(event, value) {
    if (value === false || this.options.colors.indexOf(value) !== -1 || this.customColors.indexOf(value) !== -1)
      return;

    var newSwatch = this.createSwatch(value);
    this.palette.find('.colorPicker-addSwatchContainer').before(newSwatch);

    this.customColors.push(value);

    this.element.trigger('colorPicker:addSwatch', value);
    //also trigger addswatch on window so that other colorpickers can listen for new swatches
    $(window).trigger('colorPicker:addSwatch', value);

    if (this.localStorageEnabled) {
      window.localStorage[this.customColorsKey] = window.JSON.stringify(this.customColors);
    }
  };

  ColorPicker.prototype.controlClick = function(event) {
    if (this.element.not(':disabled')) {
      this.togglePalette($('#' + this.id), $(event.currentTarget));
    }
  };

  ColorPicker.prototype.inputChange = function(event) {
    var value = this.toHex($(event.currentTarget).val());
    this.control.css("background-color", value);
    this.element.trigger('colorPicker:change', value);
  };

  ColorPicker.prototype.swatchClick = function(event) {
    var $swatchContainer = $(event.currentTarget);
    this.changeColor($swatchContainer.attr('data-color'));
  };

  ColorPicker.prototype.swatchMouseover = function(event) {
    this.previewColor($(event.currentTarget).attr('data-color'));
  };

  ColorPicker.prototype.swatchMouseout = function(event) {
    this.previewColor(this.element.val());
  };

  /**
   * Return a Hex color, convert an RGB value and return Hex, or return false.
   *
   * Inspired by http://code.google.com/p/jquery-color-utils
  **/
  ColorPicker.prototype.toHex = function(color) {
    // If we have a standard or shorthand Hex color, return that value.
    if (color.match(/[0-9A-F]{6}|[0-9A-F]{3}$/i)) {
      return (color.charAt(0) === "#") ? color: ("#" + color);

    // Alternatively, check for RGB color, then convert and return it as Hex.
    }
    else if (color.match(/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/)) {
      var c = ([parseInt(RegExp.$1, 10), parseInt(RegExp.$2, 10), parseInt(RegExp.$3, 10)]),
        pad = function(str) {
          if (str.length < 2) {
            for (var i = 0, len = 2 - str.length; i < len; i++) {
              str = '0' + str;
            }
          }

          return str;
        };

      if (c.length === 3) {
        var r = pad(c[0].toString(16)),
          g = pad(c[1].toString(16)),
          b = pad(c[2].toString(16));

        return '#' + r + g + b;
      }

    // Otherwise we wont do anything.
    }
    else {
      return false;
    }
  };

  /**
   * Check whether user clicked on the selector or owner.
  **/
  ColorPicker.prototype.checkMouse = function(event) {
    var selectorParent = $(event.target).parents("#" + this.palette.attr('id')).length;

    if (event.target === $(this.palette)[0] || event.target === this.element[0] || selectorParent > 0) {
      return;
    }

    this.hidePalette();
  };

  /**
   * Hide the color palette modal.
  **/
  ColorPicker.prototype.hidePalette = function() {
    //TODO better solution than checkMouse?
    $(document).off("mousedown.colorPicker" + this.id, $.proxy(this.checkMouse, this));

    this.palette.hide();
  };

  /**
   * Show the color palette modal.
  **/
  ColorPicker.prototype.showPalette = function() {
    var hexColor = this.element.val();

    var offset = this.control.offset();

    this.palette.css({
      top: Math.min(offset.top + this.control.outerHeight(), $(document).height() - this.palette.outerHeight()),
      left: Math.min(offset.left, $(document).width() - this.palette.outerWidth())
    });

    this.palette.show();

    $(document).on("mousedown.colorPicker" + this.id, $.proxy(this.checkMouse, this));
  };

  /**
   * Toggle visibility of the colorPicker palette.
  **/
  ColorPicker.prototype.togglePalette = function(palette, origin) {
    if (this.palette.is(':visible'))
      this.hidePalette();
    else
      this.showPalette(palette);
  };

  /**
   * Update the input with a newly selected color.
  **/
  ColorPicker.prototype.changeColor = function(value) {
    this.control.css("background-color", value);
    this.element.val(value).change();

    this.palette.find('.colorPicker-swatch-container.active').removeClass('active');
    this.palette.find('.colorPicker-swatch-container[data-color=' + value + ']').addClass('active');

    this.hidePalette();
  };

  /**
   * Preview the input with a newly selected color.
  **/
  ColorPicker.prototype.previewColor = function(value, setHexFieldValue) {
    if (setHexFieldValue === undefined || setHexFieldValue === true)
      this.hexField.val(value);
    this.control.css("background-color", value);
    this.element.trigger('colorPicker:preview', value);
  };

  /**
   * Build a color palette.
  **/
  ColorPicker.prototype.buildPalette = function(colors) {
    var self = this;
    var swatch;
    var callback = function(i, color) {
      swatch = self.createSwatch(color);
      swatch.appendTo(self.palette);
    };

    $.each(colors, callback);
    $.each(this.customColors, callback);

    this.palette.on('colorPicker:swatchClick.colorPicker', '.colorPicker-swatch-container', $.proxy(this.swatchClick, this));
    this.palette.on('mouseover.colorPicker', '.colorPicker-swatch-container', $.proxy(this.swatchMouseover, this));
    this.palette.on('mouseout.colorPicker', '.colorPicker-swatch-container', $.proxy(this.swatchMouseout, this));
  };

  ColorPicker.prototype.templates = {
    container: $('
'),
    control: $('

'),
    palette: $('
'),
    swatch : $('

'),
    hexField: $('<input type="text" class="input-small colorPicker-addSwatchInput" />'),
    addSwatchButton: $('<input type="button" class="btn colorPicker-addSwatchButton" value="add" />')
  };

  ColorPicker.prototype.customColorsKey = 'jquery.reallySimpleBootstrapColorPicker.customColors';

  try {
    ColorPicker.prototype.supportsLocalStorage = ('localStorage' in window && window['localStorage'] !== null);
  }
  catch (err) {
    ColorPicker.prototype.supportsLocalStorage = false;
  }

  try {
    ColorPicker.prototype.supportsJSON = ('JSON' in window && window['JSON'] !== null);
  }
  catch (err) {
    ColorPicker.prototype.supportsJSON = false;
  }

  if (ColorPicker.prototype.supportsLocalStorage && ColorPicker.prototype.supportsJSON) {
    ColorPicker.prototype.localStorageEnabled = true;
    try {
      ColorPicker.prototype.customColors = window.JSON.parse(window.localStorage[ColorPicker.prototype.customColorsKey]);
    }
    catch (err) {
    }
  }
  else
    ColorPicker.prototype.localStorageEnabled = false;

  if (ColorPicker.prototype.customColors === undefined || !isArray(ColorPicker.prototype.customColors)) {
    ColorPicker.prototype.customColors = [];
    window.localStorage[ColorPicker.prototype.customColorsKey] = window.JSON.stringify(ColorPicker.prototype.customColors);
  }

  /**
   * Default colorPicker options.
   *
   * They can be applied on a per-bound element basis like so:
   *
   * $('#element1').colorPicker({pickerDefault: 'efefef', transparency: true});
   * $('#element2').colorPicker({pickerDefault: '333333', colors: ['333333', '111111']});
   *
  **/
  ColorPicker.prototype.defaults = {
    // colorPicker default selected color.
    pickerDefault: "#FFFFFF",

    // Default color set.
    colors: [
      '#000000', '#993300', '#333300', '#000080', '#333399', '#333333', '#800000', '#FF6600',
      '#808000', '#008000', '#008080', '#0000FF', '#666699', '#808080', '#FF0000', '#FF9900',
      '#99CC00', '#339966', '#33CCCC', '#3366FF', '#800080', '#999999', '#FF00FF', '#FFCC00',
      '#FFFF00', '#00FF00', '#00FFFF', '#00CCFF', '#993366', '#C0C0C0', '#FF99CC', '#FFCC99',
      '#FFFF99', '#CCFFFF', '#99CCFF', '#FFFFFF'
    ]
  };

})($);


text:
package org.yuanheng.cookjson;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.Map;

import javax.json.JsonException;
import javax.json.stream.JsonGenerator;

/**
 * @author	Heng Yuan
 */
class BsonConfigHandler implements ConfigHandler
{
	private final static ConfigHandler s_instance = new BsonConfigHandler ();

	public static ConfigHandler getInstance ()
	{
		return s_instance;
	}

	private BsonConfigHandler ()
	{
	}

	@Override
	public CookJsonParser createParser (Map<String, ?> config, Reader reader)
	{
		throw new JsonException ("Cannot create a BSON parser from a Reader.");
	}

	@Override
	public CookJsonParser createParser (Map<String, ?> config, InputStream is)
	{
		BsonParser p = new BsonParser (is);

		boolean rootAsArray = false;
		Object obj = config.get (CookJsonProvider.ROOT_AS_ARRAY);
		if (obj != null)
			rootAsArray = "true".equals (obj.toString ());
		p.setRootAsArray (rootAsArray);

		int binaryFormat = BinaryFormat.BINARY_FORMAT_BASE64;
		obj = config.get (CookJsonProvider.BINARY_FORMAT);
		if (obj != null)
		{
			if (CookJsonProvider.BINARY_FORMAT_HEX.equals (obj.toString ()))
			{
				binaryFormat = BinaryFormat.BINARY_FORMAT_HEX;
			}
		}
		p.setBinaryFormat (binaryFormat);
		return p;
	}

	@Override
	public CookJsonParser createParser (Map<String, ?> config, InputStream is, Charset charset)
	{
		return createParser (config, is);
	}

	@Override
	public JsonGenerator createGenerator (Map<String, ?> config, Writer writer)
	{
		throw new JsonException ("Cannot create a BSON generator from a Writer.");
	}

	@Override
	public JsonGenerator createGenerator (Map<String, ?> config, OutputStream os)
	{
		BsonGenerator g = new BsonGenerator (os);

		boolean writeDouble = false;
		Object obj = config.get (CookJsonProvider.USE_DOUBLE);
		if (obj != null)
			writeDouble = "true".equals (obj.toString ());
		g.setUseDouble (writeDouble);

		return g;
	}

	@Override
	public JsonGenerator createGenerator (Map<String, ?> config, OutputStream os, Charset charset)
	{
		return createGenerator (config, os);
	}
}


text:
package nzbsplit.nzb;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author Sam Malone
 */
public class FileElement {

    private final List<String> groups;
    private final List<SegmentElement> segments;

    private long size = 0;
    private int date;
    private String poster;
    private String subject;

    public FileElement() {
        groups = new ArrayList<>();
        segments = new ArrayList<>();
    }

    /**
     * Add a segment that makes up this file
     * @param segment SegmentElement
     */
    public void addSegment(SegmentElement segment) {
        segments.add(segment);
        size += segment.getBytes();
    }

    /**
     * Add a usenet group that this file resides in e.g. alt.binaries.newzbin
     * @param group Usenet group
     */
    public void addUsenetGroup(String group) {
        groups.add(group);
    }

    public List<String> getUsenetGroups() {
        return groups;
    }

    /**
     * Gets an unmodifiable list of segments
     * @return
     */
    public List<SegmentElement> getSegments() {
        return Collections.unmodifiableList(segments);
    }

    public String getPoster() {
        return poster;
    }

    public void setPoster(String poster) {
        this.poster = poster;
    }

    /**
     * Get the date as a unix timestamp
     * @return date as a unix timestamp
     */
    public int getDate() {
        return date;
    }

    /**
     * Set the date
     * @param date Unix timestamp
     */
    public void setDate(int date) {
        this.date = date;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * Get the file size in bytes
     * @return file size in bytes
     */
    public long getFileSize() {
        return size;
    }

    /**
     * Sort the segments by segment number
     */
    public void sortSegments() {
        Collections.sort(segments);
    }

}


text:
require File.join(File.dirname(__FILE__), '..', 'test_helper')

class ForecastConditionTest < ActiveSupport::TestCase

  def setup
    @object = Regentanz::Conditions::Forecast.new
  end

  test "should define setters and getters" do
    [:condition, :style, :icon, :day_of_week, :high, :low].each do |attr|
      assert_respond_to @object, attr
      assert_respond_to @object, :"#{attr}="
    end
  end

  test "should initialize with attributes hash" do
    attributes = {
      "high"        => "31",
      "condition"   => "Vereinzelt Regen",
      "icon"        => "http://www.google.com/ig/images/weather/chance_of_rain.gif",
      "day_of_week" =>"Do.",
      "low"         => "16",
      "style"       => "chance-of-rain"
    }

    obj = Regentanz::Conditions::Forecast.new(attributes)
    assert_equal 31, obj.high
    assert_equal "Vereinzelt Regen", obj.condition
    assert_equal "http://www.google.com/ig/images/weather/chance_of_rain.gif", obj.icon
    assert_equal "Do.", obj.day_of_week
    assert_equal 16, obj.low
    assert_equal "chance-of-rain", obj.style
  end

end


text:
<?php if(!defined('cfih') or !cfih) die('This file cannot be directly accessed.');

/***
 * Error Codes
 *
 * 100 - empty source
 *
 * 110 - Image can not be found or the server with the image on has denied access - _T("site_upload_err_no_image");
 * 111 - The image url is not Valid
 *
 * 120 - Image format(mime) not accepted - _T("site_upload_types_accepted")
 * 121 - Image to small (pixels) - _T("site_upload_to_small")
 * 122 - Image to big (pixels) - _T("site_upload_to_big")
 * 123 - image file size to big (kb) - _T("site_upload_size_accepted")
 * 124 - error opening image
 * 125 - error moving image - _T("site_upload_err")
 *
 */

	/***
	* image format class/functions
	*/
	require CFLIBPATH.'psd.class.php'; //imagecreatefrompsd()
	//require CFLIBPATH.'ico.class.php'; //imagecreatefromico() // not working that good :(
	require CFLIBPATH.'bmp.class.php'; //imagecreatefrombmp()

	/***
	 * require gif split / merge classes
	 */
	require CFLIBPATH.'gifsplit.php';

class upload {

// image upload
	public $accepted_formats = array('image/bmp'=>'bmp','image/gif'=>'gif','image/jpg'=>'jpg','image/jpeg'=>'jpg','image/png'=>'png');
	public $max_filesize = 512000; // 500k
	public $min_dimensions = 10;
	public $max_dimensions = 3300;
	public $image_id_length = 4;
	public $upload_dir;
	public $temp_dir;
	public $info; // image info
	private $source;
	private $base_source;

	private $img_resource;
	public $error_code = false;

// duplicates/fingerprinting
	public $dup_size = 32;// Sets the width and height of the thumbnail sized image we use for deep comparison.
	public $dup_thumbWidth = 150;// Width for thumbnail images we use for fingerprinting.
	public $sensitivity = 2;// Sets how sensitive the fingerprinting will be. Higher numbers are less sensitive (more likely to match). Floats are allowed.
	public $deviation = 1;// Sets how much deviation is tolerated between two images when doing an thorough comparison.

// Image Resized
	private $imageResized;
	private $showMLimit = false;
	private $MemoryLimit = false;
	private $TweakFactor = 1.8;
	private $stretch = false;
	private $transparency = true;
	private $smaller = false;

	private $ani_gif = false;
	private $ani_delays;
	private $ani_imageResized;
	private $ani_transparent;
	private $ani_disposal;
	private $ani_allow = true;

	public function destroyImage(){
		@imagedestroy($this->img_resource);
		@imagedestroy($this->imageResized);
		unset($this->info);
		unset($this->source);
	}

	/***
	 * Grab the source
	 */
	function __construct($source) {
		$this->base_source = $source;
	}

	/***
	 * process
	 */
	public function process($multiupload = null){

		// fix multiupload $_FILES array
		//if(isset($this->base_source['name'][$multiupload])){
                if(is_array($this->base_source)){
			$this->source = array(
								'name'			=> $this->base_source['name'][$multiupload],
								'type'			=> $this->base_source['type'][$multiupload],
								'tmp_name'	=> $this->base_source['tmp_name'][$multiupload],
								'error'			=> $this->base_source['error'][$multiupload],
								'size'			=> $this->base_source['size'][$multiupload]
									);
		}else{
			$this->source = $this->base_source;
		}

	 // check for empty source
		if(empty($this->source)){
			$this->error_code = 100;
			return false;
		}

	// size error
		if(!empty($this->source['error']) && $this->source['error'] == 2){
			$this->error_code = 123;
			return false;
		}

	// check type of source (url|image $_file)
		if(!empty($this->source['name']) && strlen($this->source['name']) >4){
			return  $this->image_checks();
		}

		return  $this->url_process();
	}

	/***
	 * url_process
	 * copys the image from a url and save it to temp dir
	 */
	private function url_process(){

	// First url verification
		if(empty($this->source) || is_array($this->source) || !preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $this->source)) {
			$this->error_code = 111;
			return false;
		}

		$this->info['URL'] = $this->source; // this lets finish_upload know to copy and not move_uploaded_file
		$destination = $this->temp_dir.'temp_'.$this->create_hash(32); // name temp

	// get image for url
		$ch = curl_init($this->source);
		$fp = fopen($destination, "wb");
		$options = array(CURLOPT_FILE => $fp,CURLOPT_HEADER => false,CURLOPT_RETURNTRANSFER => true,CURLOPT_AUTOREFERER => true,CURLOPT_TIMEOUT => 120);
		curl_setopt_array($ch, $options);
		curl_setopt($ch, CURLOPT_FILE, $fp);
		curl_exec($ch);
		fclose($fp);
	// Check for 404 (file not found).
		$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
                $content_length = curl_getinfo($ch,CURLINFO_CONTENT_LENGTH_DOWNLOAD);
		curl_close($ch);
		if($httpCode == 404) {
			@unlink($destination);
		}

	// check temp file got saved
		if(!file_exists($destination)){
			$this->error_code = 110;
			return false;
		}

	// set source for file_proces
		$this->source = Array ('name' =>  basename($this->source),	'type' =>  $content_type,	'tmp_name' => $destination,	'error' =>  0,	'size' => $content_length );

	// check for errors (if so remove temp image)
		if(!$this->image_checks()){
			unlink($destination);
			return false;
		}
		return true;
	}

	/***
	 * image_checks
	 * checks image file
	 */
	private  function image_checks(){

		// setup image var
			$pieces = explode("?", $this->source['name']);
			$this->info['full_name'] = $pieces[0];

			$pathInfo = pathinfo($this->source['name']);
			$this->info['name'] = $pathInfo['filename'];
			$this->info['tmp_name'] = $this->source['tmp_name'];

			$imgSize = @getimagesize($this->info['tmp_name']);
			$this->info['width'] = $imgSize[0];
			$this->info['height'] = $imgSize[1];

		 //check the mime type & set image extension (we do not check the extension
			if(!$this->info['ext'] = $this->get_extension($imgSize['mime'])){
				$this->error_code = 120;
				return false;
			}

		//min size(pixels)
			if ($this->info['width'] < $this->min_dimensions || $this->info['height'] < $this->min_dimensions ){
				$this->error_code = 121;
				return false;
			}

		// max size(pixels)
			if ($this->info['width'] > $this->max_dimensions || $this->info['height'] > $this->max_dimensions ){
				$this->error_code = 122;
				return false;
			}

		//Check file size (kb)
			$this->info['size'] = ($this->source['size'] < 1?@filesize($this->info['tmp_name']):$this->source['size']);
			if($this->info['size'] > $this->max_filesize){
				$this->error_code = 123;
				return false;
			}

		// now open image
			if(!$this->img_resource = $this->openImage($this->info['tmp_name'])){
				$this->error_code = 124;
				return false;
			}

			unset($this->source);
		// return checks ok
			return true;
	}

	/***
	 * finish_upload
	 * finishes the upload process by setings save
	 * name and moving file tho the image folder.
	 */
	public function finish_upload($adminUpload = null){
		//New random name
			$this->info['id'] = $this->create_hash($this->image_id_length,true);
		//random delete ID
			$this->info['did'] = $this->info['id'].$this->create_hash(6);
		//Image address
			$this->info['new'] = $this->info['id'].'.'.$this->info['ext'];
			$this->info['address'] = $this->upload_dir.$this->info['new'];

		// convert BMP to JPG and PSD/ICO to PNG
			$converttypes =  array(
								'bmp'=>'jpg',
								'psd'=>'png',
								'ico'=>'png'
									);
			if(isset($converttypes[$this->info['ext']])){
			//Reset Image address
				$this->info['ext'] = $converttypes[$this->info['ext']];
				$this->info['new'] = $this->info['id'].'.'.$this->info['ext'];
				$this->info['address'] = $this->upload_dir.$this->info['new'];
				$this->imageConvert($this->info['address'],($this->info['ext'] == 'bmp'?90:60),null,true);
				$this->info['contenttype'] = ($this->info['ext'] == 'bmp'?IMAGETYPE_JPEG:IMAGETYPE_PNG);
			// remove temp file
				if(is_file($this->info['tmp_name'])){
					unlink($this->info['tmp_name']);
				}
			}
		//move image from remote server
			elseif((isset($this->info['URL']) && !empty($this->info['URL'])) || !is_null($adminUpload)){
				copy($this->info['tmp_name'],$this->info['address']);
				unlink($this->info['tmp_name']);
			}
		//move uploaded image
			else{
				move_uploaded_file($this->info['tmp_name'],$this->info['address']);
			}

		// check that the file moved ok
			if(!file_exists($this->info['address'])){
				$this->error_code = 125;
				return false;
			}

		// return uploaded done
			return true;
	}

	/***
	 * Open image resource
	 */
	private function openImage($src){
		if($this->MemoryLimit)$this->setMemoryForImage($src,$this->TweakFactor);
		switch( ( $this->info['contenttype'] = exif_imagetype($src))){
			case IMAGETYPE_PNG:
				$img = imagecreatefrompng($src);
				break;
			case IMAGETYPE_GIF:
				$img = $this->imagecreatefrom_gif($src);
				break;
			case IMAGETYPE_JPEG:
				$img = @imagecreatefromjpeg($src);
				break;
			case IMAGETYPE_BMP:
				$img = @ImageCreateFromBMP($src);
				break;
			case IMAGETYPE_PSD:
				$img = @imagecreatefrompsd($src);
				break;
		//	case IMAGETYPE_ICO:
		//		$img = imagecreatefrom_ico($src);
		//		break;
			default:
				$img = false;
				break;
		}
		return $img;
	}

	/***
	 * imagecreatefrom_gif
	 *	opens a Gif file
	 */
	private function imagecreatefrom_gif($src) {
		if($this->ani_allow && $this->ani_gif = $this->is_ani($src)){
			$gif = new GIFDecoder(file_get_contents($src));
			$img = $gif->GIFGetFrames();
			foreach ($img as $k => $frame){
				$img[$k] = imagecreatefromstring($frame);
				if($k===0){
					$img_sizex = imagesx($img[$k]);
					$img_sizey = imagesy($img[$k]);
				}elseif($img_sizex <> imagesx($img[$k]) || $img_sizey <> imagesy($img[$k])){
					unset($img);
					$this->ani_gif = false;
					$this->ani_offset = null;
					break;
				}
			}
		}

		if(!$this->ani_gif || count($img) <= 0){
			$img = imagecreatefromgif($src);
			$this->ani_gif = false;
		}else{
		// set var when 100%
			$this->ani_delays = $gif->GIFGetDelays();
			$this->ani_disposal = $gif->GIFGetDisposal();
			$this->ani_transparent['r'] = $gif->GIFGetTransparentR ( );
			$this->ani_transparent['g'] = $gif->GIFGetTransparentG ( );
			$this->ani_transparent['b'] = $gif->GIFGetTransparentB ( );
		}
		return $img;
	}

	/***
	 * is_ani
	 *	checks to see if a gif image is animated or not
	 */
	private function is_ani($filename) {
		if(!is_file($filename)) return false;
		return (bool)preg_match('/\x00\x21\xF9\x04.{4}\x00(\x2C|\x21)/s', file_get_contents($filename), $m);
	}

	/***
	 *   Fingerprint
	 *
	 *   This function analyses the filename passed to it and
	 *   returns an md5 checksum of the file's histogram.
	 */
	public function fingerprint() {

	// Create thumbnail sized copy for fingerprinting
		$ratio = $this->dup_thumbWidth / $this->info['width'];
		$newwidth = $this->dup_thumbWidth;
		$newheight = round($this->info['height'] * $ratio);
		$smallimage = imagecreatetruecolor($newwidth, $newheight);
		if(!$this->ani_gif)
			imagecopyresampled($smallimage, $this->img_resource, 0, 0, 0, 0, $newwidth, $newheight, $this->info['width'], $this->info['height']);
		else
			imagecopyresampled($smallimage, $this->img_resource[0], 0, 0, 0, 0, $newwidth, $newheight, $this->info['width'], $this->info['height']);
		$palette = imagecreatetruecolor(1, 1);
		$gsimage = imagecreatetruecolor($newwidth, $newheight);

	// Convert each pixel to greyscale, round it off, and add it to the histogram count
		$numpixels = $newwidth * $newheight;
		$histogram = array();
		for ($i = 0; $i < $newwidth; $i++) {
			for ($j = 0; $j < $newheight; $j++) {
				$pos = imagecolorat($smallimage, $i, $j);
				$cols = imagecolorsforindex($smallimage, $pos);
				$r = $cols['red'];
				$g = $cols['green'];
				$b = $cols['blue'];
				// Convert the colour to greyscale using 30% Red, 59% Blue and 11% Green
				$greyscale = round(($r * 0.3) + ($g * 0.59) + ($b * 0.11));
				$greyscale++;
				$value = (round($greyscale / 16) * 16) -1;
				@$histogram[$value]++;
			}
		}

	// Normalize the histogram by dividing the total of each colour by the total number of pixels
		$normhist = array();
		foreach ($histogram as $value => $count) {
			$normhist[$value] = $count / $numpixels;
		}

	// Find maximum value (most frequent colour)
		$max = 0;
		for ($i=0; $i<255; $i++) {
			if (@$normhist[$i] > $max) {
				$max = $normhist[$i];
			}
		}

	// Create a string from the histogram (with all possible values)
		$histstring = "";
		for ($i = -1; $i <= 255; $i = $i + 16) {
			$h = @(@$normhist[$i] / $max) * $this->sensitivity;
			if ($i < 0) {
				$index = 0;
			} else {
				$index = $i;
			}
			$height = round($h);
			$histstring .= $height;
		}

	// Destroy all the images that we've created
		imagedestroy($smallimage);
		imagedestroy($palette);
		imagedestroy($gsimage);

	// Generate an md5sum of the histogram values and return it
		return $this->info['fingerprint'] = md5($histstring);

	}

	/***
	 *   Are Duplicates
	 *
	 *   This function compares two images by resizing them
	 *   to a common size and then analysing the colours of
	 *   each pixel and calculating the difference between
	 *   both images for each colour channel and returns
	 *   an index representing how similar they are.
	 */
	public function are_duplicates($file2) {
	// Load in both images and resize them
		$image1_small = $this->dup_resizeImage();
		$image2_small = $this->dup_resizeImage($file2);

	// Compare the pixels of each image and figure out the colour difference between them
		$difference =0;
		for ($x = 0; $x < $this->dup_size; $x++) {
			for ($y = 0; $y < $this->dup_size; $y++) {
				$image1_color = imagecolorsforindex($image1_small,
				imagecolorat($image1_small, $x, $y));
				$image2_color = imagecolorsforindex($image2_small,
				imagecolorat($image2_small, $x, $y));
				$difference +=  abs($image1_color['red'] - $image2_color['red']) +
								abs($image1_color['green'] - $image2_color['green']) +
								abs($image1_color['blue'] - $image2_color['blue']);
			}
		}
		$difference = $difference / 256;

		if ($difference <= $this->deviation) {
			return true;
		} else {
			return false;
		}
	}

	/***
	 * dup_resizeImage
	 * used for Are Duplicates only
	 */
	private function dup_resizeImage($originalImage=null){
		$imageResized = imagecreatetruecolor($this->dup_size,$this->dup_size);
		if(!is_null($originalImage)){
			list($width, $height) = getimagesize($originalImage);
			$imageTmp = $this->openImage($originalImage);
		}else{
			$width = $this->info['width'];
			$height = $this->info['height'];
			if(!$this->ani_gif) $imageTmp = $this->img_resource;
			else $imageTmp = $this->img_resource[0];
		}
		imagecopyresampled($imageResized, $imageTmp, 0, 0, 0, 0, $this->dup_size,$this->dup_size, $width, $height);
		return $imageResized;
	}

	/***
	 * reszieImage
	 * used to to make thumbs
	 */
	public function resizeImage($newWidth, $newHeight, $option="auto"){
	//Get optimal width and height - based on $option
		$dimArr = $this->getDimensions($newWidth, $newHeight, $option);
	// check for ani gif
		if($this->ani_gif){
			$this->ani_resizeImage($newWidth, $newHeight,$dimArr['optimalWidth'],$dimArr['optimalHeight'], $option);
		}
	// all other image resizing
		else{
			$this->imageResized = imagecreatetruecolor($dimArr['optimalWidth'], $dimArr['optimalHeight']);//  Resample - create image canvas of x, y size
			if($this->transparency && (($this->info['contenttype'] == IMAGETYPE_GIF) || ($this->info['contenttype'] == IMAGETYPE_PNG)))	$this->setTransparency();
			imagecopyresized($this->imageResized, $this->img_resource, 0, 0, 0, 0, $dimArr['optimalWidth'], $dimArr['optimalHeight'], $this->info['width'], $this->info['height']);
			if ($option == 'crop') $this->crop($dimArr['optimalWidth'], $dimArr['optimalHeight'], $newWidth, $newHeight);// if option is 'crop', then crop too
		}
	}

	/***
	 * ani_reszieImage
	 * used to to make animated thumbs
	 */
	public function ani_resizeImage($newWidth, $newHeight,$optimalWidth,$optimalHeight, $option="auto"){
		foreach($this->img_resource as $k => $oldimg){
			$this->imageResized = null;
			$this->imageResized = imagecreatetruecolor($optimalWidth, $optimalHeight);// Resample - create image canvas of x, y size
			$this->setTransparency($oldimg);
			imagecopyresized($this->imageResized, $oldimg, 0, 0, 0, 0, $optimalWidth, $optimalHeight, $this->info['width'], $this->info['height']);
			if ($option == 'crop') $this->crop($optimalWidth, $optimalHeight, $newWidth, $newHeight);// if option is 'crop', then crop too
			$this->ani_imageResized[] =	$this->imageResized;
		}
	}

	private function getDimensions($newWidth, $newHeight, $option){

		if ($newHeight > $this->info['height'] && $newWidth > $this->info['width'] && !$this->stretch){
		//already smaller than the thumbnail
			$optimalWidth = $this->info['width'];
			$optimalHeight= $this->info['height'];
		}
		else{
			switch ($option){
				case 'exact':
					$optimalWidth = $newWidth;
					$optimalHeight= $newHeight;
					break;
				case 'portrait':
					$optimalWidth = $this->getSizeByFixedHeight($newHeight);
					$optimalHeight= $newHeight;
					break;
				case 'landscape':
					$optimalWidth = $newWidth;
					$optimalHeight= $this->getSizeByFixedWidth($newWidth);
					break;
				case 'auto':
					$optionArray = $this->getSizeByAuto($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
					break;
				case 'crop':
					$optionArray = $this->getOptimalCrop($newWidth, $newHeight);
					$optimalWidth = $optionArray['optimalWidth'];
					$optimalHeight = $optionArray['optimalHeight'];
					break;
			}
		}
		return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
	}

	private function getSizeByFixedHeight($newHeight){
		$ratio = $this->info['width'] / $this->info['height'];
		$newWidth = $newHeight * $ratio;
		return $newWidth;
	}

	private function getSizeByFixedWidth($newWidth){
		$ratio = $this->info['height'] / $this->info['width'];
		$newHeight = $newWidth * $ratio;
		return $newHeight;
	}

	private function getSizeByAuto($newWidth, $newHeight){
		if ($this->info['height'] < $this->info['width']){
		// *** Image to be resized is wider (landscape)
			$optimalWidth = $newWidth;
			$optimalHeight= $this->getSizeByFixedWidth($newWidth);
		}elseif ($this->info['height'] > $this->info['width']){
		// *** Image to be resized is taller (portrait)
			$optimalWidth = $this->getSizeByFixedHeight($newHeight);
			$optimalHeight= $newHeight;
		}else{
		// *** Image to be resizerd is a square
			if ($newHeight < $newWidth) {
				$optimalWidth = $newWidth;
				$optimalHeight= $this->getSizeByFixedWidth($newWidth);
			} else if ($newHeight > $newWidth) {
				$optimalWidth = $this->getSizeByFixedHeight($newHeight);
				$optimalHeight= $newHeight;
			} else {
				// *** Sqaure being resized to a square
				$optimalWidth = $newWidth;
				$optimalHeight= $newHeight;
			}
		}
		return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
	}

	private function getOptimalCrop($newWidth, $newHeight){

		$heightRatio = $this->info['height'] / $newHeight;
		$widthRatio  = $this->info['width'] /  $newWidth;

		if ($heightRatio < $widthRatio) {
			$optimalRatio = $heightRatio;
		} else {
			$optimalRatio = $widthRatio;
		}

		$optimalHeight = $this->info['height'] / $optimalRatio;
		$optimalWidth  = $this->info['width']  / $optimalRatio;

		return array('optimalWidth' => $optimalWidth, 'optimalHeight' => $optimalHeight);
	}

	private function crop($optimalWidth, $optimalHeight, $newWidth, $newHeight){
		if (($newHeight < $this->info['height'] || $newWidth < $this->info['width']) || $this->stretch){
			// *** Find center - this will be used for the crop
			$cropStartX = ( $optimalWidth / 2) - ( $newWidth /2 );
			$cropStartY = ( $optimalHeight/ 2) - ( $newHeight/2 );

			$crop = $this->imageResized;
			//imagedestroy($this->imageResized);

			// *** Now crop from center to exact requested size
			$this->imageResized = imagecreatetruecolor($newWidth , $newHeight);
			imagecopyresampled($this->imageResized, $crop , 0, 0, $cropStartX, $cropStartY, $newWidth, $newHeight , $newWidth, $newHeight);
		}
	}

	private function setTransparency($img_res = null){
		$transparencyIndex = @imagecolortransparent((is_null($img_res)?$this->img_resource:$img_res));
		if ($transparencyIndex >= 0) {
			$transparencyColor = @imagecolorsforindex((is_null($img_res)?$this->img_resource:$img_res), $transparencyIndex);
			$transparencyIndex = imagecolorallocate($this->imageResized, $transparencyColor['red'], $transparencyColor['green'], $transparencyColor['blue']);
			imagealphablending($this->imageResized, false);
			imagesavealpha($this->imageResized, true);
			imagepalettecopy($this->imageResized,(is_null($img_res)?$this->img_resource:$img_res));
			imagefill($this->imageResized, 0, 0, $transparencyIndex);
			imagecolortransparent($this->imageResized, $transparencyIndex);
		}elseif ($this->info['contenttype'] == IMAGETYPE_PNG) {
			imagealphablending($this->imageResized, false);
			$color = imagecolorallocatealpha($this->imageResized, 0, 0, 0, 127);
			imagefill($this->imageResized, 0, 0, $color);
			imagesavealpha($this->imageResized, true);
		  }
	}

	/***
	 * Convert image then Save the image
	 * $savePath - save Path ( /img_dir/imagename.jpg)
	 * $saveQuality - image save quality ( 1 - 100 png and jpg only)
	 * $saveExt - save extension(type) (IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_JPEG)
	 */
	public function imageConvert($savePath,$saveQuality=100,$saveExt=null, $main_resource=false){
		$this->imageResized = $this->img_resource;
		$this->saveImage($savePath,$saveQuality,$saveExt,$main_resource);
	}

	/***
	 * Save the image to a different location
	 * $savePath - save Path ( /img_dir/imagename.jpg)
	 * $saveQuality - image save quality ( 1 - 100 png and jpg only)
	 * $saveExt - save extension(type) (IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_JPEG)
	 * $main_resource - set saved imge resource to $img_resource (used for resizing the upload image)
	 */
	public function saveImage($savePath,$saveQuality=100,$saveExt=null, $main_resource=false){

		if(is_null($saveExt)){
			// *** Get extension
			$extension = strrchr($savePath, '.');
			$extension = strtolower($extension);
			switch($extension){
				case '.jpg':
				case '.jpeg':
					$saveExt = IMAGETYPE_JPEG;
					break;
				case '.gif':
					$saveExt = IMAGETYPE_GIF;
					break;
				case '.png':
					$saveExt = IMAGETYPE_PNG;
					break;
				default:
					$saveExt = IMAGETYPE_PNG;
					break;
			}
		}

	// check that we need to save or copy
		if($this->smaller && ($saveExt == $this->info['contenttype'])){
			copy($this->info['address'],$savePath); // copy image
			$this->smaller = false; // reset
			return true;
		}

		switch($saveExt){
			case IMAGETYPE_PNG:
				$scaleQuality = round(($saveQuality/100) * 9); // Scale quality from 0-100 to 0-9
				$invertScaleQuality = 9 - $scaleQuality; // Invert quality setting as 0 is best, not 9
				imagepng($this->imageResized, $savePath, $invertScaleQuality);
				break;
			case IMAGETYPE_GIF:
				$this->image_gif($savePath);
				break;
			case IMAGETYPE_JPEG:
				imagejpeg($this->imageResized, $savePath, $saveQuality);
				break;
		}

		if($main_resource){
			$this->img_resource = $this->imageResized;
			$this->info['width']  = @imagesx($this->img_resource);
			$this->info['height'] = @imagesy($this->img_resource);
		}
		else{
			@imagedestroy($this->imageResized);
			$this->ani_imageResized = null;
		}

	}

	/***
	 * image_gif
	 * Save a gif image file
	 */
	private function image_gif($savePath){
		if($this->ani_gif && is_array($this->ani_imageResized) && count($this->ani_imageResized) > 1){
			$newa = array();
			foreach($this->ani_imageResized as $i){
				ob_start();
				imagegif($i);
				$gifdata = ob_get_clean();
				$newa[] = $gifdata;
			}

			if($gifmerge = new GIFEncoder($newa, $this->ani_delays, 9999, $this->ani_disposal, $this->ani_transparent['r'], $this->ani_transparent['g'], $this->ani_transparent['b'], "bin")){
				FWrite(FOpen($savePath, "wb"), $gifmerge->GetAnimation() );
			}else{
				imagegif($this->ani_imageResized[0], $savePath);
			}
        }else{
			imagegif($this->imageResized, $savePath);
		}
	}

	/***
	 * Settings functions
	 */
	public function stretchSmallImages($var=true){$this->stretch = $var;}
	public function DontkeepImageTransparency($var=false){ $this->transparency = $var;}
	public function show_MemoryLimit ($var=false){ $this->showMLimit = ($var?true:false);}
	public function set_Memory_Limit ($var=false){$this->setMemoryLimit = ($var?true:false);}
	public function set_Tweak_Factor($var=1.8){$this->TweakFactor = ((int)$var?$var:1.8);}
	public function set_accepted_formats($var){$this->accepted_formats = $var;}
 	public function set_max_filesize($var){$this->max_filesize = $var; }
	public function set_min_dimensions($var){$this->min_dimensions = $var;}
 	public function set_max_dimensions($var){$this->max_dimensions = $var;}
	public function set_upload_dir($var){$this->upload_dir = $var;}
	public function set_temp_dir($var){$this->temp_dir = $var;}
	public function set_allow_animation($var){$this->ani_allow = ($var?true:false);}
	public function set_id_length($var=4){$this->image_id_length = ((int)$var?$var:4);}

	/***
	 * Get file ext from mine
	 * $imagetype - image/png (file mine)
	 * $requireDot - false|true
	 */
	private function get_extension($imagetype, $requireDot = false){
		if(empty($imagetype)) return false;
		if(isset($this->accepted_formats[$imagetype])) return ($requireDot ? '.' : '').$this->accepted_formats[$imagetype];
		return false;
	}

	/***
	 * very simple hash function to generate a random string
	 * Number of Possible Combinations
	 *		3 digit code 46656
	 *		4 digit code 1679616
	 *		5 digit code 60466176
	 */
	private function create_hash($length=5,$check=false){
		$valid	= false;
		$hash	= '';
		while(!$valid){
			for($i=0;$i<$length;++$i){
			// if you want to add letters you will have to change the id to varchar instead of int
				$possibleValues = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			// pick a random character from the possible ones
	    		$hash .= substr($possibleValues, mt_rand(0, strlen($possibleValues)-1), 1);

			}
			$valid = true;
			if($check){
				// checks if the hash allready exists in the db
				$files = glob($this->upload_dir.$hash.".{jpg,gif,png}", GLOB_BRACE);
				if(!empty($files)){
					$valid = false;
				}
			}
		}
		return $hash;
	}

	public function __destruct() {
		foreach ($this as $key => $value) {
			unset($this->$key);
		}
	}

}

/***
 * Missing functions
 */
if( ! function_exists('exif_imagetype') ){
	function exif_imagetype ( $f ){
		if ( false !== ( list(,,$type,) = getimagesize( $f ) ) )
			return $type;
		return IMAGETYPE_PNG; // meh
	}
}


text:
package abstractfactory.lab;

public class AdultsPackFactory implements GiftFactory {

	@Override
	public AbstractBagGift createBagGift() {
		// TODO Auto-generated method stub
		return new ReusableShopper();
	}

	@Override
	public AbstractBoxGift createBoxGift() {
		// TODO Auto-generated method stub
		return new PlainPaper();
	}

	@Override
	public AbstractWrapGift createWrapGift() {
		// TODO Auto-generated method stub
		return new EverydayValue();
	}

}


text:
import { Response } from '@angular/http';
import { Component,Input,Output,EventEmitter } from '@angular/core';
import { Router,ActivatedRoute } from '@angular/router';
import { AbstractControl } from '@angular/forms';
import { RegistrationInfo } from './shared/registrationInfo';
import { LoginInfo } from './shared/loginInfo';
import { RecoveryInfo } from './shared/recoveryInfo';
import { UsersService } from '../shared/services/users.service';
import { User } from '../shared/models/user';

@Component({
    selector: 'mrp-loginRegister',
    moduleId: module.id,
    templateUrl: './loginRegister.component.html',
    styleUrls: ['./loginRegister.component.css']
})
export class LoginRegisterComponent{
    pageTitle: string = 'Login Page';
    errorMsg: string;
    activeForm: number = 0;
    logInfo: LoginInfo = new LoginInfo();
    regInfo: RegistrationInfo = new RegistrationInfo();
    recInfo: RecoveryInfo = new RecoveryInfo();

    constructor(private _usersService:UsersService,private _route:ActivatedRoute,private _router:Router){
        let id = +this._route.snapshot.params['form'];
        if(id >= 0 && id < 3)
            this.activeForm = id;
    }

    submit() {
        if(this.activeForm == 0){
            this._usersService.loginSubmit(this.logInfo)
                .subscribe((res:Response) => res.ok ? this.saveLoginInfo(res.json()) : this.errorMsg = res.json().error,
                        (error:any) => this.errorMsg = error);
        }
        else if(this.activeForm == 1){
            this._usersService.registrationSubmit(this.regInfo)
                .subscribe((res:Response) => res.ok ? this.activeForm = 0 : this.errorMsg = 'Registration Failed',
                        (error:any) => this.errorMsg = error);
        }
        else{
            this._usersService.recoverySubmit(this.recInfo)
                .subscribe((res:Response) => res.ok ? this.errorMsg = 'new password has been sent to your email' : this.errorMsg = 'Recovery Failed',
                        (error:any) => this.errorMsg = error);
        }
    }

    saveLoginInfo(res:any): void{
        sessionStorage.setItem('token', JSON.stringify({ token:res.access_token, username:this.logInfo.Username }));
        this._router.navigate(['./findPatient']);
    }
}


text:
package db

import "net/url"

const (
	MarkIncomplete = "0"
	MarkComplete   = "1"
)

// DatabaseConfig defines config for database
type DatabaseConfig struct {
	Type          string      `toml:"type"`
	Path          interface{} `toml:"path"`
	MaxCacheSize  int         `toml:"max_cache_size"`
	CacheLifetime int         `toml:"cache_lifetime"`
}

// DatabaseStats represents the count of each bucket
type DatabaseStats struct {
	Packages  int
	Marks     int
	Documents int
	Files     int
}

// BarePackage represents the basis elements for package
type BarePackage struct {
	ID       string
	Revision string
}

type transactionable interface {
	Commit() error
	Rollback() error
}

// PocketStore represents the database factory interface
type PocketStore interface {
	Connect() error
	Close()
	Init()
	IsInitialized() bool
	GetItemCount(string) int
	GetSequence() int
	SetSequence(int)
	GetCountOfMarks(string) int
	GetIncompletePackages() []*BarePackage
	GetRevision(string) string
	GetDocument(string, bool) (string, []byte, error)
	GetAllFiles() map[string][]*url.URL
	AcquireTx() transactionable
	PutPackage(transactionable, string, string, bool, bool) error
	DeletePackage(string)
	PutCompleted(transactionable, *BarePackage, string, string, []*url.URL) bool
}

// StoreType represents the type for database store
type StoreType int

const (
	// BoltStore uses boltdb as a database backend
	BoltStore StoreType = 1 << iota
	// GormStore uses gorm as a database backend controller
	GormStore
)


text:
package app.arsh.omniknightapp.model.conductor;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import app.arsh.omniknightapp.presenter.BasePresenter;
import app.arsh.omniknightapp.presenter.MainActivityPresenter;
import app.arsh.omniknightapp.view.utils.GeneralUtils;
import java.util.HashMap;

/**
 * Created by arash on 1/31/17.
 */
public class Conductor<T extends BasePresenter> implements Application.ActivityLifecycleCallbacks {

  private static Conductor ourInstance = new Conductor();
  private HashMap<String, T> presenterContainer = new HashMap<>();
  private ConductorActivityLifeCycleListener activityListener;
  private AppCompatActivity activity;
  public static Conductor getInstance() {
    return ourInstance;
  }

  private Conductor() {
  }

  public void setCurrentActivity(AppCompatActivity appCompatActivity) {
    this.activity = appCompatActivity;
    this.activity.getApplication().registerActivityLifecycleCallbacks(this);
  }

  public void addPresenter(T presenter) {
    this.presenterContainer.put(presenter.getClass().getSimpleName(), presenter);
  }

  public T getPresenter(Class classType) {
    return this.presenterContainer.get(classType.getSimpleName());
  }

  public Boolean connectionAvailable() {
    if (GeneralUtils.isNetworkAvailable(activity)) {
      return true;
    }
    else {
      ((MainActivityPresenter)getPresenter(MainActivityPresenter.class)).showNoInternetConnection();
      return false;
    }
  }

  @Override public void onActivityCreated(Activity activity, Bundle bundle) {
    if (activityListener != null) {
      activityListener.activityStateChanged(ActivityLifeCycle.onActivityCreated);
    }
  }

  @Override public void onActivityStarted(Activity activity) {
    if (activityListener != null) {
      activityListener.activityStateChanged(ActivityLifeCycle.onActivityStarted);
    }
  }

  @Override public void onActivityResumed(Activity activity) {
    if (activityListener != null) {
      activityListener.activityStateChanged(ActivityLifeCycle.onActivityResumed);
    }
  }

  @Override public void onActivityPaused(Activity activity) {
    if (activityListener != null) {
      activityListener.activityStateChanged(ActivityLifeCycle.onActivityPaused);
    }
  }

  @Override public void onActivityStopped(Activity activity) {
    if (activityListener != null) {
      activity.getApplication().unregisterActivityLifecycleCallbacks(this);
      activityListener.activityStateChanged(ActivityLifeCycle.onActivityStopped);
    }
  }

  @Override public void onActivitySaveInstanceState(Activity activity, Bundle bundle) {
    if (activityListener != null) {
      activityListener.activityStateChanged(ActivityLifeCycle.onActivitySaveInstanceState);
    }
  }

  @Override public void onActivityDestroyed(Activity activity) {
    if (activityListener != null) {
      activityListener.activityStateChanged(ActivityLifeCycle.onActivityDestroyed);
    }
  }
}


text:
<tb-grid server-url="{{serverUrl}}" require-authentication="false" page-size="10">
     <tb-grid-table>
        <tb-column-definitions>
            <tb-column name="ID">
                <tb-column-header>
                    {{label}}
                </tb-column-header>
            </tb-column>
            <tb-column name="Name">
                <tb-column-header>
                    {{label}}
                </tb-column-header>
            </tb-column>
        </tb-column-definitions>

        <tb-row-set>
            <tb-row-template ng-repeat="row in $component.rows" row-model="row">
                <tb-cell-template column-name="ID">
                    {{row.ID}}
                </tb-cell-template>
                <tb-cell-template column-name="Name">
                    {{row.Name}}
                </tb-cell-template>
            </tb-row-template>
        </tb-row-set>
    </tb-grid-table>

    <tb-page-size-selector></tb-page-size-selector>
</tb-grid>