text:
from model.group import Group
import random

def test_edit_some_group(app, db, check_ui):
    if len(db.get_group_list()) == 0:
        app.group.create(Group(name="group before editing", header="header edited group", footer="footer edited group"))
    old_groups = db.get_group_list()
    group = Group(name="group1(ed)", header="header1(ed)", footer="footer1(ed)")
    group_for_edit = random.choice(old_groups)
    index = old_groups.index(group_for_edit)
    app.group.edit_group_by_id(group_for_edit.id, group)
    new_groups = db.get_group_list()
    old_groups[index] = Group(id=group_for_edit.id, name=group.name, header=group.header, footer=group.footer)
    assert sorted(old_groups, key = Group.id_or_max) == sorted(new_groups, key = Group.id_or_max)
    if check_ui:
        db_list = map(db.clean_group, new_groups)
        assert sorted(db_list, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)

def test_edit_group_name(app, db, check_ui):
    if len(db.get_group_list()) == 0:
        app.group.create(Group(name="group before editing", header="header edited group", footer="footer edited group"))
    old_groups = db.get_group_list()
    group = Group(name="New group")
    group_for_edit = random.choice(old_groups)
    index = old_groups.index(group_for_edit)
    app.group.edit_group_by_id(group_for_edit.id, group)
    new_groups = db.get_group_list()
    old_groups[index] = Group(id=group_for_edit.id, name=group.name, header=group.header, footer=group.footer)
    assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
    if check_ui:
        db_list = map(db.clean_group, new_groups)
        assert sorted(db_list, key=Group.id_or_max) == sorted(app.group.get_group_list(), key=Group.id_or_max)

'''
def test_edit_group_header(app):
    if app.group.count() == 0:
        app.group.create(Group(name="group before editing", header="header edited group", footer="footer edited group"))
    old_groups = app.group.get_group_list()
    group = Group(header="New header")
    group.id = old_groups[0].id
    index = randrange(len(old_groups))
    app.group.edit_group_by_index(index, group)
    assert len(old_groups) == app.group.count()
    new_groups = app.group.get_group_list()
    old_groups[index] = group
    assert sorted(old_groups, key=Group.id_or_max) == sorted(new_groups, key=Group.id_or_max)
'''


text:
It's Another Dang Parser!

Parses program input from the terminal. (not stdin)

Requires C++11 compiler support.

redpajama_set_name: RedPajamaGithub


text:
package com.outr.arango.mutation

import com.outr.arango.Field
import fabric.Json

trait FieldMutation[F] extends DataMutation {
  def field: Field[F]

  override final def store(value: Json): Json = {
    val v = value.get(field.fieldName)
    store(value, v)
  }

  override final def retrieve(value: Json): Json = {
    val v = value.get(field.fieldName)
    retrieve(value, v)
  }

  def store(value: Json, fieldValue: Option[Json]): Json

  def retrieve(value: Json, fieldValue: Option[Json]): Json
}


text:
package cleancodematters.requestfactory.tutorial.server.domain;

public interface Identifiable {
  Long getId();
}


text:
#pragma once
#include <aws/ssm/SSM_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace SSM
{
namespace Model
{

  /**
   *
Reserved for future use.

See Also:
   AWS
   * API Reference

   */
  class AWS_SSM_API SessionManagerOutputUrl
  {
  public:
    SessionManagerOutputUrl();
    SessionManagerOutputUrl(Aws::Utils::Json::JsonView jsonValue);
    SessionManagerOutputUrl& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
Reserved for future use.

     */
    inline const Aws::String& GetS3OutputUrl() const{ return m_s3OutputUrl; }

    /**
     *
Reserved for future use.

     */
    inline void SetS3OutputUrl(const Aws::String& value) { m_s3OutputUrlHasBeenSet = true; m_s3OutputUrl = value; }

    /**
     *
Reserved for future use.

     */
    inline void SetS3OutputUrl(Aws::String&& value) { m_s3OutputUrlHasBeenSet = true; m_s3OutputUrl = std::move(value); }

    /**
     *
Reserved for future use.

     */
    inline void SetS3OutputUrl(const char* value) { m_s3OutputUrlHasBeenSet = true; m_s3OutputUrl.assign(value); }

    /**
     *
Reserved for future use.

     */
    inline SessionManagerOutputUrl& WithS3OutputUrl(const Aws::String& value) { SetS3OutputUrl(value); return *this;}

    /**
     *
Reserved for future use.

     */
    inline SessionManagerOutputUrl& WithS3OutputUrl(Aws::String&& value) { SetS3OutputUrl(std::move(value)); return *this;}

    /**
     *
Reserved for future use.

     */
    inline SessionManagerOutputUrl& WithS3OutputUrl(const char* value) { SetS3OutputUrl(value); return *this;}

    /**
     *
Reserved for future use.

     */
    inline const Aws::String& GetCloudWatchOutputUrl() const{ return m_cloudWatchOutputUrl; }

    /**
     *
Reserved for future use.

     */
    inline void SetCloudWatchOutputUrl(const Aws::String& value) { m_cloudWatchOutputUrlHasBeenSet = true; m_cloudWatchOutputUrl = value; }

    /**
     *
Reserved for future use.

     */
    inline void SetCloudWatchOutputUrl(Aws::String&& value) { m_cloudWatchOutputUrlHasBeenSet = true; m_cloudWatchOutputUrl = std::move(value); }

    /**
     *
Reserved for future use.

     */
    inline void SetCloudWatchOutputUrl(const char* value) { m_cloudWatchOutputUrlHasBeenSet = true; m_cloudWatchOutputUrl.assign(value); }

    /**
     *
Reserved for future use.

     */
    inline SessionManagerOutputUrl& WithCloudWatchOutputUrl(const Aws::String& value) { SetCloudWatchOutputUrl(value); return *this;}

    /**
     *
Reserved for future use.

     */
    inline SessionManagerOutputUrl& WithCloudWatchOutputUrl(Aws::String&& value) { SetCloudWatchOutputUrl(std::move(value)); return *this;}

    /**
     *
Reserved for future use.

     */
    inline SessionManagerOutputUrl& WithCloudWatchOutputUrl(const char* value) { SetCloudWatchOutputUrl(value); return *this;}

  private:

    Aws::String m_s3OutputUrl;
    bool m_s3OutputUrlHasBeenSet;

    Aws::String m_cloudWatchOutputUrl;
    bool m_cloudWatchOutputUrlHasBeenSet;
  };

} // namespace Model
} // namespace SSM
} // namespace Aws


text:
==================
Preferred Software
==================

These are the software packages that I have found to be useful.  I
list them here because I can never remember the infrequently used
ones.

Utilities
---------

Binary(hex) editor - tweak
    tweak is an efficient hex editor.  tweak possesses a fully
    functional insert mode.  By default, tweak loads the input file
    lazily instead of loading the entire input file into memory.
    Opening a large file is instantaneous, making modifications causes
    tweak's memory usage to grow with the size of the changes rather
    than the size of the whole file, and only when saving the altered
    version will tweak have to read through the entire input file to
    write the output.

Development Tools
-----------------

UML Modelling - BOUML
    BOUML is an UML 2 tool box.  It creates reasonable sequence
    diagrams.  BOUML went closed source in version 5.0, but versions
    prior to that are free.


text:
<?xml version="1.0"?>

<payment>
    <credit_cards>
        <type id="ABC" order="0">
            ABC Credit Card Company
        </type>
        <type id="XYZ" order="10">
            ABC Credit Card Company
        </type>
    </credit_cards>
    <groups>
        <group id="other">
            Other Payment Methods
        </group>
    </groups>
</payment>


text:
package O2Plugin::Shop::Obj::Cart;

use strict;

use base 'O2::Obj::Object';

use O2 qw($context);

#--------------------------------------------------------------------
sub addItem {
  # This function will add one product to the cart
  # This function is different as it is takes a product ID
  # and not an item ID. It will create an item object and make
  # the nessesary connections.
  # Will fail if the variant is not connected to the product and so on...
  my ($obj, $productId, $amount, $variantOptionIds) = @_;

  my $product = $context->getObjectById($productId);
  die "Not a product" unless $product->isa( 'O2Plugin::Shop::Obj::Product' );

  foreach my $variantId ( keys %{$variantOptionIds} ) {
    my $variant = $context->getObjectById($variantId);
    die "Not a variant" unless $variant->isa('O2Plugin::Shop::Obj::Product::Variant');

    my $option = $context->getObjectById( $variantOptionIds->{$variantId} );
    die "Not an option" unless $option->isa('O2Plugin::Shop::Obj::Product::Variant::Option');
  }

  my $item = $context->getSingleton('O2Plugin::Shop::Mgr::Cart::ItemManager')->newObject();
  $item->setMetaName(         'cartItem'           );
  $item->setProductId(        $product->getId()    );
  $item->setAmount(           $amount              );
  $item->setVariantOptionIds( %{$variantOptionIds} );
  $item->save();

  $obj->setItemIds( $obj->getItemIds(), $item->getId() );
  $obj->save();

  return 1;
}
#--------------------------------------------------------------------
sub removeItem {
  # This function will remove an item from the cart.
  # It will also delete the item object - also, it will return false if the
  # item is not associated with this cart.
  my ($obj, $unwantedItemId) = @_;

  my @itemIds = $obj->getItemIds();

  my $found = grep /$unwantedItemId/, @itemIds;
  return 0 unless $found;

  my $item = $context->getObjectById($unwantedItemId);
  $item->deletePermanently();

  my @updatedItemIds;
  foreach my $itemId (@itemIds) {
    push @updatedItemIds, $itemId if $itemId ne $unwantedItemId;
  }

  $obj->setItemIds(@updatedItemIds);
  $obj->save();

  return 1;
}
#--------------------------------------------------------------------
sub updateAmount {
  # This function will update the sum of a selected product
  # If the value of a product is set to zero, the product is removed.
  # Will return false (0) if item is not assigned to this cart.
  my ($obj, $itemId, $amount) = @_;

  my @itemIds = $obj->getItemIds();

  my $found = grep /$itemId/, @itemIds;
  return 0 unless $found;

  my $item = $context->getObjectById($itemId);
  $item->setAmount($amount);
  $item->save();
  return 1;
}
#--------------------------------------------------------------------
sub countProducts {
  # This function will count the number of products in the cart
  # and then return a sum of all products.
  # Extracts all items and for each item it reads the amount variable
  my ($obj) = @_;

  my @itemIds = $obj->getItemIds();

  my $totalProducts = 0;
  foreach my $itemId (@itemIds) {
    my $item = $context->getObjectById($itemId);
    $totalProducts += $item->getAmount();
  }

  return $totalProducts;
}
#--------------------------------------------------------------------
sub getTotalIncVat {
  # This will query all products in the basket and collect the total inc vat
  my ($obj) = @_;

  my @itemIds = $obj->getItemIds();

  my $totalIncVat = 0;
  foreach my $itemId (@itemIds) {
    my $item      = $context->getObjectById($itemId);
    my $amount    = $item->getAmount();
    my $productId = $item->getProductId();
    my $product   = $context->getObjectById($productId);
    $totalIncVat += $amount * $product->getPriceIncVat();
  }
  return $totalIncVat;
}
#--------------------------------------------------------------------
sub getTotalExVat {
  # This will query all products in the basket and collect the total ex vat
  my ($obj) = @_;

  my @itemIds = $obj->getItemIds();

  my $totalExVat = 0;
  foreach my $itemId (@itemIds) {
    my $item      = $context->getObjectById($itemId);
    my $amount    = $item->getAmount();
    my $productId = $item->getProductId();
    my $product   = $context->getObjectById($productId);
    $totalExVat += $amount * $product->getPriceExVat();
  }
  return $totalExVat;
}
#--------------------------------------------------------------------
sub clear {
  # Empties the cart
  # Deletes all connected item objects and clears the itemIds array
  my ($obj) = @_;

  my @itemIds = $obj->getItemIds();
  foreach my $itemId (@itemIds) {
    my $item = $context->getObjectById($itemId);
    $item->deletePermanently();
  }
  $obj->setItemIds();
  $obj->save();
}
#--------------------------------------------------------------------
sub getItems {
  # Returns an array of item objects
  my ($obj) = @_;

  my @itemIds = $obj->getItemIds();

  my @items;
  foreach my $itemId (@itemIds) {
    my $item = $context->getObjectById($itemId);
    push @items, $item;
  }

  return \@items;
}
#--------------------------------------------------------------------
sub isCachable {
  return 0;
}
#--------------------------------------------------------------------
sub containsProduct {
  my ($obj, $product) = @_;
  my @items = @{ $obj->getItems() };
  foreach my $item (@items) {
    return 1 if $item->getProductId() == $product->getId();
  }
  return 0;
}
#--------------------------------------------------------------------
sub delete {
  my ($obj) = @_;
  foreach my $item (@{ $obj->getItems() }) {
    $item->delete();
  }
}
#--------------------------------------------------------------------
sub deletePermanently {
  my ($obj) = @_;
  foreach my $item (@{ $obj->getItems() }) {
    $item->deletePermanently();
  }
}
#--------------------------------------------------------------------
1;


text:
package gedi.region.bam;

import java.util.Arrays;
import java.util.function.BiFunction;

import gedi.core.data.reads.DefaultAlignedReadsData;
import gedi.core.region.ArrayGenomicRegion;
import gedi.core.region.GenomicRegion;
import gedi.core.region.MissingInformationIntronInformation;
import gedi.util.datastructure.collections.intcollections.IntArrayList;
import gedi.util.sequence.DnaSequence;
import htsjdk.samtools.SAMRecord;

public class FactoryGenomicRegion extends ArrayGenomicRegion implements MissingInformationIntronInformation {

	private BamAlignedReadDataFactory factory;
	private boolean consistent;
	private int pairedEndIntron = -1;
	private int missingEnd = 0;

	/**
	 * Missingend is 0 if nothing is missing, -1 if left part is missing and 1 if right part is missing
	 * @param coords
	 * @param cumNumCond
	 * @param consistent
	 * @param ignoreVariation
	 * @param needReadNames
	 * @param pairedEndIntron
	 * @param missingEnd
	 */
	public FactoryGenomicRegion(int[] coords, int[] cumNumCond, boolean consistent, boolean ignoreVariation, boolean needReadNames, int pairedEndIntron, int missingEnd, boolean join, BiFunction<SAMRecord, SAMRecord, DnaSequence> barcode) {
		super(coords);
		this.pairedEndIntron = pairedEndIntron;
		if (pairedEndIntron+1>=getNumParts())
			throw new RuntimeException();
		factory = new BamAlignedReadDataFactory(this,cumNumCond,ignoreVariation,needReadNames,join, barcode);
		factory.start();
		this.consistent = consistent;
		this.missingEnd = missingEnd;
	}

	public FactoryGenomicRegion(IntArrayList coords, int[] cumNumCond, boolean ignoreVariation, boolean needReadNames, boolean join, BiFunction<SAMRecord, SAMRecord, DnaSequence> barcode) {
		super(coords);
		factory = new BamAlignedReadDataFactory(this,cumNumCond,ignoreVariation,needReadNames, join, barcode);
		factory.start();
	}

	public boolean isOverlapping() {
		return factory.isOverlapping();
	}

	public void setUseBlocks(int minIntronLength) {
		factory.setUseBlocks(minIntronLength);
	}

	public FactoryGenomicRegion add(SAMRecord b, int file) {
		factory.addRecord(b, file);
		return this;
	}

	public FactoryGenomicRegion add(SAMRecord a, SAMRecord b,int file) {
		factory.addRecord(a,b, file);
		return this;
	}

	public BamAlignedReadDataFactory getFactory() {
		return factory;
	}

	public DefaultAlignedReadsData create() {
		if (factory.barcodeFun!=null)
			return factory.createBarcode();
		return factory.create();
	}

	public IntArrayList getReadIds(int distinct) {
		return factory.getReadIds(distinct);
	}

	public boolean isConsistent() {
		return consistent;
	}

	@Override
	public GenomicRegion[] getInformationGenomicRegions() {
		if (pairedEndIntron==-1) return new GenomicRegion[] {this};
		GenomicRegion[] re = new GenomicRegion[] {
				new ArrayGenomicRegion(Arrays.copyOfRange(getBoundaries(), 0, pairedEndIntron*2+2)),
				new ArrayGenomicRegion(Arrays.copyOfRange(getBoundaries(), pairedEndIntron*2+2, getNumBoundaries()))};

//		System.out.println(super.toRegionString()+" = "+re[0].toRegionString()+" + "+re[1].toRegionString());
		return re;
	}

	@Override
	public boolean isMissingInformationIntron(int intronIndex) {
		return intronIndex==pairedEndIntron;
	}

	@Override
	public boolean isLeftPartMissing() {
		return missingEnd==-1;
	}
	@Override
	public boolean isRightPartMissing() {
		return missingEnd==1;
	}

	@Override
	public String toRegionString() {
		if (pairedEndIntron==-1) return super.toRegionString();
		GenomicRegion[] two = getInformationGenomicRegions();
		return two[0].toRegionString()+"#"+two[1].toRegionString();
	}

	@Override
	public String toString() {
		return toRegionString();
	}

	@Override
	public int hashCode() {
		int re = super.hashCode();
		re = 31 * re + pairedEndIntron;
		return re;
	}

	@Override
	public boolean equals(Object obj) {
		if (!super.equals(obj)) return false;
		if (! (obj instanceof FactoryGenomicRegion))
			return false;
		FactoryGenomicRegion r = (FactoryGenomicRegion) obj;
		return r.pairedEndIntron==pairedEndIntron;
	}

}


text:
package com.github.ruediste.rise.migration;

import javax.inject.Inject;

@MigrationTaskNoAutoDiscover
public class MigrationTaskSQLFile extends MigrationTask {
    @Inject
    ClassLoader cl;

    public String sql;

    /**
     * Initialize this task
     *
     * @param sqlResourceName
     *            name in the format
     *            {@code <path>/<timestamp>.<author>.<description>.sql}
     */
    public MigrationTaskSQLFile initialize(String sqlResourceName, Class<? extends MigrationTarget<?>> target) {
        initializeFromResourceName(target, sqlResourceName);
        sql = loadResource(sqlResourceName);
        return this;
    }

}


text:
(function (window) {
    'use strict';

    function BotPhysicManager(pathManager, gameState) {

        this.pathManager = pathManager;
        this.gameState = gameState;
        this.moveLoop = {};
    }

    BotPhysicManager.prototype.clearAllMoves = function () {

        for (var botId in this.moveLoop) {
            if (this.moveLoop.hasOwnProperty(botId)) {
                clearTimeout(this.moveLoop[botId]);
            }
        }
        this.moveLoop = {};
    };

    BotPhysicManager.prototype.clearMove = function (bot) {
        clearTimeout(this.moveLoop[bot.type + bot.id]);
        delete this.moveLoop[bot.type + bot.id];
    };

    BotPhysicManager.prototype.moveOnpath = function (bot, command) {

        return this.pathManager.buildPath(bot, command)
            .then(function (path) {

                if (this.gameState.isPlaying()) {
                    return this.buildMove(bot, path);
                }
                return Promise.resolve(bot);

            }.bind(this));
    };

    BotPhysicManager.prototype.buildMove = function (bot, path) {

        var sequence = Promise.resolve();

        path.forEach(function (coords) {
            sequence = sequence.then(function () {

                return new Promise(function (resolve) {

                    if (this.gameState.isPlaying()) {
                        this.moveLoop[bot.type + bot.id] = setTimeout(function () {
                            bot.x = coords.x;
                            bot.y = coords.y;
                            resolve(bot);
                        }, bot.speed);
                    } else {
                        resolve(bot);
                    }

                }.bind(this));

            }.bind(this));
        }.bind(this));

        return sequence;
    };
    BotPhysicManager.prototype.buildMoveTemp = function (bot, path) {

        var sequence = Promise.resolve();

        path.forEach(function (coords) {
            sequence = sequence.then(function () {

                return this.buildOneStep(bot, coords);

            }.bind(this));
        }.bind(this));

        return sequence;
    };

    BotPhysicManager.prototype.buildOneStep = function (bot, coords) {

        return new Promise(function (resolve) {

            if (this.gameState.isPlaying()) {
                this.moveLoop[bot.type + bot.id] = setTimeout(function () {
                    bot.x = coords.x;
                    bot.y = coords.y;
                    resolve(bot);
                }, bot.speed);
            } else {
                resolve(bot);
            }

        }.bind(this));
    };

    window.BotPhysicManager = BotPhysicManager;

})(window);


text:
//====================================================================
using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;
//====================================================================
public class LocalizationTest : MonoBehaviour
{
    public void OnLoad1()    { SceneManager.LoadScene("T_Localization_1"); }
    public void OnLoad2()    { SceneManager.LoadScene("T_Localization_2"); }

}// public class LocalizationTest : MonoBehaviour
//====================================================================


text:
package com.example.sinav1.fragment;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.ActionBar.TabListener;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.app.SherlockFragment;
import com.example.sinav1.MainActivity;
import com.example.sinav1.R;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class IndexFragment extends SherlockFragment implements OnPageChangeListener,TabListener{

	public static final int WRITE_WEIBO = 6 ;
	public static final int ME = 7 ;
	ActionBar actionBar ;
	ViewPager viewPager;
	private Fragment[] fragmentGroup = new Fragment[] {MyPageFragment.getInstance(), new PublicPageFragment() };

	public IndexFragment(ActionBar actionBar) {
		this.actionBar=actionBar;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.index_fragment, null);
		return view;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// ÉèÖõ¼º½±êÇ©
		actionBar.addTab(actionBar.newTab().setText("ÎÒµÄÊ×Ò³").setTabListener(this));
		actionBar.addTab(actionBar.newTab().setText("¹«¹²Ê×Ò³").setTabListener(this));
		// »ñµÃViewPager¶ÔÏó
		viewPager = (ViewPager) view.findViewById(R.id.view_pager);
		// ÉèÖÃÊÊÅäÆ÷
		viewPager.setAdapter(new MyViewPagerAdapter(getActivity().getSupportFragmentManager()));
		// ViewPager¶ÔÏó×¢²á¼àÌý
		viewPager.setOnPageChangeListener(this);

		setHasOptionsMenu(true);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.write_weibo:
			((MainActivity)getActivity()).changeFragment(WRITE_WEIBO);
			break;

		case R.id.me:
			break;

		case android.R.id.home:
			((MainActivity)getActivity()).getSlidingMenu().showMenu();
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		getSherlockActivity().getSupportMenuInflater().inflate(R.menu.main, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}

	@Override
	public void onHiddenChanged(boolean hidden) {
		if(!hidden){
			// ÉèÖñêÌâ
			actionBar.setTitle("Ê×Ò³");
			// ÉèÖÃactionBarģʽ
			actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		}
		super.onHiddenChanged(hidden);
	}

	// ÊÊÅäÆ÷
	class MyViewPagerAdapter extends FragmentPagerAdapter {

		public MyViewPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public Fragment getItem(int pos) {

			return fragmentGroup[pos];
		}

		@Override
		public int getCount() {
			return fragmentGroup.length;
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int pos) {
		actionBar.getTabAt(pos).select();
	}

	@Override
	public void onTabSelected(Tab tab, FragmentTransaction ft) {
		if(viewPager!=null){
			viewPager.setCurrentItem(tab.getPosition());
		}
	}

	@Override
	public void onTabUnselected(Tab tab, FragmentTransaction ft) {
	}

	@Override
	public void onTabReselected(Tab tab, FragmentTransaction ft) {
	}

}


text:
git-hooks-code-autoformat
=========================

A collection of git `pre-commit` hooks to help with code auto-formatting.

Licensed under [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html).

Please, share your own formatters back. PRs are welcome!

How to use
----------
You could just copy contents of this repo to `$PROJECT/.git/hooks/`. However, a slightly better way might be:

1. `$ cd $PROJECT`
1. `$ git remote add git-hooks-code-autoformat https://github.com/michalrus/git-hooks-code-autoformat.git`
1. `$ git subtree add --prefix=git-hooks/ git-hooks-code-autoformat master`

Now, you have `$PROJECT/git-hooks/` directory with contents of this repo. This subtree is updateable with `$ git subtree pull --prefix=git-hooks/ git-hooks-code-autoformat master`. Any person can just clone your project and they'll have `$PROJECT/git-hooks` in place at the very moment.

What's left is to symlink `$PROJECT/.git/hooks` to `$PROJECT/git-hooks`:

1. `$ cd .git && mv hooks hooks.old && ln -s ../git-hooks hooks`

**IMPORTANT**: this linking step **has to** be done **manually** by **every developer**.

**IMPORTANT**: for **Windows** users, due to limitations on Windows shell emulators, links seem to be implemented more often than not as 'copy', so any time the git-hooks directory is updated, the linking step needs to be re-done.

The usual workflow then is:

1. Modify some files.
1. `$ git add` them.
1. `$ git commit` them.

Now, for each staged ("git-added") file, an autoformatter will be called, and then the file will be re-added, and only then the `git commit` will continue. This might create a problem, see [Known problems](#known-problems) below.

If an error occurs (e.g. trying to format a not so well-formed XML), an error message is printed and the commit is aborted.

[Existing formatters](/autoformat)
-------------------

* [Java](/autoformat/java) ← will format [`*.java`](/autoformat/java.patterns) files using a small wrapper—[eclipse-code-formatter](/tools/eclipse-java-formatter)—around [Eclipse's `CodeFormatter`](http://help.eclipse.org/luna/topic/org.eclipse.jdt.doc.isv/reference/api/org/eclipse/jdt/core/formatter/CodeFormatter.html) with [Google's Java Style definition](https://github.com/google/styleguide/blob/gh-pages/eclipse-java-google-style.xml),
* [XML](/autoformat/xml) ← will format [`*.xml`, `*.bmml` and `*.owl`](/autoformat/xml.patterns) (Balsamiq Mockups, Protégé) files and any [file that is recognized as XML](/autoformat/xml.magic) by [libmagic](http://en.wikipedia.org/wiki/File_%28command%29),
* [XMind](/autoformat/xmind) ← will format [`*.xmind/**.xml`](/autoformat/xmind.patterns) files (an `*.xmind` file is really a ZIP archive and **should be extracted**—and autoformatted—before being added to VCS; you can then open a mindmap using `$ XMind some/directory.xmind` and it will then be added to the recently opened maps list),
* [Flat OpenDocument Spreadsheet](/autoformat/flat-ods) ← will format [`*.fods`](/autoformat/flat-ods.patterns) files, a format used by LibreOffice Calc for storing spreadsheets.

Adding your own formatters
--------------------------

1. Take a look at the existing formatters above.
2. Create `autoformat/NAME.patterns` file containing a regular expressions—1 per line—matching all file names to be treated with your `NAME` formatter.
2. AND/OR create `autoformat/NAME.magic` file containing a regular expressions—1 per line—matching outputs of [libmagic](http://en.wikipedia.org/wiki/File_%28command%29)'s `/usr/bin/file "$FILE"` for all files to be treated with your `NAME` formatter.
3. Create `autoformat/NAME` executable script. It might be called several times, but always with one argument, an absolute path to a file to format. When formatting, you've got to **modify this file in place**.
4. If you want to abort the commit, print an error message and exit from the formatter with a non-zero exit code.

Known problems
--------------

1. The [`pre-commit`](/pre-commit) hook autoformats every staged ("git-added") file (if an applicable formatter exists) and then **re-adds the file to the stage**. Now, if you modify some file, `$ git add` it, then modify it again and then `$ git commit`—and there exists a formatter for this type of a file—second modification will also be commited.


text:
package tlc2.model;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import tlc2.model.Assignment;

public class AssignmentTest {

	@Test
	public void test() {
		final Assignment a = new Assignment("X", new String[0], "X");
		a.setModelValue(true);
		assertEquals("X", a.prettyPrint());

		final Assignment b = new Assignment("Y", new String[0], "{a1, b1}");
		b.setModelValue(true);
		assertEquals("Y" + Assignment.ASSIGNMENT_SIGN + "{a1, b1}", b.prettyPrint());

		final Assignment c = new Assignment("Z", new String[0], "{s1, s2}");
		c.setModelValue(true);
		c.setSymmetric(true);
		assertEquals("Z" + Assignment.ASSIGNMENT_SIGN + "s{s1, s2}", c.prettyPrint());

		final Assignment d = new Assignment("W", new String[0], "1");
		assertEquals("W" + Assignment.ASSIGNMENT_SIGN + "1", d.prettyPrint());
	}
}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <predicate lemma="unclasp">

        <roleset framnet="" id="unclasp.01" name="unclasp" vncls="23.3">
            <roles>
                <role descr="unclasper, agent" f="" n="0">
                    <vnrole vncls="23.3" vntheta="agent"/>
                </role>
                <role descr="thing unclasped, patient" f="" n="1">
                    <vnrole vncls="23.3" vntheta="patient1"/>
                </role>
                <role descr="unclasped from, source" f="" n="2">
                    <vnrole vncls="23.3" vntheta="patient2"/>
                </role>
                <note/>
            </roles>
            <example name="from Google" src="web usage" type="">
                <text>Rolling her eyes, she unclasped the necklace from around her neck and dropped it into his hand.</text>
                <note/>
                <arg f="adv" n="m">Rolling her eyes</arg>
                <arg f="" n="0">she</arg>
                <rel f="">unclasped</rel>
                <arg f="" n="1">the necklace</arg>
                <arg f="" n="2">from around her neck</arg>
            </example>
            <note>hand-checked by Kev</note>
        </roleset>
        <note>Automatically created based on framefiles: detach (23.3)</note>
    </predicate>
    <note/>
</frameset>


text:
Package.describe({
  name: 'acemtp:algolia',
  summary: 'Package to handle the blazing fast Algolia search egnine (client and server)',
  version: '1.7.0',
  git: 'https://github.com/acemtp/meteor-algolia.git'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.addFiles('server.js', 'server');
  api.addFiles('algoliasearch.js', 'client');
  api.export('Algolia', 'server');
  api.export('AlgoliaSearch', 'client');
});

Npm.depends({
  'algolia-search': '1.6.2'
});


text:
import {
  isFn
} from 'uni-shared'

const mpBehaviors = {
  'wx://form-field': {},
  'wx://component-export': {}
}

function callDefinitionFilter (mpComponentOptions) {
  const {
    behaviors,
    definitionFilter
  } = mpComponentOptions

  const behaviorDefinitionFilters = []

  if (Array.isArray(behaviors)) {
    behaviors.forEach(behavior => {
      behavior = typeof behavior === 'string' ? mpBehaviors[behavior] : behavior
      if (behavior.definitionFilter) {
        behaviorDefinitionFilters.push(behavior.definitionFilter)
        behavior.definitionFilter.call(null, mpComponentOptions, [])
      }
    })
  }

  if (isFn(definitionFilter)) {
    return function (defFields) {
      definitionFilter(defFields, behaviorDefinitionFilters)
    }
  }
}

export function parseDefinitionFilter (mpComponentOptions, vueComponentOptions) {
  callDefinitionFilter(mpComponentOptions)
}


text: java -jar jsdoc-toolkit/jsrun.jar jsdoc-toolkit/app/run.js -c=jsdoc.conf


text:
var expect = require('chai').expect;

var validate = require('../');

describe('validateS3Key', function() {
  it('should exist', function() {
    expect(validate).to.exist;
  });

  it('should return a promise', function() {
    expect(validate().then).to.exist
  });

  it('should resolve the result object if no requirements are inputted', function(done) {
    var result = {
      key: 'val'
    }
    validate(result).then(function(res) {
      if (res) {
        expect(res).to.equal(res).and.exist;
        done()
      } else {
        done(new Error("Expected result object to be resolved."))
      }
    }, function() {
      done(new Error("Expected result object to be resolved."))
    })
  });

  it('should reject with an err if no result are inputted but requirements are set', function(done) {
    var requirements = {
      srcKey: true
    }
    validate(null, requirements).then(function() {
      done(new Error("Expected scenario to fail."))
    }, function(err) {
      expect(err).to.exist
      done()
    })
  });

  it('should resolve if required keys exist', function(done) {
    var requirements = {
      srcKey: true
    }
    var result = {
      srcKey: "file.pdf"
    }
    validate(result, requirements).then(function(res) {
      if (res && res.srcKey) {
        done()
      } else {
        done(new Error("Expected result object to be resolved"))
      }
    }, function(err) {
      done(new Error("Expected validation to resolve"))
    })
  });

  it('should resolve if endsWith requirements are met', function(done) {
    var requirements = {
      srcKey: {
        endsWith: ".pdf"
      }
    }
    var result = {
      srcKey: "file.pdf"
    }
    validate(result, requirements).then(function(res) {
      if (res && res.srcKey) {
        done()
      } else {
        done(new Error("Expected result object to be resolved"))
      }
    }, function(err) {
      done(new Error("Expected validation to resolve"))
    })
  });

  it('should reject if endsWith requirements are not met', function(done) {
    var requirements = {
      srcKey: {
        endsWith: ".gif"
      }
    }
    var result = {
      srcKey: "file.pdf"
    }
    validate(result, requirements).then(function(res) {
      done(new Error("Expected non .gif files to be rejected"))
    }, function() {
      done()
    })
  });

  it('should resolve if endsWithout requirements are met', function(done) {
    var requirements = {
      srcKey: {
        endsWithout: "_180.gif"
      }
    }
    var result = {
      srcKey: "file.gif"
    }
    validate(result, requirements).then(function(res) {
      if (res && res.srcKey) {
        done()
      } else {
        done(new Error("Expected result object to be resolved"))
      }
    }, function(err) {
      done(new Error("Expected validation to resolve"))
    })
  });

  it('should reject if endsWithout requirements are not met', function(done) {
    var requirements = {
      srcKey: {
        endsWithout: "_\\d+\\.gif"
      }
    }
    var result = {
      srcKey: "file_300.gif"
    }
    validate(result, requirements).then(function(res) {
      done(new Error("Expected *_d+.gif files to be rejected"))
    }, function() {
      done()
    })
  });

  it('should resolve if startsWith requirements are met', function(done) {
    var requirements = {
      srcKey: {
        startsWith: "events/"
      }
    }
    var result = {
      srcKey: "events/party/file.gif"
    }
    validate(result, requirements).then(function(res) {
      if (res && res.srcKey) {
        done()
      } else {
        done(new Error("Expected result object to be resolved"))
      }
    }, function(err) {
      done(new Error("Expected validation to resolve"))
    })
  });

  it('should reject if startsWith requirements are not met', function(done) {
    var requirements = {
      srcKey: {
        startsWith: "events/"
      }
    }
    var result = {
      srcKey: "file.gif"
    }
    validate(result, requirements).then(function(res) {
      done(new Error("Expected non startsWith-matching files to be rejected"))
    }, function() {
      done()
    })
  });

  describe('e2e -ish', function() {

    it('should reject if only endsWithout requirements are met', function(done) {
      var requirements = {
        srcKey: {
          endsWith: ".gif",
          endsWithout: "_\\d+\\.gif",
          startsWith: "events/"
        }
      }
      var result = {
        srcKey: "events/party/file_300.gif"
      }
      validate(result, requirements).then(function(res) {
        done(new Error("Expected *_d+.gif files to be rejected"))
      }, function() {
        done()
      })
    });

    it('should reject if only startsWith requirements are met', function(done) {
      var requirements = {
        srcKey: {
          endsWith: "\\.gif",
          endsWithout: "_\\d+\\.gif",
          startsWith: "events/"
        }
      }
      var result = {
        srcKey: "file.gif"
      }
      validate(result, requirements).then(function(res) {
        done(new Error("Expected non startsWith matching files to be rejected"))
      }, function() {
        done()
      })
    });

    it('should resolve if requirements are met', function(done) {
      var requirements = {
        srcKey: {
          endsWith: "\\.gif",
          endsWithout: "_\\d+\\.gif",
          startsWith: "events/"
        }
      }
      var result = {
        srcKey: "events/partytime/file.gif"
      }
      validate(result, requirements).then(function(res) {
        if (res) {
          expect(res).to.equal(result)
          done()
        } else {
          done(new Error("Expected resolved result to match inputted result"))
        }
      }, function() {
        done(new Error("Expected Validation to pass"))
      })
    });

  })
});


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:happor="http://happor.lechange.cn/schema/tags"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
		http://happor.lechange.cn/schema/tags http://happor.lechange.cn/schema/tags/springtags.xsd">

	<happor:server port="9080" timeout="30" maxHttpSize="1000000" executeThreads="32">
	    <happor:config type="log4j" file="conf/log4j.properties" />
	    <happor:config type="container" file="conf/container.properties" />
	</happor:server>

</beans>


text:
/*global define,angular*/

(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], function() {
      return factory(root);
    });
  } else if (typeof exports === 'object') {
      // Node. Does not work with strict CommonJS, but
      // only CommonJS-like environments that support module.exports,
      // like Node.

      module.exports = factory(root);
  } else if (typeof angular === 'object') {
    // Define an Angular JS module
    angular.module('hbpCollaboratoryAppToolkit', [])
    .factory('hbpCollaboratoryAppToolkit', ['$window', function($window) {
      return factory($window);
    }]);
  } else {
    // Browser globals (root is window)
    root.hbpCollaboratoryAppToolkit = factory(root);
  }
}(this, function factory(window) {
  'use strict';
  var eventId = 0;
  var sentMessages = {};

  /**
   * @module hbpCollaboratoryAppToolkit
   */
  function AppToolkit() { }
  AppToolkit.prototype = {
    emit: emit,
    context: context
  };

  window.addEventListener('message', function(event) {
    if(!event.data.origin) {
      return;
    }
    if(!sentMessages[event.data.origin]) {
      return;
    }
    if (event.data.eventName === 'resolved') {
      sentMessages[event.data.origin](null, event.data.data);
    } else if (event.data.eventName === 'error'){
      sentMessages[event.data.origin](event.data.data);
    }
    sentMessages[event.data.origin] = null;
  });

  function emit(name, data, callback) {
    window.parent.postMessage({
      apiVersion: 1,
      eventName: name,
      data: data,
      ticket: ++eventId
    }, '*');
    sentMessages[eventId] = callback;
  }

  var currentContext;

  /**
   * @typedef HbpCollaboratoryContext
   * @type {object}
   * @property {string} mode - the current mode, either 'run' or 'edit'
   * @property {string} ctx - the UUID of the current context
   * @property {string} state - an application defined state string
   */

  /**
   * @callback hbpCollaboratoryContextCallback
   * @param {HbpError} error - an HbpError
   * @param {HbpCollaboratoryContext} context - the context informations
   */

   /**
    * @desc
    * Asynchronously retrieve the current HBP Collaboratory Context, including
    * the mode, the ctx UUID and the application state if any.
    * @function context
    * @param  [{hbpCollaboratoryContextCallback} callback] - receiver of the call
    * @static
    */
  function context(data, callback) {
    if (typeof arguments[0] === 'function') {
      callback = data;
      data = null;
    }
    var kill = setTimeout(function() {
      callback({
        type: 'TimeoutException',
        message: 'No context can be retrieved'
      }, null);
    }, 250);

    if (data) {
      // discard context if new data should be set.
      currentContext = null;
    }

    if (currentContext) {
      // directly return context when cached.
      callback(null, currentContext);
    } else {
      emit('workspace.context', data, function(err, context) {
        clearTimeout(kill)
        if (err) {
          if (callback) {
            callback(err);
          }
        } else {
          currentContext = context;
          if (callback) {
            callback(null, currentContext);
          }
        }
      });
    }
  }

  // Return a value to define the module export.
  // This example returns a functions, but the module
  // can return an object as the exported value.
  return new AppToolkit();
}));


text:
package net.paslavsky.gwt.soundmanager.client.impl;

import com.google.gwt.core.client.*;
import net.paslavsky.gwt.appload.client.AsyncModule;
import net.paslavsky.gwt.appload.client.GwtApplicationLoader;
import net.paslavsky.gwt.appload.client.PriorityOrdered;
import net.paslavsky.gwt.soundmanager.client.SM2Configuration;
import net.paslavsky.gwt.soundmanager.client.SM2Settings;
import net.paslavsky.gwt.soundmanager.client.SoundManager;
import net.paslavsky.gwt.soundmanager.client.event.SM2OnTimeoutEvent;
import net.paslavsky.gwt.soundmanager.client.event.SM2OnTimeoutHandler;
import net.paslavsky.gwt.soundmanager.client.event.SM2ReadyEvent;
import net.paslavsky.gwt.soundmanager.client.event.SM2ReadyHandler;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * SoundManager2 GWT module
 *
 * @author Andrey Paslavsky
 * @version 1.0
 */
public class SM2EntryPoint implements EntryPoint {
    private final static Logger logger = Logger.getLogger("SoundManager2");

    public void onModuleLoad() {
        if (SM2LoadProfile.INSTANCE.useAppLoader()) {
            GwtApplicationLoader loader = GWT.create(GwtApplicationLoader.class);
            loader.add(new SM2JavaScriptLoader());
            loader.add(new SetupSoundManager());
        } else {
            loadSoundManager(new SM2OnScriptLoaded());
        }
    }

    private void loadSoundManager(Callback<Void, Exception> callback) {
        logger.log(Level.CONFIG, "Loading SoundManager2 library...");
        String url = null;
        switch (SM2ProfileProvider.INSTANCE.getProfile()) {
            case Clean:
                url = SM2Scripts.INSTANCE.clean().getSafeUri().asString();
                break;
            case Debug:
                url = SM2Scripts.INSTANCE.debug().getSafeUri().asString();
                break;
            case Developer:
                url = SM2Scripts.INSTANCE.developer().getSafeUri().asString();
                break;
            case Optimized:
                url = SM2Scripts.INSTANCE.optimized().getSafeUri().asString();
                break;
        }
        assert url != null;
        logger.log(Level.CONFIG, "SoundManager2 script is " + url);
        ScriptInjector.fromUrl(url).setWindow(getWindow()).setCallback(callback).inject();
    }

    private native JavaScriptObject getWindow() /*-{
        return $wnd;
    }-*/;

    private void setupSoundManager() {
        logger.config("SoundManager2 library successfully loaded!");
        SM2Configuration configuration = GWT.create(SM2Configuration.class);
        SM2Settings settings = SM2Settings.newInstance();
        configuration.setup(settings);
        doSetupSoundManager(settings);
    }

    private native void doSetupSoundManager(SM2Settings settings) /*-{
        var thisRef = this;
        settings.onready = function() {
            thisRef.@net.paslavsky.gwt.soundmanager.client.impl.SM2EntryPoint::fireReady()();
        };
        settings.ontimeout = function() {
            thisRef.@net.paslavsky.gwt.soundmanager.client.impl.SM2EntryPoint::fireOnTimeout()();
        };
        $wnd.soundManager.setup(settings);
    }-*/;

    private void fireReady() {
        logger.config("SoundManager2 ready to work :)");
        try {
            SoundManager.getEventBus().fireEvent(new SM2ReadyEvent());
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Handled some errors from #onSoundManagerReady()!", e);
        }
    }

    private void fireOnTimeout() {
        logger.warning("Setup the SoundManager2 failed!");
        try {
            SoundManager.getEventBus().fireEvent(new SM2OnTimeoutEvent());
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Handled some errors from #onOnTimeout()!", e);
        }
    }

    private class SM2OnScriptLoaded implements Callback<Void, Exception> {
        @Override
        public void onFailure(Exception reason) {
            logger.log(Level.SEVERE, "Failed to load SoundManager2 library", reason);
        }

        @Override
        public void onSuccess(Void result) {
            setupSoundManager();
        }
    }

    private class SM2JavaScriptLoader implements AsyncModule {
        private Callback<Void, Exception> callback;

        @Override
        public void setCallback(Callback<Void, Exception> callback) {
            this.callback = callback;
        }

        @Override
        public void load() {
            loadSoundManager(callback);
        }
    }

    private class SetupSoundManager implements AsyncModule, PriorityOrdered {
        private Callback<Void, Exception> callback;

        @Override
        public void setCallback(Callback<Void, Exception> callback) {
            this.callback = callback;
        }

        @Override
        public void load() {
            SoundManager.addSM2ReadyHandler(new SM2ReadyHandler() {
                @Override
                public void onSoundManagerReady(SM2ReadyEvent event) {
                    if (callback != null) {
                        callback.onSuccess(null);
                        callback = null;
                    } else {
                        logger.warning("You are trying to initialize the SoundManager in a second time!");
                    }
                }
            });
            SoundManager.addSM2OnTimeoutHandler(new SM2OnTimeoutHandler() {
                @Override
                public void onOnTimeout(SM2OnTimeoutEvent event) {
                    if (callback != null) {
                        if (FailAppLoaderOnTimeout.INSTANCE.fail()) {
                            callback.onFailure(null);
                        } else {
                            callback.onSuccess(null);
                        }
                        callback = null;
                    } else {
                        logger.warning("You are trying to initialize the SoundManager in a second time!");
                    }
                }
            });
            setupSoundManager();
        }

        @Override
        public int getOrder() {
            return LOWEST_PRIORITY;
        }
    }
}


text:
package org.unitedinternet.cosmo.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * A filter that provides the X-Http-Override-Method header. If this header is present,
 * its value will be used as the HTTP method for the current request. This allows
 * HTTP clients with limited HTTP method support to make requests with any method.
 *
 * @author travis
 *
 */
public class HttpOverrideFilter implements Filter {

    private static final Log LOG = LogFactory.getLog(HttpOverrideFilter.class);

    public void destroy() {
        // TODO Auto-generated method stub

    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        if (request instanceof HttpServletRequest &&
            ((HttpServletRequest) request).getHeader("X-Http-Method-Override") != null &&
            LOG.isDebugEnabled()){
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            	//Fix Log Forging - fortify
            	//Writing unvalidated user input to log files can allow an attacker to forge log
            	//entries or inject malicious content into the logs.
                LOG.debug("Overriding " + httpRequest.getMethod() + " with "
                        + httpRequest.getHeader("X-Http-Method-Override"));

            chain.doFilter(new HttpOverrideRequestWrapper(httpRequest),
                    response);
            return;
        }

        chain.doFilter(request, response);
    }

    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }

    static class HttpOverrideRequestWrapper extends HttpServletRequestWrapper {

        private HttpOverrideRequestWrapper(HttpServletRequest request) {
            super(request);
        }

        @Override
        public String getMethod() {
            String overrideMethod = this.getHeader("X-Http-Method-Override");
            if (overrideMethod != null){
                return overrideMethod;
            } else {
                return super.getMethod();
            }
        }

    }

}


text:
import binaryPlugin from './lib/binary-plugin';

export default {
  input: `src/index.js`,
  plugins: [binaryPlugin()],
  output: {
    dir: 'build',
    format: 'esm',
  },
};


text:
use crate::{
    options::{BuildOptions, FuzzDirWrapper},
    project::FuzzProject,
    RunCommand,
};
use anyhow::Result;
use std::path::PathBuf;
use structopt::StructOpt;

#[derive(Clone, Debug, StructOpt)]
pub struct Cmin {
    #[structopt(flatten)]
    pub build: BuildOptions,

    #[structopt(flatten)]
    pub fuzz_dir_wrapper: FuzzDirWrapper,

    /// Name of the fuzz target
    pub target: String,

    #[structopt(parse(from_os_str))]
    /// The corpus directory to minify into
    pub corpus: Option<PathBuf>,

    #[structopt(last(true))]
    /// Additional libFuzzer arguments passed through to the binary
    pub args: Vec<String>,
}

impl RunCommand for Cmin {
    fn run_command(&mut self) -> Result<()> {
        let project = FuzzProject::new(self.fuzz_dir_wrapper.fuzz_dir.to_owned())?;
        project.exec_cmin(self)
    }
}


text:
package org.apache.camel.component.aws2.kinesis.consumer;

import org.apache.camel.component.aws2.kinesis.Kinesis2Configuration;
import software.amazon.awssdk.services.kinesis.model.GetShardIteratorRequest;
import software.amazon.awssdk.services.kinesis.model.ShardIteratorType;

public class KinesisUserConfigurationResumeAdapter implements KinesisResumeAdapter {
    private final Kinesis2Configuration configuration;
    private GetShardIteratorRequest.Builder resumable;

    public KinesisUserConfigurationResumeAdapter(Kinesis2Configuration configuration) {
        this.configuration = configuration;
    }

    private boolean hasSequenceNumber() {
        return !configuration.getSequenceNumber().isEmpty()
                && (configuration.getIteratorType().equals(ShardIteratorType.AFTER_SEQUENCE_NUMBER)
                        || configuration.getIteratorType().equals(ShardIteratorType.AT_SEQUENCE_NUMBER));
    }

    @Override
    public void setRequestBuilder(GetShardIteratorRequest.Builder resumable) {
        this.resumable = resumable;
    }

    @Override
    public void resume() {
        if (hasSequenceNumber()) {
            resumable.startingSequenceNumber(configuration.getSequenceNumber());
        }
    }
}


text:
#ifndef DS_EQUATION_ERRORS_HH
#define DS_EQUATION_ERRORS_HH
#include <string>
#include "GeneralErrors.hh"
#include "OutputStream.hh"
class Region;
class Contact;
template <typename DoubleType>
class Equation;
template <typename DoubleType>
class ContactEquation;
template <typename DoubleType>
class InterfaceEquation;

namespace dsErrors {

  std::string MissingEquationModel(const Region &, const std::string &/*equation_name*/, const std::string &/*model_name*/, ModelInfo::ModelType /*model_type*/, OutputStream::OutputType /*error_level*/);

  std::string MissingEquationIndex(const Region &, const std::string &/*equation_name*/, const std::string &/*variable_name*/, OutputStream::OutputType /*error_level*/);

  template <typename DoubleType>
  std::string MissingContactEquationModel(const Region &, const ContactEquation<DoubleType> &/*contact_equation*/, const std::string &/*model_name*/, ModelInfo::ModelType /*model_type*/, OutputStream::OutputType /*error_level*/);

  std::string MissingContactEquationIndex(const Region &, const Contact &, const std::string &/*equation_name*/, OutputStream::OutputType /*error_level*/);

  template <typename DoubleType>
  std::string SolutionVariableNonPositive(const Region &, const std::string &/*equation_name*/, const std::string &/*variable*/, DoubleType /*value*/, OutputStream::OutputType /*error_level*/);

  template <typename DoubleType>
  std::string MissingCircuitNodeOnContactEquation(const ContactEquation<DoubleType> &/*contact_equation*/,  const std::string &/*circuit_node*/, OutputStream::OutputType /*error_level*/);

  std::string EquationMathErrorInfo(const Equation<double> &/*equation*/, OutputStream::OutputType /*error_level*/);

  std::string CreateModelOnRegion(const Region &/*region*/, const std::string &/*model_name*/, OutputStream::OutputType /*error_level*/);

  template <typename DoubleType>
  std::string MissingInterfaceEquationModel(const Region &/*region*/, const InterfaceEquation<DoubleType> &/*interface_equation*/, const std::string &/*model_name*/, OutputStream::OutputType /*error_level*/);
}
#endif


text:
<?php

/**
 *  Lousson\Record\Generic\GenericRecordFactoryBasicTest class definition
 *
 *  @package    org.lousson.record
 *  @copyright  (c) 2013, The Lousson Project
 *  @license    http://opensource.org/licenses/bsd-license.php New BSD License
 *  @author     Mathias J. Hennig <mhennig at quirkies.org>
 *  @filesource
 */
namespace Lousson\Record\Generic;

/** Dependencies: */
use Lousson\Record\Generic\GenericRecordFactoryTest;
use Lousson\Record\AnyRecordBuilder;
use Lousson\Record\AnyRecordParser;
use Lousson\Record\Builtin\BuiltinRecordFactory;
use Lousson\Record\Builtin\Handler\BuiltinRecordHandlerJSON;
use Lousson\Record\Builtin\Parser\BuiltinRecordParserINI;
use Lousson\Record\Generic\GenericRecordFactory;
use Lousson\Record\Generic\GenericRecordHandler;

/**
 *  A test case for the generic record factory
 *
 *  @since      lousson/Lousson_Record-0.1.0
 *  @package    org.lousson.record
 *  @link       http://www.phpunit.de/manual/current/en/
 */
class GenericRecordFactoryBasicTest extends GenericRecordFactoryTest
{
    /**
     *  Obtain the record factory to test
     *
     *  The getRecordFactory() method returns the record factory instance
     *  that is used in the tests.
     *
     *  @return \Lousson\Record\Generic\GenericRecordFactory
     *          A generic record factory instance is returned on success
     */
    public function getGenericRecordFactory()
    {
        $factory = new GenericRecordFactory();

        $iniParser = new BuiltinRecordParserINI();
        $factory->setRecordParser("application/textedit", $iniParser);

        $jsonHandler = new BuiltinRecordHandlerJSON();
        $factory->setRecordBuilder("application/json", $jsonHandler);
        $factory->setRecordParser("application/json", $jsonHandler);

        $handler = new GenericRecordHandler($jsonHandler, $jsonHandler);
        $factory->setRecordHandler("text/json", $handler);
        $factory->setRecordBuilder("text/json", $jsonHandler);

        return $factory;
    }

    /**
     *  Provide supported media type parameters
     *
     *  The provideBuilderMediaTypes() method returns an array of multiple
     *  items, each of whose is an array with one string item representing
     *  a media type the factory is supposed to provide a builder for.
     *
     *  @return array
     *          A list of media type parameters is returned on success
     */
    public function provideBuilderMediaTypes()
    {
        return array(
            array("application/json"),
            array("text/json"),
        );
    }

    /**
     *  Provide supported media type parameters
     *
     *  The provideParserMediaTypes() method returns an array of multiple
     *  items, each of whose is an array with one string item representing
     *  a media type the factory is supposed to provide a parser for.
     *
     *  @return array
     *          A list of media type parameters is returned on success
     */
    public function provideParserMediaTypes()
    {
        return array(
            array("application/json"),
            array("application/textedit"),
        );
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dta.pizzeria.backend.metier;

import dta.pizzeria.backend.dao.ProduitsDAO;
import dta.pizzeria.backend.entity.Ingredients;
import dta.pizzeria.backend.entity.Produits;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author MHayet
 */
@Service
public class ProduitsService {

    @Autowired
    private ProduitsDAO produitsDao;

    @Autowired
    private IngredientsService ingredientsService;

    @Transactional
    public Produits setProduits(Produits produit) {

        List<Ingredients> ingredients = new ArrayList<>();
        ingredients.addAll(produit.getIngredients());

        produit.getIngredients().clear();

        //Si produit est une pizza
        if (produit.getType() == Produits.Type_Produit.PIZZA) {

            //Met Format à null
            produit.setFormat(null);

            //Enregistrement de la pizza
            produitsDao.save(produit);

            for (Ingredients ing : ingredients) {

                //Update des ingredients
                ingredientsService.updateIngredient(ing);

                //Rajout des pizza dans ingredients
                ing.getPizzas().add(produit);
                ingredientsService.updateIngredient(ing);

                //Rajout de l'ingredient dans pizza
                produit.getIngredients().add(ing);
            }
        }

        //Si le produit est une boisson
        if (produit.getType() == Produits.Type_Produit.BOISSON) {

            produitsDao.save(produit);
            //Met Taille à null
            produit.setTaille(null);
        }

        //Si le produit est un desset
        if (produit.getType() == Produits.Type_Produit.DESSERT) {

            produitsDao.save(produit);
            //Met Format et Taille à null
            produit.setFormat(null);
            produit.setTaille(null);
        }

        //Enregistrement du produit
            return produitsDao.save(produit);

    }

    public Produits updateProduits(Produits produit){
       return setProduits(produit);

    }

    public Produits getProduits(Long id){
        return produitsDao.findOne(id);
    }

    public List<Produits> listProduits(){
        return produitsDao.findAll();
    }

    public List<Produits> listPizzas(){
//        //TODO : a optimiser
//    	List<Produits> prods = listProduits();
//        List<Produits> pizzas = new ArrayList<>();
//        for (Produits prod:prods){
//            if (prod.getType().equals(Produits.Type_Produit.PIZZA)){
//                pizzas.add(prod);
//            }
//        }
//
//        return pizzas;

                return produitsDao.findByType(Produits.Type_Produit.PIZZA);
    }

    public List<Produits> listBoissons(){
//        //TODO : a optimiser
//        List<Produits> prods = listProduits();
//        List<Produits> boissons= new ArrayList<>();
//        for (Produits prod:prods){
//            if (prod.getType().equals(Produits.Type_Produit.BOISSON)){
//                boissons.add(prod);
//            }
//        }
//      return boissons;

        return produitsDao.findByType(Produits.Type_Produit.BOISSON);

    }

    public List<Produits> listDesserts(){
//        //TODO : a optimiser
//        List<Produits> prods = listProduits();
//        List<Produits> desserts = new ArrayList<>();
//        for (Produits prod:prods){
//            if (prod.getType().equals(Produits.Type_Produit.DESSERT)){
//                desserts.add(prod);
//            }
//        }
//
//        return desserts;

       return produitsDao.findByType(Produits.Type_Produit.DESSERT);

    }

    public void removeProduits(Long id){
        produitsDao.delete(id);
    }

    public void removeProduits(Produits produits){
        produitsDao.delete(produits);
    }

    public void removeAllProduits(){
        produitsDao.deleteAll();
    }

}


text:
/*
 * 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.
 */

package com.facebook.presto.spi.statistics;

import com.facebook.presto.spi.ColumnHandle;

import java.util.HashMap;
import java.util.Map;

import static com.facebook.presto.spi.statistics.Estimate.unknownValue;
import static java.util.Collections.unmodifiableMap;
import static java.util.Objects.requireNonNull;

public final class TableStatistics
{
    public static final TableStatistics EMPTY_STATISTICS = TableStatistics.builder().build();

    private static final String ROW_COUNT_STATISTIC_KEY = "row_count";

    private final Map<String, Estimate> statistics;
    private final Map<ColumnHandle, ColumnStatistics> columnStatistics;

    public TableStatistics(Estimate rowCount, Map<ColumnHandle, ColumnStatistics> columnStatistics)
    {
        requireNonNull(rowCount, "rowCount can not be null");
        this.columnStatistics = unmodifiableMap(requireNonNull(columnStatistics, "columnStatistics can not be null"));
        this.statistics = createStatisticsMap(rowCount);
    }

    private static Map<String, Estimate> createStatisticsMap(Estimate rowCount)
    {
        Map<String, Estimate> statistics = new HashMap<>();
        statistics.put(ROW_COUNT_STATISTIC_KEY, rowCount);
        return unmodifiableMap(statistics);
    }

    public Estimate getRowCount()
    {
        return statistics.get(ROW_COUNT_STATISTIC_KEY);
    }

    public Map<String, Estimate> getTableStatistics()
    {
        return statistics;
    }

    public Map<ColumnHandle, ColumnStatistics> getColumnStatistics()
    {
        return columnStatistics;
    }

    public static Builder builder()
    {
        return new Builder();
    }

    public static final class Builder
    {
        private Estimate rowCount = unknownValue();
        private Map<ColumnHandle, ColumnStatistics> columnStatisticsMap = new HashMap<>();

        public Builder setRowCount(Estimate rowCount)
        {
            this.rowCount = requireNonNull(rowCount, "rowCount can not be null");
            return this;
        }

        public Builder setColumnStatistics(ColumnHandle columnName, ColumnStatistics columnStatistics)
        {
            requireNonNull(columnName, "columnName can not be null");
            requireNonNull(columnStatistics, "columnStatistics can not be null");
            this.columnStatisticsMap.put(columnName, columnStatistics);
            return this;
        }

        public TableStatistics build()
        {
            return new TableStatistics(rowCount, columnStatisticsMap);
        }
    }
}


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

    Most of the code in the Qalingo project is copyrighted Hoteia and licensed
    under the Apache License Version 2.0 (release version 0.8.0)
            http://www.apache.org/licenses/LICENSE-2.0

                      Copyright (c) Hoteia, 2012-2014
    http://www.hoteia.com - http://twitter.com/hoteia - contact@hoteia.com

-->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <bean id="backofficeViewBeanFactory" class="org.hoteia.qalingo.web.mvc.factory.BoBusinessViewBeanFactory" />

    <bean id="backofficeFormFactory" class="org.hoteia.qalingo.web.mvc.factory.BoBusinessFormFactory " />

</beans>