text:
<?php
/**
 * top.php
 *
 * Author: pixelcave
 *
 * The first block of code used in every page of the template
 * Start of html,  tag, as well as the header of the page are included here
 *
 */
?>
<!DOCTYPE html>

        <meta charset="utf-8">

        <title><?php echo $template['title'] ?></title>

        <meta name="description" content="<?php echo $template['description'] ?>">
        <meta name="author" content="<?php echo $template['author'] ?>">
        <meta name="robots" content="noindex, nofollow">

        <meta name="viewport" content="width=device-width,initial-scale=1">

        <link rel="shortcut icon" href="img/favicon.ico">
        <link rel="apple-touch-icon" href="img/apple-touch-icon.png">
        <link rel="apple-touch-icon" sizes="57x57" href="img/apple-touch-icon-57x57-precomposed.png">
        <link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72-precomposed.png">
        <link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114-precomposed.png">
        <link rel="apple-touch-icon-precomposed" href="img/apple-touch-icon-precomposed.png">

        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:400,400italic,700,700italic">

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

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

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

        <?php if ($template['theme']) { ?>
        <link id="theme-link" rel="stylesheet" href="css/themes/<?php echo $template['theme']; ?>.css">
        <?php } ?>

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

    <body<?php if ($template['layout'] == 'fixed') echo ' class="fixed"'; ?>>

            <header class="navbar navbar-inverse<?php if ($template['header'] == 'fixed-top') echo ' navbar-fixed-top'; else if ($template['header'] == 'fixed-bottom') echo ' navbar-fixed-bottom'; ?>">

Web Design

This is a headline

Another headline

Headlines keep coming!

Web Developent

New headline

Another one

All News

Latest Tweets

Michaeljust now

Web design all the way!

Monica3 min ago

Download free PSDs at http://bit.ly/YUs4SQ

Steven45 min ago

Be sure to check out my portfolio!

Tim1 hour ago

Get all our themes for free for the next 2 hours! #freebies

                                    1

Latest Messages

George2 min ago

Thanks for your help! The tutorial really helped me a lot!

Mike6 hours ago

The logo is ready, have a look and let me know what you think!

Julia1 day ago

We should better consider our social media marketing strategy!

View All Messages

                                    1
                                    2

System

20 min ago

Support system is down for maintenance!

3 hours ago

PHP upgrade started!

5 hours ago

1 support ticket just opened!

Project #3

3 weeks ago

Project #3 published successfully!

1 month ago

Milestone #3 achieved!

John Doe joined the project!

1 year ago

This is an old notification

View All Notifications

                                         Refresh

                                         User Profile

                                         App Settings

                                         Log out


text:
[![Latest Version](https://img.shields.io/github/release/ThrusterIO/socket-client.svg?style=flat-square)]
(https://github.com/ThrusterIO/socket-client/releases)
[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)]
(LICENSE)
[![Build Status](https://img.shields.io/travis/ThrusterIO/socket-client.svg?style=flat-square)]
(https://travis-ci.org/ThrusterIO/socket-client)
[![Code Coverage](https://img.shields.io/scrutinizer/coverage/g/ThrusterIO/socket-client.svg?style=flat-square)]
(https://scrutinizer-ci.com/g/ThrusterIO/socket-client)
[![Quality Score](https://img.shields.io/scrutinizer/g/ThrusterIO/socket-client.svg?style=flat-square)]
(https://scrutinizer-ci.com/g/ThrusterIO/socket-client)
[![Total Downloads](https://img.shields.io/packagist/dt/thruster/socket-client.svg?style=flat-square)]
(https://packagist.org/packages/thruster/socket-client)

[![Email](https://img.shields.io/badge/email-team@thruster.io-blue.svg?style=flat-square)]
(mailto:team@thruster.io)

The Thruster SocketClient Component.

## Install

Via Composer

``` bash
$ composer require thruster/socket-client
```

## Testing

``` bash
$ composer test
```

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## License

Please see [License File](LICENSE) for more information.

redpajama_set_name: RedPajamaGithub


text:
import mctransmitter
mctransmitter.initialize()

mctransmitter.tx_analog(0,0)
mctransmitter.tx_analog(1,0)
mctransmitter.tx_digital(0,0)
mctransmitter.tx_digital(1,0)


text:
//
//  DEMOWorkItemLiftWeights.h
//  Workflow
//
//  Created by Josh on 3/22/13.
//  Copyright (c) 2013 iJoshSmith. All rights reserved.
//

#import "JASWorkItem.h"

/*
 This workflow node causes the imaginary test subject
 to do pump some iron, which takes a moment to complete.
 */
@interface DEMOWorkItemLiftWeights : JASWorkItem

@end


text:
FactoryGirl.define do
  factory :member, :class => Kahuna::Member do
    role { %w(web lb ns db es proxy).sample }
    sequence(:name) { |n| "#{role}#{n}.example.com" }
    sequence(:address) { |n| "10.10.10.#{n}" }
    initialize_with { new("#{name} #{address} #{role}")}
  end
end


text:
package org.commcare.fragments;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

import org.commcare.activities.CommCareActivity;
import org.commcare.adapters.EntitySubnodeDetailAdapter;
import org.commcare.cases.entity.Entity;
import org.commcare.cases.entity.NodeEntityFactory;
import org.commcare.dalvik.R;
import org.commcare.suite.model.Detail;
import org.commcare.tasks.EntityLoaderListener;
import org.commcare.tasks.EntityLoaderTask;
import org.commcare.views.EntityView;
import org.javarosa.core.model.instance.TreeReference;

import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

/**
 * Created by jschweers on 8/26/2015.
 * <p/>
 * An EntityDetailSubnodeFragment displays a detail with a row for each of a set of
 * nodes generated by expanding a given nodeset expression in the context of a given entity.
 */
public class EntitySubnodeDetailFragment extends EntityDetailFragment implements EntityLoaderListener {
    private EntityLoaderTask loader;
    private ListView listView;

    public EntitySubnodeDetailFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            this.modifier = savedInstanceState.getParcelable(MODIFIER_KEY);
        }

        Detail detailToDisplay = getDetailToUseForDisplay();
        TreeReference referenceToDisplay = getReferenceToDisplay();

        View rootView = inflater.inflate(R.layout.entity_detail_list, container, false);

        final AppCompatActivity thisActivity = (AppCompatActivity)getActivity();
        this.listView = rootView.findViewById(R.id.screen_entity_detail_list);

        if (this.adapter == null && this.loader == null && !EntityLoaderTask.attachToActivity(this)) {
            // Set up task to fetch entity data
            EntityLoaderTask theLoader =
                    new EntityLoaderTask(detailToDisplay, getFactoryContextForRef(referenceToDisplay));
            theLoader.attachListener(this);
            theLoader.executeParallel(detailToDisplay.getNodeset().contextualize(referenceToDisplay));

            // Add header row
            final LinearLayout headerLayout = rootView.findViewById(R.id.entity_detail_header);
            String[] headers = new String[detailToDisplay.getFields().length];
            for (int i = 0; i < headers.length; ++i) {
                headers[i] = detailToDisplay.getFields()[i].getHeader().evaluate();
            }
            EntityView headerView = EntityView.buildHeadersEntityView(thisActivity, detailToDisplay,
                    headers, false);
            headerLayout.removeAllViews();
            headerLayout.addView(headerView);
            headerLayout.setVisibility(View.VISIBLE);
        }

        return rootView;
    }

    @Override
    public void attachLoader(EntityLoaderTask task) {
        this.loader = task;
    }

    @Override
    public void deliverLoadResult(List<Entity<TreeReference>> entities,
                                  List<TreeReference> references,
                                  NodeEntityFactory factory, int focusTargetIndex) {
        Bundle args = getArguments();
        Detail detail = asw.getSession().getDetail(args.getString(DETAIL_ID));
        final int thisIndex = args.getInt(CHILD_DETAIL_INDEX, -1);
        final boolean detailCompound = thisIndex != -1;
        if (detailCompound) {
            detail = getChildDetailForDisplay(detail, thisIndex);
        }

        this.loader = null;
        this.adapter = new EntitySubnodeDetailAdapter(getActivity(), detail, references,
                entities, modifier, factory);
        this.listView.setAdapter((ListAdapter)this.adapter);
        if (focusTargetIndex != -1) {
            listView.setSelection(focusTargetIndex);
        }
    }

    @Override
    public void deliverLoadError(Exception e) {
        ((CommCareActivity)getActivity()).displayCaseListLoadException(e);
    }
}


text:
#include "redis.h"

#include <math.h>

/*-----------------------------------------------------------------------------
 * Sorted set API
 *----------------------------------------------------------------------------*/

/* ZSETs are ordered sets using two data structures to hold the same elements
 * in order to get O(log(N)) INSERT and REMOVE operations into a sorted
 * data structure.
 *
 * The elements are added to an hash table mapping Redis objects to scores.
 * At the same time the elements are added to a skip list mapping scores
 * to Redis objects (so objects are sorted by scores in this "view"). */

/* This skiplist implementation is almost a C translation of the original
 * algorithm described by William Pugh in "Skip Lists: A Probabilistic
 * Alternative to Balanced Trees", modified in three ways:
 * a) this implementation allows for repeated values.
 * b) the comparison is not just by key (our 'score') but by satellite data.
 * c) there is a back pointer, so it's a doubly linked list with the back
 * pointers being only at "level 1". This allows to traverse the list
 * from tail to head, useful for ZREVRANGE. */

zskiplistNode *zslCreateNode(int level, double score, robj *obj) {
    zskiplistNode *zn = zmalloc(sizeof(*zn)+level*sizeof(struct zskiplistLevel));
    zn->score = score;
    zn->obj = obj;
    return zn;
}

zskiplist *zslCreate(void) {
    int j;
    zskiplist *zsl;

    zsl = zmalloc(sizeof(*zsl));
    zsl->level = 1;
    zsl->length = 0;
    zsl->header = zslCreateNode(ZSKIPLIST_MAXLEVEL,0,NULL);
    for (j = 0; j < ZSKIPLIST_MAXLEVEL; j++) {
        zsl->header->level[j].forward = NULL;
        zsl->header->level[j].span = 0;
    }
    zsl->header->backward = NULL;
    zsl->tail = NULL;
    return zsl;
}

void zslFreeNode(zskiplistNode *node) {
    decrRefCount(node->obj);
    zfree(node);
}

void zslFree(zskiplist *zsl) {
    zskiplistNode *node = zsl->header->level[0].forward, *next;

    zfree(zsl->header);
    while(node) {
        next = node->level[0].forward;
        zslFreeNode(node);
        node = next;
    }
    zfree(zsl);
}

int zslRandomLevel(void) {
    int level = 1;
    while ((random()&0xFFFF) < (ZSKIPLIST_P * 0xFFFF))
        level += 1;
    return (level<ZSKIPLIST_MAXLEVEL) ? level : ZSKIPLIST_MAXLEVEL;
}

zskiplistNode *zslInsert(zskiplist *zsl, double score, robj *obj) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned int rank[ZSKIPLIST_MAXLEVEL];
    int i, level;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        /* store rank that is crossed to reach the insert position */
        rank[i] = i == (zsl->level-1) ? 0 : rank[i+1];
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,obj) < 0))) {
            rank[i] += x->level[i].span;
            x = x->level[i].forward;
        }
        update[i] = x;
    }
    /* we assume the key is not already inside, since we allow duplicated
     * scores, and the re-insertion of score and redis object should never
     * happpen since the caller of zslInsert() should test in the hash table
     * if the element is already inside or not. */
    level = zslRandomLevel();
    if (level > zsl->level) {
        for (i = zsl->level; i < level; i++) {
            rank[i] = 0;
            update[i] = zsl->header;
            update[i]->level[i].span = zsl->length;
        }
        zsl->level = level;
    }
    x = zslCreateNode(level,score,obj);
    for (i = 0; i < level; i++) {
        x->level[i].forward = update[i]->level[i].forward;
        update[i]->level[i].forward = x;

        /* update span covered by update[i] as x is inserted here */
        x->level[i].span = update[i]->level[i].span - (rank[0] - rank[i]);
        update[i]->level[i].span = (rank[0] - rank[i]) + 1;
    }

    /* increment span for untouched levels */
    for (i = level; i < zsl->level; i++) {
        update[i]->level[i].span++;
    }

    x->backward = (update[0] == zsl->header) ? NULL : update[0];
    if (x->level[0].forward)
        x->level[0].forward->backward = x;
    else
        zsl->tail = x;
    zsl->length++;
    return x;
}

/* Internal function used by zslDelete, zslDeleteByScore and zslDeleteByRank */
void zslDeleteNode(zskiplist *zsl, zskiplistNode *x, zskiplistNode **update) {
    int i;
    for (i = 0; i < zsl->level; i++) {
        if (update[i]->level[i].forward == x) {
            update[i]->level[i].span += x->level[i].span - 1;
            update[i]->level[i].forward = x->level[i].forward;
        } else {
            update[i]->level[i].span -= 1;
        }
    }
    if (x->level[0].forward) {
        x->level[0].forward->backward = x->backward;
    } else {
        zsl->tail = x->backward;
    }
    while(zsl->level > 1 && zsl->header->level[zsl->level-1].forward == NULL)
        zsl->level--;
    zsl->length--;
}

/* Delete an element with matching score/object from the skiplist. */
int zslDelete(zskiplist *zsl, double score, robj *obj) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,obj) < 0)))
            x = x->level[i].forward;
        update[i] = x;
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
    x = x->level[0].forward;
    if (x && score == x->score && equalStringObjects(x->obj,obj)) {
        zslDeleteNode(zsl, x, update);
        zslFreeNode(x);
        return 1;
    } else {
        return 0; /* not found */
    }
    return 0; /* not found */
}

/* Struct to hold a inclusive/exclusive range spec. */
typedef struct {
    double min, max;
    int minex, maxex; /* are min or max exclusive? */
} zrangespec;

/* Delete all the elements with score between min and max from the skiplist.
 * Min and mx are inclusive, so a score >= min || score <= max is deleted.
 * Note that this function takes the reference to the hash table view of the
 * sorted set, in order to remove the elements from the hash table too. */
unsigned long zslDeleteRangeByScore(zskiplist *zsl, zrangespec range, dict *dict) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long removed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward && (range.minex ?
            x->level[i].forward->score <= range.min :
            x->level[i].forward->score < range.min))
                x = x->level[i].forward;
        update[i] = x;
    }

    /* Current node is the last with score < or <= min. */
    x = x->level[0].forward;

    /* Delete nodes while in range. */
    while (x && (range.maxex ? x->score < range.max : x->score <= range.max)) {
        zskiplistNode *next = x->level[0].forward;
        zslDeleteNode(zsl,x,update);
        dictDelete(dict,x->obj);
        zslFreeNode(x);
        removed++;
        x = next;
    }
    return removed;
}

/* Delete all the elements with rank between start and end from the skiplist.
 * Start and end are inclusive. Note that start and end need to be 1-based */
unsigned long zslDeleteRangeByRank(zskiplist *zsl, unsigned int start, unsigned int end, dict *dict) {
    zskiplistNode *update[ZSKIPLIST_MAXLEVEL], *x;
    unsigned long traversed = 0, removed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward && (traversed + x->level[i].span) < start) {
            traversed += x->level[i].span;
            x = x->level[i].forward;
        }
        update[i] = x;
    }

    traversed++;
    x = x->level[0].forward;
    while (x && traversed <= end) {
        zskiplistNode *next = x->level[0].forward;
        zslDeleteNode(zsl,x,update);
        dictDelete(dict,x->obj);
        zslFreeNode(x);
        removed++;
        traversed++;
        x = next;
    }
    return removed;
}

/* Find the first node having a score equal or greater than the specified one.
 * Returns NULL if there is no match. */
zskiplistNode *zslFirstWithScore(zskiplist *zsl, double score) {
    zskiplistNode *x;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward && x->level[i].forward->score < score)
            x = x->level[i].forward;
    }
    /* We may have multiple elements with the same score, what we need
     * is to find the element with both the right score and object. */
    return x->level[0].forward;
}

/* Find the rank for an element by both score and key.
 * Returns 0 when the element cannot be found, rank otherwise.
 * Note that the rank is 1-based due to the span of zsl->header to the
 * first element. */
unsigned long zslGetRank(zskiplist *zsl, double score, robj *o) {
    zskiplistNode *x;
    unsigned long rank = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward &&
            (x->level[i].forward->score < score ||
                (x->level[i].forward->score == score &&
                compareStringObjects(x->level[i].forward->obj,o) <= 0))) {
            rank += x->level[i].span;
            x = x->level[i].forward;
        }

        /* x might be equal to zsl->header, so test if obj is non-NULL */
        if (x->obj && equalStringObjects(x->obj,o)) {
            return rank;
        }
    }
    return 0;
}

/* Finds an element by its rank. The rank argument needs to be 1-based. */
zskiplistNode* zslGetElementByRank(zskiplist *zsl, unsigned long rank) {
    zskiplistNode *x;
    unsigned long traversed = 0;
    int i;

    x = zsl->header;
    for (i = zsl->level-1; i >= 0; i--) {
        while (x->level[i].forward && (traversed + x->level[i].span) <= rank)
        {
            traversed += x->level[i].span;
            x = x->level[i].forward;
        }
        if (traversed == rank) {
            return x;
        }
    }
    return NULL;
}

/* Populate the rangespec according to the objects min and max. */
static int zslParseRange(robj *min, robj *max, zrangespec *spec) {
    char *eptr;
    spec->minex = spec->maxex = 0;

    /* Parse the min-max interval. If one of the values is prefixed
     * by the "(" character, it's considered "open". For instance
     * ZRANGEBYSCORE zset (1.5 (2.5 will match min < x < max
     * ZRANGEBYSCORE zset 1.5 2.5 will instead match min <= x <= max */
    if (min->encoding == REDIS_ENCODING_INT) {
        spec->min = (long)min->ptr;
    } else {
        if (((char*)min->ptr)[0] == '(') {
            spec->min = strtod((char*)min->ptr+1,&eptr);
            if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
            spec->minex = 1;
        } else {
            spec->min = strtod((char*)min->ptr,&eptr);
            if (eptr[0] != '\0' || isnan(spec->min)) return REDIS_ERR;
        }
    }
    if (max->encoding == REDIS_ENCODING_INT) {
        spec->max = (long)max->ptr;
    } else {
        if (((char*)max->ptr)[0] == '(') {
            spec->max = strtod((char*)max->ptr+1,&eptr);
            if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
            spec->maxex = 1;
        } else {
            spec->max = strtod((char*)max->ptr,&eptr);
            if (eptr[0] != '\0' || isnan(spec->max)) return REDIS_ERR;
        }
    }

    return REDIS_OK;
}

/*-----------------------------------------------------------------------------
 * Sorted set commands
 *----------------------------------------------------------------------------*/

/* This generic command implements both ZADD and ZINCRBY. */
void zaddGenericCommand(redisClient *c, robj *key, robj *ele, double score, int incr) {
    robj *zsetobj;
    zset *zs;
    zskiplistNode *znode;

    zsetobj = lookupKeyWrite(c->db,key);
    if (zsetobj == NULL) {
        zsetobj = createZsetObject();
        dbAdd(c->db,key,zsetobj);
    } else {
        if (zsetobj->type != REDIS_ZSET) {
            addReply(c,shared.wrongtypeerr);
            return;
        }
    }
    zs = zsetobj->ptr;

    /* Since both ZADD and ZINCRBY are implemented here, we need to increment
     * the score first by the current score if ZINCRBY is called. */
    if (incr) {
        /* Read the old score. If the element was not present starts from 0 */
        dictEntry *de = dictFind(zs->dict,ele);
        if (de != NULL)
            score += *(double*)dictGetEntryVal(de);

        if (isnan(score)) {
            addReplyError(c,"resulting score is not a number (NaN)");
            /* Note that we don't need to check if the zset may be empty and
             * should be removed here, as we can only obtain Nan as score if
             * there was already an element in the sorted set. */
            return;
        }
    }

    /* We need to remove and re-insert the element when it was already present
     * in the dictionary, to update the skiplist. Note that we delay adding a
     * pointer to the score because we want to reference the score in the
     * skiplist node. */
    if (dictAdd(zs->dict,ele,NULL) == DICT_OK) {
        dictEntry *de;

        /* New element */
        incrRefCount(ele); /* added to hash */
        znode = zslInsert(zs->zsl,score,ele);
        incrRefCount(ele); /* added to skiplist */

        /* Update the score in the dict entry */
        de = dictFind(zs->dict,ele);
        redisAssert(de != NULL);
        dictGetEntryVal(de) = &znode->score;
        touchWatchedKey(c->db,c->argv[1]);
        server.dirty++;
        if (incr)
            addReplyDouble(c,score);
        else
            addReply(c,shared.cone);
    } else {
        dictEntry *de;
        robj *curobj;
        double *curscore;
        int deleted;

        /* Update score */
        de = dictFind(zs->dict,ele);
        redisAssert(de != NULL);
        curobj = dictGetEntryKey(de);
        curscore = dictGetEntryVal(de);

        /* When the score is updated, reuse the existing string object to
         * prevent extra alloc/dealloc of strings on ZINCRBY. */
        if (score != *curscore) {
            deleted = zslDelete(zs->zsl,*curscore,curobj);
            redisAssert(deleted != 0);
            znode = zslInsert(zs->zsl,score,curobj);
            incrRefCount(curobj);

            /* Update the score in the current dict entry */
            dictGetEntryVal(de) = &znode->score;
            touchWatchedKey(c->db,c->argv[1]);
            server.dirty++;
        }
        if (incr)
            addReplyDouble(c,score);
        else
            addReply(c,shared.czero);
    }
}

void zaddCommand(redisClient *c) {
    double scoreval;
    if (getDoubleFromObjectOrReply(c,c->argv[2],&scoreval,NULL) != REDIS_OK) return;
    c->argv[3] = tryObjectEncoding(c->argv[3]);
    zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,0);
}

void zincrbyCommand(redisClient *c) {
    double scoreval;
    if (getDoubleFromObjectOrReply(c,c->argv[2],&scoreval,NULL) != REDIS_OK) return;
    c->argv[3] = tryObjectEncoding(c->argv[3]);
    zaddGenericCommand(c,c->argv[1],c->argv[3],scoreval,1);
}

void zremCommand(redisClient *c) {
    robj *zsetobj;
    zset *zs;
    dictEntry *de;
    double curscore;
    int deleted;

    if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
        checkType(c,zsetobj,REDIS_ZSET)) return;

    zs = zsetobj->ptr;
    c->argv[2] = tryObjectEncoding(c->argv[2]);
    de = dictFind(zs->dict,c->argv[2]);
    if (de == NULL) {
        addReply(c,shared.czero);
        return;
    }
    /* Delete from the skiplist */
    curscore = *(double*)dictGetEntryVal(de);
    deleted = zslDelete(zs->zsl,curscore,c->argv[2]);
    redisAssert(deleted != 0);

    /* Delete from the hash table */
    dictDelete(zs->dict,c->argv[2]);
    if (htNeedsResize(zs->dict)) dictResize(zs->dict);
    if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
    touchWatchedKey(c->db,c->argv[1]);
    server.dirty++;
    addReply(c,shared.cone);
}

void zremrangebyscoreCommand(redisClient *c) {
    zrangespec range;
    long deleted;
    robj *o;
    zset *zs;

    /* Parse the range arguments. */
    if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
        addReplyError(c,"min or max is not a double");
        return;
    }

    if ((o = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
        checkType(c,o,REDIS_ZSET)) return;

    zs = o->ptr;
    deleted = zslDeleteRangeByScore(zs->zsl,range,zs->dict);
    if (htNeedsResize(zs->dict)) dictResize(zs->dict);
    if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
    if (deleted) touchWatchedKey(c->db,c->argv[1]);
    server.dirty += deleted;
    addReplyLongLong(c,deleted);
}

void zremrangebyrankCommand(redisClient *c) {
    long start;
    long end;
    int llen;
    long deleted;
    robj *zsetobj;
    zset *zs;

    if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
        (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;

    if ((zsetobj = lookupKeyWriteOrReply(c,c->argv[1],shared.czero)) == NULL ||
        checkType(c,zsetobj,REDIS_ZSET)) return;
    zs = zsetobj->ptr;
    llen = zs->zsl->length;

    /* convert negative indexes */
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
    if (start > end || start >= llen) {
        addReply(c,shared.czero);
        return;
    }
    if (end >= llen) end = llen-1;

    /* increment start and end because zsl*Rank functions
     * use 1-based rank */
    deleted = zslDeleteRangeByRank(zs->zsl,start+1,end+1,zs->dict);
    if (htNeedsResize(zs->dict)) dictResize(zs->dict);
    if (dictSize(zs->dict) == 0) dbDelete(c->db,c->argv[1]);
    if (deleted) touchWatchedKey(c->db,c->argv[1]);
    server.dirty += deleted;
    addReplyLongLong(c, deleted);
}

typedef struct {
    dict *dict;
    double weight;
} zsetopsrc;

int qsortCompareZsetopsrcByCardinality(const void *s1, const void *s2) {
    zsetopsrc *d1 = (void*) s1, *d2 = (void*) s2;
    unsigned long size1, size2;
    size1 = d1->dict ? dictSize(d1->dict) : 0;
    size2 = d2->dict ? dictSize(d2->dict) : 0;
    return size1 - size2;
}

#define REDIS_AGGR_SUM 1
#define REDIS_AGGR_MIN 2
#define REDIS_AGGR_MAX 3
#define zunionInterDictValue(_e) (dictGetEntryVal(_e) == NULL ? 1.0 : *(double*)dictGetEntryVal(_e))

inline static void zunionInterAggregate(double *target, double val, int aggregate) {
    if (aggregate == REDIS_AGGR_SUM) {
        *target = *target + val;
        /* The result of adding two doubles is NaN when one variable
         * is +inf and the other is -inf. When these numbers are added,
         * we maintain the convention of the result being 0.0. */
        if (isnan(*target)) *target = 0.0;
    } else if (aggregate == REDIS_AGGR_MIN) {
        *target = val < *target ? val : *target;
    } else if (aggregate == REDIS_AGGR_MAX) {
        *target = val > *target ? val : *target;
    } else {
        /* safety net */
        redisPanic("Unknown ZUNION/INTER aggregate type");
    }
}

void zunionInterGenericCommand(redisClient *c, robj *dstkey, int op) {
    int i, j, setnum;
    int aggregate = REDIS_AGGR_SUM;
    zsetopsrc *src;
    robj *dstobj;
    zset *dstzset;
    zskiplistNode *znode;
    dictIterator *di;
    dictEntry *de;
    int touched = 0;

    /* expect setnum input keys to be given */
    setnum = atoi(c->argv[2]->ptr);
    if (setnum < 1) {
        addReplyError(c,
            "at least 1 input key is needed for ZUNIONSTORE/ZINTERSTORE");
        return;
    }

    /* test if the expected number of keys would overflow */
    if (3+setnum > c->argc) {
        addReply(c,shared.syntaxerr);
        return;
    }

    /* read keys to be used for input */
    src = zmalloc(sizeof(zsetopsrc) * setnum);
    for (i = 0, j = 3; i < setnum; i++, j++) {
        robj *obj = lookupKeyWrite(c->db,c->argv[j]);
        if (!obj) {
            src[i].dict = NULL;
        } else {
            if (obj->type == REDIS_ZSET) {
                src[i].dict = ((zset*)obj->ptr)->dict;
            } else if (obj->type == REDIS_SET) {
                src[i].dict = (obj->ptr);
            } else {
                zfree(src);
                addReply(c,shared.wrongtypeerr);
                return;
            }
        }

        /* default all weights to 1 */
        src[i].weight = 1.0;
    }

    /* parse optional extra arguments */
    if (j < c->argc) {
        int remaining = c->argc - j;

        while (remaining) {
            if (remaining >= (setnum + 1) && !strcasecmp(c->argv[j]->ptr,"weights")) {
                j++; remaining--;
                for (i = 0; i < setnum; i++, j++, remaining--) {
                    if (getDoubleFromObjectOrReply(c,c->argv[j],&src[i].weight,
                            "weight value is not a double") != REDIS_OK)
                    {
                        zfree(src);
                        return;
                    }
                }
            } else if (remaining >= 2 && !strcasecmp(c->argv[j]->ptr,"aggregate")) {
                j++; remaining--;
                if (!strcasecmp(c->argv[j]->ptr,"sum")) {
                    aggregate = REDIS_AGGR_SUM;
                } else if (!strcasecmp(c->argv[j]->ptr,"min")) {
                    aggregate = REDIS_AGGR_MIN;
                } else if (!strcasecmp(c->argv[j]->ptr,"max")) {
                    aggregate = REDIS_AGGR_MAX;
                } else {
                    zfree(src);
                    addReply(c,shared.syntaxerr);
                    return;
                }
                j++; remaining--;
            } else {
                zfree(src);
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* sort sets from the smallest to largest, this will improve our
     * algorithm's performance */
    qsort(src,setnum,sizeof(zsetopsrc),qsortCompareZsetopsrcByCardinality);

    dstobj = createZsetObject();
    dstzset = dstobj->ptr;

    if (op == REDIS_OP_INTER) {
        /* skip going over all entries if the smallest zset is NULL or empty */
        if (src[0].dict && dictSize(src[0].dict) > 0) {
            /* precondition: as src[0].dict is non-empty and the zsets are ordered
             * from small to large, all src[i > 0].dict are non-empty too */
            di = dictGetIterator(src[0].dict);
            while((de = dictNext(di)) != NULL) {
                double score, value;

                score = src[0].weight * zunionInterDictValue(de);
                for (j = 1; j < setnum; j++) {
                    dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
                    if (other) {
                        value = src[j].weight * zunionInterDictValue(other);
                        zunionInterAggregate(&score,value,aggregate);
                    } else {
                        break;
                    }
                }

                /* Only continue when present in every source dict. */
                if (j == setnum) {
                    robj *o = dictGetEntryKey(de);
                    znode = zslInsert(dstzset->zsl,score,o);
                    incrRefCount(o); /* added to skiplist */
                    dictAdd(dstzset->dict,o,&znode->score);
                    incrRefCount(o); /* added to dictionary */
                }
            }
            dictReleaseIterator(di);
        }
    } else if (op == REDIS_OP_UNION) {
        for (i = 0; i < setnum; i++) {
            if (!src[i].dict) continue;

            di = dictGetIterator(src[i].dict);
            while((de = dictNext(di)) != NULL) {
                double score, value;

                /* skip key when already processed */
                if (dictFind(dstzset->dict,dictGetEntryKey(de)) != NULL)
                    continue;

                /* initialize score */
                score = src[i].weight * zunionInterDictValue(de);

                /* because the zsets are sorted by size, its only possible
                 * for sets at larger indices to hold this entry */
                for (j = (i+1); j < setnum; j++) {
                    dictEntry *other = dictFind(src[j].dict,dictGetEntryKey(de));
                    if (other) {
                        value = src[j].weight * zunionInterDictValue(other);
                        zunionInterAggregate(&score,value,aggregate);
                    }
                }

                robj *o = dictGetEntryKey(de);
                znode = zslInsert(dstzset->zsl,score,o);
                incrRefCount(o); /* added to skiplist */
                dictAdd(dstzset->dict,o,&znode->score);
                incrRefCount(o); /* added to dictionary */
            }
            dictReleaseIterator(di);
        }
    } else {
        /* unknown operator */
        redisAssert(op == REDIS_OP_INTER || op == REDIS_OP_UNION);
    }

    if (dbDelete(c->db,dstkey)) {
        touchWatchedKey(c->db,dstkey);
        touched = 1;
        server.dirty++;
    }
    if (dstzset->zsl->length) {
        dbAdd(c->db,dstkey,dstobj);
        addReplyLongLong(c, dstzset->zsl->length);
        if (!touched) touchWatchedKey(c->db,dstkey);
        server.dirty++;
    } else {
        decrRefCount(dstobj);
        addReply(c, shared.czero);
    }
    zfree(src);
}

void zunionstoreCommand(redisClient *c) {
    zunionInterGenericCommand(c,c->argv[1], REDIS_OP_UNION);
}

void zinterstoreCommand(redisClient *c) {
    zunionInterGenericCommand(c,c->argv[1], REDIS_OP_INTER);
}

void zrangeGenericCommand(redisClient *c, int reverse) {
    robj *o;
    long start;
    long end;
    int withscores = 0;
    int llen;
    int rangelen, j;
    zset *zsetobj;
    zskiplist *zsl;
    zskiplistNode *ln;
    robj *ele;

    if ((getLongFromObjectOrReply(c, c->argv[2], &start, NULL) != REDIS_OK) ||
        (getLongFromObjectOrReply(c, c->argv[3], &end, NULL) != REDIS_OK)) return;

    if (c->argc == 5 && !strcasecmp(c->argv[4]->ptr,"withscores")) {
        withscores = 1;
    } else if (c->argc >= 5) {
        addReply(c,shared.syntaxerr);
        return;
    }

    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.emptymultibulk)) == NULL
         || checkType(c,o,REDIS_ZSET)) return;
    zsetobj = o->ptr;
    zsl = zsetobj->zsl;
    llen = zsl->length;

    /* convert negative indexes */
    if (start < 0) start = llen+start;
    if (end < 0) end = llen+end;
    if (start < 0) start = 0;

    /* Invariant: start >= 0, so this test will be true when end < 0.
     * The range is empty when start > end or start >= length. */
    if (start > end || start >= llen) {
        addReply(c,shared.emptymultibulk);
        return;
    }
    if (end >= llen) end = llen-1;
    rangelen = (end-start)+1;

    /* check if starting point is trivial, before searching
     * the element in log(N) time */
    if (reverse) {
        ln = start == 0 ? zsl->tail : zslGetElementByRank(zsl, llen-start);
    } else {
        ln = start == 0 ?
            zsl->header->level[0].forward : zslGetElementByRank(zsl, start+1);
    }

    /* Return the result in form of a multi-bulk reply */
    addReplyMultiBulkLen(c,withscores ? (rangelen*2) : rangelen);
    for (j = 0; j < rangelen; j++) {
        ele = ln->obj;
        addReplyBulk(c,ele);
        if (withscores)
            addReplyDouble(c,ln->score);
        ln = reverse ? ln->backward : ln->level[0].forward;
    }
}

void zrangeCommand(redisClient *c) {
    zrangeGenericCommand(c,0);
}

void zrevrangeCommand(redisClient *c) {
    zrangeGenericCommand(c,1);
}

/* This command implements ZRANGEBYSCORE, ZREVRANGEBYSCORE and ZCOUNT.
 * If "justcount", only the number of elements in the range is returned. */
void genericZrangebyscoreCommand(redisClient *c, int reverse, int justcount) {
    zrangespec range;
    robj *o, *emptyreply;
    zset *zsetobj;
    zskiplist *zsl;
    zskiplistNode *ln;
    int offset = 0, limit = -1;
    int withscores = 0;
    unsigned long rangelen = 0;
    void *replylen = NULL;

    /* Parse the range arguments. */
    if (zslParseRange(c->argv[2],c->argv[3],&range) != REDIS_OK) {
        addReplyError(c,"min or max is not a double");
        return;
    }

    /* Parse optional extra arguments. Note that ZCOUNT will exactly have
     * 4 arguments, so we'll never enter the following code path. */
    if (c->argc > 4) {
        int remaining = c->argc - 4;
        int pos = 4;

        while (remaining) {
            if (remaining >= 1 && !strcasecmp(c->argv[pos]->ptr,"withscores")) {
                pos++; remaining--;
                withscores = 1;
            } else if (remaining >= 3 && !strcasecmp(c->argv[pos]->ptr,"limit")) {
                offset = atoi(c->argv[pos+1]->ptr);
                limit = atoi(c->argv[pos+2]->ptr);
                pos += 3; remaining -= 3;
            } else {
                addReply(c,shared.syntaxerr);
                return;
            }
        }
    }

    /* Ok, lookup the key and get the range */
    emptyreply = justcount ? shared.czero : shared.emptymultibulk;
    if ((o = lookupKeyReadOrReply(c,c->argv[1],emptyreply)) == NULL ||
        checkType(c,o,REDIS_ZSET)) return;
    zsetobj = o->ptr;
    zsl = zsetobj->zsl;

    /* If reversed, assume the elements are sorted from high to low score. */
    ln = zslFirstWithScore(zsl,range.min);
    if (reverse) {
        /* If range.min is out of range, ln will be NULL and we need to use
         * the tail of the skiplist as first node of the range. */
        if (ln == NULL) ln = zsl->tail;

        /* zslFirstWithScore returns the first element with where with
         * score >= range.min, so backtrack to make sure the element we use
         * here has score <= range.min. */
        while (ln && ln->score > range.min) ln = ln->backward;

        /* Move to the right element according to the range spec. */
        if (range.minex) {
            /* Find last element with score < range.min */
            while (ln && ln->score == range.min) ln = ln->backward;
        } else {
            /* Find last element with score <= range.min */
            while (ln && ln->level[0].forward &&
                         ln->level[0].forward->score == range.min)
                ln = ln->level[0].forward;
        }
    } else {
        if (range.minex) {
            /* Find first element with score > range.min */
            while (ln && ln->score == range.min) ln = ln->level[0].forward;
        }
    }

    /* No "first" element in the specified interval. */
    if (ln == NULL) {
        addReply(c,emptyreply);
        return;
    }

    /* We don't know in advance how many matching elements there
     * are in the list, so we push this object that will represent
     * the multi-bulk length in the output buffer, and will "fix"
     * it later */
    if (!justcount)
        replylen = addDeferredMultiBulkLength(c);

    /* If there is an offset, just traverse the number of elements without
     * checking the score because that is done in the next loop. */
    while(ln && offset--) {
        if (reverse)
            ln = ln->backward;
        else
            ln = ln->level[0].forward;
    }

    while (ln && limit--) {
        /* Check if this this element is in range. */
        if (reverse) {
            if (range.maxex) {
                /* Element should have score > range.max */
                if (ln->score <= range.max) break;
            } else {
                /* Element should have score >= range.max */
                if (ln->score < range.max) break;
            }
        } else {
            if (range.maxex) {
                /* Element should have score < range.max */
                if (ln->score >= range.max) break;
            } else {
                /* Element should have score <= range.max */
                if (ln->score > range.max) break;
            }
        }

        /* Do our magic */
        rangelen++;
        if (!justcount) {
            addReplyBulk(c,ln->obj);
            if (withscores)
                addReplyDouble(c,ln->score);
        }

        if (reverse)
            ln = ln->backward;
        else
            ln = ln->level[0].forward;
    }

    if (justcount) {
        addReplyLongLong(c,(long)rangelen);
    } else {
        setDeferredMultiBulkLength(c,replylen,
             withscores ? (rangelen*2) : rangelen);
    }
}

void zrangebyscoreCommand(redisClient *c) {
    genericZrangebyscoreCommand(c,0,0);
}

void zrevrangebyscoreCommand(redisClient *c) {
    genericZrangebyscoreCommand(c,1,0);
}

void zcountCommand(redisClient *c) {
    genericZrangebyscoreCommand(c,0,1);
}

void zcardCommand(redisClient *c) {
    robj *o;
    zset *zs;

    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.czero)) == NULL ||
        checkType(c,o,REDIS_ZSET)) return;

    zs = o->ptr;
    addReplyLongLong(c,zs->zsl->length);
}

void zscoreCommand(redisClient *c) {
    robj *o;
    zset *zs;
    dictEntry *de;

    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
        checkType(c,o,REDIS_ZSET)) return;

    zs = o->ptr;
    c->argv[2] = tryObjectEncoding(c->argv[2]);
    de = dictFind(zs->dict,c->argv[2]);
    if (!de) {
        addReply(c,shared.nullbulk);
    } else {
        double *score = dictGetEntryVal(de);

        addReplyDouble(c,*score);
    }
}

void zrankGenericCommand(redisClient *c, int reverse) {
    robj *o;
    zset *zs;
    zskiplist *zsl;
    dictEntry *de;
    unsigned long rank;
    double *score;

    if ((o = lookupKeyReadOrReply(c,c->argv[1],shared.nullbulk)) == NULL ||
        checkType(c,o,REDIS_ZSET)) return;

    zs = o->ptr;
    zsl = zs->zsl;
    c->argv[2] = tryObjectEncoding(c->argv[2]);
    de = dictFind(zs->dict,c->argv[2]);
    if (!de) {
        addReply(c,shared.nullbulk);
        return;
    }

    score = dictGetEntryVal(de);
    rank = zslGetRank(zsl, *score, c->argv[2]);
    if (rank) {
        if (reverse) {
            addReplyLongLong(c, zsl->length - rank);
        } else {
            addReplyLongLong(c, rank-1);
        }
    } else {
        addReply(c,shared.nullbulk);
    }
}

void zrankCommand(redisClient *c) {
    zrankGenericCommand(c, 0);
}

void zrevrankCommand(redisClient *c) {
    zrankGenericCommand(c, 1);
}


text:
var sqlite3 = require('sqlite3').verbose();
var bcrypt = require('bcryptjs');
var Q = require('q');
var userManagementSettings = require('./../../lib/user-management-settings');
var dbSettings = userManagementSettings.get().dbSettings;
var db = require('./../../lib/db/db-binding-sqlite');
var fs = require('fs');

module.exports.initResourceDb = function() {

    var resourcedb = new sqlite3.Database('test/sqlite/unit-test.sqlite');

    resourcedb.close();

    var deferred = Q.defer();

    var sqlUser = 'CREATE TABLE "user" ( user_id	INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE, username	VARCHAR NOT NULL,email	VARCHAR NOT NULL, password	VARCHAR NOT NULL, salt	VARCHAR NOT NULL, role_id INTEGER NOT NULL, created_date	DATETIME NOT NULL, updated_date	DATETIME NOT NULL)';

    var sqlRole =  'CREATE TABLE "user_roles" (role_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)';

    db.run(dbSettings, sqlUser)
        .then(function(response){

            if(response === true){
                return db.run(dbSettings, sqlRole);

            } else {
                throw Error('Error creating user table');
            }

        })
        .then(function(response){

            if(response === true){
                return setupDb();

            } else {
                throw Error('Error creating role table.');
            }
        })
        .then(function(){
            deferred.resolve(true);
        })
        .catch(function(err){
            deferred.reject(err);
        })
        .done();

    return deferred.promise;
};

// Setup DB - call a function that ensures DB is in expected state;
// this function only exists in test DBs
var populateUsers = function() {

    var deferred = Q.defer();

    var salt = bcrypt.genSaltSync();
    var pwdHash = bcrypt.hashSync('password', salt);

    db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date) VALUES ('reader', 'test@test.com', '"
        + pwdHash + "', '" + salt + "', 3, datetime(), datetime());")
        .then(function(response){

            if(response === true){
                return db.run(dbSettings, "UPDATE SQLITE_SEQUENCE SET seq = 1 WHERE name = 'user';");

            } else {
                throw Error('Error resetting sequence.');
            }

        })
        .then(function(response){

            // userId 6
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'editor', email, password, salt, 2, datetime(), datetime() FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: editor');
            }
        })
        .then(function(response){

            // userId 6
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'admin', email, password, salt, 1, datetime(), datetime() FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: admin');
            }
        })
        .then(function(response){

            // userId 6
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'unknownPasswordChange', email, password, salt, 3, datetime(), datetime() FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: unknownPasswordChange');
            }
        })
        .then(function(response){

            // userId 7
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'knownPasswordChange', email, password, salt, 3, datetime(), datetime()FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: knownPasswordChange');
            }
        })
        .then(function(response){

            // userId 8
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'unknownUsername', 'tests@spatialdev.com', password, salt, 3, datetime(), datetime() FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: unknownUsername');
            }
        })
        .then(function(response){

            // userId 9
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'emailChange', 'tests@spatialdev.com', password, salt, 3, datetime(), datetime() FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: emailChange');
            }
        })
        .then(function(response){

            // userId 10
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user (username, email, password, salt, role_id, created_date, updated_date)"
                    + "SELECT 'profileChange', email, password, salt, 3, datetime(), datetime() FROM user WHERE user_id = 1;");

            } else {
                throw Error('Error adding test user: profileChange');
            }
        })

        .then(function(response){

            if(response === true){
                deferred.resolve(true);

            } else {
                throw Error();
            }
        })
        .catch(function(err){
            deferred.reject(err);
        });

    return deferred.promise;
};

var populateRoles = function() {

    var deferred = Q.defer();

    db.run(dbSettings, "INSERT INTO user_roles (name) VALUES ('admin');")
        .then(function(response){

            if(response === true){
                return db.run(dbSettings, "UPDATE SQLITE_SEQUENCE SET seq = 1 WHERE name = 'user_roles';");

            } else {
                throw Error('Error resetting sequence.');
            }

        })
        .then(function(response){

            // userId 6
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user_roles (name) VALUES ('editor');");

            } else {
                throw Error('Error adding test user: editor');
            }
        })
        .then(function(response){

            // userId 6
            if(response === true){
                return db.run(dbSettings, "INSERT INTO user_roles (name) VALUES ('reader');");

            } else {
                throw Error('Error adding test user: admin');
            }
        })
        .then(function(response){

            if(response === true){
                deferred.resolve(true);

            } else {
                throw Error();
            }
        })
        .catch(function(err){
            deferred.reject(err);
        });

    return deferred.promise;
};

// this function only exists in tests
var setupDb = function() {

    return populateRoles()
        .then(function(){
            return populateUsers();
        });

};

module.exports.cleanupResourceDb = function(){

    try {
        fs.unlinkSync('test/sqlite/unit-test.sqlite');
    } catch (err) {
        console.log("Here...");
        console.log(err);
    }
};


text:
var chalk = require('chalk');
var notify = require('gulp-notify');

/**
 * Log errors from Gulp
 * @param {string} task
 */
function handleError (task) {
  return function (err) {
    console.log(chalk.red(err));
    notify.onError(task + ' failed, check the logs..')(err);
  };
}

module.exports = handleError;


text:
using System.IO;
using System.IO.Compression;

namespace DocaLabs.Http.Client.Utils.ContentEncoding
{
    /// <summary>
    /// Defines deflate decoder for the http content.
    /// </summary>
    public class DeflateContentDecoder : IDecodeContent
    {
        /// <summary>
        /// Returns DeflateStream in decompress mode.
        /// </summary>
        public Stream GetDecompressionStream(Stream stream)
        {
            return new DeflateStream(stream, CompressionMode.Decompress);
        }
    }
}


text:
package org.keycloak.protocol.oidc;

import org.jboss.resteasy.annotations.cache.NoCache;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import org.keycloak.OAuth2Constants;
import org.keycloak.events.EventBuilder;
import org.keycloak.jose.jwk.JWK;
import org.keycloak.jose.jwk.JWKBuilder;
import org.keycloak.forms.login.LoginFormsProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.protocol.oidc.endpoints.AuthorizationEndpoint;
import org.keycloak.protocol.oidc.endpoints.LoginStatusIframeEndpoint;
import org.keycloak.protocol.oidc.endpoints.LogoutEndpoint;
import org.keycloak.protocol.oidc.endpoints.TokenEndpoint;
import org.keycloak.protocol.oidc.endpoints.UserInfoEndpoint;
import org.keycloak.protocol.oidc.representations.JSONWebKeySet;
import org.keycloak.services.ServicesLogger;
import org.keycloak.services.resources.RealmsResource;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import javax.ws.rs.core.UriInfo;

/**
 * Resource class for the oauth/openid connect token service
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
public class OIDCLoginProtocolService {

    protected static final ServicesLogger logger = ServicesLogger.ROOT_LOGGER;

    private RealmModel realm;
    private TokenManager tokenManager;
    private EventBuilder event;

    @Context
    private UriInfo uriInfo;

    @Context
    private KeycloakSession session;

    @Context
    private HttpHeaders headers;

    public OIDCLoginProtocolService(RealmModel realm, EventBuilder event) {
        this.realm = realm;
        this.tokenManager = new TokenManager();
        this.event = event;
    }

    public static UriBuilder tokenServiceBaseUrl(UriInfo uriInfo) {
        UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
        return tokenServiceBaseUrl(baseUriBuilder);
    }

    public static UriBuilder tokenServiceBaseUrl(UriBuilder baseUriBuilder) {
        return baseUriBuilder.path(RealmsResource.class).path("{realm}/protocol/" + OIDCLoginProtocol.LOGIN_PROTOCOL);
    }

    public static UriBuilder authUrl(UriInfo uriInfo) {
        UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
        return authUrl(baseUriBuilder);
    }

    public static UriBuilder authUrl(UriBuilder baseUriBuilder) {
        UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
        return uriBuilder.path(OIDCLoginProtocolService.class, "auth");
    }

    public static UriBuilder tokenUrl(UriBuilder baseUriBuilder) {
        UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
        return uriBuilder.path(OIDCLoginProtocolService.class, "token");
    }

    public static UriBuilder tokenIntrospectionUrl(UriBuilder baseUriBuilder) {
        return tokenUrl(baseUriBuilder).path(TokenEndpoint.class, "introspect");
    }

    public static UriBuilder logoutUrl(UriInfo uriInfo) {
        UriBuilder baseUriBuilder = uriInfo.getBaseUriBuilder();
        return logoutUrl(baseUriBuilder);
    }

    public static UriBuilder logoutUrl(UriBuilder baseUriBuilder) {
        UriBuilder uriBuilder = tokenServiceBaseUrl(baseUriBuilder);
        return uriBuilder.path(OIDCLoginProtocolService.class, "logout");
    }

    /**
     * Authorization endpoint
     */
    @Path("auth")
    public Object auth() {
        AuthorizationEndpoint endpoint = new AuthorizationEndpoint(realm, event);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint;
    }

    /**
     * Registration endpoint
     */
    @Path("registrations")
    public Object registerPage() {
        AuthorizationEndpoint endpoint = new AuthorizationEndpoint(realm, event);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint.register();
    }

    /**
     * Forgot-Credentials endpoint
     */
    @Path("forgot-credentials")
    public Object forgotCredentialsPage() {
        AuthorizationEndpoint endpoint = new AuthorizationEndpoint(realm, event);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint.forgotCredentials();
    }

    /**
     * Token endpoint
     */
    @Path("token")
    public Object token() {
        TokenEndpoint endpoint = new TokenEndpoint(tokenManager, realm, event);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint;
    }

    @Path("login-status-iframe.html")
    public Object getLoginStatusIframe() {
        LoginStatusIframeEndpoint endpoint = new LoginStatusIframeEndpoint(realm);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint;
    }

    @GET
    @Path("certs")
    @Produces(MediaType.APPLICATION_JSON)
    @NoCache
    public JSONWebKeySet certs() {
        JSONWebKeySet keySet = new JSONWebKeySet();
        keySet.setKeys(new JWK[]{JWKBuilder.create().rs256(realm.getPublicKey())});
        return keySet;
    }

    @Path("userinfo")
    public Object issueUserInfo() {
        UserInfoEndpoint endpoint = new UserInfoEndpoint(tokenManager, realm);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint;
    }

    @Path("logout")
    public Object logout() {
        LogoutEndpoint endpoint = new LogoutEndpoint(tokenManager, realm, event);
        ResteasyProviderFactory.getInstance().injectProperties(endpoint);
        return endpoint;
    }

    @Path("oauth/oob")
    @GET
    public Response installedAppUrnCallback(final @QueryParam("code") String code, final @QueryParam("error") String error, final @QueryParam("error_description") String errorDescription) {
        LoginFormsProvider forms = session.getProvider(LoginFormsProvider.class);
        if (code != null) {
            return forms.setClientSessionCode(code).createCode();
        } else {
            return forms.setError(error).createCode();
        }
    }

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
RelationToViewerImpl
</TITLE>

<META NAME="date" CONTENT="2011-06-10">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

com.google.code.linkedinapi.schema.xpp

Class RelationToViewerImpl

java.lang.Object
  com.google.code.linkedinapi.schema.xpp.BaseSchemaEntity
      com.google.code.linkedinapi.schema.xpp.RelationToViewerImpl

All Implemented Interfaces:
RelationToViewer, SchemaEntity, java.io.Serializable

public class RelationToViewerImpl
extends BaseSchemaEntity
implements RelationToViewer

See Also:
Serialized Form

Constructor Summary

RelationToViewerImpl()

Method Summary

 java.lang.Long
getDistance()

          Gets the value of the distance property.

 RelatedConnections
getRelatedConnections()

          Gets the value of the relatedConnections property.

 void
init(org.xmlpull.v1.XmlPullParser parser)

          Inits the.

 void
setDistance(java.lang.Long value)

          Sets the value of the distance property.

 void
setRelatedConnections(RelatedConnections value)

          Sets the value of the relatedConnections property.

 void
toXml(org.xmlpull.v1.XmlSerializer serializer)

          To xml.

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Constructor Detail

RelationToViewerImpl

public RelationToViewerImpl()

Method Detail

getRelatedConnections

public RelatedConnections getRelatedConnections()

Description copied from interface: RelationToViewer

Gets the value of the relatedConnections property.

Specified by:
getRelatedConnections in interface RelationToViewer

Returns:
possible object is
     RelatedConnections

setRelatedConnections

public void setRelatedConnections(RelatedConnections value)

Description copied from interface: RelationToViewer

Sets the value of the relatedConnections property.

Specified by:
setRelatedConnections in interface RelationToViewer

Parameters:
value - allowed object is
     RelatedConnections

getDistance

public java.lang.Long getDistance()

Description copied from interface: RelationToViewer

Gets the value of the distance property.

Specified by:
getDistance in interface RelationToViewer

Returns:
possible object is
     String

setDistance

public void setDistance(java.lang.Long value)

Description copied from interface: RelationToViewer

Sets the value of the distance property.

Specified by:
setDistance in interface RelationToViewer

Parameters:
value - allowed object is
     String

init

public void init(org.xmlpull.v1.XmlPullParser parser)
          throws java.io.IOException,
                 org.xmlpull.v1.XmlPullParserException

Description copied from class: BaseSchemaEntity

Inits the.

Specified by:
init in class BaseSchemaEntity

Parameters:
parser - the element

Throws:

java.io.IOException - TODO

org.xmlpull.v1.XmlPullParserException - TODO

toXml

public void toXml(org.xmlpull.v1.XmlSerializer serializer)
           throws java.io.IOException

Description copied from class: BaseSchemaEntity

To xml.

Specified by:
toXml in class BaseSchemaEntity

Parameters:
serializer - the document

Throws:

java.io.IOException - TODO

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
package org.eclipse.collections.api.multimap.sortedbag;

import org.eclipse.collections.api.bag.sorted.ImmutableSortedBag;
import org.eclipse.collections.api.block.function.Function;
import org.eclipse.collections.api.block.function.Function2;
import org.eclipse.collections.api.block.predicate.Predicate2;
import org.eclipse.collections.api.multimap.bag.ImmutableBagIterableMultimap;
import org.eclipse.collections.api.multimap.bag.ImmutableBagMultimap;
import org.eclipse.collections.api.multimap.list.ImmutableListMultimap;
import org.eclipse.collections.api.tuple.Pair;

/**
 * @since 4.2
 */
public interface ImmutableSortedBagMultimap<K, V>
        extends ImmutableBagIterableMultimap<K, V>, SortedBagMultimap<K, V>
{
    @Override
    ImmutableSortedBag<V> get(K key);

    @Override
    ImmutableSortedBagMultimap<K, V> newEmpty();

    @Override
    ImmutableSortedBagMultimap<K, V> newWith(K key, V value);

    @Override
    ImmutableSortedBagMultimap<K, V> newWithout(Object key, Object value);

    @Override
    ImmutableSortedBagMultimap<K, V> newWithAll(K key, Iterable<? extends V> values);

    @Override
    ImmutableSortedBagMultimap<K, V> newWithoutAll(Object key);

    @Override
    ImmutableBagMultimap<V, K> flip();

    @Override
    ImmutableSortedBagMultimap<K, V> selectKeysValues(Predicate2<? super K, ? super V> predicate);

    @Override
    ImmutableSortedBagMultimap<K, V> rejectKeysValues(Predicate2<? super K, ? super V> predicate);

    @Override
    ImmutableSortedBagMultimap<K, V> selectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate);

    @Override
    ImmutableSortedBagMultimap<K, V> rejectKeysMultiValues(Predicate2<? super K, ? super Iterable<V>> predicate);

    @Override
    <K2, V2> ImmutableBagMultimap<K2, V2> collectKeysValues(Function2<? super K, ? super V, Pair<K2, V2>> function);

    @Override
    <V2> ImmutableListMultimap<K, V2> collectValues(Function<? super V, ? extends V2> function);
}


text:
@implementation CHWebProgressView{
    CAShapeLayer *_shapeLayer;
    UIView *_progressBarView;
    float _fadeOutDelay;
}
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _springSpeed = 0.4;
        _duration = 0.5;
        _springVelocity = 0.5;
        _fadeOutDelay = 0.5f;
        self.userInteractionEnabled = NO;
        self.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _progressBarView = [[UIView alloc] initWithFrame:self.bounds];
        _progressBarView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
        UIColor *tintColor = [UIColor colorWithRed:22.f / 255.f green:126.f / 255.f blue:251.f / 255.f alpha:1.0]; // iOS7 Safari bar color
        if ([UIApplication.sharedApplication.delegate.window respondsToSelector:@selector(setTintColor:)] && UIApplication.sharedApplication.delegate.window.tintColor) {
            tintColor = UIApplication.sharedApplication.delegate.window.tintColor;
        }
        _progressBarView.backgroundColor = tintColor;
        _progressBarView.alpha = 0;
        [self addSubview:_progressBarView];
    }
    return self;
}
- (void)setColor:(UIColor *)color{
    _color = color;
    _progressBarView.backgroundColor = color;
}
- (void)setProgress:(NSProgress *)progress{
    _progress = progress;
    float fProgress = (float)progress.completedUnitCount/(float)progress.totalUnitCount;
    if (fProgress >= 1.0) {
        [UIView animateWithDuration:_duration delay:_fadeOutDelay options:UIViewAnimationOptionCurveEaseInOut animations:^{
            CGRect frame = _progressBarView.frame;
            frame.size.width = fProgress * self.bounds.size.width;
            _progressBarView.frame = frame;
        } completion:^(BOOL finished) {
            _progressBarView.alpha = 0.0;
            CGRect frame = _progressBarView.frame;
            frame.size.width = 0;
            _progressBarView.frame = frame;
        }];
    }
    else {
        _progressBarView.alpha = 1;
        [UIView animateWithDuration:_duration delay:0 usingSpringWithDamping:_springSpeed initialSpringVelocity:_springVelocity options:0 animations:^{
            CGRect frame = _progressBarView.frame;
            frame.size.width = fProgress * self.bounds.size.width;
            _progressBarView.frame = frame;
        } completion:NULL];
    }
}

@end


text:
namespace viz {

class TestLatestLocalSurfaceIdLookupDelegate
    : public LatestLocalSurfaceIdLookupDelegate {
 public:
  TestLatestLocalSurfaceIdLookupDelegate();

  TestLatestLocalSurfaceIdLookupDelegate(
      const TestLatestLocalSurfaceIdLookupDelegate&) = delete;
  TestLatestLocalSurfaceIdLookupDelegate& operator=(
      const TestLatestLocalSurfaceIdLookupDelegate&) = delete;

  ~TestLatestLocalSurfaceIdLookupDelegate() override;

  // LatestLocalSurfaceIdLookupDelegate:
  LocalSurfaceId GetSurfaceAtAggregation(
      const FrameSinkId& frame_sink_id) const override;

  void SetSurfaceIdMap(const SurfaceId& surface_id);

 private:
  base::flat_map<FrameSinkId, LocalSurfaceId> surface_id_map_;
};

}  // namespace viz

#endif  // COMPONENTS_VIZ_TEST_TEST_LATEST_LOCAL_SURFACE_ID_LOOKUP_DELEGATE_H_


text:
package ru.job4j.exam;

import java.util.ArrayList;

/**
 * CoffeeMachine.
 * @author Ivan Belyaev
 * @since 04.12.2017
 * @version 1.0
 */
public class CoffeeMachine {
    /** Available coins. */
    private int[] coins = {10, 5, 2, 1};

    /**
     * Method give change from a vending machine.
     * @param value - the amount of money invested in the machine.
     * @param price - the price of the goods.
     * @throws NotEnoughMoneyException thrown when there is insufficient amount of funds.
     * @return returns an array of coins.
     */
    public int[] changes(int value, int price) throws NotEnoughMoneyException {
        ArrayList<Integer> list = new ArrayList<>();

        if (value - price < 0) {
            throw new NotEnoughMoneyException("Not enough money.");
        }

        int change = value - price;

        for (int i = 0; i < coins.length; i++) {
            while (change / coins[i] > 0) {
                list.add(coins[i]);
                change -= coins[i];
            }
        }

        int[] result = new int[list.size()];
        for (int i = 0; i < result.length; i++) {
            result[i] = list.get(i);
        }

        return result;
    }
}


text:
import { SteeringBehavior } from '../SteeringBehavior.js';
import { Vector3 } from '../../math/Vector3.js';

const desiredVelocity = new Vector3();
const displacement = new Vector3();

/**
* This steering behavior produces a force that directs an agent toward a target position.
* Unlike {@link SeekBehavior}, it decelerates so the agent comes to a gentle halt at the target position.
*
* @author {@link https://github.com/Mugen87|Mugen87}
* @augments SteeringBehavior
*/
class ArriveBehavior extends SteeringBehavior {

	/**
	* Constructs a new arrive behavior.
	*
	* @param {Vector3} target - The target vector.
	* @param {Number} deceleration - The amount of deceleration.
	* @param {Number} tolerance - A tolerance value in world units to prevent the vehicle from overshooting its target.
	*/
	constructor( target = new Vector3(), deceleration = 3, tolerance = 0 ) {

		super();

		/**
		* The target vector.
		* @type {Vector3}
		*/
		this.target = target;

		/**
		* The amount of deceleration.
		* @type {Number}
		* @default 3
		*/
		this.deceleration = deceleration;

		/**
		* A tolerance value in world units to prevent the vehicle from overshooting its target.
		* @type {Number}
		* @default 0
		*/
		this.tolerance = tolerance;

	}

	/**
	* Calculates the steering force for a single simulation step.
	*
	* @param {Vehicle} vehicle - The game entity the force is produced for.
	* @param {Vector3} force - The force/result vector.
	* @param {Number} delta - The time delta.
	* @return {Vector3} The force/result vector.
	*/
	calculate( vehicle, force /*, delta */ ) {

		const target = this.target;
		const deceleration = this.deceleration;

		displacement.subVectors( target, vehicle.position );

		const distance = displacement.length();

		if ( distance > this.tolerance ) {

			// calculate the speed required to reach the target given the desired deceleration

			let speed = distance / deceleration;

			// make sure the speed does not exceed the max

			speed = Math.min( speed, vehicle.maxSpeed );

			// from here proceed just like "seek" except we don't need to normalize
			// the "displacement" vector because we have already gone to the trouble
			// of calculating its length.

			desiredVelocity.copy( displacement ).multiplyScalar( speed / distance );

		} else {

			desiredVelocity.set( 0, 0, 0 );

		}

		return force.subVectors( desiredVelocity, vehicle.velocity );

	}

	/**
	* Transforms this instance into a JSON object.
	*
	* @return {Object} The JSON object.
	*/
	toJSON() {

		const json = super.toJSON();

		json.target = this.target.toArray( new Array() );
		json.deceleration = this.deceleration;

		return json;

	}

	/**
	* Restores this instance from the given JSON object.
	*
	* @param {Object} json - The JSON object.
	* @return {ArriveBehavior} A reference to this behavior.
	*/
	fromJSON( json ) {

		super.fromJSON( json );

		this.target.fromArray( json.target );
		this.deceleration = json.deceleration;

		return this;

	}

}

export { ArriveBehavior };


text:
title: IRC meeting summary for 2016-06-09
permalink: /en/meetings/2016/06/09/
name: 2016-06-09-meeting
type: meetings
layout: page
lang: en
version: 1
---
{% include toc.html %}

- [Link to this week logs](https://botbot.me/freenode/bitcoin-core-dev/2016-06-09/?msg=67610017&page=3)
- [Meeting minutes by meetbot](http://www.erisian.com.au/meetbot/bitcoin-core-dev/2016/bitcoin-core-dev.2016-06-09-19.00.html)

---

## Main topics

- compile-time / memory usage
- segwit update
- Compactblock testing

## Notes / short topics

- The feature freeze for Bitcoin Core is [scheduled](https://github.com/bitcoin/bitcoin/issues/7679) next week, all the features that need to be merged should be merged before that time. Cfields has 2 p2p refactor PR's he'd like to get in, which can be done after the freeze as those aren't new features.
- After [last meetings comment](https://bitcoincore.org/en/meetings/2016/06/02/#notes--short-topics) about the [software life cycle page](https://bitcoincore.org/en/lifecycle/) Btcdrak and David Harding have been working to update that page to make it more clear and representative [here](https://github.com/bitcoin-core/bitcoincore.org/pull/179) and further [here](https://github.com/btcdrak/bitcoincore.org/pull/2), this needs review.

## compile-time / memory usage

### background

Issue [6658](https://github.com/bitcoin/bitcoin/issues/6658) (Building requires >1GB memory) and [7471](https://github.com/bitcoin/bitcoin/issues/7471) (Not a lot of headroom for building with 512 MB RAM) talk about the increasing need for RAM while compiling.

### meeting comments

Gmaxwell notes we can no longer compile on hosts with only 2GB of RAM with default settings, while we have documentation that says 1.5GB.

TheBlueMatt has a patch ready that moves all the mempool stuff out of it, which apparently gets it back to 1.5GB. He hasn't made the pull request yet though.

Wumpus notes building with [Clang](https://en.wikipedia.org/wiki/Clang) usually uses a lot less memory at the same compile settings.

The compile time probably correlates with the memory usage as disk seek/read access is negligible.

Adding binary builds for ARM and AARCH64 would reduce the amount of complaints about memory problems. Cfields is working on this. Users can currently use [cross-compilation](https://github.com/bitcoin/bitcoin/blob/master/doc/build-unix.md#arm-cross-compilation), however gmaxwell notes a lot of people using raspberry pi-like systems do not have another linux host.

### meeting conclusion

Cfields plans to add ARM binaries without GUI for 0.13 (Done after the meeting in PR [#8188][])

## Segwit update

### background

Developers are working on a soft fork to introduce segregated witness onto Bitcoin mainnet. Segregated witness (segwit) allows transaction signature data to be stored outside of the data hashed to produce transaction identifiers, removing all known forms of third-party malleability, allowing full nodes to compile the current UTXO set without downloading all signatures, and laying the groundwork for fraud proofs that can allow lightweight (SPV) clients to help enforce more of the consensus rules. The segwit soft fork also allows miners to substitute 1 byte of block space with 4 bytes of segwit data, increasing transaction capacity for wallets that use segwit. segregated witness BIPs: [BIP141][], [BIP142][], [BIP143][], [BIP144][] and [BIP145][]

### meeting comments

There are still some bugs that need to be fixed before the code minus the softfork can go into 0.13. Sipa notes everything will be addressed in the next batch of patches.

Luke-jr would like the maximum witness program length to be 75 bytes as opposed to the 40 bytes it is now. He argues there's no point in limiting (below 75, as above 75 would require more changes and additional testing) and smaller limits could very well prevent future softforks. Expanding the limit later on would require a hardfork. Sipa argues there should be no need for more than 256-bit hash + some versioning metadata, setting it to more would give the impression that there is, or as petertodd elaborates: would give the impression bitcoin is more broken than that. Gmaxwell chimes in and thinks the biggest harm he sees is that allowing a larger size potentially limits the ability to make UTXO entries limited in size in the future. However further limiting can happen later on. He also notes it is possible to expand this in the future by using a different version type signaling, however that would require a new commitment in addition to the current one.

### meeting conclusion

Discussion kept going and was deferred to off-meeting.

## Compactblock testing

### background

[BIP152][]: "Compact block relay" is a proposed idea by BlueMatt for decreasing the bandwidth used during block relay by using short transaction IDs for transactions that should be in the mempool of the node. As a side-effect this also results in reducing the block transfer latency.

### meeting comments

There are a number of nodes running compactblocks on the public network and everything seems to be working well. Instagibbs made a [chart](http://imgur.com/iq2lRGl) of it. Gmaxwell has been running tests with a modified version that reduces the hash size to 16 bits to test rare corner cases surrounding collisions by making them more common. Two large mining pools have been running it, one of which is behind the great firewall of china.

Cfields wonders if there's been discussion about a servicebit for compact blocks. The argument brought up before was that service bits should only be used for critically required services. Since it's likely to become sufficiently ubiquitous fast enough it won't be needed. Only the miners would really need it, but they should be curating their connections manually anyway.

### meeting conclusion

- The interaction with block fetching logic needs more review.
- Reviewers should stop using sipa's branch, as PR [#8068][] has been rebased on top of the [shared_ptr work][#8126].
- Review PR [#8084][] (Add recently accepted blocks and txn to AttemptToEvictConnection)

## Comic relief

{% highlight text %}
wumpus       #link https://github.com/bitcoin/bitcoin/issues/7471
cfields_     wumpus: thanks
wumpus       eeh that's the wrong one
gmaxwell     wumpus: unthanks

Lightsword   maybe we should just have a service bit for flagging fast relay nodes/miners in general for preferential peering rather than making it flag compact blocks specifically
sipa         Lightsword: we should also have an evil bit that abusive nodes should set
{% endhighlight %}

## Participants

| IRC nick      | Name/Nym                  |
|---------------|---------------------------|
| Luke-jr       | [Luke Dashjr][]           |
| jonasschnelli | [Jonas Schnelli][]        |
| petertodd     | [Peter Todd][]            |
| sipa          | [Pieter Wuille][]         |
| gmaxwell      | [Gregory Maxwell][]       |
| wumpus        | [Wladimir van der Laan][] |
| instagibbs    | [Gregory Sanders][]       |
| cfields       | [Cory Fields][]           |
| btcdrak       | [BtcDrak][]               |
| jeremyrubin   | [Jeremy Rubin][]          |
| sdaftuar      | [Suhas Daftuar][]         |
| BakSAj        | BakSAj                    |
| CodeShark     | [Eric Lombrozo][]         |
| MarcoFalke    | [Marco Falke][]           |
| Lightsword    | Lightsword                |

## Disclaimer

This summary was compiled without input from any of the participants in the discussion, so any errors are the fault of the summary author and not the discussion participants.

[#8188]: https://github.com/bitcoin/bitcoin/pull/8188
[#8068]: https://github.com/bitcoin/bitcoin/pull/8068
[#8126]: https://github.com/bitcoin/bitcoin/pull/8126
[#8084]: https://github.com/bitcoin/bitcoin/pull/8084

{% include references.md %}


text:
DesignFrame::DesignFrame(ShaderGroup * shaders) : GameSystem(shaders),
	//Setup the editor with a connection to the camera
	editor(&Camera),
	modeSelector(&editor) {
	//Move this into a load section
	toEdit = new Structure();
	toEdit->Extents = vec3(10,10,5);

	editor.EditStructure(toEdit);
	Camera.SetCameraView(toEdit->Extents*.5f);
	mouseDown = false;
	panning = false;

	matWindow.position = Rect(0,0,200,200);
	matWindow.hPin = Control::MAX;
	matWindow.vPin = Control::CENTER;
	matSelector = new MaterialSelectionControl();
	matSelector->position = Rect(10,10,180,180);
	matWindow.AddControl(matSelector);
	Controls.AddWindow(&matWindow);

	fileMenu = new FileMenuWindow(&editor);
	Controls.AddWindow(fileMenu);

	Controls.AddWindow(&modeSelector);
}
DesignFrame::~DesignFrame() {

}

void DesignFrame::OnFrameFocus() {

}

void DesignFrame::Build() {

}

bool DesignFrame::Update(double delta,double now, vector<InputEvent> inputEvents) {
	//Issue events to dialog
	//Run the dialog system and monitor pressed keys
	//events read by the dialog system are removed from the list of events
	passEventsToControl(inputEvents);

	//Read events and apply to camera rotation
	for (auto e : inputEvents) {
		if (e.Event == InputEvent::MouseDown) {
			mouseDown = true;
			prevMousePos = vec2(e.MouseX,e.MouseY);
			mouseHeldAt = OS::Now();
		}
		else if (e.Event == InputEvent::MouseUp) {
			if (!panning) {
				//The user clicked this position
				editor.SetMaterial(matSelector->GetSelectedMaterial());
				editor.PlaceVoxel();
			}
			panning = false;
			mouseDown = false;
		}
		else if (e.Event == InputEvent::MouseMove) {
			if (mouseDown) {
				vec2 cur = vec2(e.MouseX,e.MouseY);
				vec2 diff = cur - prevMousePos;

				if (panning) {
					//Apply rotation in degrees (1 degree per pixel of mouse movement)
					Camera.Pan += diff.x;
					Camera.Tilt += diff.y;
					//Save the new mouse pos
					prevMousePos = cur;
				}
				else {
					//If the user holds down click for a long time, or moves the mouse around
					//assume they want to be panning
					if ((OS::Now() - mouseHeldAt) > .3)
						panning = true;
					else if (glm::length(cur - prevMousePos) > 15)
						panning = true;
				}

			}
		}
		else if (e.Event == InputEvent::MouseScroll) {
			Camera.Distance += e.Key*-5;
			if (Camera.Distance > 100)
				Camera.Distance = 100;
			if (Camera.Distance < 5)
				Camera.Distance = 5;
		}
	}

	//Pass events to the editor if the user isn't holding the mouse
	if (!mouseDown)
		editor.ReadInput(inputEvents);

	//Update which mode is shown
	modeSelector.Update();

	return true;
}

void DesignFrame::Draw(double width, double height) {
	vec2 viewPortSize = vec2((float)width,(float)height);
	//Save size in camera as well (for unprojection)
	Camera.UpdateViewSize(viewPortSize);

	//Update the texture caching system
	Textures.Refresh();

	//Startup 3d rendering
	GL3DProgram * shaders3d = (GL3DProgram*)shaders->GetShader("3d");
	shaders3d->UseProgram();
	//Setup basics of shader program per-frame
	shaders3d->Model.Reset();
	shaders3d->Model.Apply();
	shaders3d->Acid.SetCurrentTime(VoxEngine::GetGameSimTime());
	//Acid factor currently managed by the demo system
	//this will be moved to a more powerful game logic system in the future
	shaders3d->Acid.SetAcidFactor(0.0);
	shaders3d->Fog.SetFogDistance(5000.0f);
	//Enable sensible defaults
	glEnable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);
	glDisable(GL_CULL_FACE);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	//Apply the camera
	Camera.Draw(shaders3d);

	//Draw the editor
	editor.Draw(shaders3d);

	//Call the parent draw to draw interface
	GameSystem::Draw(width,height);

}


text:
clean(EIGEN)
fpath(EIGEN "Eigen/Eigen" Eigen PATH_SUFFIXES "eigen2")
export_header(EIGEN)


text:
import os
import time
import Queue
import logging
from task_queue import TaskQueue
from libs import counter
logger = logging.getLogger('scheduler')

class Scheduler(object):
    UPDATE_PROJECT_INTERVAL = 5*60
    default_schedule = {
            'priority': 0,
            'retries': 3,
            'exetime': 0,
            'age': 30*24*60*60,
            'itag': None,
            }
    LOOP_LIMIT = 1000
    LOOP_INTERVAL = 0.1

    def __init__(self, taskdb, projectdb, newtask_queue, status_queue, out_queue, data_path = './data'):
        self.taskdb = taskdb
        self.projectdb = projectdb
        self.newtask_queue = newtask_queue
        self.status_queue = status_queue
        self.out_queue = out_queue
        self.data_path = data_path

        self._quit = False
        self.projects = dict()
        self._last_update_project = 0
        self.task_queue = dict()
        self._last_tick = int(time.time() / 60)

        self._cnt = {
                "5m": counter.CounterManager(
                    lambda : counter.TimebaseAverageWindowCounter(30, 10)),
                "1h": counter.CounterManager(
                    lambda : counter.TimebaseAverageWindowCounter(60, 60)),
                "1d": counter.CounterManager(
                    lambda : counter.TimebaseAverageWindowCounter(10*60, 24*6)),
                "all": counter.CounterManager(
                    lambda : counter.TotalCounter()),
                }
        self._cnt['1h'].load(os.path.join(self.data_path, 'scheduler.1h'))
        self._cnt['1d'].load(os.path.join(self.data_path, 'scheduler.1d'))
        self._cnt['all'].load(os.path.join(self.data_path, 'scheduler.all'))
        self._last_dump_cnt = 0

    def _load_projects(self):
        self.projects = dict()
        for project in self.projectdb.get_all():
            self.projects[project['name']] = project
        self._last_update_project = time.time()

    def _update_projects(self):
        now = time.time()
        if self._last_update_project + self.UPDATE_PROJECT_INTERVAL > now:
            return
        for project in self.projectdb.check_update(self._last_update_project):
            logger.debug("project: %s updated." % project['name'])
            self.projects[project['name']] = project
            if project['name'] not in self.task_queue:
                self._load_tasks(project['name'])
            if project['status'] in ('RUNNING', 'DEBUG'):
                self.task_queue[project['name']].rate = project['rate']
                self.task_queue[project['name']].burst = project['burst']
            else:
                self.task_queue[project['name']].rate = 0
                self.task_queue[project['name']].burst = 0
        self._last_update_project = now

    scheduler_task_fields = ['taskid', 'project', 'schedule', ]
    def _load_tasks(self, project):
        self.task_queue[project] = TaskQueue(rate=0, burst=0)
        for task in self.taskdb.load_tasks(self.taskdb.ACTIVE, project, self.scheduler_task_fields):
            taskid = task['taskid']
            _schedule = task.get('schedule', self.default_schedule)
            priority = _schedule.get('priority', self.default_schedule['priority'])
            exetime = _schedule.get('exetime', self.default_schedule['exetime'])
            self.task_queue[project].put(taskid, priority, exetime)
        if self.projects[project]['status'] in ('RUNNING', 'DEBUG'):
            self.task_queue[project].rate = self.projects[project]['rate']
            self.task_queue[project].burst = self.projects[project]['burst']
        else:
            self.task_queue[project].rate = 0
            self.task_queue[project].burst = 0
        self._cnt['all'].value((project, 'pending'), len(self.task_queue[project]))

    def task_verify(self, task):
        for each in ('taskid', 'project', 'url', ):
            if each not in task or not task[each]:
                logger.error('%s not in task: %s' % (each, unicode(task)[:200]))
                return False
        if task['project'] not in self.task_queue:
            logger.error('unknow project: %s' % task['project'])
            return False
        return True

    def insert_task(self, task):
        return self.taskdb.insert(task['project'], task['taskid'], task)

    def update_task(self, task):
        return self.taskdb.update(task['project'], task['taskid'], task)

    def put_task(self, task):
        _schedule = task.get('schedule', self.default_schedule)
        self.task_queue[task['project']].put(task['taskid'],
                priority=_schedule.get('priority', self.default_schedule['priority']),
                exetime=_schedule.get('exetime', self.default_schedule['exetime']))

    def send_task(self, task):
        self.out_queue.put(task)

    def _check_task_done(self):
        cnt = 0
        try:
            while cnt < self.LOOP_LIMIT:
                task = self.status_queue.get_nowait()
                if not self.task_verify(task):
                    continue
                self.task_queue[task['project']].done(task['taskid'])
                task = self.on_task_status(task)
                cnt += 1
        except Queue.Empty:
            pass
        return cnt

    merge_task_fields = ['taskid', 'project', 'url', 'status', 'schedule', 'lastcrawltime']
    def _check_request(self):
        cnt = 0
        try:
            while cnt < self.LOOP_LIMIT:
                task = self.newtask_queue.get_nowait()
                if not self.task_verify(task):
                    continue
                if task['taskid'] in self.task_queue[task['project']]:
                    if not task.get('schedule', {}).get('force_update', False):
                        logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s' % task)
                        continue
                oldtask = self.taskdb.get_task(task['project'], task['taskid'],
                        fields=self.merge_task_fields)
                if oldtask:
                    task = self.on_old_request(task, oldtask)
                else:
                    task = self.on_new_request(task)
                cnt += 1
        except Queue.Empty:
            pass
        return cnt

    def _check_cronjob(self):
        now = time.time()
        if now - self._last_tick * 60 < 60:
            return
        self._last_tick += 1
        for project in self.projects.itervalues():
            if project['status'] not in ('DEBUG', 'RUNNING'):
                continue
            self.send_task({
                'taskid': 'on_cronjob',
                'project': project['name'],
                'url': 'data:,on_cronjob',
                'status': self.taskdb.ACTIVE,
                'fetch': {
                    'save': {
                        'tick': self._last_tick,
                        },
                    },
                'process': {
                    'callback': 'on_cronjob',
                    },
                'project_updatetime': self.projects[project['name']].get('updatetime', 0),
                })

    request_task_fields = ['taskid', 'project', 'url', 'status', 'fetch', 'process', 'track', 'lastcrawltime']
    def _check_select(self):
        cnt_dict = dict()
        for project, task_queue in self.task_queue.iteritems():
            # task queue
            self.task_queue[project].check_update()
            cnt = 0
            taskid = task_queue.get()
            while taskid and cnt < self.LOOP_LIMIT / 10:
                task = self.taskdb.get_task(project, taskid, fields=self.request_task_fields)
                # inform processor project may updated
                task['project_updatetime'] = self.projects[project].get('updatetime', 0)
                task = self.on_select_task(task)
                taskid = task_queue.get()
                cnt += 1
            cnt_dict[project] = cnt
        return cnt_dict

    def _dump_cnt(self):
        self._cnt['1h'].dump(os.path.join(self.data_path, 'scheduler.1h'))
        self._cnt['1d'].dump(os.path.join(self.data_path, 'scheduler.1d'))
        self._cnt['all'].dump(os.path.join(self.data_path, 'scheduler.all'))

    def _try_dump_cnt(self):
        now = time.time()
        if now - self._last_dump_cnt > 60:
            self._last_dump_cnt = now
            self._dump_cnt()

    def __len__(self):
        return sum((len(x) for x in self.task_queue.itervalues()))

    def quit(self):
        self._quit = True

    def run(self):
        logger.info("loading projects")
        self._load_projects()
        for i, project in enumerate(self.projects.keys()):
            self._load_tasks(project)
            logger.info("loading tasks from %s loaded %d tasks -- %d/%d" % (project, len(self.task_queue[project]),
                i+1, len(self.projects)))

        while not self._quit:
            try:
                self._update_projects()
                self._check_task_done()
                self._check_request()
                self._check_cronjob()
                self._check_select()
                time.sleep(self.LOOP_INTERVAL)
            except KeyboardInterrupt:
                break

        logger.info("scheduler exiting...")
        self._dump_cnt()

    def xmlrpc_run(self, port=23333, bind='127.0.0.1', logRequests=False):
        from SimpleXMLRPCServer import SimpleXMLRPCServer

        server = SimpleXMLRPCServer((bind, port), allow_none=True, logRequests=logRequests)
        server.register_introspection_functions()
        server.register_multicall_functions()

        server.register_function(self.quit, '_quit')
        server.register_function(self.__len__, 'size')
        def dump_counter(_time, _type):
            return self._cnt[_time].to_dict(_type)
        server.register_function(dump_counter, 'counter')
        def new_task(task):
            if self.task_verify(task):
                self.newtask_queue.put(task)
                return True
            return False
        server.register_function(new_task, 'newtask')
        def update_project():
            self._last_update_project = 0
        server.register_function(update_project, 'update_project')

        server.serve_forever()

    def on_new_request(self, task):
        task['status'] = self.taskdb.ACTIVE
        self.insert_task(task)
        self.put_task(task)

        project = task['project']
        self._cnt['5m'].event((project, 'pending'), +1)
        self._cnt['1h'].event((project, 'pending'), +1)
        self._cnt['1d'].event((project, 'pending'), +1)
        self._cnt['all'].event((project, 'task'), +1).event((project, 'pending'), +1)
        logger.debug('new task %(project)s:%(taskid)s %(url)s' % task)
        return task

    def on_old_request(self, task, old_task):
        now = time.time()

        _schedule = task.get('schedule', self.default_schedule)
        old_schedule = old_task.get('schedule', {})

        restart = False
        if _schedule.get('itag') and _schedule['itag'] != old_schedule.get('itag'):
            restart = True
        elif _schedule.get('age', self.default_schedule['age']) + (old_task['lastcrawltime'] or 0) < now:
            restart = True
        elif _schedule.get('force_update'):
            restart = True

        if not restart:
            logger.debug('ignore newtask %(project)s:%(taskid)s %(url)s' % task)
            return

        task['status'] = self.taskdb.ACTIVE
        self.update_task(task)
        self.put_task(task)

        project = task['project']
        self._cnt['5m'].event((project, 'pending'), +1)
        self._cnt['1h'].event((project, 'pending'), +1)
        self._cnt['1d'].event((project, 'pending'), +1)
        if old_task['status'] == self.taskdb.SUCCESS:
            self._cnt['all'].event((project, 'success'), -1).event((project, 'pending'), +1)
        elif old_task['status'] == self.taskdb.FAILED:
            self._cnt['all'].event((project, 'failed'), -1).event((project, 'pending'), +1)
        logger.debug('restart task %(project)s:%(taskid)s %(url)s' % task)
        return task

    def on_task_status(self, task):
        try:
            fetchok = task['track']['fetch']['ok']
            procesok = task['track']['process']['ok']
            if task['taskid'] not in self.task_queue[task['project']].processing:
                logging.error('not processing pack: %(project)s:%(taskid)s %(url)s' % task)
                return None
        except KeyError, e:
            logger.error("Bad status pack: %s" % e)
            return None

        if fetchok and procesok:
            return self.on_task_done(task)
        else:
            return self.on_task_failed(task)

    def on_task_done(self, task):
        '''
        called by task_status
        '''
        task['status'] = self.taskdb.SUCCESS
        task['lastcrawltime'] = time.time()
        self.update_task(task)

        project = task['project']
        self._cnt['5m'].event((project, 'success'), +1)
        self._cnt['1h'].event((project, 'success'), +1)
        self._cnt['1d'].event((project, 'success'), +1)
        self._cnt['all'].event((project, 'success'), +1).event((project, 'pending'), -1)
        logger.debug('task done %(project)s:%(taskid)s %(url)s' % task)
        return task

    def on_task_failed(self, task):
        '''
        called by task_status
        '''
        old_task = self.taskdb.get_task(task['project'], task['taskid'], fields=['schedule'])
        if old_task is None:
            logging.error('unknow status pack: %s' % task)
            return
        if not task.get('schedule'):
            task['schedule'] = old_task.get('schedule', {})

        retries = task['schedule'].get('retries', self.default_schedule['retries'])
        retried = task['schedule'].get('retried', 0)
        if retried == 0:
            next_exetime = 0
        elif retried == 1:
            next_exetime = 1 * 60 * 60
        else:
            next_exetime = 6 * (2**retried) * 60 * 60

        if retried >= retries:
            task['status'] = self.taskdb.FAILED
            task['lastcrawltime'] = time.time()
            self.update_task(task)

            project = task['project']
            self._cnt['5m'].event((project, 'failed'), +1)
            self._cnt['1h'].event((project, 'failed'), +1)
            self._cnt['1d'].event((project, 'failed'), +1)
            self._cnt['all'].event((project, 'failed'), +1).event((project, 'pending'), -1)
            logger.info('task failed %(project)s:%(taskid)s %(url)s' % task)
            return task
        else:
            task['schedule']['retried'] = retried + 1
            task['schedule']['exetime'] = time.time() + next_exetime
            task['lastcrawltime'] = time.time()
            self.update_task(task)
            self.put_task(task)

            project = task['project']
            self._cnt['5m'].event((project, 'retry'), +1)
            self._cnt['1h'].event((project, 'retry'), +1)
            self._cnt['1d'].event((project, 'retry'), +1)
            logger.info('task retry %(project)s:%(taskid)s %(url)s' % task)
            return task

    def on_select_task(self, task):
        logger.debug('select %(project)s:%(taskid)s %(url)s' % task)
        self.send_task(task)
        return task