text:
var express = require('express');
var request = require('request');
var sign=require('../libs/sign');//微信提供的签名方法
var config=require('../libs/config.json');//配置文件
var router = express.Router();

/* 最简单的获取签名信息 */
router.get('/', function(req, res) {
	request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appId+'&secret='+config.appSecret, function (error, response, body) {
		console.log('根据appId和appSecret获取accessToken ..');
		if(error || response.statusCode != 200){
			res.send(error);
			return;
		}
		var access_token=JSON.parse(body).access_token;
		console.log('access_token: '+access_token);

		request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi', function (error, response, body) {
			console.log('根据accessToken获取..');
			if (error || response.statusCode != 200) {
				res.send(error);
				return;
			}

		  	var ticket=JSON.parse(body).ticket;
		  	console.log('ticket: '+ticket);

		  	var port = req.app.settings.port;
		  	var url=req.protocol + '://' + req.host  + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;
		  	var result=sign(ticket,url);

		  	res.send(result);
		});
	});
});

var globalToken={};
var max_live=7200-1000;

router.get('/sign',function(req,res){
	var now=new Date().getTime()/1000;
	var callback=function(){
		var url= req.param('url');
		var result=sign(globalToken.ticket,url);
		res.send(result);
	}

	if (!globalToken.time || now-globalToken.time>max_live){
		refreshGlobalToken(req,res,function(){
			console.log('获取新的token');
			callback();
		})
	}else{
		console.log('重复使用token');
		callback();
	}
});

/* 正式的演示代码,包括服务器端生成签名,客户端通过签名使用微信API方法 */
router.get('/client', function(req, res) {
	var now=new Date().getTime()/1000;

	if (!globalToken.time || now-globalToken.time>max_live){
		refreshGlobalToken(req,res,function(){
			console.log('获取新的token');
			renderClient(req,res);
		})
	}else{
		console.log('重复使用token');
		renderClient(req,res);
	}
});

function refreshGlobalToken(req,res,callback){
	request('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='+config.appId+'&secret='+config.appSecret, function (error, response, body) {
		console.log('根据appId和appSecret获取accessToken ..');
		if(error || response.statusCode != 200){
			res.send(error);
			return;
		}
		var access_token=JSON.parse(body).access_token;
		console.log('access_token: '+access_token);

		request('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='+access_token+'&type=jsapi', function (error, response, body) {
			console.log('根据accessToken获取..');
			if (error || response.statusCode != 200) {
				res.send(error);
				return;
			}

		  	var ticket=JSON.parse(body).ticket;
		  	console.log('ticket: '+ticket);

		  	globalToken.time=new Date().getTime()/1000;
		  	globalToken.ticket=ticket;
		  	callback();
		});
	});
}

function renderClient(req,res){
	var port = req.app.settings.port;
	var url=req.protocol + '://' + req.host  + ( port == 80 || port == 443 ? '' : ':'+port ) + req.path;
	var result=sign(globalToken.ticket,url);
	res.render('client',{config:config,result:result});
}

module.exports = router;

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

  <meta charset="utf-8">
  <title>Test for Bug 341604 - plugins</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

Mozilla Bug 341604 - Implement HTML5 sandbox attribute for IFRAMEs

<embed id="plugin1" type="application/x-test" width="200" height="200"></embed>


text:
import sys, os
Q = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.abspath(Q + "/src"))

# import flask application
from dfs.cmds.serve import Serve, application

if __name__ == "__main__":
    application.run()


text:
package header

import (
	"encoding/json"
	"net/http"

	"github.com/google/martian/v3"
	"github.com/google/martian/v3/parse"
)

const idHeaderName string = "X-Martian-ID"

func init() {
	parse.Register("header.Id", idModifierFromJSON)
}

type idModifier struct{}

type idModifierJSON struct {
	Scope []parse.ModifierType `json:"scope"`
}

// NewIDModifier returns a request modifier that will set a header with the name
// X-Martian-ID with a value that is a unique identifier for the request. In the case
// that the X-Martian-ID header is already set, the header is unmodified.
func NewIDModifier() martian.RequestModifier {
	return &idModifier{}
}

// ModifyRequest sets the X-Martian-ID header with a unique identifier.  In the case
// that the X-Martian-ID header is already set, the header is unmodified.
func (im *idModifier) ModifyRequest(req *http.Request) error {
	// Do not rewrite an ID if req already has one
	if req.Header.Get(idHeaderName) != "" {
		return nil
	}

	ctx := martian.NewContext(req)
	req.Header.Set(idHeaderName, ctx.ID())

	return nil
}

func idModifierFromJSON(b []byte) (*parse.Result, error) {
	msg := &idModifierJSON{}
	if err := json.Unmarshal(b, msg); err != nil {
		return nil, err
	}

	modifier := NewIDModifier()

	return parse.NewResult(modifier, msg.Scope)
}


text:
/* // +build ignore */

// Copyright (c) 2012-2015 Ugorji Nwoke. All rights reserved.
// Use of this source code is governed by a MIT license found in the LICENSE file.

// ************************************************************
// DO NOT EDIT.
// THIS FILE IS AUTO-GENERATED from gen-helper.go.tmpl
// ************************************************************

package codec

import (
	"encoding"
	"reflect"
)

// GenVersion is the current version of codecgen.
const GenVersion = 6

// This file is used to generate helper code for codecgen.
// The values here i.e. genHelper(En|De)coder are not to be used directly by
// library users. They WILL change continuously and without notice.
//
// To help enforce this, we create an unexported type with exported members.
// The only way to get the type is via the one exported type that we control (somewhat).
//
// When static codecs are created for types, they will use this value
// to perform encoding or decoding of primitives or known slice or map types.

// GenHelperEncoder is exported so that it can be used externally by codecgen.
//
// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE.
func GenHelperEncoder(e *Encoder) (genHelperEncoder, encDriver) {
	return genHelperEncoder{e: e}, e.e
}

// GenHelperDecoder is exported so that it can be used externally by codecgen.
//
// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE.
func GenHelperDecoder(d *Decoder) (genHelperDecoder, decDriver) {
	return genHelperDecoder{d: d}, d.d
}

// Library users: DO NOT USE IT DIRECTLY. IT WILL CHANGE CONTINOUSLY WITHOUT NOTICE.
func BasicHandleDoNotUse(h Handle) *BasicHandle {
	return h.getBasicHandle()
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
type genHelperEncoder struct {
	e *Encoder
	F fastpathT
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
type genHelperDecoder struct {
	d *Decoder
	F fastpathT
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncBasicHandle() *BasicHandle {
	return f.e.h
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncBinary() bool {
	return f.e.cf.be // f.e.hh.isBinaryEncoding()
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncFallback(iv interface{}) {
	// println(">>>>>>>>> EncFallback")
	// f.e.encodeI(iv, false, false)
	f.e.encodeValue(reflect.ValueOf(iv), nil, false)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncTextMarshal(iv encoding.TextMarshaler) {
	bs, fnerr := iv.MarshalText()
	f.e.marshal(bs, fnerr, false, c_UTF8)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncJSONMarshal(iv jsonMarshaler) {
	bs, fnerr := iv.MarshalJSON()
	f.e.marshal(bs, fnerr, true, c_UTF8)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncBinaryMarshal(iv encoding.BinaryMarshaler) {
	bs, fnerr := iv.MarshalBinary()
	f.e.marshal(bs, fnerr, false, c_RAW)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncRaw(iv Raw) {
	f.e.rawBytes(iv)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) TimeRtidIfBinc() uintptr {
	if _, ok := f.e.hh.(*BincHandle); ok {
		return timeTypId
	}
	return 0
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) IsJSONHandle() bool {
	return f.e.cf.js
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) HasExtensions() bool {
	return len(f.e.h.extHandle) != 0
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperEncoder) EncExt(v interface{}) (r bool) {
	rt := reflect.TypeOf(v)
	if rt.Kind() == reflect.Ptr {
		rt = rt.Elem()
	}
	rtid := rt2id(rt)
	if xfFn := f.e.h.getExt(rtid); xfFn != nil {
		f.e.e.EncodeExt(v, xfFn.tag, xfFn.ext, f.e)
		return true
	}
	return false
}

// ---------------- DECODER FOLLOWS -----------------

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecBasicHandle() *BasicHandle {
	return f.d.h
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecBinary() bool {
	return f.d.be // f.d.hh.isBinaryEncoding()
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecSwallow() {
	f.d.swallow()
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecScratchBuffer() []byte {
	return f.d.b[:]
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecFallback(iv interface{}, chkPtr bool) {
	// println(">>>>>>>>> DecFallback")
	rv := reflect.ValueOf(iv)
	if chkPtr {
		rv = f.d.ensureDecodeable(rv)
	}
	f.d.decodeValue(rv, nil, false, false)
	// f.d.decodeValueFallback(rv)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecSliceHelperStart() (decSliceHelper, int) {
	return f.d.decSliceHelperStart()
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecStructFieldNotFound(index int, name string) {
	f.d.structFieldNotFound(index, name)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecArrayCannotExpand(sliceLen, streamLen int) {
	f.d.arrayCannotExpand(sliceLen, streamLen)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecTextUnmarshal(tm encoding.TextUnmarshaler) {
	fnerr := tm.UnmarshalText(f.d.d.DecodeStringAsBytes())
	if fnerr != nil {
		panic(fnerr)
	}
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecJSONUnmarshal(tm jsonUnmarshaler) {
	// bs := f.dd.DecodeStringAsBytes()
	// grab the bytes to be read, as UnmarshalJSON needs the full JSON so as to unmarshal it itself.
	fnerr := tm.UnmarshalJSON(f.d.nextValueBytes())
	if fnerr != nil {
		panic(fnerr)
	}
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecBinaryUnmarshal(bm encoding.BinaryUnmarshaler) {
	fnerr := bm.UnmarshalBinary(f.d.d.DecodeBytes(nil, true))
	if fnerr != nil {
		panic(fnerr)
	}
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecRaw() []byte {
	return f.d.rawBytes()
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) TimeRtidIfBinc() uintptr {
	if _, ok := f.d.hh.(*BincHandle); ok {
		return timeTypId
	}
	return 0
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) IsJSONHandle() bool {
	return f.d.js
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) HasExtensions() bool {
	return len(f.d.h.extHandle) != 0
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecExt(v interface{}) (r bool) {
	rt := reflect.TypeOf(v).Elem()
	rtid := rt2id(rt)
	if xfFn := f.d.h.getExt(rtid); xfFn != nil {
		f.d.d.DecodeExt(v, xfFn.tag, xfFn.ext)
		return true
	}
	return false
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) DecInferLen(clen, maxlen, unit int) (rvlen int) {
	return decInferLen(clen, maxlen, unit)
}

// FOR USE BY CODECGEN ONLY. IT *WILL* CHANGE WITHOUT NOTICE. *DO NOT USE*
func (f genHelperDecoder) StringView(v []byte) string {
	return stringView(v)
}


text:
import re

MAJOR = 0
MINOR = 3
VERSION = "%d.%d" % (MAJOR, MINOR)

# Simple major.minor matcher
re_version = re.compile(r"^(\d+)\.(\d+)$")

def version_check(required_version):
	match = re_version.match(required_version)

	if match:
		required_major = int(match.group(1))
		required_minor = int(match.group(2))
	else:
		raise ValueError("Specified required version %s has incorrect format, for example correct format is 1.0" % required_version)

	if MAJOR > required_major:
		print("WARNING: BuildFox executable major version %s is greater than 'buildfox_required_version' (%s).\nVersions may be incompatible" % (VERSION, required_version))
	elif (required_major == MAJOR and required_minor > MINOR) or required_major > MAJOR:
		raise RuntimeError("BuildFox version %s is incompatible with the version required %s" % (VERSION, required_version))


text:
package com.syshuman.kadir.haircolor3.eventbus;
import com.syshuman.kadir.haircolor3.model.VisitM;

import java.util.List;

public class VisitEvents {

    public static class onVisitCreated {
        public VisitM visitM;
        public onVisitCreated(VisitM visitM) {
            this.visitM = visitM;
        }
    }

    public static class onVisitRead {
        public List<VisitM> visitMList;
        public onVisitRead(List<VisitM> visitMList) {
            this.visitMList = visitMList;
        }
    }

    public static class onVisitUpdated {
        public VisitM visitM;
        public onVisitUpdated(VisitM visitM) {
            this.visitM = visitM;
        }
    }

    public static class onVisitDeleted {
        public VisitM visitM;
        public onVisitDeleted(VisitM visitM) {
            this.visitM = visitM;
        }
    }
}


text:
//
// For things I need handy for one time scripts, like creating and deleteing lots of users.
//
// node miscTestScript.js

var async = require('async');
var assert = require('assert');

//var request = require('supertest')('https://NewsWatcher.azurewebsites.net/'); // To hit production!
//var request = require('supertest')('http://localhost:3000'); // For local testing from command line launching
var request = require('supertest')('http://localhost:1337'); // For local testing for VS launching

var NUM_USERS = 50;
var usersP = [];
for (var i = 0; i < NUM_USERS; i++) {
	usersP.push({ idx: i, email: 'testrunPPP87654980' + i + '@example.com', displayName: 'testrunPPP87654980' + i, password: 'abc123*', token: null, userId: null, savedDoc: null });
}

async.series({
	one: function (callback) { // logins
		console.log("STEP: Log in all accounts");
		async.eachLimit(usersP, 2, function (user, innercallback) {
			request.post("/api/sessions")
         .send({
				email: usersP[user.idx].email,
				password: usersP[user.idx].password
			})
         .end(function (err, res) {
				if (res.status == 201) {
					usersP[user.idx].token = res.body.token;
					usersP[user.idx].userId = res.body.userId;
				}
				innercallback();
			});
		}, function (err) {
			if (err) {
				console.log('User login failure');
			} else {
				console.log('User login success');
			}
			callback(err, 1);
		});
	},
	two: function (callback) { // User account deletions
		console.log("STEP: Delete all test user accounts");
		async.eachLimit(usersP, 2, function (user, innercallback) {
			if (usersP[user.idx].userId != null) {
				request.del("/api/users/" + usersP[user.idx].userId)
				.set('x-auth', usersP[user.idx].token)
				.end(function (err, res) {
					assert.equal(res.status, 200);
					innercallback();
				});
			} else {
				innercallback();
			}
		}, function (err) {
			if (err) {
				console.log('User deletion failure');
			} else {
				console.log('User deletion success');
			}
			callback(err, 1);
		});
	}
},
function (err, results) {
	console.log("END: misc script");
});


text:
require 'rbbt/util/open'
require 'rbbt/rest/common/render'

require 'haml'
module EntityRESTHelpers

  def setup_entity(type, entity, params)
    base_type, format = type.split ":"
    entity_class = case
                   when Entity.formats.include?(base_type)
                     Entity.formats[base_type]
                   when Entity.formats.include?(format)
                     Entity.formats[format]
                   else
                     nil
                   end

    raise "Unknown entity type: #{ type }" if entity_class.nil?

    raise "Entity type not supported in REST: #{ type }" unless entity_class.include? Entity::REST

    entity_annotations = {}
    entity_class.annotations.each do |annotation|
      value = consume_parameter annotation, params
      value = Entity::REST.restore_element(value) if String === value
      value = false if value == "false"
      value = true if value == "true"
      entity_annotations[annotation] = value
    end

    entity.extend entity_class
    entity_class.setup_hash(entity, entity_annotations)
    entity.format = format if format and entity.respond_to? :format

    entity
  end

  def entity_render(entity, params = {})
    template_file = locate_entity_template(entity)

    params = {} if params.nil?
    locals = {:entity => entity}.merge(params)

    name = entity.respond_to?(:name)? entity.name : entity
    @title = "#{name} [#{$title}]"

    Log.low "Rendering #{ entity }: #{ template_file }"
    layout_file = layout ? locate_template("layout") : nil

    render(template_file, locals, layout_file, "Entity: #{ entity }".gsub(/\s/,'_'))
  end

  def entity_action_render(entity, action, params = {})
    template_file = locate_entity_action_template(entity, action)

    locals = params.merge({:entity => entity})

    name = entity.respond_to?(:name)? entity.name : entity
    @title = "#{action} #{name} [#{$title}]"

    Log.low "Rendering #{ entity } #{ action }: #{ template_file }"
    layout_file = layout ? locate_template("layout") : nil

    render(template_file, locals, layout_file, "Action #{ action }: #{ entity }".gsub(/\s/,'_'))
  end

  def entity_list_render(list, id)
    template_file = locate_entity_list_template(list)

    locals = {:list => list, :list_id => id}

    name = id
    @title = "#{name} [#{$title}]"

    Log.low "Rendering #{list.base_type.to_s} list: #{ template_file }"
    layout_file = layout ? locate_template("layout") : nil

    render(template_file, locals, layout_file, "Entity list: #{ id }".gsub(/\s/,'_'))
  end

  def entity_list_action_render(list, action, id, params = {})
    template_file = locate_entity_list_action_template(list, action)

    locals = params.merge({:list => list, :list_id => id})

    name = id
    @title = "#{action} #{name} [#{$title}]"

    Log.low "Rendering #{list.base_type.to_s} list #{ action }: #{ template_file }"
    layout_file = layout ? locate_template("layout") : nil

    render(template_file, locals, layout_file, "Action #{ action } for list: #{ id }".gsub(/\s/,'_'))
  end

  def entity_map_render(map_id, type, column)
    template_file = locate_entity_map_template(type, column)

    map = Entity::Map.load_map(type, column, map_id, user)
    locals = {:map => map, :map_id => map_id}

    name = map_id
    @title = "#{name} [#{$title}]"

    Log.low "Rendering #{type} map: #{ template_file }"
    layout_file = layout ? locate_template("layout") : nil

    render(template_file, locals, layout_file, "Entity map: #{ map_id }".gsub(/\s/,'_'))
  end

  def entity_map_action_render(map, action, id, params = {})
    template_file = locate_entity_map_action_template(map, action)

    locals = params.merge({:map => map, :map_id => id})

    name = id
    @title = "#{action} #{name} [#{$title}]"

    Log.low "Rendering '#{map.key_field} - #{map.fields.first}' map #{ action }: #{ template_file }"
    layout_file = layout ? locate_template("layout") : nil

    render(template_file, locals, layout_file, "Action #{ action } for map: #{ id }".gsub(/\s/,'_'))
  end
end


text:
<?php

declare(strict_types=1);

namespace Matthias\SymfonyConsoleForm\Bridge\Transformer;

final class NumberTransformer extends AbstractTextInputBasedTransformer
{
}


text:
Codes from [Structure and Interpretation of Computer Programs](http://mitpress.mit.edu/sicp/) by H. Abelson and G.J. Sussman using [MIT/GNU Scheme](http://www.gnu.org/software/mit-scheme/). For implementation in Common Lisp, see [cl-sicp](https://github.com/cbpark/cl-sicp).

Table of Contents
========================

1. Building Abstractions with Procedures
2. Building Abstractions with Data
3. Modularity, Objects, and State
4. Metalinguistic Abstraction
5. Computing with Register Machines


text:
           ___                                   ___                        ___           ___
          /  /\                      ___        /  /\          ___         /  /\         /  /\
         /  /:/_                    /__/|      /  /::\        /__/\       /  /:/_       /  /::\
        /  /:/ /\  ___     ___     |  |:|     /  /:/\:\       \  \:\     /  /:/ /\     /  /:/\:\
       /  /:/ /:/ /__/\   /  /\    |  |:|    /  /:/  \:\       \  \:\   /  /:/ /:/_   /  /:/~/:/
      /__/:/ /:/  \  \:\ /  /:/  __|__|:|   /__/:/ \__\:\  ___  \__\:\ /__/:/ /:/ /\ /__/:/ /:/___
      \  \:\/:/    \  \:\  /:/  /__/::::\   \  \:\ /  /:/ /__/\ |  |:| \  \:\/:/ /:/ \  \:\/:::::/
       \  \::/      \  \:\/:/      ~\~~\:\   \  \:\  /:/  \  \:\|  |:|  \  \::/ /:/   \  \::/~~~~
        \  \:\       \  \::/         \  \:\   \  \:\/:/    \  \:\__|:|   \  \:\/:/     \  \:\
         \  \:\       \__\/           \__\/    \  \::/      \__\::::/     \  \::/       \  \:\
          \__\/                                 \__\/           ~~~~       \__\/         \__\/

What's that plane flying overhead?

I live underneath a flight path for airplanes arriving at LaGuardia Airport in New York. When I hear the planes, I get curious: where are those people coming from? I wrote this to find out. You can read more about my feelings [here](http://jeremybmerrill.com/blog/2016/01/flyover.html).

How does this work?
-------------------

On the Raspberry Pi, we're running [Dump1090](https://github.com/mutability/dump1090) to handle the hard work of determining what planes are in the sky nearby. Piggybacking on Dump1090's JSON, `dump1090_to_nearest_flight.py` outputs the flight number and change-in-altitude of the nearest plane, optionally restricting that plane to a given area and/or altitude . `flight_number_to_departure_airport.py` translates that flight number, using a database, to the mostly likely non-NYC airport that is that flight's departure airport or destination. `display_letters.py` displays that airport's code (and, maybe, eventually, the city name for non-US airports).

Build your own
---------------

[Follow the instructions!](/instructions.md) If something seems wrong or could be improved upon, please submit a pull request.

If you need to draw an area for your favorite flight path, use [geojson.io](http://geojson.io). That's what I used to generate [laguardia_area.geojson](laguardia_area.geojson).

TODO
----
- look up airport names for non-US airports and display them too. (Where right now we'd display EGLL, we should instead display EGLL (London Heathrow, UK)).
- maybe also track noise. cf. http://webtrak5.bksv.com/panynj4
- it appears Southwest's airplanes may broadcast their flight number as just the number, i.e. 539, not SWA539.

Theoretically Askable Questions
-------------------------------

*Are you a NIMBY who is opposed to noise, airplanes, travel, etc.?*

Nah. I can hear the planes, but it's not really annoying. I'm not worried or angry, just curious about the world around me... :)

I do have a cat named Nimby though.

*But airplanes flying overhead could crash on you! They are dangerous!*

No, they're not. Please don't contact me anymore.

*Why isn't this Python 3 compatible?*

I couldn't get the Adafruit Python LED Backpack library working in Python 3. That's probably because I'm bad at Python, not on them.

*I have an idea to make this better. Can I send you a pull request?*

Yes, please. I would like that very much.

I would like to thank the Academy...
------------------------------------
This project would have been impossible without:

1. the maintainers of [dump1090](https://github.com/antirez/dump1090) and the [Mutability fork](https://github.com/mutability/dump1090).
2. the maintainers of the Virtual Radar Server [FlightNumbers dump](http://www.virtualradarserver.co.uk/FlightRoutes.aspx).
3. @calus at the FlightAware forums who [pointed me there](http://discussions.flightaware.com/ads-b-flight-tracking-f21/mapping-n-numbers-to-departure-airports-t36511.html).
4. Adafruit for their cool hardware and libraries.
5. [Sam Keddy](http://samkeddy.com/) who created the Thintel font I'm using.


text:
let target = d3.select("#dashboard").node();
// create tooltip
let tooltip = d3.select("body").append("div").style({"position": "absolute","z-index": "10","visibility": "hidden"}).attr({"class": "tooltip"});
// trigger loader
let spinner = new Spinner(opts).spin(target);

// dimensions for the charts
var dashboardHeight = getSize().height;
var headerHeight = document.querySelector('div.w3-main > header').offsetHeight;
var footerHeight = document.querySelector('div.w3-main > footer').offsetHeight;

var treeMapHeaderHeight = document.querySelector('#treeMap header').offsetHeight;
var treeMapFooterHeight = document.querySelector('#treeMap footer').offsetHeight;
var treeMapHeight = (dashboardHeight - headerHeight - footerHeight - treeMapHeaderHeight - treeMapFooterHeight) * 8/9;

// var treeMapWidth = document.querySelector('#treeMap footer').clientWidth; // does not include margin, padding, or scroll bar widths
var treeMapWidth = document.querySelector('#treeMap footer').offsetWidth - 16;

// patterned after Bill White's treemap
// http://www.billdwhite.com/wordpress/2012/12/16/d3-treemap-with-title-headers/

var chartWidth = treeMapWidth;
var chartHeight = treeMapHeight;
var xscale = d3.scale.linear().range([0, chartWidth]);
var yscale = d3.scale.linear().range([0, chartHeight]);
var color = d3.scale.category20();
var headerHeight = 40;
var headerColor = "#6E6E6E";
var transitionDuration = 750;
var root;
var node;
// var year = d3.select("#investment_year").property('value');
var year = 'cy';

var margins = {
    top: 25,
    right: 10,
    bottom: 20,
    left: 10
};

var treemap = d3.layout.treemap()
    .round(false)
    .size([chartWidth, chartHeight])
    .sticky(true)
    .sort(function(a, b) {
        return a.value - b.value;
    })
    .value(function(d) {
        return d['size_' + year];
    });

var chart = d3.select("#component")
    .append("svg:svg")
    .attr("width", chartWidth)
    .attr("height", chartHeight)
    .append("svg:g");

function createViz(error, data) {

    if (error) throw error;

    // stop spin.js loader
    spinner.stop();

    var records = data.value.map(function(d) {
        d.Year = +d.Year;
        if (d.Year === 2017) {
            d.Total_CY = +d.Total * 1000;
        } else if (d.Year === 2018) {
            d.Total_BY = +d.Total * 1000;
        } else if (d.Year === 2016) {
            d.Total_PY = +d.Total * 1000;
        }
        return d;
    });

    var nest = d3.nest()
        .key(function(d) {
            return d.Component;
        })
        .key(function(d) {
            return d.InvestmentName;
        })
        .rollup(function(leaves) {
            return {
                "total_cy": d3.sum(leaves, function(d) {
                    return d.Total_CY;
                }),
                "total_by": d3.sum(leaves, function(d) {
                    return d.Total_BY;
                }),
                "total_py": d3.sum(leaves, function(d) {
                    return d.Total_PY;
                })
            };
        })
        .entries(records);

    var children = nest.map(function(d) {
        // var count = d.values.length;
        var investments = d.values.map(function(g) {
            return {
                name: g.key,
                // count: count,
                count_cy: g.values.total_cy === 0 ? 0 : 1,
                count_py: g.values.total_py === 0 ? 0 : 1,
                count_by: g.values.total_by === 0 ? 0 : 1,
                size_cy: g.values.total_cy,
                size_py: g.values.total_py,
                size_by: g.values.total_by
            };
        });
        return {
            name: d.key,
            children: investments
        };

    });

    var root = {
        name: "Department of Justice",
        children: children
    };

    node = root;
    var nodes = treemap.nodes(root);

    children = nodes.filter(function(d) {
        return !d.children;
    });
    var parents = nodes.filter(function(d) {
        return d.children;
    });

    // create parent cells
    var parentCells = chart.selectAll("g.cell.parent")
        .data(parents, function(d) {
            return "p-" + d.name;
        });

    // var parentEnterTransition = parentCells.enter()
    //     .append("g")
    //     .attr("class", "cell parent")
    var parentEnterTransition = parentCells.enter()
        .append("g")
        .attr("class", "cell parent")
        .on("click", function(d) {
            zoom(d);
        })
        .append("svg")
        .attr("class", "clip")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", headerHeight)
        .on("click", function(d) {
            zoom(d);
        });

    parentEnterTransition.append("rect")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", headerHeight)
        .style("fill", headerColor);

    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
    parentEnterTransition.append('text')
        .attr("class", "label")
        .attr("transform", "translate(3, 23)")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", headerHeight)
        .style("fill","#fff")
        .text(function(d) {
            var text = d.depth > 0 ? " investments, " + formatAbbreviation(d.value) : " Components";
            var count = d.depth > 0 ? d3.sum(d.children,function(g) { return g['count_'+year] }) : d.children.length;
            return d.name + ": " + count + text;
        })
        ;

    // update transition
    var parentUpdateTransition = parentCells.transition().duration(transitionDuration);
    parentUpdateTransition.select(".cell")
        .attr("transform", function(d) {
            return "translate(" + d.dx + "," + d.y + ")";
        });

    parentUpdateTransition.select("rect")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", headerHeight)
        .style("fill", headerColor);

    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
    parentUpdateTransition.select(".label")
        .attr("transform", "translate(3, 23)")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", headerHeight)
        ;
    // remove transition
    parentCells.exit()
        .remove();

    // create children cells
    var childrenCells = chart.selectAll("g.cell.child")
        .data(children, function(d) {
            return "c-" + d.name;
        });
    // enter transition
    var childEnterTransition = childrenCells.enter()
        .append("g")
        .attr("class", "cell child")
        .on("click", function(d) {
            zoom(node === d.parent ? root : d.parent);
        });
    childEnterTransition.append("rect")
        .classed("background", true)
        .style("fill", function(d) {
            return color(d.parent.name);
        });

    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
    childEnterTransition.append('text')
        .attr("class", "label")
        .attr('x', function(d) {
            return d.dx / 2;
        })
        .attr('y', function(d) {
            return d.dy / 2;
        })
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("display", "none")
        .text(function(d) {
            return d.name;
        })
        ;

    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
    childEnterTransition.selectAll(".label")
        .style("display", "none")
    ;

    // update transition
    var childUpdateTransition = childrenCells.transition().duration(transitionDuration);
    childUpdateTransition.select(".cell")
        .attr("transform", function(d) {
            return "translate(" + d.x + "," + d.y + ")";
        });
    childUpdateTransition.select("rect")
        .attr("width", function(d) {
            return Math.max(0.01, d.dx);
        })
        .attr("height", function(d) {
            return d.dy;
        })
        .style("fill", function(d) {
            return color(d.parent.name);
        });

    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
    childUpdateTransition.select(".label")
        .attr('x', function(d) {
            return d.dx / 2;
        })
        .attr('y', function(d) {
            return d.dy / 2;
        })
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("display", "none")
        .text(function(d) {
            return d.name;
        })
        ;

    // exit transition
    childrenCells.exit()
        .remove();

    // Change the date header to reflect the date and time of the data
    d3.select('#dateHeader').text(formatDate(new Date()));

    d3.select("#investment_year").on("change", function() {
        year = this.value;
        treemap.value(size)
            .nodes(root);
        zoom(node);
    });

    var treeChart = d3.select("#component")
    var width = +treeChart.select('svg').attr('width');
    var height = +treeChart.select('svg').attr('height');
    var calcString = +(height / width) * 100 + "%";

    var svgElement = treeChart.select('svg');
    var svgParent = d3.select(treeChart.select('svg').node().parentNode);

    svgElement.attr({
        'class':'scaling-svg',
        'preserveAspectRatio':'xMinYMin',
        'viewBox':'0 0 ' + width + ' ' + height,
        'width':null,
        'height':null
    });

    svgParent.style('padding-bottom',calcString);

    zoom(node);

    // define mouseover and mouseout events
    function bindHover() {
        document.body.addEventListener('mousemove',function( e ) {
            if ((e.target.nodeName == 'rect' && e.target.classList.contains('background'))) {
                var d = d3.select(e.target).data()[0];
                var key = d.name;
                var amount = formatAbbreviation(d['size_' + year]);
                showDetail(e, key, amount, null, null);
            }
        });

        document.body.addEventListener('mouseout',function( e ) {
            if ((e.target.nodeName == 'rect' && e.target.classList.contains('background'))) hideDetail();
        });
    }

    bindHover();

}

function size(d) {
    return d['size_' + year];
}

//and another one
function textHeight(d) {
    var ky = chartHeight / d.dy;
    yscale.domain([d.y, d.y + d.dy]);
    return (ky * d.dy) / headerHeight;
}

function getRGBComponents(color) {
    var r = color.substring(1, 3);
    var g = color.substring(3, 5);
    var b = color.substring(5, 7);
    return {
        R: parseInt(r, 16),
        G: parseInt(g, 16),
        B: parseInt(b, 16)
    };
}

function idealTextColor(bgColor) {
    var nThreshold = 105;
    var components = getRGBComponents(bgColor);
    var bgDelta = (components.R * 0.299) + (components.G * 0.587) + (components.B * 0.114);
    return ((255 - bgDelta) < nThreshold) ? "#000000" : "#ffffff";
}

function zoom(d) {
    this.treemap
        .padding([headerHeight / (chartHeight / d.dy), 0, 0, 0])
        .nodes(d);

    // moving the next two lines above treemap layout messes up padding of zoom result
    var kx = chartWidth / d.dx;
    var ky = chartHeight / d.dy;
    var level = d;

    xscale.domain([d.x, d.x + d.dx]);
    yscale.domain([d.y, d.y + d.dy]);

    if (node != level) {
        // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
        chart.selectAll(".cell.child .label")
            .style("display", "none")
        ;
    }

    var zoomTransition = chart.selectAll("g.cell").transition().duration(transitionDuration)
        .attr("transform", function(d) {
            return "translate(" + xscale(d.x) + "," + yscale(d.y) + ")";
        })
        .each("end", function(d, i) {
            if (!i && (level !== self.root)) {
                chart.selectAll(".cell.child")
                    .filter(function(d) {
                        return d.parent === self.node; // only get the children for selected group
                    })
                    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
                    .select(".label")
                    .style("display", "")
                    .style("fill", function(d) {
                        return idealTextColor(color(d.parent.name));
                    })

                    .text(function(d) {
                        return d.name;
                    })
                    .each(wordWrap)
                    ;
                chart.selectAll(".clip .label")
                    .text(function(d) {
                        var text = d.depth > 0 ? " investments, " + formatAbbreviation(d.value) : " Components";
                        var count = d.depth > 0 ? d3.sum(d.children,function(g) { return g['count_'+year] }) : d.children.length;
                        return d.name + ": " + count + text;
                    });
            }
        });

    // use <text> tag instead of non-SVG compliant <foreignObject> tag, which also doesn't work in IE
    zoomTransition.select(".clip")
        .attr("width", function(d) {
            return Math.max(0.01, (kx * d.dx));
        })
        .attr("height", function(d) {
            return d.children ? headerHeight : Math.max(0.01, (ky * d.dy));
        });

    zoomTransition.select(".label")
        .attr("width", function(d) {
            return Math.max(0.01, (kx * d.dx));
        })
        .attr("height", function(d) {
            return d.children ? headerHeight : Math.max(0.01, (ky * d.dy));
        });

    zoomTransition.select(".child .label")
        .attr("x", function(d) {
            return kx * d.dx / 2;
        })
        .attr("y", function(d) {
            return ky * d.dy / 2;
        });
    // update the width/height of the rects
    zoomTransition.select("rect")
        .attr("width", function(d) {
            return Math.max(0.01, kx * d.dx);
        })
        .attr("height", function(d) {
            return d.children ? headerHeight : Math.max(0.01, ky * d.dy);
        })
        .style("fill", function(d) {
            return d.children ? headerColor : color(d.parent.name);
        });

    node = d;

    d3.select('#total_spend')
        .text('')
        .text(formatAbbreviation(d3.select('.parent').datum().value));

    if (d3.event) {
        d3.event.stopPropagation();
    }
}

// adapted from http://bl.ocks.org/mundhradevang/1387786
function fontSize(d, i) {
    var size = d.dx / 5;
    var words = d.name.split(' ');
    var word = words[0];
    var width = d.dx;
    var height = d.dy;
    var length = 0;
    d3.select(this).style("font-size", size + "px").text(word);
    while (((this.getBBox().width >= width) || (this.getBBox().height >= height)) && (size > 12)) {
        size--;
        d3.select(this).style("font-size", size + "px");
        this.firstChild.data = word;
    }
}

// adapted from http://bl.ocks.org/mundhradevang/1387786
function wordWrap(d, i) {
    var words = d.name.split(' ');
    var line = new Array();
    var length = 0;
    var text = "";
    var strokeWidth = parseInt(d3.select(this.previousSibling).style('stroke-width')); // get stroke width to provide "padding" for text
    var width = +this.previousSibling.getAttribute('width') - (strokeWidth * 2); // get the width of the <rect> svg since the d.dx data property reflects a non-zoomed in dimension
    var height = +this.previousSibling.getAttribute('height') - (strokeWidth * 2); // get the height of the <rect> svg since the d.dx data property reflects a non-zoomed in dimension
    var word;
    do {
        word = words.shift();
        line.push(word);
        if (words.length)
            this.firstChild.data = line.join(' ') + " " + words[0];
        else
            this.firstChild.data = line.join(' ');
        length = this.getBBox().width;
        if (length < width && words.length) {
        }
        else {
            text = line.join(' ');
            this.firstChild.data = text;
            if (this.getBBox().width > width) {
                text = d3.select(this).select(function() {
                    return this.lastChild;
                }).text();
                text = text + "...";
                d3.select(this).select(function() {
                    return this.lastChild;
                }).text(text);
                d3.select(this).classed("wordwrapped", true);
                break;
            }
            else
            ;

            if (text != '') {
                d3.select(this).append("tspan") // <tspan> tag should inherit x, y, and dy, properties of the <text> tag
                    .text(text);

            }
            else
            ;

            if (this.getBBox().height > height && words.length) {
                text = d3.select(this).select(function() {
                    return this.lastChild;
                }).text();
                text = text + "...";
                d3.select(this).select(function() {
                    return this.lastChild;
                }).text(text);
                d3.select(this).classed("wordwrapped", true);

                break;
            }
            else
            ;

            line = new Array();
        }
    } while (words.length);
    this.firstChild.data = '';
}

// if this JavaScript source file resides on a SharePoint server
// the function will return an endpoint Url pointing to a specified SharePoint list
// if not, the endpoint will point to a json file
function getData() {

    var test = '';
    var siteUrl = '';
    var columns = '';
    var expand = '';
    var filter = '';
    var top = '';
    var instrg = 0;

    // test if on SharePoint
    try {
        instrg = _spPageContextInfo.webAbsoluteUrl.indexOf('itim');
        if (typeof _spPageContextInfo !== undefined &&  instrg > 0) {
            siteUrl = _spPageContextInfo.webAbsoluteUrl;
            test = false;
        } else {
            siteUrl = undefined;
            test = true;
        }
    }
    catch (e) {
        siteUrl = undefined;
        test = true;
    }

    function callData(siteUrl, type, title, columns, expand, filter, top) {

        var url = "",
            endpoint;

        if (!test) {
        	if (type !== 'web') {
            	url = siteUrl + "/_api/web/lists/GetByTitle('" + title + "')/items?$select=" + columns + "&$expand=" + expand + "&$filter=" + filter + "&$top=" + top;
        	} else {
        		url = siteUrl + "/_api/web/" + title;
        	}
            endpoint = d3.json(url).header("accept", "application/json;odata=nometadata");

        }
        else {
            url = instrg == 0 ? "../SiteAssets/data/" + title + ".json" : "../SiteAssets/data/" + title + ".js";
            endpoint = d3.json(url);
        }

        return endpoint;

    }

    columns = "Id,Component,InvestmentName,Year,Total";
    expand = "";
    filter = "(InvestmentName ne null) and (Year gt 2015) and (Total ne 0) and (BudgetCall eq 'Passback')";
    top = 3000;

    var componentEndpoint = callData(siteUrl, 'list','AnnualBudgetData', columns, expand, filter, top);

    // Get the data
    componentEndpoint.get(function(error, data) {
        createViz(error, data);
    });

}
getData();


text:
package io.pivotal.fe.demos.citiesui;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CitiesUiApplication {

    public static void main(String[] args) {
        SpringApplication.run(CitiesUiApplication.class, args);
    }
}


text:
title:  Aile Bağlarında Rahat Bulmak
date:  31/07/2021
---

### Konuyla İlgili Metinler
Yaratılış 34; İbraniler 11:17–22; Yasa'nın Tekrarı 4:29; 1.Yuhanna 3:1, 2; Yaratılış 39; Efesliler 6:1–13.

>
Hatırlama Metni

> "Bu nedenle, sevgili kardeşlerim, ilke tanımayan kişilerin aldatmasıyla sürüklenip kararlılığınızdan sapmamak için bunları önceden bilerek sakının. Öte yandan Rabbimiz ve Kurtarıcımız İsa Mesih'in lütfunda ve O'nu tanımakta ilerleyin. Şimdi ve sonsuza dek O'na yücelik olsun! Amin" (2.Petrus 3:17, 18).

Genç adam dikkatle ufuğa baktı. Sonunda, onları gördü. Günlerdir kardeşlerini arıyordu. El sallayıp bağırarak asık suratlı topluluğa yaklaştığında, hiç iyi karşılanmadı. Kendi kardeşleri aslında onu öldürmek istiyorlardı. Eğer Ruben olmasa, anlatacak bir öykü olmayabilirdi. Ruben diğer kardeşlerini onu biraz hırpalayıp kuru bir kuyuya atmaya ikna etti. Daha sonra, Yahuda, onu yoldan geçen köle tüccarlarına satarak hem ondan kurtulacakları hem de biraz para kazanacakları bir planla geldi.

Bozuk aile düzenine ne örnek ama!

Yaşamda pek çok şeyi seçebiliriz fakat ailemizi seçemeyiz. Hiçbirimiz kusursuz değiliz ve hiçbirimizin kusursuz aileleri ya da kusursuz aile ilişkileri yok. Bazılarımız Allah'ın sevgisini yansıtan ebeveynler, kardeşler ya da diğer aile üyeleri sayesinde bereketlenmişizdir fakat pek çok kişi olması gerekenden çok azıyla yetinmek zorundadır. Aile ilişkileri sıklıkla karmaşık ve acı vericidir, bizi huzursuz, incinmiş ve sonunda diğer insanlara yüklediğimiz duygusal yükleri taşımak zorunda bırakırlar.

Yaşamlarımızın bu alanında Allah'ın rahatını nasıl bulabiliriz? Bu hafta, bozuk aile ilişkilerine rağmen Allah'ın nasıl da iyileştirip duygusal rahata kavuşturduğunu görmek için Yusuf ve onun aile bağlarını inceleyeceğiz.

_*7 Ağustos Sebt Günü'ne hazırlık için bu haftanın konusunu çalış._


text:
package android.speech;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.RemoteException;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * This class provides access to the speech recognition service. This service allows access to the
 * speech recognizer. Do not instantiate this class directly, instead, call
 * {@link SpeechRecognizer#createSpeechRecognizer(Context)}. This class's methods must be
 * invoked only from the main application thread.
 *
 *
The implementation of this API is likely to stream audio to remote servers to perform speech
 * recognition. As such this API is not intended to be used for continuous recognition, which would
 * consume a significant amount of battery and bandwidth.
 *
 *
Please note that the application must have {@link android.Manifest.permission#RECORD_AUDIO}
 * permission to use this class.
 */
public class SpeechRecognizer {
    /** DEBUG value to enable verbose debug prints */
    private final static boolean DBG = false;

    /** Log messages identifier */
    private static final String TAG = "SpeechRecognizer";

    /**
     * Key used to retrieve an {@code ArrayList<String>} from the {@link Bundle} passed to the
     * {@link RecognitionListener#onResults(Bundle)} and
     * {@link RecognitionListener#onPartialResults(Bundle)} methods. These strings are the possible
     * recognition results, where the first element is the most likely candidate.
     */
    public static final String RESULTS_RECOGNITION = "results_recognition";

    /**
     * Key used to retrieve a float array from the {@link Bundle} passed to the
     * {@link RecognitionListener#onResults(Bundle)} and
     * {@link RecognitionListener#onPartialResults(Bundle)} methods. The array should be
     * the same size as the ArrayList provided in {@link #RESULTS_RECOGNITION}, and should contain
     * values ranging from 0.0 to 1.0, or -1 to represent an unavailable confidence score.
     *

     * Confidence values close to 1.0 indicate high confidence (the speech recognizer is confident
     * that the recognition result is correct), while values close to 0.0 indicate low confidence.
     *

     * This value is optional and might not be provided.
     */
    public static final String CONFIDENCE_SCORES = "confidence_scores";

    /** Network operation timed out. */
    public static final int ERROR_NETWORK_TIMEOUT = 1;

    /** Other network related errors. */
    public static final int ERROR_NETWORK = 2;

    /** Audio recording error. */
    public static final int ERROR_AUDIO = 3;

    /** Server sends error status. */
    public static final int ERROR_SERVER = 4;

    /** Other client side errors. */
    public static final int ERROR_CLIENT = 5;

    /** No speech input */
    public static final int ERROR_SPEECH_TIMEOUT = 6;

    /** No recognition result matched. */
    public static final int ERROR_NO_MATCH = 7;

    /** RecognitionService busy. */
    public static final int ERROR_RECOGNIZER_BUSY = 8;

    /** Insufficient permissions */
    public static final int ERROR_INSUFFICIENT_PERMISSIONS = 9;

    /** action codes */
    private final static int MSG_START = 1;
    private final static int MSG_STOP = 2;
    private final static int MSG_CANCEL = 3;
    private final static int MSG_CHANGE_LISTENER = 4;

    /** The actual RecognitionService endpoint */
    private IRecognitionService mService;

    /** The connection to the actual service */
    private Connection mConnection;

    /** Context with which the manager was created */
    private final Context mContext;

    /** Component to direct service intent to */
    private final ComponentName mServiceComponent;

    /** Handler that will execute the main tasks */
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_START:
                    handleStartListening((Intent) msg.obj);
                    break;
                case MSG_STOP:
                    handleStopMessage();
                    break;
                case MSG_CANCEL:
                    handleCancelMessage();
                    break;
                case MSG_CHANGE_LISTENER:
                    handleChangeListener((RecognitionListener) msg.obj);
                    break;
            }
        }
    };

    /**
     * Temporary queue, saving the messages until the connection will be established, afterwards,
     * only mHandler will receive the messages
     */
    private final Queue<Message> mPendingTasks = new LinkedList<Message>();

    /** The Listener that will receive all the callbacks */
    private final InternalListener mListener = new InternalListener();

    /**
     * The right way to create a {@code SpeechRecognizer} is by using
     * {@link #createSpeechRecognizer} static factory method
     */
    private SpeechRecognizer(final Context context, final ComponentName serviceComponent) {
        mContext = context;
        mServiceComponent = serviceComponent;
    }

    /**
     * Basic ServiceConnection that records the mService variable. Additionally, on creation it
     * invokes the {@link IRecognitionService#startListening(Intent, IRecognitionListener)}.
     */
    private class Connection implements ServiceConnection {

        public void onServiceConnected(final ComponentName name, final IBinder service) {
            // always done on the application main thread, so no need to send message to mHandler
            mService = IRecognitionService.Stub.asInterface(service);
            if (DBG) Log.d(TAG, "onServiceConnected - Success");
            while (!mPendingTasks.isEmpty()) {
                mHandler.sendMessage(mPendingTasks.poll());
            }
        }

        public void onServiceDisconnected(final ComponentName name) {
            // always done on the application main thread, so no need to send message to mHandler
            mService = null;
            mConnection = null;
            mPendingTasks.clear();
            if (DBG) Log.d(TAG, "onServiceDisconnected - Success");
        }
    }

    /**
     * Checks whether a speech recognition service is available on the system. If this method
     * returns {@code false}, {@link SpeechRecognizer#createSpeechRecognizer(Context)} will
     * fail.
     *
     * @param context with which {@code SpeechRecognizer} will be created
     * @return {@code true} if recognition is available, {@code false} otherwise
     */
    public static boolean isRecognitionAvailable(final Context context) {
        final List<ResolveInfo> list = context.getPackageManager().queryIntentServices(
                new Intent(RecognitionService.SERVICE_INTERFACE), 0);
        return list != null && list.size() != 0;
    }

    /**
     * Factory method to create a new {@code SpeechRecognizer}. Please note that
     * {@link #setRecognitionListener(RecognitionListener)} should be called before dispatching any
     * command to the created {@code SpeechRecognizer}, otherwise no notifications will be
     * received.
     *
     * @param context in which to create {@code SpeechRecognizer}
     * @return a new {@code SpeechRecognizer}
     */
    public static SpeechRecognizer createSpeechRecognizer(final Context context) {
        return createSpeechRecognizer(context, null);
    }

    /**
     * Factory method to create a new {@code SpeechRecognizer}. Please note that
     * {@link #setRecognitionListener(RecognitionListener)} should be called before dispatching any
     * command to the created {@code SpeechRecognizer}, otherwise no notifications will be
     * received.
     *
     * Use this version of the method to specify a specific service to direct this
     * {@link SpeechRecognizer} to. Normally you would not use this; use
     * {@link #createSpeechRecognizer(Context)} instead to use the system default recognition
     * service.
     *
     * @param context in which to create {@code SpeechRecognizer}
     * @param serviceComponent the {@link ComponentName} of a specific service to direct this
     *        {@code SpeechRecognizer} to
     * @return a new {@code SpeechRecognizer}
     */
    public static SpeechRecognizer createSpeechRecognizer(final Context context,
            final ComponentName serviceComponent) {
        if (context == null) {
            throw new IllegalArgumentException("Context cannot be null)");
        }
        checkIsCalledFromMainThread();
        return new SpeechRecognizer(context, serviceComponent);
    }

    /**
     * Sets the listener that will receive all the callbacks. The previous unfinished commands will
     * be executed with the old listener, while any following command will be executed with the new
     * listener.
     *
     * @param listener listener that will receive all the callbacks from the created
     *        {@link SpeechRecognizer}, this must not be null.
     */
    public void setRecognitionListener(RecognitionListener listener) {
        checkIsCalledFromMainThread();
        putMessage(Message.obtain(mHandler, MSG_CHANGE_LISTENER, listener));
    }

    /**
     * Starts listening for speech. Please note that
     * {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise
     * no notifications will be received.
     *
     * @param recognizerIntent contains parameters for the recognition to be performed. The intent
     *        may also contain optional extras, see {@link RecognizerIntent}. If these values are
     *        not set explicitly, default values will be used by the recognizer.
     */
    public void startListening(final Intent recognizerIntent) {
        if (recognizerIntent == null) {
            throw new IllegalArgumentException("intent must not be null");
        }
        checkIsCalledFromMainThread();
        if (mConnection == null) { // first time connection
            mConnection = new Connection();

            Intent serviceIntent = new Intent(RecognitionService.SERVICE_INTERFACE);

            if (mServiceComponent == null) {
                String serviceComponent = Settings.Secure.getString(mContext.getContentResolver(),
                        Settings.Secure.VOICE_RECOGNITION_SERVICE);

                if (TextUtils.isEmpty(serviceComponent)) {
                    Log.e(TAG, "no selected voice recognition service");
                    mListener.onError(ERROR_CLIENT);
                    return;
                }

                serviceIntent.setComponent(ComponentName.unflattenFromString(serviceComponent));
            } else {
                serviceIntent.setComponent(mServiceComponent);
            }

            if (!mContext.bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE)) {
                Log.e(TAG, "bind to recognition service failed");
                mConnection = null;
                mService = null;
                mListener.onError(ERROR_CLIENT);
                return;
            }
        }
        putMessage(Message.obtain(mHandler, MSG_START, recognizerIntent));
    }

    /**
     * Stops listening for speech. Speech captured so far will be recognized as if the user had
     * stopped speaking at this point. Note that in the default case, this does not need to be
     * called, as the speech endpointer will automatically stop the recognizer listening when it
     * determines speech has completed. However, you can manipulate endpointer parameters directly
     * using the intent extras defined in {@link RecognizerIntent}, in which case you may sometimes
     * want to manually call this method to stop listening sooner. Please note that
     * {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise
     * no notifications will be received.
     */
    public void stopListening() {
        checkIsCalledFromMainThread();
        putMessage(Message.obtain(mHandler, MSG_STOP));
    }

    /**
     * Cancels the speech recognition. Please note that
     * {@link #setRecognitionListener(RecognitionListener)} should be called beforehand, otherwise
     * no notifications will be received.
     */
    public void cancel() {
        checkIsCalledFromMainThread();
        putMessage(Message.obtain(mHandler, MSG_CANCEL));
    }

    private static void checkIsCalledFromMainThread() {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            throw new RuntimeException(
                    "SpeechRecognizer should be used only from the application's main thread");
        }
    }

    private void putMessage(Message msg) {
        if (mService == null) {
            mPendingTasks.offer(msg);
        } else {
            mHandler.sendMessage(msg);
        }
    }

    /** sends the actual message to the service */
    private void handleStartListening(Intent recognizerIntent) {
        if (!checkOpenConnection()) {
            return;
        }
        try {
            mService.startListening(recognizerIntent, mListener);
            if (DBG) Log.d(TAG, "service start listening command succeded");
        } catch (final RemoteException e) {
            Log.e(TAG, "startListening() failed", e);
            mListener.onError(ERROR_CLIENT);
        }
    }

    /** sends the actual message to the service */
    private void handleStopMessage() {
        if (!checkOpenConnection()) {
            return;
        }
        try {
            mService.stopListening(mListener);
            if (DBG) Log.d(TAG, "service stop listening command succeded");
        } catch (final RemoteException e) {
            Log.e(TAG, "stopListening() failed", e);
            mListener.onError(ERROR_CLIENT);
        }
    }

    /** sends the actual message to the service */
    private void handleCancelMessage() {
        if (!checkOpenConnection()) {
            return;
        }
        try {
            mService.cancel(mListener);
            if (DBG) Log.d(TAG, "service cancel command succeded");
        } catch (final RemoteException e) {
            Log.e(TAG, "cancel() failed", e);
            mListener.onError(ERROR_CLIENT);
        }
    }

    private boolean checkOpenConnection() {
        if (mService != null) {
            return true;
        }
        mListener.onError(ERROR_CLIENT);
        Log.e(TAG, "not connected to the recognition service");
        return false;
    }

    /** changes the listener */
    private void handleChangeListener(RecognitionListener listener) {
        if (DBG) Log.d(TAG, "handleChangeListener, listener=" + listener);
        mListener.mInternalListener = listener;
    }

    /**
     * Destroys the {@code SpeechRecognizer} object.
     */
    public void destroy() {
        if (mConnection != null) {
            mContext.unbindService(mConnection);
        }
        mPendingTasks.clear();
        mService = null;
        mConnection = null;
        mListener.mInternalListener = null;
    }

    /**
     * Internal wrapper of IRecognitionListener which will propagate the results to
     * RecognitionListener
     */
    private class InternalListener extends IRecognitionListener.Stub {
        private RecognitionListener mInternalListener;

        private final static int MSG_BEGINNING_OF_SPEECH = 1;
        private final static int MSG_BUFFER_RECEIVED = 2;
        private final static int MSG_END_OF_SPEECH = 3;
        private final static int MSG_ERROR = 4;
        private final static int MSG_READY_FOR_SPEECH = 5;
        private final static int MSG_RESULTS = 6;
        private final static int MSG_PARTIAL_RESULTS = 7;
        private final static int MSG_RMS_CHANGED = 8;
        private final static int MSG_ON_EVENT = 9;

        private final Handler mInternalHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (mInternalListener == null) {
                    return;
                }
                switch (msg.what) {
                    case MSG_BEGINNING_OF_SPEECH:
                        mInternalListener.onBeginningOfSpeech();
                        break;
                    case MSG_BUFFER_RECEIVED:
                        mInternalListener.onBufferReceived((byte[]) msg.obj);
                        break;
                    case MSG_END_OF_SPEECH:
                        mInternalListener.onEndOfSpeech();
                        break;
                    case MSG_ERROR:
                        mInternalListener.onError((Integer) msg.obj);
                        break;
                    case MSG_READY_FOR_SPEECH:
                        mInternalListener.onReadyForSpeech((Bundle) msg.obj);
                        break;
                    case MSG_RESULTS:
                        mInternalListener.onResults((Bundle) msg.obj);
                        break;
                    case MSG_PARTIAL_RESULTS:
                        mInternalListener.onPartialResults((Bundle) msg.obj);
                        break;
                    case MSG_RMS_CHANGED:
                        mInternalListener.onRmsChanged((Float) msg.obj);
                        break;
                    case MSG_ON_EVENT:
                        mInternalListener.onEvent(msg.arg1, (Bundle) msg.obj);
                        break;
                }
            }
        };

        public void onBeginningOfSpeech() {
            Message.obtain(mInternalHandler, MSG_BEGINNING_OF_SPEECH).sendToTarget();
        }

        public void onBufferReceived(final byte[] buffer) {
            Message.obtain(mInternalHandler, MSG_BUFFER_RECEIVED, buffer).sendToTarget();
        }

        public void onEndOfSpeech() {
            Message.obtain(mInternalHandler, MSG_END_OF_SPEECH).sendToTarget();
        }

        public void onError(final int error) {
            Message.obtain(mInternalHandler, MSG_ERROR, error).sendToTarget();
        }

        public void onReadyForSpeech(final Bundle noiseParams) {
            Message.obtain(mInternalHandler, MSG_READY_FOR_SPEECH, noiseParams).sendToTarget();
        }

        public void onResults(final Bundle results) {
            Message.obtain(mInternalHandler, MSG_RESULTS, results).sendToTarget();
        }

        public void onPartialResults(final Bundle results) {
            Message.obtain(mInternalHandler, MSG_PARTIAL_RESULTS, results).sendToTarget();
        }

        public void onRmsChanged(final float rmsdB) {
            Message.obtain(mInternalHandler, MSG_RMS_CHANGED, rmsdB).sendToTarget();
        }

        public void onEvent(final int eventType, final Bundle params) {
            Message.obtain(mInternalHandler, MSG_ON_EVENT, eventType, eventType, params)
                    .sendToTarget();
        }
    }
}


text:
package org.testifyproject.fixture.locator;

/**
 *
 * @author saden
 */
public interface MultiImplmentationContract {

}


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>enhance (Rake::Task)</title>
  <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  <link rel="stylesheet" href="../../.././rdoc-style.css" type="text/css" media="screen" />

     # File lib/rake.rb, line 525
525:     def enhance(deps=nil, &block)
526:       @prerequisites |= deps if deps
527:       @actions << block if block_given?
528:       self
529:     end


text:
from rotamer.topology.residue_sidechains import amino_acids
import rotamer.dihedral.find_dihedrals as find_dihedrals
from rotamer.io.gmin import read_lowest
import rotamer.topology.read_amber_prmtop as ra
import numpy as np

class BaseRotamerState(object):
    """
    Base class for rotamer states for the GMIN rotamer library.
    """
    pass

class FullRotamerState(BaseRotamerState):
    """
    Defines a rotamer state for use with the GMIN rotamer library.

    A rotamer state corresponds to a single minimum from the rotamer library simulations. Each state has the values of
    all the dihedrals in the corresponding tripeptide and the energy (relative to the global minimum for that
    tripeptide).
    """
    pass

class RotamerStateFactory(object):
    """
    Creates new rotamer states, either from raw GMIN data or from a HDF5 database.
    """

    def from_lowest(self, prmtop_filename, lowest_filename, state_type):
        """
        Creates a new RotamerState of appropriate type from a GMIN lowest file.

        :param prmtop_filename: File name of the AMBER topology file
        :param lowest_filename: File name of the GMIN lowest file
        :param state_type: Type of rotamer state (i.e. what sort of dependence on neighbours, backbone dihedrals etc.)
        """
        molecule = ra.parse_topology_file(prmtop_filename)
        find_dihedrals.map_dihedrals(*(molecule.identify_residues()))
        self.configs = read_lowest(lowest_filename)
        find_dihedrals.phi_psi_dihedrals(molecule)
        find_dihedrals.sidechain_dihedrals(molecule)
        lowest0 = self.lowest_config_coords(0)
        lowest25 = self.lowest_config_coords(25)
        for res in sorted([res for res in molecule.residues.nodes() if res.name != "ACE" and res.name != "NME"],
                          key=lambda x: x.index):
            print "---------------"
            print res.name, res.index
            print "---------------"
            print "phi", res.dihedrals["phi"].measure_dihedral(lowest0) * 180.0 / np.pi
            print "psi", res.dihedrals["psi"].measure_dihedral(lowest0) * 180.0 / np.pi
            for dihedral, dihe_object in sorted([(k, v) for k, v in res.dihedrals.items() if 'chi' in k]):
                print dihedral, dihe_object.measure_dihedral(lowest0) * 180.0 / np.pi
            print ""
        for res in sorted([res for res in molecule.residues.nodes() if res.name != "ACE" and res.name != "NME"],
                          key=lambda x: x.index):
            print "---------------"
            print res.name, res.index
            print "---------------"
            print "phi", res.dihedrals["phi"].measure_dihedral(lowest25) * 180.0 / np.pi
            print "psi", res.dihedrals["psi"].measure_dihedral(lowest25) * 180.0 / np.pi
            for dihedral, dihe_object in sorted([(k, v) for k, v in res.dihedrals.items() if 'chi' in k]):
                print dihedral, dihe_object.measure_dihedral(lowest25) * 180.0 / np.pi
            print ""

    def lowest_config_coords(self, index):
        return self.configs[index]['coords']

def norm_lowest_configs(lowest_configs):
    global_min_energy = min([x["energy"] for x in lowest_configs])
    for config in lowest_configs:
        config["energy"] -= global_min_energy
    return global_min_energy

def lowest_to_dihedral_csv(prmtop_filename, lowest_filename, csv_filename):
    """
    Reads a topology and lowest filename and writes dihedral information to a csv file.

    The file has the following structure:

    <res_1>,<res_2>,<res_3>,...,<res_n>
    global minimum,<energy of global minimum>
    <res_1>,phi,psi,[chi_1],...,[chi_n]
    <res_2>,phi,psi,[chi_1],...,[chi_n]
    .
    .
    .
    <res_n>,phi,psi,[chi_1],...,[chi_n]
    <norm_energy_0>,<res_1_phi>,<res_1_psi>,[<res_1_chi_1>],...,<res_2_phi>,...,<res_n_phi>,...,[<res_n_chi_n>]
    <norm_energy_1>,<res_1_phi>,<res_1_psi>,[<res_1_chi_1>],...,<res_2_phi>,...,<res_n_phi>,...,[<res_n_chi_n>]
    .
    .
    .
    <norm_energy_N>,<res_1_phi>,<res_1_psi>,[<res_1_chi_1>],...,<res_2_phi>,...,<res_n_phi>,...,[<res_n_chi_n>]

    N.B. energies are given relative to the global minimum and angles are given in degrees in the order specified at the
    top of the file

    :param prmtop_filename: Amber topology filename
    :param lowest_filename: GMIN lowest filename
    :return:
    """
    import csv

    molecule = ra.parse_topology_file(prmtop_filename)
    find_dihedrals.map_dihedrals(*(molecule.identify_residues()))
    find_dihedrals.phi_psi_dihedrals(molecule)
    find_dihedrals.sidechain_dihedrals(molecule)
    lowest_configs = read_lowest(lowest_filename)
    res_no_termini = [res for res in sorted(molecule.residues.nodes(), key=lambda x: x.index)
                      if res.name != "ACE" and res.name != "NME"]
    with open(csv_filename, "w") as csv_file:
        dihe_writer = csv.writer(csv_file)
        dihe_writer.writerow(res_no_termini)
        global_min_energy = norm_lowest_configs(lowest_configs)
        dihe_writer.writerow(["global minimum", global_min_energy])
        ordered_dihe = []
        for res in res_no_termini:
            backbone = sorted([dihe for dihe in res.dihedrals if 'p' in dihe])
            sidechain = sorted([dihe for dihe in res.dihedrals if 'p' not in dihe])
            dihe_writer.writerow([res.name] + backbone + sidechain)
            ordered_dihe += [res.dihedrals[x] for x in backbone]
            ordered_dihe += [res.dihedrals[x] for x in sidechain]
        last_energy = 0.0
        for config in lowest_configs:
            energy = config["energy"]
            if (energy - last_energy) > 10.0:
                break
            angles = [x.measure_dihedral(config["coords"]) * 180.0 / np.pi for x in ordered_dihe]
            dihe_writer.writerow(["{:.8f}".format(energy)] + ["{: 9.4f}".format(angle) for angle in angles])
            last_energy = energy

if __name__ == "__main__":
    from rotamer.topology.residue_sidechains import amino_acids
    import itertools
    import os.path
    import time
    import sys
    now = time.time()
    # for comb in itertools.product(amino_acids, repeat=3):
    for comb in [('MET', 'CYS', 'HID')]:
        print comb, "{:.1f}s".format(time.time() - now)
        # lowest = os.path.join(directory, "lowest")
        # lowest_configs = read_lowest(lowest_filename)
        # global_min_energy = norm_lowest_configs(lowest_configs)
        # print "Number accessible:", len([1 for l in lowest_configs if l["energy"] < 5.0])
        # if not sys.argv[1] in comb[0]:
        #     continue
        # directory = os.path.join(os.path.curdir, *comb)
        directory = os.path.join("/scratch/khs26/rotamer_lib_igb2", *comb)
        prmtop = os.path.join(directory, "coords.prmtop")
        lowest = os.path.join(directory, "lowest")
        dihedral_csv = os.path.join("/home/khs26/rotamer_library", "dihedrals", "".join(("_".join(comb), ".csv")))
        lowest_to_dihedral_csv(prmtop, lowest, dihedral_csv)


text:
using System;
using System.Xml.Serialization;
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;

namespace JdSdk.Response.Address
{
    [Serializable]
    public class AreaListBeanVO : JdObject
    {
        [JsonProperty("id")]
        public Nullable<Int64> Id
        {
            get;
            set;
        }

        [JsonProperty("name")]
        public String Name
        {
            get;
            set;
        }

        [JsonProperty("is3cod")]
        public String Is3cod
        {
            get;
            set;
        }

        [JsonProperty("cod")]
        public Nullable<Boolean> Cod
        {
            get;
            set;
        }

    }

}


text:
INCLUDE(FindPkgConfig)
PKG_CHECK_MODULES(PC_CHANNELCODING channelcoding)

FIND_PATH(
    CHANNELCODING_INCLUDE_DIRS
    NAMES channelcoding/api.h
    HINTS $ENV{CHANNELCODING_DIR}/include
        ${PC_CHANNELCODING_INCLUDEDIR}
    PATHS ${CMAKE_INSTALL_PREFIX}/include
          /usr/local/include
          /usr/include
)

FIND_LIBRARY(
    CHANNELCODING_LIBRARIES
    NAMES gnuradio-channelcoding
    HINTS $ENV{CHANNELCODING_DIR}/lib
        ${PC_CHANNELCODING_LIBDIR}
    PATHS ${CMAKE_INSTALL_PREFIX}/lib
          ${CMAKE_INSTALL_PREFIX}/lib64
          /usr/local/lib
          /usr/local/lib64
          /usr/lib
          /usr/lib64
)

INCLUDE(FindPackageHandleStandardArgs)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(CHANNELCODING DEFAULT_MSG CHANNELCODING_LIBRARIES CHANNELCODING_INCLUDE_DIRS)
MARK_AS_ADVANCED(CHANNELCODING_LIBRARIES CHANNELCODING_INCLUDE_DIRS)


text:
layout: posts.liquid

title:   My fourth Blogpost
published_date:    2015-05-29 23:00:00 +0100
categories: [ foo ]
---
# {{ page.title }}

Hey there this is my first blogpost and this is super awesome.

My Blog is lorem ipsum like, yes it is..


text: Rails.application.config.session_store :cookie_store, key: '_demo_cache_angularjs_session'


text:
package org.taitasciore.android.hospitalk.review;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;

import org.taitasciore.android.hospitalk.ActivityUtils;
import org.taitasciore.android.hospitalk.R;
import org.taitasciore.android.hospitalk.StarUtils;
import org.taitasciore.android.model.Review;
import org.taitasciore.android.network.HospitalkApi;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by roberto on 19/04/17.
 */

public class ReviewDetailsFragment extends Fragment implements ReviewDetailsContract.View {

    private Review mReview;

    private ReviewDetailsContract.Presenter mPresenter;

    private ProgressDialog mDialog;

    @BindView(R.id.mainContent) LinearLayout mMainContent;

    @BindView(R.id.tvNombreServicio) TextView mTvServiceName;
    @BindView(R.id.tvCiudadServicio) TextView mTvServiceCity;
    @BindView(R.id.tvNombreHospital) TextView mTvHospitalName;
    @BindView(R.id.tvActividadHospital) TextView mTvHospitalActivity;
    @BindView(R.id.tvTelefono) TextView mTvPhone;
    @BindView(R.id.tvDireccion) TextView mTvAddress;
    @BindView(R.id.tvTituloOpinion) TextView mTvReviewTitle;
    @BindView(R.id.tvUsuario) TextView mTvUsername;
    @BindView(R.id.tvUbicacion) TextView mTvLocation;
    @BindView(R.id.tvFecha) TextView mTvDate;
    @BindView(R.id.tvNombreServicio2) TextView mTvServiceName2;
    @BindView(R.id.tvOpinion) TextView mTvReview;
    @BindView(R.id.lyAvg) LinearLayout mLyAvg;
    @BindView(R.id.img) SimpleDraweeView mImg;
    @BindView(R.id.btnRespuesta) Button mBtnRespuesta;
    @BindView(R.id.btnVotos) Button mBtnVotos;

    public static ReviewDetailsFragment newInstance(int id) {
        ReviewDetailsFragment f = new ReviewDetailsFragment();
        Bundle args = new Bundle();
        args.putInt("id", id);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_review_details, container, false);
        ButterKnife.bind(this, v);
        return v;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (mPresenter == null) mPresenter = new ReviewDetailsPresenter(this);
        else mPresenter.bindView(this);
    }

    @Override
    public void onDetach() {
        hideProgress();
        super.onDetach();
        if (mPresenter != null) mPresenter.unbindView();
    }

    @Override
    public void onResume() {
        super.onResume();

        if (mReview != null) {
            showReviewInfo(mReview);
            showMainContent();
        } else {
            mPresenter.getReview(getArguments().getInt("id"));
        }
    }

    @Override
    public void bindPresenter(ReviewDetailsContract.Presenter presenter) {
        mPresenter = presenter;
        mPresenter.bindView(this);
    }

    @Override
    public void showProgress() {
        mDialog = ActivityUtils.showProgressDialog(getActivity());
    }

    @Override
    public void hideProgress() {
        if (mDialog != null && mDialog.isShowing()) mDialog.dismiss();
    }

    @Override
    public void setReview(Review review) {
        mReview = review;
    }

    @Override
    public void showReviewInfo(Review review) {
        mReview = review;
        mTvServiceName.setText(review.getServiceName()+"");
        mTvServiceCity.setText(review.getServiceCityName()+"");
        mTvHospitalName.setText(review.getCompanyName()+"");
        mTvHospitalActivity.setText(review.getCompanyActivityName()+"");

        String phone = review.getCompanyPhone();
        if (phone == null || phone.isEmpty() || phone.equalsIgnoreCase("null")) {
            mTvPhone.setVisibility(View.GONE);
        } else {
            mTvPhone.setText(review.getCompanyPhone() + "");
        }

        String address = review.getCompanyAddress();
        if (address == null || address.isEmpty() || address.equalsIgnoreCase("null")) {
            mTvAddress.setVisibility(View.GONE);
        } else {
            mTvAddress.setText(review.getCompanyAddress()+"");
        }

        if (review.getRatingTitle() != null && !review.getRatingTitle().isEmpty()) {
            mTvReviewTitle.setText("\"" + review.getRatingTitle() + "\"");
        } else {
            mTvReviewTitle.setText("Título de opinión no disponible");
        }

        mTvUsername.setText(review.getUserName());
        mTvLocation.setText(review.getUserCityName() + ", " + review.getUserCountryName());
        mTvDate.setText(review.getDays());
        mTvServiceName2.setText(review.getServiceName());
        mTvReview.setText(review.getRatingReview());
        StarUtils.resetStars(mLyAvg);
        StarUtils.addStars(getActivity(), 5, mLyAvg);
        StarUtils.fillStars(getActivity(), review.getRatingValue(), mLyAvg);

        String imgUrl = HospitalkApi.BASE_URL + "user/image?id_user=" + review.getIdUser();
        mImg.setImageURI(Uri.parse(imgUrl));

        if (review.getCompanyAnswer() > 0) {
            mBtnRespuesta.setText("SÍ");
        } else {
            mBtnRespuesta.setText("NO");
        }
        setRepliesButtonBackground(mBtnRespuesta, review.getCompanyAnswer());

        mBtnVotos.setText(review.getRatingHelpfulVotes()+"");
    }

    @Override
    public void setRepliesButtonBackground(Button btn, int replies) {
        int bgColor;

        if (replies > 0) {
            bgColor = ContextCompat.getColor(getActivity(), R.color.colorPrimary);
        } else {
            bgColor = ContextCompat.getColor(getActivity(), R.color.colorPrimaryText);
        }

        btn.setBackgroundColor(bgColor);
    }

    @Override
    public void showMainContent() {
        mMainContent.setVisibility(View.VISIBLE);
    }

    @Override
    public void showNetworkError() {
        Toast.makeText(getActivity(), getString(R.string.network_error), Toast.LENGTH_SHORT).show();
        getActivity().onBackPressed();
    }

    @Override
    public void showNetworkFailedError() {
        Toast.makeText(getActivity(), getString(R.string.network_failed_error), Toast.LENGTH_SHORT).show();
        getActivity().onBackPressed();
    }

    @Override
    public void showReviewNotApprovedError() {
        Toast.makeText(getActivity(), getString(R.string.review_not_approved_error), Toast.LENGTH_SHORT).show();
        getActivity().onBackPressed();
    }
}


text:
#######################DISA INFORMATION##################################
# Group ID (Vulid): V-22596
# Group Title: GEN000000-LNX00530
# Rule ID: SV-26999r1_rule
# Severity: medium
# Rule Version (STIG-ID): GEN000000-LNX00530
# Rule Title: The /etc/sysctl.conf file must not have an extended ACL.
#
# Vulnerability Discussion: The sysctl.conf file specifies the values for
# kernel parameters to be set on boot.  These settings can affect the
# system's security.
#
# Responsibility: System Administrator
# IAControls: ECLP-1
#
# Check Content:
#
# Check the permissions of the file.

# ls -lL /etc/sysctl.conf

# If the permissions of the file or directory contain a '+', an extended
# ACL is present. If the file has an extended ACL and it has not been
# documented with the IAO, this is a finding.
#
# Fix Text:
#
# Remove the extended ACL from the file.
# setfacl --remove-all /etc/sysctl.conf
#######################DISA INFORMATION##################################

# Global Variables
PDI=GEN000000-LNX00530

# Start-Lockdown

if [ -a "/etc/sysctl.conf" ]
then
  ACLOUT=`getfacl --skip-base /etc/sysctl.conf 2>/dev/null`;
  if [ "$ACLOUT" != "" ]
  then
    setfacl --remove-all /etc/sysctl.conf
  fi
fi


text:
'use strict';

require(process.cwd() + '/packages/activists/server/models/activist');
require(process.cwd() + '/packages/organizations/server/models/organization');
require(process.cwd() + '/packages/events/server/models/event');

// Module dependencies.
var should = require('should'),
    async = require('async'),
    mongoose = require('mongoose'),
    User = mongoose.model('User'),
    Activist = mongoose.model('Activist'),
    Organization = mongoose.model('Organization'),
    Event = mongoose.model('Event');

describe('<Unit Test>', function() {

    describe('Event model:', function () {

        var user, activist, organization, theEvent;

        before(function (done) {

            // user

            user = new User({
                name: 'user',
                email: 'user@example.com',
                username: 'user',
                password: 'user'
            });

            organization = new Organization({
                user: user,
                title: 'user organization'
            });

            activist = new Activist({
                user: user,
                name: user.name
            });

            theEvent = new Event({
                user: user,
                title: 'user event',
                organization: organization,
                datetime: new Date(),
                status: Event.statuses[0]
            });

            // save user

            async.series([
                user.save.bind(user),
                activist.save.bind(activist),
                organization.save.bind(organization)
            ], done);

        });

        describe('event save', function() {

            it('should begin without the test event', function(done) {
                Event.find({id: theEvent._id}, function(err, events) {
                    should.not.exist(err);
                    events.should.have.length(0);
                    done();
                });
            });

            it('should be able to save event without problems', function(done) {
                theEvent.save(function (err) {
                    should.not.exist(err);
                    done();
                });
            });

            it('should show an error when try to save event without title', function(done) {
                Event.find({_id: theEvent._id}, function(err, events) {
                    events.should.have.length(1);
                    events[0].title = '';
                    events[0].save(function (err) {
                        should.exist(err);
                        err.name.should.be.equal('ValidationError');
                        done();
                    });
                });
            });

            it('should be able to save updated event without problems', function(done) {
                Event.find({_id: theEvent._id}, function(err, events) {
                    events.should.have.length(1);
                    events[0].title = 'user event updated';
                    events[0].save(function (err) {
                        should.not.exist(err);
                        done();
                    });
                });
            });
        });

        after(function(done) {
            async.series([
                user.remove.bind(user),
                activist.remove.bind(activist),
                organization.remove.bind(organization),
                theEvent.remove.bind(theEvent)
            ], function () {
                done();
            });
        });

    });

});


text:
#import <Foundation/NSObject.h>

@class NSDate;

NS_ASSUME_NONNULL_BEGIN

@protocol NSLocking

- (void)lock;
- (void)unlock;

@end

@interface NSLock : NSObject <NSLocking> {
@private
    void *_priv;
}

- (BOOL)tryLock;
- (BOOL)lockBeforeDate:(NSDate *)limit;

@property (nullable, copy) NSString *name NS_AVAILABLE(10_5, 2_0);

@end

@interface NSConditionLock : NSObject <NSLocking> {
@private
    void *_priv;
}

- (instancetype)initWithCondition:(NSInteger)condition NS_DESIGNATED_INITIALIZER;

@property (readonly) NSInteger condition;
- (void)lockWhenCondition:(NSInteger)condition;
- (BOOL)tryLock;
- (BOOL)tryLockWhenCondition:(NSInteger)condition;
- (void)unlockWithCondition:(NSInteger)condition;
- (BOOL)lockBeforeDate:(NSDate *)limit;
- (BOOL)lockWhenCondition:(NSInteger)condition beforeDate:(NSDate *)limit;

@property (nullable, copy) NSString *name NS_AVAILABLE(10_5, 2_0);

@end

@interface NSRecursiveLock : NSObject <NSLocking> {
@private
    void *_priv;
}

- (BOOL)tryLock;
- (BOOL)lockBeforeDate:(NSDate *)limit;

@property (nullable, copy) NSString *name NS_AVAILABLE(10_5, 2_0);

@end

NS_CLASS_AVAILABLE(10_5, 2_0)
@interface NSCondition : NSObject <NSLocking> {
@private
    void *_priv;
}

- (void)wait;
- (BOOL)waitUntilDate:(NSDate *)limit;
- (void)signal;
- (void)broadcast;

@property (nullable, copy) NSString *name NS_AVAILABLE(10_5, 2_0);

@end

NS_ASSUME_NONNULL_END


text:
<?php

namespace ws\loewe\Woody\Components\Controls;

use \ws\loewe\Woody\App\TestApplication;
use \ws\loewe\Woody\Components\Timer\Timer;
use \ws\loewe\Utils\Geom\Point;
use \ws\loewe\Utils\Geom\Dimension;

/**
 * Test class for PushButton.
 * Generated by PHPUnit on 2011-12-15 at 22:14:10.
 */
class PushButtonTest extends \PHPUnit_Framework_TestCase {

  /**
   * the push button to test
   *
   * @var \ws\loewe\Woody\Components\Controls\PushButton
   */
  private $pushButton = null;

  /**
   * the test application
   *
   * @var \ws\loewe\Woody\App\TestApplication
   */
  private $application = null;

  /**
   * the timer for the test application
   *
   * @var \ws\loewe\Woody\Components\Timer\Timer
   */
  private $timer = null;

  /**
   * Sets up the fixture, for example, opens a network connection.
   * This method is called before a test is executed.
   */
  protected function setUp() {
    $this->application = new TestApplication();

    $this->pushButton = new PushButton('buttonLabel', Point::createInstance(20, 20), Dimension::createInstance(80, 20));

    $this->application->getWindow()->getRootPane()->add($this->pushButton);
  }

  /**
   * Tears down the fixture, for example, closes a network connection.
   * This method is called after a test is executed.
   */
  protected function tearDown() {
  }

  /**
   * @covers \ws\loewe\Woody\Components\Controls\PushButton::getLabel
   * @covers \ws\loewe\Woody\Components\Controls\PushButton::setLabel
   */
  public function testGetSetLabel() {
    $this->timer = new Timer(function() {
                              $this->assertEquals('buttonLabel', $this->pushButton->getLabel());

                              $this->pushButton->setLabel('pushButtonNew');
                              $this->assertEquals('pushButtonNew', $this->pushButton->getLabel());

                              $this->timer->destroy();
                              $this->application->stop();
                            }, $this->application->getWindow(), Timer::TEST_TIMEOUT);

    $this->timer->start();

    $this->application->start();
  }
}


text:
  Ranzières est
       un village
       situé dans le département de Meuse en Lorraine. Elle comptait 66 habitants en 2008.

Le parc de logements, à Ranzières, se décomposait en 2011 en deux appartements et 50 maisons soit
 un marché relativement équilibré.

Si vous pensez venir habiter à Ranzières, vous pourrez aisément trouver une maison à acheter.

À coté de Ranzières sont positionnées géographiquement les villes de
Villers-sur-Meuse localisée à 5 km, 219 habitants,
Lacroix-sur-Meuse à 5 km, 684 habitants,
Ambly-sur-Meuse à 3 km, 267 habitants,
Tilly-sur-Meuse à 4 km, 247 habitants,
Rupt-en-Woëvre localisée à 3 km, 303 habitants,
Génicourt-sur-Meuse localisée à 4 km, 272 habitants,
 entre autres. De plus, Ranzières est située à seulement 17 km de Verdun.