text:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Data;
using ArchiveStation.Bean;
using Newtonsoft.Json;

namespace ArchiveStation
{
    /// <summary>
    /// 打印管理类
    /// </summary>
    public class PrintManager
    {
        /// <summary>
        /// 打印模板文件夹路径
        /// </summary>
        protected string _reportFolder = Application.StartupPath + "\\Templete" ;

        protected string Report_借阅单
        {
            get
            {
                string path = _reportFolder + "\\借阅单.frx";
                return path;
            }
        }

        private static PrintManager _single = null;
        private PrintManager()
        {
            //设置FastReport 打印时不显示进度框
            FastReport.Utils.Config.ReportSettings.ShowProgress = false;
            FastReport.Utils.Config.ReportSettings.ShowPerformance = false;
        }

        public static PrintManager Single
        {
            get
            {
                if (_single == null)
                {
                    _single = new PrintManager();
                }
                return _single;
            }
        }
        /// <summary>
        /// 模板设计器
        /// </summary>
        //public void Desinger(string hospitalId, string hospitalName)
        //{
        //    FormDesigner form = new FormDesigner(hospitalId, hospitalName);
        //    form.Show();
        //}

        public int Print_Borrow(List<PrintBorrowBean> list )
        {
            try
            {
                if (list == null || list.Count < 1) return -2;
                if (System.IO.File.Exists(Report_借阅单) == false) return -1;

                foreach (PrintBorrowBean entity in list)
                {
                    FastReport.Report report = new FastReport.Report();
                    report.Load(Report_借阅单);
                    SetParameters<BorrowerBean , ArchiveBean>(entity.Borrower , entity.ArchiveList , report);
                    PrintReport(report);
                }
                return list.Count;
            }
            catch (System.Drawing.Printing.InvalidPrinterException pex)
            {
                return -4;
            }
            catch (Exception ex)
            {
                return -3;
            }
        }

        /// <summary>
        /// 预览 挂号单
        /// </summary>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public int Preview_Borrow(List<PrintBorrowBean> list)
        {
            try
            {
                if (list == null || list.Count < 1) return -2;
                if (System.IO.File.Exists(Report_借阅单) == false) return -1;

                FormPreview form = new FormPreview(list, Report_借阅单);
                form.ShowDialog();
                return 0;

            }
            catch (System.Drawing.Printing.InvalidPrinterException pex)
            {
                LogHelper.WriteException(pex);
                return -4;
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex);
                return -3;
            }
        }

        /// <summary>
        /// 打印预览时,屏蔽打印功能,返回 0张页数
        /// </summary>
        /// <param name="report"></param>
        /// <returns></returns>
        protected int PreviewReport(FastReport.Report report)
        {
            try
            {
                //PreviewForm.Report = report;
                //PreviewForm.ShowDialog();
                return 0;
            }
            catch (Exception ex)
            {
                string msg = ex.Message;
                return -3;
            }
        }

        protected int PrintReport(FastReport.Report report)
        {
            //report.PrintPrepared();
            //report.Prepare();
            //int pagecount = report.PreparedPages.Count;

            //LogHelper.WriteLog("FastReport ShowProgress:" + FastReport.Utils.Config.ReportSettings.ShowProgress);
            //FastReport.Utils.Config.ReportSettings.ShowProgress = false;
            //LogHelper.WriteLog("FastReport ShowProgress:" + FastReport.Utils.Config.ReportSettings.ShowProgress);
            //LogHelper.WriteLog("FastReport WebModel:" + FastReport.Utils.Config.WebMode);
            //FastReport.Utils.Config.WebMode = true;
            //LogHelper.WriteLog("FastReport WebModel:" + FastReport.Utils.Config.WebMode);
            //LogHelper.WriteLog("FastReport ShowPerformance:" + FastReport.Utils.Config.ReportSettings.ShowPerformance);
            //LogHelper.WriteLog("FastReport UseFileCache:" + report.UseFileCache);

            report.PrintSettings.ShowDialog = false;
            System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            report.Print();

            watch.Stop();
            LogHelper.WriteLog("pring() time:" + watch.ElapsedMilliseconds / 1000.00);

            report.Clear();
            report.Dispose();
            report = null;
            //return pagecount;
            return 1;
        }

        protected T GetEntity<T>(string jsonString)
        {
            T entity = default(T);
            try
            {
                entity = JsonConvert.DeserializeObject<T>(jsonString);
                return entity;
            }
            catch
            {
                //return -2;
                return default(T);
            }
        }

        protected List<T> GetEntityList<T>(string jsonString)
        {
            try
            {
                List<T> list = JsonConvert.DeserializeObject<List<T>>(jsonString);
                return list;
            }
            catch( Exception ex )
            {
                LogHelper.WriteException(ex);
                return null;
            }
        }

        protected void SetParameters<T, H>(T patient, IList<H> chargeItem, FastReport.Report report)
        {
            System.Reflection.PropertyInfo[] properties = patient.GetType().GetProperties();
            foreach (System.Reflection.PropertyInfo info in properties)
            {
                string name = info.Name;
                object value = info.GetValue(patient, null);
                if (report.Parameters.FindByName(name) != null)
                {
                    report.SetParameterValue(name, value);
                }
            }
            System.Data.DataTable dt = ToDataTable<H>(chargeItem);
            dt.TableName = "detail";
            report.RegisterData(dt, "detail");
        }

        /// <summary>
        /// 将List转换成DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data"></param>
        /// <returns></returns>
        public static DataTable ToDataTable<T>(IList<T> data)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
            DataTable dt = new DataTable();
            for (int i = 0; i < properties.Count; i++)
            {
                PropertyDescriptor property = properties[i];
                dt.Columns.Add(property.Name, property.PropertyType);
            }
            object[] values = new object[properties.Count];
            foreach (T item in data)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = properties[i].GetValue(item);
                }
                dt.Rows.Add(values);
            }
            return dt;
        }

    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sun.syndication.feed.synd.impl;

import com.sun.syndication.feed.WireFeed;
import com.sun.syndication.feed.atom.Content;
import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
import com.sun.syndication.feed.atom.Link;
import com.sun.syndication.feed.atom.Person;
import com.sun.syndication.feed.module.impl.ModuleUtils;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.Converter;
import com.sun.syndication.feed.synd.SyndEnclosure;
import com.sun.syndication.feed.synd.SyndEnclosureImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndContent;
import com.sun.syndication.feed.synd.SyndLink;
import com.sun.syndication.feed.synd.SyndLinkImpl;
import com.sun.syndication.feed.synd.SyndPerson;
import com.sun.syndication.feed.synd.SyndPersonImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Date;
import java.util.Iterator;

/**
 */
public class ConverterForAtom03 implements Converter {
    private String _type;

    public ConverterForAtom03() {
        this("atom_0.3");
    }

    protected ConverterForAtom03(String type) {
        _type = type;
    }

    public String getType() {
        return _type;
    }

    public void copyInto(WireFeed feed,SyndFeed syndFeed) {
        Feed aFeed = (Feed) feed;

        syndFeed.setModules(ModuleUtils.cloneModules(aFeed.getModules()));

        if (((List)feed.getForeignMarkup()).size() > 0) {
            syndFeed.setForeignMarkup(feed.getForeignMarkup());
        }

        syndFeed.setEncoding(aFeed.getEncoding());

        syndFeed.setUri(aFeed.getId());

        syndFeed.setTitle(aFeed.getTitle());

        // use first alternate links as THE link
        if (aFeed.getAlternateLinks() != null
                && aFeed.getAlternateLinks().size() > 0) {
            Link theLink = (Link)aFeed.getAlternateLinks().get(0);
            syndFeed.setLink(theLink.getHrefResolved());
        }
        // lump alternate and other links together
        List syndLinks = new ArrayList();
        if (aFeed.getAlternateLinks() != null
                && aFeed.getAlternateLinks().size() > 0) {
            syndLinks.addAll(createSyndLinks(aFeed.getAlternateLinks()));
        }
        if (aFeed.getOtherLinks() != null
                && aFeed.getOtherLinks().size() > 0) {
            syndLinks.addAll(createSyndLinks(aFeed.getOtherLinks()));
        }
        syndFeed.setLinks(syndLinks);

        Content tagline = aFeed.getTagline();
        if (tagline!=null) {
            syndFeed.setDescription(tagline.getValue());
        }

        List aEntries = aFeed.getEntries();
        if (aEntries!=null) {
            syndFeed.setEntries(createSyndEntries(aEntries, syndFeed.isPreservingWireFeed()));
        }

        // Core Atom language/author/copyright/modified elements have precedence
        // over DC equivalent info.

        String language = aFeed.getLanguage();
        if (language!=null) {
            syndFeed.setLanguage(language);
        }

        List authors = aFeed.getAuthors();
        if (authors!=null && authors.size() > 0) {
            syndFeed.setAuthors(createSyndPersons(authors));
        }

        String copyright = aFeed.getCopyright();
        if (copyright!=null) {
            syndFeed.setCopyright(copyright);
        }

        Date date = aFeed.getModified();
        if (date!=null) {
            syndFeed.setPublishedDate(date);
        }

    }

    protected List createSyndLinks(List aLinks) {
        ArrayList sLinks = new ArrayList();
        for (Iterator iter = aLinks.iterator(); iter.hasNext();) {
            Link link = (Link)iter.next();
            if (!link.getRel().equals("enclosure")) {
                SyndLink sLink = createSyndLink(link);
                sLinks.add(sLink);
            }
        }
        return sLinks;
    }

    public SyndLink createSyndLink(Link link) {
        SyndLink syndLink = new SyndLinkImpl();
        syndLink.setRel(     link.getRel());
        syndLink.setType(    link.getType());
        syndLink.setHref(    link.getHrefResolved());
        syndLink.setTitle(   link.getTitle());
        return syndLink;
    }

    protected List createSyndEntries(List atomEntries, boolean preserveWireItems) {
        List syndEntries = new ArrayList();
        for (int i=0;i<atomEntries.size();i++) {
            syndEntries.add(createSyndEntry((Entry) atomEntries.get(i), preserveWireItems));
        }
        return syndEntries;
    }

    protected SyndEntry createSyndEntry(Entry entry, boolean preserveWireItem) {
        SyndEntryImpl syndEntry = new SyndEntryImpl();
        if (preserveWireItem) {
        	syndEntry.setWireEntry(entry);
        }

        syndEntry.setModules(ModuleUtils.cloneModules(entry.getModules()));

        if (((List)entry.getForeignMarkup()).size() >  0) {
            syndEntry.setForeignMarkup((List)entry.getForeignMarkup());
        }

        syndEntry.setTitle(entry.getTitle());

        // if there is exactly one alternate link, use that as THE link
        if (entry.getAlternateLinks() != null
				&& entry.getAlternateLinks().size() == 1) {
            Link theLink = (Link)entry.getAlternateLinks().get(0);
            syndEntry.setLink(theLink.getHrefResolved());
        }

        // Create synd enclosures from enclosure links
        List syndEnclosures = new ArrayList();
        if (entry.getOtherLinks() != null && entry.getOtherLinks().size() > 0) {
            List oLinks = entry.getOtherLinks();
            for (Iterator iter = oLinks.iterator(); iter.hasNext(); ) {
                Link thisLink = (Link)iter.next();
                if ("enclosure".equals(thisLink.getRel()))
                    syndEnclosures.add(createSyndEnclosure(entry, thisLink));
            }
        }
        syndEntry.setEnclosures(syndEnclosures);

        // lump alternate and other links together
        List syndLinks = new ArrayList();
        if (entry.getAlternateLinks() != null
                && entry.getAlternateLinks().size() > 0) {
            syndLinks.addAll(createSyndLinks(entry.getAlternateLinks()));
        }
        if (entry.getOtherLinks() != null
                && entry.getOtherLinks().size() > 0) {
            syndLinks.addAll(createSyndLinks(entry.getOtherLinks()));
        }
        syndEntry.setLinks(syndLinks);

        String id = entry.getId();
        if (id!=null) {
            syndEntry.setUri(entry.getId());
        }
        else {
            syndEntry.setUri(syndEntry.getLink());
        }

        Content content = entry.getSummary();
        if (content==null) {
            List contents = entry.getContents();
            if (contents!=null && contents.size()>0) {
                content = (Content) contents.get(0);
            }
        }
        if (content!=null) {
            SyndContent sContent = new SyndContentImpl();
            sContent.setType(content.getType());
            sContent.setValue(content.getValue());
            syndEntry.setDescription(sContent);
        }

        List contents = entry.getContents();
        if (contents.size()>0) {
            List sContents = new ArrayList();
            for (int i=0;i<contents.size();i++) {
                content = (Content) contents.get(i);
                SyndContent sContent = new SyndContentImpl();
                sContent.setType(content.getType());
                sContent.setValue(content.getValue());
                sContent.setMode(content.getMode());
                sContents.add(sContent);
            }
            syndEntry.setContents(sContents);
        }

        List authors = entry.getAuthors();
        if (authors!=null && authors.size() > 0) {
            syndEntry.setAuthors(createSyndPersons(authors));
            SyndPerson person0 = (SyndPerson)syndEntry.getAuthors().get(0);
            syndEntry.setAuthor(person0.getName());
        }

        Date date = entry.getModified();
        if (date==null) {
            date = entry.getIssued();
            if (date==null) {
                date = entry.getCreated();
            }
        }
        if (date!=null) {
            syndEntry.setPublishedDate(date);
        }

        return syndEntry;
    }

    public SyndEnclosure createSyndEnclosure(Entry entry, Link link) {
        SyndEnclosure syndEncl = new SyndEnclosureImpl();
        syndEncl.setUrl(link.getHrefResolved());
        syndEncl.setType(link.getType());
        syndEncl.setLength(link.getLength());
        return syndEncl;
    }

    public WireFeed createRealFeed(SyndFeed syndFeed) {
        Feed aFeed = new Feed(getType());
        aFeed.setModules(ModuleUtils.cloneModules(syndFeed.getModules()));

        aFeed.setEncoding(syndFeed.getEncoding());

        aFeed.setId(syndFeed.getUri());

        SyndContent sTitle = syndFeed.getTitleEx();
        if (sTitle != null) {
            Content title = new Content();
            if (sTitle.getType() != null) {
                title.setType(sTitle.getType());
            }

            if (sTitle.getMode() != null) {
                title.setMode(sTitle.getMode());
            }

            title.setValue(sTitle.getValue());
            aFeed.setTitleEx(title);
        }

        // separate SyndEntry's links collection into alternate and other links
        List alternateLinks = new ArrayList();
        List otherLinks = new ArrayList();
        List slinks = syndFeed.getLinks();
        if (slinks != null) {
            for (Iterator iter=slinks.iterator(); iter.hasNext();) {
                SyndLink syndLink = (SyndLink)iter.next();
                Link link = createAtomLink(syndLink);
                if (link.getRel() == null ||
                        "".equals(link.getRel().trim()) ||
                        "alternate".equals(link.getRel())) {
                    alternateLinks.add(link);
                } else {
                    otherLinks.add(link);
                }
            }
        }
        // no alternate link? then use THE link if there is one
        if (alternateLinks.size() == 0 && syndFeed.getLink() != null) {
            Link link = new Link();
            link.setRel("alternate");
            link.setHref(syndFeed.getLink());
            alternateLinks.add(link);
        }

        if (alternateLinks.size() > 0) aFeed.setAlternateLinks(alternateLinks);
        if (otherLinks.size() > 0) aFeed.setOtherLinks(otherLinks);

        String sDesc = syndFeed.getDescription();
        if (sDesc!=null) {
            Content tagline = new Content();
            tagline.setValue(sDesc);
            aFeed.setTagline(tagline);
        }

        aFeed.setLanguage(syndFeed.getLanguage());

        List authors = syndFeed.getAuthors();
        if (authors!=null && authors.size() > 0) {
            aFeed.setAuthors(createAtomPersons(authors));
        }

        aFeed.setCopyright(syndFeed.getCopyright());

        aFeed.setModified(syndFeed.getPublishedDate());

        List sEntries = syndFeed.getEntries();
        if (sEntries!=null) {
            aFeed.setEntries(createAtomEntries(sEntries));
        }

        return aFeed;
    }

    protected static List createAtomPersons(List sPersons) {
        List persons = new ArrayList();
        for (Iterator iter = sPersons.iterator(); iter.hasNext(); ) {
            SyndPerson sPerson = (SyndPerson)iter.next();
            Person person = new Person();
            person.setName(sPerson.getName());
            person.setUri(sPerson.getUri());
            person.setEmail(sPerson.getEmail());
            person.setModules(sPerson.getModules());
            persons.add(person);
        }
        return persons;
    }

    protected static List createSyndPersons(List aPersons) {
        List persons = new ArrayList();
        for (Iterator iter = aPersons.iterator(); iter.hasNext(); ) {
            Person aPerson = (Person)iter.next();
            SyndPerson person = new SyndPersonImpl();
            person.setName(aPerson.getName());
            person.setUri(aPerson.getUri());
            person.setEmail(aPerson.getEmail());
            person.setModules(aPerson.getModules());
            persons.add(person);
        }
        return persons;
    }

    protected List createAtomEntries(List syndEntries) {
        List atomEntries = new ArrayList();
        for (int i=0;i<syndEntries.size();i++) {
            atomEntries.add(createAtomEntry((SyndEntry)syndEntries.get(i)));
        }
        return atomEntries;
    }

    protected Entry createAtomEntry(SyndEntry sEntry) {
        Entry aEntry = new Entry();
        aEntry.setModules(ModuleUtils.cloneModules(sEntry.getModules()));

        aEntry.setId(sEntry.getUri());

        SyndContent sTitle = sEntry.getTitleEx();
        if (sTitle!=null) {
            Content title = new Content();
            if (sTitle.getType() != null) {
                title.setType(sTitle.getType());
            }

            if (sTitle.getMode() != null) {
                title.setMode(sTitle.getMode());
            }

            title.setValue(sTitle.getValue());
            aEntry.setTitleEx(title);
        }

        // separate SyndEntry's links collection into alternate and other links
        List alternateLinks = new ArrayList();
        List otherLinks = new ArrayList();
        List slinks = sEntry.getLinks();
        if (slinks != null) {
            for (Iterator iter=slinks.iterator(); iter.hasNext();) {
                SyndLink syndLink = (SyndLink)iter.next();
                Link link = createAtomLink(syndLink);
                if (link.getRel() == null ||
                        "".equals(link.getRel().trim()) ||
                        "alternate".equals(link.getRel())) {
                    alternateLinks.add(link);
                } else {
                    otherLinks.add(link);
                }
            }
        }
        // no alternate link? then use THE link if there is one
        if (alternateLinks.size() == 0 && sEntry.getLink() != null) {
            Link link = new Link();
            link.setRel("alternate");
            link.setHref(sEntry.getLink());
            alternateLinks.add(link);
        }

        List sEnclosures = sEntry.getEnclosures();
        if (sEnclosures != null) {
            for (Iterator iter=sEnclosures.iterator(); iter.hasNext();) {
                SyndEnclosure syndEnclosure = (SyndEnclosure) iter.next();
                Link link = createAtomEnclosure(syndEnclosure);
                otherLinks.add(link);
            }
        }

        if (alternateLinks.size() > 0) aEntry.setAlternateLinks(alternateLinks);
        if (otherLinks.size() > 0) aEntry.setOtherLinks(otherLinks);

        SyndContent sContent = sEntry.getDescription();
        if (sContent!=null) {
            Content content = new Content();
            content.setType(sContent.getType());
            content.setValue(sContent.getValue());
            content.setMode(Content.ESCAPED);
            aEntry.setSummary(content);
        }

        List contents = sEntry.getContents();
        if (contents.size()>0) {
            List aContents = new ArrayList();
            for (int i=0;i<contents.size();i++) {
                sContent = (SyndContentImpl) contents.get(i);
                Content content = new Content();
                content.setType(sContent.getType());
                content.setValue(sContent.getValue());
                content.setMode(sContent.getMode());
                aContents.add(content);

            }
            aEntry.setContents(aContents);
        }

        List sAuthors = sEntry.getAuthors();
        if (sAuthors!=null && sAuthors.size() > 0) {
            aEntry.setAuthors(createAtomPersons(sAuthors));
        } else if (sEntry.getAuthor() != null) {
            Person person = new Person();
            person.setName(sEntry.getAuthor());
            List authors = new ArrayList();
            authors.add(person);
            aEntry.setAuthors(authors);
        }

        aEntry.setModified(sEntry.getPublishedDate());
        aEntry.setIssued(sEntry.getPublishedDate());

        return aEntry;
    }

    public Link createAtomLink(SyndLink syndLink) {
        Link link = new Link();
        link.setRel(     syndLink.getRel());
        link.setType(    syndLink.getType());
        link.setHref(    syndLink.getHref());
        link.setTitle(   syndLink.getTitle());
        return link;
    }

    public Link createAtomEnclosure(SyndEnclosure syndEnclosure) {
      Link link = new Link();
      link.setRel(     "enclosure");
      link.setType(    syndEnclosure.getType());
      link.setHref(    syndEnclosure.getUrl());
      link.setLength(  syndEnclosure.getLength());
      return link;
    }

}


text:
Class.define = Class.Define;
Class.create = Class.Create;
Class.getByName = Class.GetByName;
Class.CustomizeSyntax({
	GetClassUid: 'getClassUid',
	GetInstanceUid: 'getInstanceUid',
	Inherited: 'inherited',
	Extend: 'extend',
	Static: 'static',
	// for 'constructor' is not possible to use javascript
	// build in function property 'constructor', use different:
	Constructor: 'construct',
	// for 'name' is not possible to use javascript
	// build in 'Function.name' property, use different:
	Name: 'className',
	Fullname: 'classFullname',
	Namespace: 'classNamespace',
	static: 'static',
	self: 'self',
	parent: 'parent'
});

// Declare named class by Class.Define(...)
// call into global memory space as 'Animal'
Class.define('Animal', {
	static: {
		getInstance: function () {
			// this.static contains a child class definition
			// as later static binding in PHP normaly works
			return new this.static(arguments);
		}
	},
	construct: function (name, sound) {
		this.name = name;
		this.sound = sound;
	},
	name: '',
	sound: '',
	makeNoise: function () {
		console.log(this.sound);
	},
	introduceYourself: function () {
		console.log(
			"People call me '{0}'.".format(this.name)
		);
	},
	defineYourself: function () {
		console.log(
			"Globaly, I'm an '{0}'.".format(this.self.className)
			+ "\n" +
			"More precisely, I'm a '{0}'.".format(this.static.className)
			+ "\n" +
			"I belong to namespace '{0}'.".format(this.static.classNamespace)
			+ "\n" +
			"My full description is '{0}'.".format(this.static.classFullname)
		);
	},
	tellYourStory: function () {
		this.makeNoise();
		this.defineYourself();
	}
});

// Declare named classes by Class.Define(...) call
// into global memory space as 'Animal.Dog' and 'Animal.Cat'
// as extended classes from 'Animal' class.
Class.define('Animal.Dog', {
	extend: Animal,
	tellYourStory: function () {
		this.makeNoise();
		this.introduceYourself();
		this.defineYourself();
		console.log("But I'm the best friend of human.")
	}
});
Class.define('Animal.Cat', {
	extend: Animal,
	tellYourStory: function () {
		this.makeNoise();
		this.introduceYourself();
		this.defineYourself();
		console.log(
			"I don't care about people, but sometimes \n" +
			"they have something very good to eat."
		);
	}
});

// Create instances:
var creature = Class.create("Animal", "Creature", "Rrroooaaarrr!")
var dog = new Animal.Dog("Charlie", "Wrr haf!");
var cat = Animal.Cat.getInstance('Suzy', 'Pchchchchch!');

// 'Rrroooaaarrr!'

// Globaly, I'm an 'Animal'.
// More precisely, I'm a 'Animal'.
// I belong to namespace ''.
// My full description is 'Animal'.
creature.tellYourStory();

console.log("-------------------");

// 'Wrr haf!'
// People call me 'Charlie'.

// Globaly, I'm an 'Animal'.
// More precisely, I'm a 'Dog'.
// I live between 'Animal'.
// My type is 'Animal.Dog'.

// But the best friend of human.
dog.tellYourStory();

console.log("-------------------");

// Pchchchchch! [String]
// People call me 'Suzy'. [String]

// Globaly, I'm an 'Animal'.
// More precisely, I'm a 'Cat'.
// I live between 'Animal'.
// My type is 'Animal.Cat'. [String]

// I don't care about people, but sometimes
// they have something very good to eat.
cat.tellYourStory();

console.log("-------------------");

console.log(dog instanceof Animal); // true
console.log(dog instanceof Animal.Dog); // true
console.log(dog instanceof Animal.Cat); // false
console.log(dog instanceof Date); // false

console.log("-------------------");

console.log(dog.static.className); // 'Dog'
console.log(dog.static.classFullname); // 'Animal.Dog'
console.log(dog.static.classNamespace); // 'Animal'
console.log(dog.static.extend.className); // 'Animal'
console.log(dog.static.extend.classFullname); // 'Animal'
console.log(dog.static.extend.classNamespace); // ''

console.log("-------------------");

console.log(dog.static === Animal.Dog); // true
console.log(dog.static.extend === Animal); // true
console.log(dog.static.prototype === Animal.Dog.prototype); // true
console.log(dog.static.extend.prototype === Animal.prototype); // true

console.log("-------------------");

console.log(typeof Animal.Dog); // 'function'
console.log(typeof dog); // 'object'
console.log(dog.toString()); // '[object Animal.Dog]'


text:
package com.inari.commons.lang.indexed;

public abstract class IndexedTypeKey extends BaseIndexedObject implements IIndexedTypeKey {

    public final Class<? extends IndexedType> indexedType;

    protected IndexedTypeKey( Class<? extends IndexedType> indexedType ) {
        super();
        this.indexedType = indexedType;
        aspectGroup().createAspect( name(), index() );
    }

    @Override
    public final Class<? extends IndexedTypeKey> indexedObjectType() {
        return this.getClass();
    }

    @SuppressWarnings( "unchecked" )
    @Override
    public final <T> Class<T> type() {
        return (Class<T>) indexedType;
    }

    @Override
    public final String name() {
        return indexedType.getName().replace( ".", "_" );
    }

    @Override
    public String toString() {
        return indexedObjectType().getSimpleName() + " [indexedType=" + indexedType + ", index=" + index + "]";
    }

    final void disable() {
        aspectGroup().disposeAspect( index() );
        index = -1;
    }

    final void enable( int index ) {
        this.index = index;
        aspectGroup().createAspect( name(), index() );
    }

}


text:
<?php
/**
 * Created by PhpStorm.
 * User: Jan
 * Date: 17.03.2015
 * Time: 17:03
 */
namespace AppBundle\Repository;

use Doctrine\ORM\EntityRepository;

class ThreadRepository extends EntityRepository
{
    public function findAllOrderedByLastModifiedDate($category_id)
    {
        $repository = $this->getEntityManager()
            ->getRepository('AppBundle:Thread');

        $query = $repository->createQueryBuilder('t')
            ->where("t.category = :id")
            ->setParameter('id', $category_id)
            ->orderBy('t.last_modified_date', 'desc')
            ->getQuery();
        return $query;
    }

    public function findAllPostsOrderedById($thread_id)
    {
        $repository = $this->getEntityManager()
            ->getRepository('AppBundle:Post');

        $query = $repository->createQueryBuilder('p')
            ->where("p.thread = :id")
            ->setParameter('id', $thread_id)
            ->getQuery();
        return $query;
    }
}


text:
package io.smartcat.cassandra.diagnostics.module.metrics;

import java.io.IOException;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RMISocketFactory;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectInstance;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.rmi.ssl.SslRMIClientSocketFactory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.smartcat.cassandra.diagnostics.GlobalConfiguration;
import io.smartcat.cassandra.diagnostics.Measurement;

/**
 * Metrics collector class. Handles mbeans, jmx connection and collecting metrics.
 */
public class MetricsCollector {

    private static final Logger logger = LoggerFactory.getLogger(MetricsCollector.class);

    private static final String JXM_URL_FORMAT = "service:jmx:rmi:///jndi/rmi://[%s]:%d/jmxrmi";

    private static final String DEFAULT_SOCKET_FACTORY = "com.sun.jndi.rmi.factory.socket";

    private final String service;

    private final MetricsConfiguration config;

    private final GlobalConfiguration globalConfiguration;

    private JMXConnector jmxc;

    private MBeanServerConnection mbeanServerConn;

    private Set<MetricsMBean> mbeans = new HashSet<>();

    /**
     * Constructor.
     *
     * @param service             service name for measurements
     * @param config              metrics configuration
     * @param globalConfiguration Global diagnostics configuration
     */
    public MetricsCollector(final String service, final MetricsConfiguration config,
            final GlobalConfiguration globalConfiguration) {
        this.service = service;
        this.config = config;
        this.globalConfiguration = globalConfiguration;
    }

    /**
     * Close jmx connection.
     */
    public void close() {
        if (jmxc != null) {
            try {
                jmxc.close();
            } catch (IOException e) {
                logger.error("Error while trying to close jmx connection", e);
            }
            jmxc = null;
        }
    }

    /**
     * Open jmx connection and collect mbeans matching configuration defined patterns.
     *
     * @return success of connect and collect
     */
    public boolean connect() {
        try {
            JMXServiceURL jmxUrl = new JMXServiceURL(String.format(JXM_URL_FORMAT, config.jmxHost(), config.jmxPort()));
            Map<String, Object> env = new HashMap<String, Object>();
            if (config.jmxSslEnabled()) {
                String[] creds = new String[2];
                creds[0] = config.jmxSslUsername();
                creds[1] = config.jmxSslPassword();
                env.put(JMXConnector.CREDENTIALS, creds);
            }

            env.put(DEFAULT_SOCKET_FACTORY, getRMIClientSocketFactory());

            jmxc = JMXConnectorFactory.connect(jmxUrl, env);
            mbeanServerConn = jmxc.getMBeanServerConnection();

            for (String packageName : config.metricsPackageNames()) {
                String queryName = String.format("%s:*", packageName);
                mbeans.addAll(filterMBeans(packageName, mbeanServerConn.queryMBeans(new ObjectName(queryName), null)));
            }

            return true;
        } catch (IOException e) {
            logger.error("Cannot connect to jmx on {}:{}", config.jmxHost(), config.jmxPort(), e);
        } catch (MalformedObjectNameException e) {
            logger.error("Failed to query by object name", e);
        } catch (ReflectionException | IntrospectionException | InstanceNotFoundException e) {
            logger.error("Failed to get mbean attributes", e);
        }

        return false;
    }

    /**
     * Collect all measurement using defined mbeans.
     *
     * @return list of measurements
     */
    public List<Measurement> collectMeasurements() {
        List<Measurement> measurements = new ArrayList<Measurement>();

        for (final MetricsMBean mbean : mbeans) {
            for (final MBeanAttributeInfo attribute : mbean.getMBeanAttributes()) {
                try {
                    final ObjectName mbeanObjectName = mbean.getMBean().getObjectName();
                    if (mbeanServerConn.isRegistered(mbeanObjectName)) {
                        final Object value = mbeanServerConn.getAttribute(mbeanObjectName, attribute.getName());

                        if (value != null) {
                            measurements.add(createMeasurement(
                                    service + config.metricsSeparator() + mbean.getMeasurementName()
                                            + config.metricsSeparator() + attribute.getName(),
                                    Double.parseDouble(value.toString())));
                        }
                    }

                } catch (Exception e) {
                    logger.error("Exception while reading attribute {} of type {}", attribute.getName(),
                            attribute.getType(), e);
                }
            }
        }

        return measurements;
    }

    private Measurement createMeasurement(final String service, final double value) {
        final Map<String, String> tags = new HashMap<>(2);
        tags.put("host", globalConfiguration.hostname);
        tags.put("systemName", globalConfiguration.systemName);
        return Measurement.createSimple(service, value, System.currentTimeMillis(), TimeUnit.MILLISECONDS, tags,
                new HashMap<String, String>());
    }

    private Set<MetricsMBean> filterMBeans(final String packageName, final Set<ObjectInstance> mbeanObjectInstances)
            throws IntrospectionException, ReflectionException, InstanceNotFoundException, IOException {
        Set<MetricsMBean> results = new HashSet<MetricsMBean>();
        List<Pattern> patterns = new ArrayList<Pattern>();
        for (String pattern : config.metricsPatterns()) {
            patterns.add(Pattern.compile(pattern));
        }

        for (ObjectInstance objectInstance : mbeanObjectInstances) {
            final MBeanAttributeInfo[] attributes = mbeanServerConn.getMBeanInfo(objectInstance.getObjectName())
                    .getAttributes();
            final List<MBeanAttributeInfo> filteredAttributes = new ArrayList<>();

            for (MBeanAttributeInfo attributeInfo : attributes) {
                try {
                    final Object obj = mbeanServerConn
                            .getAttribute(objectInstance.getObjectName(), attributeInfo.getName());
                    // With trying to parse double we are including all mbean attributes that have a number value.
                    // This is necessary because some of the attributes are defined as type Object and type checking
                    // is not possible in that case.
                    Double.parseDouble(obj.toString());
                    filteredAttributes.add(attributeInfo);
                } catch (Exception e) {
                    // Exception handling is unnecessary because we are skipping this attribute
                }
            }

            MetricsMBean mbean = new MetricsMBean(packageName, config, objectInstance, filteredAttributes);

            boolean matches = false;
            if (patterns.isEmpty()) {
                matches = true;
            }

            for (Pattern pattern : patterns) {
                if (pattern.matcher(mbean.getMBeanName()).matches()) {
                    matches = true;
                }
            }

            if (matches) {
                results.add(mbean);
            }
        }

        for (MetricsMBean mbean : results) {
            logger.debug(mbean.toString());
        }

        return results;
    }

    private RMIClientSocketFactory getRMIClientSocketFactory() {
        if (config.jmxSslEnabled()) {
            return new SslRMIClientSocketFactory();
        } else {
            return RMISocketFactory.getDefaultSocketFactory();
        }
    }

}


text:
#ifndef BLE_L2CAP_EVT_CONN_H__
#define BLE_L2CAP_EVT_CONN_H__

/**
 * @addtogroup ser_codecs Serialization codecs
 * @ingroup ble_sdk_lib_serialization
 */

/**
 * @addtogroup ser_conn_s130_codecs Connectivity S132 codecs
 * @ingroup ser_codecs
 */

/**@file
 *
 * @defgroup ble_l2cap_evt_conn L2CAP Connectivity event encoders
 * @{
 * @ingroup  ser_conn_s130_codecs
 *
 * @brief    L2CAP Connectivity event encoders.
 */
#include "ble.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @brief Encodes ble_l2cap_evt_rx event.
 *
 * @param[in] p_event          Pointer to the \ref ble_evt_t buffer that shall be encoded.
 * @param[in] event_len        Size (in bytes) of \p p_event buffer.
 * @param[out] p_buf           Pointer to the beginning of a buffer for encoded event packet.
 * @param[in,out] p_buf_len    \c in: Size (in bytes) of \p p_buf buffer.
 *                             \c out: Length of encoded contents in \p p_buf.
 *
 * @retval NRF_SUCCESS               Encoding success.
 * @retval NRF_ERROR_NULL            Encoding failure. NULL pointer supplied.
 * @retval NRF_ERROR_INVALID_LENGTH  Encoding failure. Incorrect buffer length.
 */
uint32_t ble_l2cap_evt_rx_enc(ble_evt_t const * const p_event,
                              uint32_t                event_len,
                              uint8_t * const         p_buf,
                              uint32_t * const        p_buf_len);

/** @} */

#ifdef __cplusplus
}
#endif

#endif


text:
#ifndef _ELG_ERROR_H
#define _ELG_ERROR_H

#ifdef __cplusplus
#   define EXTERN extern "C"
#else
#   define EXTERN extern
#endif

/*
 *-----------------------------------------------------------------------------
 *
 *  EPILOG Library (Event Processing, Investigating, and Logging)
 *
 *  - Error messages
 *
 *-----------------------------------------------------------------------------
 */

#define CHK_NOT_NULL(ptr) if (ptr == NULL) { elg_error(); }

/* set process id/rank for messages */
EXTERN void elg_error_pid(const int pid);

/* set thread id function for messages */
EXTERN void elg_error_thread_init(int (*id_fn)(void));  /* supply omp_get_thread_num() as argument */

/* set verbosity for this process (and its threads) */
EXTERN void elg_verbosity(const int val);

/* determine whether specification matches given rank */
EXTERN int elg_rank_match(const int rank, const char* spec);

/* abort and system error message */
#define elg_error() elg_error_impl(__FILE__, __LINE__)
EXTERN void elg_error_impl(const char* f, int l);

/* abort and user error message */
EXTERN void elg_error_msg(const char* fmt, ...);

/* user warning message without abort */
EXTERN void elg_warning(const char* fmt, ...);

/* user control message without abort (printed only if verbosity enabled) */
EXTERN void elg_cntl_msg(const char* fmt, ...);

#endif


text:
package org.apache.camel.component.sjms.batch;

import java.util.Map;
import java.util.concurrent.ExecutorService;

import javax.jms.ConnectionFactory;

import org.apache.camel.Endpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.HeaderFilterStrategyComponent;
import org.apache.camel.util.ObjectHelper;

@Component("sjms-batch")
public class SjmsBatchComponent extends HeaderFilterStrategyComponent {

    private ExecutorService asyncStartStopExecutorService;

    @Metadata(label = "advanced")
    private ConnectionFactory connectionFactory;
    @Metadata(label = "advanced")
    private boolean asyncStartListener;
    @Metadata(label = "advanced", defaultValue = "5000")
    private int recoveryInterval = 5000;

    public SjmsBatchComponent() {
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        ConnectionFactory cf = resolveAndRemoveReferenceParameter(parameters, "connectionFactory", ConnectionFactory.class);
        if (cf != null) {
            setConnectionFactory(cf);
        }
        ObjectHelper.notNull(connectionFactory, "connectionFactory");

        SjmsBatchEndpoint answer = new SjmsBatchEndpoint(uri, this, remaining);
        answer.setAsyncStartListener(isAsyncStartListener());
        answer.setRecoveryInterval(getRecoveryInterval());
        setProperties(answer, parameters);

        return answer;
    }

    public ConnectionFactory getConnectionFactory() {
        return connectionFactory;
    }

    /**
     * A ConnectionFactory is required to enable the SjmsBatchComponent.
     */
    public void setConnectionFactory(ConnectionFactory connectionFactory) {
        this.connectionFactory = connectionFactory;
    }

    public boolean isAsyncStartListener() {
        return asyncStartListener;
    }

    /**
     * Whether to startup the consumer message listener asynchronously, when starting a route. For example if a
     * JmsConsumer cannot get a connection to a remote JMS broker, then it may block while retrying and/or failover.
     * This will cause Camel to block while starting routes. By setting this option to true, you will let routes
     * startup, while the JmsConsumer connects to the JMS broker using a dedicated thread in asynchronous mode. If this
     * option is used, then beware that if the connection could not be established, then an exception is logged at WARN
     * level, and the consumer will not be able to receive messages; You can then restart the route to retry.
     */
    public void setAsyncStartListener(boolean asyncStartListener) {
        this.asyncStartListener = asyncStartListener;
    }

    public int getRecoveryInterval() {
        return recoveryInterval;
    }

    /**
     * Specifies the interval between recovery attempts, i.e. when a connection is being refreshed, in milliseconds. The
     * default is 5000 ms, that is, 5 seconds.
     */
    public void setRecoveryInterval(int recoveryInterval) {
        this.recoveryInterval = recoveryInterval;
    }

    @Override
    protected void doShutdown() throws Exception {
        if (asyncStartStopExecutorService != null) {
            getCamelContext().getExecutorServiceManager().shutdownNow(asyncStartStopExecutorService);
            asyncStartStopExecutorService = null;
        }
        super.doShutdown();
    }

    protected synchronized ExecutorService getAsyncStartStopExecutorService() {
        if (asyncStartStopExecutorService == null) {
            // use a cached thread pool for async start tasks as they can run for a while, and we need a dedicated thread
            // for each task, and the thread pool will shrink when no more tasks running
            asyncStartStopExecutorService
                    = getCamelContext().getExecutorServiceManager().newCachedThreadPool(this, "AsyncStartStopListener");
        }
        return asyncStartStopExecutorService;
    }

}


text:
layout: page
title: StratuX Project
tagline: Aviation
category: aviation, stratux, projects
tags: [aviation, aircraft, stratux, raspberry pi, SDR]

bigimg:
  - "/aviation/stratux/img/power_boost.JPG" : "Adafruit PowerBoost 1000"
  - "/aviation/stratux/img/kerbos.jpg" : "OLED test with KerbOS"
  - "/aviation/stratux/img/hello.jpg" : "OLED test with Hello World!"
  - "/aviation/stratux/img/usb_power.JPG" : "Power measurements StratuX"

---
StratuX
=============

StratuX is project that allows a person to build a ADS-B receiver.  It should be noted that this is just a receiver, it has no transmit abilities at all.  This is the reason that this is a cheap way to receive ADS-B traffic and weather information into the cockpit.

For more information about StratuX and see where the development of the software is, I highly recommend that you go to the [StratuX website](http://stratux.me/).  You can see the latest news and download the latest version of StratuX.

To build a StratuX reciever you will need at least the following items:

* Raspberry Pi 2 or 3
* WiFi dongle (not needed with the Pi 3)
* SDR that is compatabile with the RTL-SDR (RTL2832U)
* 8 GB or higher SD Card (should be Class 10)
* 5 VDC Power Supply (Can be battery pack, more on this later)

You can also add additional equipment that can provide some other functions as well.  This items are listed below.

* WAAS Enabled GPS
* IMU Unit (available on RY835AI GPS)
* Additional SDR reciever (for dual band operation)

We will talk about some of these features and their impact on the system later on.

Power consideration
-----
Power was one of the first things I wanted to look into and change with how many StratuX systems were doing.  Most systems was relaying on an external battery.  These are typically used to charge cell phones and tablets and provide 5 VDC and usually have a fairly large capacity (10,000 mAh or higher).  But there is a problem.  Let's talk about the USB specification for providing power.

The USB Specifications state that the voltage on USB shall be between 5 VDC plus or minus .25 VDC.  The Raspberry Pi follows this specification and must be supplied with a power source that matches it.  If it does not stay in that range, then the Raspberry Pi may "brownout" which may be poor performance or it may just reboot.  The problem with some battery packs though, is that under heavy load they may not maintain the correct voltage.  This is not usually a large problem for most charging applications which they are designed for.  But for the Raspberry Pi it can be bad.

There is also the issue of needing to carry an external battery pack with you.  It would be bettery if the battery was built into the case.

More to come later...


text:
package carbon.internal;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import carbon.R;
import carbon.widget.FrameLayout;
import carbon.widget.TextView;

public class SeekBarPopup extends PopupWindow {
    private final Context context;
    private final View contentView;
    private FrameLayout bubble;
    private TextView label;

    public SeekBarPopup(Context context) {
        super(LayoutInflater.from(context).inflate(R.layout.carbon_seekbar_bubble, null, false));
        contentView = getContentView();
        label = contentView.findViewById(R.id.carbon_label);
        bubble = contentView.findViewById(R.id.carbon_bubble);
        this.context = context;

        setBackgroundDrawable(new ColorDrawable(context.getResources().getColor(android.R.color.transparent)));

        setTouchable(false);
        setFocusable(false);
        setOutsideTouchable(false);
        setAnimationStyle(0);
        setClippingEnabled(false);
    }

    @Override
    public void update(int x, int y) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        super.update(0, y, wm.getDefaultDisplay().getWidth(), contentView.getMeasuredHeight());
        bubble.setTranslationX(x);
    }

    public boolean show(View anchor) {

        super.showAtLocation(anchor, Gravity.START | Gravity.TOP, 0, 0);

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        contentView.measure(View.MeasureSpec.makeMeasureSpec(wm.getDefaultDisplay().getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        super.update(wm.getDefaultDisplay().getWidth(), contentView.getMeasuredHeight());

        bubble.animateVisibility(View.VISIBLE);

        return true;
    }

    public boolean showImmediate(View anchor) {
        super.showAtLocation(anchor, Gravity.START | Gravity.TOP, 0, 0);

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        contentView.measure(View.MeasureSpec.makeMeasureSpec(wm.getDefaultDisplay().getWidth(), View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        super.update(wm.getDefaultDisplay().getWidth(), contentView.getMeasuredHeight());

        bubble.setVisibility(View.VISIBLE);

        return true;
    }

    @Override
    public void dismiss() {
        bubble.animateVisibility(View.INVISIBLE);
        Animator animator = bubble.getAnimator();
        if (animator != null) {
            animator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    SeekBarPopup.super.dismiss();
                }
            });
        }
    }

    public void dismissImmediate() {
        super.dismiss();
    }

    public void setText(String text) {
        label.setText(text);
    }

    public int getBubbleWidth() {
        return bubble.getMeasuredWidth();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toast_text"
    android:inputType="text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:singleLine="true"
    android:layout_gravity="center" />


text:
   <TITLE>CCP13 Documentation: XFIX</TITLE>

CCP13 - Software Development for Fibre Diffraction

  XFIX: Preliminary Analysis of Fibre Diffraction Patterns

Version 1.0: 20/04/98 Richard Denny

Introduction

XFIX is designed to help ascertain some important parameters of a
fibre diffraction pattern with the aid of an OSF/Motif-based
graphical user interface (GUI). The job of the GUI is to handle the
display images, collect information specifying regions of the data
and to communicate with the program FIX which performs much of the
underlying data-processing.

Information such as the pattern centre, detector orientation,
fibre tilt can be estimated and refined and putative unit cells can
be plotted over the pattern. In addition, more general functions are
available such as the capability to plot and fit integrated slices or
scans through the pattern.

The XFIX Main Window

The top part of the main window is comprised of a menubar, some
text fields for displaying the current file name, the current frame
number, the (x,y) coordinates of the pointer, the (interpolated)
value at the pointer coordinates and two arrow buttons to switch
between images either side of a text field which indicates the
current image number. If no file has been specified, the image number
field is blank. Once a file has been specified, the first image
displayed (the whole frame) is numbered zero.

The middle part contains the large scrolled image area, the
magnified area, two text fields for specifying the current display
thresholds, two push buttons for inverting the current palette and
refreshing the display and a set of toggle buttons used to specify
subsequent behaviour and use of the pointer and mouse buttons.

The bottom part contains a scrolled text window for displaying
output from the processing program, FIX and commands sent to FIX by
the XFIX interface.

The File Menu

New ...

   This allows the user to specify a file using the BSL File
   Selection interface. A new XFIX interface will then appear with
   the specified file loaded.

Open ...

   This allows the user to specify a file using the BSL File
   Selection interface. The specified file will then be loaded into
   XFIX.

Next Frame

   This loads the next frame from a multi-frame file.

Save As Postscript ...

   This saves the current image as a Postscript file.

Quit

   This exits the program, subject to confirmation by the user.

The Edit Menu

Parameters ...

   This causes the Parameter Editor dialog to appear. This interface
   is used to specify wavelength, sample to detector distance,
   detector centre and orientation, sample tilt. If a calibration
   ring is present on the image it may be useful to specify the
   calibrant d-spacing in order to calculate the sample to detector
   distance. Even if the default values for the wavelength and
   calibrant d-spacing are known to be correct, it is necessary to
   "OK" or "Apply" the values using this interface so that the sample
   to detector distance is calculated.

Objects ...

   This causes the Object Editor dialog to appear. This interface
   handles some of the items which can be collected from the data:
   points, rectangles, polygons and sectors. These items can be
   selected in the editor and will then be highlighted in image
   window (objects are normally labelled white on a black background;
   selection causes the background to become red). Selected objects
   will be used if estimation of the pattern centre, detector
   rotation or sample tilt is performed. If no objects are selected
   and one of these functions is requested all objects will be used.

Lines ...

   This causes the Line Editor dialog to appear. This interface
   handles lines and thicklines collected from the data. These items
   are labelled white on a blue background; selection causes the
   background to become green. Selected lines can be plotted or
   fitted. If no lines are selected and plotting or fitting is
   requested, all lines are processed.

Scans ...

   This causes the Scan Editor dialog to appear. This interface
   handles radial or azimuthal scans collected from the data. These
   items are labelled white on a blue background; selection causes
   the background to become green. Selected scans can be plotted or
   fitted with radial or azimuthal averaging. If no scans are
   selected and plotting or fitting is requested, all scans are
   processed.

Cell ...

   This interface is used to specify unit cell lengths and angles and
   the missetting angles of the unit cell away from the fibre axis.
   The cell parameters can be used to generate reciprocal lattice
   points which are listed and mapped onto the diffraction pattern
   within the specified resolution range.

The Estimate Menu

Centre

   The centre of the pattern is estimated using the objects defined
   by the Object Editor. If three or more points are available, the
   estimation is made by fitting a circle to the objects. If the
   wavelength or calibrant spacing have been specified using the
   Parameter Editor, the option is given to calculate the sample to
   detector distance.

Rotation

   The rotation of the pattern is estimated using a pairs of objects
   defined by the Object Editor. It is usually sufficient to select
   one pair of objects related by mirror symmetry across the meridian
   as the rotation can be refined later.

Tilt

   The tilt of the sample is estimated using a pairs of points
   defined by the Object Editor. It is usually sufficient to select
   one pair of points related by mirror symmetry (for an untilted
   sample) across the equator as the tilt can be refined later.

The Process Menu

List Objects

   This causes FIX to calculate and list the filespace, standard
   (i.e. centred and rotated) and reciprocal space coordinates for
   each object if the required parameters have been entered or
   determined for each calculation.

Plot Lines ...

   This causes selected lines to be plotted (and possibly fitted)
   using the XFIT interface to FIT. If no lines are selected, all
   lines are plotted.

Plot Scans ...

   This causes selected scans to be plotted (and possibly fitted)
   using the XFIT interface to FIT. If no scans are selected, all
   scans are plotted.

Refine ...

   This causes the Refine Dialog interface to appear. The parameters
   for the refinement can be chosen and clicking on "OK" starts the
   refinement. The refinement algorithm uses the current image as
   data, mapping the coordinates of the image into the four quadrants
   of reciprocal space in order to compare the data in the quadrants
   and minimize the variance between quadrants. This means that the
   current image should be carefully chosen (not too big, but not so
   small that there is little contrast in the image, not too close to
   the equator if sample tilt is being refined but the intensity on
   the image should be present on all four quadrants of the image).

The Options Menu

Palette >

   This contains options for a grey scale and various colour
   representations of the pixel values.

Magnification >

   This contains options for the factor applied in the magnification
   window.

Line Colour >

   This contains options for the colour with which crosses, rectangles,
   sectors and circles will be drawn.

Lattice Point Colour >

   This contains options for the colour with which lattice points
   will be drawn.

Log Scale

   This causes subsequent threshold changes to scale the data on a
   logarithmic scale.

Interpolate

   This causes subsequent images to be interpolated to fit the
   current image window size. This happens automatically for zoomed
   images.

Fit Lines/Scans

   This allows subsequent plots of lines or scans to be fitted.

Show Lattice Points

   This causes subsequently generated lattice points to be drawn onto
   the current image. If there are any lattice points in memory,
   these will be drawn immediately.

Azimuthal Scan

   This causes subsequently plotted scans to be integrated radially
   and the integrated values to be plotted as a function of angle.

Radial Scan

   This causes subsequently plotted scans to be integrated
   azimuthally and the integrated values to be plotted as a function
   of radius.

The Help Menu

The HTML help documents are displayed in your current Netscape Web
browser.

Image Thresholds Selection

The threshold values for displaying the current image can be set
by editing the threshold text fields (labelled "High" and "Low") and
hitting <return>. When an image is first loaded, the thresholds
are set to the maximum and minimum values in the data for that image.

Inverting the Current Palette

The "Invert Palette" button reverses the colour scale of the
current palette.

Refreshing the Image Display

The "Refresh" button can be used to redraw the image windows. This
can be useful if another application has modified the colour map or
if it is desired to erase circles or crosses drawn by FIX.

Data Collection Tools

To facilitate collection of various data items from the current
image, a set of toggle buttons is provided which determine the
behaviour of the mouse buttons and pointer.

Points

   "Points" mode causes the image in the magnification window to
   track the position of the pointer in the main image window. Points
   can be created by clicking the left-hand mouse button.
   Alternatively, tracking of the pointer can be frozen by clicking
   on the middle mouse button and the point can then be positioned in
   the magnification window using the left-hand mouse button.
   Tracking of the pointer can be restarted by clicking on the
   right-hand mouse button in either the main image or magnification
   windows. On creation, the point is numbered and displayed in the
   Object Editor.

Lines

   This mode allows lines to be created by holding down left-hand
   mouse button and dragging the pointer to select the starting
   point, the end point being selected in a similar way using the
   middle mouse button. The line is not created until the right-hand
   mouse button is pressed to indicate that the user is satisfied
   with the start and end points selected. While the pointer is being
   dragged, its position is tracked by the magnification window
   unless the tracking has previously been frozen while the interface
   was in "Points" mode. If this is the case, lines can also be
   selected from the magnification window. On creation, the line is
   numbered and displayed in the Line Editor.

Thick Lines

   This is similar to "Lines" mode except that the line is now
   considered to have a width and is drawn as a rectangular box. The
   width of the box can be adjusted by holding down the <shift>
   key while holding down the left-hand mouse button and dragging the
   pointer.

Rectangles

   This is essentially similar to "Lines" mode, except that the
   left-hand mouse button selects the top left-hand corner of the
   rectangle and the middle mouse button selects the bottom
   right-hand corner of the rectangle. On creation, the centre of the
   rectangle is marked with a cross and the rectangle is numbered (as
   an object) and displayed in the Object Editor. Centring is
   achieved by averaging data values along the perimeter of the
   rectangle to obtain a background value. This value is then
   subtracted from data points interior to the rectangle and the
   centre of gravity of the modified values is calculated.

Polygons

   This is similar to "Rectangle" mode except that the left-hand
   mouse button selects a vertex, the middle mouse button deletes the
   last vertex and the right-hand mouse button closes and creates the
   polygon.

Sectors

   This is essentially similar to "Rectangle" mode except that the
   left-hand mouse button selects the starting angle and radius and
   the middle mouse button selects the end angle and radius. Radii
   are measured from the pattern centre as defined in the Parameter
   Editor and angles are positive going anticlockwise on the image.

Scans

   This is similar to "Sector" mode except that the parameters
   describing the area chosen are stored so that scans can be
   produced: a radial scan implies averaging over an arc defined by the
   azimuthal range for each radius while an azimuthal scan implies averaging
   over radius. On creation, the scan is numbered and displayed in the Scan
   Editor.

Zoom

   This is essentially similar to "Rectangle" mode except that the
   rectangle chosen is blown up to the current size of the main image
   window using bilinear interpolation to find intermediate pixel
   values.

Plotting and Fitting

Lines and scans can be plotted and fitted using many of the
interfaces developed for the XFIT program which
utilizes PGPLOT
graphics. Plotting is activated using the "Plot Lines/Scans" button in
the "Process" menu. In the following description, where the word "line"
is used, "scan" could be substituted.

Channel Selection

When a line is plotted the distance between the start and end
points of the line is divided into a sequence of channels, the length
of a channel corresponding to the size of a data pixel. The values
placed into the channels are found by interpolation of the data
values. The first and last channels for plotting can be entered in
the Channel Dialog box which appears soon after plotting has been
activated. Clicking on the "Cancel" button in the Channel Dialog box
will cause XFIX to move on to the next line selected for plotting.

Plot Thresholds Selection

When the data for the line are plotted, the thresholds for the
plot will be the minimum and maximum channel values present in the
selected channels. If necessary, these can be altered by entering the
appropriate values into the Threshold dialog box. Clicking on the
"Cancel" button in the Threshold Dialog box will cause XFIX to move
on to the next line selected for plotting.

Selection of the region to be used in the fit

If the data is to be fitted ("Fit Lines/Scans" has been selected
in the "Options" menu), the user can choose to delimit the region to
be used in the fit using the Limit Dialog box. The limits can then be
selected by clicking on the plot with any mouse button. Once the limits
of the region have been selected, the plot will be redrawn using only
the required region.

Peak Type Selection

Six peak types are available:

Peak type                          Key  Parameters

Gaussian                            g    3

Lorentzian                          c    3

Pearson VII                         p    4

Voigt                               v    4

Debye Gaussian chain scattering     d    3

Double exponential                  x    4

The selection is made by pressing the appropriate key while the
focus is in the plot window. All subsequent peaks will be of the same
type until a different peak type is selected. The default peak type
is Gaussian.

Peak Parameters

The formulae used for the different peak types give different
meanings to the descriptions width and shape. In what follows, the
position of the peak is assumed to be at the origin of the x-axis, h
is the height of the peak, w is the width and s is the shape. Peak widths
are the full width at half maximum (FWHM) unless otherwise stated.

Gaussian

   <MATH>y = he-4ln2(x/w)2</MATH>

Lorentzian

   <MATH>y = h/[1 + 4(x/w)2]</MATH>

Pearson VII

   <MATH>y = h/[1 +
   4(x/w)2(21/s-1)]s</MATH>

   When s = 1, the Pearson VII is equivalent to a Lorentzian but as s
   increases, the peak becomes more Gaussian in character.

Voigt

   The Voigt is a convolution of a Lorentzian with a Gaussian.
   The shape parameter, s, corresponds to the ratio of the width of the
   Lorentzian to the width of the Gaussian, w. Therefore, when s = 0, the
   resulting curve is a Gaussian of width w. This can be expressed as:

   <MATH>y = h Integral <BOX>e-4ln2(t/w)2/
   [(x+(2<SQRT>ln2</SQRT>/w)2 + ln2s2]</BOX>dt
</MATH>

   An approximation is used:

   <MATH>y = h
   <BOX>
   [Σi=14
   <BOX>
   (Ci(s/2 - Ai) + Di(2<SQRT>ln2</SQRT>x/w - Bi))
   /<ATOP> (
   (s/2 - Ai)2 + (2<SQRT>ln2</SQRT>x/w - Bi)2)
   </BOX>]
   /<ATOP>
   [Σi=14
   <BOX>
   (Cis/2 - CiAi + DiBi)
   /<ATOP>
   (s2/4 - sAi + Ai2 + Bi2)
   </BOX>]
   </BOX> </MATH>

   where the constants have the following values,

 i =     1       2        3        4

  A   -1.2150  -1.3509  -1.2150  -1.3509

  B    1.2359   0.3786  -1.2359  -0.3786

  C   -0.3085   0.5906  -0.3085   0.5906

  D    0.0210  -1.1858  -0.0210   1.1858

Debye Gaussian Chain Scattering

   <MATH>y = 2h[e-(x/w)2 - (1-(x/w)2)]/(x/w)4</MATH>

   Here, w corresponds to 1/Rg if the x-axis corresponds
   to a q-axis. The central (guinier) region of the peak is Gaussian in
   character while the tail (power law) region is Lorentzian in character.

Double Exponential

   <MATH>y = 2h/[e-x/w + e+x/s]</MATH>

   This peak is asymmetric; w corresponds to the rate at which the
   peak grows, approaching from the left, while s corresponds to the
   rate of growth, approaching from the right.

Peak Parameter Selection

A peak of the current type is initialized for fitting to the data
when the left mouse button is pressed. The position of the peak is
determined by the X coordinate of the cursor when the button is
pressed. The width of the peak is determined simultaneously by the Y
coordinate of the cursor. The height of the peak is given by the Y
value of the data point nearest to the peak position.

Background Selection

A polynomial of degree 4 or less, expressed as

<MATH>a0 + a1x + a2x2 +
a3x3 + a4x4</MATH>

can be fitted as background to the data. The degree of the polynomial
can be selected by using the keys <1>,...,<4> while the
focus is in the plot window. The default polynomial degree is 3.

An exponential component can be added into the background by
pressing <e> while the focus is in the plot window. This will
add two parameters to the fit to define the exponential curve,

<MATH>e1ee2x</MATH>.

Once all the required peak and background parameters have been
initialized, selection can be terminated by clicking on the right
mouse button while the focus is in the plot window.

Controlling the fit

Some control over the fitting procedure can be excercised through
the Setup Dialog box. This interface provides a list of all the
parameters in the fit with their current values displayed in text
fields so that they can be easily modified. There is also an option
menu associated with each parameter. The following selections can be
made from this menu:

Free - if a parameter has been previously constrained
   using the other options, it is released to be a free parameter in
   the fit.

Set - fix the value of a parameter to the value in the
   text field. The parameter is effectively removed from the fit.

Limit... - this causes the Limit dialog box to appear.
   This has a label to show you the parameter number you are limiting
   and a brief description of the parameter. Two text fields are
   available for setting limits on the value of the parameter. The
   parameter number can be incremented by use of the arrow buttons
   next to the parameter number. Activation of the arrow buttons has
   the effect of applying the limits to the previous parameter.

Tie... - this causes the Tie dialog box to appear. This
   has a label to show you which parameter you are tying and a brief
   description of the parameter. A text field is available for
   setting the parameter number to which the dependent parameter will
   be tied. A brief description of the independent parameter is
   updated when the apply button is activated. An option menu is
   available to specify the type of constraint to be applied to the
   dependent parameter. These are either an equality constraint or
   simple lattice constraints, i.e. applying (h,k) indices for
   hexagonal and tetragonal lattice positions or (h,k,l) indices for
   cubic lattice positions. These must be relative to the (1,0) or
   (1,0,0) positions, respectively. The parameter number can be
   incremented by use of the arrow buttons next to the parameter
   number. Activation of the arrow buttons has the effect of applying
   the tie constraint for the previous parameter. N.B. xfit always
   ties the higher parameter number to the lower one and modifies the
   Tie dialog and Setup dialog boxes to reflect this. It is not
   possible to make a compound tie constraint unless the constraint
   is one of equality, e.g. to tie parameter 8 to parameter 5 as the
   (1,1) hexagonal position and then tie parameter 5 to parameter to
   parameter 2 as the (2,0) tetragonal position.

The three buttons at the bottom of the Setup dialog box have the
following effects:

PLOT - this allows you to plot the curve corresponding
   to the (modified) parameter set.

STEP - this makes <Step_its> linearized least-squares
   iterations.
   This is useful in seeing if the current model has a good chance of
   converging to the global minimum. The refinement may converge
   after a step. If the converged solution is satisfactory click on
   "RUN" to continue.

RUN - this allows the algorithm to continue to
   convergence or to the maximum number of iterations (<+Max_its>
   + number of iterations already performed).

   The algorithm is deemed to have converged when the following two conditions
   are fulfilled:

χ2current < χ2previous

χ2previous - χ2current
< χ2current * <Chi-test>

   After the "RUN" button has been activated, the parameter entries
   and the buttons in the Setup dialog box will be made insensitive
   and the Try Again confirm dialog box will appear.

Trying Again

Clicking on "Yes" in the "Try Again" Confirm Dialog box will give
you another attempt at fitting the current frame starting from the
point where you select the peak types, positions, etc. The Setup
Dialog box will disappear and the Information Dialog box will appear,
reiterating the procedure for setting up the initial model. Clicking
on "No" will cause XFIX to proceed onto the next line.


text:
namespace PetStore.Data.Migrations
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<PetStore.Data.PetStoreEntities>
    {
        public Configuration()
        {
            this.AutomaticMigrationsEnabled = true;
            this.AutomaticMigrationDataLossAllowed = true;
        }

        protected override void Seed(PetStore.Data.PetStoreEntities context)
        {

        }
    }
}


text:
package com.velvetPearl.lottery;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v4.app.TaskStackBuilder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.velvetPearl.lottery.dataAccess.firebase.FirebaseQueryObject;
import com.velvetPearl.lottery.dataAccess.firebase.scheme.LotteriesScheme;
import com.velvetPearl.lottery.dataAccess.models.Lottery;
import com.velvetPearl.lottery.fragments.LotteryHome;

/**
 * Created by Stensig on 24-Nov-16.
 */

public class NotificationService extends IntentService {

    private static final String LOG_TAG = "NotificationService";
    private static final int NOTIFICATION_ID = 1;

    private FirebaseQueryObject fbQueryObj;
    private long initialLotteryCount;

    public NotificationService() {
        super("NotificationService");
        initialLotteryCount = -1;
        FirebaseAuth.getInstance().signInAnonymously().addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if (task.isSuccessful()) {
                    Log.i(LOG_TAG, "Firebase authentication succeeded.");
                } else {
                    Log.e(LOG_TAG, "Firebase authentication failed. ", task.getException());
                }
            }
        });
    }

    @Override
    protected void onHandleIntent(final Intent intent) {
        if (fbQueryObj != null) {
            Log.i(LOG_TAG, "Firebase query already active.");
            return;
        }

        fbQueryObj = new FirebaseQueryObject();
        fbQueryObj.query = FirebaseDatabase.getInstance().getReference(LotteriesScheme.LABEL);
        fbQueryObj.query.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                initialLotteryCount = dataSnapshot.getChildrenCount();
                Log.i(LOG_TAG, String.format("%d initial lotteries at service start.", initialLotteryCount));
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(LOG_TAG, "Counting initial lotteries failed: ", databaseError.toException());
            }
        });

        // Wait until the number of initial lotteries has been determined
        while (initialLotteryCount == -1) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        fbQueryObj.listener = new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                // Don't notify about additions if it is still among the initial lotteries
                if (initialLotteryCount > 0) {
                    --initialLotteryCount;
                    return;
                }

                Lottery lottery = dataSnapshot.getValue(Lottery.class);
                lottery.setId(dataSnapshot.getKey());
                Log.i(LOG_TAG, String.format("onChildAdded %s", (String)lottery.getId()));
                NotificationCompat.Builder notificationBuilder =
                        new NotificationCompat.Builder(getApplicationContext())
                        .setSmallIcon(android.R.drawable.ic_menu_add)
                        .setContentTitle(getString(R.string.lottery_notification_title))
                        .setContentText(String.format(getString(R.string.lottery_notification_text),lottery.getName()))
                        .setAutoCancel(true);

                Intent targetActivity = new Intent(getApplicationContext(), MainActivity.class);
                targetActivity.putExtra("lotteryId", (String) lottery.getId());

                // The stack builder object will contain an artificial back stack for the
                // started Activity.
                // This ensures that navigating backward from the Activity leads out of
                // your application to the Home screen.
                TaskStackBuilder stackBuilder = TaskStackBuilder.create(getApplicationContext());
                // Adds the back stack for the Intent (but not the Intent itself)
                stackBuilder.addParentStack(MainActivity.class);

                // Adds the Intent that starts the Activity to the top of the stack
                stackBuilder.addNextIntent(targetActivity);
                PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
                notificationBuilder.setContentIntent(resultPendingIntent);
                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {
                // ignore
            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {
                // ignore
            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {
                // ignore
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Log.e(LOG_TAG, "Firebase query failed. ", databaseError.toException());
            }
        };

        Log.i(LOG_TAG, "Starting firebase listener.");
        fbQueryObj.query.addChildEventListener(fbQueryObj.listener);

        // Don't let the call return or the service stops
        while (true) {
            try {
                Thread.sleep(333);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDestroy() {
        if (fbQueryObj != null) {
            Log.i(LOG_TAG, "Removing firebase listener.");
            fbQueryObj.query.removeEventListener(fbQueryObj.listener);
        }
        Log.i(LOG_TAG, "Destroying service.");
        super.onDestroy();
    }
}


text:
<?php

namespace App\Services;

use Dotenv\Dotenv;
use Illuminate\Database\Capsule\Manager as Capsule;

class Boot
{
    public static function  loadEnv(){
        // Env
        $env = new Dotenv(BASE_PATH);
        $env->load();
    }

    public static function setDebug(){
        // debug
        if (Config::get('debug') == "true"){
            define("DEBUG",true);
        }
    }

    public static function setVersion($version){
        $System_Config['version'] = $version;
    }

    public static function setTimezone(){
        // config time zone
        date_default_timezone_set(Config::get('timeZone'));
    }

    public static function bootDb(){
        // Init Eloquent ORM Connection
        $capsule = new Capsule;
        $capsule->addConnection(Config::getDbConfig(),'default');
		if(Config::get('radius_db_user')!='')
		{
			$capsule->addConnection(Config::getRadiusDbConfig(),'radius');
		}

		if(Config::get('wecenter_db_user')!='')
		{
			$capsule->addConnection(Config::getWecenterDbConfig(),'wencenter');
		}
        $capsule->bootEloquent();
    }
}


text:
package com.angkorteam.pluggable.framework.page;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import com.angkorteam.pluggable.framework.mapper.JobMapper;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.springframework.jdbc.core.JdbcTemplate;

import com.angkorteam.pluggable.framework.core.AbstractWebApplication;
import com.angkorteam.pluggable.framework.core.Menu;
import com.angkorteam.pluggable.framework.core.Mount;
import com.angkorteam.pluggable.framework.database.EntityMapper;
import com.angkorteam.pluggable.framework.entity.Job;
import com.angkorteam.pluggable.framework.layout.AbstractLayout;
import com.angkorteam.pluggable.framework.utilities.FrameworkUtilities;
import com.angkorteam.pluggable.framework.utilities.TableUtilities;
import com.angkorteam.pluggable.framework.wicket.authroles.Role;
import com.angkorteam.pluggable.framework.wicket.authroles.authorization.strategies.role.Roles;
import com.angkorteam.pluggable.framework.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;

/**
 * @author Socheat KHAUV
 */
@Mount("/q")
@AuthorizeInstantiation(roles = { @Role(name = "ROLE_PAGE_JOB_MANAGEMENT", description = "Access Job Management Page") })
public final class JobManagementPage extends WebPage {

    /**
     *
     */
    private static final long serialVersionUID = -8827747090739298001L;

    private static final DateFormat DATE_FORMAT = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss ZZ");

    @Override
    public String getPageTitle() {
        return "Job Management";
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();
        AbstractLayout layout = requestLayout("layout");
        add(layout);

        AbstractWebApplication application = (AbstractWebApplication) getApplication();
        JdbcTemplate jdbcTemplate = application.getJdbcTemplate();

        List<Job> jobs = jdbcTemplate.query(
                "select * from " + TableUtilities.getTableName(Job.class),
               new JobMapper());

        ListView<Job> table = new ListView<Job>("table", jobs) {

            private static final long serialVersionUID = -8045778852435218474L;

            @Override
            protected void populateItem(ListItem<Job> item) {

                Job job = item.getModelObject();

                PageParameters parameters = new PageParameters();
                parameters.add("jobId", job.getId());

                BookmarkablePageLink<Void> nameLink = new BookmarkablePageLink<Void>(
                        "nameLink", EditJobPage.class, parameters);
                item.add(nameLink);

                Label nameLabel = new Label("nameLabel", job.getId());
                nameLink.add(nameLabel);

                Label description = new Label("description",
                        job.getDescription());
                item.add(description);

                Label disable = new Label("disable", job.isDisable());
                item.add(disable);

                Label status = new Label("status", job.getStatus());
                item.add(status);

                Label pause = new Label("pause", job.isPause());
                item.add(pause);

                Label cron = new Label("cron", job.getNewCron() == null
                        || "".equals(job.getNewCron()) ? job.getCron()
                        : job.getNewCron());
                item.add(cron);

                Label lastError = new Label("lastError",
                        job.getLastError() == null
                                || "".equals(job.getLastError()) ? "N/A"
                                : job.getLastError());
                item.add(lastError);

                Label lastProcess = new Label("lastProcess",
                        job.getLastProcess() == null ? "N/A"
                                : DATE_FORMAT.format(job.getLastProcess()));
                item.add(lastProcess);
            }
        };
        layout.add(table);
    }

    @Override
    public List<Menu> getPageMenus(Roles roles) {
        AbstractWebApplication application = (AbstractWebApplication) getApplication();
        return FrameworkUtilities.getSecurityMenu(application, roles)
                .getChildren();
    }

}


text:
package org.sparkcommerce.openadmin.web.form.entity;

/**
 * @author Andre Azzolini (apazzolini)
 */
public class CodeField extends Field {

    protected String fileType;
    protected String fetchUrlSuffix;

    /* ************************** */
    /* STANDARD GETTERS / SETTERS */
    /* ************************** */

    public String getFileType() {
        return fileType;
    }

    public void setFileType(String fileType) {
        this.fileType = fileType;
    }

    public String getFetchUrlSuffix() {
        return fetchUrlSuffix;
    }

    public void setFetchUrlSuffix(String fetchUrlSuffix) {
        this.fetchUrlSuffix = fetchUrlSuffix;
    }

}


text:
class RolesController < ApplicationController
  before_action :set_team
  before_action :set_role, except: [:index, :show]

  load_and_authorize_resource except: [:index, :show]

  def new
    @role = @team.roles.new(name: params[:name])
    @users = User.order(:github_handle)
  end

  def create
    @role.user = User.where(github_handle: params[:role][:github_handle]).first_or_create

    respond_to do |format|
      if @role.save
        format.html { redirect_to @team, notice: 'Team was successfully created.' }
        format.json { render action: :show, status: :created, location: @team }
      else
        format.html { render action: :new }
        format.json { render json: @role.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @role.destroy
    redirect_to @team
  end

  private

    def set_team
      @team = Team.find(params[:team_id])
    end

    def set_role
      @role = if params[:id]
        @team.roles.find(params[:id])
      else
        @team.roles.new(role_params)
      end
    end

    def role_params
      params[:role] ||= { name: params[:name] }
      params.require(:role).permit(:user_id, :team_id, :name, :github_handle)
    end

end


text:
package rx.redis

import rx.redis.clients.RawClient
import rx.redis.resp.{RespBytes, RespType}
import rx.redis.serialization._
import rx.redis.util.{DefaultRedisHost, DefaultRedisPort, Utf8}

import rx.functions.Action1

import io.netty.buffer.{ByteBuf, Unpooled}
import org.scalatest.FunSuite

class ThreadSafetySpec extends FunSuite {

  val total = 10000
  val threadCount = 8

  private class TestThread(
      commandToSend: () ⇒ ByteBuf,
      expected: RespType,
      getClient: => RawClient,
      shutdown: RawClient => Unit)
    extends Thread {

    private final var _correct = 0
    private final var _incorrect = 0
    private final val action: Action1[_ >: RespType] =
      new Action1[RespType] {
        def call(t1: RespType): Unit = {
          if (t1 == expected) _correct +=1
          else _incorrect += 1
        }
      }

    private final val client = getClient

    override def run(): Unit = {
      for (n <- 1 until total) {
        client.command(commandToSend()).forEach(action)
      }
      val last = client.command(commandToSend())
      last.toBlocking.forEach(action)

      shutdown(client)
    }

    def incorrect: Int = _incorrect
    def correct: Int = _correct
  }

  test("must not diverge when shared amongst threads") {

    val client = RawClient(DefaultRedisHost, DefaultRedisPort)

    def createThread(n: Int) = new TestThread(
      () ⇒ cmd"ECHO ${n.toString}",
      RespBytes(n.toString),
      client,
      _ => ())

    val threads = List.tabulate(threadCount)(createThread)

    threads foreach (_.start())
    threads foreach (_.join())

    threads foreach { t =>
      assert(t.correct == total)
      assert(t.incorrect == 0)
    }
  }

  test("must not diverge when used in isolation") {

    def client = RawClient(DefaultRedisHost, DefaultRedisPort)

    def createThread(n: Int) = new TestThread(
      () ⇒ cmd"ECHO ${n.toString}",
      RespBytes(n.toString),
      client,
      _.disconnect().toBlocking.lastOrDefault(()))

    val threads = List.tabulate(threadCount)(createThread)

    threads foreach (_.start())
    threads foreach (_.join())

    threads foreach { t =>
      assert(t.correct == total)
      assert(t.incorrect == 0)
    }
  }

  def RespBytes(s: String): RespBytes =
    rx.redis.resp.RespBytes.wrap(Unpooled.copiedBuffer(s, Utf8))
}


text:
package kafka.server

import java.nio.ByteBuffer

import kafka.network.RequestChannel
import kafka.utils.Logging
import org.apache.kafka.clients.{ClientResponse, NodeApiVersions}
import org.apache.kafka.common.errors.TimeoutException
import org.apache.kafka.common.protocol.Errors
import org.apache.kafka.common.requests.{AbstractRequest, AbstractResponse, EnvelopeRequest, EnvelopeResponse, RequestContext, RequestHeader}

import scala.compat.java8.OptionConverters._

trait ForwardingManager {
  def forwardRequest(
    originalRequest: RequestChannel.Request,
    responseCallback: Option[AbstractResponse] => Unit
  ): Unit = {
    val buffer = originalRequest.buffer.duplicate()
    buffer.flip()
    forwardRequest(originalRequest.context,
      buffer,
      originalRequest.body[AbstractRequest],
      () => originalRequest.toString,
      responseCallback)
  }

  def forwardRequest(
    originalRequest: RequestChannel.Request,
    newRequestBody: AbstractRequest,
    responseCallback: Option[AbstractResponse] => Unit
  ): Unit = {
    val buffer = newRequestBody.serializeWithHeader(originalRequest.header)
    forwardRequest(originalRequest.context,
      buffer,
      newRequestBody,
      () => originalRequest.toString,
      responseCallback)
  }

  /**
   * Forward given request to the active controller.
   *
   * @param requestContext      The request context of the original envelope request.
   * @param requestBufferCopy   The request buffer we want to send. This should not be the original
   *                            byte buffer from the envelope request, since we will be mutating
   *                            the position and limit fields. It should be a copy.
   * @param requestBody         The AbstractRequest we are sending.
   * @param requestToString     A callback which can be invoked to produce a human-readable decription
   *                            of the request.
   * @param responseCallback    A callback which takes in an `Option[AbstractResponse]`.
   *                            We will call this function with Some(x) after the controller responds with x.
   *                            Or, if the controller doesn't support the request version, we will complete
   *                            the callback with None.
   */
  def forwardRequest(
    requestContext: RequestContext,
    requestBufferCopy: ByteBuffer,
    requestBody: AbstractRequest,
    requestToString: () => String,
    responseCallback: Option[AbstractResponse] => Unit
  ): Unit

  def controllerApiVersions: Option[NodeApiVersions]
}

object ForwardingManager {
  def apply(
    channelManager: BrokerToControllerChannelManager
  ): ForwardingManager = {
    new ForwardingManagerImpl(channelManager)
  }

  private[server] def buildEnvelopeRequest(context: RequestContext,
                                           forwardRequestBuffer: ByteBuffer): EnvelopeRequest.Builder = {
    val principalSerde = context.principalSerde.asScala.getOrElse(
      throw new IllegalArgumentException(s"Cannot deserialize principal from request context $context " +
        "since there is no serde defined")
    )
    val serializedPrincipal = principalSerde.serialize(context.principal)
    new EnvelopeRequest.Builder(
      forwardRequestBuffer,
      serializedPrincipal,
      context.clientAddress.getAddress
    )
  }
}

class ForwardingManagerImpl(
  channelManager: BrokerToControllerChannelManager
) extends ForwardingManager with Logging {

  override def forwardRequest(
    requestContext: RequestContext,
    requestBufferCopy: ByteBuffer,
    requestBody: AbstractRequest,
    requestToString: () => String,
    responseCallback: Option[AbstractResponse] => Unit
  ): Unit = {
    val envelopeRequest = ForwardingManager.buildEnvelopeRequest(requestContext, requestBufferCopy)

    class ForwardingResponseHandler extends ControllerRequestCompletionHandler {
      override def onComplete(clientResponse: ClientResponse): Unit = {

        if (clientResponse.versionMismatch != null) {
          debug(s"Returning `UNKNOWN_SERVER_ERROR` in response to ${requestToString()} " +
            s"due to unexpected version error", clientResponse.versionMismatch)
          responseCallback(Some(requestBody.getErrorResponse(Errors.UNKNOWN_SERVER_ERROR.exception)))
        } else if (clientResponse.authenticationException != null) {
          debug(s"Returning `UNKNOWN_SERVER_ERROR` in response to ${requestToString()} " +
            s"due to authentication error", clientResponse.authenticationException)
          responseCallback(Some(requestBody.getErrorResponse(Errors.UNKNOWN_SERVER_ERROR.exception)))
        } else {
          val envelopeResponse = clientResponse.responseBody.asInstanceOf[EnvelopeResponse]
          val envelopeError = envelopeResponse.error()

          // Unsupported version indicates an incompatibility between controller and client API versions. This
          // could happen when the controller changed after the connection was established. The forwarding broker
          // should close the connection with the client and let it reinitialize the connection and refresh
          // the controller API versions.
          if (envelopeError == Errors.UNSUPPORTED_VERSION) {
            responseCallback(None)
          } else {
            val response = if (envelopeError != Errors.NONE) {
              // A general envelope error indicates broker misconfiguration (e.g. the principal serde
              // might not be defined on the receiving broker). In this case, we do not return
              // the error directly to the client since it would not be expected. Instead we
              // return `UNKNOWN_SERVER_ERROR` so that the user knows that there is a problem
              // on the broker.
              debug(s"Forwarded request ${requestToString()} failed with an error in the envelope response $envelopeError")
              requestBody.getErrorResponse(Errors.UNKNOWN_SERVER_ERROR.exception)
            } else {
              parseResponse(envelopeResponse.responseData, requestBody, requestContext.header)
            }
            responseCallback(Option(response))
          }
        }
      }

      override def onTimeout(): Unit = {
        debug(s"Forwarding of the request ${requestToString()} failed due to timeout exception")
        val response = requestBody.getErrorResponse(new TimeoutException())
        responseCallback(Option(response))
      }
    }

    channelManager.sendRequest(envelopeRequest, new ForwardingResponseHandler)
  }

  override def controllerApiVersions: Option[NodeApiVersions] =
    channelManager.controllerApiVersions()

  private def parseResponse(
    buffer: ByteBuffer,
    request: AbstractRequest,
    header: RequestHeader
  ): AbstractResponse = {
    try {
      AbstractResponse.parseResponse(buffer, header)
    } catch {
      case e: Exception =>
        error(s"Failed to parse response from envelope for request with header $header", e)
        request.getErrorResponse(Errors.UNKNOWN_SERVER_ERROR.exception)
    }
  }
}