text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>T795366371106299904</title>
  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:300,300i,600">
  <link rel="stylesheet" href="/style.css">
  <link rel="stylesheet" href="/custom.css">

	<link rel="shortcut icon" href="https://micro.blog/curt/favicon.png" type="image/x-icon" />
  <link rel="alternate" type="application/rss+xml" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.xml" />

  <link rel="alternate" type="application/json" title="Curt Clifton" href="http://microblog.curtclifton.net/feed.json" />
  <link rel="EditURI" type="application/rsd+xml" href="/rsd.xml" />

  <link rel="me" href="https://micro.blog/curt" />

  	<link rel="me" href="https://twitter.com/curtclifton" />

  <link rel="authorization_endpoint" href="https://micro.blog/indieauth/auth" />
  <link rel="token_endpoint" href="https://micro.blog/indieauth/token" />
  <link rel="micropub" href="https://micro.blog/micropub" />
  <link rel="webmention" href="https://micro.blog/webmention" />
  <link rel="subscribe" href="https://micro.blog/users/follow" />

    Curt Clifton

    <time class="dt-published" datetime="2016-11-06 12:44:54 -0800">06 Nov 2016</time>

So what is Comey going to do for a follow up tomorrow? smh


text:
/*
 * SQL Server Helpers Unit Tests
 * Regression Test for Bug 1 - https://github.com/JoshKeegan/SqlServerHelpers/issues/1
 * Authors:
 *  Josh Keegan 04/01/2017
 */

using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

using NUnit.Framework;

using SqlServerHelpers;
using SqlServerHelpers.ExtensionMethods;

namespace UnitTests.Regression
{
    [TestFixture]
    public class Bug1
    {
        [Test]
        public void Bug1Repro()
        {
            // Strings of lengths longer than the first were being silently truncated to the length of the first one
            //  so just test by selecting the strings back out, with some later strings being longer than the first
            string[] expected = new string[] { "abd", "abcdefg", "def", "fghjkm" };
            SqlDbTypeSize valueField = new SqlDbTypeSize(SqlDbType.VarChar);

            using (SqlConnection conn = new SqlConnection(Constants.DATABASE_CONNECTION_STRING))
            using (SqlCommand command = conn.GetSqlCommand())
            {
                conn.Open();

                // Build the command
                command.CommandText =
                    @"SELECT v
                    FROM @vals";

                // Make the parameters
                command.Parameters.AddWithValue("@vals", expected, valueField);

                // Run the command
                command.Prepare();
                SqlDataReader reader = command.ExecuteReader();

                List<string> actual = new List<string>(expected.Length);
                while (reader.Read())
                {
                    actual.Add(reader.GetString("v"));
                }

                CollectionAssert.AreEqual(expected, actual);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
    <Properties>
        <Property name="log-path">/cassandra-logs/</Property>
        <!--<Property name="log-path">${env:LOG_PATH}</Property>-->
    </Properties>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%msg%n" />
        </Console>
        <RollingFile name="RollingFile" fileName="${log-path}/cassandra-server.log"
                     filePattern="${log-path}/server-%d{yyyy-MM-dd}-%i.log" immediateFlush="false" append="false">
            <PatternLayout>
                <pattern>%d{dd/MMM/yyyy HH:mm:ss,SSS}- %c{1}: %m%n</pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="8192 KB" />
            </Policies>
            <DefaultRolloverStrategy max="4"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <logger name="com.datastax.cassandra" level="error" />
        <logger name="com.cassava" level="debug" />
        <Root level="info" >
            <AppenderRef ref="Console" />
            <AppenderRef ref="RollingFile"/>
        </Root>
    </Loggers>
</Configuration>


text:
/* eslint-disable max-len */
/**
 * Build config for development process that uses Hot-Module-Replacement
 * https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
 */

import path from 'path';
import webpack from 'webpack';
import validate from 'webpack-validator';
import merge from 'webpack-merge';
import formatter from 'eslint-formatter-pretty';
import baseConfig from './webpack.config.base';

const port = process.env.PORT || 3000;

export default validate(merge(baseConfig, {
  debug: true,

  devtool: 'inline-source-map',

  entry: {
    vendor: [
      `webpack-hot-middleware/client?path=http://localhost:${port}/__webpack_hmr`,
      'babel-polyfill',
      'react', 'react-dom',
      'ramda', 'partial.lenses', 'karet', 'karet.util'
    ],
    bundle: [
      `webpack-hot-middleware/client?path=http://localhost:${port}/__webpack_hmr`,
      './app/index'
    ]
  },

  resolve: {
    root: [
      path.resolve('./app')
    ]
  },

  output: {
    filename: '[name].js',
    publicPath: `http://localhost:${port}/dist/`
  },

  module: {
    // preLoaders: [
    //   {
    //     test: /\.js$/,
    //     loader: 'eslint-loader',
    //     exclude: /node_modules/
    //   }
    // ],
    loaders: [
      {
        test: /\.global\.css$/,
        loaders: [
          'style-loader',
          'css-loader?sourceMap'
        ]
      },
      {
        test: /\.global\.scss$/,
        loaders: [
          'style-loader',
          'css-loader?sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'sass-loader?sourceMap&localIdentName=[name]__[local]___[hash:base64:5]'
        ]
      },
      {
        test: /^((?!\.global).)*\.scss$/,
        loaders: [
          'style-loader',
          'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
          'sass-loader?sourceMap&localIdentName=[name]__[local]___[hash:base64:5]'
        ]
        // loaders: ['style-loader', 'css-loader?sourceMap', 'sass-loader?sourceMap']
      },
      {
        test: /^((?!\.global).)*\.css$/,
        loaders: [
          'style-loader',
          'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]'
        ]
      },

      { test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
      { test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff' },
      { test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream' },
      { test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file' },
      { test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml' },
      {
        test: /\.(?:ico|gif|png|jpg|jpeg|webp)$/,
        loader: 'url-loader'
      }
    ]
  },

  eslint: {
    formatter
  },

  plugins: [
    // https://webpack.github.io/docs/hot-module-replacement-with-webpack.html
    new webpack.HotModuleReplacementPlugin(),

    // "If you are using the CLI, the webpack process will not exit with an error code by enabling this plugin."
    // https://github.com/webpack/docs/wiki/list-of-plugins#noerrorsplugin
    new webpack.NoErrorsPlugin(),

    // NODE_ENV should be production so that modules do not perform certain development checks
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],

  // https://github.com/chentsulin/webpack-target-electron-renderer#how-this-module-works
  target: 'electron-renderer'
}));


text:
@interface CustomMenuItem : JHPageMenuItem

@property (weak, nonatomic) IBOutlet UILabel *lbTitle;

@end


text:
@implementation XVimNumericEvaluator

- (XVimEvaluator*)eval:(XVimKeyStroke*)keyStroke{
    NSString* keyStr = [keyStroke toSelectorString];

    if (keyStroke.isNumeric) {
        if (self.numericMode) {
            NSString* numStr = [keyStr substringFromIndex:3];
            NSUInteger n = (NSUInteger)[numStr integerValue];
			NSUInteger newHead = self.numericArg;
            // prevent integer overflow
            if(newHead <= floor((NSUIntegerMax - n) / 10)){
                newHead*=10;
                newHead+=n;
                self.numericArg = newHead;
                [self.argumentString appendString:numStr];
            }
            return self;
        }
        else{
            if( [keyStr isEqualToString:@"NUM0"] ){
                // Nothing to do
                // Maybe handled by XVimNormalEvaluator
            }else{
                NSString* numStr = [keyStr substringFromIndex:3];
                NSUInteger n = (NSUInteger)[numStr integerValue];
				self.numericArg = n;
				[self.argumentString appendString:numStr];
                self.numericMode = YES;
                return self;
            }
        }
    }

    return [super eval:keyStroke];
}

- (void)resetNumericArg{
    [super resetNumericArg];
    self.numericMode = NO;
}

@end


text:
Factory Girl Matchers
=====================

[![Build Status](https://secure.travis-ci.org/yannlugrin/factory-girl-matchers.png?branch=master)](http://travis-ci.org/yannlugrin/factory-girl-matchers?branch=master)

Test::Unit- and RSpec-compatible one-liners that test your factories build with Factory Girl

```ruby
  describe Post do
    it { should be_built_by_factory } # Factory named ':post' is used
    it { should be_created_by_factory } # Factory named ':post' is used

    it { should be_built_by_factory(:my_factory) }
    it { should be_created_by_factory(:my_factory) }
  end
```

Installation
------------

```shell
gem install factory-girl-matchers
```
or add the following line to Gemfile:

```ruby
gem 'factory-girl-matchers'
```
and run `bundle install` from your shell.

More Information
----------------

* [Rubygems](https://rubygems.org/gems/factory-girl-matchers)
* [Code](http://www.github.com/yannlugrin/factory-girl-matchers)
* [Issues](https://github.com/yannlugrin/factory-girl-matchers/issues)

Copyright & License
-------------------

Copyright (c) 2012 Yann Lugrin. See LICENSE for details.


text:
package nl.qbusict.cupboard.convert;

import android.content.ContentValues;
import android.database.Cursor;

import java.util.List;

import nl.qbusict.cupboard.annotation.Index;

/**
 * An entity converter is responsible for converting an entity to {@link android.content.ContentValues} and from a {@link android.database.Cursor}
 *
 * @param <T> the entity type
 */
public interface EntityConverter<T> {
    /**
     * Create an entity from the cursor. The cursor supplied is guaranteed to provide the columns in the order returned by {@link nl.qbusict.cupboard.convert.EntityConverter#getColumns()},
     * but the number of columns might be less if the result does not contain them.
     *
     * For example, if the converter has 10 columns and the cursor has only 7, the columns 0-6 from {@link nl.qbusict.cupboard.convert.EntityConverter#getColumns()} will be supplied, even
     * if the original cursor does not contain all of them. This allows a {@link nl.qbusict.cupboard.convert.EntityConverter} to iterate over the columns without checking for column name.
     *
     * Note the contract between @{link #getColumns} and this function: {@link #getColumns()} should always specify the required columns for conversion. Any unlisted columns will be dropped from
     * the cursor that is supplied here for performance reasons.
     *
     * @param cursor the cursor
     * @return the entity
     */
    public T fromCursor(Cursor cursor);

    /**
     * Convert an entity to content values
     * Generally speaking do not add content values for columns that aren't returned from {@link #getColumns()} and omit columns of value {@link nl.qbusict.cupboard.convert.EntityConverter.ColumnType#JOIN}
     *
     * @param object the entity
     * @param values the content values to populate
     */
    public void toValues(T object, ContentValues values);

    /**
     * Get the database column names along with the colum types
     * @see ColumnType
     * @return the list of colums
     */
    public List<Column> getColumns();

    /**
     * Set the id value on an entity
     * @param id the id
     * @param instance the instance to set the id on
     */
    public void setId(Long id, T instance);

    /**
     * Get the id of an entity
     * @param instance the entity
     * @return the id
     */
    public Long getId(T instance);

    /**
     * Get the database table for the entity
     * @return the mapped table name
     */
    public String getTable();

    /**
     * The SQLite column type
     */
    public enum ColumnType {
        TEXT,
        INTEGER,
        REAL,
        BLOB,
        /**
         * A surrogate type for columns that are only read, but never written.
         */
        JOIN
    }

    /**
     * Holds the column name and type
     */
    public static class Column {
        public final String name;
        public final ColumnType type;
        public final Index index;

        /**
         * Define an unindexed column
         *
         * @param name column name
         * @param type column type
         */
        public Column(String name, ColumnType type) {
            this(name, type, null);
        }

        /**
         * Define a column with an optional index definition
         *
         * @param name  the column name
         * @param type  the column type
         * @param index the index definition or null for no index
         * @see nl.qbusict.cupboard.annotation.Index
         * @see nl.qbusict.cupboard.convert.IndexBuilder
         */
        public Column(String name, ColumnType type, Index index) {
            this.name = name;
            this.type = type;
            this.index = index;
        }

        @Override
        public int hashCode() {
            return 37 * name.hashCode();
        }

        @Override
        public boolean equals(Object o) {
            if (o instanceof Column) {
                Column c = (Column) o;
                return c.name.equals(name) && c.type == type;
            } else if (o instanceof String) {
                return name.equals(o);
            } else {
                return super.equals(o);
            }
        }
    }
}


text:
class CreateMessages < ActiveRecord::Migration[5.0]
  def change
    create_table :messages do |t|
      t.string :name
      t.string :message

      t.timestamps
    end
  end
end


text:
function maDashboardPanel($state) {
    return {
        restrict: 'E',
        scope: {
            collection: '&',
            entries: '&',
            datastore: '&'
        },
        link: function(scope) {
            scope.gotoList = function () {
                $state.go($state.get('list'), { entity: scope.collection().entity.name() });
            };
        },
        template:
`

    {{ collection().title() || collection().entity.label() }}

<ma-datagrid name="{{ collection().name() }}"
    entries="entries()"
    fields="::collection().fields()"
    entity="::collection().entity"
    list-actions="::collection().listActions()"
    datastore="datastore()">
</ma-datagrid>`
    };
}

maDashboardPanel.$inject = ['$state'];

export default maDashboardPanel;


text:
package com.xerox.services;

/**
 *
 * @author aczerny
 */
public interface ClientEngine {
    /**
     * We just test if Felix likes it more when services come from an interface
     */
    public RestEngine getPull();

    public RestEngine getPush();
}


text:
package ariba.ui.aribaweb.core;

import java.lang.reflect.Field;
import java.util.Map;

import ariba.ui.aribaweb.core.AWComponent.RenderingListener.InterestLevel;
import ariba.ui.aribaweb.util.AWEncodedString;
import ariba.util.core.StringUtil;

public class AWGenericContainer extends AWContainerElement
{
    protected static final AWEncodedString LeftAngleSlash = new AWEncodedString("</");
    protected static final AWEncodedString RightAngle = new AWEncodedString(">");
    private AWGenericElement _genericElement;

    // ** Thread Safety Considerations: This is shared but all ivars are immutable -- no locking required.

    public void init (String tagName, Map bindingsHashtable)
    {
        _genericElement = new AWGenericElement();
        _genericElement.init(tagName, bindingsHashtable, true);
        super.init(tagName, null);
    }

    public AWGenericElement _genericElement ()
    {
        return _genericElement;
    }

    public AWBinding[] allBindings ()
    {
        return _genericElement.allBindings();
    }

    public void setTemplateName (String name)
    {
        _genericElement.setTemplateName(name);
        super.setTemplateName(name);
    }

    public void setLineNumber (int line)
    {
        _genericElement.setLineNumber(line);
        super.setLineNumber(line);
    }

    public void applyValues(AWRequestContext requestContext, AWComponent component)
    {
        _genericElement.applyValues(requestContext, component);
        super.applyValues(requestContext, component);
    }

    public AWResponseGenerating invokeAction(AWRequestContext requestContext, AWComponent component)
    {
        AWResponseGenerating actionResults = _genericElement.invokeAction(requestContext, component);
        if (actionResults == null) {
            actionResults = super.invokeAction(requestContext, component);
        }
        return actionResults;
    }

    public void renderResponse(AWRequestContext requestContext, AWComponent component)
    {
        InterestLevel interestLevel = InterestLevel.Interested;

        if (interestLevel == InterestLevel.Interested) {
            interestLevel = component.componentWillRender(requestContext, this, component);
        }
        AWEncodedString encodedTagName = _genericElement.tagNameInComponent(component);
        // let this method decide how to deal with null bytes
        _genericElement.renderResponse(requestContext, component, encodedTagName);
        super.renderResponse(requestContext, component);
        if (encodedTagName != null) {
            AWResponse response = requestContext.response();
            // hook for listeners to inject any more content
            if (interestLevel == InterestLevel.Interested) {
                interestLevel = component.componentClosingTag(requestContext, this, component);
            }
            response.appendContent(LeftAngleSlash);
            response.appendContent(encodedTagName);
            response.appendContent(RightAngle);
        }
        if (interestLevel == InterestLevel.Interested) {
            interestLevel = component.componentFinishedRender(requestContext, this, component);
        }

    }

    public String toString ()
    {
        return StringUtil.strcat(super.toString(), ":\"", _genericElement.staticTagName(), "\"");
    }

    protected Object getFieldValue (Field field)
      throws IllegalArgumentException, IllegalAccessException
    {
        try {
            return field.get(this);
        }
        catch (IllegalAccessException ex) {
            return super.getFieldValue(field);
        }
    }
}


text: package "emacs24-nox"


text:
package com.atlassian.maven.plugins.crowd;

import com.atlassian.maven.plugins.amps.GenerateRestDocsMojo;

import org.jfrog.maven.annomojo.annotations.MojoGoal;
import org.jfrog.maven.annomojo.annotations.MojoRequiresDependencyResolution;

/**
 * @since 3.6.1
 */
@MojoGoal("generate-rest-docs")
@MojoRequiresDependencyResolution("test")
public class CrowdGenerateRestDocsMojo extends GenerateRestDocsMojo
{
}


text:
namespace inspire {

   Service::Service(const uint servicePort) : _initialized(false)
   {
      _async = new AsyncConnection(servicePort);
      if (NULL == _async)
      {
         //LogError
      }
   }

   Service::~Service()
   {
      if (NULL != _async)
      {
         delete _async;
         _async = NULL;
      }
   }

   void Service::init()
   {
      if (!_initialized)
      {
         _async->init();
         _async->bindAndListen();

         _ioservice = new IOService();
         if (NULL == _ioservice)
         {
            LogError("Failed to create IOService");
            return;
         }
         _initialized = true;
      }
   }

   void Service::initService()
   {
      init();

      if (_ioservice)
      {
         _ioservice->init();
         _ioservice->bind(_async);
      }
   }

   void Service::stop()
   {
      _ioservice->stop();
   }

   void Service::run()
   {
      initService();
      _ioservice->run();
   }

   void Service::destroy()
   {
      _ioservice->destroy();
      delete _async;
      _async = NULL;
   }
}


text:
/****************************************************************************************
Portions of this file are derived from the following 3GPP standard:

    3GPP TS 26.073
    ANSI-C code for the Adaptive Multi-Rate (AMR) speech codec
    Available from http://www.3gpp.org

(C) 2004, 3GPP Organizational Partners (ARIB, ATIS, CCSA, ETSI, TTA, TTC)
Permission to distribute, modify and use this file under the standard license
terms listed above has been obtained from the copyright holder.
****************************************************************************************/
/*

 Pathname: ./gsm-amr/c/src/shr_r.c

------------------------------------------------------------------------------
 REVISION HISTORY

 Description: Created separate file for the shr_r function. Sync'ed up
          with the current template and fixed tabs.

 Description: Passing around pOverflow as per EPOC changes.

 Who:                           Date:
 Description:

------------------------------------------------------------------------------
 INPUT AND OUTPUT DEFINITIONS

 Inputs:
    var1 = 16 bit short signed integer (Word16) whose value falls in
           the range : 0xffff 8000 <= var1 <= 0x0000 7fff.
    var2 = 16 bit short signed integer (Word16) whose value falls in
           the range : 0xffff 8000 <= var2 <= 0x0000 7fff.

 Local Stores/Buffers/Pointers Needed:
    None

 Global Stores/Buffers/Pointers Needed:
    None

 Outputs:
    var_out = shifted input w/ rounding (Word16)

 Pointers and Buffers Modified:
    None

 Local Stores Modified:
    None

 Global Stores Modified:
    None

------------------------------------------------------------------------------
 FUNCTION DESCRIPTION

 This function arithmetically shifts the 16 bit input var1 right var2 positions
 with rounding. If var2 is negative, arithmetically shift var1 left by
 -var2 with rounding. Saturate the result in case of underflows or
 overflows.

    - If var2 is greater than zero :
        if (sub(shl(shr(var1,var2),1),shr(var1,sub(var2,1))))
        is equal to zero
        then
            shr_r(var1,var2) = shr(var1,var2)
        else
            shr_r(var1,var2) = add(shr(var1,var2),1)
    - If var2 is less than or equal to zero :
        shr_r(var1,var2) = shr(var1,var2).

------------------------------------------------------------------------------
 REQUIREMENTS

 None

------------------------------------------------------------------------------
 REFERENCES

 [1] basicop2.c, ETS Version 2.0.0, February 8, 1999

------------------------------------------------------------------------------
 PSEUDO-CODE

Word16 shr_r (Word16 var1, Word16 var2)
{
    Word16 var_out;

    if (var2 > 15)
    {
        var_out = 0;
    }
    else
    {
        var_out = shr (var1, var2);
#if (WMOPS)
        multiCounter[currCounter].shr--;
#endif

        if (var2 > 0)
        {
            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
            {
                var_out++;
            }
        }
    }
#if (WMOPS)
    multiCounter[currCounter].shr_r++;
#endif
    return (var_out);
}

------------------------------------------------------------------------------
 RESOURCES USED
   When the code is written for a specific target processor the
     the resources used should be documented below.

 STACK USAGE: [stack count for this module] + [variable to represent
          stack usage for each subroutine called]

     where: [stack usage variable] = stack usage for [subroutine
         name] (see [filename].ext)

 DATA MEMORY USED: x words

 PROGRAM MEMORY USED: x words

 CLOCK CYCLES: [cycle count equation for this module] + [variable
           used to represent cycle count for each subroutine
           called]

     where: [cycle count variable] = cycle count for [subroutine
        name] (see [filename].ext)

------------------------------------------------------------------------------
*/

/*----------------------------------------------------------------------------
; INCLUDES
----------------------------------------------------------------------------*/
#include    "basic_op.h"

/*----------------------------------------------------------------------------
; MACROS
; Define module specific macros here
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; DEFINES
; Include all pre-processor statements here. Include conditional
; compile variables also.
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; LOCAL FUNCTION DEFINITIONS
; Function Prototype declaration
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; LOCAL STORE/BUFFER/POINTER DEFINITIONS
; Variable declaration - defined here and used outside this module
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; EXTERNAL FUNCTION REFERENCES
; Declare functions defined elsewhere and referenced in this module
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; EXTERNAL GLOBAL STORE/BUFFER/POINTER REFERENCES
; Declare variables used in this module but defined elsewhere
----------------------------------------------------------------------------*/

/*----------------------------------------------------------------------------
; FUNCTION CODE
----------------------------------------------------------------------------*/
Word16 shr_r(register Word16 var1, register Word16 var2, Flag *pOverflow)
{
    /*----------------------------------------------------------------------------
    ; Define all local variables
    ----------------------------------------------------------------------------*/
    Word16 var_out;

    /*----------------------------------------------------------------------------
    ; Function body here
    ----------------------------------------------------------------------------*/
    if (var2 > 15)
    {
        var_out = 0;
    }
    else
    {
        var_out = shr(var1, var2, pOverflow);
        if (var2 > 0)
        {
            if ((var1 & ((Word16) 1 << (var2 - 1))) != 0)
            {
                var_out++;
            }
        }
    }

    /*----------------------------------------------------------------------------
    ; Return nothing or data or data pointer
    ----------------------------------------------------------------------------*/
    return (var_out);
}


text:
require 'optparse'
require_relative 'sharded_queue'

host     = '127.0.0.1'
keyspace = 'foo'
name     = 'test'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: producer.rb [options]"

  opts.on("-H", "--host HOST", "Cassandra host") { |h| host = h }
  opts.on("-K", "--keyspace KEYSPACE", "Keyspace to use") { |k| keyspace = k }
  opts.on("-N", "--name NAME", "Specifies the queue") { |n| name = n }
end.parse!

queue = ShardedQueue.new(name,host,keyspace)
queue.init_shards


text:
/**
 * @fileOverview
 * Master test runner.
 *
 * Provides functions to:
 *
 * 1) launch an Express web server,
 * 2) launch and shutdown SSH tunnels,
 * 3) launch multiple test subprocesses.
 */

var childProcess = require('child_process');
var fs = require('fs');
var path = require('path');
var async = require('async');
var uuid = require('uuid');
var expressApp = require('../server/expressApp');

//---------------------------------------------------------------------------
// Properties that will be set.
//---------------------------------------------------------------------------

exports.config = undefined;
// HttpServer instance.
exports.server = undefined;
// The child process instance running the SSH tunnel.
exports.tunnelProcess = undefined;
// To hold the test runner processes to be spawned.
exports.testProcesses = [];

//---------------------------------------------------------------------------
// Run everything.
//---------------------------------------------------------------------------

/**
 * Setup the server, SSH tunnel, and run the tests.
 *
 * @param {String} configPath
 *   Path to configuration, to be passed to require(). Relative to the upper
 *   directory of the project.
 * @param {Function} callback
 *   Of the form function function (error, incompleteTestProcessCount, failedTestCount).
 */
exports.run = function (configPath, callback) {
  var self = this;
  async.series({
    readConfiguration: function (asyncCallback) {
      self.readConfiguration(configPath, asyncCallback);
    },
    ensureLogDirectory: function (asyncCallback) {
      self.ensureLogDirectory(asyncCallback);
    },
    startServer: function (asyncCallback) {
      self.startServer(asyncCallback);
    },
    startTunnel: function (asyncCallback) {
      self.startTunnel(asyncCallback);
    },
    runTestProcesses: function (asyncCallback) {
      self.runTestProcesses(asyncCallback);
    },
    stopTunnel: function (asyncCallback) {
      self.stopTunnel(asyncCallback);
    },
    stopServer: function (asyncCallback) {
      self.stopServer(asyncCallback);
    }
  }, function (error) {
    // Meaning we had an issue somewhere in the control code, and probably
    // didn't even launch the tests.
    if (error) {
      return self.handleError(error, function () {
        callback(error);
      });
    }

    var incompleteTestProcessCount = 0;
    var failedTestCount = 0;

    exports.testProcesses.forEach(function (testProcess) {
      if(testProcess.complete) {
        failedTestCount += testProcess.failureCount;
      } else {
        incompleteTestProcessCount++;
      }
    });
    callback(null, incompleteTestProcessCount, failedTestCount);
  });
};

//---------------------------------------------------------------------------
// Manage issues and errors.
//---------------------------------------------------------------------------

/**
 * Shut everything down on error.
 *
 * The callback is optional, but this will end the process without it. If
 * provided, the error will be passed through to the callback.
 *
 * @param {Error} error
 * @param {Function} [callback]
 */
exports.handleError = function (error, callback) {
  var self = this;
  console.error('An error occurred. Halting testing.');

  async.series({
    haltTestProcesses: function (asyncCallback) {
      self.haltTestProcesses(asyncCallback);
    },
    stopTunnel: function (asyncCallback) {
      self.stopTunnel(asyncCallback);
    },
    stopServer: function (asyncCallback) {
      self.stopServer(asyncCallback);
    }
  }, function (shutdownError) {
    if (shutdownError) {
      console.error('A further error occurred while halting testing:');
      console.error(shutdownError.stack);
    }
    if (callback) {
      callback(error);
    } else {
      console.error(error.stack);
      process.exit(1);
    }
  });
};

//---------------------------------------------------------------------------
// Other utilities.
//---------------------------------------------------------------------------

/**
 * Read the configuration file to be used.
 *
 * @param {String} configPath
 *   Path to configuration, to be passed to require(). Relative to the upper
 *   directory of the project.
 * @param {Function} callback
 *   Of the form function function (error).
 */
exports.readConfiguration = function (configPath, callback) {
  try {
    this.config = require(path.join(__dirname, '..', configPath));
    callback();
  } catch (error) {
    callback(new Error('Invalid configuration file path: ' + configPath));
  }
};

/**
 * Create a logs directory if it doesn't exist.
 *
 * @param {Function} callback
 */
exports.ensureLogDirectory = function (callback) {
  var logDir = path.join(__dirname, '..', 'logs');
  fs.exists(logDir, function (exists) {
    if (exists) {
      callback();
    } else {
      fs.mkdir(logDir, callback);
    }
  });
};

//---------------------------------------------------------------------------
// Express server.
//---------------------------------------------------------------------------

/**
 * Launch the Express server.
 *
 * We are running it in this process, which should be fine as it won't be
 * doing much in the way of heavy lifting.
 */
exports.startServer = function (callback) {
  if (this.config.launchExampleServer) {
    expressApp.start(this.config);
  }
  callback();
};

/**
 * Stop the Express server.
 */
exports.stopServer = function (callback) {
  expressApp.stop(callback);
};

//---------------------------------------------------------------------------
// SSH Tunnel management.
//---------------------------------------------------------------------------

/**
 * Launch a BrowserStack SSH tunnel instance.
 *
 * @param {Function} callback
 */
exports.launchBrowserStackTunnel = function (callback) {
  var self = this;
  var callbackInvoked = false;

  if(!this.config.browserstack.user) {
    return callback(new Error('Missing config.browserstack.user.'));
  }
  if(!this.config.browserstack.key) {
    return callback(new Error('Missing config.browserstack.key.'));
  }

  console.log('Launching BrowserStack SSH tunnel. It might take a minute for a remote Selenium server to be ready...');

  // BrowserStack requires specification of all servers that will be accessed
  // through the tunnel. If you don't list yours, then it won't work.
  //
  // Here we only care about the localhost server, but you can list more than
  // one server:
  // host1,port1,ssl1,host2,port2,ssl2,etc ...
  var hostString = [
    this.config.server.host,
    this.config.server.port,
    // Indicating that this is not an SSL connection.
    0
  ].join(',');

  var args = [
    this.config.browserstack.key,
    hostString,
    // Uncomment for verbose logging - not a great deal of difference with this
    // tunnel, however.
    // '-v',
    '-tunnelIdentifier',
    this.config.browserstack.tunnel.identifier,
    // Disable Live Testing and Screenshots, just test with Automate.
    '-onlyAutomate',
    // Skip checking for the validity of the folder/hosts parameters. This is
    // usually advisable, as you might want to fire up the tunnel before the
    // thing you are testing is ready, so as to save time.
    '-skipCheck'
  ];

  this.tunnelProcess = childProcess.spawn(this.config.browserstack.tunnel.path, args, {
    cwd: path.join(__dirname, '..')
  });

  // Pipe both stdout and stderr to the specified log file.
  var logFilePath = path.join(__dirname, '..', this.config.log.directory, this.config.browserstack.tunnel.logfile);
  var writer = fs.createWriteStream(logFilePath);
  this.tunnelProcess.stderr.pipe(writer);
  this.tunnelProcess.stdout.pipe(writer);

  // Set up a timeout watch to shut down if the tunnel setup hangs - which does
  // happen, though not often.
  var timeoutId = setTimeout(function () {
    self.tunnelProcess.removeListener('data', readyListener);
    callbackInvoked = true;
    callback(new Error('Timed out waiting for SSH tunnel to initialize.'));
  }, this.config.browserstack.tunnel.timeout);

  /**
   * A listener function for the tunnel. Callback when the tunnel outputs a
   * ready message.
   *
   * @param {Buffer} data
   */
  function readyListener (data) {
    if (data.toString().match(/You can now access your local server/)) {
      console.log('BrowserStack SSH tunnel launched and ready.');
      // Get rid of this listener and the timeout function.
      self.tunnelProcess.removeListener('data', readyListener);
      clearTimeout(timeoutId);
      // And onwards.
      callbackInvoked = true;
      callback();
    }
  }
  this.tunnelProcess.stdout.on('data', readyListener);

  // If the tunnel exits for any reason before the stopTunnel() method is
  // called than that is an error condition.
  this.tunnelProcess.on('exit', function (code) {
    // This might happen before readiness, so get rid of this listener and the
    // timeout function.
    self.tunnelProcess.removeListener('data', readyListener);
    clearTimeout(timeoutId);
    delete self.tunnelProcess;

    // And if it does happen before readiness, then we should make sure the
    // callback still happens.
    var error = new Error('SSH tunnel exited unexpectedly with code: ' + code);
    if (callbackInvoked) {
      self.handleError(error);
    } else {
      callbackInvoked = true;
      callback(error);
    }
  });
};

/**
 * Launch a SauceLabs SSH tunnel instance.
 *
 * @param {Function} callback
 */
exports.launchSauceLabsTunnel = function(callback) {
  var self = this;
  var callbackInvoked = false;

  if(!this.config.saucelabs.user) {
    return callback(new Error('Missing config.saucelabs.user.'));
  }
  if(!this.config.saucelabs.key) {
    return callback(new Error('Missing config.saucelabs.key.'));
  }

  console.log('Launching SauceLabs SSH tunnel. It might take a minute for a remote Selenium server to be ready...');

  // The process will touch a file when the remote Selenium server has started
  // and it is ready for use.
  var readyFilePath = path.join(__dirname, this.config.saucelabs.tunnel.identifier + '-ready');
  var logFile = path.join(__dirname, '..', this.config.log.directory, this.config.saucelabs.tunnel.logfile);

  var args = [
    '--user',
    this.config.saucelabs.user,
    '--api-key',
    this.config.saucelabs.key,
    // Uncomment for verbose logging.
    // '--verbose',
    '--tunnel-identifier',
    this.config.saucelabs.tunnel.identifier,
    // Apparently this doesn't work - so we're using pipes from the process
    // below.
    //'--logfile',
    //logFile,
    '--readyfile',
    readyFilePath,
    '--se-port',
    this.config.saucelabs.tunnel.seleniumPort,
  ];

  this.tunnelProcess = childProcess.spawn(this.config.saucelabs.tunnel.path, args, {
    cwd: path.join(__dirname, '..')
  });

  // Pipe both stdout and stderr to the specified log file.
  var writer = fs.createWriteStream(logFile);
  this.tunnelProcess.stderr.pipe(writer);
  this.tunnelProcess.stdout.pipe(writer);

  // Set up a timeout watch to shut down if the tunnel setup hangs - which does
  // happen, though not often.
  var timeoutId = setTimeout(function () {
    clearInterval(checkReadyId);
    callbackInvoked = true;
    callback(new Error('Timed out waiting for SSH tunnel to initialize.'));
  }, this.config.saucelabs.tunnel.timeout);

  // Set up a periodic check for the existence of the readyfile.
  var checkReadyId = setInterval(function () {
    fs.exists(readyFilePath, function (exists) {
      if (exists) {
        console.log('SauceLabs SSH tunnel launched and ready.');
        fs.unlink(readyFilePath, function () {});
        clearTimeout(timeoutId);
        clearInterval(checkReadyId);
        callbackInvoked = true;
        callback();
      }
    });
  }, 1000);

  // If the tunnel exits for any reason before the stopTunnel() method is
  // called than that is an error condition.
  this.tunnelProcess.on('exit', function (code) {
    // This might happen before readiness, so get rid of the various timeout
    // and interval functions.
    clearTimeout(timeoutId);
    clearInterval(checkReadyId);
    delete self.tunnelProcess;

    // And if it does happen before readiness, then we should make sure the
    // callback still happens.
    var error = new Error('SSH tunnel exited unexpectedly with code: ' + code);
    if (callbackInvoked) {
      self.handleError(error);
    } else {
      callbackInvoked = true;
      callback(error);
    }
  });
};

/**
 * Launch a TestingBot SSH tunnel instance.
 *
 * @param {Function} callback
 */
exports.launchTestingBotTunnel = function(callback) {
  var self = this;
  var callbackInvoked = false;

  if(!this.config.testingbot.key) {
    return callback(new Error('Missing config.testingbot.key.'));
  }
  if(!this.config.testingbot.secret) {
    return callback(new Error('Missing config.testingbot.secret.'));
  }

  console.log('Launching TestingBot SSH tunnel. It might take a minute for a remote Selenium server to be ready...');

  // The process will touch a file when the remote Selenium server has started
  // and it is ready for use.
  var readyFilePath = path.join(__dirname, this.config.testingbot.tunnel.identifier + '-ready');
  var logFile = path.join(__dirname, '..', this.config.log.directory, this.config.testingbot.tunnel.logfile);

  // Note that tunnel identifier isn't passed in the arguments.
  var args = [
    '-jar',
    this.config.testingbot.tunnel.path,
    this.config.testingbot.key,
    this.config.testingbot.secret,
    // Supposedly makes the tunnel faster, but it simply doesn't work if this is
    // enabled.
    //'--boost',
    '--readyfile',
    readyFilePath,
    '--se-port',
    this.config.testingbot.tunnel.seleniumPort,
  ];

  this.tunnelProcess = childProcess.spawn('java', args, {
    cwd: path.join(__dirname, '..')
  });

  // Pipe both stdout and stderr to the specified log file.
  var writer = fs.createWriteStream(logFile);
  this.tunnelProcess.stderr.pipe(writer);
  this.tunnelProcess.stdout.pipe(writer);

  // Set up a timeout watch to shut down if the tunnel setup hangs - which does
  // happen, though not often.
  var timeoutId = setTimeout(function () {
    clearInterval(checkReadyId);
    callbackInvoked = true;
    callback(new Error('Timed out waiting for SSH tunnel to initialize.'));
  }, this.config.testingbot.tunnel.timeout);

  // Set up a periodic check for the existence of the readyfile.
  var checkReadyId = setInterval(function () {
    fs.exists(readyFilePath, function (exists) {
      if (exists) {
        console.log('TestingBot SSH tunnel launched and ready.');
        fs.unlink(readyFilePath, function () {});
        clearTimeout(timeoutId);
        clearInterval(checkReadyId);
        callbackInvoked = true;
        callback();
      }
    });
  }, 1000);

  // If the tunnel exits for any reason before the stopTunnel() method is
  // called than that is an error condition.
  this.tunnelProcess.on('exit', function (code) {
    // This might happen before readiness, so get rid of the various timeout
    // and interval functions.
    clearTimeout(timeoutId);
    clearInterval(checkReadyId);
    delete self.tunnelProcess;

    // And if it does happen before readiness, then we should make sure the
    // callback still happens.
    var error = new Error('SSH tunnel exited unexpectedly with code: ' + code);
    if (callbackInvoked) {
      self.handleError(error);
    } else {
      callbackInvoked = true;
      callback(error);
    }
  });
};

/**
 * Start the appropriate SSH tunnel.
 *
 * The callback is invoked when the tunnel is ready for use, which requires
 * waiting for the remote Selenium server to become available.
 *
 * @param {Function} callback
 */
exports.startTunnel = function (callback) {
  var capabilities;

  switch (this.config.service) {
    case 'browserstack':
      // Fill out necessary configuration.
      this.config.browserstack.tunnel.identifier = uuid.v4();
      capabilities = this.config.browserstack.capabilities;
      capabilities['browserstack.tunnelIdentifier'] = this.config.browserstack.tunnel.identifier;
      capabilities['browserstack.user'] = this.config.browserstack.user;
      capabilities['browserstack.key'] = this.config.browserstack.key;
      // Then on to launching the tunnel process.
      this.launchBrowserStackTunnel(callback);
      break;

    case 'saucelabs':
      // Fill out necessary configuration.
      this.config.saucelabs.tunnel.identifier = uuid.v4();
      capabilities = this.config.saucelabs.capabilities;
      capabilities['tunnel-identifier'] = this.config.saucelabs.tunnel.identifier;
      // Then on to launching the tunnel process.
      this.launchSauceLabsTunnel(callback);
      break;

    case 'testingbot':
      // Fill out necessary configuration.
      this.config.testingbot.tunnel.identifier = uuid.v4();
      // Then on to launching the tunnel process.
      this.launchTestingBotTunnel(callback);
      break;

    default:
      callback(new Error('Invalid service specified: ' + this.config.service));
      break;
  }
};

/**
 * Stop the tunnel if it is running.
 *
 * @param {Function} callback
 */
exports.stopTunnel = function (callback) {
  var self = this;
  if (!this.tunnelProcess) {
    return callback();
  }

  console.log('Halting SSH tunnel...');

  // Get rid of the error listener we put on the tunnel process.
  this.tunnelProcess.removeAllListeners('exit');
  // Sends a SIGTERM to the process, but we should wait for it to clean up.
  // Immediately killing a Selenium service SSH tunnel can lead to issues with
  // some of the services.
  this.tunnelProcess.kill();

  function callbackOnTunnelProcessExit() {
    // The _handle property on a child process is set null when the process
    // ends. This isn't a public property, so may evaporate in some future
    // Node.js release, but it is useful.
    if (self.tunnelProcess._handle) {
      return;
    }

    clearInterval(intervalId);
    delete self.tunnelProcess;
    callback();
  }

  console.log('SSH tunnel sent kill signal, waiting for it to shut down.');
  var intervalId = setInterval(callbackOnTunnelProcessExit, 1000);
};

//---------------------------------------------------------------------------
// Run tests in subprocesses.
//---------------------------------------------------------------------------

/**
 * Launch the test runner subprocesses.
 */
exports.runTestProcesses = function (callback) {
  var self = this;

  function onExit(wrapper, code) {
    console.log('Test process ' + wrapper.index + ' exited with code ' + code);
    wrapper.code = code;
    delete wrapper.process;

    var complete = self.testProcesses.every(function (processWrapper) {
      return !processWrapper.process;
    });
    if (complete) {
      callback();
    }
  }

  this.testProcesses = this.config.workers.map(function (paths, index) {
    console.log('Launching test process ' + index);
    // Spawn a worker process, sending over the index and the base64 encoded
    // configuration to work with.
    var testProcess = childProcess.fork('./src/worker', [
      index,
      new Buffer(JSON.stringify(self.config)).toString('base64')
    ], {
      cwd: path.join(__dirname, '..'),
      silent: true
    });

    var wrapper = {
      complete: false,
      index: index,
      process: testProcess
    };

    testProcess.on('exit', function (code) {
      onExit(wrapper, code);
    });

    testProcess.on('message', function (message) {
      wrapper.complete = true;
      wrapper.failureCount = message.failureCount;
    });

    var logFile = path.join(__dirname, '..', self.config.log.directory, self.config.log.workerLogPrefix + index + '.log');
    var writer = fs.createWriteStream(logFile);
    testProcess.stderr.pipe(writer);
    testProcess.stdout.pipe(writer);

    return wrapper;
  });
};

/**
 * Halt all the test runner subprocesses.
 */
exports.haltTestProcesses = function (callback) {
  this.testProcesses.filter(function (testProcessHolder) {
    return !!testProcessHolder.process;
  }).forEach(function (testProcessHolder) {
    testProcessHolder.process.removeAllListeners('exit');
    testProcessHolder.process.kill();
    // Distinctive code for being shut down.
    testProcessHolder.code = 10;
    delete testProcessHolder.process;
  });
  callback();
};


text:
layout: event
published: true
cancelled: false
cancel_reason:
title: Welcome Drinks
date:     2021-09-23 19:00:00 +0100
date_end: 2021-09-23 23:59:59 +0100
banner: 2021_09_23_welcome_drinks.jpg
ticket_link: https://forms.gle/wL9TQCRv9Z7DoTEQA
location: The Brass Pig
price: Free
category:
    - Social
---

Join us at 7pm for welcome drinks at the Brass Pig! Make new friends and mingle with other students from years.

If you plan on attending, please fill in [this](https://forms.gle/wL9TQCRv9Z7DoTEQA) form here so that we know how many
people to expect. But feel free to also show up on the day even if you didn't fill in the form!

And of course, in the classic CSS fashion, there will be free booze!

**This event is open to students from all years.**

**RSVP:** https://forms.gle/CWSQR6FHr4kgMyaU9


text:
import moment from 'moment';
import Q from 'q';
import lodash from 'lodash';
import jQuery from 'jquery';
import XmlParser from 'xml2js';

function CurrencyRange() {
	this.delay = 1000;
	this.firstDate = new Date();
	this.lastDate = new Date();
	this.selected = 'USD';
	this.currency = [
		{ id: 145, name: 'USD' },
		{ id: 19, name: 'EUR' },
	];
	this.graphData = {
		labels: [],
		rates: [],
	};
	Object.freeze( this.currency );
	Object.seal( this.graphData );

	this.reset = () => {
		const date = new Date();
		date.setDate( date.getDate() - 7 );
		this.firstDate = date;
		this.lastDate = new Date();
	};
	// Update the date values on construct
	this.reset();

	this.parseCustomDate = ( value, isFirst ) => {
		if ( isFirst ) {
			return this.parseFirstDate( value );
		}
		return this.parseLastDate( value );
	};

	this._parseDate = ( value ) => {
		const date = new Date( value );

		if ( Object.prototype.toString.call( date ) === '[object Date]' ) {
			if ( !isNaN( date.getTime() ) ) {
				return date;
			}
		}

		return null;
	};

	this._isInRange = ( date, isFirst ) => {
		const otherDate = isFirst ? this.lastDate : this.firstDate;
		return date.toDateString() === otherDate.toDateString() ||
			( isFirst ? date.valueOf() < otherDate.valueOf() : otherDate.valueOf() < date.valueOf() );
	};

	this.parseFirstDate = ( value ) => {
		const date = this._parseDate( value );
		if ( date && this._isInRange( date, true ) ) {
			this.firstDate = date;
			return this.firstDate;
		}

		return null;
	};

	this.parseLastDate = ( value ) => {
		const date = this._parseDate( value );
		if ( date && this._isInRange( date, false ) ) {
			this.lastDate = date;
			return this.lastDate;
		}

		return null;
	};

	this.getFirstDate = () => {
		return moment( this.firstDate ).format('YYYY-MM-DD');
	};

	this.getLastDate = () => {
		return moment( this.lastDate ).format('YYYY-MM-DD');
	};

	this.setSelected = ( value ) => {
		const contains = this.currency.find( ( currency ) => {
			return currency.name === value;
		});

		if ( contains ) {
			this.selected = value;
		}
	};

	this.getCurrency = () => {
		return this.currency;
	};

	this._getUrl = () => {
		const id = this.currency.find( ( value ) => { return value.name === this.selected; } ).id;
		const fromDate = moment( this.firstDate ).format( 'M/D/YYYY' );
		const toDate = moment( this.lastDate ).format( 'M/D/YYYY' );
		return `http://www.nbrb.by/Services/XmlExRatesDyn.aspx?curId=${id}&fromDate=${fromDate}&toDate=${toDate}`;
	};

	this._filterData = ( data ) => {
		let filteredData = data.replace( /<body>/g, '' );
		filteredData = filteredData.replace( /<\/body>/g, '' );
		filteredData = filteredData.replace( /
/g, '' );
		return filteredData.trim();
	};

	this._loadData = () => {
		// Not good enough support in old browsers for:
		// return new Promise( ( resolve, reject )
		const deferred = Q.defer();
		const url = `http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22${encodeURIComponent(this._getUrl())}%22&format=xml'&callback=?`;

		jQuery.getJSON(url, ( data ) => {
			if (data.results[0]) {
				let xml = data.results[0];

				xml = xml.replace(/<body>/g, '');
				xml = xml.replace(/<\/body>/g, '');
				xml = xml.replace(/
/g, '');
				xml = xml.trim();

				XmlParser.parseString( xml, ( err, result ) => {
					if ( result && result.currency && result.currency.length !== 0) {
						this.graphData.labels = result.currency.record.map( value => { return moment( new Date( value.$.date ) ).format( 'YYYY-MM-DD' ); } );
						this.graphData.rates = result.currency.record.map( value => { return value.rate[0]; } );
					}

					deferred.resolve( this.graphData );
				});
			} else {
				deferred.reject( Error( 'Data load failed' ) );
			}
		}).fail( () => {
			deferred.reject( Error( 'Data load failed' ) );
		});

		return deferred.promise;
	};

	this.delayedLoadData = lodash.debounce(
		this._loadData.bind( this ),
		this.delay,
		{ leading: true },
	);
}

export default new CurrencyRange();


text:
package org.ggp.base.util.gdl.model;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.ggp.base.util.concurrency.ConcurrencyUtils;
import org.ggp.base.util.gdl.GdlUtils;
import org.ggp.base.util.gdl.grammar.Gdl;
import org.ggp.base.util.gdl.grammar.GdlConstant;
import org.ggp.base.util.gdl.grammar.GdlFunction;
import org.ggp.base.util.gdl.grammar.GdlLiteral;
import org.ggp.base.util.gdl.grammar.GdlPool;
import org.ggp.base.util.gdl.grammar.GdlRelation;
import org.ggp.base.util.gdl.grammar.GdlRule;
import org.ggp.base.util.gdl.grammar.GdlSentence;
import org.ggp.base.util.gdl.grammar.GdlTerm;
import org.ggp.base.util.gdl.grammar.GdlVariable;

import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

public class SentenceFormsFinder {
	private final ImmutableList<Gdl> description;
	private final Map<NameAndArity, List<TermModel>> sentencesModel = Maps.newHashMap();
	private boolean haveCreatedModel = false;

	public SentenceFormsFinder(ImmutableList<Gdl> description) {
		this.description = description;
	}

	public ImmutableSet<SentenceForm> findSentenceForms() throws InterruptedException {
		createModel();

		return ImmutableSet.copyOf(getSentenceFormsFromModel());
	}

	public Map<SentenceForm, SentenceFormDomain> findCartesianDomains() throws InterruptedException {
		createModel();

		return getCartesianDomainsFromModel();
	}

	private void createModel() throws InterruptedException {
		synchronized (this) {
			if (!haveCreatedModel) {
				addTrueSentencesToModel();
				applyRulesToModel();
				haveCreatedModel = true;
			}
		}
	}

	private Map<SentenceForm, SentenceFormDomain> getCartesianDomainsFromModel() throws InterruptedException {
		Map<SentenceForm, SentenceFormDomain> results = Maps.newHashMap();
		for (Entry<NameAndArity, List<TermModel>> sentenceEntry : sentencesModel.entrySet()) {
			ConcurrencyUtils.checkForInterruption();
			NameAndArity nameAndArity = sentenceEntry.getKey();
			GdlConstant name = nameAndArity.getName();
			List<TermModel> bodyModels = sentenceEntry.getValue();
			// We'll end up taking the Cartesian product of the different
			// types of terms we have available
			if (nameAndArity.getArity() == 0) {
				GdlSentence sentence = GdlPool.getProposition(name);
				SimpleSentenceForm form = SimpleSentenceForm.create(sentence);
				results.put(form, CartesianSentenceFormDomain.create(form, ImmutableList.<Set<GdlConstant>>of()));
			} else {
				List<Set<GdlTerm>> sampleTerms = toSampleTerms(bodyModels);
				for (List<GdlTerm> terms : Sets.cartesianProduct(sampleTerms)) {
					ConcurrencyUtils.checkForInterruption();
					GdlRelation sentence = GdlPool.getRelation(name, terms);
					SimpleSentenceForm form = SimpleSentenceForm.create(sentence);
					SentenceFormDomain domain = getDomain(form, sentence);
					results.put(form, domain);
				}
			}
		}
		return results;
	}

	private SentenceFormDomain getDomain(SentenceForm form, GdlRelation sentence) {
		List<Set<GdlConstant>> domainContents = Lists.newArrayList();
		getDomainInternal(sentence.getBody(), sentencesModel.get(new NameAndArity(sentence)), domainContents);
		return CartesianSentenceFormDomain.create(form, domainContents);
	}

	//Appends to domainContents
	private void getDomainInternal(List<GdlTerm> body, List<TermModel> bodyModel,
			List<Set<GdlConstant>> domainContents) {
		if (body.size() != bodyModel.size()) {
			throw new IllegalStateException("Should have same arity in example as in model");
		}
		for (int i = 0; i < body.size(); i++) {
			GdlTerm term = body.get(i);
			TermModel termModel = bodyModel.get(i);
			if (term instanceof GdlConstant) {
				domainContents.add(termModel.getPossibleConstants());
			} else if (term instanceof GdlFunction) {
				GdlFunction function = (GdlFunction) term;
				List<TermModel> functionBodyModel = termModel.getFunctionBodyModel(function);
				getDomainInternal(function.getBody(), functionBodyModel, domainContents);
			} else {
				throw new IllegalStateException();
			}
		}
	}

	private Set<SentenceForm> getSentenceFormsFromModel() {
		Set<SentenceForm> results = Sets.newHashSet();
		for (Entry<NameAndArity, List<TermModel>> sentenceEntry : sentencesModel.entrySet()) {
			NameAndArity nameAndArity = sentenceEntry.getKey();
			GdlConstant name = nameAndArity.getName();
			List<TermModel> bodyModels = sentenceEntry.getValue();
			// We'll end up taking the Cartesian product of the different
			// types of terms we have available
			if (nameAndArity.getArity() == 0) {
				GdlSentence sentence = GdlPool.getProposition(name);
				results.add(SimpleSentenceForm.create(sentence));
			} else {
				List<Set<GdlTerm>> sampleTerms = toSampleTerms(bodyModels);
				for (List<GdlTerm> terms : Sets.cartesianProduct(sampleTerms)) {
					GdlSentence sentence = GdlPool.getRelation(name, terms);
					results.add(SimpleSentenceForm.create(sentence));
				}
			}
		}
		return results;
	}

	private List<Set<GdlTerm>> toSampleTerms(List<TermModel> bodyModels) {
		List<Set<GdlTerm>> results = Lists.newArrayList();
		for (TermModel termModel : bodyModels) {
			results.add(toSampleTerms(termModel));
		}
		return results;
	}

	private Set<GdlTerm> toSampleTerms(TermModel termModel) {
		Set<GdlTerm> results = Sets.newHashSet();
		if (!termModel.getPossibleConstants().isEmpty()) {
			results.add(termModel.getPossibleConstants().iterator().next());
		}
		for (NameAndArity nameAndArity : termModel.getPossibleFunctions().keySet()) {
			List<TermModel> bodyModel = termModel.getPossibleFunctions().get(nameAndArity);
			List<Set<GdlTerm>> functionSampleTerms = toSampleTerms(bodyModel);
			Set<List<GdlTerm>> functionBodies = Sets.cartesianProduct(functionSampleTerms);
			for (List<GdlTerm> functionBody : functionBodies) {
				GdlFunction function = GdlPool.getFunction(nameAndArity.getName(), functionBody);
				results.add(function);
			}
		}
		return results;
	}

	private void applyRulesToModel() throws InterruptedException {
		//Apply injections
		boolean changeMade = true;
		while (changeMade) {
			changeMade = false;
			for (Gdl gdl : description) {
				if (gdl instanceof GdlRule) {
					changeMade |= addRule((GdlRule) gdl);
				}
			}
			changeMade |= applyLanguageRules();
		}
	}

	private boolean applyLanguageRules() throws InterruptedException {
		boolean changesMade = false;
		changesMade |= applyInjection(new NameAndArity(GdlPool.INIT, 1), new NameAndArity(GdlPool.TRUE, 1));
		changesMade |= applyInjection(new NameAndArity(GdlPool.NEXT, 1), new NameAndArity(GdlPool.TRUE, 1));
		changesMade |= applyInjection(new NameAndArity(GdlPool.LEGAL, 2), new NameAndArity(GdlPool.DOES, 2));
		return changesMade;
	}

	private boolean applyInjection(NameAndArity oldName,
			NameAndArity newName) throws InterruptedException {
		ConcurrencyUtils.checkForInterruption();
		Preconditions.checkArgument(oldName.getArity() == newName.getArity());
		boolean changesMade = false;
		if (sentencesModel.containsKey(oldName)) {
			List<TermModel> oldModel = sentencesModel.get(oldName);
			if (!sentencesModel.containsKey(newName)) {
				changesMade = true;
				sentencesModel.put(newName, getNTermModels(newName.arity));
			}
			List<TermModel> newModel = sentencesModel.get(newName);
			if (oldModel.size() != newModel.size()) {
				throw new IllegalStateException();
			}
			for (int i = 0; i < oldModel.size(); i++) {
				ConcurrencyUtils.checkForInterruption();
				changesMade |= newModel.get(i).mergeIn(oldModel.get(i));
			}
		}
		return changesMade;
	}

	private boolean addRule(GdlRule rule) throws InterruptedException {
		// Stuff can make it into the head sentence form either as part of
		// the head of the rule as presented or due to a variable connected
		// to the positive literals in the rule. (In the latter case, it
		// should be in the intersection of the models of all such positive
		// literals.) For each slot in the body, we want to set up everything
		// that will be injected into it.
		GdlSentence headSentence = rule.getHead();

		// We need to get the possible contents of variables beforehand, to
		// deal with the case of variables being inside functions.
		Map<GdlVariable, TermModel> varsToModelsMap = getVarsToModelsMap(rule);

		return addSentenceToModel(headSentence, varsToModelsMap);
	}

	private Map<GdlVariable, TermModel> getVarsToModelsMap(GdlRule rule) {
		Set<GdlVariable> varsToUse = Sets.newHashSet(GdlUtils.getVariables(rule.getHead()));
		Map<GdlVariable, TermModel> varsToModelsMap = Maps.newHashMap();
		for (GdlVariable var : varsToUse) {
			varsToModelsMap.put(var, new TermModel());
		}

		for (GdlLiteral literal : rule.getBody()) {
			if (literal instanceof GdlRelation) {
				List<GdlTerm> literalBody = ((GdlRelation) literal).getBody();
				NameAndArity nameAndArity = new NameAndArity((GdlSentence) literal);
				if (!sentencesModel.containsKey(nameAndArity)) {
					sentencesModel.put(nameAndArity, getNTermModels(nameAndArity.getArity()));
				}
				List<TermModel> literalModel = sentencesModel.get(nameAndArity);
				addVariablesToMap(literalBody, literalModel, varsToModelsMap);
			}
		}
		return varsToModelsMap;
	}

	private void addVariablesToMap(List<GdlTerm> body,
			List<TermModel> model,
			Map<GdlVariable, TermModel> varsToModelsMap) {
		if (body.size() != model.size()) {
			throw new IllegalArgumentException("The term model and body sizes don't match: model is " + model + ", body is: " + body);
		}
		for (int i = 0; i < body.size(); i++) {
			GdlTerm term = body.get(i);
			TermModel termModel = model.get(i);
			if (term instanceof GdlVariable) {
				GdlVariable var = (GdlVariable) term;
				if (varsToModelsMap.containsKey(var)) {
					varsToModelsMap.get(var).mergeIn(termModel);
				}
			} else if (term instanceof GdlFunction) {
				GdlFunction function = (GdlFunction) term;
				List<TermModel> functionBodyModel = termModel.getFunctionBodyModel(function);
				if (functionBodyModel != null) {
					addVariablesToMap(function.getBody(), functionBodyModel, varsToModelsMap);
				}
			}
		}
	}

	private void addTrueSentencesToModel() throws InterruptedException {
		for (Gdl gdl : description) {
			ConcurrencyUtils.checkForInterruption();
			if (gdl instanceof GdlSentence) {
				addSentenceToModel((GdlSentence) gdl, ImmutableMap.<GdlVariable, TermModel>of());
			}
		}
	}

	private boolean addSentenceToModel(GdlSentence sentence, Map<GdlVariable, TermModel> varsToModelsMap) throws InterruptedException {
		ConcurrencyUtils.checkForInterruption();
		boolean changesMade = false;
		NameAndArity sentenceName = new NameAndArity(sentence);
		if (!sentencesModel.containsKey(sentenceName)) {
			changesMade = true;
			sentencesModel.put(sentenceName, getNTermModels(sentence.arity()));
		}
		changesMade |= addBodyToModel(sentencesModel.get(sentenceName), sentence.getBody(), varsToModelsMap);
		return changesMade;
	}

	private static List<TermModel> getNTermModels(int arity) {
		List<TermModel> result = Lists.newArrayListWithCapacity(arity);
		for (int i = 0; i < arity; i++) {
			result.add(new TermModel());
		}
		return result;
	}

	private static boolean addBodyToModel(List<TermModel> model, List<GdlTerm> body, Map<GdlVariable, TermModel> varsToModelsMap) {
		boolean changesMade = false;
		if (model.size() != body.size()) {
			throw new IllegalArgumentException("The term model and body sizes don't match: model is " + model + ", body is: " + body);
		}
		for (int i = 0; i < model.size(); i++) {
			TermModel termModel = model.get(i);
			GdlTerm term = body.get(i);
			changesMade |= termModel.addTerm(term, varsToModelsMap);
		}
		return changesMade;
	}

	private static class TermModel {
		private final Set<GdlConstant> possibleConstants = Sets.newHashSet();
		private final Map<NameAndArity, List<TermModel>> possibleFunctions = Maps.newHashMap();

		public List<TermModel> getFunctionBodyModel(GdlFunction function) {
			return possibleFunctions.get(new NameAndArity(function));
		}

		public Set<GdlConstant> getPossibleConstants() {
			return possibleConstants;
		}

		public Map<NameAndArity, List<TermModel>> getPossibleFunctions() {
			return possibleFunctions;
		}

		public boolean mergeIn(TermModel other) {
			boolean changesMade = false;
			changesMade |= possibleConstants.addAll(other.possibleConstants);
			for (NameAndArity key : other.possibleFunctions.keySet()) {
				List<TermModel> theirFunctionBodies = other.possibleFunctions.get(key);
				if (!possibleFunctions.containsKey(key)) {
					possibleFunctions.put(key, deepCopyOf(theirFunctionBodies));
					changesMade = true;
				} else {
					List<TermModel> ourFunctionBodies = possibleFunctions.get(key);
					if (ourFunctionBodies.size() != theirFunctionBodies.size()) {
						throw new IllegalStateException();
					}
					for (int i = 0; i < ourFunctionBodies.size(); i++) {
						changesMade |= ourFunctionBodies.get(i).mergeIn(theirFunctionBodies.get(i));
					}
				}
			}
			return changesMade;
		}

		public TermModel() {
		}

		public boolean addTerm(GdlTerm term, Map<GdlVariable, TermModel> varsToModelsMap) {
			boolean changesMade = false;
			if (term instanceof GdlConstant) {
				changesMade = possibleConstants.add((GdlConstant) term);
			} else if (term instanceof GdlFunction) {
				GdlFunction function = (GdlFunction) term;
				NameAndArity sentenceName = new NameAndArity(function);
				if (!possibleFunctions.containsKey(sentenceName)) {
					changesMade = true;
					possibleFunctions.put(sentenceName, getNTermModels(function.arity()));
				}
				changesMade |= addBodyToModel(possibleFunctions.get(sentenceName), function.getBody(), varsToModelsMap);
			} else if (term instanceof GdlVariable) {
				changesMade = mergeIn(varsToModelsMap.get(term));
			} else {
				throw new RuntimeException("Unrecognized term type " + term.getClass() + " for term " + term);
			}
			return changesMade;
		}

		@Override
		public String toString() {
			return "NewTermModel [possibleConstants=" + possibleConstants
					+ ", possibleFunctions=" + possibleFunctions + "]";
		}

		public static TermModel copyOf(TermModel originalTermModel) {
			TermModel termModel = new TermModel();
			termModel.mergeIn(originalTermModel);
			return termModel;
		}
	}

	private static class NameAndArity {
		private final GdlConstant name;
		private final int arity;

		public NameAndArity(GdlSentence sentence) {
			this.name = sentence.getName();
			this.arity = sentence.arity();
		}

		public NameAndArity(GdlFunction function) {
			this.name = function.getName();
			this.arity = function.arity();
		}

		public NameAndArity(GdlConstant name, int arity) {
			this.name = name;
			this.arity = arity;
		}

		public GdlConstant getName() {
			return name;
		}

		public int getArity() {
			return arity;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + arity;
			result = prime * result + ((name == null) ? 0 : name.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object obj) {
			if (this == obj)
				return true;
			if (obj == null)
				return false;
			if (getClass() != obj.getClass())
				return false;
			NameAndArity other = (NameAndArity) obj;
			if (arity != other.arity)
				return false;
			if (name == null) {
				if (other.name != null)
					return false;
			} else if (!name.equals(other.name))
				return false;
			return true;
		}

		@Override
		public String toString() {
			return "NameAndArity [name=" + name + ", arity=" + arity + "]";
		}
	}

	public static List<TermModel> deepCopyOf(List<TermModel> original) {
		List<TermModel> copy = Lists.newArrayListWithCapacity(original.size());
		for (TermModel originalTermModel : original) {
			copy.add(TermModel.copyOf(originalTermModel));
		}
		return copy;
	}
}


text:
var Inbox = require('simple-imap-inbox');
var Role = require('./role');
var Dashboard = require('./dashboard');
var Q = require('q');
var path = require('path');

/**
 * Project resource.
 *
 * @constructor
 *
 * @property {API} api API instance
 * @property {User} user User instance
 * @property {Object} data Server data
 *
 * @param {API} api  API instance
 * @param {User} user User instance
 * @param {Object} data [optional] Server data
 */
var Project = function(api, user, data) {
    this.api = api;
    this.user = user;
    this.data = data || {};
};

Project.prototype = {
    /**
     * Project URI
     *
     * @readOnly
     * @type {String}
     */
    get uri() { return this.data.links && this.data.links.self; }
};

/**
 * Load project data from project resource
 *
 * Data is stored in `data` property of this instance
 *
 * @param  {String} projectUri [optional] Project URL
 * @return {Promise}
 */
Project.prototype.load = function(projectUri) {
    projectUri = projectUri || this.uri;

    return this.api.request(projectUri).then(function(res) {
        this.data = res.data.project;

        return this.data;
    }.bind(this));
};

/**
 * Delete project on server.
 *
 * @param  {String} projectUri [optional] Project URI
 * @return {Promise}
 */
Project.prototype.delete = function(projectUri) {
    projectUri = projectUri || this.uri;

    return this.api.request(projectUri, 'DELETE').then(function() {
        this.data = null;
    }.bind(this));
};

/**
 * Set this project as user's default
 *
 * @param {String} projectUri [optional] Project URI
 *
 * @return {Promise}
 */
Project.prototype.setAsDefault = function(projectUri) {
    projectUri = projectUri || this.uri;

    return this.user.getSettings().then(function(settings) {
        settings.currentProjectUri = projectUri;

        return this.user.setSettings(settings);
    }.bind(this));
};

/**
 * Query project for list of objects of given type.
 *
 * Available objects include:
 *
 * - projectdashboards
 * - reports
 * - datasets
 * - userfilters
 * - scheduledemails
 *
 * Returned promise is resolved with an array of result objects
 *
 * @param  {String} type Subject of query, e.g. projectdashboards
 * @return {Promise}
 */
Project.prototype.query = function(type) {
    var queryUrl = path.join(this.data.links.metadata, 'query', type);

    return this.api.request(queryUrl).then(function(res) {
        return res.data.query.entries;
    });
};

/**
 * Query project for list of objects of given type
 * and load each object's data.
 *
 * You can pass second parameter of type function that will be called
 * for each returned object and return value of this call will be used
 * instead of raw data.
 *
 * Returned promise is resolved with array of loaded objects.
 *
 * @private
 *
 * @param  {String} type    Subject of query, e.g. projectdashboards
 * @param  {Function} wrapper [optional] Processor callback
 * @return {Promise}
 */
Project.prototype.__queryAndLoad = function(type, wrapper) {
    var api = this.api;

    wrapper = wrapper || function(data) { return data; };

    return this.query(type).then(function(entries) {
        return Q.all(entries.map(function(entry) {
            return api.request(entry.link).then(function(res) {
                return wrapper(res.data);
            });
        }));
    });
};

/**
 * List project dashboards
 *
 * Returned promise is resolved with an array of Dashboard objects
 *
 * @return {Promise}
 */
Project.prototype.listDashboards = function() {
    var project = this;
    var api = this.api;

    return this.__queryAndLoad('projectdashboards', function(data) {
        return new Dashboard(api, project, data.projectDashboard);
    });
};

/**
 * List all the project roles
 *
 * Returned promise is resolved with an array of Role instances
 *
 * @return {Promise}
 */
Project.prototype.listRoles = function() {
    var project = this;
    var api = this.api;

    return api.request(this.data.links.roles).then(function(res) {
        return Q.all(res.data.projectRoles.roles.map(function(role) {
            return api.request(role).then(function(res) {
                res.data.projectRole.links.self = role;

                return res.data.projectRole;
            });
        })).then(function(rolesData) {
            return rolesData.map(function(roleData) {
                return new Role(api, project, roleData);
            });
        });
    });
};

/**
 * Finds a role by name. In cae there s no role with such a name,
 * promise is rejected.
 *
 * Returned promise is resolved with found Role instance.
 *
 * @param  {String} name Role name
 * @return {Promise}
 */
Project.prototype.getRoleByName = function(name) {
    return this.listRoles().then(function(roles) {
        return (function() {
            for (var i = 0, n = roles.length; i < n; i++) {
                if (roles[i].data.meta.title === name) {
                    return roles[i];
                }
            }
        })();
    });
};

/**
 * Invite user to this project.
 *
 * This method receives an instance of User object (user HAS to be at least logged in!),
 * String name of the role that this user should be assigned and Object containing
 * email credentials needed to accept invitation sent by email.
 *
 * Returned promise is resolved with this instance.
 *
 * @throws {Error} If user is not loaded
 *
 * @param  {User|String} user User instance or user login email
 * @param  {String} roleName Role name, e.g. `Admin`, `Editor`
 * @return {Promise}
 */
Project.prototype.invite = function(user, roleName, emailCredentials) {
    var login = typeof(user) === 'string' ? user : user.data.login;

    if (!login) {
        throw new Error('No login for invitation provided');
    }

    return this.getRoleByName(roleName).then(function(role) { // Load role definition
        return this.api.request(this.data.links.invitations, 'POST', { // Create invitation
            invitations: [
                {
                    invitation: {
                        content: {
                            email: login,
                            firstname: '',
                            lastname: '',
                            role: role.data.links.self,
                            action: {
                                setMessage: ''
                            }
                        }
                    }
                }
            ]
        });
    }.bind(this)).then(function() {
        var criteria = [
            ['FROM', 'invitation@gooddata.com'],
            ['TO', login],
            'UNSEEN'
        ];
        var inbox = new Inbox({
            user: emailCredentials.username,
            password: emailCredentials.password
        }).useGmail();

        var search = function() {
            return inbox.search(criteria, { markSeen: true }).then(function(messages) {
                return messages.length ? messages.pop() : search();
            });
        };

        return inbox.connect().then(function() {
            return search();
        }).then(function(message) {
            inbox.on('error', function() {});

            return inbox.disconnect().then(function() {
                return message;
            });
        });
    }).then(function(message) {
        var regexp = new RegExp('https://[a-zA-Z0-9_.:-]+/p/([a-zA-Z0-9_-]+)');
        var matches = message.body.match(regexp);

        if (!matches) {
            throw new Error('Email with invitation link not found');
        }

        return matches[1];
    }).then(function(invitationId) {
        var invitationUri = '/gdc/account/invitations/' + invitationId;

        return this.api.request(invitationUri, 'POST', {
            invitationStatusAccept: {
                status: 'ACCEPTED'
            }
        });
    }.bind(this)).then(function() {
        return this;
    }.bind(this));
};

module.exports = Project;


text:
{% extends 'board_base.html' %}
{% load i18n %}
{% load mptt_tags %}
{% load forum_tags %}
{% load forum_conversation_tags %}
{% load forum_permission_tags %}
{% load forum_tracking_tags %}
{% load activity_tags %}
{% load forum_extras %}
{% load crispy_forms_tags %}

{% block sub_title %}{{ forum.name }}{% endblock sub_title %}

{% block content %}

{{ forum.name }}

{% if sub_forums %}

    {% if request.user.is_authenticated %}

       {% trans "Mark subforums read" %}

    {% endif %}

{% forum_list sub_forums %}
{% endif %}
{% if forum.is_forum %}

    {% get_permission 'can_add_topic' forum request.user as user_can_add_topic %}
    {% get_permission 'can_read_forum' forum request.user as user_can_read_forum %}
    {% if user_can_add_topic %}
     {% trans "New topic" %}
    {% endif %}
    {% if user_can_read_forum and request.user|is_following:forum %}
        {% get_follow_object_pk request.user forum as follow_object_pk %}
        {% if follow_object_pk %}
            <form class="d-inline" method="post" action="{% url 'notifications:follow-delete' pk=follow_object_pk %}">
                {% csrf_token %}
                <button type="submit" class="btn btn-info btn-sm btn-subscription">
                    {% trans "Unsubscribe" %}
                </button>
            </form>
        {% endif %}
    {% elif user_can_read_forum and not request.user|is_following:forum %}
        {% get_content_type forum as forum_ct %}
        {% follow_form user=request.user content_type=forum_ct.id object_id=forum.id as follow_form %}
        <form class="d-inline" method="post" action="{% url 'notifications:follow-create' %}">
            {% csrf_token %}
            {{ follow_form|crispy }}
            <button type="submit" class="btn btn-info btn-sm btn-subscription">
                {% trans "Subscribe" %}
            </button>
        </form>
    {% endif %}

    {% if topics|length > 0 and request.user.is_authenticated %}

      {% trans "Mark topics read" %}

    {% endif %}
    {% with "pagination-sm justify-content-end" as pagination_size %}
    {% include "partials/pagination.html" %}
    {% endwith %}

{% trans "Announcements" as announcements_title_trans %}
{% with topic_list_title=announcements_title_trans topics=announces hide_if_empty=True unread_topics=unread_topics %}
{% include "forum_conversation/topic_list.html" %}
{% endwith %}
{% trans "Topics" as topics_title_trans %}
{% with topic_list_title=topics_title_trans unread_topics=unread_topics%}
{% include "forum_conversation/topic_list.html" %}
{% endwith %}

    {% if user_can_add_topic %}
     {% trans "New topic" %}
    {% endif %}

    {% if topics|length > 0 and request.user.is_authenticated %}

      {% trans "Mark topics read" %}

    {% endif %}
    {% with "pagination-sm justify-content-end" as pagination_size %}
    {% include "partials/pagination.html" %}
    {% endwith %}

{% endif %}
{% endblock content %}


text:
if [ $# -lt 3 ]; then
    echo "usage: ./set_ui_port_forward.sh <external IP> <Weave internal IP> <Port>"
    echo "example: ./set_ambari_server_network.sh 104.196.56.56 192.168.2.2 8088"
    exit 1
fi

from_ip=$1
to_ip=$2
port=$3

# enable forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

echo "forward port $port from $from_ip to $to_ip"

#just to be sure firewall doesn't block
iptables -I FORWARD -p tcp -d $from_ip --dport $port -j ACCEPT
#actual forward
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport $port -j DNAT --to $to_ip

#same for UDP
iptables -I FORWARD -p udp -d $from_ip --dport $port -j ACCEPT
iptables -t nat -A PREROUTING -p udp -i eth0 --dport $port -j DNAT --to $to_ip


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CodeReaction.Domain.Commits
{
    public class CommitService
    {
        UnitOfWork unitOfWork;

        public CommitService(UnitOfWork unitOfWork)
        {
            this.unitOfWork = unitOfWork;
        }

        public void ApproveCommit( int revision, string author )
        {
            var commit = unitOfWork.Context.Commits.Single( c => c.Revision == revision);
            commit.ApprovedBy = author;
        }
    }
}


text:
<?php

namespace Biz\Article\Dao\Impl;

use Biz\Article\Dao\CategoryDao;
use Codeages\Biz\Framework\Dao\GeneralDaoImpl;

class CategoryDaoImpl extends GeneralDaoImpl implements CategoryDao
{
    protected $table = 'article_category';

    public function getByParentId($parentId)
    {
        return $this->getByFields(array(
            'parentId' => $parentId,
        ));
    }

    public function findByParentId($parentId)
    {
        return $this->findByFields(array(
            'parentId' => $parentId,
        ));
    }

    public function findAllPublishedByParentId($parentId)
    {
        $sql = "SELECT * FROM {$this->table()} WHERE parentId = ? AND published = ? order by weight";

        return $this->db()->fetchAll($sql, array($parentId, 1)) ?: array();
    }

    public function findByCode($code)
    {
        $sql = "SELECT * FROM {$this->table()} WHERE code = ? LIMIT 1";

        return $this->db()->fetchAssoc($sql, array($code)) ?: array();
    }

    public function searchByParentId($parentId, $orderBy, $start, $limit)
    {
        return $this->search(
            array(
                'parentId' => $parentId,
            ),
            $orderBy,
            $start,
            $limit
        );
    }

    public function countByParentId($parentId)
    {
        $sql = "SELECT COUNT(*) FROM {$this->table()} WHERE  parentId = ?";

        return $this->db()->fetchColumn($sql, array($parentId));
    }

    public function findByIds(array $ids)
    {
        return $this->findInField('id', $ids);
    }

    public function findAll()
    {
        $sql = "SELECT * FROM {$this->table()} ORDER BY weight ASC";

        return $this->db()->fetchAll($sql) ?: array();
    }

    public function declares()
    {
        return array(
            'conditions' => array(
                'parentId = :parentId',
            ),
        );
    }
}


text:
package internal

type PlainCrypter struct{}

func (pc PlainCrypter) Name() string {
	return "plain"
}

func (pc PlainCrypter) Encrypt(plaintext string, encryptParams EncryptParams) (Ciphertext, DecryptParams, error) {
	return Ciphertext(plaintext), nil, nil
}

func (pc PlainCrypter) Decrypt(myCiphertext Ciphertext, decryptParams DecryptParams) (string, error) {
	return string(myCiphertext), nil
}


text:
var Hapi   = require('hapi');
var secret = 'NeverShareYourSecret';

// for debug options see: http://hapijs.com/tutorials/logging
var debug;
// debug = { debug: { 'request': ['error', 'uncaught'] } };
debug = { debug: false };
var server = new Hapi.Server(debug);
server.connection();

var sendToken = function(req, reply) {
  return reply(req.auth.token);
};

var privado = function(req, reply) {
  return reply(req.auth.credentials);
};

// defining our own validate function lets us do something
// useful/custom with the decodedToken before reply(ing)
var customVerifyFunc = function (decoded, request, callback) {
  if(decoded.error) {
    return callback(new Error('customVerify fails!'));
  }
  else if (decoded.some_property) {
    return callback(null, true);
  }
  else {
    return callback(null, false, decoded);
  }
};

server.register(require('../'), function () {

  server.auth.strategy('jwt', 'jwt', {
    verifyFunc: customVerifyFunc // no validateFunc or key required.
  });

  server.route([
    { method: 'GET',  path: '/', handler: sendToken, config: { auth: false } },
    { method: 'GET', path: '/required', handler: privado, config: { auth: { mode: 'required', strategy: 'jwt' } } },
    { method: 'GET', path: '/optional', handler: privado, config: { auth: { mode: 'optional', strategy: 'jwt' } } },
    { method: 'GET', path: '/try', handler: privado, config: { auth: { mode: 'try', strategy: 'jwt' } } }
  ]);

});

module.exports = server;


text:
<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Post2 | Caio Santos - Analista de TI e Desenvolvedor Web</title>
      <meta name="title" content="Caio Santos - Desenvolvedor Web">
      <meta name="description" content="My personal web site, for curriculum, blog, technology matters and others.">
      <meta name="keywords" content="pessoal, tecnologia, blog, caio, resume, portfolio, front end, back end, desenvolvedor, programador, web, internet, tecnologia, linux, javascript. nodejs, estudo, trabalho">
      <link href="https://fonts.googleapis.com/css?family=Raleway:400,700" rel="stylesheet">
      <link href="https://fonts.googleapis.com/css?family=Roboto:400,400i" rel="stylesheet">
      <link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">
      <link rel="canonical" href="https://www.caiocss.com">
      <link rel="stylesheet" href="css/reset.css">
      <link rel="stylesheet" href="css/main_style.css">
      <link rel="stylesheet" href="css/post_style.css">

            About

            Labs and Projects

            Blog

Mais um Dia em TI é Viver e Aprender!

            posted on
            <time datetime="2018-12-25" class="date" itemprop="datePublished">
                25 de Dezembro, 2017
            </time>
             /
            Link

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Velit quidem ex maxime commodi incidunt reiciendis reprehenderit officiis vel deserunt consequatur qui voluptas, sit labore tenetur quaerat totam a saepe accusamus! Lorem ipsum dolor sit amet consectetur adipisicing elit. Aliquid, blanditiis nostrum harum illo quas consequatur reprehenderit dolores tenetur cum vel itaque voluptate accusantium quam deserunt libero. Unde labore in eveniet.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Velit, facilis? Totam odio odit est facere ratione quisquam, doloribus molestiae, accusamus cum harum iure omnis recusandae ipsum. Minima dicta quis esse, lorem ipsum dolor sit amet consectetur adipisicing elit. Assumenda cum iure enim ex adipisci porro non provident blanditiis nemo exercitationem dicta voluptatum eligendi vel, iste aut, fugiat est temporibus! Vero.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure adipisci est beatae quos, quasi earum, tempora suscipit similique ducimus expedita, testando um estilo do site do uol bem aqui qui dolor excepturi natus ratione ad autem eos, sapiente repellendus!

Lorem, ipsum dolor sit amet consectetur adipisicing elit. Libero minima molestiae repellendus error perspiciatis iure cumque ullam ipsam, quos nesciunt, vitae fuga nulla corrupti assumenda consectetur sed, minus distinctio possimus.

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatum neque veniam enim quasi omnis sapiente odio, ipsa illum autem eligendi eaque nemo repellat minus natus nisi sint quae fuga quos! Lorem ipsum dolor sit, amet consectetur adipisicing elit. Necessitatibus aliquam, sunt dolores repellat a nam quod dignissimos at, aspernatur error distinctio quae recusandae? Eius fugit, sed harum aperiam itaque molestias, Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ut adipisci nisi enim laudantium dolorum, aspernatur minima voluptatem amet, autem inventore necessitatibus itaque ipsam, atque laborum cumque similique! Ipsum, quas accusamus? Lorem ipsum dolor sit amet consectetur adipisicing elit. Nam exercitationem magni vero, eveniet reiciendis nemo. Minus inventore asperiores porro reiciendis, delectus dolore facere consectetur impedit quas quisquam eaque corporis recusandae.

Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolor ducimus quasi eum, qui officia et dolorum, voluptates eligendi dicta pariatur, expedita recusandae? Harum facere quidem officiis sint sit laudantium blanditiis!

      Please enable JavaScript to view the

        comments powered by Disqus.


text:
package com.netflix.astyanax.serializers;

import java.nio.ByteBuffer;

import com.netflix.astyanax.shaded.org.apache.cassandra.db.marshal.DoubleType;

/**
 * Uses LongSerializer via translating Doubles to and from raw long bytes form.
 *
 * @author Yuri Finkelstein
 */
public class DoubleSerializer extends AbstractSerializer<Double> {

    private static final DoubleSerializer instance = new DoubleSerializer();

    public static DoubleSerializer get() {
        return instance;
    }

    @Override
    public ByteBuffer toByteBuffer(Double obj) {
        return LongSerializer.get().toByteBuffer(
                Double.doubleToRawLongBits(obj));
    }

    @Override
    public Double fromByteBuffer(ByteBuffer bytes) {
        if (bytes == null)
            return null;
        ByteBuffer dup = bytes.duplicate();
        return Double
                .longBitsToDouble(LongSerializer.get().fromByteBuffer(dup));
    }

    @Override
    public ByteBuffer fromString(String str) {
        return DoubleType.instance.fromString(str);
    }

    @Override
    public String getString(ByteBuffer byteBuffer) {
        return DoubleType.instance.getString(byteBuffer);
    }

    @Override
    public ByteBuffer getNext(ByteBuffer byteBuffer) {
        double val = fromByteBuffer(byteBuffer.duplicate());
        if (val == Double.MAX_VALUE) {
            throw new ArithmeticException("Can't paginate past max double");
        }
        return toByteBuffer(val + Double.MIN_VALUE);
    }

    @Override
    public ComparatorType getComparatorType() {
        return ComparatorType.DOUBLETYPE;
    }
}