text:
Jarvis Slacker is a bot for Slack running on Google AppEngine written in Go.

It has an easy to write plugin system where you can register your own commands and aliases.

## Development

Developing a custom plugin for Jarvis is very easy.

Unfortunately, there's no nice way, that I can think of right now to handle the initialization code for it.

As such, you'll need to first copy the ``` frontend/frontend.go ``` to your AppEngine module.

### Register a command

Then, you can register your commands like this: ```jarvis.RegisterCommand(decode.NewCommand)```

### Initialize jarvis

A part of the initialization is sending the keys to various modules. This is need as there's no nice way
to have custom variables in AppEngine (as far as I know, yet) and you might want to publish various modules for it.

Once you have the list of all the keys in place, simply call:

```go
jarvis.Initialize("/jarvis", "jarvis", keys)
http.HandleFunc("/slashCommand", jarvis.SlashCommandHandler)
```

And that's it.

For an example on how this could look like, you can see [jarvis-slacker-3d](https://github.com/dlsniper/jarvis-slacker-3d)

## Deployment

First you need to: ```cp app.yaml.dist app.yaml```

Then you need to replace ```<your AppEngine project ID goes here>``` from app.yaml with your AppEngine project id.

You can deploy this bot like this:

```bash
cd /repository/root/path
goapp deploy frontend
```

##LICENSE

Jarvis Slacker is distributed under MIT license.

You can see the full license in the [LICENSE](LICENSE.md) file.


text:
package com.example.jingbin.cloudreader.base.baseadapter;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;

/**
 * Created by jingbin on 2016/11/25
 */
public abstract class BaseRecyclerViewHolder<T, D extends ViewDataBinding> extends RecyclerView.ViewHolder {

    public D binding;

    public BaseRecyclerViewHolder(ViewGroup viewGroup, int layoutId) {
        // 注意要依附 viewGroup,不然显示item不全!!
        super(DataBindingUtil.inflate(LayoutInflater.from(viewGroup.getContext()), layoutId, viewGroup, false).getRoot());
        // 得到这个View绑定的Binding
        binding = DataBindingUtil.getBinding(this.itemView);
    }

    /**
     * @param object   the data of bind
     * @param position the item position of recyclerView
     */
    public abstract void onBindViewHolder(T object, final int position);

    /**
     * 当数据改变时,binding会在下一帧去改变数据,如果我们需要立即改变,就去调用executePendingBindings方法。
     */
    void onBaseBindViewHolder(T object, final int position) {
        onBindViewHolder(object, position);
        binding.executePendingBindings();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import _ from 'lodash'
import { booleans, booleanObjects } from './booleans'
import { nils, nilObjects } from './nils'
import { numbers, numberObjects } from './numbers'
import { strings, stringObjects } from './strings'
import symbols  from './symbols'

const typeMap = {
  booleans,
  booleanObjects,
  nils,
  nilObjects,
  numbers,
  numberObjects,
  strings,
  stringObjects,
  symbols
}
export default function primitives(context, selected = ['booleans', 'booleanObjects', 'nils', 'nilObjects', 'numbers', 'numberObjects', 'strings', 'stringObjects', 'symbols']) {
  return _.flatten(
    _.map(_.pick(typeMap, selected), type => type(context))
  )
}


text:
<script src="../dist/MqttWorker.js"></script>
<script src="app.js"></script>


text:
 define(function(require, exports, module) {
    var Validator = require('bootstrap.validator');
    require('common/validator-rules').inject(Validator);

    var WebUploader = require('edusoho.webuploader');
    var Notify = require('common/bootstrap-notify');

    exports.run = function() {

        var uploader = new WebUploader({
            element: '#group-save-btn'
        });

        uploader.on('uploadSuccess', function(file, response ) {
            var url = $("#group-save-btn").data("gotoUrl");
            Notify.success(Translator.trans('上传成功!'), 1);
            document.location.href = url;
        });

    };

});


text:
package _threads.main.java.Chronometer_ex;

import java.awt.*;

public final class Chrono extends Canvas {

	private static final long serialVersionUID = 1L;
	private Color backGround = Color.black;
	private Color color = Color.white;
	private int fontSize = 20;
	private Font font = new Font("Arial", 1, fontSize);
	private int deltaHigh = 10;
	private int maxNbrOfDigits = 8;

	private int h = fontSize + deltaHigh;
	private int w = (maxNbrOfDigits * (fontSize / 2));

	public Chrono() {
		setSize(w, h);
		setFont(font);
		setBackground(backGround);
		setForeground(color);

	}

	public void paint(Graphics g) {
		String s = "";
		s = s + 0 + ":" + 0 + ":" + 0;
		g.setColor(Color.yellow);
		g.drawString(s, 0, 20);
	}
}


text:
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
[<!ENTITY % poky SYSTEM "../poky.ent"> %poky; ] >

<book id='ref-manual' lang='en'
      xmlns:xi="http://www.w3.org/2003/XInclude"
      xmlns="http://docbook.org/ns/docbook"
      >
    <bookinfo>

        <mediaobject>
            <imageobject>
                <imagedata fileref='figures/poky-title.png'
                    format='SVG'
                    align='left' scalefit='1' width='100%'/>
            </imageobject>
        </mediaobject>

        <title>
            Yocto Project Reference Manual
        </title>

        <authorgroup>
            <author>
                <firstname>Richard</firstname> <surname>Purdie</surname>
                <affiliation>
                    <orgname>Linux Foundation</orgname>
                </affiliation>
                <email>richard.purdie@linuxfoundation.org</email>
            </author>

        </authorgroup>

        <revhistory>
            <revision>
                <revnumber>4.0+git</revnumber>
                <date>24 November 2010</date>
                <revremark>Released with the Yocto Project 0.9 Release</revremark>
            </revision>
            <revision>
                <revnumber>1.0</revnumber>
                <date>6 April 2011</date>
                <revremark>Released with the Yocto Project 1.0 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.0.1</revnumber>
                <date>23 May 2011</date>
                <revremark>Released with the Yocto Project 1.0.1 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.1</revnumber>
                <date>6 October 2011</date>
                <revremark>Released with the Yocto Project 1.1 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.2</revnumber>
                <date>April 2012</date>
                <revremark>Released with the Yocto Project 1.2 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.3</revnumber>
                <date>October 2012</date>
                <revremark>Released with the Yocto Project 1.3 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.4</revnumber>
                <date>April 2013</date>
                <revremark>Released with the Yocto Project 1.4 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.4.1</revnumber>
                <date>June 2013</date>
                <revremark>Released with the Yocto Project 1.4.1 Release.</revremark>
            </revision>
            <revision>
                <revnumber>1.4.2</revnumber>
                <date>August 2013</date>
                <revremark>Released with the Yocto Project 1.4.2 Release.</revremark>
            </revision>
        </revhistory>

    <copyright>
      <year>&COPYRIGHT_YEAR;</year>
      <holder>Linux Foundation</holder>
    </copyright>

    <legalnotice>
      <para>
        Permission is granted to copy, distribute and/or modify this document under
        the terms of the <ulink type="http" url="http://creativecommons.org/licenses/by-sa/2.0/uk/">Creative Commons Attribution-Share Alike 2.0 UK: England & Wales</ulink> as published by Creative Commons.
      </para>
      <note>
          Due to production processes, there could be differences between the Yocto Project
          documentation bundled in the release tarball and the
          <ulink url='&YOCTO_DOCS_REF_URL;'>Yocto Project Reference Manual</ulink> on
          the <ulink url='&YOCTO_HOME_URL;'>Yocto Project</ulink> website.
          For the latest version of this manual, see the manual on the website.
      </note>
    </legalnotice>

    </bookinfo>

    <xi:include href="introduction.xml"/>

    <xi:include href="usingpoky.xml"/>

    <xi:include href="technical-details.xml"/>

    <xi:include href="migration.xml"/>

    <xi:include href="ref-structure.xml"/>

    <xi:include href="ref-bitbake.xml"/>

    <xi:include href="ref-classes.xml"/>

    <xi:include href="ref-images.xml"/>

    <xi:include href="ref-features.xml"/>

    <xi:include href="ref-variables.xml"/>

    <xi:include href="ref-varlocality.xml"/>

    <xi:include href="faq.xml"/>

    <xi:include href="resources.xml"/>

<!--    <index id='index'>
      <title>Index</title>
    </index>
-->

</book>
<!--
vim: expandtab tw=80 ts=4
-->


text:
/* CSS file */
@namespace s "library://ns.adobe.com/flex/spark";
@namespace mx "library://ns.adobe.com/flex/mx";

mx|Alert {
	background-color: #f2f2f2;
	message-style-name: messageStyle;
	title-style-name: titleStyle;
}

.messageStyle{
	font-family: Arial, Verdana, sans-serif;
	font-size: 12;
	font-weight: normal;
	color: black;
}

.titleStyle{
	font-family: Verdana;
	font-size: 13;
	font-weight: bold;
	color: black;
}


text:
package com.landian.sql.jpa.criterion;

import org.apache.commons.lang.StringUtils;

import java.util.Date;

/**
 * 日期查询
 */
public class CriterionDateTimeLe implements Criterion {

	private static final long serialVersionUID = 1L;

	public CriterionDateTimeLe(String column, Date date) {
		this.column = column;
		this.dateTime = CriterionUtils.TIME_FORMAT.format(date);
	}

	/**
	 * 字段
	 */
	private String column;
	/**
	 * 日期时间
	 */
	private String dateTime;

	/**
	 * SQL片段
	 */
	public String SQL(){
		StringBuffer sb = new StringBuffer();
		if(StringUtils.isNotBlank(dateTime)){
			sb.append(column + " <= '" + dateTime.trim() + "'");
		}
		return sb.toString();
	}
}


text:
require_relative './test_helper'

class TestInvoice < MiniTest::Test
  def test_list
    mock_call_api("invoice.list", { "page" => 1 }, "invoice_list_response")

    invoices = FreshBooksLegacy::Invoice.list
    assert_equal 3, invoices.size
    assert_invoice invoices[0], 0
    assert_invoice invoices[1], 1
  end

  def test_get
    invoice_id = 2
    mock_call_api("invoice.get", { "invoice_id" => invoice_id }, "invoice_get_response")

    invoice = FreshBooksLegacy::Invoice.get(invoice_id)
    assert_invoice invoice, 0, true
  end

  def test_create
    invoice = FreshBooksLegacy::Invoice.new
    assert_nil invoice.invoice_id

    mock_call_api("invoice.create", { "invoice" => invoice }, "invoice_create_response")
    assert invoice.create
    assert_equal 1, invoice.invoice_id
  end

  def test_update
    invoice = FreshBooksLegacy::Invoice.new
    invoice.invoice_id = 1

    mock_call_api("invoice.update", { "invoice" => invoice }, "success_response")
    assert invoice.update
  end

  def test_delete
    invoice = FreshBooksLegacy::Invoice.new
    invoice.invoice_id = 2
    mock_call_api("invoice.delete", { "invoice_id" => invoice.invoice_id }, "success_response")

    assert invoice.delete
  end

  def test_send_by_email
    invoice = FreshBooksLegacy::Invoice.new
    invoice.invoice_id = 2
    mock_call_api("invoice.sendByEmail", { "invoice_id" => invoice.invoice_id }, "success_response")

    assert invoice.send_by_email
  end

  def test_send_by_snail_mail
    invoice = FreshBooksLegacy::Invoice.new
    invoice.invoice_id = 2
    mock_call_api("invoice.sendBySnailMail", { "invoice_id" => invoice.invoice_id }, "success_response")

    assert invoice.send_by_snail_mail
  end

private

  def mock_call_api(method, options, response_fixture)
    FreshBooksLegacy::Base.connection.
      expects(:call_api).
      with(method, options).
      returns(FreshBooksLegacy::Response.new(fixture_xml_content(response_fixture)))
  end

  def assert_invoice(invoice, number, expanded_form = false)
    number = number + 1

    assert_equal number, invoice.invoice_id
    assert_equal "number#{number}", invoice.number
    assert_equal number, invoice.client_id
    assert_equal number, invoice.recurring_id
    assert_equal "draft", invoice.status
    assert_equal (number * 100), invoice.amount
    assert_equal (number * 100) / 2, invoice.amount_outstanding
    assert_equal Date.parse("2009-02-0#{number}"), invoice.date

    assert_equal number, invoice.po_number
    assert_equal number.to_f, invoice.discount
    assert_equal "notes#{number}", invoice.notes
    assert_equal "terms#{number}", invoice.terms
    assert_equal "first_name#{number}", invoice.first_name
    assert_equal "last_name#{number}", invoice.last_name
    assert_equal "p_street1#{number}", invoice.p_street1
    assert_equal "p_street2#{number}", invoice.p_street2
    assert_equal "p_city#{number}", invoice.p_city
    assert_equal "p_state#{number}", invoice.p_state
    assert_equal "p_country#{number}", invoice.p_country
    assert_equal "p_code#{number}", invoice.p_code

    assert_equal "return_uri#{number}", invoice.return_uri
    assert_equal DateTime.parse("2009-08-#{number} 0#{number}:00:00 -04:00"), invoice.updated

    assert_equal "client_view#{number}", invoice.links.client_view
    assert_equal "view#{number}", invoice.links.view
    assert_equal "edit#{number}", invoice.links.edit

    lines = invoice.lines
    assert_equal 1, lines.size
    lines.each_with_index do |line, index|
      assert_line(line, index)
    end
  end

  def assert_line(line, number)
    number = number + 1

    assert_equal number.to_f, line.amount
    assert_equal "name#{number}", line.name
    assert_equal "description#{number}", line.description
    assert_equal number.to_f, line.unit_cost
    assert_equal number, line.quantity
    assert_equal "tax1_name#{number}", line.tax1_name
    assert_equal "tax2_name#{number}", line.tax2_name
    assert_equal number.to_f, line.tax1_percent
    assert_equal number.to_f, line.tax2_percent
  end
end


text:
Lets-Node-exp-express-routes
============================

Lets Node Example Express Routes


text:
package org.carewebframework.shell.layout;

/**
 * Interface for implementing a layout loader.
 */
public interface ILayoutLoader {

    /**
     * The unique identifier for this loader.
     *
     * @return Return the unique identifier for this loader.
     */
    String getId();

    /**
     * Loads the named layout.
     *
     * @param layoutName The layout name.
     * @return The loaded layout.
     */
    Layout loadLayout(String layoutName);
}


text:
def makeDraggable(widget):
    element = widget.getElement()
    DOM.setAttribute(element, 'draggable', True)
    # the following are needed for older versions of webkit/safari
    widget.setStyleAttribute('-webkit-user-drag', 'element')
    widget.setStyleAttribute('-webkit-user-select', 'none')


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/MBDeleteFileAction.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/MBDeleteFileAction</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>FileActions.h</DeclaredIn>

			<NodeRef refid="12"/>
		</Token>

	</File>
</Tokens>


text:
import { Template } from 'meteor/templating';
import { FlowRouter } from 'meteor/kadira:flow-router';

// The Header menu does not use dropdown menus, but most menus do.
// Here's how to do the required initialization for Semantic UI dropdown menus.
Template.Header.onRendered(function enableDropDown() {
  this.$('.dropdown').dropdown();
});

Template.Header.helpers({
  routeUserName() {
    return FlowRouter.getParam('username');
  },
});


text:
"""
These "weapons" are attacks, not weapons per se.
They are bound to a creature.

The idea is that beyond the standard weapons more exotic ones can be added.
Finesse is a quality that springs to mind.

TODO the standard weapons will be loaded from a JSON or a CSV file.
 for now, they are hardcoded here temporarily.

"""
from .action import Action
from .melee import MeleeAttack
from ..dice import AttackRoll, Dice
from .enums import AttackType
from typing import *
__all__ = ['equip_standard_weapon', 'weapons']

# todo make into json/csv
weapons = {'club': 4,
           'greatclub': 8,
           'dagger': 4,
           'shortsword': 6,
           'longsword': 8, 'bastardsword': 10, 'greatsword': 12,
           'rapier': 8, 'scimitar': 6, 'sickle': 4,
           'handaxe': 6, 'battleaxe': 8, 'waraxe': 10, 'greataxe': 12,
           'javelin': 6, 'spear': 6, 'flail': 8, 'glaive': 10, 'halberd': 10, 'lance': 12, 'pike': 10,
           'trident': 6,
           'war pick': 8,
           'lighthammer': 4, 'mace': 6, 'warhammer': 8,
           'quaterstaff': 6, 'morningstar': 8, 'punch': 1,
           'whip': 4}

# todo make into a class method once all set up
def equip_standard_weapon(creature,
                          weapon_name: str,
                          modifier:int=0) -> Action:
    """
    This creates the attack but does not add it to creature.actions
    """
    # ## determine if weapon is known
    if weapon_name not in weapon_name:
        raise ValueError(f'{weapon_name} does not appear in the list of weapons known. {list(weapons.keys())}')
    # ## get info
    # todo change:
    weapon_data = weapons[weapon_name]  # int now, Dict later!
    ability_name = 'str'
    damage = weapon_data
    print(damage)
    damage_dice = Dice(damage, 0)
    attack_roll = AttackRoll(name=weapon_name,
                             ability_die=creature[ability_name],
                             damage_dice=damage_dice,
                             modifier=modifier
                             )
    # ## determine weapon type
    # todo for now, everything is a melee weapon.
    attack_type = AttackType.melee
    if attack_type == AttackType.melee:
        SpecificAttack = MeleeAttack
    else:
        raise NotImplementedError('Ranged etc. attacks are made yet.')
    return SpecificAttack(creature=creature,
                          name=weapon_name,
                          attack_roll=attack_roll
                            )


text:
package org.kuali.continuity.util;

import static org.junit.Assert.*;

import org.junit.Test;

public class DataUtilTest {

	@Test
	public void testSafeTrimmingString() {
		String leadingSpace = "   abc";
		assertEquals(DataUtil.safeTrimmingString(leadingSpace), "abc");
		String trailingSpace = "abc   ";
		assertEquals(DataUtil.safeTrimmingString(trailingSpace), "abc");
		String middleSpace = " a bc   ";
		assertEquals(DataUtil.safeTrimmingString(middleSpace), "a bc");
		String nullString = "";
		assertEquals(DataUtil.safeTrimmingString(nullString), "");
		assertEquals(DataUtil.safeTrimmingString(null), "");
	}

}


text:
package edu.psu.compbio.seqcode.gse.deepseq.utilities;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import edu.psu.compbio.seqcode.gse.datasets.general.NamedRegion;
import edu.psu.compbio.seqcode.gse.datasets.general.Region;
import edu.psu.compbio.seqcode.gse.datasets.seqdata.SeqLocator;
import edu.psu.compbio.seqcode.gse.datasets.species.Genome;
import edu.psu.compbio.seqcode.gse.datasets.species.Organism;
import edu.psu.compbio.seqcode.gse.deepseq.DeepSeqExpt;
import edu.psu.compbio.seqcode.gse.deepseq.ReadHit;
import edu.psu.compbio.seqcode.gse.deepseq.discovery.SingleConditionFeatureFinder;
import edu.psu.compbio.seqcode.gse.ewok.verbs.ChromRegionIterator;
import edu.psu.compbio.seqcode.gse.tools.utils.Args;
import edu.psu.compbio.seqcode.gse.utils.ArgParser;
import edu.psu.compbio.seqcode.gse.utils.NotFoundException;
import edu.psu.compbio.seqcode.gse.utils.Pair;

/**
 * Outputs a GeneTrack index format file for a deep-seq experiment.
 *
 * @author Shaun Mahony
 * @version	%I%, %G%
 */
public class IDXExporter {
	private Organism org;
	private Genome gen;
	protected DeepSeqExpt expt;
	protected int [] stackedHitCountsPos;
	protected int [] stackedHitCountsNeg;
	private int readLength=1;
	private String outName="out";
	private boolean dbconnected=false;
	private int perBaseMax=-1;
	private boolean needlefiltering=false;
	private static final Logger logger = Logger.getLogger(SingleConditionFeatureFinder.class);

	public static void main(String[] args) throws SQLException, NotFoundException {

		IDXExporter wig = new IDXExporter(args);
		wig.execute();
	}

	public IDXExporter(String [] args) {
		if(args.length==0){
			System.err.println("IDXExporter usage:\n" +
					"\t--species <organism;genome>\n" +
					"\t--(rdb)expt <experiment names>\n" +
					"\t--pbmax <max read count per base>\n" +
					"\t--out <output file name>");
			System.exit(1);
		}
		ArgParser ap = new ArgParser(args);
		try {
			if(ap.hasKey("species")){
				Pair<Organism, Genome> pair = Args.parseGenome(args);
				if(pair != null){
					gen = pair.cdr();
					dbconnected=true;
				}
			}else{
				//Make fake genome... chr lengths provided???
				if(ap.hasKey("geninfo") || ap.hasKey("g")){
					String fName = ap.hasKey("geninfo") ? ap.getKeyValue("geninfo") : ap.getKeyValue("g");
					gen = new Genome("Genome", new File(fName), true);
				}else{
				    gen = null;
				}
			}
		}catch (NotFoundException e) {
			e.printStackTrace();
		}

		outName = Args.parseString(args,"out",outName);
		perBaseMax = Args.parseInteger(args,"pbmax",perBaseMax);
		if(ap.hasKey("pbmax")){needlefiltering=true;}

	    // Load the experiments
	    List<SeqLocator> dbexpts = Args.parseSeqExpt(args, "dbexpt");
	    List<SeqLocator> rdbexpts = Args.parseSeqExpt(args,"rdbexpt");
	    List<File> expts = Args.parseFileHandles(args, "expt");
	    boolean nonUnique = ap.hasKey("nonunique") ? true : false;
	    String fileFormat = Args.parseString(args, "format", "ELAND");
	    if(expts.size()>0 && dbexpts.size() == 0 && rdbexpts.size()==0){
	       	expt= new DeepSeqExpt(gen, expts, nonUnique, fileFormat, (int)readLength);
	    }else if (dbexpts.size() > 0 && expts.size() == 0) {
	    	expt = new DeepSeqExpt(gen, dbexpts, "db", (int)readLength);
	    	dbconnected = true;
	    }else if (rdbexpts.size()>0 && expts.size() == 0){
	    	expt = new DeepSeqExpt(gen, rdbexpts, "readdb", -1);
	    	dbconnected=true;
	    }else {
	      logger.error("Must provide either an aligner output file or Gifford lab DB experiment name for the signal experiment (but not both)");
	      System.exit(1);
	    }
	    logger.info("Expt hit count: " + (int) expt.getHitCount() + ", weight: " + (int) expt.getWeightTotal());
	}

	public void execute(){
		try {
			FileWriter fw = new FileWriter(outName);
			fw.write("chrom\tindex\tforward\treverse\tvalue\n");

			double basesDone=0, printStep=10000000,  numPrint=0;

			ChromRegionIterator chroms = new ChromRegionIterator(gen);
			while(chroms.hasNext()){
				NamedRegion currentRegion = chroms.next();

				//Split the job up into chunks of 100Mbp
				for(int x=currentRegion.getStart(); x<=currentRegion.getEnd(); x+=100000000){
					int y = x+100000000;
					if(y>currentRegion.getEnd()){y=currentRegion.getEnd();}
					Region currSubRegion = new Region(gen, currentRegion.getChrom(), x, y);

					ArrayList<ReadHit> hits = new ArrayList<ReadHit>();
                    hits.addAll(expt.loadHits(currSubRegion));
                    double stackedHitCountsPos[] = make5PrimeLandscape(hits, currSubRegion, perBaseMax, '+');
                    double stackedHitCountsNeg[] = make5PrimeLandscape(hits, currSubRegion, perBaseMax, '-');

                    //Scan regions
					for(int i=currSubRegion.getStart(); i<currSubRegion.getEnd(); i++){
						int offset = i-currSubRegion.getStart();
						double posHits=stackedHitCountsPos[offset];
						double negHits=stackedHitCountsNeg[offset];
						double sum = posHits+negHits;

						if(posHits>0 || negHits>0){
							fw.write("chr"+currSubRegion.getChrom()+"\t"+i+"\t"+String.format("%.1f\t%.1f\t%.1f", posHits, negHits, sum) +"\n");
						}
						//Print out progress
						basesDone++;
						if(basesDone > numPrint*printStep){
							if(numPrint%10==0){System.out.print(String.format("(%.0f)", (numPrint*printStep)));}
							else{System.out.print(".");}
							if(numPrint%50==0 && numPrint!=0){System.out.print("\n");}
							numPrint++;
						}
					}
				}
			}
			System.out.print("\n");
			fw.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected double[] make5PrimeLandscape(ArrayList<ReadHit> hits, Region currReg, int perBaseMax, char strand){
		double[] startcounts = new double[(int)currReg.getWidth()+1];
        for(int i=0; i<=currReg.getWidth(); i++){startcounts[i]=0;}
        for(ReadHit r : hits){
            if(strand=='.' || r.getStrand()==strand){
            	if(r.getFivePrime()>=currReg.getStart() && r.getFivePrime()<=currReg.getEnd()){
	                int offset5=inBounds(r.getFivePrime()-currReg.getStart(),0,currReg.getWidth());
	                if(!needlefiltering || (startcounts[offset5] <= perBaseMax)){
	                    if(needlefiltering && (startcounts[offset5]+r.getWeight() > perBaseMax))
	                    	startcounts[offset5]=perBaseMax;
	                    else
	                    	startcounts[offset5]+=r.getWeight();
	                }
            	}
            }
        }
        return(startcounts);
    }
	//keep the number in bounds
	protected final double inBounds(double x, double min, double max){
		if(x<min){return min;}
		if(x>max){return max;}
		return x;
	}
	protected final int inBounds(int x, int min, int max){
		if(x<min){return min;}
		if(x>max){return max;}
		return x;
	}
}


text:
// Copyright 2016 Rolosoft Ltd
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// <copyright file="AuthorizationCodeStore.cs" company="Rolosoft Ltd">
// Copyright (c) Rolosoft Ltd. All rights reserved.
// </copyright>
namespace Rsft.Identity3.CacheRedis.Stores
{
    using System.Diagnostics.Contracts;
    using Entities;
    using IdentityServer3.Core.Models;
    using IdentityServer3.Core.Services;
    using Interfaces;

    /// <summary>
    /// The Authorization Code Store
    /// </summary>
    /// <seealso cref="IAuthorizationCodeStore" />
    public sealed class AuthorizationCodeStore : RedisStoreBase<AuthorizationCode>, IAuthorizationCodeStore
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AuthorizationCodeStore"/> class.
        /// </summary>
        /// <param name="cacheManager">The cache manager.</param>
        /// <param name="cacheConfiguration">The cache configuration.</param>
        internal AuthorizationCodeStore(
            ICacheManager<AuthorizationCode> cacheManager,
            IConfiguration<RedisCacheConfigurationEntity> cacheConfiguration)
            : base(cacheManager, cacheConfiguration)
        {
            Contract.Requires(cacheManager != null);
            Contract.Requires(cacheConfiguration != null);
        }

        /// <summary>
        /// Prefixes the key.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>The Prefixed Key</returns>
        protected override string PrefixKey(string key)
        {
            return $"ACS_{key}";
        }
    }
}


text:
#include "testClasses.h"

#define SERIALISATION_ARRAY_TEST( type )                                                                               \
    SERIALISATION_TEST( Container, Vector, TestClassArray< type >, type, MakeSeed<type>( 42 ) , GetRandom<uint32_t>() );

SERIALISATION_ALL_TYPES(SERIALISATION_ARRAY_TEST);


text:
package machinelabel

import (
	mapiv1 "github.com/openshift/cluster-api/pkg/apis/machine/v1beta1"
	"github.com/pkg/errors"
	"github.com/rook/rook/pkg/operator/ceph/disruption/controllerconfig"
	corev1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/types"
	"sigs.k8s.io/controller-runtime/pkg/client"
	"sigs.k8s.io/controller-runtime/pkg/controller"
	"sigs.k8s.io/controller-runtime/pkg/handler"
	"sigs.k8s.io/controller-runtime/pkg/manager"
	"sigs.k8s.io/controller-runtime/pkg/reconcile"
	"sigs.k8s.io/controller-runtime/pkg/source"
)

const (
	osdPodLabelKey         = "app"
	osdPODLabelValue       = "rook-ceph-osd"
	osdClusterNameLabelKey = "rook_cluster"
)

// Add adds a new Controller to the Manager based on machinelabel.ReconcileMachineLabel and registers the relevant watches and handlers.
// Read more about how Managers, Controllers, and their Watches, Handlers, Predicates, etc work here:
// https://godoc.org/github.com/kubernetes-sigs/controller-runtime/pkg
func Add(mgr manager.Manager, context *controllerconfig.Context) error {
	reconcileMachineLabel := &ReconcileMachineLabel{
		client:  mgr.GetClient(),
		scheme:  mgr.GetScheme(),
		options: context,
	}

	reconciler := reconcile.Reconciler(reconcileMachineLabel)
	// create a new controller
	c, err := controller.New(controllerName, mgr, controller.Options{Reconciler: reconciler})
	if err != nil {
		return errors.Wrapf(err, "could not create controller %q", controllerName)
	}

	// Watch for the machines and enqueue the machineRequests if the machine is occupied by the osd pods
	err = c.Watch(&source.Kind{Type: &mapiv1.Machine{}}, handler.EnqueueRequestsFromMapFunc(
		handler.MapFunc(func(obj client.Object) []reconcile.Request {
			clusterNamespace, isNamespacePresent := obj.GetLabels()[MachineFencingNamespaceLabelKey]
			if !isNamespacePresent || len(clusterNamespace) == 0 {
				return []reconcile.Request{}
			}
			clusterName, isClusterNamePresent := obj.GetLabels()[MachineFencingLabelKey]
			if !isClusterNamePresent || len(clusterName) == 0 {
				return []reconcile.Request{}
			}
			req := reconcile.Request{NamespacedName: types.NamespacedName{Name: clusterName, Namespace: clusterNamespace}}
			return []reconcile.Request{req}
		}),
	))
	if err != nil {
		return errors.Wrap(err, "could not watch machines")
	}

	// Watch for the osd pods and enqueue the CephCluster in the namespace from the pods
	return c.Watch(&source.Kind{Type: &corev1.Pod{}}, handler.EnqueueRequestsFromMapFunc(
		handler.MapFunc(func(obj client.Object) []reconcile.Request {
			_, ok := obj.(*corev1.Pod)
			if !ok {
				return []reconcile.Request{}
			}
			labels := obj.GetLabels()
			if value, present := labels[osdPodLabelKey]; !present || value != osdPODLabelValue {
				return []reconcile.Request{}
			}
			namespace := obj.GetNamespace()
			rookClusterName, present := labels[osdClusterNameLabelKey]
			if !present {
				return []reconcile.Request{}
			}
			req := reconcile.Request{NamespacedName: types.NamespacedName{Namespace: namespace, Name: rookClusterName}}
			return []reconcile.Request{req}
		}),
	))
}


text:
<?php

namespace Werkspot\MessageQueue\ScheduledQueue\Repository;

use Werkspot\MessageQueue\Message\MessageInterface;

class FailedMessage
{
    /**
     * @var MessageInterface
     */
    private $message;

    /**
     * @var int
     */
    private $count;

    public function __construct(MessageInterface $message, int $count)
    {
        $this->message = $message;
        $this->count = $count;
    }

    public function getMessage(): MessageInterface
    {
        return $this->message;
    }

    public function getCount(): int
    {
        return $this->count;
    }
}


text:
package com.github.wesleyegberto.adoptajsr.jsfchat.controller;

import java.io.Serializable;

import jakarta.enterprise.context.SessionScoped;
import jakarta.inject.Named;

import com.github.wesleyegberto.adoptajsr.jsfchat.model.User;

@Named
@SessionScoped
public class UserBean implements Serializable {
	private static final long serialVersionUID = 1L;
	private User user;

	public void startSessionFor(User user) {
		this.user = user;
	}

	public void finishSession() {
		this.user = null;
	}

	public User getUser() {
		return user;
	}

	public String getName() {
		if (user == null)
			return "Anonymous";
		return user.getName();
	}

	public String getNickname() {
		if (user == null)
			return "Anonymous";
		return user.getNickname();
	}

	public boolean isLogged() {
		return user != null;
	}

}


text:
class Solution(object):
    def canFinish(self, numCourses, prerequisites):
        """
        O(V+E)
        :type numCourses: int
        :type prerequisites: List[List[int]]
        :rtype: bool
        """
        zero_indegree = []
        indegree = {}
        outdegree = {}

        # save the indegree and outdegree
        for i, j in prerequisites:
            if i not in indegree:
                indegree[i] = set()
            if j not in outdegree:
                outdegree[j] = set()
            indegree[i].add(j)
            outdegree[j].add(i)

        # find zero indegree in the graph
        for i in range(numCourses):
            if i not in indegree:
                zero_indegree.append(i)

        while zero_indegree:
            prerequest = zero_indegree.pop(0)
            if prerequest in outdegree:
                for course in outdegree[prerequest]:
                    indegree[course].remove(prerequest)
                    # empty
                    if not indegree[course]:
                        zero_indegree.append(course)
                del (outdegree[prerequest])

        # check out degree
        if outdegree:
            return False
        return True

    def canFinish(self, n, pres):

        oud = [[] for _ in range(n)]  # indegree
        ind = [0] * n  # outdegree
        for succ,pre in pres:
            ind[succ] += 1
            oud[pre].append(succ)
        dq = []
        for i in range(n):
            if ind[i] == 0:
                dq.append(i)
        count = 0
        while dq:
            pre_course = dq.pop(0)
            count += 1
            for succ in oud[pre_course]:
                ind[succ] -= 1
                if ind[succ] == 0:
                    dq.append(succ)
        return count == n


text:
package com.enjoyshop.bean;

import java.io.Serializable;
import java.util.List;

/**
 * Created by 高磊华
 * Time  2017/8/8
 * Describe:  热卖商品.也是 一级菜单  二级菜单的数据模型
 *            同时,也是首页跳转到商品列表 的数据模型
 */

public class HotGoods {

    private String           copyright;
    private int              totalCount;
    private int              currentPage;
    private int              totalPage;
    private int              pageSize;
    private List<OrdersBean> orders;
    private List<ListBean>   list;

    public String getCopyright() {
        return copyright;
    }

    public void setCopyright(String copyright) {
        this.copyright = copyright;
    }

    public int getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(int totalCount) {
        this.totalCount = totalCount;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(int totalPage) {
        this.totalPage = totalPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public List<OrdersBean> getOrders() {
        return orders;
    }

    public void setOrders(List<OrdersBean> orders) {
        this.orders = orders;
    }

    public List<ListBean> getList() {
        return list;
    }

    public void setList(List<ListBean> list) {
        this.list = list;
    }

    public static class OrdersBean {
        /**
         * orderType : DESC
         * field : id
         */

        private String orderType;
        private String field;

        public String getOrderType() {
            return orderType;
        }

        public void setOrderType(String orderType) {
            this.orderType = orderType;
        }

        public String getField() {
            return field;
        }

        public void setField(String field) {
            this.field = field;
        }
    }

    public static class ListBean implements Serializable {

        /**
         * id : 1
         * categoryId : 5
         * campaignId : 1
         * name : 联想(Lenovo)拯救者14.0英寸游戏本(i7-4720HQ 4G 1T硬盘 GTX960M 2G独显 FHD IPS屏 背光键盘)黑
         * imgUrl : http://7mno4h.com2.z0.glb.qiniucdn.com/s_recommend_55c1e8f7N4b99de71.jpg
         * price : 5979
         * sale : 8654
         */

        private int    id;
        private int    categoryId;
        private int    campaignId;
        private String name;
        private String imgUrl;
        private double price;
        private double sale;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public int getCategoryId() {
            return categoryId;
        }

        public void setCategoryId(int categoryId) {
            this.categoryId = categoryId;
        }

        public int getCampaignId() {
            return campaignId;
        }

        public void setCampaignId(int campaignId) {
            this.campaignId = campaignId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getImgUrl() {
            return imgUrl;
        }

        public void setImgUrl(String imgUrl) {
            this.imgUrl = imgUrl;
        }

        public double getPrice() {
            return price;
        }

        public void setPrice(double price) {
            this.price = price;
        }

        public double getSale() {
            return sale;
        }

        public void setSale(double sale) {
            this.sale = sale;
        }
    }
}


text:
package org.springframework.cloud.netflix.eureka;

import java.io.IOException;
import java.security.GeneralSecurityException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;

import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.configuration.TlsProperties;
import org.springframework.cloud.netflix.eureka.config.DiscoveryClientOptionalArgsConfiguration;
import org.springframework.cloud.netflix.eureka.http.EurekaClientHttpRequestFactorySupplier;
import org.springframework.cloud.netflix.eureka.http.RestTemplateDiscoveryClientOptionalArgs;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Bean;

import static org.assertj.core.api.Assertions.assertThat;

public class RestTemplateEurekaClientTest extends BaseCertTest {

	private static final Log log = LogFactory.getLog(RestTemplateEurekaClientTest.class);

	private static EurekaServerRunner server;

	private static EurekaClientRunner service;

	@BeforeAll
	public static void setupAll() {
		server = startEurekaServer(RestTemplateEurekaClientTest.RestTemplateTestEurekaServer.class);
		service = startService(server, RestTemplateEurekaClientTest.RestTemplateTestApp.class);
		// Will use RestTemplate
		assertThat(service.discoveryClientOptionalArgs()).isInstanceOf(RestTemplateDiscoveryClientOptionalArgs.class);
		log.info("Successfully asserted that RestTemplate will be used");
		waitForRegistration(() -> new RestTemplateEurekaClientTest().createEurekaClient());
	}

	@AfterAll
	public static void tearDownAll() {
		stopService(service);
		stopEurekaServer(server);
	}

	@Override
	EurekaClientRunner createEurekaClient() {
		return new EurekaClientRunner(RestTemplateTestApp.class, server);
	}

	@SpringBootConfiguration
	@EnableAutoConfiguration
	public static class RestTemplateTestApp {

		// Want to force reusing exactly the same bean as on production without excluding
		// jersey from the classpath
		@Bean
		public RestTemplateDiscoveryClientOptionalArgs forceRestTemplateDiscoveryClientOptionalArgs(
				TlsProperties tlsProperties, DiscoveryClientOptionalArgsConfiguration configuration,
				EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier)
				throws GeneralSecurityException, IOException {
			return configuration.restTemplateDiscoveryClientOptionalArgs(tlsProperties,
					eurekaClientHttpRequestFactorySupplier);
		}

	}

	@SpringBootConfiguration
	@EnableAutoConfiguration
	@EnableEurekaServer
	public static class RestTemplateTestEurekaServer {

	}

}


text:
#include "config.h"
#include "LinkLoader.h"

#include "CSSStyleSheet.h"
#include "CachedCSSStyleSheet.h"
#include "CachedResourceLoader.h"
#include "CachedResourceRequest.h"
#include "ContainerNode.h"
#include "DNS.h"
#include "Document.h"
#include "Frame.h"
#include "FrameView.h"
#include "LinkRelAttribute.h"
#include "Settings.h"
#include "StyleResolver.h"

namespace WebCore {

LinkLoader::LinkLoader(LinkLoaderClient* client)
    : m_client(client)
    , m_linkLoadTimer(this, &LinkLoader::linkLoadTimerFired)
    , m_linkLoadingErrorTimer(this, &LinkLoader::linkLoadingErrorTimerFired)
{
}

LinkLoader::~LinkLoader()
{
    if (m_cachedLinkResource)
        m_cachedLinkResource->removeClient(this);
}

void LinkLoader::linkLoadTimerFired(Timer<LinkLoader>* timer)
{
    ASSERT_UNUSED(timer, timer == &m_linkLoadTimer);
    m_client->linkLoaded();
}

void LinkLoader::linkLoadingErrorTimerFired(Timer<LinkLoader>* timer)
{
    ASSERT_UNUSED(timer, timer == &m_linkLoadingErrorTimer);
    m_client->linkLoadingErrored();
}

void LinkLoader::notifyFinished(CachedResource* resource)
{
    ASSERT_UNUSED(resource, m_cachedLinkResource.get() == resource);

    if (m_cachedLinkResource->errorOccurred())
        m_linkLoadingErrorTimer.startOneShot(0);
    else
        m_linkLoadTimer.startOneShot(0);

    m_cachedLinkResource->removeClient(this);
    m_cachedLinkResource = 0;
}

bool LinkLoader::loadLink(const LinkRelAttribute& relAttribute, const String& type,
                          const String& sizes, const KURL& href, Document* document)
{
    // We'll record this URL per document, even if we later only use it in top level frames
    if (relAttribute.m_iconType != InvalidIcon && href.isValid() && !href.isEmpty()) {
        if (!m_client->shouldLoadLink())
            return false;
        document->addIconURL(href.string(), type, sizes, relAttribute.m_iconType);
    }

    if (relAttribute.m_isDNSPrefetch) {
        Settings* settings = document->settings();
        // FIXME: The href attribute of the link element can be in "//hostname" form, and we shouldn't attempt
        // to complete that as URL <https://bugs.webkit.org/show_bug.cgi?id=48857>.
        if (settings && settings->dnsPrefetchingEnabled() && href.isValid() && !href.isEmpty())
            prefetchDNS(href.host());
    }

#if ENABLE(LINK_PREFETCH)
    if ((relAttribute.m_isLinkPrefetch || relAttribute.m_isLinkSubresource) && href.isValid() && document->frame()) {
        if (!m_client->shouldLoadLink())
            return false;
        ResourceLoadPriority priority = ResourceLoadPriorityUnresolved;
        CachedResource::Type type = CachedResource::LinkPrefetch;
        // We only make one request to the cachedresourcelodaer if multiple rel types are
        // specified,
        if (relAttribute.m_isLinkSubresource) {
            priority = ResourceLoadPriorityLow;
            type = CachedResource::LinkSubresource;
        }
        CachedResourceRequest linkRequest(ResourceRequest(document->completeURL(href)), priority);

        if (m_cachedLinkResource) {
            m_cachedLinkResource->removeClient(this);
            m_cachedLinkResource = 0;
        }
        m_cachedLinkResource = document->cachedResourceLoader()->requestLinkResource(type, linkRequest);
        if (m_cachedLinkResource)
            m_cachedLinkResource->addClient(this);
    }
#endif

    return true;
}

void LinkLoader::released()
{
}

}


text:
package org.assertj.core.error;

import static org.assertj.core.data.Index.atIndex;
import static org.assertj.core.error.ShouldBeAtIndex.shouldBeAtIndex;
import static org.assertj.core.util.Lists.newArrayList;

import static org.assertj.core.api.Assertions.assertThat;

import org.assertj.core.api.TestCondition;
import org.assertj.core.description.Description;
import org.assertj.core.description.TextDescription;
import org.assertj.core.presentation.StandardRepresentation;
import org.junit.jupiter.api.Test;

/**
 * Tests for <code>{@link ShouldBeAtIndex#create(Description, org.assertj.core.presentation.Representation)}</code>.
 *
 * @author Bo Gotthardt
 */
public class ShouldBeAtIndex_create_Test {

  @Test
  public void should_create_error_message() {
    ErrorMessageFactory factory = shouldBeAtIndex(newArrayList("Yoda", "Luke"), new TestCondition<String>("red lightsaber"), atIndex(1),
        "Luke");
    String message = factory.create(new TextDescription("Test"), new StandardRepresentation());
    assertThat(message).isEqualTo(String.format(
        "[Test] %nExpecting:%n <\"Luke\">%nat index <1> to be:%n <red lightsaber>%nin:%n <[\"Yoda\", \"Luke\"]>%n"
    ));
  }
}


text:
Namespace DataSetInterfaceTableAdapters
    ' these are two large interface tables that need to get updated daily and the update querytime can exceed the 30sec. default timeout
    Partial Public Class mpCDSCurveTableAdapter
        Sub SetCommandTimeout(ByVal _timeoutSeconds As Integer)
            For Each Command As System.Data.SqlClient.SqlCommand In Me.CommandCollection
                Command.CommandTimeout = _timeoutSeconds
            Next
        End Sub
    End Class

    Partial Public Class SPRatingsIFaceTableAdapter
        Sub SetCommandTimeout(ByVal _timeoutSeconds As Integer)
            For Each Command As System.Data.SqlClient.SqlCommand In Me.CommandCollection
                Command.CommandTimeout = _timeoutSeconds
            Next
        End Sub
    End Class

End Namespace

Namespace DataSetBespokeTableAdapters
    Partial Public Class PortfolioSPIndustryTableAdapter
        Sub SetCommandTimeout(ByVal _timeoutSeconds As Integer)
            For Each Command As System.Data.SqlClient.SqlCommand In Me.CommandCollection
                Command.CommandTimeout = _timeoutSeconds
            Next
        End Sub
    End Class

    Partial Public Class PortfolioSPTableAdapter
        Sub SetCommandTimeout(ByVal _timeoutSeconds As Integer)
            For Each Command As System.Data.SqlClient.SqlCommand In Me.CommandCollection
                Command.CommandTimeout = _timeoutSeconds
            Next
        End Sub
    End Class

    Partial Public Class PortfolioZSCORETop10Pct
        Sub SetCommandTimeout(ByVal _timeoutSeconds As Integer)
            For Each Command As System.Data.SqlClient.SqlCommand In Me.CommandCollection
                Command.CommandTimeout = _timeoutSeconds
            Next
        End Sub
    End Class

End Namespace


text:
/**
 *
 */
package org.pjay;

import java.util.Random;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author vijayk
 *
 */
@RestController
public class WordController {

	@Value("${words}") String words;

	@RequestMapping("/")
	public String getWord(){
		String[] wordArray = words.split(",");
		Random random = new Random();
		return wordArray[random.nextInt(wordArray.length)];
	}

	// Below are Testing end points for verifying the end points registry keys with eureka server
/*
	@RequestMapping("/hello")
	public String sayHello() {
		return "Hello Microservices";
	}

	@RequestMapping("/hello/{username}")
	public String sayHelloUser(@PathVariable String username) {
		return "Hi there " + username;
	}

	@RequestMapping("/test")
	public String testMethod() {
		return "This is test endpoint response";
	}
*/

}


text:
#include "postgres.h"
#include "fmgr.h"
#include "mb/pg_wchar.h"
#include "../../Unicode/euc_jp_to_utf8.map"
#include "../../Unicode/utf8_to_euc_jp.map"

PG_MODULE_MAGIC;

PG_FUNCTION_INFO_V1(euc_jp_to_utf8);
PG_FUNCTION_INFO_V1(utf8_to_euc_jp);

/* ----------
 * conv_proc(
 *		INTEGER,	-- source encoding id
 *		INTEGER,	-- destination encoding id
 *		CSTRING,	-- source string (null terminated C string)
 *		CSTRING,	-- destination string (null terminated C string)
 *		INTEGER		-- source string length
 * ) returns VOID;
 * ----------
 */
Datum
euc_jp_to_utf8(PG_FUNCTION_ARGS)
{
	unsigned char *src = (unsigned char *) PG_GETARG_CSTRING(2);
	unsigned char *dest = (unsigned char *) PG_GETARG_CSTRING(3);
	int			len = PG_GETARG_INT32(4);

	CHECK_ENCODING_CONVERSION_ARGS(PG_EUC_JP, PG_UTF8);

	LocalToUtf(src, len, dest,
			   LUmapEUC_JP, lengthof(LUmapEUC_JP),
			   NULL, 0,
			   NULL,
			   PG_EUC_JP);

	PG_RETURN_VOID();
}

Datum
utf8_to_euc_jp(PG_FUNCTION_ARGS)
{
	unsigned char *src = (unsigned char *) PG_GETARG_CSTRING(2);
	unsigned char *dest = (unsigned char *) PG_GETARG_CSTRING(3);
	int			len = PG_GETARG_INT32(4);

	CHECK_ENCODING_CONVERSION_ARGS(PG_UTF8, PG_EUC_JP);

	UtfToLocal(src, len, dest,
			   ULmapEUC_JP, lengthof(ULmapEUC_JP),
			   NULL, 0,
			   NULL,
			   PG_EUC_JP);

	PG_RETURN_VOID();
}


text:
#import "CSNModalWindow.h"
#import "CSNTransit.h"
#import "CSNHeroView.h"
#import "CSNSecondaryActionView.h"

@implementation CSNModalWindow {
    UIView *modalWindowBkg;
    CSNSecondaryActionView *cardView;
    UIButton *closeModalWindow;
}

- (id) initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {

    }
    return self;
}

- (id) initWithFrame:(CGRect)frame forAd:(CSNAd *)nativeAd withReportsBuilder:(CSNAdReportsBuilder *)reportsBuilder {
    self = [super initWithFrame:frame];
    if (self)
    {

        modalWindowBkg = [[UIView alloc] initWithFrame:self.bounds];
        CGRect cardViewRect = CGRectMake(self.bounds.size.width/2.0, 500.0, self.bounds.size.width - 50.0, 325.0);
        cardView = [[CSNSecondaryActionView alloc] initWithFrame:cardViewRect forAd:nativeAd withReportsBuilder:reportsBuilder];

        [modalWindowBkg setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.6]];
        [modalWindowBkg setAlpha:0.0];
        [self addSubview:modalWindowBkg];
        [self addSubview:cardView];
        [modalWindowBkg setUserInteractionEnabled:YES];

        NSString *imagePath = [[NSBundle bundleForClass:[CSNModalWindow class]] pathForResource:@"close_interstitial_card" ofType:@"png"];
        NSData *imageData = [NSData dataWithContentsOfFile:imagePath];
        UIImage *buttonBkg = [[UIImage alloc] initWithData:imageData];
        CGRect closeInterstitialCardButtonRect = CGRectMake(self.bounds.size.width/2.0,(self.bounds.size.height - 130.0),80.0, 80.0);
        closeModalWindow = [UIButton buttonWithType:UIButtonTypeCustom];
        closeModalWindow.frame = closeInterstitialCardButtonRect;
        CGRect closeModalWindowFrame = [closeModalWindow frame];

        closeModalWindowFrame.origin.x = (closeModalWindow.frame.origin.x - closeModalWindow.frame.size.width/2);

        [closeModalWindow setFrame:closeModalWindowFrame];
        [closeModalWindow setAlpha:0.0];
        [closeModalWindow setBackgroundImage:buttonBkg forState:UIControlStateNormal];
        [closeModalWindow addTarget:self action:@selector(tapViewAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:closeModalWindow];

        CGFloat cardTop = (closeModalWindowFrame.origin.y/2) - (cardView.frame.size.height/2);

        [UIView animateWithDuration:0.3
                         animations:^{

                             [closeModalWindow setAlpha:1.0];
                             [modalWindowBkg setAlpha:1.0];
                             [cardView setAlpha:1.0];
                             [cardView setFrame:CGRectMake(cardView.frame.origin.x, cardTop, cardView.frame.size.width, cardView.frame.size.height)];

                         }
                         completion:^(BOOL finished){

                         }];

    }
    return self;
}

- (id<CSNComponentView>)getSecondaryActionView {
    return cardView;
}

-(void) tapViewAction:(UIGestureRecognizer *)sender{

    [UIView animateWithDuration:0.3
                     animations:^{

                         [closeModalWindow setAlpha:0.0];
                         [modalWindowBkg setAlpha:0.0];
                         [cardView setAlpha:0.0];
                         [cardView setFrame:CGRectMake(cardView.frame.origin.x, 500.0, cardView.frame.size.width, cardView.frame.size.height)];

                     }
                     completion:^(BOOL finished){
                         [self setHidden:YES];
                         // avoid tracking this view for impressions by hidding it and setting its size to 0
                         [cardView setFrame:CGRectMake(0,0,0,0)];
                         [cardView setHidden:YES];
                         [self removeFromSuperview];
                     }];

}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
<!-- Meta -->
<meta charset="utf-8">
<title>Running Shoes | Toko Sepatu Online Original Terlengkap</title>
<meta name="keywords" content="Sepatu, Murah, Original, Baru, Terlengkap, Harga, Bersaing" />
<meta name="author" content="Hakko Bio Richard"/>
<meta name="editor" content="Arifin Jiwantoko">

<!-- Mobile Specific -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<meta property="og:title" content=""/>
<!-- Facebook Open Graph -->
<meta property="og:description" content=""/>
<meta property="og:type" content=""/>
<meta property="og:url" content=""/>
<meta property="og:image" content=""/>

<!-- CSS -->
<link href="../css/bootstrap.css" rel="stylesheet">
<link href="../css/bootstrap-responsive.css" rel="stylesheet">
<link href="../css/style.css" rel="stylesheet">

<!-- Font -->
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans:400,700">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Serif">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Boogaloo">
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Economica:700,400italic">

  <!-- Le HTML5 shim, for IE6-8 support of HTML5 elements -->
  <!--[if lt IE 9]>
    <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
  <![endif]-->


text:
package org.pentaho.di.trans.steps.zendesk;

import java.util.List;

import org.pentaho.di.core.annotations.Step;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.exception.KettleStepException;
import org.pentaho.di.core.exception.KettleXMLException;
import org.pentaho.di.core.row.RowMetaInterface;
import org.pentaho.di.core.row.ValueMetaInterface;
import org.pentaho.di.core.variables.VariableSpace;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.repository.ObjectId;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.pentaho.di.trans.step.StepDataInterface;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.metastore.api.IMetaStore;
import org.w3c.dom.Node;

@Step(
    id = "ZendeskInputGroupMemberships",
    image = "org/pentaho/di/trans/steps/zendesk/zendesk.png",
    i18nPackageName = "org.pentaho.di.trans.steps.zendesk",
    name = "ZendeskInputGroupMemberships.Name",
    description = "ZendeskInputGroupMemberships.TooltipDesc",
    categoryDescription = "i18n:org.pentaho.di.trans.step:BaseStep.Category.Input"
  )
public class ZendeskInputGroupMembershipsMeta extends ZendeskInputMeta {

  private String groupMembershipIdFieldname;
  private String groupMembershipUrlFieldname;
  private String userIdFieldname;
  private String groupIdFieldname;
  private String createdAtFieldname;
  private String updatedAtFieldname;
  private String defaultGroupFieldname;

  public String getCreatedAtFieldname() {
    return createdAtFieldname;
  }

  public String getDefaultGroupFieldname() {
    return defaultGroupFieldname;
  }

  @Override
  public void getFields( RowMetaInterface inputRowMeta, String name, RowMetaInterface[] info, StepMeta nextStep,
      VariableSpace space, Repository repository, IMetaStore metaStore ) throws KettleStepException {
    super.getFields( inputRowMeta, name, info, nextStep, space, repository, metaStore );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getGroupMembershipIdFieldname() ), ValueMetaInterface.TYPE_INTEGER );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getGroupMembershipUrlFieldname() ), ValueMetaInterface.TYPE_STRING );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getUserIdFieldname() ), ValueMetaInterface.TYPE_INTEGER );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getGroupIdFieldname() ), ValueMetaInterface.TYPE_INTEGER );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getCreatedAtFieldname() ), ValueMetaInterface.TYPE_DATE );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getUpdatedAtFieldname() ), ValueMetaInterface.TYPE_DATE );
    addFieldToRow( inputRowMeta, space.environmentSubstitute( getDefaultGroupFieldname() ), ValueMetaInterface.TYPE_BOOLEAN );
  }

  public String getGroupIdFieldname() {
    return groupIdFieldname;
  }

  public String getGroupMembershipIdFieldname() {
    return groupMembershipIdFieldname;
  }

  public String getGroupMembershipUrlFieldname() {
    return groupMembershipUrlFieldname;
  }

  @Override
  public StepInterface getStep( StepMeta stepMeta, StepDataInterface stepDataInterface, int copyNr,
      TransMeta transMeta, Trans trans ) {
    return new ZendeskInputGroupMemberships( stepMeta, stepDataInterface, copyNr, transMeta, trans );
  }

  @Override
  public StepDataInterface getStepData() {
    return new ZendeskInputGroupMembershipsData();
  }

  public String getUpdatedAtFieldname() {
    return updatedAtFieldname;
  }

  public String getUserIdFieldname() {
    return userIdFieldname;
  }

  @Override
  public String getXML() throws KettleException {
    StringBuilder xml = new StringBuilder();
    xml.append( super.getXML() );
    xml.append( "    " ).append( XMLHandler.addTagValue( "groupMembershipIdFieldname", getGroupMembershipIdFieldname() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "groupMembershipUrlFieldname", getGroupMembershipUrlFieldname() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "userIdFieldname", getUserIdFieldname() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "groupIdFieldname", getGroupIdFieldname() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "createdAtFieldname", getCreatedAtFieldname() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "updatedAtFieldname", getUpdatedAtFieldname() ) );
    xml.append( "    " ).append( XMLHandler.addTagValue( "defaultGroupFieldname", getDefaultGroupFieldname() ) );
    return xml.toString();
  }

  @Override
  public void loadXML( Node stepnode, List<DatabaseMeta> databases, IMetaStore metaStore ) throws KettleXMLException {
    super.loadXML( stepnode, databases, metaStore );
    setGroupMembershipIdFieldname( XMLHandler.getTagValue( stepnode, "groupMembershipIdFieldname" ) );
    setGroupMembershipUrlFieldname( XMLHandler.getTagValue( stepnode, "groupMembershipUrlFieldname" ) );
    setUserIdFieldname( XMLHandler.getTagValue( stepnode, "userIdFieldname" ) );
    setGroupIdFieldname( XMLHandler.getTagValue( stepnode, "groupIdFieldname" ) );
    setCreatedAtFieldname( XMLHandler.getTagValue( stepnode, "createdAtFieldname" ) );
    setUpdatedAtFieldname( XMLHandler.getTagValue( stepnode, "updatedAtFieldname" ) );
    setDefaultGroupFieldname( XMLHandler.getTagValue( stepnode, "defaultGroupFieldname" ) );
  }

  @Override
  public void readRep( Repository rep, IMetaStore metaStore, ObjectId id_step, List<DatabaseMeta> databases )
    throws KettleException {
    super.readRep( rep, metaStore, id_step, databases );
    setGroupMembershipIdFieldname( rep.getStepAttributeString( id_step, "groupMembershipIdFieldname" ) );
    setGroupMembershipUrlFieldname( rep.getStepAttributeString( id_step, "groupMembershipUrlFieldname" ) );
    setUserIdFieldname( rep.getStepAttributeString( id_step, "userIdFieldname" ) );
    setGroupIdFieldname( rep.getStepAttributeString( id_step, "groupIdFieldname" ) );
    setCreatedAtFieldname( rep.getStepAttributeString( id_step, "createdAtFieldname" ) );
    setUpdatedAtFieldname( rep.getStepAttributeString( id_step, "updatedAtFieldname" ) );
    setDefaultGroupFieldname( rep.getStepAttributeString( id_step, "defaultGroupFieldname" ) );
  }

  @Override
  public void saveRep( Repository rep, IMetaStore metaStore, ObjectId id_transformation, ObjectId id_step )
    throws KettleException {
    // TODO Auto-generated method stub
    super.saveRep( rep, metaStore, id_transformation, id_step );
    rep.saveStepAttribute( id_transformation, id_step, "groupMembershipIdFieldname", getGroupMembershipIdFieldname() );
    rep.saveStepAttribute( id_transformation, id_step, "groupMembershipUrlFieldname", getGroupMembershipUrlFieldname() );
    rep.saveStepAttribute( id_transformation, id_step, "userIdFieldname", getUserIdFieldname() );
    rep.saveStepAttribute( id_transformation, id_step, "groupIdFieldname", getGroupIdFieldname() );
    rep.saveStepAttribute( id_transformation, id_step, "createdAtFieldname", getCreatedAtFieldname() );
    rep.saveStepAttribute( id_transformation, id_step, "updatedAtFieldname", getUpdatedAtFieldname() );
    rep.saveStepAttribute( id_transformation, id_step, "defaultGroupFieldname", getDefaultGroupFieldname() );
  }

  public void setCreatedAtFieldname( String createdAtFieldname ) {
    this.createdAtFieldname = createdAtFieldname;
  }

  @Override
  public void setDefault() {
    super.setDefault();
    setGroupMembershipIdFieldname( "Group_Membership_ID" );
    setGroupMembershipUrlFieldname( "Group_Membership_URL" );
    setUserIdFieldname( "User_ID" );
    setGroupIdFieldname( "Group_ID" );
    setCreatedAtFieldname( "Created_Time" );
    setUpdatedAtFieldname( "Updated_Time" );
    setDefaultGroupFieldname( "Is_Default_Group" );
  }

  public void setDefaultGroupFieldname( String defaultGroupFieldname ) {
    this.defaultGroupFieldname = defaultGroupFieldname;
  }

  public void setGroupIdFieldname( String groupIdFieldname ) {
    this.groupIdFieldname = groupIdFieldname;
  }

  public void setGroupMembershipIdFieldname( String groupMembershipIdFieldname ) {
    this.groupMembershipIdFieldname = groupMembershipIdFieldname;
  }

  public void setGroupMembershipUrlFieldname( String groupMembershipUrlFieldname ) {
    this.groupMembershipUrlFieldname = groupMembershipUrlFieldname;
  }

  public void setUpdatedAtFieldname( String updatedAtFieldname ) {
    this.updatedAtFieldname = updatedAtFieldname;
  }

  public void setUserIdFieldname( String userIdFieldname ) {
    this.userIdFieldname = userIdFieldname;
  }

}


text:
using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
using TestApp;

namespace SampleLocalApp.Droid
{
    [Activity(Label = "SampleLocalApp", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            Messier16.Forms.Android.Controls.Messier16Controls.InitAll();
            LoadApplication(new App());
        }
    }
}


text:
formalMethods
=============

Academic projects for Formal Methods course (PUCRS 2014/2).


text:
#include <aws/ebs/model/Block.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace EBS
{
namespace Model
{

Block::Block() :
    m_blockIndex(0),
    m_blockIndexHasBeenSet(false),
    m_blockTokenHasBeenSet(false)
{
}

Block::Block(JsonView jsonValue) :
    m_blockIndex(0),
    m_blockIndexHasBeenSet(false),
    m_blockTokenHasBeenSet(false)
{
  *this = jsonValue;
}

Block& Block::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("BlockIndex"))
  {
    m_blockIndex = jsonValue.GetInteger("BlockIndex");

    m_blockIndexHasBeenSet = true;
  }

  if(jsonValue.ValueExists("BlockToken"))
  {
    m_blockToken = jsonValue.GetString("BlockToken");

    m_blockTokenHasBeenSet = true;
  }

  return *this;
}

JsonValue Block::Jsonize() const
{
  JsonValue payload;

  if(m_blockIndexHasBeenSet)
  {
   payload.WithInteger("BlockIndex", m_blockIndex);

  }

  if(m_blockTokenHasBeenSet)
  {
   payload.WithString("BlockToken", m_blockToken);

  }

  return payload;
}

} // namespace Model
} // namespace EBS
} // namespace Aws


text:
import os
from itertools import chain
from .log import warn
from .entry import Entry, LoadError

DB_FILE_DEFAULT = os.path.expanduser(os.path.join("~", ".ripple.txt"))
DB_FILE = os.path.realpath(os.environ.get('RIPPLE_DB', DB_FILE_DEFAULT))
DB_DIR = os.environ.get('RIPPLE_DB_DIR', None)
if DB_DIR and os.path.isdir(DB_DIR):
    DB_DIR = os.path.realpath(DB_DIR)
else:
    DB_DIR = None
DB_TMP_FILE = DB_FILE + '.tmp'

def get_db(write=False):
    """
    Opens the database file and returns the resulting instance.
    """
    files = set()
    if DB_DIR and not write:
        files = set([os.path.join(DB_DIR, file) for file in os.listdir(DB_DIR)])
    if os.path.isfile(DB_FILE):
        files.add(DB_FILE)

    if not files:
        return DB()

    handles = []
    for file in files:
        handles.append(open(file, 'r+'))

    return DB.load(chain(*handles))

def save_db(db):
    """
    Saves the database to disk
    """
    with open(DB_TMP_FILE, 'w') as handle:
        db.dump(handle)
    os.rename(DB_TMP_FILE, DB_FILE)

class DB(object):
    """
    The database of all entries.

    Nothing fancy for now, everything in-memory, so you should probably
    archive entries at some point.
    """
    def __init__(self):
        self.entries = []

    def append(self, entry):
        """
        Adds the given entry at the end of the database.

        @param Entry entry
        """
        self.entries.append(entry)

    def dump(self, writer):
        """
        Encodes the state into text format and writes it
        to the given writer.

        @param [.write(str)-supporting object] writer
        """
        for entry in self.entries:
            writer.write(entry.dumps())
            writer.write("\n")

    @classmethod
    def load(cls, iterable):
        """
        Creates a new DB instance, pre-populated with the parseable
        entries.

        @param iterable iterable (usually emitting lines)
        """
        x = 1
        db = DB()
        for line in iterable:
            if not line.strip() or line[0] == '#':
                continue
            try:
                entry = Entry.loads(line.strip(), id=x)
            except LoadError:
                warn("unable to parse a line!")
                continue
            if entry:
                db.entries.append(entry)
                x += 1

        db.entries.sort(cmp=lambda a, b: cmp(a.start, b.start))
        return db

    def get_entries(self):
        """
        Returns an iterator over all entries
        """
        return self.entries

    def get_unfinished_entries(self):
        """
        Returns a generator over all entries which have not been
        finished yet. Usually this should only be one entry.

        @return generator
        """
        for entry in self.entries:
            if not entry.end:
                yield entry

    def get_most_recent_entry(self):
        """
        Returns the most-recently added entry.

        @return Entry
        """
        if self.entries:
            return self.entries[-1]
        return None


text:
<!--
~ Copyright 2017-present Open Networking Foundation
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~     http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
    <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackNetworkListCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackPortListCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackRouterListCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackFloatingIpListCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackPurgeStateCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackSyncStateCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackSecurityGroupListCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackPurgeRulesCommand"/>
        </command>
        <command>
            <action class="org.onosproject.openstacknetworking.cli.OpenstackSyncRulesCommand"/>
        </command>
    </command-bundle>
</blueprint>


text:
package org.apache.camel.component.undertow.rest;

import org.apache.camel.BindToRegistry;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.undertow.BaseUndertowTest;
import org.apache.camel.component.undertow.DefaultUndertowHttpBinding;
import org.apache.camel.component.undertow.UndertowHttpBinding;
import org.junit.Test;

public class RestUndertowHttpGetWildcardsTest extends BaseUndertowTest {

    @BindToRegistry("mybinding")
    private UndertowHttpBinding binding = new DefaultUndertowHttpBinding();

    @Test
    public void testProducerGet() throws Exception {
        String out = template.requestBody("undertow:http://localhost:{{port}}/users/123/basic", null, String.class);
        assertEquals("123;Donald Duck", out);
    }

    @Test
    public void testServletProducerGetWildcards() throws Exception {
        String out = template.requestBody("undertow:http://localhost:{{port}}/users/456/name=g*", null, String.class);
        assertEquals("456;Goofy", out);
    }

    @Override
    protected RouteBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                // configure to use undertow on localhost with the given port
                restConfiguration().component("undertow").host("localhost").port(getPort()).endpointProperty("undertowHttpBinding", "#mybinding");

                // use the rest DSL to define the rest services
                rest("/users/").get("{id}/{query}").route().to("log:query").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        String id = exchange.getIn().getHeader("id", String.class);
                        exchange.getOut().setBody(id + ";Goofy");
                    }
                }).endRest().get("{id}/basic").route().to("log:input").process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        String id = exchange.getIn().getHeader("id", String.class);
                        exchange.getOut().setBody(id + ";Donald Duck");
                    }
                }).endRest();
            }
        };
    }

}


text:
static const char *ECHO_SERVER_NAME = "org.freedesktop.DBus.Examples.Echo";
static const char *ECHO_SERVER_PATH = "/org/freedesktop/DBus/Examples/Echo";

EchoServer::EchoServer(DBus::Connection &connection)
: DBus::ObjectAdaptor(connection, ECHO_SERVER_PATH)
{
}

int32_t EchoServer::Random(DBus::Error &error)
{
	return rand();
}

std::string EchoServer::Hello(const std::string &name, DBus::Error &error)
{
	return "Hello " + name + "!";
}

DBus::Variant EchoServer::Echo(const DBus::Variant &value, DBus::Error &error)
{
	this->Echoed(value);

	return value;
}

std::vector< uint8_t > EchoServer::Cat(const std::string &file, DBus::Error &error)
{
	FILE *handle = fopen(file.c_str(), "rb");

	if (!handle) throw DBus::Error("org.freedesktop.DBus.EchoDemo.ErrorFileNotFound", "file not found");

	uint8_t buff[1024];

	size_t nread = fread(buff, 1, sizeof(buff), handle);

	fclose(handle);

	return std::vector< uint8_t > (buff, buff + nread);
}

int32_t EchoServer::Sum(const std::vector<int32_t>& ints, DBus::Error &error)
{
	int32_t sum = 0;

	for (size_t i = 0; i < ints.size(); ++i) sum += ints[i];

	return sum;
}

std::map< std::string, std::string > EchoServer::Info(DBus::Error &error)
{
	std::map< std::string, std::string > info;
	char hostname[HOST_NAME_MAX];

	gethostname(hostname, sizeof(hostname));
	info["hostname"] = hostname;
	info["username"] = getlogin();

	return info;
}

DBus::BusDispatcher dispatcher;

void niam(int sig)
{
	dispatcher.leave();
}

int main()
{
	signal(SIGTERM, niam);
	signal(SIGINT, niam);

	DBus::default_dispatcher = &dispatcher;

	DBus::Connection conn = DBus::Connection::SessionBus();
	conn.request_name(ECHO_SERVER_NAME);

	EchoServer server(conn);

	dispatcher.enter();

	return 0;
}


text:
namespace Google.Cloud.Channel.V1.Snippets
{
    // [START cloudchannel_v1_generated_CloudChannelService_ListCustomerRepricingConfigs_sync_flattened_resourceNames]
    using Google.Api.Gax;
    using Google.Cloud.Channel.V1;
    using System;

    public sealed partial class GeneratedCloudChannelServiceClientSnippets
    {
        /// <summary>Snippet for ListCustomerRepricingConfigs</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void ListCustomerRepricingConfigsResourceNames()
        {
            // Create client
            CloudChannelServiceClient cloudChannelServiceClient = CloudChannelServiceClient.Create();
            // Initialize request argument(s)
            CustomerName parent = CustomerName.FromAccountCustomer("[ACCOUNT]", "[CUSTOMER]");
            // Make the request
            PagedEnumerable<ListCustomerRepricingConfigsResponse, CustomerRepricingConfig> response = cloudChannelServiceClient.ListCustomerRepricingConfigs(parent);

            // Iterate over all response items, lazily performing RPCs as required
            foreach (CustomerRepricingConfig item in response)
            {
                // Do something with each item
                Console.WriteLine(item);
            }

            // Or iterate over pages (of server-defined size), performing one RPC per page
            foreach (ListCustomerRepricingConfigsResponse page in response.AsRawResponses())
            {
                // Do something with each page of items
                Console.WriteLine("A page of results:");
                foreach (CustomerRepricingConfig item in page)
                {
                    // Do something with each item
                    Console.WriteLine(item);
                }
            }

            // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
            int pageSize = 10;
            Page<CustomerRepricingConfig> singlePage = response.ReadPage(pageSize);
            // Do something with the page of items
            Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
            foreach (CustomerRepricingConfig item in singlePage)
            {
                // Do something with each item
                Console.WriteLine(item);
            }
            // Store the pageToken, for when the next page is required.
            string nextPageToken = singlePage.NextPageToken;
        }
    }
    // [END cloudchannel_v1_generated_CloudChannelService_ListCustomerRepricingConfigs_sync_flattened_resourceNames]
}


text:
<?php

interface TestInterface {
    public const ABCD = 1;
}


text:
package org.apache.falcon.regression.prism;

import org.apache.falcon.regression.Entities.FeedMerlin;
import org.apache.falcon.regression.Entities.ProcessMerlin;
import org.apache.falcon.regression.core.bundle.Bundle;
import org.apache.falcon.entity.v0.EntityType;
import org.apache.falcon.entity.v0.feed.ActionType;
import org.apache.falcon.entity.v0.feed.ClusterType;
import org.apache.falcon.regression.core.helpers.ColoHelper;
import org.apache.falcon.regression.core.util.AssertUtil;
import org.apache.falcon.regression.core.util.BundleUtil;
import org.apache.falcon.regression.core.util.HadoopUtil;
import org.apache.falcon.regression.core.util.InstanceUtil;
import org.apache.falcon.regression.core.util.OSUtil;
import org.apache.falcon.regression.core.util.OozieUtil;
import org.apache.falcon.regression.core.util.TimeUtil;
import org.apache.falcon.regression.core.util.Util;
import org.apache.falcon.regression.testHelper.BaseTestClass;
import org.apache.hadoop.fs.FileSystem;
import org.apache.log4j.Logger;
import org.apache.oozie.client.CoordinatorAction.Status;
import org.apache.oozie.client.OozieClient;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;

/**
 * Update replication feed tests.
 */
@Test(groups = { "distributed", "embedded", "multiCluster" })
public class PrismFeedReplicationUpdateTest extends BaseTestClass {

    private ColoHelper cluster1 = servers.get(0);
    private ColoHelper cluster2 = servers.get(1);
    private ColoHelper cluster3 = servers.get(2);
    private OozieClient cluster1OC = serverOC.get(0);
    private OozieClient cluster2OC = serverOC.get(1);
    private OozieClient cluster3OC = serverOC.get(2);
    private FileSystem cluster1FS = serverFS.get(0);
    private FileSystem cluster2FS = serverFS.get(1);
    private FileSystem cluster3FS = serverFS.get(2);
    private String cluster1Colo = cluster1.getClusterHelper().getColoName();
    private String cluster2Colo = cluster2.getClusterHelper().getColoName();
    private String cluster3Colo = cluster3.getClusterHelper().getColoName();
    private final String baseTestDir = cleanAndGetTestDir();
    private final String inputPath = baseTestDir + "/input-data" + MINUTE_DATE_PATTERN;
    private String alternativeInputPath = baseTestDir + "/newFeedPath/input-data"
        + MINUTE_DATE_PATTERN;
    private String aggregateWorkflowDir = baseTestDir + "/aggregator";
    private static final Logger LOGGER = Logger.getLogger(PrismFeedReplicationUpdateTest.class);

    @BeforeClass(alwaysRun = true)
    public void prepareCluster() throws IOException {
        // upload workflow to hdfs
        uploadDirToClusters(aggregateWorkflowDir, OSUtil.RESOURCES_OOZIE);
    }

    @BeforeMethod(alwaysRun = true)
    public void setUp() throws Exception {
        Bundle bundle = BundleUtil.readELBundle();

        for (int i = 0; i < 3; i++) {
            bundles[i] = new Bundle(bundle, servers.get(i));
            bundles[i].generateUniqueBundle(this);
            bundles[i].setProcessWorkflow(aggregateWorkflowDir);
        }
    }

    @AfterMethod(alwaysRun = true)
    public void tearDown() {
        removeTestClassEntities();
    }

    /**
     * Set feed cluster1 as target, clusters 2 and 3 as source. Run feed. Update feed and check
     * if action succeed. Check that appropriate number of replication and retention coordinators
     * exist on matching clusters.
     *
     * @throws Exception
     */
    @Test(enabled = true, timeOut = 1200000)
    public void multipleSourceOneTarget() throws Exception {

        bundles[0].setInputFeedDataPath(inputPath);
        Bundle.submitCluster(bundles[0], bundles[1], bundles[2]);

        FeedMerlin feed = new FeedMerlin(bundles[0].getDataSets().get(0));
        feed.clearFeedClusters();

        // use the colo string here so that the test works in embedded and distributed mode.
        String postFix = "/US/" + cluster2Colo;
        String prefix = bundles[0].getFeedDataPathPrefix();
        HadoopUtil.deleteDirIfExists(prefix.substring(1), cluster2FS);
        HadoopUtil.lateDataReplenish(cluster2FS, 5, 80, prefix, postFix);

        // use the colo string here so that the test works in embedded and distributed mode.
        postFix = "/UK/" + cluster3Colo;
        prefix = bundles[0].getFeedDataPathPrefix();
        HadoopUtil.deleteDirIfExists(prefix.substring(1), cluster3FS);
        HadoopUtil.lateDataReplenish(cluster3FS, 5, 80, prefix, postFix);

        String startTime = TimeUtil.getTimeWrtSystemTime(-30);

        feed
            .addFeedCluster(new FeedMerlin.FeedClusterBuilder(
                Util.readEntityName(bundles[1].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, TimeUtil.addMinsToTime(startTime, 85))
                .withClusterType(ClusterType.SOURCE)
                .withPartition("US/${cluster.colo}")
                .build());

        feed.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[0].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(TimeUtil.addMinsToTime(startTime, 20),
                    TimeUtil.addMinsToTime(startTime, 105))
                .withClusterType(ClusterType.TARGET)
                .build());

        feed.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[2].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(TimeUtil.addMinsToTime(startTime, 40),
                    TimeUtil.addMinsToTime(startTime, 130))
                .withClusterType(ClusterType.SOURCE)
                .withPartition("UK/${cluster.colo}")
                .build());

        LOGGER.info("feed: " + Util.prettyPrintXml(feed.toString()));

        AssertUtil.assertSucceeded(prism.getFeedHelper().submitEntity(feed.toString()));
        AssertUtil.assertSucceeded(prism.getFeedHelper().schedule(feed.toString()));

        //change feed location path
        feed.setFilePath(alternativeInputPath);

        LOGGER.info("updated feed: " + Util.prettyPrintXml(feed.toString()));

        //update feed
        AssertUtil.assertSucceeded(prism.getFeedHelper().update(feed.toString(), feed.toString()));
        Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feed.getName(), "REPLICATION"), 0);
        Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster2OC, feed.getName(), "RETENTION"), 2);
        Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feed.getName(), "REPLICATION"), 0);
        Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster3OC, feed.getName(), "RETENTION"), 2);
        Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feed.getName(), "REPLICATION"), 4);
        Assert.assertEquals(OozieUtil.checkIfFeedCoordExist(cluster1OC, feed.getName(), "RETENTION"), 2);
    }

    /**
     * Set feed1 to have cluster1 as source, cluster3 as target. Set feed2 clusters vise versa.
     * Add both clusters to process and feed2 as input feed. Run process. Update feed1.
     * TODO test case is incomplete
     *
     * @throws Exception
     */
    @Test(enabled = true, timeOut = 1800000)
    public void updateFeedDependentProcessTest() throws Exception {
        //set cluster colos
        bundles[0].setCLusterColo(cluster1Colo);
        bundles[1].setCLusterColo(cluster2Colo);
        bundles[2].setCLusterColo(cluster3Colo);

        //submit 3 clusters
        Bundle.submitCluster(bundles[0], bundles[1], bundles[2]);

        //get 2 unique feeds
        FeedMerlin feed01 = new FeedMerlin(bundles[0].getInputFeedFromBundle());
        FeedMerlin feed02 = new FeedMerlin(bundles[1].getInputFeedFromBundle());
        FeedMerlin outputFeed = new FeedMerlin(bundles[0].getOutputFeedFromBundle());

        //set clusters to null;
        feed01.clearFeedClusters();
        feed02.clearFeedClusters();
        outputFeed.clearFeedClusters();

        //set new feed input data
        feed01.setFeedPathValue(baseTestDir + "/feed01" + MINUTE_DATE_PATTERN);
        feed02.setFeedPathValue(baseTestDir + "/feed02" + MINUTE_DATE_PATTERN);

        //generate data in both the colos ua1 and ua3
        String prefix = feed01.getFeedPrefix();
        HadoopUtil.deleteDirIfExists(prefix.substring(1), cluster1FS);
        HadoopUtil.lateDataReplenish(cluster1FS, 25, 1, prefix, null);

        prefix = feed02.getFeedPrefix();
        HadoopUtil.deleteDirIfExists(prefix.substring(1), cluster3FS);
        HadoopUtil.lateDataReplenish(cluster3FS, 25, 1, prefix, null);

        String startTime = TimeUtil.getTimeWrtSystemTime(-50);

        //set clusters for feed01
        feed01.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[0].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, "2099-01-01T00:00Z")
                .withClusterType(ClusterType.SOURCE)
                .build());

        feed01.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[2].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, "2099-01-01T00:00Z")
                .withClusterType(ClusterType.TARGET)
                .build());

        //set clusters for feed02
        feed02.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[0].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, "2099-01-01T00:00Z")
                .withClusterType(ClusterType.TARGET)
                .build());

        feed02.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[2].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, "2099-01-01T00:00Z")
                .withClusterType(ClusterType.SOURCE)
                .build());

        //set clusters for output feed
        outputFeed.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[0].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, "2099-01-01T00:00Z")
                .withClusterType(ClusterType.SOURCE)
                .build());

        outputFeed.addFeedCluster(
            new FeedMerlin.FeedClusterBuilder(Util.readEntityName(bundles[2].getClusters().get(0)))
                .withRetention("hours(10)", ActionType.DELETE)
                .withValidity(startTime, "2099-01-01T00:00Z")
                .withClusterType(ClusterType.TARGET)
                .build());

        //submit and schedule feeds
        prism.getFeedHelper().submitAndSchedule(feed01.toString());
        prism.getFeedHelper().submitAndSchedule(feed02.toString());
        prism.getFeedHelper().submitAndSchedule(outputFeed.toString());

        //create a process with 2 clusters

        //get a process
        ProcessMerlin process = new ProcessMerlin(bundles[0].getProcessData());

        //add clusters to process
        String processStartTime = TimeUtil.getTimeWrtSystemTime(-6);
        String processEndTime = TimeUtil.getTimeWrtSystemTime(70);

        process.clearProcessCluster();

        process.addProcessCluster(
            new ProcessMerlin.ProcessClusterBuilder(
                Util.readEntityName(bundles[0].getClusters().get(0)))
                .withValidity(processStartTime, processEndTime)
                .build());

        process.addProcessCluster(
            new ProcessMerlin.ProcessClusterBuilder(
                Util.readEntityName(bundles[2].getClusters().get(0)))
                .withValidity(processStartTime, processEndTime)
                .build()
        );
        process.addInputFeed(feed02.getName(), feed02.getName());

        //submit and schedule process
        AssertUtil.assertSucceeded(prism.getProcessHelper().submitAndSchedule(process.toString()));

        LOGGER.info("Wait till process goes into running ");

        int timeout = OSUtil.IS_WINDOWS ? 50 : 25;
        InstanceUtil.waitTillInstanceReachState(serverOC.get(0), process.getName(), 1,
            Status.RUNNING, EntityType.PROCESS, timeout);
        InstanceUtil.waitTillInstanceReachState(serverOC.get(2), process.getName(), 1,
            Status.RUNNING, EntityType.PROCESS, timeout);

        feed01.setFilePath(alternativeInputPath);
        LOGGER.info("updated feed: " + Util.prettyPrintXml(feed01.toString()));
        AssertUtil.assertSucceeded(prism.getFeedHelper().update(feed01.toString(), feed01.toString()));
    }
}


text:
<?php
namespace Concrete\Package\FotoramaBlock\Block\Fotorama;

use Concrete\Core\Block\BlockController;
use Loader;
use Less_Parser;
use Less_Tree_Rule;
use Core;
use Page;
use AssetList;
use Asset;
use FileSet;
use Database;
use File;
use Events;

defined('C5_EXECUTE') or die("Access Denied.");

class Controller extends BlockController
{
    protected $btTable = 'btFotorama';
    protected $btInterfaceWidth = "538";
    protected $btInterfaceHeight = "500";
    protected $btWrapperClass = 'ccm-ui';
    protected $btCacheBlockRecord = true;
    protected $btCacheBlockOutput = true;
    protected $btCacheBlockOutputOnPost = true;
    protected $btCacheBlockOutputForRegisteredUsers = false;
    protected $btDefaultSet = 'multimedia';
    protected $defaults = array(
        'width' => '100%',
        'height' => '',
        'fit' => 'contain',
        'transition' => 'slide',
        'nav_position' => 'bottom',
        'allow_fullscreen' => '1',
        'arrows' => '1',
        'swipe' => '1',
        'transitiondelay' => '1',
        'nav' => 'thumbs'
    );

    public function getBlockTypeName()
    {
        return t("Fotorama");
    }
    public function getBlockTypeDescription()
    {
        return t("Add Fotorama galleries to your website.");
    }

    public function getBlockTypeHelp() {
        return t('For support please go to the marketplace page.');
    }

    public function registerViewAssets($outputContent = '')
    {
        $this->requireAsset('fotorama');
        $this->requireAsset('javascript', 'jquery');
    }

    public function view()
    {
        $this->set('images', $this->getImages());
    }

    public function form()
    {
        // Assets
        $this->requireAsset('core/file-manager');
        $this->requireAsset('select2');
        $this->requireAsset('css', 'font-awesome');
        $this->requireAsset('switchery');
        $this->requireAsset('javascript', 'bootstrap/tab');

        // Source Object Lists
        $this->set('image_sources', $this->getImageSources());
        $this->set('available_file_sets', $this->getPublicFileSets());

        // Selected Source Objects
        $selected_file_set_ids = array();
        foreach ($this->getFileSets() as $r) {
            $selected_file_set_ids[] = $r['object_id'];
        }
        $this->set('selected_file_set_ids', $selected_file_set_ids);
        $this->set('selected_images', $this->getFiles());

        // Defaults
        if ($this->bID <= 0) {
            foreach ($this->defaults as $k => $v) {
                $this->set($k, $v);
            }
        }
        $this->set('defaults', $this->defaults);
    }

    public function add()
    {
        $this->form();
    }

    public function edit()
    {
        $this->form();
    }

    public function composer() {
        $this->form();
    }

    public function save($args)
    {
        $event = new \Symfony\Component\EventDispatcher\GenericEvent();
        $event->setArgument('args', $args);
        Events::dispatch('on_fotorama_save', $event);

        if ('file_sets' === $args['image_source'] && is_array($args['selected_file_set_ids'])) {
            $this->saveIds($args['selected_file_set_ids'], 'FS', $this->bID);
        } elseif ('files' === $args['image_source'] && is_array($args['img'])) {
            $this->saveIds($args['img'], 'F', $this->bID);
        }

        // Checkboxes
        $checkboxes = array(
            'allow_fullscreen',
            'lazy_loading',
            'captions',
            'hash_nav',
            'loop_images',
            'autoplay',
            'keyboard',
            'arrows',
            'click',
            'swipe',
        );

        foreach ($checkboxes as $checkbox) {
            if (empty($args[$checkbox])) {
                $args[$checkbox] = 0;
            } else {
                $args[$checkbox] = 1;
            }
        }

        $args['transitionduration'] =
            empty($args['transitionduration']) ? 1 : intval($args['transitionduration']);

        parent::save($args);
    }

    public function duplicate($newBID)
    {
        if ('file_sets' === $this->image_source) {
            $ids = array_map(function($item) { return $item['object_id']; }, $this->getFileSets());
            $this->saveIds($ids, 'FS', $newBID);
        } elseif ('files' === $this->image_source) {
            $ids = array_map(function($item) { return $item->getFileId(); }, $this->getFiles());
            $this->saveIds($ids, 'F', $newBID);
        }

        parent::duplicate($newBID);
    }

    protected function saveIds(array $ids, $type = '', $bID)
    {
        $db = Database::get();
        $db->exec('DELETE FROM btFotoramaEntries WHERE bID = ' . $bID);

        foreach ($ids as $k => $v) {
            $db->insert(
                'btFotoramaEntries',
                array(
                    'bID' => $bID,
                    'object_id' => $v,
                    'object_type' => $type,
                    'entry_order' => $k
                )
            );
        }
    }

    public function getImages()
    {
        $db = Database::get();
        $q = 'SELECT * FROM btFotoramaEntries WHERE bID = ? ORDER BY entry_order ASC';
        $r = $db->query($q, array($this->bID));

        $images = array();
        foreach ($r as $entry) {

            if ('FS' === $entry['object_type']) {
                $fs = FileSet::getById($entry['object_id']);
                $files = $fs->getFiles();
            } elseif ('F' === $entry['object_type']) {
                $files = array(File::getById($entry['object_id']));
            }

            foreach ($files as $file) {
                if (!empty($file)) {
                    $images[] = $file;
                }
            }
        }

        return $images;
    }

    public function getImageSources()
    {
        return array(
            'files' => t('Selected Files'),
            'file_sets' => t('File Set'),
        );
    }

    public function getPublicFileSets()
    {
        $fsl = new \Concrete\Core\File\Set\SetList();
        $fsl->filterByType(FileSet::TYPE_PUBLIC);
        $sets = $fsl->get();

        $sets_array = array();
        if (count($sets) > 0) {
            $sets_array = array();
            foreach ($sets as $set) {
                $sets_array[$set->getFileSetID()] = $set->getFileSetName();
            }
        }
        return $sets_array;
    }

    public function getFileSets()
    {
        $db = Database::get();
        $q = 'SELECT * FROM btFotoramaEntries WHERE bID = ? AND object_type = "FS" ORDER BY entry_order ASC';
        return $db->fetchAll($q, array($this->bID));
    }

    public function getFiles()
    {
        $db = Database::get();
        $q = 'SELECT * FROM btFotoramaEntries WHERE bID = ? AND object_type = "F" ORDER BY entry_order ASC';
        return $db->project($q, array($this->bID), function ($r) {
            return File::getById($r['object_id']);
        });
    }
}