text:
var express    = require('express');
var fs         = require("fs");
var path = require('path');
var sqlite3    = require("sqlite3").verbose();
var helpers    = require("./helpers");
var config     = require("./config");
var users      = require("./users");
var posts      = require("./posts");
var when       = require("when");
var busboy     = require('connect-busboy');
var sanitizer  = require("sanitizer");
var sanitizefn = require("sanitize-filename");

var app = express();
var port = config.port;
var dbfile = config.dbfile;

// file uploads restrictions
app.use(busboy({
  highWaterMark: 1 * 1024 * 1024,
  limits: {
    fileSize: 1 * 1024 * 1024 // 1 MB upload limit
  }
}));

// parse the body of the request and then it sets the body property on the request object.
app.use(express.json());
app.use(express.urlencoded());

// Create the database if it doesn't exist
var exists = fs.existsSync(dbfile);
var db = new sqlite3.Database(dbfile);
db.serialize(function() {
	if(!exists) {
		console.log("creating a new db...")
		console.log("creating db tables...")
		db.run("CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT, password TEXT)");
		db.run("CREATE TABLE posts (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, title TEXT, body TEXT, date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP)");
	}
});
db.close();

// start the server
app.listen(process.env.PORT || port);
console.log("forum-server started - listening on port " + port);

// routes
app.post('/users/signup', function(req, res) {

	var user = {
		email: req.body.email,
		pw: req.body.password
	}

	// sanitize input for any unsafe HTML - XSS protection
	users.sanitizeUser(user)

	// validate the user input
	.then(helpers.validatePasswordLength)
	.then(function () {
		return user.email;
	})
	.then(helpers.validateEmail)

	// check if the email already exists
	.then(users.userExists)
	.then(function () {
		return user.pw;
	})

	// create the password hash
	.then(helpers.generateHashedPassword)
	.then(function (hash) {
		user.pw = hash;
		return user;
	})

	// save to the database
	.then (users.saveUser)
	.then (function() {
		console.log (req.body.email + " registered!");
		res.send(req.body.email + " has been successfully registered.");
	}, function (error) {
		console.log (error);
		res.json(401, {error: error.message});
	});
});

// simple authentication function
var auth = express.basicAuth(function(user, pass, callback) {
	var user = {
		email: user,
		pw: pass
	}

 	users.authenticate(user).then(function (matched) {
 		callback(null, matched);
 	}, function (error) {
 		console.log(error);
 		callback(null, false);
 	});
});

// a user can add posts only if authenticated using the auth function.
app.post('/posts/add', auth, function(req, res) {

 	// get the user email from the request header
 	var useremail = helpers.getUserEmailFromRequestHeader(req);

 	var post = {
 		title: req.body.title,
 		body: req.body.body,
 		user_id: 0 // will be set below
 	}

 	// sanitize user input against any unsafe code
 	posts.sanitizePost(post)
 	.then(function () {
 		return useremail;
 	})

 	// get user's id
	.then(users.getUserByEmail)
	.then(function (records) {
		post.user_id = records[0].id;
		return post;
	})

 	// add the post to the database
 	.then(posts.add)

 	.then (function() {
		console.log ("The '" + post.title + "' post has been successfully added.");
		res.send("The '" + post.title + "' post has been successfully added.");
	}, function (error) {
		console.log (error);
		res.json(401, {error: error.message});
	});

});

// get all posts for a specific user
app.get('/posts/get', auth, function(req, res) {

	// get the user email from the request header
	var useremail = helpers.getUserEmailFromRequestHeader(req);

	// get user's id
	users.getUserByEmail(useremail)
	.then(function (records) {
		return records[0].id;
	})

	// get user's posts
	.then(posts.getPostsByUserID)

	.then (function(records) {
		res.json(200, records);
	}, function (error) {
		console.log (error);
		res.json(401, {error: error.message});
	});
});

// file upload api
app.post('/files/upload', auth, function(req, res) {
    var fstream;
    var results = [];
    req.busboy.on('file', function (fieldname, file, filename) {
        console.log("Uploading: " + filename);

        // get the user email from the request header
 		var useremail = helpers.getUserEmailFromRequestHeader(req);

 		users.getUserByEmail(useremail)
		.then(function (records) {
	 		var distinationdir = path.join(__dirname, '/uploads/');

	        // create the uploads directory if it doesn't exist
	        fs.mkdir(distinationdir, function (err) {
	        	if (err && err.code != 'EEXIST') {
	        		console.log(err);
	        		return;
	        	}

	        	// create the user's directory if it doesn't exist - the directory name will be the user's ID
	        	fs.mkdir(path.join(distinationdir, String(records[0].id)), function (err) {
		        	if (err && err.code != 'EEXIST') {
		        		console.log(err);
		        		return;
		        	}

		        	// sanitize the filename for any unsafe code
		        	sanitizer.sanitize(filename);

	        		// Sanitize a string to be safe for use as a file name in
	        		// Windows and Unix systems by stripping all control characters and restricted characters
	        		sanitizefn(filename);
	        		filename = path.basename(filename);

		        	// for server files safety, the overwrite is not supported
		        	var filepath = path.join(distinationdir, String(records[0].id), filename);
		        	var fileexists = fs.existsSync(filepath)
		        	if (fileexists)
		        	{
		        		file.resume();
		        		console.log("Trying to overwrite existing file. upload will abort.");
		        		results.push("Overwriting existing files is not supported. please use a different file name");
		        		return;
		        	}

					fstream = fs.createWriteStream(filepath);
					file.pipe(fstream);
					fstream.on('close', function () {
					    results.push(filename + " has been successfully uploaded.");
					});

				});

	        });

	    }, function (err) {
			console.log(err);
	    });
    });

    req.pipe(req.busboy);

    req.busboy.on('finish', function() {
      console.log('Done!');
      res.writeHead(200, { Connection: 'close' });
      res.end(JSON.stringify(results));
    });
});

app.get('/files/getmyfiles', auth, function(req, res) {

	// get the user email from the request header
	var useremail = helpers.getUserEmailFromRequestHeader(req);

	users.getUserByEmail(useremail)
	.then(function (records) {
		var distinationdir = path.join(__dirname, '/uploads/', String(records[0].id));
	    fs.exists(distinationdir, function (exists) {
	    	if (exists)
	    	{
	    		fs.readdir(distinationdir, function (err, files) {
	    			console.log(files);
	    			if (files.length == 0)
	    				res.json(200, "No files uploaded yet");
	    			else
	    				res.json(200, files);
	    			return;
	    		});
	    	}
	    	else
	    	{
	    		res.json(200, "No files uploaded yet");
	    	}
	    });
	});
});

app.get('/files/download/:filename', auth, function(req, res) {

	var filename = req.params.filename;

	// sanitize the filename for any unsafe code
	sanitizer.sanitize(filename);

	// Sanitize a string to be safe for use as a file name in
	// Windows and Unix systems by stripping all control characters and restricted characters
	sanitizefn(filename);
	filename = path.basename(filename);

	// get the user email from the request header
	var useremail = helpers.getUserEmailFromRequestHeader(req);

	users.getUserByEmail(useremail)
	.then(function (records) {
		var distinationdir = path.join(__dirname, '/uploads/', String(records[0].id));
	    fs.exists(distinationdir, function (exists) {
	    	if (exists)
	    	{
	    		var filepath = path.join(distinationdir, filename);
	    		res.download(filepath);
	    	}
	    	else
	    	{
	    		res.json(200, "No files uploaded yet");
	    	}
	    });
	});
});

app.get('/', function(req, res) {
	res.send('Hello, welcome to the forum server.');
});


text:
import { matches } from "./dom"

let preventDefault

// Polyfill for CustomEvent in IE9+
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent#Polyfill
let {
  CustomEvent
} = window

if (typeof CustomEvent !== "function") {
  CustomEvent = function(event, params) {
    const evt = document.createEvent("CustomEvent")
    evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
    return evt
  }

  CustomEvent.prototype = window.Event.prototype;

  // Fix setting `defaultPrevented` when `preventDefault()` is called
  // http://stackoverflow.com/questions/23349191/event-preventdefault-is-not-working-in-ie-11-for-custom-events
  ({ preventDefault } = CustomEvent.prototype)
  CustomEvent.prototype.preventDefault = function() {
    const result = preventDefault.call(this)
    if (this.cancelable && !this.defaultPrevented) {
      Object.defineProperty(this, "defaultPrevented", {get() { return true }})
    }
    return result
  }
}

// Triggers a custom event on an element and returns false if the event result is false
// obj::
//   a native DOM element
// name::
//   string that corresponds to the event you want to trigger
//   e.g. 'click', 'submit'
// data::
//   data you want to pass when you dispatch an event
const fire = (obj, name, data) => {
  const event = new CustomEvent(
    name, {
    bubbles: true,
    cancelable: true,
    detail: data
  }
  )
  obj.dispatchEvent(event)
  return !event.defaultPrevented
}

// Helper function, needed to provide consistent behavior in IE
const stopEverything = (e) => {
  fire(e.target, "ujs:everythingStopped")
  e.preventDefault()
  e.stopPropagation()
  e.stopImmediatePropagation()
}

// Delegates events
// to a specified parent `element`, which fires event `handler`
// for the specified `selector` when an event of `eventType` is triggered
// element::
//   parent element that will listen for events e.g. document
// selector::
//   CSS selector; or an object that has `selector` and `exclude` properties (see: Rails.matches)
// eventType::
//   string representing the event e.g. 'submit', 'click'
// handler::
//   the event handler to be called
const delegate = (element, selector, eventType, handler) => element.addEventListener(eventType, function(e) {
  let {
    target
  } = e
  while (!!(target instanceof Element) && !matches(target, selector)) { target = target.parentNode }
  if (target instanceof Element && (handler.call(target, e) === false)) {
    e.preventDefault()
    e.stopPropagation()
  }
})

export { fire, stopEverything, delegate }

redpajama_set_name: RedPajamaGithub


text: Small school project I made to convert units.


text:
import {
    BufferAttribute,
    Line,
    LineBasicMaterial,
} from "three";

export class CellLine extends Line {
    public readonly material: LineBasicMaterial;

    constructor(vertices: number[][]) {
        super();

        this._makeAttributes(vertices);

        this.matrixAutoUpdate = false;
        this.updateMatrix();
        this.updateMatrixWorld(false);
    }

    public dispose(): void {
        this.geometry.dispose();
        this.material.dispose();
    }

    private _makeAttributes(vertices: number[][]): void {
        const closedPolygon = vertices.slice()
        closedPolygon.push(vertices[0]);

        let index = 0;
        const positions = new Float32Array(3 * (vertices.length + 1));
        for (const vertex of closedPolygon) {
            positions[index++] = vertex[0];
            positions[index++] = vertex[1];
            positions[index++] = vertex[2];
        }

        this.geometry.setAttribute(
            "position",
            new BufferAttribute(positions, 3));
    }
}


text:
class DeviseInvitableAddToUsers < ActiveRecord::Migration[5.2]
  def up
    change_table :users do |t|
      t.string     :invitation_token
      t.datetime   :invitation_created_at
      t.datetime   :invitation_sent_at
      t.datetime   :invitation_accepted_at
      t.integer    :invitation_limit
      t.references :invited_by, polymorphic: true
      t.integer    :invitations_count, default: 0
      t.index      :invitations_count
      t.index      :invitation_token, unique: true # for invitable
      t.index      :invited_by_id
    end
  end

  def down
    change_table :users do |t|
      t.remove_references :invited_by, polymorphic: true
      t.remove :invitations_count, :invitation_limit, :invitation_sent_at, :invitation_accepted_at, :invitation_token, :invitation_created_at
    end
  end
end


text:
#include "lm/enumerate_vocab.hh"
#include "lm/model.hh"
#include "lm/left.hh"
#include "lm/state.hh"
#include "util/murmur_hash.hh"

#include <iostream>

#include <string.h>
#include <stdlib.h>
#include <jni.h>
#include <pthread.h>

// Grr.  Everybody's compiler is slightly different and I'm trying to not depend on boost.
#include <unordered_set>
#include <vector>

// Verify that jint and lm::ngram::WordIndex are the same size. If this breaks
// for you, there's a need to revise probString.
namespace {

template<bool> struct StaticCheck {
};

template<> struct StaticCheck<true> {
  typedef bool StaticAssertionPassed;
};

typedef StaticCheck<sizeof(jint) == sizeof(lm::WordIndex)>::StaticAssertionPassed FloatSize;

// Could be uint64_t if you wanted to have 33-bit support.
typedef uint32_t StateIndex;
typedef std::vector<lm::ngram::ChartState> StateVector;

class HashIndex : public std::unary_function<StateIndex, uint64_t> {
  public:
    explicit HashIndex(const StateVector &vec) : vec_(vec) {}

    uint64_t operator()(StateIndex index) const {
      return hash_value(vec_[index]);
    }

  private:
    const StateVector &vec_;
};

class EqualIndex : public std::binary_function<StateIndex, StateIndex, bool> {
  public:
    explicit EqualIndex(const StateVector &vec) : vec_(vec) {}

    bool operator()(StateIndex first, StateIndex second) const {
      return vec_[first] == vec_[second];
    }

  private:
    const StateVector &vec_;
};

typedef std::unordered_set<StateIndex, HashIndex, EqualIndex> Lookup;

/**
 * A Chart bundles together a vector holding CharStates and an unordered_set of StateIndexes
 * which provides a mapping between StateIndexes and the positions of ChartStates in the vector.
 * This allows for duplicate states to avoid allocating separate state objects at multiple places
 * throughout a sentence.
 */
class Chart {
  public:
    Chart(long* ngramBuffer) :
    ngramBuffer_(ngramBuffer),
    lookup_(1000, HashIndex(vec_), EqualIndex(vec_)) {}

    StateIndex Intern(const lm::ngram::ChartState &state) {
      vec_.push_back(state);
      std::pair<Lookup::iterator, bool> ins(lookup_.insert(vec_.size() - 1));
      if (!ins.second) {
        vec_.pop_back();
      }
      return *ins.first + 1; // +1 so that the first id is 1, not 0.  We use sign bit to
                             // distinguish ChartState from vocab id.
    }

    const lm::ngram::ChartState &InterpretState(StateIndex index) const {
      return vec_[index - 1];
    }
    long* ngramBuffer_;

  private:
    StateVector vec_;
    Lookup lookup_;
};

// Vocab ids above what the vocabulary knows about are unknown and should
// be mapped to that.
void MapArray(const std::vector<lm::WordIndex>& map, jint *begin, jint *end) {
  for (jint *i = begin; i < end; ++i) {
    *i = map[*i];
  }
}

char *PieceCopy(const StringPiece &str) {
  char *ret = (char*) malloc(str.size() + 1);
  memcpy(ret, str.data(), str.size());
  ret[str.size()] = 0;
  return ret;
}

// Rather than handle several different instantiations over JNI, we'll just
// do virtual calls C++-side.
class VirtualBase {
public:
  virtual ~VirtualBase() {
  }

  // compute/return n-gram probability for array of Joshua word ids
  virtual float Prob(jint *begin, jint *end) const = 0;

  // Compute/return n-gram probability for array of lm:WordIndexes
  virtual float ProbForWordIndexArray(jint *begin, jint *end) const = 0;

  // Returns the internal lm::WordIndex for a string
  virtual uint GetLmId(const StringPiece& word) const = 0;

  virtual bool IsLmOov(const int joshua_id) const = 0;

  virtual bool IsKnownWordIndex(const lm::WordIndex& id) const = 0;

  virtual float ProbRule(lm::ngram::ChartState& state, const Chart &chart) const = 0;

  virtual float ProbString(jint * const begin, jint * const end,
      jint start) const = 0;

  virtual float EstimateRule(jlong *begin, jlong *end) const = 0;

  virtual uint8_t Order() const = 0;

  virtual bool RegisterWord(const StringPiece& word, const int joshua_id) = 0;

protected:
  VirtualBase() {
  }
};

template<class Model> class VirtualImpl: public VirtualBase {
public:
  VirtualImpl(const char *name) :
      m_(name) {
    // Insert unknown id mapping.
    map_.push_back(0);
  }

  ~VirtualImpl() {
  }

  float Prob(jint * const begin, jint * const end) const {
    // map Joshua word ids to lm::WordIndexes
    MapArray(map_, begin, end);
    return ProbForWordIndexArray(begin, end);
  }

  float ProbForWordIndexArray(jint * const begin, jint * const end) const {
    std::reverse(begin, end - 1);
    lm::ngram::State ignored;
    return m_.FullScoreForgotState(
        reinterpret_cast<const lm::WordIndex*>(begin),
        reinterpret_cast<const lm::WordIndex*>(end - 1), *(end - 1),
        ignored).prob;
  }

  uint GetLmId(const StringPiece& word) const {
    return m_.GetVocabulary().Index(word);
  }

  bool IsLmOov(const int joshua_id) const {
    if (map_.size() <= joshua_id) {
      return true;
    }
    return !IsKnownWordIndex(map_[joshua_id]);
  }

  bool IsKnownWordIndex(const lm::WordIndex& id) const {
      return id != m_.GetVocabulary().NotFound();
  }

  float ProbRule(lm::ngram::ChartState& state, const Chart &chart) const {

    // By convention the first long in the ngramBuffer denotes the size of the buffer
    long* begin = chart.ngramBuffer_ + 1;
    long* end = begin + *chart.ngramBuffer_;

    if (begin == end) return 0.0;
    lm::ngram::RuleScore<Model> ruleScore(m_, state);

    if (*begin < 0) {
      ruleScore.BeginNonTerminal(chart.InterpretState(-*begin));
    } else {
      const lm::WordIndex word = map_[*begin];
      if (word == m_.GetVocabulary().BeginSentence()) {
        ruleScore.BeginSentence();
      } else {
        ruleScore.Terminal(word);
      }
    }
    for (jlong* i = begin + 1; i != end; i++) {
      long word = *i;
      if (word < 0)
        ruleScore.NonTerminal(chart.InterpretState(-word));
      else
        ruleScore.Terminal(map_[word]);
    }
    return ruleScore.Finish();
  }

  float EstimateRule(jlong * const begin, jlong * const end) const {
    if (begin == end) return 0.0;
    lm::ngram::ChartState nullState;
    lm::ngram::RuleScore<Model> ruleScore(m_, nullState);

    if (*begin < 0) {
      ruleScore.Reset();
    } else {
      const lm::WordIndex word = map_[*begin];
      if (word == m_.GetVocabulary().BeginSentence()) {
        ruleScore.BeginSentence();
      } else {
        ruleScore.Terminal(word);
      }
    }
    for (jlong* i = begin + 1; i != end; i++) {
      long word = *i;
      if (word < 0)
        ruleScore.Reset();
      else
        ruleScore.Terminal(map_[word]);
    }
    return ruleScore.Finish();
  }

  float ProbString(jint * const begin, jint * const end, jint start) const {
    MapArray(map_, begin, end);

    float prob;
    lm::ngram::State state;
    if (start == 0) {
      prob = 0;
      state = m_.NullContextState();
    } else {
      std::reverse(begin, begin + start);
      prob = m_.FullScoreForgotState(
          reinterpret_cast<const lm::WordIndex*>(begin),
          reinterpret_cast<const lm::WordIndex*>(begin + start),
          begin[start], state).prob;
      ++start;
    }
    lm::ngram::State state2;
    for (const jint *i = begin + start;;) {
      if (i >= end)
        break;
      float got = m_.Score(state, *i, state2);
      i++;
      prob += got;
      if (i >= end)
        break;
      got = m_.Score(state2, *i, state);
      i++;
      prob += got;
    }
    return prob;
  }

  uint8_t Order() const {
    return m_.Order();
  }

  bool RegisterWord(const StringPiece& word, const int joshua_id) {
    if (map_.size() <= joshua_id) {
      map_.resize(joshua_id + 1, 0);
    }
    bool already_present = false;
    if (map_[joshua_id] != 0)
      already_present = true;
    map_[joshua_id] = m_.GetVocabulary().Index(word);
    return already_present;
  }

private:
  Model m_;
  std::vector<lm::WordIndex> map_;
};

VirtualBase *ConstructModel(const char *file_name) {
  using namespace lm::ngram;
  ModelType model_type;
  if (!RecognizeBinary(file_name, model_type))
    model_type = HASH_PROBING;
  switch (model_type) {
  case PROBING:
    return new VirtualImpl<ProbingModel>(file_name);
  case REST_PROBING:
    return new VirtualImpl<RestProbingModel>(file_name);
  case TRIE:
    return new VirtualImpl<TrieModel>(file_name);
  case ARRAY_TRIE:
    return new VirtualImpl<ArrayTrieModel>(file_name);
  case QUANT_TRIE:
    return new VirtualImpl<QuantTrieModel>(file_name);
  case QUANT_ARRAY_TRIE:
    return new VirtualImpl<QuantArrayTrieModel>(file_name);
  default:
    UTIL_THROW(
        lm::FormatLoadException,
        "Unrecognized file format " << (unsigned) model_type
            << " in file " << file_name);
  }
}

} // namespace

extern "C" {

JNIEXPORT jlong JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_construct(
    JNIEnv *env, jclass, jstring file_name) {
  const char *str = env->GetStringUTFChars(file_name, 0);
  if (!str)
    return 0;

  VirtualBase *ret;
  try {
    ret = ConstructModel(str);
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
    abort();
  }
  env->ReleaseStringUTFChars(file_name, str);
  return reinterpret_cast<jlong>(ret);
}

JNIEXPORT void JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_destroy(
    JNIEnv *env, jclass, jlong pointer) {
  delete reinterpret_cast<VirtualBase*>(pointer);
}

JNIEXPORT jlong JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_createPool(
    JNIEnv *env, jclass, jobject arr) {
  jlong* ngramBuffer = (jlong*)env->GetDirectBufferAddress(arr);
  Chart *newChart = new Chart(ngramBuffer);
  return reinterpret_cast<long>(newChart);
}

JNIEXPORT void JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_destroyPool(
    JNIEnv *env, jclass, jlong pointer) {
  delete reinterpret_cast<Chart*>(pointer);
}

JNIEXPORT jint JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_order(
    JNIEnv *env, jclass, jlong pointer) {
  return reinterpret_cast<VirtualBase*>(pointer)->Order();
}

JNIEXPORT jboolean JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_registerWord(
    JNIEnv *env, jclass, jlong pointer, jstring word, jint id) {
  const char *str = env->GetStringUTFChars(word, 0);
  if (!str)
    return false;
  jint ret;
  try {
    ret = reinterpret_cast<VirtualBase*>(pointer)->RegisterWord(str, id);
  } catch (std::exception &e) {
    std::cerr << e.what() << std::endl;
    abort();
  }
  env->ReleaseStringUTFChars(word, str);
  return ret;
}

JNIEXPORT jfloat JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_prob(
    JNIEnv *env, jclass, jlong pointer, jintArray arr) {
  jint length = env->GetArrayLength(arr);
  if (length <= 0)
    return 0.0;
  // GCC only.
  jint values[length];
  env->GetIntArrayRegion(arr, 0, length, values);

  return reinterpret_cast<const VirtualBase*>(pointer)->Prob(values,
      values + length);
}

JNIEXPORT jfloat JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_probForString(
    JNIEnv *env, jclass, jlong pointer, jobjectArray arr) {
  jint length = env->GetArrayLength(arr);
  if (length <= 0)
    return 0.0;
  jint values[length];
  const VirtualBase* lm_base = reinterpret_cast<const VirtualBase*>(pointer);
  for (int i=0; i<length; i++) {
      jstring word = (jstring) env->GetObjectArrayElement(arr, i);
      const char *str = env->GetStringUTFChars(word, 0);
      values[i] = lm_base->GetLmId(str);
      env->ReleaseStringUTFChars(word, str);
  }
  return lm_base->ProbForWordIndexArray(values,
      values + length);
}

JNIEXPORT jboolean JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_isLmOov(
    JNIEnv *env, jclass, jlong pointer, jint word) {
    const VirtualBase* lm_base = reinterpret_cast<const VirtualBase*>(pointer);
    return lm_base->IsLmOov(word);
}

JNIEXPORT jboolean JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_isKnownWord(
    JNIEnv *env, jclass, jlong pointer, jstring word) {
    const char *str = env->GetStringUTFChars(word, 0);
    if (!str)
      return false;
    bool ret;
    const VirtualBase* lm_base = reinterpret_cast<const VirtualBase*>(pointer);
    lm::WordIndex id = lm_base->GetLmId(str);
    ret = lm_base->IsKnownWordIndex(id);
    env->ReleaseStringUTFChars(word, str);
    return ret;
}

JNIEXPORT jfloat JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_probString(
    JNIEnv *env, jclass, jlong pointer, jintArray arr, jint start) {
  jint length = env->GetArrayLength(arr);
  if (length <= start)
    return 0.0;
  // GCC only.
  jint values[length];
  env->GetIntArrayRegion(arr, 0, length, values);

  return reinterpret_cast<const VirtualBase*>(pointer)->ProbString(values,
      values + length, start);
}

union FloatConverter {
  float f;
  uint32_t i;
};

JNIEXPORT jlong JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_probRule(
  JNIEnv *env, jclass, jlong pointer, jlong chartPtr) {

  // Compute the probability
  lm::ngram::ChartState outState;
  const VirtualBase *base = reinterpret_cast<const VirtualBase*>(pointer);
  Chart* chart = reinterpret_cast<Chart*>(chartPtr);
  FloatConverter prob;
  prob.f = base->ProbRule(outState, *chart);
  StateIndex index = chart->Intern(outState);
  return static_cast<uint64_t>(index) << 32 | static_cast<uint64_t>(prob.i);
}

JNIEXPORT jfloat JNICALL Java_org_apache_joshua_decoder_ff_lm_KenLM_estimateRule(
  JNIEnv *env, jclass, jlong pointer, jlongArray arr) {
  jint length = env->GetArrayLength(arr);
  // GCC only.
  jlong values[length];
  env->GetLongArrayRegion(arr, 0, length, values);

  // Compute the probability
  return reinterpret_cast<const VirtualBase*>(pointer)->EstimateRule(values,
      values + length);
}

} // extern


text:
/**
 * Created by Bell on 16/8/10.
 */

const Router = require('koa-router');

import * as auth from '../tools/auth';
import * as controller from '../controllers/user';

let base_url = '/users';
let router = new Router({ prefix: base_url });

router
    .get('/', auth.ensureUser, auth.ensureManager, controller.list)
    .get('/me/profile', auth.ensureUser, controller.myProfile)
    .post('/me/modify-password', auth.ensureUser, controller.modifyMyPassword)
    .get('/:id/profile', auth.ensureUser, auth.ensureManager, controller.profile)
    .post('/:id/password', auth.ensureUser, auth.ensureManager, controller.updatePassword)
    .post('/:id/status', auth.ensureUser, auth.ensureManager, controller.updateStatus);

export default {
    base_url,
    router: router
};


text:
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0">

    <servlet>
        <servlet-name>CQSControllerServlet</servlet-name>
        <servlet-class>com.comcast.cqs.controller.CQSControllerServlet</servlet-class>
	    <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>CQSControllerServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

	<servlet>
		<servlet-name>EndpointServlet</servlet-name>
		<servlet-class>com.comcast.cmb.common.controller.EndpointServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>EndpointServlet</servlet-name>
		<url-pattern>/Endpoint/*</url-pattern>
	</servlet-mapping>

    <servlet>
    	<servlet-name>AdminServlet</servlet-name>
    	<servlet-class>com.comcast.cmb.common.controller.AdminServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>AdminServlet</servlet-name>
    	<url-pattern>/webui/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSUserPageServlet</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSUserPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSUserPageServlet</servlet-name>
    	<url-pattern>/webui/cnsuser/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSEditTopicDisplayNamePage</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSEditTopicDisplayNamePage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSEditTopicDisplayNamePage</servlet-name>
    	<url-pattern>/webui/cnsuser/editdisplayname/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSEditTopicDeliveryPolicyPage</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSEditTopicDeliveryPolicyPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSEditTopicDeliveryPolicyPage</servlet-name>
    	<url-pattern>/webui/cnsuser/editdeliverypolicy/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSEditSubscriptionDeliveryPolicyPage</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSEditSubscriptionDeliveryPolicyPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSEditSubscriptionDeliveryPolicyPage</servlet-name>
    	<url-pattern>/webui/cnsuser/subscription/editdeliverypolicy/*</url-pattern>
    </servlet-mapping>

     <servlet>
    	<servlet-name>CNSRawMessageDeliveryPolicyPage</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSRawMessageDeliveryPolicyPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSRawMessageDeliveryPolicyPage</servlet-name>
    	<url-pattern>/webui/cnsuser/subscription/rawmessagedeliverypolicy/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSTopicPermissionPage</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSTopicPermissionPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSTopicPermissionPage</servlet-name>
    	<url-pattern>/webui/cnsuser/permission/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSTopicAddPermissionPage</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSTopicAddPermissionPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSTopicAddPermissionPage</servlet-name>
    	<url-pattern>/webui/cnsuser/addpermission/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CQSUserPageServlet</servlet-name>
    	<servlet-class>com.comcast.cqs.controller.CQSUserPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CQSUserPageServlet</servlet-name>
    	<url-pattern>/webui/cqsuser/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>UserLoginPageServlet</servlet-name>
    	<servlet-class>com.comcast.cmb.common.controller.UserLoginPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>UserLoginPageServlet</servlet-name>
    	<url-pattern>/webui/userlogin/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>UserPageServlet</servlet-name>
    	<servlet-class>com.comcast.cmb.common.controller.UserPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>UserPageServlet</servlet-name>
    	<url-pattern>/webui/user/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSSubscriptionPageServlet</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSSubscriptionPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSSubscriptionPageServlet</servlet-name>
    	<url-pattern>/webui/cnsuser/subscription/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CNSPublishToTopicPageServlet</servlet-name>
    	<servlet-class>com.comcast.cns.controller.CNSPublishToTopicPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CNSPublishToTopicPageServlet</servlet-name>
    	<url-pattern>/webui/cnsuser/publish/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CQSQueueMessagesPageServlet</servlet-name>
    	<servlet-class>com.comcast.cqs.controller.CQSQueueMessagesPageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CQSQueueMessagesPageServlet</servlet-name>
    	<url-pattern>/webui/cqsuser/message/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CQSAddQueuePermissionPage</servlet-name>
    	<servlet-class>com.comcast.cqs.controller.CQSAddQueuePermissionPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CQSAddQueuePermissionPage</servlet-name>
    	<url-pattern>/webui/cqsuser/addpermission/*</url-pattern>
    </servlet-mapping>

    <servlet>
    	<servlet-name>CQSQueuePermissionsPage</servlet-name>
    	<servlet-class>com.comcast.cqs.controller.CQSQueuePermissionsPage</servlet-class>
    </servlet>
    <servlet-mapping>
    	<servlet-name>CQSQueuePermissionsPage</servlet-name>
    	<url-pattern>/webui/cqsuser/permissions/*</url-pattern>
    </servlet-mapping>

	<servlet>
		<servlet-name>CQSAPIStatePageServlet</servlet-name>
		<servlet-class>com.comcast.cqs.controller.CQSAPIStatePageServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CQSAPIStatePageServlet</servlet-name>
		<url-pattern>/webui/cqsapistate/*</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>CNSWorkerStatePageServlet</servlet-name>
		<servlet-class>com.comcast.cns.controller.CNSWorkerStatePageServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CNSWorkerStatePageServlet</servlet-name>
		<url-pattern>/webui/cnsworkerstate/*</url-pattern>
	</servlet-mapping>

	<servlet>
    	<servlet-name>CQSEditQueueAttributePage</servlet-name>
    	<servlet-class>com.comcast.cqs.controller.CQSEditQueueAttributePage</servlet-class>
  	</servlet>
  	<servlet-mapping>
    	<servlet-name>CQSEditQueueAttributePage</servlet-name>
    	<url-pattern>/webui/cqsuser/editqueueattributes/*</url-pattern>
  	</servlet-mapping>

	<servlet>
		<servlet-name>CMBStatsServlet</servlet-name>
		<servlet-class>com.comcast.cmb.common.controller.CMBStatsServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CMBStatsServlet</servlet-name>
		<url-pattern>/webui/cmbcallstats/*</url-pattern>
	</servlet-mapping>

	<servlet>
		<servlet-name>CMBVisualizerServlet</servlet-name>
		<servlet-class>com.comcast.cmb.common.controller.CMBVisualizerServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>CMBVisualizerServlet</servlet-name>
		<url-pattern>/webui/cmbvisualizer/*</url-pattern>
	</servlet-mapping>

</web-app>


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

<title>Uses of Package jade.mtp (JADE 4.3.1 API Reference)</title>
<meta name="date" content="2013-12-04">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
jade.mtp

Packages that use jade.mtp

Package
Description

jade.core

This package contains the microkernel of JADE
system.

jade.mtp

jade.util

This package contains utility classes and in particular:

classes for handling properties in an extended way (see the Tutorial),
the Logger class for logging capabilities;
the leap subpackage, that is a replacement for
the Java collection framework that is not supported by J2ME.

jade.wrapper

Together with the classes jade.core.Profile and jade.core.Runtime
this package provides support for the JADE in-process interface
that allows external Java applications to use JADE as a kind of library and
to launch the JADE Runtime from within the application itself.

Classes in jade.mtp used by jade.core

Class and Description

MTPDescriptor

MTPException

Generic exception class for MTP errors.

TransportAddress

Classes in jade.mtp used by jade.mtp

Class and Description

InChannel

This interface is the receiver's view of an MTP.

InChannel.Dispatcher

Callback interface to be notified of message arrivals over this
     Message Transport Protocol.

MTPException

Generic exception class for MTP errors.

OutChannel

This interface is the sender's view of an MTP.

TransportAddress

Classes in jade.mtp used by jade.util

Class and Description

TransportAddress

Classes in jade.mtp used by jade.wrapper

Class and Description

MTPDescriptor

MTPException

Generic exception class for MTP errors.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
module FullTextSearch
  class UpsertTargetJob < ActiveJob::Base
    queue_as :full_text_search
    queue_with_priority 15

    discard_on ActiveRecord::RecordNotFound

    def perform(mapper_class_name, source_id)
      mapper_class = mapper_class_name.constantize
      source = mapper_class.redmine_class.find(source_id)
      mapper = mapper_class.redmine_mapper(source)
      mapper.upsert_fts_target
    end
  end
end


text:
class CreateApis < ActiveRecord::Migration
  def change
    create_table :apis do |t|
      t.string :title
      t.text :description
      t.string :tips
      t.float :average_score
      t.text :logo_url
      t.string :key_required
      t.string :documentation
      t.string :endpoint_url
      t.string :dev_homepage
      t.text :sample_call
      t.text :sample_response
      t.string :dev_twitter_url
      t.string :category
      t.string :terms_of_service
      t.string :usage_limits
      t.timestamps
    end
  end
end


text:
namespace breakpad {
class CrashDumpManager;
}
#endif

namespace base {
class Thread;
}

namespace devtools_http_handler {
class DevToolsHttpHandler;
}

namespace net {
class NetLog;
}

namespace content {

class ShellBrowserMainParts : public BrowserMainParts {
 public:
  explicit ShellBrowserMainParts(const MainFunctionParams& parameters);
  ~ShellBrowserMainParts() override;

  // BrowserMainParts overrides.
  void PreEarlyInitialization() override;
  void PreMainMessageLoopStart() override;
  void PostMainMessageLoopStart() override;
  void PreMainMessageLoopRun() override;
  bool MainMessageLoopRun(int* result_code) override;
  void PostMainMessageLoopRun() override;
  void PostDestroyThreads() override;

  devtools_http_handler::DevToolsHttpHandler* devtools_http_handler() {
    return devtools_http_handler_.get();
  }

  ShellBrowserContext* browser_context() { return browser_context_.get(); }
  ShellBrowserContext* off_the_record_browser_context() {
    return off_the_record_browser_context_.get();
  }

  net::NetLog* net_log() { return net_log_.get(); }

 protected:
  virtual void InitializeBrowserContexts();
  virtual void InitializeMessageLoopContext();

  void set_browser_context(ShellBrowserContext* context) {
    browser_context_.reset(context);
  }
  void set_off_the_record_browser_context(ShellBrowserContext* context) {
    off_the_record_browser_context_.reset(context);
  }

 private:
#if defined(OS_ANDROID)
  scoped_ptr<breakpad::CrashDumpManager> crash_dump_manager_;
#endif
  scoped_ptr<net::NetLog> net_log_;
  scoped_ptr<ShellBrowserContext> browser_context_;
  scoped_ptr<ShellBrowserContext> off_the_record_browser_context_;

  // For running content_browsertests.
  const MainFunctionParams parameters_;
  bool run_message_loop_;

  scoped_ptr<devtools_http_handler::DevToolsHttpHandler> devtools_http_handler_;

  DISALLOW_COPY_AND_ASSIGN(ShellBrowserMainParts);
};

}  // namespace content

#endif  // CONTENT_SHELL_BROWSER_SHELL_BROWSER_MAIN_PARTS_H_


text:
// ==========================================================================
// Project:   SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
//            Portions ©2008-2011 Apple Inc. All rights reserved.
// License:   Licensed under MIT license (see license.js)
// ==========================================================================

SC.mixin(Function.prototype, /** @scope Function.prototype */ {

  /**
    Creates a timer that will execute the function after a specified
    period of time.

    If you pass an optional set of arguments, the arguments will be passed
    to the function as well.  Otherwise the function should have the
    signature:

        function functionName(timer)

    @param target {Object} optional target object to use as this
    @param interval {Number} the time to wait, in msec
    @returns {SC.Timer} scheduled timer
  */
  invokeLater: function(target, interval) {
    if (interval === undefined) interval = 1 ;
    var f = this;
    if (arguments.length > 2) {
      var args = SC.$A(arguments).slice(2,arguments.length);
      args.unshift(target);
      // f = f.bind.apply(f, args) ;
      var func = f ;
      // Use "this" in inner func because it get its scope by
      // outer func f (=target). Could replace "this" with target for clarity.
      f = function() { return func.apply(this, args.slice(1)); } ;
    }
    return SC.Timer.schedule({ target: target, action: f, interval: interval });
  }

});


text:
RayPump-Addon
=============

Blender script that communicates with Online Cycles Accelerator for Blender (RayPump.com)


text:
#include "highlyreliablemarkers.h"
#include <iostream>
#include <time.h>
#include <opencv2/highgui/highgui.hpp>

typedef std::vector<bool> Word;

class WordsLikeHood : public std::vector<double>
{
  std::vector<Word> words;
  std::vector<unsigned int> chosen;
  double totalPosibilities; //(2^n)^n - (2^n - 1)^n

public:
  WordsLikeHood(unsigned int wordSize);
  Word sampleWord();
  void incrementWord(Word w);
  void decrementWord(Word w);
  void update();

  static unsigned int wordToNumber(Word w);
  static unsigned int wordTransitions(Word w);
  static Word wordFromNumber(unsigned int n, unsigned int bits);

};

using namespace std;

int main(int argc,char **argv)
{
   if(argc < 4) {
     cerr<<"Invalid number of arguments"<<endl;
     cerr << "Usage: outputfile.yml dictSize n \n \
      outputfile.yml: output file for the dictionary \n \
      dictSize: number of markers to add to the dictionary \n \
      n: marker size." << endl;
     exit(-1);
   }

    aruco::Dictionary D;
    unsigned int dictSize = atoi(argv[2]);
    unsigned int n = atoi(argv[3]);

    unsigned int tau = 2*( ( 4*( (n*n)/4 ) )/3 );
    cout << "Tau: " << tau << endl;

    WordsLikeHood P(n);

    vector<Word> wordsInM;
    wordsInM.resize(n);

    unsigned int countUnproductive=0;
    while(D.size() < dictSize) {
      aruco::MarkerCode candidate( n );
      for(unsigned int i=0; i<n; i++) {
	P.update();
	wordsInM[i] = P.sampleWord();
    for(unsigned int j=0; j<n; j++) candidate.set(i*n+j, wordsInM[i][j]);
	P.incrementWord(wordsInM[i]);
      }
//        for(unsigned int i=0; i<candidate.size(); i++) cout << candidate.get(i);
//        cout << endl;
      if( D.distance(candidate)>=tau && candidate.selfDistance()>=tau) {
	D.push_back(candidate);
	cout << "Accepted Marker " << D.size() << "/" << dictSize << endl;
	cv::imshow("Marker", candidate.getImg(200) );
	countUnproductive=0;
      }
      else { // decrease words previously increased because they are not accepted!
    for(unsigned int i=0; i<n; i++) P.decrementWord(wordsInM[i]);
	countUnproductive++;
      }
      if(countUnproductive==5000) {
	tau--;
	countUnproductive=0;
	cout << "Reducing Tau to: " << tau << endl;
	if(tau==0) {
	  std::cerr << "Error: Tau=0. Small marker size for too high number of markers. Stop" << std::endl;
	  break;
	}
      }
      char key = cv::waitKey(10);
      if(key==27) break;
      if(key=='r') {
	tau--;
	cout << "Reducing Tau to: " << tau << endl;
      }
    }

  D.toFile(argv[1]);

}

WordsLikeHood::WordsLikeHood(unsigned int wordSize)
{
  resize( pow(float(2), float(wordSize)) );
  words.resize( size() );
  chosen.resize( size() );
  for(unsigned int i=0; i<size(); i++) {
    words[i] = WordsLikeHood::wordFromNumber(i, wordSize);
    chosen[i] = 0;
  }
  srand(time(NULL));
//   totalPosibilities = pow(2, wordSize*wordSize) - pow( pow(2,wordSize)-1.0 , wordSize); //(2^n)^n - (2^n - 1)^n
  totalPosibilities = 1;
  update();
}

void WordsLikeHood::incrementWord(Word w)
{
  assert( words.size()>0 && w.size()==words[0].size() );
  unsigned int id = WordsLikeHood::wordToNumber(w);
  chosen[id]++;
  totalPosibilities++;
}

void WordsLikeHood::decrementWord(Word w)
{
  assert( words.size()>0 && w.size()==words[0].size() );
  unsigned int id = WordsLikeHood::wordToNumber(w);
  if(chosen[id]!=0) chosen[id]--;
  totalPosibilities--;
}

void WordsLikeHood::update()
{
  for(unsigned int i=0; i<size(); i++) {
    (*this)[i] = ( 1.- ((double)chosen[i])/(double)totalPosibilities  ) * ((double)WordsLikeHood::wordTransitions(words[i])+1)/(double)(words[0].size());
  }

  double total = 0.0;
  for(unsigned int i=0; i<size(); i++) total+=(*this)[i];

  for(unsigned int i=0; i<size(); i++) {
    (*this)[i] /= total;
  }

}

Word WordsLikeHood::sampleWord()
{
  int randInt = rand();
  double randDouble = (double)randInt/(double)RAND_MAX;
  double acc = 0;
  for(unsigned int i=0; i<size(); i++) {
    acc += (*this)[i];
    if(acc >= randDouble) return words[i];
  }
  return Word();
}

unsigned int WordsLikeHood::wordToNumber(Word w)
{
  unsigned int id=0;
  unsigned int uintSize = sizeof(unsigned int)*8;
  for(unsigned int i=0; i<w.size() && i<uintSize; i++) {
    id += pow(float(2),float(i))*w[i];
  }
  return id;
}

unsigned int WordsLikeHood::wordTransitions(Word w)
{
    unsigned int count = 0;
    for(unsigned int i=0; i<w.size()-1; i++) {
      if(w[i]!=w[i+1]) count ++;
    }
    return count;
}

Word WordsLikeHood::wordFromNumber(unsigned int n, unsigned int bits)
{
    if(pow(float(2),float(bits)) < n ) {
      std::cerr << "Not enough number of bits to codify id " << n << std::endl;
    }

    Word res;
    res.resize(bits);
    for(unsigned int i=0; i<bits; i++) {
      if(n & (unsigned int)pow(float(2),float(i))) res[i] = 1;
      else res[i] = 0;
    }

    return res;
}


text:
// This test concerns the identity of dependent types within the
// canonical type system. This corresponds to C++ [temp.type], which
// specifies type equivalence within a template.
//
// FIXME: template template parameters

namespace N {
  template<typename T>
  struct X2 {
    template<typename U>
    struct apply {
      typedef U* type;
    };
  };
}

namespace Nalias = N;

template<typename T>
struct X0 { };

using namespace N;

template<typename T, typename U>
struct X1 {
  typedef T type;
  typedef U U_type;

  void f0(T); // expected-note{{previous}}
  void f0(U);
  void f0(type); // expected-error{{redeclar}}

  void f1(T*); // expected-note{{previous}}
  void f1(U*);
  void f1(type*); // expected-error{{redeclar}}

  void f2(X0<T>*); // expected-note{{previous}}
  void f2(X0<U>*);
  void f2(X0<type>*); // expected-error{{redeclar}}

  void f3(X0<T>*); // expected-note{{previous}}
  void f3(X0<U>*);
  void f3(::X0<type>*); // expected-error{{redeclar}}

  void f4(typename T::template apply<U>*); // expected-note{{previous}}
  void f4(typename U::template apply<U>*);
  void f4(typename type::template apply<T>*);
  void f4(typename type::template apply<U_type>*); // expected-error{{redeclar}}

  void f5(typename T::template apply<U>::type*); // expected-note{{previous}}
  void f5(typename U::template apply<U>::type*);
  void f5(typename U::template apply<T>::type*);
  void f5(typename type::template apply<T>::type*);
  void f5(typename type::template apply<U_type>::type*); // expected-error{{redeclar}}

  void f6(typename N::X2<T>::template apply<U> *); // expected-note{{previous}}
  void f6(typename N::X2<U>::template apply<U> *);
  void f6(typename N::X2<U>::template apply<T> *);
  void f6(typename ::N::X2<type>::template apply<U_type> *); // expected-error{{redeclar}}

  void f7(typename N::X2<T>::template apply<U> *); // expected-note{{previous}}
  void f7(typename N::X2<U>::template apply<U> *);
  void f7(typename N::X2<U>::template apply<T> *);
  void f7(typename X2<type>::template apply<U_type> *); // expected-error{{redeclar}}

  void f8(typename N::X2<T>::template apply<U> *); // expected-note{{previous}}
  void f8(typename N::X2<U>::template apply<U> *);
  void f8(typename N::X2<U>::template apply<T> *);
  void f8(typename ::Nalias::X2<type>::template apply<U_type> *); // expected-error{{redeclar}}
};

namespace PR6851 {
  template <bool v>
  struct S;

  struct N {
    template <bool w>
    S< S<w>::cond && 1 > foo();
  };

  struct Alien;
  bool operator&&(const Alien&, const Alien&);

  template <bool w>
  S< S<w>::cond && 1 > N::foo() { }
}

namespace PR7460 {
  template <typename T>
  struct TemplateClass2
  {
    enum { SIZE = 100 };
    static T member[SIZE];
  };

  template <typename T>
  T TemplateClass2<T>::member[TemplateClass2<T>::SIZE];
}


text:
var asset = {};

(function (asset) {
    asset.process = function (type, path, destination, elem) {
        if (!store.user) {
            $('#modal-login').modal('show');
            return;
        }
        $(elem).find("i").removeClass().addClass('fa fa-spinner fa-spin');
        $(elem).find('#main-bookmark').html(" Adding...");
        $(elem).unbind('click');
        $.ajax({
            url: caramel.url('/apis/subscriptions'),
            data: {type: type, asset: path, destination: encodeURIComponent(location.href)},
            method: 'POST',
            success: function (data) {
                messages.alertSuccess("Successfully subscribed to asset");
                $('i', elem).removeClass().addClass('fw fw-bookmark store-bookmarked');
                if ($(elem).find('#main-bookmark').length > 0) {
                    $(elem).find("i").removeClass().addClass('fa fa-star');
                    $(elem).find('#main-bookmark').html("Bookmarked");
                    $(elem).attr('id', 'btn-remove-subscribe');
                }
            },
            error: function () {
                messages.alertError("Failed to bookmark this asset!");
                $('i', elem).removeClass().addClass('fw fw-bookmark store-bookmark');
            }
        });
        //location.href = caramel.context + '/apis/subscriptions?type=' + type + '&asset=' + path + '&destination=' + encodeURIComponent(location.href);
    };

    asset.unsubscribeBookmark = function (type, path, destination, elem) {
        if (!store.user) {
            $('#modal-login').modal('show');
            return;
        }
        $(elem).find("i").removeClass().addClass('fa fa-spinner fa-spin');
        $(elem).find('#main-bookmark').html(" Removing...");
        $(elem).unbind('click');
        $.ajax({
            url: caramel.url('/apis/subscriptions') + '?type=' + type + '&asset=' + path,
            method: 'DELETE',
            dataType: 'text json',
            success: function (data) {
                messages.alertSuccess("Successfully un-subscribed to asset");
                $('i', elem).removeClass().addClass('fw fw-bookmark store-bookmark');
                if ($(elem).find('#main-bookmark').length > 0) {
                    $(elem).find("i").removeClass().addClass('fw fw-bookmark');
                    $(elem).find('#main-bookmark').html("Bookmark");
                    $(elem).attr('id', 'btn-add-gadget');
                }
            },
            error: function (data) {
                messages.alertError("Failed to un-bookmark this asset!");
                $('i', elem).removeClass().addClass('fw fw-bookmark store-bookmarked');
            }
        });
    };
}(asset));


text:
package gov.nih.nci.caintegrator.web.action.abstractlist;

import gov.nih.nci.caintegrator.application.study.Visibility;
import gov.nih.nci.caintegrator.domain.application.AbstractList;
import gov.nih.nci.caintegrator.domain.application.StudySubscription;
import gov.nih.nci.caintegrator.web.action.AbstractCaIntegrator2Action;

import java.util.Date;

import org.apache.commons.lang3.StringUtils;

/**
 * Provides functionality to list and add array designs.
 */
public abstract class AbstractEditListAction extends AbstractCaIntegrator2Action {
    private static final long serialVersionUID = 1L;
    private static final int LIST_NAME_LENGTH = 100;
    private AbstractList abstractList;
    private String listOldName = "";
    private String listName = "";
    private String selectedAction;
    private boolean creationSuccess = false;
    private boolean editOn = true;
    private boolean visibleToOther = false;;
    private boolean globalList = false;

    static final String EDIT_ACTION = "editList";
    static final String EDIT_GLOBAL_ACTION = "editGlobalList";
    static final String DELETE_ACTION = "deleteList";
    static final String CANCEL_ACTION = "cancel";
    static final String SAVE_ACTION = "saveList";
    static final String LIST_NAME = "listName";
    static final String HOME_PAGE = "homePage";
    static final String EDIT_PAGE = "editPage";
    static final String EDIT_GLOBAL_PAGE = "editGlobalPage";

    /**
     * @return the Struts result.
     */
    @Override
    public String execute() {
        if (EDIT_ACTION.equals(selectedAction)) {
            setGlobalList(false);
            abstractList = getAbstractList(getListName(), isGlobalList());
            setOpenList(listName);
            return editList();
        } else if (EDIT_GLOBAL_ACTION.equals(selectedAction)) {
            setGlobalList(true);
            abstractList = getAbstractList(getListName(), isGlobalList());
            setOpenGlobalList(listName);
            return editGlobalList();
        } else if (DELETE_ACTION.equals(selectedAction)) {
            clearAnalysisCache();
            return deleteList();
        } else if (SAVE_ACTION.equals(selectedAction)) {
            clearAnalysisCache();
            return saveList();
        } else if (CANCEL_ACTION.equals(selectedAction)) {
            clearAnalysisCache();
            return HOME_PAGE;
        }
        return SUCCESS;
    }

    abstract AbstractList getAbstractList(String name, boolean isGlobal);
    abstract void setOpenList(String name);
    abstract void setOpenGlobalList(String name);

    /**
     * Go to the edit page.
     * @return the Struts result.
     */
    public String editList() {
        setListOldName(getListName());
        setVisibleToOther(Visibility.GLOBAL.equals(getAbstractList().getVisibility()));
        return SUCCESS;
    }

    /**
     * Go to the edit page.
     * @return the Struts result.
     */
    public String editGlobalList() {
        setListOldName(getListName());
        setVisibleToOther(Visibility.GLOBAL.equals(getAbstractList().getVisibility()));
        return SUCCESS;
    }

    /**
     * Rename the subject list.
     * @return the Struts result.
     */
    public String saveList() {
        abstractList = getAbstractList(listOldName, isGlobalList());
        if (abstractList != null) {
            abstractList.setName(listName);
            abstractList.setVisibility(isVisibleToOther() ? Visibility.GLOBAL : null);
            abstractList.setLastModifiedDate(new Date());
            saveAbstractList();
            listOldName = listName;
            return isVisibleToOther() ? EDIT_GLOBAL_PAGE : EDIT_PAGE;
        } else {
            listNoLongerAvailable();
            return SUCCESS;
        }
    }

    private void saveAbstractList() {
        if (isVisibleToOther() == isGlobalList()) {
            getWorkspaceService().saveUserWorkspace(getWorkspace());
        } else if (isVisibleToOther()) {
            abstractList.setStudyConfiguration(getSubscription().getStudy().getStudyConfiguration());
            getWorkspaceService().makeListGlobal(abstractList);
        } else {
            abstractList.setSubscription(getSubscription());
            getWorkspaceService().makeListPrivate(abstractList);
        }

    }

    /**
     * Delete the subject list.
     * @return the Struts result.
     */
    public String deleteList() {
        abstractList = getAbstractList(listName, isGlobalList());
        if (abstractList != null) {
            getWorkspaceService().deleteAbstractList(getSubscription(), abstractList);
            return HOME_PAGE;
        } else {
            listNoLongerAvailable();
            return SUCCESS;
        }
    }

    private void listNoLongerAvailable() {
        addActionError(getText("struts.messages.error.list.unavailable", getArgs(listOldName)));
        editOn = false;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void validate() {
        clearErrorsAndMessages();
        if (creationSuccess) {
            addActionMessage(getCreationSuccessfulMessage());
        }
        if (EDIT_ACTION.equals(selectedAction)) {
            setGlobalList(false);
            validateList(isGlobalList());
        } else if (EDIT_GLOBAL_ACTION.equals(selectedAction)) {
            validateEditGlobalAction();
        } else if (SAVE_ACTION.equalsIgnoreCase(selectedAction)) {
            validateListName();
        }
    }

    private void validateEditGlobalAction() {
        if (!isStudyManager()) {
            setInvalidDataBeingAccessed(true);
        } else {
            setGlobalList(true);
            validateList(isGlobalList());
        }
    }

    /**
     * Creation message (overridden by subclasses).
     * @return message.
     */
    protected String getCreationSuccessfulMessage() {
        return getText("struts.messages.list.successfully.created");
    }

    private void validateList(boolean isGlobal) {
        abstractList = getAbstractList(getListName(), isGlobal);
        if (abstractList == null) {
            addActionError(getText("struts.messages.error.list.unavailable", getArgs(getListName())));
            editOn = false;
        }
    }

    private void validateListName() {
        if (StringUtils.isEmpty(getListName())) {
            addFieldError(LIST_NAME, getText("struts.messages.error.name.required", getArgs("List")));
        } else if (StringUtils.length(getListName()) > LIST_NAME_LENGTH) {
            addFieldError(LIST_NAME, getText("struts.message.error.list.name.length"));
        } else if ((!listOldName.equals(listName) && getAbstractList(listName, isVisibleToOther()) != null)
                || (isVisibleToOther() != isGlobalList() && getAbstractList(listName, isVisibleToOther()) != null)) {
            addFieldError(LIST_NAME, getText("struts.messages.error.duplicate.name", getArgs("List", getListName())));
            abstractList = getAbstractList(listOldName, isGlobalList());
            setListName(listOldName);
        }
    }

    /**
     * @return the selectedAction
     */
    public String getSelectedAction() {
        return selectedAction;
    }

    /**
     * @param selectedAction the selectedAction to set
     */
    public void setSelectedAction(String selectedAction) {
        this.selectedAction = selectedAction;
    }

    /**
     * @return the listName
     */
    public String getListName() {
        return listName;
    }

    /**
     * @param listName the listName to set
     */
    public void setListName(String listName) {
        this.listName = listName;
    }

    /**
     * @return the study subscription
     */
    public StudySubscription getSubscription() {
        return getStudySubscription();
    }

    /**
     * @return the listOldName
     */
    public String getListOldName() {
        return listOldName;
    }

    /**
     * @param listOldName the listOldName to set
     */
    public void setListOldName(String listOldName) {
        this.listOldName = listOldName;
    }

    /**
     * @return the editOn
     */
    public boolean isEditOn() {
        return editOn;
    }

    /**
     * @return the visibleToOther
     */
    public boolean isVisibleToOther() {
        return visibleToOther;
    }

    /**
     * @param visibleToOther the visibleToOther to set
     */
    public void setVisibleToOther(boolean visibleToOther) {
        this.visibleToOther = visibleToOther;
    }

    /**
     * @return the globalList
     */
    public boolean isGlobalList() {
        return globalList;
    }

    /**
     * @param globalList the globalList to set
     */
    public void setGlobalList(boolean globalList) {
        this.globalList = globalList;
    }

    /**
     * @return the abstractList
     */
    public AbstractList getAbstractList() {
        return abstractList;
    }

    /**
     * @return the creationSuccess
     */
    public boolean isCreationSuccess() {
        return creationSuccess;
    }

    /**
     * @param creationSuccess the creationSuccess to set
     */
    public void setCreationSuccess(boolean creationSuccess) {
        this.creationSuccess = creationSuccess;
    }
}


text:
import Deal from 'scripts'
import {
  GET_FAVOURITES_ESTATES
} from './const'

export function getFavouritesEstates (id = '') {
  return (dispatch) => {

    return Deal.Favourites.get(id).then((json) => {
      dispatch({
        payload: json,
        type: GET_FAVOURITES_ESTATES
      })
    }).catch((error) => {
      //@TODO log in error log file
    })
  }
}


text:
const char kConfFileEnvVariable[] = "BOCHSPWN_CONF";
const uint8_t kHeapTaintByte = 0xaa;
const uint8_t kStackTaintByte = 0xbb;
const unsigned int kTaintHelperAllocSize = 16 * 4096;

#define __GFP_ZERO 0x8000

// Types of breakpoints set in the Linux kernel.
#define BP_KMALLOC_PROLOGUE      0
#define BP_VMALLOC_PROLOGUE      1
#define BP_ALLOC_EPILOGUE        2
#define BP_ALLOC_FREE            3
#define BP_CACHE_CREATE_PROLOGUE 4
#define BP_CACHE_CREATE_EPILOGUE 5
#define BP_CACHE_DESTROY         6
#define BP_CACHE_ALLOC_PROLOGUE  7
#define BP_CACHE_FREE            8
#define BP_CACHE_CONSTRUCTOR     9
#define BP_BLACKLISTED           10

// ------------------------------------------------------------------
// Internal enumerations and structures.
// ------------------------------------------------------------------

// Generic settings read from .ini configuration file.
struct bochspwn_config {
  // Path to output log file.
  char *log_path;

  // Handle to output file.
  FILE *file_handle;

  // Guest operating system version, used as the name for system-specific
  // .ini configuration section.
  char *os_version;

  // Maximum number of stack frames stored in a single memory access
  // descriptor.
  uint32_t callstack_length;

  // Indicates if heap allocations should be tainted.
  uint32_t taint_heap;

  // Indicates if stack "allocations" made by executing SUB ESP, imm32 and
  // similar instructions should be tainted.
  uint32_t taint_stack;

  // Indicates if the stack/heap allocation origins should be saved (which
  // takes additional 8GB of memory and some CPU overhead).
  uint32_t track_origins;

  // Indicates if callstack-based uniquization should take place.
  uint32_t uniquize;

  // Indicates if an interrupt should be generated within the guest OS if
  // an error is encountered.
  uint32_t break_on_bug;

  // Indicates if only kernel--->user memory disclosures should be reported in
  // the log files, or all accesses to uninitialized memory.
  uint32_t only_kernel_to_user;

  // Indicates if dumping shadow memory state to files is enabled.
  uint32_t dump_shadow_to_files;

  // Indicates the interval between subsequent shadow memory dumps, in seconds.
  uint32_t dump_shadow_interval;

  // Path of the directory where shadow memory dumps are saved.
  char *dump_shadow_path;

  // Initialize fields with typical values for safety.
  bochspwn_config() : log_path(strdup("memlog.txt")), file_handle(NULL),
                      os_version(strdup("ubuntu_16.10_x86")), taint_heap(1),
                      taint_stack(0), track_origins(0), uniquize(0),
                      break_on_bug(0), only_kernel_to_user(0),
                      dump_shadow_to_files(0), dump_shadow_path(NULL)  { }

  ~bochspwn_config() {
    if (log_path != NULL) {
      free(log_path);
    }

    if (os_version != NULL) {
      free(os_version);
    }

    if (file_handle != NULL) {
      fclose(file_handle);
    }
  }
};

// Included here to mitigate the header hell.
#include "bochs.h"
#include "cpu/cpu.h"
#include "mem_interface.h"

// Stack-trace descriptor, contains a full list of absolute virtual
// function call addresses.
struct stack_trace {
  std::vector<uint64_t> trace;

  bool operator< (const stack_trace& a) const {
    return (trace < a.trace);
  }
  bool operator != (const stack_trace& a) const {
    return (trace != a.trace);
  }
};

// Information about a known kernel module currently loaded in the
// operating system.
struct module_info {
  uint64_t module_base;
  uint64_t module_size;
  char *module_name;

  module_info() : module_base(0), module_size(0), module_name(NULL) {}
  module_info(bx_address b, bx_address s, const char *n) :
    module_base(b), module_size(s), module_name(strdup(n)) {}
  ~module_info() { if (module_name) free(module_name); }
};

// ------------------------------------------------------------------
// Global helper functions.
// ------------------------------------------------------------------

// Identifies loaded module based on a virtual address.
module_info* find_module(bx_address item);

// Formats string as a hex binary blob.
std::string format_hex(const std::string& data);

// Translates memory access type enum into textual representation.
const char *translate_mem_access(bug_report_t::mem_access_type type);

// Generates an interrupt exception in the guest operating system.
void invoke_guest_int3(BX_CPU_C *pcpu);

// ------------------------------------------------------------------
// Global helper macros.
// ------------------------------------------------------------------
#define READ_INI_STRING(file, section, name, buf, size) \
  if (!GetPrivateProfileStringA((section), (name), NULL, (buf), (size), (file))) {\
    fprintf(stderr, "Unable to read the %s/%s string from configuration file.\n", \
            (section), (name));\
    return false;\
  }

#define READ_INI_INT(file, section, name, buf, size, dest) \
  READ_INI_STRING((file), (section), (name), (buf), (size));\
  dest = strtoul(buf, NULL, 0);

// ------------------------------------------------------------------
// Global objects.
// ------------------------------------------------------------------
namespace globals {

// Generic configuration.
extern bochspwn_config config;

// Global information about all currently known kernel modules. Updated
// lazily, only when an unknown driver is encountered.
extern std::vector<module_info *> modules;

// If known_callstack_item.find(address) != .end(), it means that the address
// has been already encountered as a part of a stack trace.
extern std::unordered_set<bx_address> known_callstack_item;

// Large helper allocations filled with the heap/stack taint bytes (both of size
// kTaintHelperAllocSize).
extern uint8_t *heap_taint_alloc;
extern uint8_t *stack_taint_alloc;

// An instruction-scope marker (set by before_execution, unset by
// after_execution) indicating if the current instruction (handled by
// lin_access) is a member of the REP MOVSx family, in which case it is
// handled in a special way.
extern bool rep_movs;

// An instruction-scope marker similar to rep_movs indicating if the
// current instruction is one of the esp-modifying ones.
extern bool esp_change;

// If Esp is being modified by the current instruction, this variable
// stores its original value from before its execution.
extern uint32_t esp_value;

// Indicates if the strict-checking mode is enabled for a given stack pointer
// value, meaning that all memory references at that ESP are checked for
// uninitialized memory, not just copying to user-mode. This is triggered by the
// LFENCE instruction and disabled by SFENCE, which surround the operand-reading
// part of the put_user() macro.
extern std::unordered_set<uint32_t> strict_checking;

// Saved information about currently active kmem caches.
struct kmem_cache {
  uint32_t size;
  uint32_t constructor;
};
extern std::unordered_map<uint32_t, kmem_cache> kmem_caches;
extern std::unordered_map<uint32_t, uint32_t> kmem_cache_constructor_to_size;

// The specifics of requested cache creations per stack pointer, as captured by
// the cache creator prologue hook.
extern std::unordered_map<uint32_t, kmem_cache> per_site_cache_reqs;

// The specifics (length, flags, cache) of requested heap allocations per stack
// pointer, as captured by the allocator prologue hook.
struct alloc_request {
  uint32_t cache;
  uint32_t length;
  uint32_t flags;
};
extern std::unordered_map<uint32_t, alloc_request> per_site_alloc_reqs;

// Stores information on whether a custom breakpoint was installed by the
// instrumentation (in order to break into kernel debugger), and the location
// that was modified in order to insert it.
extern bool bp_active;
extern uint32_t bp_address;
extern uint8_t bp_orig_byte;

}  // namespace globals

#endif  // BOCHSPWN_COMMON_H_


text:
<?php

namespace WNC\SoldierBundle\Admin;

use Sonata\UserBundle\Admin\Model\UserAdmin as Admin;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Show\ShowMapper;

use FOS\UserBundle\Model\UserManagerInterface;

class UserAdmin extends Admin
{

//    /**
//     * {@inheritdoc}
//     */
//    protected function configureListFields(ListMapper $listMapper)
//    {
//        $listMapper
//            ->addIdentifier('username')
//            ->addIdentifier('firstname')
//            ->addIdentifier('lastname')
//            ->add('email')
//            ->add('createdAt')
//        ;
//
//    }
//
//    /**
//     * {@inheritdoc}
//     */
//    protected function configureDatagridFilters(DatagridMapper $filterMapper)
//    {
//        $filterMapper
//            ->add('id')
//            ->add('username')
//            ->add('email')
//        ;
//    }
//
//    /**
//     * {@inheritdoc}
//     */
//    protected function configureShowFields(ShowMapper $showMapper)
//    {
//        $showMapper
//            ->with('General')
//                ->add('email')
//            ->end()
//            ->with('Profile')
//                ->add('firstname')
//                ->add('lastname')
//            ->end()
//        ;
//    }
//
//    /**
//     * {@inheritdoc}
//     */
//    protected function configureFormFields(FormMapper $formMapper)
//    {
//        $formMapper
//            ->with('General')
//                ->add('email')
//            ->end()
//            ->with('Profile')
//                ->add('firstname', null, array('required' => false))
//                ->add('lastname', null, array('required' => false))
//            ->end()
//        ;
//
//
//
//    }

}


text:
namespace CGFF {

	class Group : public Renderable2D
	{
	public:
		Group(const QMatrix4x4& matrix);
        virtual~Group();
		void submit(QSharedPointer<Renderer2D> renderer) override;
		void add(QSharedPointer<Renderable2D> renderable);

	private:
		QVector<QSharedPointer<Renderable2D>> m_renderables;
		QMatrix4x4 m_transformationMatrix;
	};

}

#endif


text:
class ZTreeError(Exception):
    pass

class ContextPathError(ZTreeError):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class ConstraintError(ZTreeError):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class QuantifierError(ConstraintError):
    def __init__(self, value):
        self.value = value

class SlugNotUniqueError(ZTreeError):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)

class TreeFilterError(ZTreeError):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return repr(self.value)


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Tag extends QA_Publics
{
	function index($str = NULL, $ajax = NULL)
	{
		if (!empty($str))
		{
			if (!empty($this->_get($str)))
			{
				foreach ($this->_get($str) as $tag)
				{
					if (!empty($ajax)) {
						$data = array(
							'questions' => $this->qa_model->join4_where_ajax('question', 'question_tag', 'tag', 'user', 'category', 'question_tag.question_id=question.id_question', 'question_tag.tag_id=tag.id_tag', 'question.user_id=user.id_user', 'question.category_id=category.id_category', array('tag.tag_name' => uri_decode($str)), 'question.id_question', 5, $ajax),
							);
						if (!empty($data['questions']))
						{
							$this->load->view('questions/questions_ajax', $data);
						}
						else
						{
							show_404();
							return FALSE;
						}
					} else {
						$data = array(
							'tag' => $this->_get($str),
							'questions' => $this->qa_model->join4_where_ajax('question', 'question_tag', 'tag', 'user', 'category', 'question_tag.question_id=question.id_question', 'question_tag.tag_id=tag.id_tag', 'question.user_id=user.id_user', 'question.category_id=category.id_category', array('tag.tag_name' => uri_decode($str)), 'question.id_question', 5, 0),
							);
						if (!empty($data['questions']))
						{
							$this->_render('tag/questions', $data);
						}
						else
						{
							show_404();
							return FALSE;
						}
					}
				}
			}
			else
			{
				show_404();
				return FALSE;
			}
		}
		else
		{
			$data = array(
				'tags' => $this->qa_model->all('tag', 'id_tag DESC'),
				);
			if (!empty($data['tags']))
			{
				$this->_render('tag/list', $data);
			}
			else
			{
				$data = array('messages' => 'Belum ada data Tag yang dapat ditampilkan.');
				$this->_render('independent/messages', $data);
			}
		}
	}

    function _get($str)
    {
        $var = $this->qa_model->get('tag', array('tag_name' => uri_decode($str)));
        return ($var == FALSE)?array():$var;
    }
}


text:
using Refit;

namespace FreeAgent.Model
{
	public class AccessRequest
	{
        [AliasAs("client_id")]
        public string ClientId { get; set; }

        [AliasAs("client_secret")]
        public string ClientSecret { get; set; }

        [AliasAs("grant_type")]
        public AccessRequestType GrantType { get; set; }

        [AliasAs("code")]
        public string Code { get; set; }

        [AliasAs("refresh_token")]
        public string RefreshToken { get; set; }
	}
}


text:
from distutils.core import setup

setup(
    name='glider_binary_data_reader',
    version='1.0',
    author='Michael Lindemuth',
    author_email='mlindemu@usf.edu',
    packages=['glider_binary_data_reader'],
)


text:
CREATE TABLE C_ROOM (
  ID         BIGINT NOT NULL AUTO_INCREMENT,
  ID_GAME    BIGINT,
  ID_COUNTRY BIGINT,
  NAME       VARCHAR(255),
  PRIMARY KEY (ID)
);

ALTER TABLE C_ROOM
ADD INDEX FK_C_ROOM_GAME (ID_GAME),
ADD CONSTRAINT FK_C_ROOM_GAME
FOREIGN KEY (ID_GAME)
REFERENCES GAME (ID);

ALTER TABLE C_ROOM
ADD INDEX FK_C_ROOM_COUNTRY (ID_COUNTRY),
ADD CONSTRAINT FK_C_ROOM_COUNTRY
FOREIGN KEY (ID_COUNTRY)
REFERENCES COUNTRY (ID);

ALTER TABLE C_ROOM
ADD CONSTRAINT UK_C_ROOM
UNIQUE (ID_GAME, NAME);

CREATE TABLE C_PRESENT (
  ID         BIGINT NOT NULL AUTO_INCREMENT,
  ID_C_ROOM  BIGINT,
  ID_COUNTRY BIGINT,
  PRESENT    BIT,
  VISIBLE    BIT,
  PRIMARY KEY (ID)
);

ALTER TABLE C_PRESENT
ADD INDEX FK_C_PRESENT_C_ROOM (ID_C_ROOM),
ADD CONSTRAINT FK_C_PRESENT_C_ROOM
FOREIGN KEY (ID_C_ROOM)
REFERENCES C_ROOM (ID);

ALTER TABLE C_PRESENT
ADD INDEX FK_C_PRESENT_COUNTRY (ID_COUNTRY),
ADD CONSTRAINT FK_C_PRESENT_COUNTRY
FOREIGN KEY (ID_COUNTRY)
REFERENCES COUNTRY (ID);

CREATE TABLE C_MESSAGE (
  ID         BIGINT NOT NULL AUTO_INCREMENT,
  ID_COUNTRY BIGINT,
  MESSAGE    VARCHAR(4096),
  DATE_SENT  TIMESTAMP,
  PRIMARY KEY (ID)
);

ALTER TABLE C_MESSAGE
ADD INDEX FK_C_MESSAGE_COUNTRY (ID_COUNTRY),
ADD CONSTRAINT FK_C_MESSAGE_COUNTRY
FOREIGN KEY (ID_COUNTRY)
REFERENCES COUNTRY (ID);

CREATE TABLE C_CHAT (
  ID           BIGINT NOT NULL AUTO_INCREMENT,
  ID_C_ROOM    BIGINT,
  ID_COUNTRY   BIGINT,
  ID_C_MESSAGE BIGINT,
  DATE_READ TIMESTAMP NULL,
  PRIMARY KEY (ID)
);

ALTER TABLE C_CHAT
ADD INDEX FK_C_CHAT_C_ROOM (ID_C_ROOM),
ADD CONSTRAINT FK_C_CHAT_C_ROOM
FOREIGN KEY (ID_C_ROOM)
REFERENCES C_ROOM (ID);

ALTER TABLE C_CHAT
ADD INDEX FK_C_CHAT_COUNTRY (ID_COUNTRY),
ADD CONSTRAINT FK_C_CHAT_COUNTRY
FOREIGN KEY (ID_COUNTRY)
REFERENCES COUNTRY (ID);

ALTER TABLE C_CHAT
ADD INDEX FK_C_CHAT_C_MESSAGE (ID_C_MESSAGE),
ADD CONSTRAINT FK_C_CHAT_C_MESSAGE
FOREIGN KEY (ID_C_MESSAGE)
REFERENCES C_MESSAGE (ID);

CREATE TABLE C_ROOM_GLOBAL (
  ID      BIGINT NOT NULL AUTO_INCREMENT,
  ID_GAME BIGINT,
  PRIMARY KEY (ID)
);

ALTER TABLE C_ROOM_GLOBAL
ADD INDEX FK_C_ROOM_GLOBAL_GAME (ID_GAME),
ADD CONSTRAINT FK_C_ROOM_GLOBAL_GAME
FOREIGN KEY (ID_GAME)
REFERENCES GAME (ID);

CREATE TABLE C_MESSAGE_GLOBAL (
  ID               BIGINT NOT NULL AUTO_INCREMENT,
  ID_C_ROOM_GLOBAL BIGINT,
  ID_COUNTRY       BIGINT,
  MESSAGE          VARCHAR(4096),
  DATE_SENT        TIMESTAMP,
  PRIMARY KEY (ID)
);

ALTER TABLE C_MESSAGE_GLOBAL
ADD INDEX FK_C_MESSAGE_GLOBAL_C_ROOM_GLOBAL (ID_C_ROOM_GLOBAL),
ADD CONSTRAINT FK_C_MESSAGE_GLOBAL_C_ROOM_GLOBAL
FOREIGN KEY (ID_C_ROOM_GLOBAL)
REFERENCES C_ROOM_GLOBAL (ID);

ALTER TABLE C_MESSAGE_GLOBAL
ADD INDEX FK_C_MESSAGE_GLOBAL_COUNTRY (ID_COUNTRY),
ADD CONSTRAINT FK_C_MESSAGE_GLOBAL_COUNTRY
FOREIGN KEY (ID_COUNTRY)
REFERENCES COUNTRY (ID);


text:
package uk.nhs.hdn.common.digits;

import org.jetbrains.annotations.NotNull;
import uk.nhs.hdn.common.comparison.ComparisonHelper;
import uk.nhs.hdn.common.comparison.ExtendedComparable;
import uk.nhs.hdn.common.serialisers.CouldNotSerialiseValueException;
import uk.nhs.hdn.common.serialisers.CouldNotWriteValueException;
import uk.nhs.hdn.common.serialisers.ValueSerialisable;
import uk.nhs.hdn.common.serialisers.ValueSerialiser;

public enum Digit implements ExtendedComparable<Digit>, ValueSerialisable
{
	Zero(0)
	{
		@SuppressWarnings("RefusedBequest")
		@Override
		public boolean isZeroToOne()
		{
			return true;
		}

		@SuppressWarnings("RefusedBequest")
		@Override
		public boolean isZeroToTwo()
		{
			return true;
		}
	},
	One(1)
	{
		@SuppressWarnings("RefusedBequest")
		@Override
		public boolean isZeroToOne()
		{
			return true;
		}

		@SuppressWarnings("RefusedBequest")
		@Override
		public boolean isZeroToTwo()
		{
			return true;
		}
	},
	Two(2)
	{
		@SuppressWarnings("RefusedBequest")
		@Override
		public boolean isZeroToTwo()
		{
			return true;
		}
	},
	Three(3),
	Four(4),
	Five(5),
	Six(6),
	Seven(7),
	Eight(8),
	Nine(9),
	;

	private static final int Utf16CodeForZero = 48;
	private final char asCharacter;
	private final String asString;

	@SuppressWarnings({"ClassWithoutConstructor", "UtilityClassWithoutPrivateConstructor"})
	private static final class CompilerWorkaround
	{
		private static final Digit[] Index = new Digit[10];
	}

	private final int digit;

	@SuppressWarnings("NumericCastThatLosesPrecision")
	Digit(final int digit)
	{
		this.digit = digit;
		CompilerWorkaround.Index[digit] = this;
		asCharacter = (char) (Utf16CodeForZero + this.digit);
		asString = Integer.toString(this.digit);
	}

	@SuppressWarnings("MethodNamesDifferingOnlyByCase")
	public int digit()
	{
		return digit;
	}

	public char toChar()
	{
		return asCharacter;
	}

	@SuppressWarnings("RefusedBequest")
	@Override
	@NotNull
	public String toString()
	{
		return asString;
	}

	@SuppressWarnings("MethodNamesDifferingOnlyByCase")
	@NotNull
	public static Digit digit(final int zeroBased)
	{
		if (zeroBased < 0 || zeroBased > 9)
		{
			throw new IllegalArgumentException("digit must be between 0 and 9");
		}
		return CompilerWorkaround.Index[zeroBased];
	}

	@SuppressWarnings("MethodNamesDifferingOnlyByCase")
	@NotNull
	public static Digit digit(final long zeroBased)
	{
		//noinspection NumericCastThatLosesPrecision
		return digit((int) zeroBased);
	}

	@NotNull
	public static Digit digitFromUtf16Code(final char utf16Code)
	{
		return digit((int) utf16Code - Utf16CodeForZero);
	}

	@NotNull
	public static Digit digitFromCodepoint(final int unicodeCodePoint)
	{
		return digit(unicodeCodePoint - Utf16CodeForZero);
	}

	public boolean isZeroToOne()
	{
		return true;
	}

	public boolean isZeroToTwo()
	{
		return false;
	}

	@Override
	public boolean isLessThan(@NotNull final Digit right)
	{
		return ComparisonHelper.isLessThan(this, right);
	}

	@Override
	public boolean isEqualTo(@NotNull final Digit right)
	{
		return ComparisonHelper.isEqualTo(this, right);
	}

	@Override
	public boolean isNotEqualTo(@NotNull final Digit right)
	{
		return ComparisonHelper.isNotEqualTo(this, right);
	}

	@Override
	public boolean isGreaterThan(@NotNull final Digit right)
	{
		return ComparisonHelper.isGreaterThan(this, right);
	}

	@Override
	public boolean isLessThanOrEqualTo(@NotNull final Digit right)
	{
		return ComparisonHelper.isLessThanOrEqualTo(this, right);
	}

	@Override
	public boolean isGreaterThanOrEqualTo(@NotNull final Digit right)
	{
		return ComparisonHelper.isGreaterThanOrEqualTo(this, right);
	}

	@Override
	public void serialiseValue(@NotNull final ValueSerialiser valueSerialiser) throws CouldNotSerialiseValueException
	{
		try
		{
			valueSerialiser.writeValue(digit);
		}
		catch (CouldNotWriteValueException e)
		{
			throw new CouldNotSerialiseValueException(this, e);
		}
	}
}


text:
using System.Collections.Generic;
using MoonSharp.Interpreter;
using UniRx;

using FlatBuffers;
using UniRx;
using Zenject;
using System;
using System.Threading;
using Service.Serializer;

namespace Service.MemoryBrowserService
{
    public  abstract class MemoryBrowserServiceBase : DefaultSerializable2,IMemoryBrowserService, IDisposable
    {
        protected DisposableManager _dManager;
        protected Service.Events.IEventsService _eventService;
        protected Service.AsyncManager.IAsyncManager _asyncManager;

        protected CompositeDisposable disposables = new CompositeDisposable();

        protected ReactivePriorityExecutionList rxOnStartup {
            get { return Kernel.Instance.rxStartup; }
        }
        protected ReactivePriorityExecutionList rxOnShutdown {
            get { return Kernel.Instance.rxShutDown; }
        }
        protected bool DeSerializationFinished = false;
        protected Semaphore deSerializationFinishedSempahore;

        protected Service.Scripting.IScriptingService _scriptingService;
        protected Service.Scripting.IScriptingService ScriptingService {
            get {
                if (_scriptingService == null) _scriptingService = Kernel.Instance.Container.Resolve<Service.Scripting.IScriptingService>();
                return _scriptingService;
            }
        }

        [Inject]
        void Initialize(
          [Inject] DisposableManager dManager,
          [Inject] Service.Events.IEventsService eventService,
          [Inject] Service.AsyncManager.IAsyncManager asyncManager
        ) {
            _dManager = dManager;
            _eventService = eventService;
            _asyncManager = asyncManager;

            // register as disposable
            _dManager.Add(this);

            try {
                System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
                watch.Start();
                AfterInitialize();
                watch.Stop();
#if UNITY_EDITOR || DEVELOPMENT_BUILD
                UnityEngine.Debug.LogWarning($"Service MemoryBrowserServiceBase AfterInitialize() took {watch.Elapsed.TotalSeconds}s");
#endif
                Observable.NextFrame().Subscribe(_ => {
                    InitAPI();
                });
            }
            catch (Exception e) {
                UnityEngine.Debug.LogError("Catched exception in AfterInitialize() from service:" + GetType());
                UnityEngine.Debug.LogException(e);
            }
        }

        protected abstract void InitAPI();

        protected void ActivateDefaultScripting(string name) {
            try {
                var scriptService = Kernel.Instance.Resolve<Service.Scripting.IScriptingService>();
                var mainscript = scriptService.GetMainScript();
                mainscript.Globals[name] = this;
            }
            catch (Exception e) {
                UnityEngine.Debug.LogError("Error activating default scripting for Service.MemoryBrowserService with lua-name:" + name);
                UnityEngine.Debug.LogException(e);
            }
        }

        /// <summary>
        /// Publish the specified global event.
        /// </summary>
        /// <param name="evt">Evt.</param>
        protected void Publish(object evt) {
            _eventService.Publish(evt);
        }
        protected void Publish(object evt, Subject<object> eventStream) {
            _eventService.Publish(evt, eventStream);
        }

        /// <summary>
        /// Subscribe to a global event of type TEvent
        /// </summary>
        /// <typeparam name="TEvent">The 1st type parameter.</typeparam>
        protected IObservable<TEvent> OnEvent<TEvent>() {
            return _eventService.OnEvent<TEvent>();
        }
        protected IObservable<TEvent> OnEvent<TEvent>(Subject<object> eventStream) {
            return _eventService.OnEvent<TEvent>(eventStream);
        }

        public void AddDisposable(IDisposable disposable) {
            disposables.Add(disposable);
        }

        // overwrite this method to be called right after eventmanger and dManager got initalized
        protected virtual void AfterInitialize() {

        }

        bool isDisposed = false;

        public virtual void Dispose() {
            //if (isDisposed || Kernel.applicationQuitting) return;
            if (isDisposed) return;
            isDisposed = true;
            disposables.Dispose();

            OnDispose();

            _dManager.Remove(this);
        }

        protected virtual void OnDispose() { }

        public abstract             bool IsSimpleType(object obj);

        public abstract             MemoryBrowser CreateMemoryBrowser(string id,object root);

        public abstract             MemoryBrowser GetBrowser(string id);

        public abstract             ReactiveDictionary<string, MemoryBrowser> rxGetAllBrowsers();

        public virtual int Serialize(FlatBufferBuilder builder) {
            UnityEngine.Debug.LogError("No serializer for MemoryBrowserServiceBase implemented");
            return 0;
        }

        public virtual void Deserialize(object incoming) {
            UnityEngine.Debug.LogError("No deserializer for MemoryBrowserServiceBase implemented");
        }

        public virtual void Deserialize(ByteBuffer buf) {
            throw new NotImplementedException();
        }

    }
}
///////////////////////////////////////////////////////////////////////
//
// WARNING: THIS FILE IS AUTOGENERATED! DO NOT CHANGE IT
//
//////////////////////////////////////////////////////////////////////


text:
<?php
declare(strict_types = 1);

namespace BlockHorizons\BlockPets\listeners;

use BlockHorizons\BlockPets\Loader;
use pocketmine\event\entity\EntityTeleportEvent;
use pocketmine\event\Listener;
use pocketmine\event\player\PlayerQuitEvent;
use pocketmine\event\server\DataPacketReceiveEvent;
use pocketmine\network\mcpe\protocol\InteractPacket;
use pocketmine\network\mcpe\protocol\PlayerAuthInputPacket;
use pocketmine\player\Player;

class RidingListener implements Listener {

	public function __construct(private Loader $loader) {
	}

	/**
	 * Used for getting values of arrows clicked during the riding of a pet, and when dismounted, as well as throwing the rider off the vehicle when leaving.
	 */
	public function ridePet(DataPacketReceiveEvent $event): void {
		$packet = $event->getPacket();
		if($packet instanceof PlayerAuthInputPacket) {
			$loader = $this->getLoader();
			$player = $event->getOrigin()->getPlayer();
			if($loader->isRidingAPet($player)) {
				if(((int)$packet->getMoveVecX()) === 0 && ((int)$packet->getMoveVecZ()) === 0) {
					return;
				}
				$pet = $loader->getRiddenPet($player);
				if($pet->isClosed() || $pet->isFlaggedForDespawn()) {
					return;
				}
				$pet->doRidingMovement($packet->getMoveVecX(), $packet->getMoveVecZ());
			}
		} elseif($packet instanceof InteractPacket) {
			if($packet->action === InteractPacket::ACTION_LEAVE_VEHICLE) {
				$loader = $this->getLoader();
				$player = $event->getOrigin()->getPlayer();
				if($loader->isRidingAPet($player)) {
					$loader->getRiddenPet($player)->throwRiderOff();
				}
			}
		}
	}

	public function getLoader(): Loader {
		return $this->loader;
	}

	/**
	 * Used to dismount the player if it warps, just like it does in vanilla.
	 */
	public function onTeleport(EntityTeleportEvent $event): void {
		$player = $event->getEntity();
		if($player instanceof Player) {
			$loader = $this->getLoader();
			if($loader->isRidingAPet($player)) {
				$loader->getRiddenPet($player)->throwRiderOff();
				foreach($loader->getPetsFrom($player) as $pet) {
					$pet->dismountFromOwner();
				}
			}
		}
	}

	/**
	 * Used to dismount the player from the ridden pet. This does not matter for the player, but could have a significant effect on the pet's behaviour.
	 */
	public function onPlayerQuit(PlayerQuitEvent $event): void {
		$loader = $this->getLoader();
		foreach($loader->getPetsFrom($event->getPlayer()) as $pet) {
			if($pet->isRidden()) {
				$pet->throwRiderOff();
			}
			$pet->close();
		}
	}
}


text:
import itertools
from typing import List, Optional, Tuple

import numpy as np

from .constraints import IConstraint
from .discrete_parameter import InformationSourceParameter
from .parameter import Parameter

class ParameterSpace(object):
    """
    Represents parameter space for a given problem.
    """

    def __init__(self, parameters: List, constraints: Optional[List[IConstraint]] = None):
        """
        Creates a new instance of a parameter space.

        :param parameters: A list of parameters in the space.
        :param constraints: A list of constraints on the input domain
        """
        self._parameters = parameters

        if constraints:
            self.constraints = constraints
        else:
            self.constraints = []

        # Check no more than one InformationSource parameter
        source_parameter = [param for param in self.parameters if isinstance(param, InformationSourceParameter)]
        if len(source_parameter) > 1:
            raise ValueError("More than one source parameter found")

        # Check uniqueness of parameter names
        names = self.parameter_names
        if not len(names) == len(set(names)):
            raise ValueError("Parameter names are not unique")

    def find_parameter_index_in_model(self, parameter_name: str) -> List[int]:
        """
        Find the indices of the encoding of the specified parameter in the input vector

        :param parameter_name: Parameter name to find indices for
        :return: List of indices
        """
        i_start = 0
        for param in self._parameters:
            if param.name == parameter_name:
                return list(range(i_start, i_start + param.dimension))
            else:
                i_start += param.dimension
        raise ValueError("Parameter {} not found".format(parameter_name))

    @property
    def dimensionality(self):
        return sum([p.dimension for p in self._parameters])

    @property
    def parameters(self) -> List:
        """
        Returns the list of parameters in the space.
        """

        return self._parameters

    @property
    def parameter_names(self) -> List:
        """
        Returns the list of names of parameters in the space.
        """

        return [p.name for p in self._parameters]

    def get_parameter_by_name(self, name: str) -> Parameter:
        """
        Returns parameter with the given name

        :param name: Parameter name
        :returns: A parameter object
        """

        for param in self.parameters:
            if param.name == name:
                return param
        raise ValueError("Parameter with name " + name + " not found.")

    def get_bounds(self) -> List[Tuple]:
        """
        Returns a list of tuples containing the min and max value each parameter can take.

        If the parameter space contains categorical variables, the min and max values correspond to each variable used
        to encode the categorical variables.
        """

        # bounds is a list of lists
        bounds = [param.bounds for param in self.parameters]
        # Convert list of lists to one list
        return list(itertools.chain.from_iterable(bounds))

    def round(self, x: np.ndarray) -> np.ndarray:
        """
        Rounds given values x to closest valid values within the space.

        :param x: A 2d array of values to be rounded
        :returns: A 2d array of rounded values
        """

        x_rounded = []
        current_idx = 0
        for param in self.parameters:
            param_columns = x[:, current_idx : (current_idx + param.dimension)]
            x_rounded.append(param.round(param_columns))
            current_idx += param.dimension

        return np.column_stack(x_rounded)

    def check_points_in_domain(self, x: np.ndarray) -> np.ndarray:
        """
        Checks that each column of x lies in the domain of the corresponding parameter

        :param x: 2d numpy array of points to check
        :return: A 1d numpy array which contains a boolean indicating whether each point is in domain
        """
        len_encoding = sum(len(param.model_parameters) for param in self.parameters)
        if x.shape[1] != len_encoding:
            raise ValueError(
                "x should have number of columns equal to the sum"
                "of all parameter encodings, expected {} actual {}".format(x.shape[1], len_encoding)
            )

        in_domain = np.ones(x.shape[0], dtype=bool)
        encoding_index = 0
        for param in self._parameters:
            # First check if this particular parameter is in domain
            param_in_domain = [
                param.check_in_domain(x[[point_ix], encoding_index : (encoding_index + param.dimension)])
                for point_ix in range(x.shape[0])
            ]
            # Set in_domain to be False if this parameter or any previous parameter is out of domain
            in_domain = np.all([in_domain, param_in_domain], axis=0)
            encoding_index += param.dimension
        return in_domain

    def sample_uniform(self, point_count: int) -> np.ndarray:
        """
        Generates multiple uniformly distributed random parameter points.

        :param point_count: number of data points to generate.
        :returns: Generated points with shape (point_count, num_features)
        """
        parameter_samples = [param.sample_uniform(point_count) for param in self.parameters]
        return np.hstack(parameter_samples)


text:
package me.justgame.vote.test.dao.mapper;

import me.justgame.vote.common.annotations.MyBatisMapper;
import me.justgame.vote.test.model.Test;

import java.util.List;

/**
 * Created by xcl on 2017-01-05.
 */

@MyBatisMapper
public interface TestMapper {

    List<Test> getTest() throws Exception;

}


text:
package com.bumptech.glide.load;

/**
 * Options for setting the value of {@link android.graphics.Bitmap#getConfig()} for
 * {@link android.graphics.Bitmap}s returned by {@link com.bumptech.glide.load.ResourceDecoder}s.
 *
 *
 Note - In some cases it may not be possible to obey the requested setting, not all
 * {@link com.bumptech.glide.load.resource.bitmap.Downsampler}s support setting formats and certain
 * images may not be able to be loaded as certain configurations. Therefore this class represents a
 * preference rather than a requirement.

 */
public enum DecodeFormat {
  /**
   * Bitmaps returned by the {@link com.bumptech.glide.load.ResourceDecoder}.
   * should return {@link android.graphics.Bitmap.Config#ARGB_8888} for
   * {@link android.graphics.Bitmap#getConfig()} when possible.
   *
   *
On Android O+, this format will will use ARGB_8888 only when it's not possible to use
   * {@link android.graphics.Bitmap.Config#HARDWARE}.
   *
   *
 GIF images decoded by {@link android.graphics.BitmapFactory} currently use an internal
   * hidden format that is returned as null from {@link android.graphics.Bitmap#getConfig()}. Since
   * we cannot force {@link android.graphics.BitmapFactory} to always return our desired config,
   * this setting is a preference, not a promise.
   */
  PREFER_ARGB_8888,

  /**
   * Identical to {@link #PREFER_ARGB_8888} but prevents Glide from using {@link
   * android.graphics.Bitmap.Config#HARDWARE} on Android O+.
   *
   * @deprecated If you must disable hardware bitmaps, set
   * {@link com.bumptech.glide.load.resource.bitmap.Downsampler#ALLOW_HARDWARE_CONFIG} to false
   * instead.
   */
  @Deprecated
  PREFER_ARGB_8888_DISALLOW_HARDWARE,

  /**
   * Bitmaps decoded from image formats that support and/or use alpha (some types of PNGs, GIFs etc)
   * should return {@link android.graphics.Bitmap.Config#ARGB_8888} for
   * {@link android.graphics.Bitmap#getConfig()}. Bitmaps decoded from formats that don't support or
   * use alpha should return {@link android.graphics.Bitmap.Config#RGB_565} for
   * {@link android.graphics.Bitmap#getConfig()}.
   *
   *
On Android O+, this format will will use ARGB_8888 only when it's not possible to use
   * {@link android.graphics.Bitmap.Config#HARDWARE}.
   */
  PREFER_RGB_565;

  /**
   * The default value for DecodeFormat.
   */
  public static final DecodeFormat DEFAULT = PREFER_ARGB_8888_DISALLOW_HARDWARE;
}


text:
"""Datastore object to keep track of a single Pipeline run."""

import collections

from google.appengine.ext import ndb

from lib.crud import crud_model

class RunStat(crud_model.CrudNdbModel):
  """A RunStat to keep track of Pipelines."""
  parent_model_name = 'Pipeline'

  started = ndb.DateTimeProperty(auto_now_add=True)
  stopped = ndb.DateTimeProperty(auto_now=True)
  result_code = ndb.IntegerProperty()

  @staticmethod
  def GetHistory(this_pipeline):
    """Search for stats generated by this pipeline."""
    return RunStat.query(ancestor=this_pipeline)

class ResultCodes(object):
  """Types of pipeline run results. Currently with placeholders."""

  SUCCESS, FAILURE, TIME_OUT = range(3)

  messages = collections.OrderedDict(((SUCCESS, 'Pipeline run succeeded'),
                                      (FAILURE, 'Pipeline run failed'),
                                      (TIME_OUT, 'Pipeline run timed out')))

  @staticmethod
  def ToString(i):
    return ResultCodes.messages.get(i, 'Pipeline status unknown')