text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="trikita.obsqr"
	android:installLocation="auto">

	<uses-permission android:name="android.permission.CAMERA" />

	<uses-feature android:name="android.hardware.camera" />
	<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />

	<application android:label="@string/app_name"
		android:allowBackup="true"
		android:fullBackupContent="false"
		android:hardwareAccelerated="true"
		android:supportsRtl = "true"
		android:icon="@drawable/ic_launcher"
		android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
		<meta-data android:name="com.google.android.gms.version"
			android:value="@integer/google_play_services_version" />
		<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES"
			android:value="barcode" />
		<activity android:name="ObsqrActivity"
			android:launchMode="singleTop"
			android:label="@string/app_name">
			<intent-filter>
				<action android:name="android.intent.action.SEARCH_LONG_PRESS" />
				<category android:name="android.intent.category.DEFAULT" />
				<action android:name="android.intent.action.MAIN" />
				<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
	</application>
</manifest>


text:
require 'generator_spec_helper'
require_generator :roles_model => :roles

describe 'helper_generator' do
  let(:strategy) { 'one_role' }

  use_orm :active_record
  helpers :model

  before :each do
    setup_generator 'roles_generator' do
      tests RolesModel::Generators::RolesGenerator
    end
    remove_model 'user'
  end

  after :each do
    remove_model 'user'
  end

  it "should configure 'one_role' strategy" do
    create_model :user do
      '# content'
    end
    with_generator do |g|
      arguments = "User --strategy #{strategy} --roles admin user --orm active_record"
      puts "arguments: #{arguments}"
      g.run_generator arguments.args
      g.should generate_model :user do |clazz|
        clazz.should include_module 'RoleModels::Generic'
        clazz.should have_call :role_class, :args => ':role'
        clazz.should have_call :valid_roles_are, :args => ':admin, :user'
        clazz.should have_call :strategy, :args => ":#{strategy}"
      end
    end
  end
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef __C_GUI_TAB_CONTROL_H_INCLUDED__
#define __C_GUI_TAB_CONTROL_H_INCLUDED__

#include "IrrCompileConfig.h"
#ifdef _IRR_COMPILE_WITH_GUI_

#include "IGUITabControl.h"
#include "irrArray.h"
#include "IGUISkin.h"

namespace irr
{
namespace gui
{
	class CGUITabControl;
	class IGUIButton;

	// A tab, onto which other gui elements could be added.
	class CGUITab : public IGUITab
	{
	public:

		//! constructor
		CGUITab(s32 number, IGUIEnvironment* environment,
			IGUIElement* parent, const core::rect<s32>& rectangle,
			s32 id);

		//! destructor
		//virtual ~CGUITab();

		//! Returns number of this tab in tabcontrol. Can be accessed
		//! later IGUITabControl::getTab() by this number.
		virtual s32 getNumber() const _IRR_OVERRIDE_;

		//! Sets the number
		virtual void setNumber(s32 n);

		//! draws the element and its children
		virtual void draw() _IRR_OVERRIDE_;

		//! sets if the tab should draw its background
		virtual void setDrawBackground(bool draw=true) _IRR_OVERRIDE_;

		//! sets the color of the background, if it should be drawn.
		virtual void setBackgroundColor(video::SColor c) _IRR_OVERRIDE_;

		//! sets the color of the text
		virtual void setTextColor(video::SColor c) _IRR_OVERRIDE_;

		//! returns true if the tab is drawing its background, false if not
		virtual bool isDrawingBackground() const _IRR_OVERRIDE_;

		//! returns the color of the background
		virtual video::SColor getBackgroundColor() const _IRR_OVERRIDE_;

		virtual video::SColor getTextColor() const _IRR_OVERRIDE_;

		//! Writes attributes of the element.
		virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const _IRR_OVERRIDE_;

		//! Reads attributes of the element
		virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options) _IRR_OVERRIDE_;

		//! only for internal use by CGUITabControl
		void refreshSkinColors();

	private:

		s32 Number;
		video::SColor BackColor;
		bool OverrideTextColorEnabled;
		video::SColor TextColor;
		bool DrawBackground;
	};

	//! A standard tab control
	class CGUITabControl : public IGUITabControl
	{
	public:

		//! destructor
		CGUITabControl(IGUIEnvironment* environment,
			IGUIElement* parent, const core::rect<s32>& rectangle,
			bool fillbackground=true, bool border=true, s32 id=-1);

		//! destructor
		virtual ~CGUITabControl();

		//! Adds a tab
		virtual IGUITab* addTab(const wchar_t* caption, s32 id=-1) _IRR_OVERRIDE_;

		//! Adds a tab that has already been created
		virtual void addTab(CGUITab* tab);

		//! Insert the tab at the given index
		virtual IGUITab* insertTab(s32 idx, const wchar_t* caption, s32 id=-1) _IRR_OVERRIDE_;

		//! Removes a tab from the tabcontrol
		virtual void removeTab(s32 idx) _IRR_OVERRIDE_;

		//! Clears the tabcontrol removing all tabs
		virtual void clear() _IRR_OVERRIDE_;

		//! Returns amount of tabs in the tabcontrol
		virtual s32 getTabCount() const _IRR_OVERRIDE_;

		//! Returns a tab based on zero based index
		virtual IGUITab* getTab(s32 idx) const _IRR_OVERRIDE_;

		//! Brings a tab to front.
		virtual bool setActiveTab(s32 idx) _IRR_OVERRIDE_;

		//! Brings a tab to front.
		virtual bool setActiveTab(IGUITab *tab) _IRR_OVERRIDE_;

		//! Returns which tab is currently active
		virtual s32 getActiveTab() const _IRR_OVERRIDE_;

		//! get the the id of the tab at the given absolute coordinates
		virtual s32 getTabAt(s32 xpos, s32 ypos) const _IRR_OVERRIDE_;

		//! called if an event happened.
		virtual bool OnEvent(const SEvent& event) _IRR_OVERRIDE_;

		//! draws the element and its children
		virtual void draw() _IRR_OVERRIDE_;

		//! Removes a child.
		virtual void removeChild(IGUIElement* child) _IRR_OVERRIDE_;

		//! Writes attributes of the element.
		virtual void serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options) const _IRR_OVERRIDE_;
		//! Set the height of the tabs
		virtual void setTabHeight( s32 height ) _IRR_OVERRIDE_;

		//! Reads attributes of the element
		virtual void deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options) _IRR_OVERRIDE_;

		//! Get the height of the tabs
		virtual s32 getTabHeight() const _IRR_OVERRIDE_;

		//! set the maximal width of a tab. Per default width is 0 which means "no width restriction".
		virtual void setTabMaxWidth(s32 width ) _IRR_OVERRIDE_;

		//! get the maximal width of a tab
		virtual s32 getTabMaxWidth() const _IRR_OVERRIDE_;

		//! Set the alignment of the tabs
		//! note: EGUIA_CENTER is not an option
		virtual void setTabVerticalAlignment( gui::EGUI_ALIGNMENT alignment ) _IRR_OVERRIDE_;

		//! Get the alignment of the tabs
		virtual gui::EGUI_ALIGNMENT getTabVerticalAlignment() const _IRR_OVERRIDE_;

		//! Set the extra width added to tabs on each side of the text
		virtual void setTabExtraWidth( s32 extraWidth ) _IRR_OVERRIDE_;

		//! Get the extra width added to tabs on each side of the text
		virtual s32 getTabExtraWidth() const _IRR_OVERRIDE_;

		//! Update the position of the element, decides scroll button status
		virtual void updateAbsolutePosition() _IRR_OVERRIDE_;

	private:

		void scrollLeft();
		void scrollRight();
		bool needScrollControl( s32 startIndex=0, bool withScrollControl=false );
		s32 calcTabWidth(s32 pos, IGUIFont* font, const wchar_t* text, bool withScrollControl ) const;
		core::rect<s32> calcTabPos();

		void recalculateScrollButtonPlacement();
		void recalculateScrollBar();
		void refreshSprites();

		core::array<CGUITab*> Tabs;	// CGUITab* because we need setNumber (which is certainly not nice)
		s32 ActiveTab;
		bool Border;
		bool FillBackground;
		bool ScrollControl;
		s32 TabHeight;
		gui::EGUI_ALIGNMENT VerticalAlignment;
		IGUIButton* UpButton;
		IGUIButton* DownButton;
		s32 TabMaxWidth;
		s32 CurrentScrollTabIndex;
		s32 TabExtraWidth;
	};

} // end namespace gui
} // end namespace irr

#endif // _IRR_COMPILE_WITH_GUI_

#endif


text:
<component name="libraryTable">
  <library name="Maven: xmlenc:xmlenc:0.52">
    <CLASSES>
      <root url="jar://${symbol_dollar}MAVEN_REPOSITORY${symbol_dollar}/xmlenc/xmlenc/0.52/xmlenc-0.52.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://${symbol_dollar}MAVEN_REPOSITORY${symbol_dollar}/xmlenc/xmlenc/0.52/xmlenc-0.52-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://${symbol_dollar}MAVEN_REPOSITORY${symbol_dollar}/xmlenc/xmlenc/0.52/xmlenc-0.52-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
using namespace llvm;

#define DEBUG_TYPE "UndoTruncateToOddInteger"

Value *
clspv::UndoTruncateToOddIntegerPass::ZeroExtend(Value *v,
                                                uint32_t desired_bit_width) {
  unsigned bit_width = 0;
  if (v->getType()->isIntegerTy())
    bit_width = v->getType()->getIntegerBitWidth();
  if (bit_width > 32) {
    errs() << "Unhandled bit width for " << *v << "\n";
    llvm_unreachable("Unhandled bit width");
  }

  auto where = extended_value_.find(v);
  if (where != extended_value_.end()) {
    return where->second;
  }

  // This base case makes for easier recursion.
  if (bit_width == desired_bit_width && !isa<ZExtInst>(v))
    return v;

  auto desired_int_ty = IntegerType::get(v->getContext(), desired_bit_width);
  if (auto *ci = dyn_cast<ConstantInt>(v)) {
    return ConstantInt::get(desired_int_ty, uint32_t(ci->getZExtValue()));
  }
  Value *result = nullptr;
  if (auto *trunc = dyn_cast<TruncInst>(v)) {
    Value *tmp = nullptr;
    auto input = trunc->getOperand(0);
    uint32_t input_bit_width = input->getType()->getIntegerBitWidth();
    if (input_bit_width > desired_bit_width) {
      tmp = new TruncInst(input, desired_int_ty, "", trunc);
    } else if (input_bit_width == desired_bit_width) {
      tmp = input;
    } else if (input_bit_width > bit_width) {
      tmp = new ZExtInst(input, desired_int_ty, "", trunc);
    } else {
      tmp = ZeroExtend(input, desired_bit_width);
    }

    // Now, and the extended version to keep the range of the output
    // restricted to the original bit width.
    result = BinaryOperator::Create(
        Instruction::And, tmp,
        ConstantInt::get(
            desired_int_ty,
            (uint32_t)APInt::getAllOnesValue(bit_width).getZExtValue()),
        "", trunc);
  } else if (auto *zext = dyn_cast<ZExtInst>(v)) {
    auto tmp = ZeroExtend(zext->getOperand(0), desired_bit_width);
    uint32_t zext_width = zext->getType()->getIntegerBitWidth();
    //
    if (zext_width < desired_bit_width) {
      result = new TruncInst(tmp, zext->getType(), "", zext);
    } else if (zext_width > desired_bit_width) {
      zext->setOperand(0, tmp);
      result = zext;
    } else {
      result = tmp;
    }
  } else if (auto *phi = dyn_cast<PHINode>(v)) {
    const auto num_branches = phi->getNumIncomingValues();
    PHINode *new_phi = PHINode::Create(desired_int_ty, num_branches, "", phi);
    for (unsigned i = 0; i < num_branches; i++) {
      new_phi->addIncoming(
          ZeroExtend(phi->getIncomingValue(i), desired_bit_width),
          phi->getIncomingBlock(i));
    }
    result = new_phi;
  } else if (auto *sel = dyn_cast<SelectInst>(v)) {
    auto *ext_true = ZeroExtend(sel->getTrueValue(), desired_bit_width);
    auto *ext_false = ZeroExtend(sel->getFalseValue(), desired_bit_width);
    result =
        SelectInst::Create(sel->getCondition(), ext_true, ext_false, "", sel);
  } else if (auto *binop = dyn_cast<BinaryOperator>(v)) {
    // White-list binary operators that are ok to transform.
    if (binop->getOpcode() == Instruction::Add ||
        binop->getOpcode() == Instruction::Sub ||
        binop->getOpcode() == Instruction::Mul ||
        binop->getOpcode() == Instruction::And ||
        binop->getOpcode() == Instruction::Or ||
        binop->getOpcode() == Instruction::Xor) {
      auto *op1 = ZeroExtend(binop->getOperand(0), desired_bit_width);
      auto *op2 = ZeroExtend(binop->getOperand(1), desired_bit_width);
      result = BinaryOperator::Create(binop->getOpcode(), op1, op2, "", binop);
      if (binop->getOpcode() == Instruction::Add ||
          binop->getOpcode() == Instruction::Sub ||
          binop->getOpcode() == Instruction::Mul) {
        // Add an extra masking for add and sub in case of integer wrapping.
        result = BinaryOperator::Create(
            Instruction::And, result,
            ConstantInt::get(
                desired_int_ty,
                (uint32_t)APInt::getAllOnesValue(bit_width).getZExtValue()),
            "", binop);
      }
    } else {
      errs() << "Unhandled instruction feeding switch " << *v << "\n";
      llvm_unreachable("Unhandled instruction feeding switch!");
    }
  } else if (auto SI = dyn_cast<SwitchInst>(v)) {
    auto extended_cond = ZeroExtend(SI->getCondition(), desired_bit_width);
    if (extended_cond && extended_cond != SI->getCondition()) {
      SI->setCondition(extended_cond);
      for (auto Cases : SI->cases()) {
        // The original value of the case.
        auto V = Cases.getCaseValue()->getZExtValue();

        // A new value for the case with the correct type.
        auto CI = dyn_cast<ConstantInt>(ConstantInt::get(desired_int_ty, V));

        // And we replace the old value.
        Cases.setValue(CI);
      }
    }
  } else if (auto inst = dyn_cast<Instruction>(v)) {
    for (unsigned i = 0; i < inst->getNumOperands(); ++i) {
      auto extended_op = ZeroExtend(inst->getOperand(i), desired_bit_width);
      if (extended_op && extended_op != inst->getOperand(i))
        inst->setOperand(i, extended_op);
    }
  } else {
    errs() << "Unhandled instruction " << *v << "\n";
    llvm_unreachable("Unhandled instruction!");
  }

  // If the instruction was replaced, mark it as a zombie.
  if (auto *inst = dyn_cast<Instruction>(v)) {
    if (result && result != inst)
      zombies_.insert(inst);
  }

  if (result)
    extended_value_[v] = result;
  return result;
}

PreservedAnalyses
clspv::UndoTruncateToOddIntegerPass::run(Module &M, ModuleAnalysisManager &) {
  PreservedAnalyses PA;

  SmallVector<std::pair<Instruction *, uint32_t>, 8> WorkList;
  for (Function &F : M) {
    for (BasicBlock &BB : F) {
      for (Instruction &I : BB) {
        if (auto trunc = dyn_cast<TruncInst>(&I)) {
          if (trunc->getType()->isVectorTy())
            continue;
          auto desired_bit_width =
              trunc->getOperand(0)->getType()->getIntegerBitWidth();
          switch (trunc->getType()->getIntegerBitWidth()) {
          default:
            WorkList.push_back(std::make_pair(
                trunc, static_cast<uint32_t>(PowerOf2Ceil(desired_bit_width))));
            break;
          case 1: // i1 is a bool.
          case 8:
          case 16:
          case 32:
          case 64:
            break;
          }
        }
      }
    }
  }

  zombies_.reset();

  while (!WorkList.empty()) {
    auto inst = WorkList.back().first;
    auto desired_bit_width = WorkList.back().second;
    WorkList.pop_back();

    auto extended = ZeroExtend(inst, desired_bit_width);
    if (extended && extended != inst) {
      for (auto user : inst->users()) {
        if (auto user_inst = dyn_cast<Instruction>(user)) {
          WorkList.push_back(std::make_pair(user_inst, desired_bit_width));
        }
      }
    }
  }

  // Remove the zombies if we can.  We expect to. We've ordered zombies in
  // reverse.
  for (int i = zombies_.size(); i >= 1; --i) {
    auto zombie = zombies_[i];
    if (!zombie->hasNUsesOrMore(1))
      zombie->eraseFromParent();
  }

  return PA;
}


text:
Camera::Camera()
{
	camera.open(0);
}

Camera::Camera(Size size)
{
	camera.open(0);

	camera.set(CV_CAP_PROP_FRAME_WIDTH, size.width);
    camera.set(CV_CAP_PROP_FRAME_HEIGHT, size.height);
}

Camera::~Camera()
{
	camera.release();
}

RGBFrame Camera::getRGBFrame()
{
	Mat frame;

	while(!frame.data)
	{
		camera >> frame;
	}

	return RGBFrame(frame);
}


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

namespace bovigo\assert\predicate;
/**
 * Applies a predicate to each value of an array or traversable.
 *
 * Please note that an empty array or traversable will result in a successful
 * test.
 *
 * @since  1.3.0
 */
abstract class IteratingPredicate extends Predicate
{
    /**
     * @var  \bovigo\assert\predicate\Predicate
     */
    protected $predicate;

    /**
     * constructor
     *
     * @param  callable|\bovigo\assert\predicate\Predicate  $predicate
     */
    public function __construct($predicate)
    {
        $this->predicate = Predicate::castFrom($predicate);
    }

    /**
     * evaluates predicate against given value
     *
     * @param   mixed  $value
     * @return  bool
     * @throws  \InvalidArgumentException
     */
    public function test($value): bool
    {
        if (!is_array($value) && !($value instanceof \Traversable)) {
            throw new \InvalidArgumentException(
                    'Given value is neither an array nor an instance of '
                    . '\Traversable, but of type ' . gettype($value)
            );
        }

        $traversable = $this->traversable($value);
        $key         = $this->key($traversable);
        $result      = $this->doTest($traversable);
        if (null !== $key) {
            $this->rewind($traversable, $key);
        }

        return $result;
    }

    /**
     * actually tests the value
     *
     * @param   iterable  $traversable
     * @return  bool
     */
    protected abstract function doTest(iterable $traversable): bool;

    /**
     * retrieve actual iterator
     *
     * @param   iterable  $traversable
     * @return  array|\Iterator
     */
    private function traversable(iterable $traversable)
    {
        if ($traversable instanceof \IteratorAggregate) {
            return $this->traversable($traversable->getIterator());
        }

        return $traversable;
    }

    /**
     * retrieves current key of traversable
     *
     * @param   array|\Iterator  $traversable
     * @return  int|string|null
     */
    private function key($traversable)
    {
        if (is_array($traversable)) {
            return key($traversable);
        }

        return $traversable->key();
    }

    /**
     * rewinds traversable to given key to not change state of traversable
     *
     * @param  array<mixed>|\Iterator<mixed,mixed>  $traversable
     * @param  int|string       $key
     */
    private function rewind($traversable, $key): void
    {
        if (is_array($traversable)) {
            foreach ($traversable as $currentKey => $value) {
                if ($currentKey === $key) {
                    break;
                }
            }
        } else {
            $traversable->rewind();
            while ($traversable->valid() && $key !== $traversable->key()) {
                $traversable->next();
            }
        }
    }

    /**
     * returns amount of checks done in this predicate
     *
     * @return  int
     */
    public function count(): int
    {
        return count($this->predicate);
    }
}


text:
@interface PodsDummy_Pods_DY : NSObject
@end
@implementation PodsDummy_Pods_DY
@end


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

namespace Innmind\Rest\Server\Exception;

final class RouteNotFound extends RuntimeException
{
}


text:
This project adheres to [Semantic Versioning](http://semver.org/).

This CHANGELOG follows the format listed at [Keep A Changelog](http://keepachangelog.com/)

## [Unreleased]
### Added
* Adding support for Regular Expression matching
* Added simple response time metric
- Unlocked the dnsruby dependency to allow upgrades

## [0.0.6] - 2015-09-28
### Changed
- Migrated from ruby library resolv to dnsruby to support more dns related checks

## [0.0.5] - 2015-08-05
### Removed
- PTR lookups no longer end with a dot '.'

### Changed
- Removed need for dig and replace with ruby resolv
- general gem cleanup

## [0.0.4] - 2015-07-14
### Changed
- updated sensu-plugin gem to 1.2.0

## [0.0.3] - 2015-06-02
### Fixed
- added binstubs

### Changed
- removed cruft from /lib

[Unreleased]: https://github.com/sensu-plugins/sensu-plugins-ansible/compare/0.0.6...HEAD
[0.0.5]: https://github.com/sensu-plugins/sensu-plugins-ansible/compare/0.0.5...0.0.6
[0.0.5]: https://github.com/sensu-plugins/sensu-plugins-ansible/compare/0.0.4...0.0.5
[0.0.4]: https://github.com/sensu-plugins/sensu-plugins-ansible/compare/0.0.3...0.0.4
[0.0.3]: https://github.com/sensu-plugins/sensu-plugins-ansible/compare/0.0.2...0.0.3
[0.0.2]: https://github.com/sensu-plugins/sensu-plugins-ansible/compare/0.0.1...0.0.2


text:
const Double_t nevtmin= 1;
const Double_t nevtmax = 15000;

// Muons
const Double_t ymin  = -4.0 ;
const Double_t ymax  =  -2.5 ;

const Double_t phimin = -180;
const Double_t phimax = 180;

// Resonance
const Int_t    PDG = 443; //JPsi

const Double_t ptmin =  0.0 ;
const Double_t ptmax =  30 ;
const Double_t pmin =  0.0 ;
const Double_t pmax =  700 ;
const Int_t    charge  = 0 ;
const Double_t mmin =  0.1 ;
const Double_t mmax =  12 ;
const Double_t mymin =  -4 ;
const Double_t mymax =  -2.5 ;
const Double_t costCSmin =  -1.;
const Double_t costCSmax =  1.;
const Double_t costHEmin =  -1.;
const Double_t costHEmax =  1.;
const Double_t phiCSmin =  -TMath::Pi();
const Double_t phiCSmax =  TMath::Pi();
const Double_t phiHEmin =  -TMath::Pi();
const Double_t phiHEmax =  TMath::Pi();

//----------------------------------------------------

Bool_t AliCFMuonResTask1(
			    const Bool_t useGrid = 0,
			    const Bool_t readAOD = 0,
			    const char * kTagXMLFile="wn.xml" // XML file containing tags
			    )
{

  TBenchmark benchmark;
  benchmark.Start("AliMuonResTask1");

  AliLog::SetGlobalDebugLevel(0);

  Load() ; // load the required libraries

  TChain * analysisChain ;

///// INPUT

  if (useGrid) { // data located on AliEn
    TGrid::Connect("alien://") ;    //  Create an AliRunTagCuts and an AliEventTagCuts Object
                                    //  and impose some selection criteria
    AliRunTagCuts      *runCuts   = new AliRunTagCuts();
    AliEventTagCuts    *eventCuts = new AliEventTagCuts();
    AliLHCTagCuts      *lhcCuts   = new AliLHCTagCuts();
    AliDetectorTagCuts *detCuts   = new AliDetectorTagCuts();
    eventCuts->SetMultiplicityRange(0,2000);

    //  Create an AliTagAnalysis Object and chain the tags
    AliTagAnalysis   *tagAna = new AliTagAnalysis();
    if (readAOD) tagAna->SetType("AOD");  // for aliroot > v4-05
    else         tagAna->SetType("ESD");  // for aliroot > v4-05
    TGridCollection *coll   = gGrid->OpenCollection(kTagXMLFile);
    TGridResult      *tagResult = coll->GetGridResult("",0,0);
    tagResult->Print();
    tagAna->ChainGridTags(tagResult);

    // Create a new esd chain and assign the chain that is returned by querying the tags
    analysisChain = tagAna->QueryTags(runCuts,lhcCuts,detCuts,eventCuts);
  }

  else {// local data
    // here put your input data path
    printf("\n\nRunning on local file, please check the path\n\n");

    if (readAOD) {
      analysisChain = new TChain("aodTree");
      analysisChain->Add("AliAOD.root");
    }
    else {
      analysisChain = new TChain("esdTree");
      analysisChain->Add("/alidata/alice/arnaldi/CORRFW/polar-1.1000.1000/AliESDs.root");
      analysisChain->Add("/alidata/alice/arnaldi/CORRFW/polar-1.1001.1000/AliESDs.root");
      analysisChain->Add("/alidata/alice/arnaldi/CORRFW/polar-1.1002.1000/AliESDs.root");
   }
  }

///// END INPUT

  Info("AliCFMuonResTask1",Form("CHAIN HAS %d ENTRIES",(Int_t)analysisChain->GetEntries()));

  // CONTAINER DEFINITION
  Info("AliCFMuonResTask1","SETUP CONTAINER");

  // The sensitive variables (13 in this example), their indices
  UInt_t nevt  = 0;
  UInt_t y1  = 1;
  UInt_t phi1  = 2;
  UInt_t y2  = 3;
  UInt_t phi2  = 4;
  UInt_t imass  = 5;
  UInt_t y  = 6;
  UInt_t pt = 7;
  UInt_t p = 8;
  UInt_t costCS = 9;
  UInt_t phiCS = 10;
  UInt_t costHE = 11;
  UInt_t phiHE = 12;

  // Setting up the container grid
  UInt_t nstep = 2 ; //number of selection steps : MC and ESD
  const Int_t nvar   = 13 ;     //number of variables on the grid
  const Int_t nbin1  = nevtmax ;
  const Int_t nbin2  = 100 ;
  const Int_t nbin3  = 360 ;
  const Int_t nbin4  = 100 ;
  const Int_t nbin5  = 360 ;
  const Int_t nbin6  = 100 ;
  const Int_t nbin7  = 50 ;
  const Int_t nbin8  = 50 ;
  const Int_t nbin9  = 50 ;
  const Int_t nbin10  = 20 ;
  const Int_t nbin11  = 20 ;
  const Int_t nbin12  = 20 ;
  const Int_t nbin13  = 20 ;

  // arrays for the number of bins in each dimension
  Int_t iBin[nvar];
  iBin[0]=nbin1;
  iBin[1]=nbin2;
  iBin[2]=nbin3;
  iBin[3]=nbin4;
  iBin[4]=nbin5;
  iBin[5]=nbin6;
  iBin[6]=nbin7;
  iBin[7]=nbin8;
  iBin[8]=nbin9;
  iBin[9]=nbin10;
  iBin[10]=nbin11;
  iBin[11]=nbin12;
  iBin[12]=nbin13;

  // arrays for lower bounds :
  Double_t *binLim1=new Double_t[nbin1+1];
  Double_t *binLim2=new Double_t[nbin2+1];
  Double_t *binLim3=new Double_t[nbin3+1];
  Double_t *binLim4=new Double_t[nbin4+1];
  Double_t *binLim5=new Double_t[nbin5+1];
  Double_t *binLim6=new Double_t[nbin6+1];
  Double_t *binLim7=new Double_t[nbin7+1];
  Double_t *binLim8=new Double_t[nbin8+1];
  Double_t *binLim9=new Double_t[nbin9+1];
  Double_t *binLim10=new Double_t[nbin10+1];
  Double_t *binLim11=new Double_t[nbin11+1];
  Double_t *binLim12=new Double_t[nbin12+1];
  Double_t *binLim13=new Double_t[nbin13+1];

  // values for bin lower bounds
  for(Int_t i=0; i<=nbin1; i++) binLim1[i]=(Double_t)nevtmin  + (nevtmax-nevtmin)  /nbin1*(Double_t)i ;
  for(Int_t i=0; i<=nbin2; i++) binLim2[i]=(Double_t)ymin  + (ymax-ymin)  /nbin2*(Double_t)i ;
  for(Int_t i=0; i<=nbin3; i++) binLim3[i]=(Double_t)phimin  + (phimax-phimin)  /nbin3*(Double_t)i ;
  for(Int_t i=0; i<=nbin4; i++) binLim4[i]=(Double_t)ymin  + (ymax-ymin)  /nbin4*(Double_t)i ;
  for(Int_t i=0; i<=nbin5; i++) binLim5[i]=(Double_t)phimin  + (phimax-phimin)  /nbin5*(Double_t)i ;
  for(Int_t i=0; i<=nbin6; i++) binLim6[i]=(Double_t)mmin  + (mmax-mmin)  /nbin6*(Double_t)i ;
  for(Int_t i=0; i<=nbin7; i++) binLim7[i]=(Double_t)mymin  + (mymax-mymin)  /nbin7*(Double_t)i ;
  for(Int_t i=0; i<=nbin8; i++) binLim8[i]=(Double_t)ptmin + (ptmax-ptmin)/nbin8*(Double_t)i ;
  for(Int_t i=0; i<=nbin9; i++) binLim9[i]=(Double_t)pmin + (pmax-pmin)/nbin9*(Double_t)i ;
  for(Int_t i=0; i<=nbin10; i++) binLim10[i]=(Double_t)costCSmin + (costCSmax-costCSmin)/nbin10*(Double_t)i ;
  for(Int_t i=0; i<=nbin11; i++) binLim11[i]=(Double_t)phiCSmin + (phiCSmax-phiCSmin)/nbin11*(Double_t)i ;
  for(Int_t i=0; i<=nbin12; i++) binLim12[i]=(Double_t)costHEmin + (costHEmax-costHEmin)/nbin12*(Double_t)i ;
  for(Int_t i=0; i<=nbin13; i++) binLim13[i]=(Double_t)phiHEmin + (phiHEmax-phiHEmin)/nbin13*(Double_t)i ;

  // one container  of 2 steps (MC and ESD) with 12 variables
  AliCFContainer* container = new AliCFContainer("container","container for tracks",nstep,nvar,iBin);
  // setting the bin limits
  container -> SetBinLimits(nevt,binLim1);
  container -> SetBinLimits(y1,binLim2);
  container -> SetBinLimits(phi1,binLim3);
  container -> SetBinLimits(y2,binLim4);
  container -> SetBinLimits(phi2,binLim5);
  container -> SetBinLimits(imass,binLim6);
  container -> SetBinLimits(y,binLim7);
  container -> SetBinLimits(pt,binLim8);
  container -> SetBinLimits(p,binLim9);
  container -> SetBinLimits(costCS,binLim10);
  container -> SetBinLimits(phiCS,binLim11);
  container -> SetBinLimits(costHE,binLim12);
  container -> SetBinLimits(phiHE,binLim13);

  // Set list
  TList* qaList = new TList();

  //CREATE THE CUTS
  // Choice of the Resonance
  AliCFParticleGenCuts* mcGenCuts = new AliCFParticleGenCuts("mcGenCuts","MC particle generation cuts");
  mcGenCuts->SetRequirePdgCode(PDG);
  mcGenCuts->SetQAOn(qaList);

  // Set a pt range of the resonance
  AliCFTrackKineCuts *mcKineCuts = new AliCFTrackKineCuts("mcKineCuts","MC-level kinematic cuts");
  mcKineCuts->SetChargeMC(charge);
  mcKineCuts->SetPtRange(ptmin,ptmax);
  mcKineCuts->SetQAOn(qaList);

  // Create and fill the list associated
  TObjArray* mcList = new TObjArray(0) ;
  mcList->AddLast(mcKineCuts);
  mcList->AddLast(mcGenCuts);

  // kinematic cuts on muons rapidity
  AliCFTrackKineCuts *recKineCuts = new AliCFTrackKineCuts("recKineCuts","rec-level kine cuts");
//  recKineCuts->SetRapidityRange(ymin,ymax);
  recKineCuts->SetRapidityRange(-4,-2.5);
  recKineCuts->SetQAOn(qaList);
  TObjArray* recList = new TObjArray(0) ;
  recList->AddLast(recKineCuts);

  // CREATE THE INTERFACE TO CORRECTION FRAMEWORK USED IN THE TASK

  printf("CREATE INTERFACE AND CUTS\n");
  AliCFManager* man = new AliCFManager() ;
  man->SetParticleContainer     (container);

  man->SetParticleCutsList(AliCFManager::kPartGenCuts,mcList);
  man->SetParticleCutsList(AliCFManager::kPartAccCuts,recList);

  //CREATE THE TASK
  printf("CREATE TASK\n");
  // create the task
  AliCFMuonResTask1 *task = new AliCFMuonResTask1("AliMuonResTask1");
  task->SetCFManager(man); //here is set the CF manager
  task->SetQAList(qaList);
  if (readAOD)       task->SetReadAODData() ;

  //SETUP THE ANALYSIS MANAGER TO READ INPUT CHAIN AND WRITE DESIRED OUTPUTS
  printf("CREATE ANALYSIS MANAGER\n");
  // Make the analysis manager
  AliAnalysisManager *mgr = new AliAnalysisManager("TestManager");

  if (useGrid) mgr->SetAnalysisType(AliAnalysisManager::kGridAnalysis);
  else mgr->SetAnalysisType(AliAnalysisManager::kLocalAnalysis);

  AliMCEventHandler*  mcHandler = new AliMCEventHandler();
  mgr->SetMCtruthEventHandler(mcHandler);

  AliInputEventHandler* dataHandler ;

  if   (readAOD) dataHandler = new AliAODInputHandler();
  else           dataHandler = new AliESDInputHandler();
  mgr->SetInputEventHandler(dataHandler);

  // Create and connect containers for input/output

  // input data
  AliAnalysisDataContainer *cinput0  = mgr->CreateContainer("cchain0",TChain::Class(),AliAnalysisManager::kInputContainer);

  // output data
  Char_t file[256];
  sprintf(file,"CFMuonResTask1.root");
  printf("Analysis output in %s \n",file);

  // output TH1I for event counting
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("chist0", TH1I::Class(),AliAnalysisManager::kOutputContainer,file);
  // output Correction Framework Container (for acceptance & efficiency calculations)
  AliAnalysisDataContainer *coutput2 = mgr->CreateContainer("ccontainer0", AliCFContainer::Class(),AliAnalysisManager::kOutputContainer,file);

  cinput0->SetData(analysisChain);
  mgr->AddTask(task);

  mgr->ConnectInput(task,0,mgr->GetCommonInputContainer());

  mgr->ConnectOutput(task,1,coutput1);
  mgr->ConnectOutput(task,2,coutput2);

  printf("READY TO RUN\n");
  //RUN !!!
  if (mgr->InitAnalysis()) {
    mgr->PrintStatus();
    mgr->StartAnalysis("local",analysisChain);
  }

  benchmark.Stop("AliMuonResTask1");
  benchmark.Show("AliMuonResTask1");

  return kTRUE ;
}

void Load() {

  //load the required aliroot libraries
  gSystem->Load("libANALYSIS") ;
  gSystem->Load("libANALYSISalice") ;

//  gSystem->Load("libCORRFW") ;
  gSystem->Load("$ALICE_ROOT/lib/tgt_linux/libCORRFW") ;

  //compile online the task class
  gSystem->SetIncludePath("-I. -I$ALICE_ROOT/include -I$ROOTSYS/include");
  gROOT->LoadMacro("./AliCFMuonResTask1.cxx+");
}


text:
Welcome

Info

Hi guys. The Statistics in this site are taken from offical premier league website. Datas in this site are related to our league in FPL. Data is parsed from the offical site everytime you make a request. So there may be errors when their server is busy, also the site may be slow since we are taking data from their webiste every time. If you find any bugs or want to request any features etc.. please comment under my post in our group or email me at bivinvinod@gmail.com. The site is written in php(CI 3.0). If you like to contribute let me know. I hope you guys like it. Cheers!!

                        Bivin


text:
function varargout = isreal(varargin)
%ISREAL   Real-valued CHEBFUN2 test.
%   ISREAL(F) returns logical true if F does not have an imaginary part and
%   false otherwise.
%
%   ~ISREAL(F) detects CHEBFUN2 object that have an imaginary part even if it is
%   all zero.

% Copyright 2016 by The University of Oxford and The Chebfun Developers.
% See http://www.chebfun.org/ for Chebfun information.

[varargout{1:nargout}] = isreal@separableApprox(varargin{:});

end


text:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="@color/extra_light_blue_background"
        android:pathData="M12,12m-10,0a10,10 0,1 1,20 0a10,10 0,1 1,-20 0"/>
</vector>


text:
             chevron_left

Contacts

            menu

Journey To Mountains

You can contact me:

By phone: {{tel}}

By email: {{email}}

    Like
    Read more


text:
import json
import logging
import os
import sys
import time
import urlparse

import boto3

here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, "vendored"))
import requests

# Lambda bootstrapper installs its logging handler which prevents setting
# our own logging config. Remove all handlers at first
root = logging.getLogger()
if root.handlers:
    for handler in root.handlers:
        root.removeHandler(handler)
logging.basicConfig(level=logging.INFO, format="%(levelname)s \"%(message)s\"")
logger = logging.getLogger()

JENKINS_USER = None
JENKINS_PASSWORD = None
SLACK_TOKEN = None

requests.packages.urllib3.disable_warnings()

def init_globals():
    global JENKINS_USER
    global JENKINS_PASSWORD
    global SLACK_TOKEN

    if "jenkinsUser" not in os.environ:
        raise Exception("jenkinsUser environment variable is not defined")
    JENKINS_USER = os.environ["jenkinsUser"]

    if "jenkinsPassword" not in os.environ:
        raise Exception("jenkinsPassword environment variable is not defined")
    JENKINS_PASSWORD = os.environ["jenkinsPassword"]

    if "slackToken" not in os.environ:
        raise Exception("slackToken environment variable is not defined")
    SLACK_TOKEN = os.environ["slackToken"]

def get_payload(body_str):
    request_body = urlparse.parse_qs(body_str)

    if "payload" not in request_body:
        raise Exception("Request must contain 'payload' field")

    payload_str = request_body["payload"][0]
    return json.loads(payload_str)

def get_approval_status(payload):
    """
    Gets data from command received from Slack
    """
    approve_action = next(a for a in payload["actions"] if a["name"] == "approve")
    if approve_action is None:
        raise Exception("Request must contain 'approve' action")
    action_data = approve_action["value"].split("|")
    return {
        "approved": action_data[0].lower() == "true",
        "buildUrl": action_data[1],
        "jenkinsUrl": action_data[2],
        "buildVersion": action_data[3]
    }

def get_jenkins_crumb(jenkins_url):
    logger.info("Getting Jenkins crumb from " + jenkins_url)
    res = requests.get(jenkins_url + "crumbIssuer/api/json",
                       auth=(JENKINS_USER, JENKINS_PASSWORD),
                       verify=False)
    crumb = res.json()["crumb"]
    logger.info("Crumb is " + crumb)
    return crumb

def get_pending_input_url(build_url, crumb):
    """
    Returns URLs for pending input submission
    :param build_url: API entry point for build
    :param crumb: Jenkins crumb
    :return: None if build is not waiting for input, API URLs for proceeding and aborting the build
    """

    logger.info("Getting build status")
    res = requests.get(build_url + "wfapi",
                       auth=(JENKINS_USER, JENKINS_PASSWORD),
                       verify=False,
                       headers={
                           "Jenkins-Crumb": crumb
                       })
    response = res.json()
    if response["status"] != "PAUSED_PENDING_INPUT":
        logger.info("Build is not waiting for input, status is " + response["status"])
        return None

    logger.info("Getting proceed URL")
    res = requests.post(build_url + "wfapi/pendingInputActions",
                        auth=(JENKINS_USER, JENKINS_PASSWORD),
                        verify=False,
                        headers={
                            "Jenkins-Crumb": crumb
                        })
    response = res.json()
    input_id = response[0]["id"]
    return (
        str.format("{}wfapi/inputSubmit?inputId={}", build_url, input_id),  # Proceed URL
        str.format("{}input/{}/abort", build_url, input_id))  # Abort URL

def approve_build(proceed_url, crumb):
    logger.info("Approving build")
    res = requests.post(proceed_url,
                        auth=(JENKINS_USER, JENKINS_PASSWORD),
                        verify=False,
                        headers={
                            "Jenkins-Crumb": crumb,
                            "Content-Type": "application/x-www-form-urlencoded"
                        },
                        data={
                            "Proceed": "proceed",
                            "json": json.dumps({
                                "parameter": []
                            })
                        })
    return res.ok

def reject_build(abort_url, crumb):
    logger.info("Rejecting build")
    res = requests.post(abort_url,
                        auth=(JENKINS_USER, JENKINS_PASSWORD),
                        verify=False,
                        headers={
                            "Jenkins-Crumb": crumb
                        },
                        data={})
    return res.ok

def post_response_to_slack(response_url, body):
    res = requests.post(response_url, json=body)
    if not res.ok:
        logger.error("Error posting response to Slack: %s", res.text)

def handler(event, context):
    try:
        init_globals()

        payload = get_payload(event["body"])

        # Check Slack token for validity
        if "token" not in payload or payload["token"] != SLACK_TOKEN:
            raise Exception("token is not valid")

        if "response_url" not in payload:
            raise Exception("response_url not found in request")

        # Initial request received. Response with HTTP 200 and
        # call ourself again
        if "recursive" not in event:
            logger.info("Initial call")
            session = boto3.session.Session()
            lambda_cli = session.client("lambda")
            lambda_cli.invoke_async(FunctionName=context.function_name,
                                    InvokeArgs=json.dumps(dict({"recursive": True}, **event)))
            return {
                "statusCode": 200
            }

        response_url = payload["response_url"]
        user_name = payload["user"]["name"]
        user_id = payload["user"]["id"]
        logger.info("Received command request from " + user_name)

        command_request = get_approval_status(payload)
        build_version = command_request["buildVersion"]
        approval_status = command_request["approved"]
        crumb = get_jenkins_crumb(command_request["jenkinsUrl"])
        pending_input_urls = get_pending_input_url(command_request["buildUrl"], crumb)
        if pending_input_urls is None:
            post_response_to_slack(
                response_url,
                {
                    "attachments": [{
                        "text": "Build %s is not waiting for input" % build_version,
                        "color": "warning",
                        "ts": int(round(time.time()))
                    }]
                })
            return {}

        if approval_status:
            approve_build(pending_input_urls[0], crumb)
        else:
            reject_build(pending_input_urls[1], crumb)

        approve_msg = str.format("Version {} deployment *{}* by <@{}|{}>",
                                 build_version,
                                 "approved" if approval_status else "declined",
                                 user_name,
                                 user_id)

        post_response_to_slack(
            response_url,
            {
                "attachments": [{
                    "text": approve_msg,
                    "color": "good" if approval_status else "danger",
                    "mrkdwn_in": ["text"],
                    "ts": int(round(time.time()))
                }]
            })
    except Exception as e:
        logger.error(e.message, exc_info=1)

    return {}


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Grace.DependencyInjection.Impl.Expressions
{
    /// <summary>
    /// Interface for creating linq expression to add instance to disposal scope
    /// </summary>
    public interface IDisposalScopeExpressionCreator
    {
        /// <summary>
        /// Create expression to add instance to disposal scope
        /// </summary>
        /// <param name="scope">scope for strategy</param>
        /// <param name="request">request</param>
        /// <param name="activationConfiguration">activation configuration</param>
        /// <param name="result">result for instantiation</param>
        /// <returns></returns>
        IActivationExpressionResult CreateExpression(IInjectionScope scope, IActivationExpressionRequest request,
            TypeActivationConfiguration activationConfiguration, IActivationExpressionResult result);
    }

    /// <summary>
    /// Creates linq expression that add instance to disposal scope
    /// </summary>
    public class DisposalScopeExpressionCreator : IDisposalScopeExpressionCreator
    {
#if NETSTANDARD2_1
        private MethodInfo _addAsyncMethod;
        private MethodInfo _addAsyncMethodWithCleanup;
#endif
        private MethodInfo _addMethod;
        private MethodInfo _addMethodWithCleanup;

        /// <summary>
        /// Create expression to add instance to disposal scope
        /// </summary>
        /// <param name="scope">scope for strategy</param>
        /// <param name="request">request</param>
        /// <param name="activationConfiguration">activation configuration</param>
        /// <param name="result">result for instantiation</param>
        /// <returns></returns>
        public IActivationExpressionResult CreateExpression(IInjectionScope scope, IActivationExpressionRequest request,
            TypeActivationConfiguration activationConfiguration, IActivationExpressionResult result)
        {
            var addMethod = AddMethod;
            var addMethodWithCleanup = AddMethodWithCleanup;
#if NETSTANDARD2_1
            if (activationConfiguration.ActivationType.GetTypeInfo()
                .ImplementedInterfaces.Contains(typeof(IAsyncDisposable)))
            {
                addMethod = AddAsyncMethod;
                addMethodWithCleanup = AddAsyncMethodWithCleanup;
            }
#endif
            var closedActionType = typeof(Action<>).MakeGenericType(activationConfiguration.ActivationType);

            object disposalDelegate = null;

            if (closedActionType == activationConfiguration.DisposalDelegate?.GetType())
            {
                disposalDelegate = activationConfiguration.DisposalDelegate;
            }

            MethodInfo closedGeneric;
            Expression[] parameterExpressions;

            var resultExpression = result.Expression;

            if (resultExpression.Type != activationConfiguration.ActivationType)
            {
                resultExpression = Expression.Convert(resultExpression, activationConfiguration.ActivationType);
            }

            if (disposalDelegate != null)
            {
                closedGeneric = addMethodWithCleanup.MakeGenericMethod(activationConfiguration.ActivationType);
                parameterExpressions = new[]
                    {resultExpression, Expression.Convert(Expression.Constant(disposalDelegate), closedActionType)};
            }
            else
            {
                closedGeneric = addMethod.MakeGenericMethod(activationConfiguration.ActivationType);
                parameterExpressions = new[] {resultExpression};
            }

            request.RequireDisposalScope();

            var disposalCall = Expression.Call(request.DisposalScopeExpression, closedGeneric, parameterExpressions);

            var disposalResult = request.Services.Compiler.CreateNewResult(request, disposalCall);

            disposalResult.AddExpressionResult(result);

            return disposalResult;
        }

        /// <summary>
        /// Method info for add method on IDisposalScope
        /// </summary>
        protected MethodInfo AddMethod => _addMethod ??
                                          (_addMethod = typeof(IDisposalScope).GetTypeInfo()
                                              .DeclaredMethods.First(m =>
                                                  m.Name == nameof(IDisposalScope.AddDisposable) &&
                                                  m.GetParameters().Length == 1));

        /// <summary>
        /// Method info for add method on IDisposalScope with cleanup delegate
        /// </summary>
        protected MethodInfo AddMethodWithCleanup => _addMethodWithCleanup ??
                                                     (_addMethodWithCleanup = typeof(IDisposalScope).GetTypeInfo()
                                                         .DeclaredMethods.First(m =>
                                                             m.Name == nameof(IDisposalScope.AddDisposable) &&
                                                             m.GetParameters().Length == 2));
#if NETSTANDARD2_1
        /// <summary>
        /// Method info for add async method on IDisposalScope
        /// </summary>
        protected MethodInfo AddAsyncMethod => _addAsyncMethod ??
                                               (_addAsyncMethod =
                                                   typeof(IDisposalScope).GetTypeInfo()
                                                       .DeclaredMethods.First(m =>
                                                           m.Name == nameof(IDisposalScope.AddAsyncDisposable) &&
                                                           m.GetParameters().Length == 1));

        /// <summary>
        /// Method info for add method on IDisposalScope with cleanup delegate
        /// </summary>
        protected MethodInfo AddAsyncMethodWithCleanup => _addAsyncMethodWithCleanup ??
                                                          (_addAsyncMethodWithCleanup =
                                                              typeof(IDisposalScope).GetTypeInfo()
                                                                  .DeclaredMethods.First(m =>
                                                                      m.Name ==
                                                                      nameof(IDisposalScope.AddAsyncDisposable) &&
                                                                      m.GetParameters().Length == 2));
#endif
    }
}


text:
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using UnityEditorInternal;
using System.Reflection;
using System.Linq;
using System.Text.RegularExpressions;

public class Puppet2D_BoneCreation : Editor {

    public static void BoneFinishCreation()
    {

        Puppet2D_Editor.BoneCreation = false;
        EditorPrefs.SetBool("Puppet2D_BoneCreation", false);

		Puppet2D_HiddenBone[] hiddenBones = GameObject.FindObjectsOfType<Puppet2D_HiddenBone>();

		SpriteRenderer[] sprites = GameObject.FindObjectsOfType<SpriteRenderer>();
		foreach (SpriteRenderer spr in sprites)
		{
			if(spr.sprite!=null && spr.sprite.name == "BoneNoJoint" && spr.transform.parent ==null)
			{
				GameObject globalCtrlNew = Puppet2D_CreateControls.CreateGlobalControl();

				spr.transform.parent = globalCtrlNew.transform;
			}

		}

		GameObject globalCtrl = Puppet2D_CreateControls.CreateGlobalControl();

		if(globalCtrl!=null)
		{
			foreach(Puppet2D_HiddenBone hiddenBone in hiddenBones)
			{
				if (hiddenBone.transform.parent.parent == null)
					hiddenBone.transform.parent.parent = globalCtrl.transform;
			}
		}

    }
    [MenuItem ("GameObject/Puppet2D/Skeleton/Create Bone Tool")]
    static void CreateBoneTool()
    {
        Puppet2D_Editor.BoneCreation = true;
        EditorPrefs.SetBool("Puppet2D_BoneCreation", true);

    }

    public static void sortOutBoneHierachy(GameObject changedBone, bool move = false)
    {

        SpriteRenderer spriteRenderer = changedBone.GetComponent<SpriteRenderer>();
        if(spriteRenderer)
            if(spriteRenderer.sprite)
                if(!spriteRenderer.sprite.name.Contains("Bone"))
                    return;

        // UNPARENT CHILDREN
        List<Transform> children = new List<Transform>();

        foreach (Transform child in changedBone.transform)
        {
            if (child.GetComponent<Puppet2D_HiddenBone>() == null)
                children.Add(child);
        }
        foreach (Transform child in children)
        {
            if (!move)
                child.transform.parent = null;
        }
        Transform changedBonesParent = null;
        Transform changedBonesParentsParent = null;
        if (changedBone.transform.parent)
        {
            changedBonesParent = changedBone.transform.parent.transform;
            Undo.RecordObject(changedBonesParent, "bone parent");

            if (changedBone.transform.parent.transform.parent)
            {
                changedBonesParentsParent = changedBone.transform.parent.transform.parent.transform;

                changedBone.transform.parent.transform.parent = null;
            }

        }
        if (!move)
            changedBone.transform.parent = null;

        List<Transform> parentsChildren = new List<Transform>();

        // ORIENT & SCALE PARENT

        if (changedBonesParent)
        {
            foreach (Transform child in changedBonesParent.transform)
            {
                if (child.GetComponent<Puppet2D_HiddenBone>() == null)
                {
                    parentsChildren.Add(child);
                }

            }
            foreach (Transform child in parentsChildren)
            {
                Undo.RecordObject(child, "parents child");
                child.transform.parent = null;
            }
            SpriteRenderer sprParent = changedBonesParent.GetComponent<SpriteRenderer>();
            if(sprParent)
                if(sprParent.sprite)
                    if(sprParent.sprite.name.Contains("Bone"))
                {
                    float dist = Vector3.Distance(changedBonesParent.position, changedBone.transform.position);
                    if (dist > 0)
                        changedBonesParent.rotation = Quaternion.LookRotation(changedBone.transform.position - changedBonesParent.position, Vector3.back) * Quaternion.AngleAxis(90, Vector3.right);
                    float length = (changedBonesParent.position - changedBone.transform.position).magnitude;

                    changedBonesParent.localScale = new Vector3(length, length, length);
                }

        }
        if (!move)
            changedBone.transform.localScale = Vector3.one;

        // REPARENT CHILDREN

        if (children.Count > 0)
        {
            foreach (Transform child in children)
            {
                SpriteRenderer spr = child.GetComponent<SpriteRenderer>();
                if (spr)
                    if (spr.sprite)
                        if (spr.sprite.name.Contains("Bone"))
                    {
                        Undo.RecordObject(child, "parents child");
                        child.transform.parent = changedBone.transform;
                    }
            }
        }
        else
        {
            Undo.RecordObject(spriteRenderer,"sprite change");
            spriteRenderer.sprite = Puppet2D_Editor.boneNoJointSprite;
        }

        if (changedBonesParent)
        {
            changedBone.transform.parent = changedBonesParent;
            if (changedBonesParentsParent)
                changedBone.transform.parent.transform.parent = changedBonesParentsParent;

            foreach (Transform child in parentsChildren)
            {
                Undo.RecordObject(child, "parents child");
                child.transform.parent = changedBonesParent;
            }
            SpriteRenderer spr = changedBonesParent.GetComponent<SpriteRenderer>();
            if (spr)
            {
                if (spr.sprite)
                {
                    if (spr.sprite.name.Contains("Bone"))
                    {
                        Undo.RecordObject(spr, "sprite change");
                        spr.sprite = Puppet2D_Editor.boneSprite;
                    }
                }
            }

        }

        // SET CORRECT SPRITE
        if (!move)
        {
            if (children.Count > 0)
                changedBone.GetComponent<SpriteRenderer>().sprite = Puppet2D_Editor.boneSprite;
            else
                changedBone.GetComponent<SpriteRenderer>().sprite = Puppet2D_Editor.boneNoJointSprite;

        }

        children.Clear();
        parentsChildren.Clear();

    }
    public static GameObject BoneCreationMode(Vector3 mousePos)
    {

        bool isSplineBone = false;
        if(Selection.activeGameObject == null)
            if(Puppet2D_Editor.currentActiveBone)
                Selection.activeGameObject = Puppet2D_Editor.currentActiveBone;
        if (Selection.activeGameObject)
        {
            if (Selection.activeGameObject.GetComponent<Puppet2D_HiddenBone>())
                Selection.activeGameObject = Selection.activeGameObject.transform.parent.gameObject;

            if(Selection.activeGameObject.GetComponent<SpriteRenderer>())
            {
                if(Selection.activeGameObject.GetComponent<SpriteRenderer>().sprite)
                {
                    if(Selection.activeGameObject.GetComponent<SpriteRenderer>().sprite.name.Contains("Bone"))
                    {
                        // MAKE SURE SELECTION IS NOT AN IK OR PARENT

                        Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType<Puppet2D_GlobalControl> ();
                        for (int i = 0; i < globalCtrlScripts.Length; i++)
                        {
                            foreach(Puppet2D_IKHandle Ik in globalCtrlScripts[i]._Ikhandles)
                            {
                                if((Ik.topJointTransform == Selection.activeGameObject.transform)||(Ik.bottomJointTransform == Selection.activeGameObject.transform)||(Ik.middleJointTransform == Selection.activeGameObject.transform))
                                {
                                    Debug.LogWarning("Cannot parent bone, as this one has an IK handle");
                                    Selection.activeGameObject = null;
                                    return null;
                                }
                            }
                            foreach(Puppet2D_SplineControl splineCtrl in globalCtrlScripts[i]._SplineControls)
                            {
                                foreach (GameObject bone in splineCtrl.bones)
                                {
                                    if (bone == Selection.activeGameObject)
                                    {
                                        isSplineBone = true;

                                    }
                                }
                            }
                        }
                    }
                    else
                        return null;
                }
                else
                    return null;
            }
            else
                return null;
        }

        GameObject newBone = new GameObject(GetUniqueBoneName("bone"));
        Undo.RegisterCreatedObjectUndo (newBone, "Created newBone");
        newBone.transform.position = mousePos;
        newBone.transform.position = new Vector3(newBone.transform.position.x, newBone.transform.position.y, 0);

        if( Selection.activeGameObject)
        {
            newBone.transform.parent = Selection.activeGameObject.transform;

            GameObject newInvisibleBone = new GameObject(GetUniqueBoneName("hiddenBone"));
            Undo.RegisterCreatedObjectUndo(newInvisibleBone, "Created new invisible Bone");

            SpriteRenderer spriteRendererInvisbile = newInvisibleBone.AddComponent<SpriteRenderer>();
            newInvisibleBone.transform.position = new Vector3(10000, 10000, 10000);
            spriteRendererInvisbile.sortingLayerName = Puppet2D_Editor._boneSortingLayer;
            spriteRendererInvisbile.sprite = Puppet2D_Editor.boneHiddenSprite;
            newInvisibleBone.transform.parent = Selection.activeGameObject.transform;
            Puppet2D_HiddenBone hiddenBoneComp = newInvisibleBone.AddComponent<Puppet2D_HiddenBone>();
            hiddenBoneComp.boneToAimAt = newBone.transform;
            hiddenBoneComp.Refresh();

        }

        SpriteRenderer spriteRenderer = newBone.AddComponent<SpriteRenderer>();
        spriteRenderer.sortingLayerName = Puppet2D_Editor._boneSortingLayer;

        if (isSplineBone)
            newBone.transform.parent = null;

        sortOutBoneHierachy(newBone);

        if (isSplineBone)
            newBone.transform.parent = Selection.activeGameObject.transform;

        Selection.activeGameObject = newBone;

        Puppet2D_Editor.currentActiveBone = newBone;

        return newBone;

    }
    public static void BoneMoveMode(Vector3 mousePos)
    {
        GameObject selectedGO = Selection.activeGameObject;

        bool isParentSplineBone = false;

        if(selectedGO)
        {
            if (selectedGO.GetComponent<Puppet2D_HiddenBone>())
            {
                selectedGO = Selection.activeGameObject.transform.parent.gameObject;
                Selection.activeGameObject = selectedGO;
            }

            if(selectedGO.GetComponent<SpriteRenderer>())
            {
                if(selectedGO.GetComponent<SpriteRenderer>().sprite)
                {
                    if(selectedGO.GetComponent<SpriteRenderer>().sprite.name.Contains("Bone"))
                    {
                        // MAKE SURE SELECTION IS NOT AN IK OR PARENT

                        Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType<Puppet2D_GlobalControl> ();
                        for (int i = 0; i < globalCtrlScripts.Length; i++)
                        {
                            foreach(Puppet2D_IKHandle Ik in globalCtrlScripts[i]._Ikhandles)
                            {
                                if((Ik.topJointTransform == selectedGO.transform)||(Ik.bottomJointTransform == selectedGO.transform)||(Ik.middleJointTransform == selectedGO.transform))
                                {
                                    Debug.LogWarning("Cannot move bone, as this one has an IK handle");
                                    return;
                                }
                            }
                            foreach (Puppet2D_SplineControl splineCtrl in globalCtrlScripts[i]._SplineControls)
                            {

                                foreach (GameObject bone in splineCtrl.bones)
                                {
                                    if (bone.transform == selectedGO.transform)
                                    {
                                        Debug.LogWarning("Cannot move Spline Bones");
                                        return;
                                    }
                                    if (selectedGO.transform.parent)
                                    {
                                        if (bone.transform == selectedGO.transform.parent)
                                        {
                                            isParentSplineBone = true;
                                        }
                                    }

                                }
                            }
                        }
                    }
                    else
                        return;
                }
                else
                    return;
            }
            else
                return;

            selectedGO.transform.position = mousePos;
            selectedGO.transform.position = new Vector3(Selection.activeGameObject.transform.position.x, Selection.activeGameObject.transform.position.y, 0);

            if(!isParentSplineBone)
                sortOutBoneHierachy(selectedGO, true);

        }

    }
    public static void BoneMoveIndividualMode(Vector3 mousePos)
    {
        GameObject selectedGO = Selection.activeGameObject;

        bool isParentSplineBone = false;

        if(selectedGO)
        {
            if (selectedGO.GetComponent<Puppet2D_HiddenBone>())
            {
                selectedGO = Selection.activeGameObject.transform.parent.gameObject;
                Selection.activeGameObject = selectedGO;
            }
            if(selectedGO.GetComponent<SpriteRenderer>())
            {
                if(selectedGO.GetComponent<SpriteRenderer>().sprite)
                {
                    if(selectedGO.GetComponent<SpriteRenderer>().sprite.name.Contains("Bone"))
                    {
                        // MAKE SURE SELECTION IS NOT AN IK OR PARENT

                        Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType<Puppet2D_GlobalControl> ();
                        for (int i = 0; i < globalCtrlScripts.Length; i++)
                        {
                            foreach(Puppet2D_IKHandle Ik in globalCtrlScripts[i]._Ikhandles)
                            {
                                if((Ik.topJointTransform == selectedGO.transform)||(Ik.bottomJointTransform == selectedGO.transform)||(Ik.middleJointTransform == selectedGO.transform))
                                {
                                    Debug.LogWarning("Cannot move bone, as this one has an IK handle");
                                    return;
                                }

                            }

                            foreach (Puppet2D_SplineControl splineCtrl in globalCtrlScripts[i]._SplineControls)
                            {

                                foreach (GameObject bone in splineCtrl.bones)
                                {
                                    if (bone.transform == selectedGO.transform)
                                    {
                                        Debug.LogWarning("Cannot move Spline Bones");
                                        return;
                                    }
                                    if (selectedGO.transform.parent)
                                    {
                                        if (bone.transform == selectedGO.transform.parent)
                                        {
                                            isParentSplineBone = true;
                                        }
                                    }

                                }
                            }

                        }
                    }
                    else
                        return;
                }
                else
                    return;
            }
            else
                return;

            List<Transform> children = new List<Transform>();
            foreach (Transform child in selectedGO.transform)
            {
                if (child.GetComponent<Puppet2D_HiddenBone>()==null)
                    children.Add(child);
            }
            foreach (Transform child in children)
                child.parent = null;

            selectedGO.transform.position = mousePos;
            selectedGO.transform.position = new Vector3(Selection.activeGameObject.transform.position.x, Selection.activeGameObject.transform.position.y, 0);

            if(!isParentSplineBone)
                sortOutBoneHierachy(selectedGO, true);

            foreach (Transform child in children)
            {
                child.parent = selectedGO.transform;
                sortOutBoneHierachy(child.gameObject, true);
            }

            children.Clear();

        }

    }
    public static void BoneDeleteMode()
    {
        GameObject selectedGO = Selection.activeGameObject;
        if(selectedGO)
        {
            if (selectedGO.GetComponent<Puppet2D_HiddenBone>())
            {
                GameObject hiddenBone = selectedGO;
                selectedGO = selectedGO.transform.parent.gameObject;
                DestroyImmediate(hiddenBone);

                Selection.activeGameObject = selectedGO;

            }
            if(selectedGO.GetComponent<SpriteRenderer>())
            {
                if(selectedGO.GetComponent<SpriteRenderer>().sprite)
                {
                    if(selectedGO.GetComponent<SpriteRenderer>().sprite.name.Contains("Bone"))
                    {
                        // MAKE SURE SELECTION IS NOT AN IK OR PARENT

                        Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType<Puppet2D_GlobalControl> ();
                        for (int i = 0; i < globalCtrlScripts.Length; i++)
                        {
                            foreach(Puppet2D_IKHandle Ik in globalCtrlScripts[i]._Ikhandles)
                            {
                                if((Ik.topJointTransform == selectedGO.transform)||(Ik.bottomJointTransform == selectedGO.transform)||(Ik.middleJointTransform == selectedGO.transform))
                                {
                                    Debug.LogWarning("Cannot move bone, as this one has an IK handle");
                                    return;
                                }
                            }
                            foreach (Puppet2D_SplineControl splineCtrl in globalCtrlScripts[i]._SplineControls)
                            {

                                foreach (GameObject bone in splineCtrl.bones)
                                {
                                    if (bone.transform == selectedGO.transform)
                                    {
                                        Debug.LogWarning("Cannot delete Spline Bones Individually");
                                        return;
                                    }

                                }
                            }
                        }
                    }
                    else
                        return;
                }
                else
                    return;
            }
            else
                return;

            if (selectedGO.transform.parent)
            {
                GameObject parentGO = selectedGO.transform.parent.gameObject;
                DestroyImmediate(selectedGO);
                sortOutBoneHierachy(parentGO);
                Selection.activeGameObject = parentGO;
                foreach (Transform child in parentGO.transform)
                {
                    if(child.GetComponent<Puppet2D_HiddenBone>() == null)
                        sortOutBoneHierachy(child.gameObject, true);
                }
            }
            else
            {
                DestroyImmediate(selectedGO);
            }

        }

    }
    public static void BoneAddMode(Vector3 mousePos)
    {
        GameObject selectedGO = Selection.activeGameObject;

        if(selectedGO)
        {
            if (selectedGO.GetComponent<Puppet2D_HiddenBone>())
            {
                selectedGO = Selection.activeGameObject.transform.parent.gameObject;
                Selection.activeGameObject = selectedGO;
            }
            if(selectedGO.GetComponent<SpriteRenderer>())
            {
                if(selectedGO.GetComponent<SpriteRenderer>().sprite)
                {
                    if(selectedGO.GetComponent<SpriteRenderer>().sprite.name.Contains("Bone"))
                    {
                        // MAKE SURE SELECTION IS NOT AN IK OR PARENT

                        Puppet2D_GlobalControl[] globalCtrlScripts = Transform.FindObjectsOfType<Puppet2D_GlobalControl> ();
                        for (int i = 0; i < globalCtrlScripts.Length; i++)
                        {
                            foreach(Puppet2D_IKHandle Ik in globalCtrlScripts[i]._Ikhandles)
                            {
                                if((Ik.topJointTransform == selectedGO.transform)||(Ik.bottomJointTransform == selectedGO.transform)||(Ik.middleJointTransform == selectedGO.transform))
                                {
                                    Debug.LogWarning("Cannot add bone, as this one has an IK handle");
                                    return;
                                }
                            }
                            foreach (Puppet2D_SplineControl splineCtrl in globalCtrlScripts[i]._SplineControls)
                            {

                                foreach (GameObject bone in splineCtrl.bones)
                                {
                                    if (bone.transform == selectedGO.transform)
                                    {
                                        Debug.LogWarning("Cannot add to Spline Bones");
                                        return;
                                    }

                                }
                            }
                        }
                    }
                    else
                        return;
                }
                else
                    return;
            }
            else
                return;

            List<Transform> children = new List<Transform>();
            foreach (Transform child in selectedGO.transform)
                children.Add(child);
            foreach (Transform child in children)
                child.parent = null;

            GameObject newBone = BoneCreationMode(mousePos);

            foreach (Transform child in children)
            {

                child.parent = newBone.transform;
                if (child.GetComponent<Puppet2D_HiddenBone>() == null)
                {
                    sortOutBoneHierachy(child.gameObject, true);
                }
                else
                    child.GetComponent<Puppet2D_HiddenBone>().Refresh();

            }
            Selection.activeGameObject = newBone;
            children.Clear();

        }

    }

    public static string GetUniqueBoneName (string name)
    {
        string nameToAdd = name;
        int nameToAddLength = nameToAdd.Length +1;
        int index =0;
        foreach(GameObject go in GameObject.FindObjectsOfType(typeof(GameObject)))
        {
            if(go.name.StartsWith(nameToAdd))
            {
                string endOfName = go.name.Substring(nameToAddLength,go.name.Length-nameToAddLength);

                int indexTest = 0;
                if(int.TryParse(endOfName,out indexTest))
                {
                    if(int.Parse(endOfName)>index)
                    {
                        index =int.Parse(endOfName);
                    }
                }

            }
        }
        index++;
        return (name+"_"+index);

    }
}


text:
Zend-Doctrine2-SkeletonApplication
=======================

Introduction
------------
This is a an updated version of the Zend 2.2 skeleton application incorporating changes
from Jason Grimes' excellent tutorial on swapping out Zend's native database layer
with the Doctrine2 ORM found here: [www.jasongrimes.org](http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/) . I've also added a 'show' action that displays a single listing
to the controller and views to bring things more in line with the type of CRUD behavior you
might expect from a more Rails-like framework.

Installation
------------

Using Composer (recommended)
----------------------------
The recommended way to get a working copy of this project is to clone the repository
and use `composer` to install dependencies:

    cd my/project/dir
    git clone https://github.com/tclowers/Zend-Doctrine2-SkeletonApplication.git
    cd Zend-Doctrine2-SkeletonApplication
    php composer.phar self-update
    php composer.phar install

(The `self-update` directive is to ensure you have an up-to-date `composer.phar`
available.)

You would then invoke `composer` to install dependencies per the previous
example.

You will need to use `composer update` to at least install the doctrine2 module listed in composer.json

Web Server Setup
----------------

### PHP CLI Server

The simplest way to get started if you are using PHP 5.4 or above is to start the internal PHP cli-server in the root directory:

    php -S 0.0.0.0:8080 -t public/ public/index.php

This will start the cli-server on port 8080, and bind it to all network
interfaces.

**Note: ** The built-in CLI server is *for development only*.

### Apache Setup

To setup apache, setup a virtual host to point to the public/ directory of the
project and you should be ready to go! It should look something like below:

    <VirtualHost *:80>
        ServerName zf2-tutorial.localhost
        DocumentRoot /path/to/zf2-tutorial/public
        SetEnv APPLICATION_ENV "development"
        <Directory /path/to/zf2-tutorial/public>
            DirectoryIndex index.php
            AllowOverride All
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>


text:
.class Landroid/support/v4/print/PrintHelper$PrintHelperImpl;
.super Ljava/lang/Object;
.source "PrintHelper.java"

# interfaces
.implements Landroid/support/v4/print/PrintHelper$PrintHelperVersionImpl;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/support/v4/print/PrintHelper;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "PrintHelperImpl"
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<RealHelper:",
        "Landroid/support/v4/print/PrintHelperKitkat;",
        ">",
        "Ljava/lang/Object;",
        "Landroid/support/v4/print/PrintHelper$PrintHelperVersionImpl;"
    }
.end annotation

# instance fields
.field private final mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TRealHelper;"
        }
    .end annotation
.end field

# direct methods
.method protected constructor <init>(Landroid/support/v4/print/PrintHelperKitkat;)V
    .locals 0
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(TRealHelper;)V"
        }
    .end annotation

    .prologue
    .line 161
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    .local p1, "helper":Landroid/support/v4/print/PrintHelperKitkat;, "TRealHelper;"
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 162
    iput-object p1, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    .line 163
    return-void
.end method

# virtual methods
.method public getColorMode()I
    .locals 1

    .prologue
    .line 182
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    iget-object v0, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v0}, Landroid/support/v4/print/PrintHelperKitkat;->getColorMode()I

    move-result v0

    return v0
.end method

.method public getOrientation()I
    .locals 1

    .prologue
    .line 192
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    iget-object v0, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v0}, Landroid/support/v4/print/PrintHelperKitkat;->getOrientation()I

    move-result v0

    return v0
.end method

.method public getScaleMode()I
    .locals 1

    .prologue
    .line 172
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    iget-object v0, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v0}, Landroid/support/v4/print/PrintHelperKitkat;->getScaleMode()I

    move-result v0

    return v0
.end method

.method public printBitmap(Ljava/lang/String;Landroid/graphics/Bitmap;Landroid/support/v4/print/PrintHelper$OnPrintFinishCallback;)V
    .locals 2
    .param p1, "jobName"    # Ljava/lang/String;
    .param p2, "bitmap"    # Landroid/graphics/Bitmap;
    .param p3, "callback"    # Landroid/support/v4/print/PrintHelper$OnPrintFinishCallback;

    .prologue
    .line 198
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    const/4 v0, 0x0

    .line 199
    .local v0, "delegateCallback":Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;
    if-eqz p3, :cond_0

    .line 200
    new-instance v0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl$1;

    .end local v0    # "delegateCallback":Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;
    invoke-direct {v0, p0, p3}, Landroid/support/v4/print/PrintHelper$PrintHelperImpl$1;-><init>(Landroid/support/v4/print/PrintHelper$PrintHelperImpl;Landroid/support/v4/print/PrintHelper$OnPrintFinishCallback;)V

    .line 207
    .restart local v0    # "delegateCallback":Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;
    :cond_0
    iget-object v1, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v1, p1, p2, v0}, Landroid/support/v4/print/PrintHelperKitkat;->printBitmap(Ljava/lang/String;Landroid/graphics/Bitmap;Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;)V

    .line 208
    return-void
.end method

.method public printBitmap(Ljava/lang/String;Landroid/net/Uri;Landroid/support/v4/print/PrintHelper$OnPrintFinishCallback;)V
    .locals 2
    .param p1, "jobName"    # Ljava/lang/String;
    .param p2, "imageFile"    # Landroid/net/Uri;
    .param p3, "callback"    # Landroid/support/v4/print/PrintHelper$OnPrintFinishCallback;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/FileNotFoundException;
        }
    .end annotation

    .prologue
    .line 213
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    const/4 v0, 0x0

    .line 214
    .local v0, "delegateCallback":Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;
    if-eqz p3, :cond_0

    .line 215
    new-instance v0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl$2;

    .end local v0    # "delegateCallback":Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;
    invoke-direct {v0, p0, p3}, Landroid/support/v4/print/PrintHelper$PrintHelperImpl$2;-><init>(Landroid/support/v4/print/PrintHelper$PrintHelperImpl;Landroid/support/v4/print/PrintHelper$OnPrintFinishCallback;)V

    .line 222
    .restart local v0    # "delegateCallback":Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;
    :cond_0
    iget-object v1, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v1, p1, p2, v0}, Landroid/support/v4/print/PrintHelperKitkat;->printBitmap(Ljava/lang/String;Landroid/net/Uri;Landroid/support/v4/print/PrintHelperKitkat$OnPrintFinishCallback;)V

    .line 223
    return-void
.end method

.method public setColorMode(I)V
    .locals 1
    .param p1, "colorMode"    # I

    .prologue
    .line 177
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    iget-object v0, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v0, p1}, Landroid/support/v4/print/PrintHelperKitkat;->setColorMode(I)V

    .line 178
    return-void
.end method

.method public setOrientation(I)V
    .locals 1
    .param p1, "orientation"    # I

    .prologue
    .line 187
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    iget-object v0, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v0, p1}, Landroid/support/v4/print/PrintHelperKitkat;->setOrientation(I)V

    .line 188
    return-void
.end method

.method public setScaleMode(I)V
    .locals 1
    .param p1, "scaleMode"    # I

    .prologue
    .line 167
    .local p0, "this":Landroid/support/v4/print/PrintHelper$PrintHelperImpl;, "Landroid/support/v4/print/PrintHelper$PrintHelperImpl<TRealHelper;>;"
    iget-object v0, p0, Landroid/support/v4/print/PrintHelper$PrintHelperImpl;->mPrintHelper:Landroid/support/v4/print/PrintHelperKitkat;

    invoke-virtual {v0, p1}, Landroid/support/v4/print/PrintHelperKitkat;->setScaleMode(I)V

    .line 168
    return-void
.end method


text:
'use strict';

angular.module('advisorLinkApp')
.controller('ForumCtrl', function ($scope, $http, socket, Auth) {
  $scope.currentQuestions = [];

  $http.get('/api/questions').success(function(currentQuestions) {
    $scope.currentQuestions = currentQuestions;
    socket.syncUpdates('question', $scope.currentQuestions);
  });

  $scope.categories = [ 'Debt Management', 'Insurance Planning', 'Retirement Savings', 'etc.' ];

  $scope.addQuestion = function() {
    if($scope.newQuestion === '') {
      return;
    }
    $http.post('/api/questions', {
      text: $scope.newQuestion,
      author: Auth.getCurrentUser()
    });
    $scope.newQuestion = '';
  };

  $scope.deleteQuestion = function(question) {
    $http.delete('/api/questions/' + question._id);
  };

  $scope.$on('$destroy', function () {
    socket.unsyncUpdates('question');
  });
});


text:
require 'spec_helper'

describe RateLimiter do
  let(:empty_app) { proc { ['200', { 'Content-Type' => 'text/html' }, ['Hello world']] } }
  let(:app) { Rack::Lint.new(rate_limiter) }

  context 'when we make multiple requests' do
    let(:rate_limiter) { RateLimiter.new(empty_app) }

    it 'should decrease the remaining rate limit' do
      get('/')
      expect(last_response.headers['X-RateLimit-Remaining']).to eq '59'
      2.times { get('/') }
      expect(last_response.headers['X-RateLimit-Remaining']).to eq '57'
      3.times { get('/') }
      expect(last_response.headers['X-RateLimit-Remaining']).to eq '54'
    end
  end

  context 'when the middleware does not have any specified options' do
    let(:rate_limiter) { RateLimiter.new(empty_app) }

    before do
      get('/')
      Timecop.freeze.to_i
    end

    after { Timecop.return }

    it 'should respond successfully' do
      expect(last_response.status).to eq 200
      expect(last_response.body).to eq 'Hello world'
    end

    it 'should contain the rate limiting headers' do
      expect(last_response.headers['X-RateLimit-Limit']).to eq '60'
      expect(last_response.headers['X-RateLimit-Remaining']).to eq '59'
      expect(last_response.headers['X-RateLimit-Reset']).to eq((Time.now.to_i + 3600).to_s)
    end
  end

  context 'when the middleware has given limit as an option' do
    let(:rate_limiter) { RateLimiter.new(empty_app, limit: 10) }

    before do
      2.times { get('/') }
      Timecop.freeze.to_i
    end

    after { Timecop.return }

    it 'should contain the rate limiting headers' do
      expect(last_response.headers['X-RateLimit-Limit']).to eq '10'
      expect(last_response.headers['X-RateLimit-Remaining']).to eq '8'
      expect(last_response.headers['X-RateLimit-Reset']).to eq((Time.now.to_i + 3600).to_s)
    end

    it 'should respond successfully 10 times in total' do
      8.times { get('/') }
      expect(last_response.status).to eq 200
    end

    context 'and the limit was reached' do
      before { 8.times { get('/') } }

      it 'should get the 429 status code' do
        get('/')
        expect(last_response.status).to eq 429
      end

      it 'should not call the "call" method' do
        expect(empty_app).not_to receive(:call)
        get('/')
      end

      context 'but after an hour' do
        before { Timecop.travel(3601) }

        it 'should reset the limit' do
          get('/')
          expect(last_response.headers['X-RateLimit-Remaining']).to eq '9'
          expect(last_response.headers['X-RateLimit-Reset']).to eq((Time.now.to_i + 3600).to_s)
        end
      end
    end
  end

  describe 'Client detection' do
    context 'when the block is given' do
      let(:rate_limiter) do
        RateLimiter.new(empty_app, limit: 10) do |env|
          Rack::Request.new(env).params['api_token']
        end
      end

      it 'should set the rate limiting headers for each of requests' do
        get('/?api_token=token')
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '9'
        2.times { get('/?api_token=token2') }
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '8'
        5.times { get('/?api_token=token3') }
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '5'
      end
    end

    context 'when the block returns nil' do
      let(:rate_limiter) do
        RateLimiter.new(empty_app, limit: 10) { nil }
      end

      it 'should set remaining limit header to nil' do
        get('/?api_token=token')
        expect(last_response.headers).not_to include('X-RateLimit-Limit')
        expect(last_response.headers).not_to include('X-RateLimit-Remaining')
        expect(last_response.headers).not_to include('X-RateLimit-Reset')
      end
    end

    context 'when the block is not given' do
      let(:rate_limiter) { RateLimiter.new(empty_app, limit: 10) }

      it 'should set a proper remaining limit for each of them' do
        get('/', {}, 'REMOTE_ADDR' => '10.0.0.1')
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '9'
        2.times { get('/', {}, 'REMOTE_ADDR' => '10.0.0.2') }
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '8'
        3.times { get('/', {}, 'REMOTE_ADDR' => '10.0.0.3') }
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '7'
      end
    end
  end

  describe 'Custom store' do
    let(:store) { Store.new }
    let(:hash) { { remaining_rate_limit: 30, reset_limit_at: Time.now.to_i + 1000 } }
    let(:rate_limiter) { RateLimiter.new(empty_app, store: store) }

    context 'when we call the store' do
      before do
        allow(store).to receive(:set)
        allow(store).to receive(:get).with('10.0.0.1').and_return(hash)
        get('/', {}, 'REMOTE_ADDR' => '10.0.0.1')
      end

      it 'should set and get proper values' do
        expect(store).to have_received(:set).with('10.0.0.1', hash).once
        expect(store).to have_received(:get).with('10.0.0.1').twice
        expect(last_response.headers['X-RateLimit-Remaining']).to eq '29'
        expect(last_response.headers['X-RateLimit-Reset']).to eq((Time.now.to_i + 1000).to_s)
      end
    end
  end
end


text:
package com.webcohesion.enunciate.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class SortedList<T> extends ArrayList<T> {
  private Comparator<T> comparator;

  public SortedList(Comparator<T> comparator) {
    this.comparator = comparator;
  }

  @Override
  public boolean add(T t) {
    int index = Collections.binarySearch(this, t, comparator);
    if (index < 0) {
      index = -index - 1;
    }
    if (index >= size()) {
      super.add(t);
    }
    else {
      super.add(index, t);
    }
    return true;
  }
}


text:
package com.slack.api.methods.request.calls;

import com.slack.api.methods.SlackApiRequest;
import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class CallsInfoRequest implements SlackApiRequest {

    /**
     * Authentication token bearing required scopes.
     */
    private String token;

    /**
     * id of the Call returned by the calls.add method.
     */
    private String id;
}


text:
@class RTToastMessage;

@interface RTToastManager : NSObject {
    CGRect _minFrame;
    CGRect _maxFrame;
    __weak UIWindow *_window;
    UIView *_backgroundView;
    UIView *_toastView;
    UIView *_messageView;
    NSMutableArray *_messages; // array of RTToastMessage instances
    NSTimer *_hidingTimer;
    NSTimeInterval _duration;
}

+ (RTToastManager *)sharedManager;

- (id)initInWindow:(UIWindow *)window;

- (void)showMessage:(RTToastMessage *)message;
- (void)showMessageWithText:(NSString *)text;
- (void)showMessageWithText:(NSString *)text duration:(NSTimeInterval)duration;

@end