text:
package com.microsoft.z3;

import com.microsoft.z3.enumerations.Z3_lbool;

/**
 * Solvers.
 **/
public class Solver extends Z3Object
{
    /**
     * A string that describes all available solver parameters.
     **/
    public String getHelp() throws Z3Exception
    {
        return Native.solverGetHelp(getContext().nCtx(), getNativeObject());
    }

    /**
     * Sets the solver parameters.
     *
     * @throws Z3Exception
     **/
    public void setParameters(Params value) throws Z3Exception
    {
        getContext().checkContextMatch(value);
        Native.solverSetParams(getContext().nCtx(), getNativeObject(),
                value.getNativeObject());
    }

    /**
     * Retrieves parameter descriptions for solver.
     *
     * @throws Z3Exception
     **/
    public ParamDescrs getParameterDescriptions() throws Z3Exception
    {
        return new ParamDescrs(getContext(), Native.solverGetParamDescrs(
                getContext().nCtx(), getNativeObject()));
    }

    /**
     * The current number of backtracking points (scopes). <seealso cref="Pop"/>
     * <seealso cref="Push"/>
     **/
    public int getNumScopes() throws Z3Exception
    {
        return Native
                .solverGetNumScopes(getContext().nCtx(), getNativeObject());
    }

    /**
     * Creates a backtracking point. <seealso cref="Pop"/>
     **/
    public void push() throws Z3Exception
    {
        Native.solverPush(getContext().nCtx(), getNativeObject());
    }

    /**
     * Backtracks one backtracking point. <remarks>.
     **/
    public void pop() throws Z3Exception
    {
        pop(1);
    }

    /**
     * Backtracks <paramref name="n"/> backtracking points. <remarks>Note that
     * an exception is thrown if <paramref name="n"/> is not smaller than
     * NumScopes</remarks> <seealso cref="Push"/>
     **/
    public void pop(int n) throws Z3Exception
    {
        Native.solverPop(getContext().nCtx(), getNativeObject(), n);
    }

    /**
     * Resets the Solver. <remarks>This removes all assertions from the
     * solver.</remarks>
     **/
    public void reset() throws Z3Exception
    {
        Native.solverReset(getContext().nCtx(), getNativeObject());
    }

    /**
     * Assert a multiple constraints into the solver.
     *
     * @throws Z3Exception
     **/
    public void add(BoolExpr... constraints) throws Z3Exception
    {
        getContext().checkContextMatch(constraints);
        for (BoolExpr a : constraints)
        {
            Native.solverAssert(getContext().nCtx(), getNativeObject(),
                    a.getNativeObject());
        }
    }

    // /
    // / Assert multiple constraints into the solver, and track them (in the
    // unsat) core
    // / using the Boolean constants in ps.
    // /
    // / <remarks>
    // / This API is an alternative to <see cref="Check"/> with assumptions for
    // extracting unsat cores.
    // / Both APIs can be used in the same solver. The unsat core will contain a
    // combination
    // / of the Boolean variables provided using <see cref="AssertAndTrack"/>
    // and the Boolean literals
    // / provided using <see cref="Check"/> with assumptions.
    // / </remarks>
    public void assertAndTrack(BoolExpr[] constraints, BoolExpr[] ps) throws Z3Exception
    {
        getContext().checkContextMatch(constraints);
        getContext().checkContextMatch(ps);
        if (constraints.length != ps.length)
            throw new Z3Exception("Argument size mismatch");

        for (int i = 0; i < constraints.length; i++)
            Native.solverAssertAndTrack(getContext().nCtx(), getNativeObject(),
                    constraints[i].getNativeObject(), ps[i].getNativeObject());
    }

    // /
    // / Assert a constraint into the solver, and track it (in the unsat) core
    // / using the Boolean constant p.
    // /
    // / <remarks>
    // / This API is an alternative to <see cref="Check"/> with assumptions for
    // extracting unsat cores.
    // / Both APIs can be used in the same solver. The unsat core will contain a
    // combination
    // / of the Boolean variables provided using <see cref="AssertAndTrack"/>
    // and the Boolean literals
    // / provided using <see cref="Check"/> with assumptions.
    // / </remarks>
    public void assertAndTrack(BoolExpr constraint, BoolExpr p) throws Z3Exception
    {
        getContext().checkContextMatch(constraint);
        getContext().checkContextMatch(p);

        Native.solverAssertAndTrack(getContext().nCtx(), getNativeObject(),
                constraint.getNativeObject(), p.getNativeObject());
    }

    /**
     * The number of assertions in the solver.
     *
     * @throws Z3Exception
     **/
    public int getNumAssertions() throws Z3Exception
    {
        ASTVector ass = new ASTVector(getContext(), Native.solverGetAssertions(
                getContext().nCtx(), getNativeObject()));
        return ass.size();
    }

    /**
     * The set of asserted formulas.
     *
     * @throws Z3Exception
     **/
    public BoolExpr[] getAssertions() throws Z3Exception
    {
        ASTVector ass = new ASTVector(getContext(), Native.solverGetAssertions(
                getContext().nCtx(), getNativeObject()));
        int n = ass.size();
        BoolExpr[] res = new BoolExpr[n];
        for (int i = 0; i < n; i++)
            res[i] = new BoolExpr(getContext(), ass.get(i).getNativeObject());
        return res;
    }

    /**
     * Checks whether the assertions in the solver are consistent or not.
     * <remarks> <seealso cref="Model"/> <seealso cref="UnsatCore"/> <seealso
     * cref="Proof"/> </remarks>
     **/
    public Status check(Expr... assumptions) throws Z3Exception
    {
        Z3_lbool r;
        if (assumptions == null)
            r = Z3_lbool.fromInt(Native.solverCheck(getContext().nCtx(),
                    getNativeObject()));
        else
            r = Z3_lbool.fromInt(Native.solverCheckAssumptions(getContext()
                    .nCtx(), getNativeObject(), (int) assumptions.length, AST
                    .arrayToNative(assumptions)));
        switch (r)
        {
        case Z3_L_TRUE:
            return Status.SATISFIABLE;
        case Z3_L_FALSE:
            return Status.UNSATISFIABLE;
        default:
            return Status.UNKNOWN;
        }
    }

    /**
     * Checks whether the assertions in the solver are consistent or not.
     * <remarks> <seealso cref="Model"/> <seealso cref="UnsatCore"/> <seealso
     * cref="Proof"/> </remarks>
     **/
    public Status check() throws Z3Exception
    {
        return check((Expr[]) null);
    }

    /**
     * The model of the last Check. <remarks> The result is
     * null if Check was not invoked before, if its
     * results was not SATISFIABLE, or if model production is not
     * enabled. </remarks>
     *
     * @throws Z3Exception
     **/
    public Model getModel() throws Z3Exception
    {
        long x = Native.solverGetModel(getContext().nCtx(), getNativeObject());
        if (x == 0)
            return null;
        else
            return new Model(getContext(), x);
    }

    /**
     * The proof of the last Check. <remarks> The result is
     * null if Check was not invoked before, if its
     * results was not UNSATISFIABLE, or if proof production is
     * disabled. </remarks>
     *
     * @throws Z3Exception
     **/
    public Expr getProof() throws Z3Exception
    {
        long x = Native.solverGetProof(getContext().nCtx(), getNativeObject());
        if (x == 0)
            return null;
        else
            return Expr.create(getContext(), x);
    }

    /**
     * The unsat core of the last Check. <remarks> The unsat core
     * is a subset of Assertions The result is empty if
     * Check was not invoked before, if its results was not
     * UNSATISFIABLE, or if core production is disabled. </remarks>
     *
     * @throws Z3Exception
     **/
    public Expr[] getUnsatCore() throws Z3Exception
    {

        ASTVector core = new ASTVector(getContext(), Native.solverGetUnsatCore(
                getContext().nCtx(), getNativeObject()));
        int n = core.size();
        Expr[] res = new Expr[n];
        for (int i = 0; i < n; i++)
            res[i] = Expr.create(getContext(), core.get(i).getNativeObject());
        return res;
    }

    /**
     * A brief justification of why the last call to Check returned
     * UNKNOWN.
     **/
    public String getReasonUnknown() throws Z3Exception
    {
        return Native.solverGetReasonUnknown(getContext().nCtx(),
                getNativeObject());
    }

    /**
     * Solver statistics.
     *
     * @throws Z3Exception
     **/
    public Statistics getStatistics() throws Z3Exception
    {
        return new Statistics(getContext(), Native.solverGetStatistics(
                getContext().nCtx(), getNativeObject()));
    }

    /**
     * A string representation of the solver.
     **/
    public String toString()
    {
        try
        {
            return Native
                    .solverToString(getContext().nCtx(), getNativeObject());
        } catch (Z3Exception e)
        {
            return "Z3Exception: " + e.getMessage();
        }
    }

    Solver(Context ctx, long obj) throws Z3Exception
    {
        super(ctx, obj);
    }

    void incRef(long o) throws Z3Exception
    {
        getContext().solver_DRQ().incAndClear(getContext(), o);
        super.incRef(o);
    }

    void decRef(long o) throws Z3Exception
    {
        getContext().solver_DRQ().add(o);
        super.decRef(o);
    }
}


text:
\set ECHO
\set QUIET 1
-- Turn off echo and keep things quiet.

-- Format the output for nice TAP.
\pset format unaligned
--\pset tuples_only true
\pset pager

-- Revert all changes on failure.
\set ON_ERROR_ROLLBACK 1
\set ON_ERROR_STOP true
\set QUIET 1

\c postgres
\set test_db_name `echo $TEST_DB_NAME`
drop database if exists :test_db_name;
create database :test_db_name;

\c :test_db_name
CREATE EXTENSION IF NOT EXISTS pgtap ;
SET log_statement TO 'none';

redpajama_set_name: RedPajamaGithub


text:
/**
 * @author theluk
 */

(function() {

	$.ComplexTypeReader = $.Merger.extend({

		init: function() {
			this._super();
			this._itemReaderType = $.ComplexTypeReader;
		},

		getItemReader: function(xml) {
			if (!xml || xml.nodeName == "#text") return null;
			var ctor = this.getItemReaderType(xml);
			if (!ctor) return; // throw "ComplexTypeReader.getItemReader : Ctor is undefined";
			return new ctor(this.getItemReaderOptions(xml));
		},
		getItemReaderOptions : function(xml) {
			return {
				context: this.context.createChild(),
				xml: xml
			};
		},
		getItemReaderType: function(xml) {
			return this._itemReaderType;
		},
		setItemReaderType: function(value) {
			this._itemReaderType = value;
		},
		onChildren: function() {

			this._super();

			var children = [];

			this.x.children().each(_.bind(function(el) {
				var reader = this.getItemReader(el);
				if (reader) {
					children.push(reader);
					reader.read();
				}
			}, this));
			if (children.length > 0) this.context.data.set("ChildrenItemReaders", children);
		},
		onBuildChildren : function() {
			var children = this.context.data.get("ChildrenItemReaders");

			if (children && children.length > 0) {
				_.each(children, _.bind(function(child) {

					child.build();
					if (!child._valid) return;
					if (this.appendInstance) this.context.addBuild(function() {
						this.appendInstance(child, this.context.ptr);
					}, this);

				}, this));
			}
			this._super();

		}

	});

})();


text:
'use strict';

const webpack = require('webpack');
let webpackConfig;

if (process.env.PROJECT_TYPE === 'typescript') {
    webpackConfig = require('./webpack.lib-ts-docs.js');
} else {
    webpackConfig = require('./webpack.lib-docs.js');
}

const compiler = webpack(webpackConfig);

compiler.run(function(error, stats) {
    if (error) {
        console.log(error);
        process.exit(1);
    }
});


text:
package scala.meta.internal
package semanticdb

import scala.{meta => m}
import scala.meta.internal.inputs._

trait SymbolOps { self: DatabaseOps =>

  implicit class XtensionGSymbolMSymbol(sym: g.Symbol) {
    def toSemantic: m.Symbol = {
      if (sym == null || sym == g.NoSymbol) return m.Symbol.None
      if (sym.isOverloaded) return m.Symbol.Multi(sym.alternatives.map(_.toSemantic))
      if (sym.isModuleClass) return sym.asClass.module.toSemantic
      if (sym.isRootPackage) return m.Symbol.Global(m.Symbol.None, m.Signature.Term("_root_"))
      if (sym.isEmptyPackage) return m.Symbol.Global(m.Symbol.None, m.Signature.Term("_empty_"))

      def isLocal(sym: g.Symbol): Boolean = {
        def definitelyGlobal = sym.hasPackageFlag
        def definitelyLocal =
          sym == g.NoSymbol ||
            sym.name.decoded.startsWith(g.nme.LOCALDUMMY_PREFIX) ||
            (sym.owner.isMethod && !sym.isParameter) ||
            ((sym.owner.isAliasType || sym.owner.isAbstractType) && !sym.isParameter)
        !definitelyGlobal && (definitelyLocal || isLocal(sym.owner))
      }
      if (isLocal(sym)) {
        val mpos = sym.pos.toMeta
        return {
          if (mpos == m.Position.None) m.Symbol.None
          else m.Symbol.Local(mpos.syntax)
        }
      }

      val owner = sym.owner.toSemantic
      val signature = {
        def name(sym: g.Symbol): String = {
          if (sym.name == g.tpnme.REFINE_CLASS_NAME) {
            // See https://github.com/scalameta/scalameta/pull/1109#discussion_r137194314
            // for a motivation why <refinement> symbols should have $anon as names.
            // This may be the wrong encoding of the symbol, but with the current
            // implementation it makes the use-site symbols of this refinement
            // decl match with the definition-site of the refinement decl.
            g.nme.ANON_CLASS_NAME.decoded
          } else {
            sym.name.decoded.stripSuffix(g.nme.LOCAL_SUFFIX_STRING)
          }
        }
        def jvmSignature(sym: g.MethodSymbol): String = {
          // NOTE: unfortunately, this simple-looking facility generates side effects that corrupt the state of the compiler
          // in particular, mixin composition stops working correctly, at least for `object Main extends App`
          // val g = c.universe.asInstanceOf[scala.tools.nsc.Global]
          // exitingDelambdafy(new genASM.JPlainBuilder(null, false).descriptor(sym))
          def encode(tpe: g.Type): String = {
            val g.TypeRef(_, sym, args) = tpe
            require(args.isEmpty || sym == g.definitions.ArrayClass)
            if (sym == g.definitions.UnitClass) "V"
            else if (sym == g.definitions.BooleanClass) "Z"
            else if (sym == g.definitions.CharClass) "C"
            else if (sym == g.definitions.ByteClass) "B"
            else if (sym == g.definitions.ShortClass) "S"
            else if (sym == g.definitions.IntClass) "I"
            else if (sym == g.definitions.FloatClass) "F"
            else if (sym == g.definitions.LongClass) "J"
            else if (sym == g.definitions.DoubleClass) "D"
            else if (sym == g.definitions.ArrayClass) "[" + encode(args.head)
            else "L" + sym.fullName.replace(".", "/") + ";"
          }
          val g.MethodType(params, ret) = sym.info.erasure
          val jvmRet = if (!sym.isConstructor) ret else g.definitions.UnitClass.toType
          "(" + params.map(param => encode(param.info)).mkString("") + ")" + encode(jvmRet)
        }

        if (sym.isMethod && !sym.asMethod.isGetter)
          m.Signature.Method(name(sym), jvmSignature(sym.asMethod))
        else if (sym.isTypeParameter) m.Signature.TypeParameter(name(sym))
        else if (sym.isValueParameter || sym.isParamAccessor) m.Signature.TermParameter(name(sym))
        else if (sym.owner.thisSym == sym) m.Signature.Self(name(sym))
        else if (sym.isType) m.Signature.Type(name(sym))
        else m.Signature.Term(name(sym))
      }
      m.Symbol.Global(owner, signature)
    }
  }
}


text:
package com.ctrip.xpipe.redis.keeper.impl;

import com.ctrip.xpipe.endpoint.DefaultEndPoint;
import com.ctrip.xpipe.redis.core.entity.RedisMeta;
import com.ctrip.xpipe.redis.core.meta.KeeperState;
import com.ctrip.xpipe.redis.core.store.ReplicationStore;
import com.ctrip.xpipe.redis.keeper.RedisClient;
import com.ctrip.xpipe.redis.keeper.RedisKeeperServer;
import com.ctrip.xpipe.redis.keeper.RedisKeeperServer.PROMOTION_STATE;
import com.ctrip.xpipe.redis.keeper.impl.RedisPromotor.SlavePromotionInfo;

import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * @author wenchao.meng
 *
 * Jun 8, 2016
 */
public class RedisKeeperServerStateActive extends AbstractRedisKeeperServerState{

	private PROMOTION_STATE promotionState = PROMOTION_STATE.NORMAL;

	public RedisKeeperServerStateActive(RedisKeeperServer redisKeeperServer) {
		super(redisKeeperServer);
	}

	public RedisKeeperServerStateActive(RedisKeeperServer redisKeeperServer, InetSocketAddress masterAddress) {
		super(redisKeeperServer, masterAddress);
	}

	@Override
	public void becomeBackup(InetSocketAddress masterAddress){

		logger.info("[becomeBackup]{}", masterAddress);
		doBecomeBackup(masterAddress);
	}

	@Override
	public void becomeActive(InetSocketAddress masterAddress) {

		setMasterAddress(masterAddress);
	}

	@Override
	protected void keeperMasterChanged() {

		reconnectMaster();
	}

	@Override
	public void setPromotionState(PROMOTION_STATE promotionState, Object info) throws IOException {

		@SuppressWarnings("unused")
		PROMOTION_STATE oldState = this.promotionState;
		this.promotionState = promotionState;

		logger.info("[setKeeperServerState]{},{}" ,promotionState, info);

		switch(promotionState){
			case NORMAL:
				break;
			case BEGIN_PROMOTE_SLAVE:
				redisKeeperServer.stopAndDisposeMaster();
				break;
			case SLAVE_PROMTED:

				InetSocketAddress newMasterAddress = null;
				if(info instanceof SlavePromotionInfo){
					SlavePromotionInfo promotionInfo = (SlavePromotionInfo) info;
					RedisMeta newMaster = masterChanged(promotionInfo.getKeeperOffset(), promotionInfo.getNewMasterEndpoint()
								, promotionInfo.getNewMasterRunid(), promotionInfo.getNewMasterReplOffset());
					newMasterAddress = new InetSocketAddress(newMaster.getIp(), newMaster.getPort());
				}else if (info instanceof InetSocketAddress){
					newMasterAddress = (InetSocketAddress) info;
				}else{
					throw new IllegalStateException("unknown info:" + info);
				}
				this.promotionState = PROMOTION_STATE.REPLICATION_META_EXCHANGED;
				setMasterAddress(newMasterAddress);
				break;
			case REPLICATION_META_EXCHANGED:
				throw new IllegalStateException("state should no be changed outside:" + promotionState);
			default:
				throw new IllegalStateException("unkonow state:" + promotionState);
		}
	}

	@SuppressWarnings("deprecation")
	public RedisMeta masterChanged(long keeperOffset, DefaultEndPoint newMasterEndpoint, String newMasterRunid, long newMasterReplOffset) throws IOException {

		ReplicationStore replicationStore = redisKeeperServer.getReplicationStore();
		replicationStore.getMetaStore().masterChanged(keeperOffset, newMasterEndpoint, newMasterRunid, newMasterReplOffset);

		RedisMeta redisMeta = new RedisMeta();
		redisMeta.setIp(newMasterEndpoint.getHost());
		redisMeta.setPort(newMasterEndpoint.getPort());

		return redisMeta;
	}

	@Override
	public boolean psync(RedisClient redisClient, String []args) {
		return true;
	}

	@Override
	protected void reconnectMaster() {

		if(promotionState == PROMOTION_STATE.NORMAL || promotionState == PROMOTION_STATE.REPLICATION_META_EXCHANGED){
			super.reconnectMaster();
		}else{
			logger.warn("[reconnectMaster][can  not reconnect][promotioning...]{}, {}", promotionState, this.redisKeeperServer);
		}
	}

	@Override
	public void initPromotionState() {
		this.promotionState = PROMOTION_STATE.NORMAL;
	}

	@Override
	public KeeperState keeperState() {
		return KeeperState.ACTIVE;
	}

	@Override
	public boolean handleSlaveOf() {
		return true;
	}
}


text:
//
//  ButtonAnimations.m
//  ButtonAnimation
//
//  Created by Baojia on 14/11/19.
//  Copyright (c) 2014年 Baojia. All rights reserved.
//

#import "ButtonAnimations.h"

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

    }
    return self;
}
- (void)setNeedsDisplay:(NSArray *)priceArr
{
    [super setNeedsDisplay];
    [self createAnimation:priceArr];
    NSLog(@"%@", priceArr);
}

- (void)createBtToCar
{
    UIFont *font = [UIFont systemFontOfSize:10];

    UIButton *toCar = [UIButton buttonWithType:UIButtonTypeCustom];
    [toCar setFrame:CGRectMake(55, 3, 48, 48)];
    [toCar setTag:1];
    [toCar.layer setMasksToBounds:YES];
    [toCar.layer setBorderWidth:0];
    [toCar.layer setCornerRadius:24];
    [toCar setBackgroundImage:[UIImage imageNamed:@"image_ziqu_2.png"] forState:UIControlStateNormal];
    [toCar setTintColor:[UIColor blueColor]];

    [toCar addTarget:self action:@selector(toCarAction:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:toCar];

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(60, toCar.frame.size.height +toCar.frame.origin.y, 48, 25)];
    [label setFont:font];
    label.tag = 11;
    [label setTextColor:[UIColor blackColor]];
    [label setText:@"Label1"];
    [self addSubview:label];

    UIButton *Cowner_toCar = [UIButton buttonWithType:UIButtonTypeSystem];
    [Cowner_toCar.titleLabel setFont:font];
    [Cowner_toCar setFrame:CGRectMake(215, 3, 48, 48)];
    [Cowner_toCar setTag:100];
    Cowner_toCar.alpha = 1;
    [Cowner_toCar setBackgroundImage:[UIImage imageNamed:@"image_songche_1.png"] forState:UIControlStateNormal];
    //    [Cowner_toCar setTintColor:[UIColor blackColor]];
    [Cowner_toCar.layer setMasksToBounds:YES];
    [Cowner_toCar addTarget:self action:@selector(Cowner_toCarAction:) forControlEvents:UIControlEventTouchUpInside];
    [Cowner_toCar.layer setBorderWidth:0];
    [Cowner_toCar.layer setCornerRadius:24];
    [self addSubview:Cowner_toCar];
    UILabel *labelCowner = [[UILabel alloc] initWithFrame:CGRectMake(220, Cowner_toCar.frame.size.height +Cowner_toCar.frame.origin.y, 48, 25)];
    [labelCowner setFont:font];
    labelCowner.tag = 12;
    [labelCowner setTextColor:[UIColor blackColor]];
    [labelCowner setText:@"Label2"];
    [self addSubview:labelCowner];

}

//label1点击事件
- (void)toCarAction:(id)sender
{

    self.sendPrice = @"0";
    self.sendType = @"0";

    if (self.SendCarPriceBlock) {
        self.SendCarPriceBlock(self.sendType,self.sendPrice);
    }

    //点击label1 的同时 收起label2 的动画
    if (self.expanded == YES) {

        for (int i = 0; i < 3; i++) {
            UIButton *button = [self.arrbt objectAtIndex:i];

            [UIView animateWithDuration:0.2
                             animations:^{
                                 if (i != 3) {
                                     button.alpha = 0;
                                 }

                                 switch (i) {
                                     case 0:
                                         button.frame = CGRectMake(220, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     case 1:
                                         button.frame = CGRectMake(220, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     case 2:
                                         button.frame = CGRectMake(220,3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     default:
                                         break;
                                 }
                                 UIButton *toCar = (UIButton *)sender;
                                 [toCar setBackgroundImage:[UIImage imageNamed:@"image_ziqu_2.png"] forState:UIControlStateNormal];
                                 [toCar setFrame:CGRectMake(55, 3, 48, 48)];
                                 UIButton *cowner_car = (UIButton *)[self viewWithTag:100];
                                 cowner_car.alpha = 1;

                                 //                                 UIButton *toCar = (UIButton *)[self viewWithTag:1];
                                 //                                 [toCar setFrame:CGRectMake(55, 3, 48, 48)];

                                 UILabel *label = (UILabel *)[self viewWithTag:11];
                                 [label setFrame:CGRectMake(60, toCar.frame.size.height +toCar.frame.origin.y, 48, 25)];
                                 UILabel *labelCowner = (UILabel *)[self viewWithTag:12];
                                 //                                 labelCowner.alpha = 1;
                                 [labelCowner  setFrame:CGRectMake(220, toCar.frame.size.height +toCar.frame.origin.y, 48, 25)];

                                 //                                 UIButton *touchBt = (UIButton *)sender;
                                 //                                 touchBt.alpha = 1;
                                 //                                 [touchBt setBackgroundImage:[UIImage imageNamed:@"songche_3.png"] forState:UIControlStateNormal];

                             }];
            _expanded = NO;
        }

    }else{
        UIButton *toCar = (UIButton *)sender;
        [toCar setBackgroundImage:[UIImage imageNamed:@"image_ziqu_2.png"] forState:UIControlStateNormal];

        UIButton *cowner_car = (UIButton *)[self viewWithTag:100];
        cowner_car.alpha = 1;
        for (int i = 0; i < 3; i++) {
            UIButton *button = [self.arrbt objectAtIndex:i];
            button.alpha = 0;
        }
    }

}

- (void)createAnimation:(NSArray *)pricesArr
{
    UIFont *font = [UIFont systemFontOfSize:12];

    UIButton *twYuan = [UIButton buttonWithType:UIButtonTypeSystem];
    [twYuan.titleLabel setFont:font];
    [twYuan setFrame:CGRectMake(220, 3, 48, 48)];
    [twYuan setTag:97];
    [twYuan addTarget:self action:@selector(Cowner_toCarAction:) forControlEvents:UIControlEventTouchUpInside];
    twYuan.alpha = 0;
    NSString *twTitle = [pricesArr objectAtIndex:0];
    [twYuan setTitle:twTitle forState:UIControlStateNormal];
    [twYuan setTitleEdgeInsets:UIEdgeInsetsMake(-3, 0, 0, 0)];
    [twYuan setBackgroundImage:[UIImage imageNamed:@"songche_4.png"] forState:UIControlStateNormal];
    [self addSubview:twYuan];
    [twYuan setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    UIButton *fifYuan = [UIButton buttonWithType:UIButtonTypeSystem];
    NSString *fifTitle = [pricesArr objectAtIndex:1];
    [fifYuan setTitle:fifTitle forState:UIControlStateNormal];
    [fifYuan setTag:98];
    [fifYuan setFrame:CGRectMake(220, 3, 48, 48)];
    fifYuan.alpha = 0;
    [fifYuan setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [fifYuan addTarget:self action:@selector(Cowner_toCarAction:) forControlEvents:UIControlEventTouchUpInside];
    [fifYuan setBackgroundImage:[UIImage imageNamed:@"songche_4.png"] forState:UIControlStateNormal];
//    [fifYuan.titleLabel setFont:font];
    [self addSubview:fifYuan];

    UIButton *yibaiYuan = [UIButton buttonWithType:UIButtonTypeSystem];
    [yibaiYuan setTitle:[pricesArr objectAtIndex:2] forState:UIControlStateNormal];
    [yibaiYuan setTag:99];
    [yibaiYuan setFrame:CGRectMake(220, 3, 48, 48)];
    yibaiYuan.alpha = 0;
    [yibaiYuan setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [yibaiYuan addTarget:self action:@selector(Cowner_toCarAction:) forControlEvents:UIControlEventTouchUpInside];
    [yibaiYuan setBackgroundImage:[UIImage imageNamed:@"songche_4.png"] forState:UIControlStateNormal];
//    [yibaiYuan.titleLabel setFont:font];
    [self addSubview:yibaiYuan];

    self.arrbt = [NSArray arrayWithObjects:twYuan, fifYuan, yibaiYuan, nil];

}

//label2点击事件
- (void)Cowner_toCarAction:(UIButton *)sender
{
    UIButton *toCar = (UIButton *)[self viewWithTag:1];
    [toCar setBackgroundImage:[UIImage imageNamed:@"image_ziqu_1.png"] forState:UIControlStateNormal];

    //展开动画
    if (!self.expanded) {
        for (int i = 0; i < 3; i++) {

            UIButton *button = [self.arrbt objectAtIndex:i];
            if (button != (UIButton *)sender) {
                [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                [button setBackgroundImage:[UIImage imageNamed:@"songche_4.png"] forState:UIControlStateNormal];
            }

            [UIView animateWithDuration:0.2
                             animations:^{
                                 if (i != 3) {
                                     button.alpha = 1;
                                 }

                                 switch (i) {
                                     case 0:
                                         button.frame = CGRectMake(i * 48+100, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     case 1:
                                         button.frame = CGRectMake(i * 48 + 25 + 100, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     case 2:
                                         button.frame = CGRectMake(i * 48 + 50 + 100, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     default:
                                         break;
                                 }
                                 UIButton *cowner_car = (UIButton *)[self viewWithTag:100];
                                 cowner_car.alpha = 0;
                                 UIButton *toCar = (UIButton *)[self viewWithTag:1];
                                 [toCar setFrame:CGRectMake(30, 3, 48, 48)];

                                 UILabel *label = (UILabel *)[self viewWithTag:11];
                                 [label setFrame:CGRectMake(34, toCar.frame.size.height +toCar.frame.origin.y, 48, 25)];

                                 UILabel *labelCowner = (UILabel *)[self viewWithTag:12];
                                 //                         labelCowner.alpha = 0;
                                 labelCowner.frame = CGRectMake(2 * 48 + 50 + 103, toCar.frame.size.height +toCar.frame.origin.y, 48, 25);

                             } completion:^(BOOL finished) {

                             }];
            _expanded = YES;
        }
    }else {
        //收起动画
        for (int i = 0; i < 3; i++) {
            UIButton *button = [self.arrbt objectAtIndex:i];

            [UIView animateWithDuration:0.2
                             animations:^{
                                 if (i != 3) {
                                     button.alpha = 0;
                                 }

                                 switch (i) {
                                     case 0:
                                         button.frame = CGRectMake(215, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     case 1:
                                         button.frame = CGRectMake(215, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     case 2:
                                         button.frame = CGRectMake(215, 3, 48, 48);
                                         NSLog(@"%f", button.frame.origin.x);
                                         break;
                                     default:
                                         break;
                                 }

                                 UIButton *toCar = (UIButton *)[self viewWithTag:1];
                                 [toCar setFrame:CGRectMake(55, 3, 48, 48)];

                                 UILabel *label = (UILabel *)[self viewWithTag:11];
                                 [label setFrame:CGRectMake(60, toCar.frame.size.height +toCar.frame.origin.y, 48, 25)];

                                 UIButton *touchBt = (UIButton *)sender;
                                 touchBt.alpha = 1;
                                 [touchBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                                 [touchBt setBackgroundImage:[UIImage imageNamed:@"songche_3.png"] forState:UIControlStateNormal];

                                 UILabel *labelCowner = (UILabel *)[self viewWithTag:12];

                                 [labelCowner  setFrame:CGRectMake(220, toCar.frame.size.height +toCar.frame.origin.y, 48, 25)];
                             }];
            _expanded = NO;
        }
        UIButton *touchBt = (UIButton *)sender;
        self.sendType = @"1";
        self.sendPrice = [NSString stringWithFormat:@"%@", touchBt.titleLabel.text];
        NSLog(@"%@", touchBt.titleLabel.text);

        if (self.SendCarPriceBlock) {

            self.SendCarPriceBlock(self.sendType,self.sendPrice);
        }

    }

}

//Block回调
- (void)sendCar:(void (^)(NSString *sendType, NSString *sendPrice))block
{
    self.SendCarPriceBlock = block;
}

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

@end

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com


text:
package com.fmtech.ffmpeg;

import java.io.File;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;

/**
 * @author Chiang.CMBA
 * @date Created on: 2017-3-4 下午3:18:56
 * @version v1.0
 * @Description: TODO(What's the class used for?)
 */

public class MainActivity0 extends Activity{

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);

	}

	public void mDecode(View btn){
		String input = new File(Environment.getExternalStorageDirectory(),"input.mp4").getAbsolutePath();
		String output = new File(Environment.getExternalStorageDirectory(),"CHIANG" + File.separator + "output_1280x720_yuv420p.yuv").getAbsolutePath();
		VideoUtils.decode(input, output);
	}

}


text:
using System.Net.Http;
using System.Threading;
using Climax.Web.Http.Cors;
using NUnit.Framework;
using Should;

namespace Climax.Web.Http.Tests.Cors
{
    [TestFixture]
    class ConfigurableCorsPolicyAttributeTests
    {
        [Test]
        public void Ctor_CanSetAllAllowSettings_ToStar()
        {
            var elements = new CorsElementCollection();
            var fooElement = new CorsElement
            {
                Name = "foo",
                Headers = "*",
                Methods = "*",
                Origins = "*"
            };
            elements.Add(fooElement);

            var corsSection = new CorsSection
            {
                CorsPolicies = elements
            };

            var attr = new ConfigurableCorsPolicyAttribute("foo", corsSection);

            var policy = attr.GetCorsPolicyAsync(new HttpRequestMessage(), default(CancellationToken)).Result;
            policy.AllowAnyMethod.ShouldEqual(true);
            policy.AllowAnyHeader.ShouldEqual(true);
            policy.AllowAnyOrigin.ShouldEqual(true);
        }

        [Test]
        public void Ctor_CanSetAllAllowSettings_ToRequiredValues()
        {
            var elements = new CorsElementCollection();
            var fooElement = new CorsElement
            {
                Name = "foo",
                Headers = "X-Api-Rate;Foo",
                Methods = "GET;POST;PUT",
                Origins = "http://foo.com;http://www.abc.com"
            };
            elements.Add(fooElement);

            var corsSection = new CorsSection
            {
                CorsPolicies = elements
            };

            var attr = new ConfigurableCorsPolicyAttribute("foo", corsSection);
            var policy = attr.GetCorsPolicyAsync(new HttpRequestMessage(), default(CancellationToken)).Result;

            policy.AllowAnyMethod.ShouldEqual(false);
            policy.Methods.ShouldContain("GET");
            policy.Methods.ShouldContain("POST");
            policy.Methods.ShouldContain("PUT");

            policy.AllowAnyHeader.ShouldEqual(false);
            policy.Headers.ShouldContain("X-Api-Rate");
            policy.Headers.ShouldContain("Foo");

            policy.AllowAnyOrigin.ShouldEqual(false);
            policy.Origins.ShouldContain("http://foo.com");
            policy.Origins.ShouldContain("http://www.abc.com");
        }
    }
}


text:
CREATE TABLE users (
  id SERIAL,
  username VARCHAR(25) NOT NULL,
  enabled BOOLEAN DEFAULT TRUE,
  last_login TIMESTAMP NOT NULL,
  PRIMARY KEY (id)
);


text:
- 问题,我有一个plist文件,表示56个民族的,但是里面保存的字典,我想转换成一个数组
- 好的,那么就先遍历这个plist,然后将结果保存到一个数组中,这里出现的一个问题就是C语言字符串转换成NSString的问题,一开始使用`- (nullable id)initWithCString:(const char *)bytes`,一直出问题,转换后有问题。
- 然后我就换了一个方法`- (nullable id)initWithCString:(const char *)bytes length:(NSUInteger)length ` 这个方法转换后没有问题了。
- 第一个plist是按照26个英文字母为key的字典。
- 结果,按照数组保存。

```objc
    // 读取56个民族
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"nation.plist" ofType:nil];
    NSDictionary *dict2 = [NSDictionary dictionaryWithContentsOfFile:filePath];

    // 拼接路径
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask,YES);
    NSString *plistPath1 = [paths objectAtIndex:0];
    NSString *filename = [plistPath1 stringByAppendingPathComponent:@"nation2.plist"];

    NSMutableArray *mutab = [NSMutableArray array];

    for (int i = 0 ; i < 26; i ++) {
        char x = 65 + i;
        NSString *str=  [[NSString alloc] initWithCString:&x length:1];
        NSArray *arr = dict2[str];
        for (NSInteger j = 0; j < arr.count; j ++) {
            [mutab addObject:arr[j]];
        }
    }
    // 保存成数组
    [mutab writeToFile:filename atomically:NO];
    NSLog(@"%@",mutab);
```


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycopath. Mycol. appl. 25: 162 (1965)

#### Original name
Arbuscula eugeniae Bat. & Peres, 1965

### Remarks
null


text:
#ifndef QTMWIDGTES__ABSTRACTLISTVIEW_HPP__INCLUDED
#define QTMWIDGTES__ABSTRACTLISTVIEW_HPP__INCLUDED

// QtMWidgets include.
#include "abstractscrollarea.hpp"
#include "private/abstractscrollarea_p.hpp"
#include "listmodel.hpp"
#include "fingergeometry.hpp"

// Qt include.
#include <QWidget>
#include <QMouseEvent>
#include <QTimer>
#include <QElapsedTimer>
#include <QPainter>

namespace QtMWidgets {

class AbstractListViewBase;

//
// AbstractListViewBasePrivate
//

class AbstractListViewBasePrivate
	:	public AbstractScrollAreaPrivate
{
public:
	AbstractListViewBasePrivate( AbstractListViewBase * parent );
	virtual ~AbstractListViewBasePrivate();

	inline AbstractListViewBase * q_func();

	inline const AbstractListViewBase * q_func() const;

	//! Spacing.
	int spacing;
}; // AbstractListViewBasePrivate

template< typename T >
class AbstractListView;

//
// AbstractListViewPrivate
//

template< typename T >
class AbstractListViewPrivate
	:	public AbstractListViewBasePrivate
{
public:
	AbstractListViewPrivate( AbstractListView< T > * parent );
	virtual ~AbstractListViewPrivate();

	int maxOffsetAndFirstVisibleRow( int * row = 0 ) const;
	int calculateScroll( int row, int expectedOffset ) const;
	bool canScrollDown( int row ) const;
	void normalizeOffset( int & row, int & offset );
	QSize calcScrolledAreaSize() const;
	bool updateIfNeeded( int firstRow, int lastRow );
	void init();

	inline AbstractListView< T > * q_func();
	inline const AbstractListView< T > * q_func() const;

	//! Model.
	ListModel< T > * model;
	//! First visible row.
	int firstVisibleRow;
	//! Offset in drawing.
	int offset;
	//! Mouse move delta.
	int mouseMoveDelta;
	//! Click count;
	int clickCount;
	//! Timer.
	QTimer * timer;
	//! Elapsed timer.
	QElapsedTimer elapsedTimer;
}; // class AbstractListViewPrivate

namespace Private {

//
// Viewport
//

template< typename T >
class Viewport
	:	public QWidget
{
public:
	Viewport( QWidget * parent )
		:	QWidget( parent )
	{
		setContentsMargins( 0, 0, 0, 0 );
	}

	void setData( AbstractListViewPrivate< T > * d )
	{
		data = d;
	}

protected:
	void paintEvent( QPaintEvent * ) override
	{
		QPainter p( this );

		drawListView( &p );
	}

private:
	void drawListView( QPainter * p )
	{
		int row = data->firstVisibleRow;
		const int spacing = data->spacing;
		const QRect r = rect();
		const int x = spacing;
		int y = data->offset + spacing;

		if( data->model && row >= 0 )
			while( y < r.y() + r.height() && row < data->model->rowCount() )
			{
				const int width = r.width() - spacing * 2;
				const int height =
					data->q_func()->rowHeightForWidth( row, width );

				const QRect rowRect( x, y, width, height );

				data->q_func()->drawRow( p, rowRect, row );

				y += height + spacing;
				++row;
			}
	}

private:
	AbstractListViewPrivate< T > * data;
}; // class Viewport

} /* namespace Private */

//
// AbstractListViewBase
//

class AbstractListViewBase
	:	public AbstractScrollArea
{
	Q_OBJECT

	/*!
		\property spacing

		This property holds the space around the items in the layout.

		This property is the size of the empty space that is padded around
		an item in the layout.

		Setting this property when the view is visible will cause the
		items to be laid out again.

		By default, this property contains a value of 0.
	*/
	Q_PROPERTY( int spacing READ spacing WRITE setSpacing )

signals:
	//! This signal emits when user touched the row.
	void rowTouched( int row );
	//! This signal emits when user long touched the row.
	void rowLongTouched( int row );
	//! This signal emits when user double touched the row.
	void rowDoubleTouched( int row );

public:
	//! Scroll hints.
	enum ScrollHint {
		//! Scroll to ensure that the item is visible.
		EnsureVisible = 0,
		//! Scroll to position the item at the top of the viewport.
		PositionAtTop = 1,
		//! Scroll to position the item at the bottom of the viewport.
		PositionAtBottom = 2,
		//! Scroll to position the item at the center of the viewport.
		PositionAtCenter = 3
	}; // enum ScrollHint

	Q_ENUM( ScrollHint )

public:
	virtual ~AbstractListViewBase();

	//! \return Spacing.
	int spacing() const;
	//! Set spacing.
	void setSpacing( int s );

protected:
	AbstractListViewBase( AbstractListViewBasePrivate * dd,
		QWidget * parent = 0 );

	virtual void recalculateSize() = 0;

protected slots:
	virtual void dataChanged( int first, int last ) = 0;
	virtual void modelReset() = 0;
	virtual void rowsInserted( int first, int last ) = 0;
	virtual void rowsRemoved( int first, int last ) = 0;
	virtual void rowsMoved( int sourceStart,
		int sourceEnd, int destinationRow ) = 0;
	virtual void timerElapsed() = 0;

private:
	friend class AbstractListViewBasePrivate;

	inline AbstractListViewBasePrivate * d_func()
		{ return reinterpret_cast< AbstractListViewBasePrivate* >
			( d.data() ); }
	inline const AbstractListViewBasePrivate * d_func() const
		{ return reinterpret_cast< const AbstractListViewBasePrivate* >
			( d.data() ); }

	Q_DISABLE_COPY( AbstractListViewBase )
}; // class AbstractListViewBase

//
// AbstractListView
//

template< typename T >
class AbstractListView
	:	public AbstractListViewBase
{
public:
	AbstractListView( QWidget * parent = 0 )
		:	AbstractListViewBase(
				new AbstractListViewPrivate< T > ( this ), parent )
	{
		AbstractListViewPrivate< T > * d = d_func();

		d->init();
	}

	virtual ~AbstractListView()
	{
	}

	//! \return Model.
	ListModel< T > * model() const
	{
		const AbstractListViewPrivate< T > * d = d_func();

		return d->model;
	}

	//! Set model.
	void setModel( ListModel< T > * m )
	{
		AbstractListViewPrivate< T > * d = d_func();

		if( d->model )
			disconnect( d->model, 0, this, 0 );

		d->model = m;

		connect( d->model, &ListModel< T >::dataChanged,
			this, &AbstractListView< T >::dataChanged );
		connect( d->model, &ListModel< T >::modelReset,
			this, &AbstractListView< T >::modelReset );
		connect( d->model, &ListModel< T >::rowsInserted,
			this, &AbstractListView< T >::rowsInserted );
		connect( d->model, &ListModel< T >::rowsRemoved,
			this, &AbstractListView< T >::rowsRemoved );
		connect( d->model, &ListModel< T >::rowsMoved,
			this, &AbstractListView< T >::rowsMoved );
	}

	/*!
		\return The model row of the item at the viewport coordinates point.
	*/
	int rowAt( const QPoint & p ) const
	{
		const AbstractListViewPrivate< T > * d = d_func();

		int row = d->firstVisibleRow;
		const int spacing = d->spacing;
		const int x = spacing;
		int y = d->offset;
		const int width = d->viewport->width() - spacing * 2;

		if( p.x() < x || p.x() > x + width )
			return -1;

		bool lastIteration = false;

		if( d->model )
			while( row >= 0 && row < d->model->rowCount() )
			{
				int height = rowHeightForWidth( row, width );

				const QRect r( x, y, width, height );

				if( r.contains( p ) )
					return row;

				if( !lastIteration )
				{
					if( p.y() < y )
					{
						int prevRowHeight = -1;

						--row;

						if( row < 0 )
							return -1;

						prevRowHeight = rowHeightForWidth( row, width );

						y -= ( prevRowHeight + spacing );

						if( y < p.y() )
							lastIteration = true;
					}
					else if( p.y() > y )
					{
						++row;

						y += height + spacing;

						if( y > p.y() )
							lastIteration = true;
					}
				}
				else
					return -1;
			}

		return -1;
	}

	/*!
		Scrolls the view if necessary to ensure that the item at
		\a row row is visible. The view will try to position the item
		according to the given \a hint hint.
	*/
	void scrollTo( int row, ScrollHint hint = EnsureVisible )
	{
		AbstractListViewPrivate< T > * d = d_func();

		if( d->model && row >= 0 && row < d->model->rowCount() )
		{
			switch( hint )
			{
				case EnsureVisible :
				{
					if( !visualRect( row ).isNull() )
						return;
					else
					{
						const int offset = -1;

						const int delta = d->calculateScroll( row, offset );

						QPoint p = topLeftPointShownArea();
						p.setY( p.y() + delta );
						setTopLeftPointShownArea( p );
					}
				}
					break;

				case PositionAtTop :
				{
					const int offset = -1;

					const int delta = d->calculateScroll( row, offset );

					QPoint p = topLeftPointShownArea();
					p.setY( p.y() + delta );
					setTopLeftPointShownArea( p );
				}
					break;

				case PositionAtBottom :
				{
					const QRect r = d->viewport->rect();

					const int offset = r.y() + r.height() -
						rowHeightForWidth( row,
							r.width() - d->spacing * 2 ) - d->spacing - 1;

					const int delta = d->calculateScroll( row, offset );

					QPoint p = topLeftPointShownArea();
					p.setY( p.y() + delta );
					setTopLeftPointShownArea( p );
				}
					break;

				case PositionAtCenter :
				{
					const QRect r = d->viewport->rect();

					const int offset = r.y() + r.height() / 2 -
						rowHeightForWidth( row,
							r.width() - d->spacing * 2 ) / 2;

					const int delta = d->calculateScroll( row, offset );

					QPoint p = topLeftPointShownArea();
					p.setY( p.y() + delta );
					setTopLeftPointShownArea( p );
				}
					break;

				default :
					break;
			}
		}
	}

	/*!
		Returns the rectangle on the viewport occupied by the
		item at \a row row.

		If your item is displayed in several areas then visualRect
		returns the primary area that contains index and not the complete
		area that \a row row might encompasses, touch or cause drawing.
	*/
	QRect visualRect( int row ) const
	{
		const AbstractListViewPrivate< T > * d = d_func();

		if( row >= d->firstVisibleRow )
		{
			int tmpRow = d->firstVisibleRow;
			const QRect r = d->viewport->rect();
			const int spacing = d->spacing;
			const int x = r.x() + spacing;
			int y = r.y() + d->offset;
			const int width = r.width() - spacing * 2;
			int height = rowHeightForWidth( tmpRow, width );

			while( tmpRow < row )
			{
				y += height + spacing;

				if( y > r.height() )
					return QRect();

				++tmpRow;
				height = rowHeightForWidth( tmpRow, width );
			}

			return r.intersected( QRect( x, y, width, height ) );
		}
		else
			return QRect();
	}

protected:
	explicit AbstractListView( AbstractListViewPrivate< T > * dd,
		QWidget * parent = 0 )
		:	AbstractListViewBase( dd, parent )
	{
		AbstractListViewPrivate< T > * d = d_func();

		d->init();
	}

	//! Draw row in the list view.
	virtual void drawRow( QPainter * painter,
		const QRect & rect, int row ) = 0;

	//! \return Height of the given \a row row for the given \a width width.
	virtual int rowHeightForWidth( int row, int width ) const
	{
		Q_UNUSED( row )
		Q_UNUSED( width )

		return FingerGeometry::height();
	}

	void scrollContentsBy( int dx, int dy ) override
	{
		Q_UNUSED( dx )

		AbstractListViewPrivate< T > * d = d_func();

		d->offset += dy;

		d->normalizeOffset( d->firstVisibleRow, d->offset );
	}

	void dataChanged( int first, int last ) override
	{
		AbstractListViewPrivate< T > * d = d_func();

		recalculateSize();

		d->updateIfNeeded( first, last );
	}

	void modelReset() override
	{
		AbstractListViewPrivate< T > * d = d_func();

		d->firstVisibleRow = -1;
		d->offset = 0;

		recalculateSize();

		d->viewport->update();
	}

	void rowsInserted( int first, int last ) override
	{
		AbstractListViewPrivate< T > * d = d_func();

		if( d->firstVisibleRow == -1 )
			d->firstVisibleRow = 0;

		recalculateSize();

		d->updateIfNeeded( first, last );
	}

	void rowsRemoved( int first, int last ) override
	{
		AbstractListViewPrivate< T > * d = d_func();

		if( d->firstVisibleRow >= first && d->firstVisibleRow <= last )
		{
			if( d->model && d->model->rowCount() )
			{
				if( first - 1 >= 0 )
					d->firstVisibleRow = first - 1;
				else
					d->firstVisibleRow = last + 1;

				d->offset = 0;
			}
			else
			{
				d->firstVisibleRow = -1;
				d->offset = 0;
			}
		}

		recalculateSize();

		d->updateIfNeeded( first, last )	;
	}

	void rowsMoved( int sourceStart,
		int sourceEnd, int destinationRow ) override
	{
		AbstractListViewPrivate< T > * d = d_func();

		if( ( d->firstVisibleRow >= sourceStart
				&& d->firstVisibleRow <= sourceEnd ) ||
			( d->firstVisibleRow >= destinationRow
				&& d->firstVisibleRow <= destinationRow
						+ sourceEnd - sourceStart ) )
			d->offset = 0;

		if( !d->updateIfNeeded( sourceStart, sourceEnd ) )
			d->updateIfNeeded( destinationRow,
				destinationRow + sourceEnd - sourceStart );
	}

	void timerElapsed() override
	{
		AbstractListViewPrivate< T > * d = d_func();

		d->timer->stop();

		const int row = rowAt( d->mousePos );

		if( row >= 0 && row < d->model->rowCount() )
			emit rowLongTouched( row );
	}

	void recalculateSize() override
	{
		AbstractListViewPrivate< T > * d = d_func();

		setScrolledAreaSize( d->calcScrolledAreaSize() );
	}

protected:
	void mousePressEvent( QMouseEvent * e ) override
	{
		AbstractListViewBase::mousePressEvent( e );

		AbstractListViewPrivate< T > * d = d_func();

		if( e->button() == Qt::LeftButton )
		{
			if( d->elapsedTimer.elapsed() > 500 )
				d->clickCount = 0;

			d->mouseMoveDelta = 0;
			d->timer->start( 2000 );
			d->elapsedTimer.start();
		}
	}

	void mouseMoveEvent( QMouseEvent * e ) override
	{
		AbstractListViewPrivate< T > * d = d_func();

		d->mouseMoveDelta += ( d->mousePos - e->pos() ).manhattanLength();

		if( d->mouseMoveDelta > FingerGeometry::longTouchBounce() )
			d->timer->stop();

		AbstractListViewBase::mouseMoveEvent( e );
	}

	void mouseReleaseEvent( QMouseEvent * e ) override
	{
		AbstractListViewBase::mouseReleaseEvent( e );

		AbstractListViewPrivate< T > * d = d_func();

		d->timer->stop();

		if( e->button() == Qt::LeftButton &&
			d->mouseMoveDelta <= FingerGeometry::touchBounce() )
		{
			const int row = rowAt( e->pos() );

			if( row >= 0 && row < d->model->rowCount() )
				emit rowTouched( row );

			if( d->elapsedTimer.elapsed() <= 500 )
				++d->clickCount;
			else
				d->clickCount = 0;

			d->elapsedTimer.start();

			if( d->clickCount == 2 && row >= 0 && row < d->model->rowCount() )
				emit rowDoubleTouched( row );
		}
	}

	void resizeEvent( QResizeEvent * e ) override
	{
		AbstractListViewBase::resizeEvent( e );

		recalculateSize();

		AbstractListViewPrivate< T > * d = d_func();

		if( d->model &&
			scrolledAreaSize().height() - topLeftPointShownArea().y() <=
				d->viewport->height() )
				scrollTo( d->model->rowCount() - 1, PositionAtBottom );
	}

private:
	friend class AbstractListViewPrivate< T >;
	friend class Private::Viewport< T >;

	inline AbstractListViewPrivate< T > * d_func()
		{ return reinterpret_cast< AbstractListViewPrivate< T >* >
			( d.data() ); }
	inline const AbstractListViewPrivate< T > * d_func() const
		{ return reinterpret_cast< const AbstractListViewPrivate< T >* >
			( d.data() ); }

	Q_DISABLE_COPY( AbstractListView )
}; // class AbstractListView

//
// AbstractListViewPrivate
//

template< typename T >
inline
AbstractListViewPrivate< T >::AbstractListViewPrivate(
	AbstractListView< T > * parent )
	:	AbstractListViewBasePrivate( parent )
	,	model( 0 )
	,	firstVisibleRow( -1 )
	,	offset( 0 )
	,	mouseMoveDelta( 0 )
	,	clickCount( 0 )
	,	timer( 0 )
{
}

template< typename T >
inline
AbstractListViewPrivate< T >::~AbstractListViewPrivate()
{
}

template< typename T >
inline
int
AbstractListViewPrivate< T >::maxOffsetAndFirstVisibleRow( int * row ) const
{
	const QRect r = viewport->rect();
	const int width = r.width() - spacing * 2;
	int tmpRow = ( model ? model->rowCount() - 1 : -1 );
	int y = 0;

	const AbstractListView< T > * q = q_func();

	while( y < r.height() && tmpRow >= 0 )
	{
		y += q->rowHeightForWidth( tmpRow, width ) + spacing;
		--tmpRow;
	}

	if( row )
		*row = tmpRow + 1;

	if( y > r.height() )
		return r.height() - y - 1 - spacing;
	else
		return 0;
}

template< typename T >
inline
int
AbstractListViewPrivate< T >::calculateScroll( int row,
	int expectedOffset ) const
{
	const int width = viewport->width() - spacing * 2;

	int delta = - offset + expectedOffset;

	int tmpRow = firstVisibleRow;

	const AbstractListView< T > * q = q_func();

	if( tmpRow > row )
	{
		--tmpRow;

		while( tmpRow >= row )
		{
			delta += spacing + q->rowHeightForWidth( tmpRow, width );
			--tmpRow;
		}
	}
	else if( tmpRow < row )
	{
		while( tmpRow < row )
		{
			delta -= ( q->rowHeightForWidth( tmpRow, width ) + spacing );
			++tmpRow;
		}
	}

	return -delta;
}

template< typename T >
inline
bool
AbstractListViewPrivate< T >::canScrollDown( int row ) const
{
	if( row == -1 )
		return false;

	if( !model )
		return false;

	int tmpRow = 0;

	maxOffsetAndFirstVisibleRow( &tmpRow );

	if( row < tmpRow )
		return true;
	else
		return false;
}

template< typename T >
inline
void
AbstractListViewPrivate< T >::normalizeOffset( int & row, int & offset )
{
	AbstractListView< T > * q = q_func();

	if( offset > 0 )
	{
		if( row > 0 )
		{
			const int width = viewport->rect().width() - spacing * 2;

			while( offset > 0 )
			{
				if( row != 0 )
					--row;
				else
				{
					offset = 0;
					break;
				}

				const int delta = q->rowHeightForWidth( row,
					width ) + spacing;
				offset -= delta;
			}
		}
		else
			offset = 0;
	}
	else if( offset < 0 )
	{
		if( canScrollDown( row ) )
		{
			const int width = viewport->rect().width() - spacing * 2;
			int height = q->rowHeightForWidth( row, width );

			while( qAbs( offset ) > height + spacing )
			{
				const int delta = height + spacing;
				offset += delta;

				if( model && row < model->rowCount() - 1 )
				{
					++row;
					height = q->rowHeightForWidth( row, width );
				}
				else
				{
					offset = 0;
					break;
				}
			}
		}
		else
		{
			const int max = maxOffsetAndFirstVisibleRow();

			if( offset < max )
				offset = max;
		}
	}
}

template< typename T >
inline
QSize
AbstractListViewPrivate< T >::calcScrolledAreaSize() const
{
	const AbstractListView< T > * q = q_func();

	const int width = viewport->rect().width();
	const int rowWidth = width - spacing * 2;
	int height = spacing;

	if( model )
		for( int i = 0, last = model->rowCount(); i < last; ++i )
			height += q->rowHeightForWidth( i, rowWidth ) + spacing;

	return QSize( width, height );
}

template< typename T >
inline
bool
AbstractListViewPrivate< T >::updateIfNeeded( int firstRow, int lastRow )
{
	AbstractListView< T > * q = q_func();

	for( int i = firstRow; i <= lastRow; ++i )
	{
		if( !q->visualRect( i ).isNull() )
		{
			viewport->update();

			return true;
		}
	}

	return false;
}

template< typename T >
inline
void
AbstractListViewPrivate< T >::init()
{
	AbstractListView< T > * q = q_func();

	Private::Viewport< T > * viewport = new Private::Viewport< T >( q );
	viewport->setData( this );

	timer = new QTimer( q );

	q->setViewport( viewport );

	QObject::connect( timer, &QTimer::timeout,
		q, &AbstractListView< T >::timerElapsed );
}

template< typename T >
inline
AbstractListView< T > *
AbstractListViewPrivate< T >::q_func()
{
	return static_cast< AbstractListView< T >* >( q );
}

template< typename T >
inline
const AbstractListView< T > *
AbstractListViewPrivate< T >::q_func() const
{
	return static_cast< const AbstractListView< T >* >( q );
}

} /* namespace QtMWidgets */

#endif // QTMWIDGTES__ABSTRACTLISTVIEW_HPP__INCLUDED


text:
cd ..

vers=`grep Version: DESCRIPTION | awk '{print $2}'`

R --vanilla --quiet -e 'library(devtools); document()'

export R_RD4PDF=times,hyper
rm -f inst/tictoc_${vers}.pdf
R CMD Rd2pdf -o inst/tictoc_${vers}.pdf .


text:
layout: sermon
series: "James"
title: "Submission & Humility."
date: "2015-11-01 10:30:00"
audio: "http://media.coggesparish.com/2015-11-01 Andy McCulloch.mp3"
speaker: "Andy McCulloch"
speaker_info: "Andy joined the Cogges Staff Team as Operations Director this September"
duration: "20"
youtube_videos: [""]
vimeo_videos: [""]
slides: [""]
files: [""]
bible_passages: ["James 4: 1-12"]
bible_links: ["James 4:1-12&version=NIVUK"]
bible_videos: [""]
bible_videos_links: [""]
category: "sermon"
---


text:
<!DOCTYPE html>

    <title>refresh</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css">
    <link rel="stylesheet" href="../assets/bootstrap-table/src/bootstrap-table.css">
    <link rel="stylesheet" href="../assets/examples.css">

            View Source on GitHub

refresh

            Refresh the remote server data, you can set {silent: true} to refresh the data silently, and set {url: newUrl} to change the url. To supply query params specific to this request, set {query: {foo: 'bar'}}.

            $table.bootstrapTable('refresh');

            <button id="button" class="btn btn-default">refresh</button>

                ID
                Item Name
                Item Price


text:
'use strict';

angular.module('yapp')
    .controller('pythonInterpreterCtrl', function ($analytics, Database, $window, $location, User, $scope, $state, $sce) {
        $scope.showScore = false;
        $scope.input = ""
        var Sk = $window.Sk;

        var aceHl;

        $scope.frameURL = $sce.trustAsResourceUrl("http://pythontutor.com/iframe-embed.html#code=%23%20this%20is%20the%20debugger&cumulative=false&py=3&curInstr=0");
        //CKC - interactive code
        $scope.aceLoaded = function (_editor) {
            // Options
            _editor.setReadOnly(false);
            // CKC save and reload work
            _editor.setValue(User.savedEx($scope.exercise, $scope.question), 1);// set editor value to user's saved solution
            aceHl = _editor;

        };

        $scope.aceChanged = function (e) {
            clearAll();
        };

        function outf(text) {

            var mypre = document.getElementById("output");
            mypre.innerHTML = mypre.innerHTML + text;
        }

        function builtinRead(x) {
            if (Sk.builtinFiles === undefined || Sk.builtinFiles["files"][x] === undefined)
                throw "File not found: '" + x + "'";
            return Sk.builtinFiles["files"][x];
        }

         $scope.runit = function () {
            clearAll();
            var prog = aceHl.getValue();
            var mypre = document.getElementById("output");

            // save user work
            User.updateSaved(prog, $scope.exercise, $scope.question);

            mypre.innerHTML = '';
            Sk.pre = "output";
            Sk.configure({
                output: outf, read: builtinRead, inputfun: function (str) {
                    console.log($scope.input)
                    return $scope.input;
                },
                inputfunTakesPrompt: true
            });
            (Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
            var myPromise = Sk.misceval.asyncToPromise(function () {
                return Sk.importMainWithBody("<stdin>", false, prog, true);
            });
            myPromise.then(function (mod) {

            },
                function (err) {
                    var mypre = document.getElementById("output");
                    mypre.innerHTML = mypre.innerHTML + err.toString();
                });

        };

        // CKC visual debugger
        $scope.debugit = function () {
            // must run program to check that there are no syntax errors before debugging
            clearAll();
            var prog = aceHl.getValue();
            var mypre = document.getElementById("output");

            mypre.innerHTML = '';
            Sk.pre = "output";
            Sk.configure({
                output: outf, read: builtinRead, inputfun: function (str) {
                    console.log($scope.input);
                    return $scope.input;
                },
                inputfunTakesPrompt: true
            });
            (Sk.TurtleGraphics || (Sk.TurtleGraphics = {})).target = 'mycanvas';
            var myPromise = Sk.misceval.asyncToPromise(function () {
                return Sk.importMainWithBody("<stdin>", false, prog, true);
            });

            myPromise.then(function (mod) {
                clearAll();
                document.getElementById("debHd").style.visibility = "visible";
                var placeHere = document.getElementById("frameHere");
                var iframe = document.createElement('iframe');
                iframe.style.display = "inline";
                iframe.id = "debugger";
                iframe.width = "90%";
                iframe.height = "600px";
                var url = "https://pythontutor.com/iframe-embed.html#code=" + encodeURIComponent(aceHl.getValue()) + "&codeDivHeight=400&codeDivWidth=550&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false";
                iframe.src = url;
                placeHere.appendChild(iframe);
            },
                function (err) {
                    var mypre = document.getElementById("output");
                    mypre.innerHTML = "Cannot debug with syntax errors: \n" + mypre.innerHTML + err.toString();
                });
            console.log("debugging");
        };

       // RK automated marker
        $scope.automaticMark = function (question,exercise) {
            var finalResult = ""
            var mypre = document.getElementById("output");
            var prog = aceHl.getValue();
            mypre.innerHTML = "";

            console.log("Submit for automatic marking");
            var prog = aceHl.getValue();
            Database.assessment_ref.child(exercise).child(question).once("value", function (snapshot) {
                var tests = snapshot.val();
                var totalMark = snapshot.val().length - 1
                var mark = 0;
                mypre.innerHTML = "**MARKING QUESTION " + question + "**\n\n"
                var keys = Object.keys(tests);
                asyncLoop(keys.length, function (loop) {
                    var finalResult = "";

                    mypre.innerHTML = mypre.innerHTML + "Running test " + (loop.iteration() + 1) + ":\n";
                    var test = tests[keys[loop.iteration()]];
                    var input = test.input[0];
                    var output = test.output.toString();

                    mypre.innerHTML = mypre.innerHTML + "input: " + input + "\n"
                    mypre.innerHTML = mypre.innerHTML + "expected output:\n"
                    mypre.innerHTML = mypre.innerHTML + output + "\n"

                    Sk.configure({
                        output: function (result) {
                            finalResult += result
                        }, read: builtinRead, inputfun: function (str) {
                            return input
                        },
                        inputfunTakesPrompt: true
                    });
                    mypre.innerHTML = mypre.innerHTML + "what your program produced:\n"
                    Sk.misceval.asyncToPromise(function () {
                        return Sk.importMainWithBody("<stdin>", false, prog, true);
                    }).then(function () {
                        finalResult = finalResult.trim()

                        mypre.innerHTML = mypre.innerHTML + finalResult + "\n"

                        if (output === finalResult) {
                            mark++;
                            mypre.innerHTML = mypre.innerHTML + "Congratulations! Your program performed correctly for this test!\n";
                        }
                        else {
                            mypre.innerHTML = mypre.innerHTML + "Uh Oh! Your program didn't yield the correct result for this test!\n\nThe differences are as follows:\n";
                            var splitResult = finalResult.split('\n');
                            var splitOutput = output.split('\n');
                            if (splitResult.length > splitOutput.length) {
                                for (var i = 0; i < splitResult.length; i++) {
                                    if (i < splitOutput.length) {
                                        if (splitOutput[i] !== splitResult[i]) {
                                            mypre.innerHTML = mypre.innerHTML + "line "+ (i + 1) + ":" + splitOutput[i] + "  !=   " + splitResult[i] + "\n"
                                        }
                                    }
                                    else {
                                        mypre.innerHTML = mypre.innerHTML + "line "+(i + 1) + ": " + splitResult[i] + "\n"
                                    }
                                }
                            }
                            else {
                                for (var i = 0; i < splitOutput.length; i++) {
                                    if (i < splitResult.length) {
                                        if (splitOutput[i] !== splitResult[i]) {
                                            mypre.innerHTML = mypre.innerHTML + "line "+ (i + 1) + ": " + splitOutput[i] + "  !=   " + splitResult[i] + "\n"
                                        }
                                    }
                                    else {
                                        mypre.innerHTML = mypre.innerHTML + "line "+ (i + 1) + ": " + splitOutput[i] + "\n"
                                    }
                                }

                            }

                        }
                        mypre.innerHTML = mypre.innerHTML + "\n\n";
                        loop.next()
                    }, function (err) {
                        console.error(err);
                        var mypre = document.getElementById("output");
                        mypre.innerHTML = mypre.innerHTML + err.toString() + "\n\n";
                        loop.next()
                    })
                }, function () {
                    $analytics.eventTrack('AutomaticAssessment', { category: 'Result', label: question + " : " + ((mark / totalMark) * 100) + "%" });

                    $scope.$apply(function () {
                        $scope.showScore = true
                        $scope.mark = mark;
                        $scope.totalMarks = totalMark
                    })

                    console.log('cycle ended')

                })

            });

            // analytics: record user ID, timestamp, marking was inititated, success/failure?
        };

        function clearAll() {
            var placeHere = document.getElementById("frameHere");
            placeHere.innerHTML = ""; // clear previous debugging console
            document.getElementById("debHd").style.visibility = "hidden";
            var mypre = document.getElementById("output");
            mypre.innerHTML = "";
        }

        function asyncLoop(iterations, func, callback) {
            var index = 0;
            var done = false;
            var loop = {
                next: function () {
                    if (done) {
                        return;
                    }

                    if (index < iterations) {
                        index++;
                        func(loop);

                    } else {
                        done = true;
                        callback();
                    }
                },

                iteration: function () {
                    return index - 1;
                },

                break: function () {
                    done = true;
                    callback();
                }
            };
            loop.next();
            return loop;
        }

    });
function getDifference(a, b) {
    var i = 0;
    var j = 0;
    var result = "";

    while (j < b.length) {
        if (a[i] != b[j] || i == a.length)
            result += b[j];
        else
            i++;
        j++;
    }
    return result;
}


text:
title: 'Facebook Puzzle #4 Solution – Breathalyzer'
author: Kenny
layout: post
permalink: /2011/11/18/facebook-puzzle-4-solution-breathalyzer/
dsq_thread_id:
  - 496275093
dcssb_short_url:
  - http://su.pr/1XId1C
categories:
  - Passions
  - Programming
tags:
  - facebook
  - PHP
  - python
---
After reading this part of the [the puzzle's description][1]:

> A change is defined as replacing a single letter with another letter, adding a letter in any position, or removing a letter from any position. The total score for the wall post is the minimum number of changes necessary to make all words in the post acceptable.

I was immediately reminded of the Levenshtein algorithm I read earlier in the PHP documentation.

Ironically, I didn't come up with a solution in PHP, but Python:

          [gist id=1377213]

Here are some sample benchmarks:

$ time python breathalyzer.py "hello world"
0 0 real 0m0.235s user 0m0.170s sys 0m0.020s

The program processes all the words quite fast if they are found identically written in the list.

Here is the the levenshtein algorithm in action:

$ time python breathalyzer.py "hellofdsf worldtra"
3 3 real 0m1.121s user 0m1.110s sys 0m0.007s

Just above a second… passable.

I want it to actually do some work, so let's throw the phrase found at the puzzle's page to the program: "tihs sententcnes iss nout varrry goud"

$ time python breathalyzer.py "tihs sententcnes iss nout varrry goud"
1 2 1 1 2 1 real 0m4.092s user 0m4.013s sys 0m0.070s

4 seconds! I haven't benchmarked other solutions, so I cannot say if my implementation is one of the faster or slower ones… so leave your comments about your solution (and also some rocking benchmarks).

 [1]: https://www.facebook.com/careers/puzzles.php?puzzle_id=17


text:
.class public final Landroid/os/UserHandle;
.super Ljava/lang/Object;
.source "UserHandle.java"

# interfaces
.implements Landroid/os/Parcelable;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/os/UserHandle$1;
    }
.end annotation

# static fields
.field public static final ALL:Landroid/os/UserHandle;

.field public static final CREATOR:Landroid/os/Parcelable$Creator;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Landroid/os/Parcelable$Creator",
            "<",
            "Landroid/os/UserHandle;",
            ">;"
        }
    .end annotation
.end field

.field public static final CURRENT:Landroid/os/UserHandle;

.field public static final CURRENT_OR_SELF:Landroid/os/UserHandle;

.field public static final MU_ENABLED:Z = true

.field public static final OWNER:Landroid/os/UserHandle;
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final PER_USER_RANGE:I = 0x186a0

.field public static final SEM_ALL:Landroid/os/UserHandle;

.field public static final SEM_CURRENT:Landroid/os/UserHandle;

.field public static final SEM_OWNER:Landroid/os/UserHandle;
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final SEM_USER_CURRENT:I = -0x2

.field public static final SEM_USER_NULL:I = -0x2710

.field public static final SEM_USER_OWNER:I = 0x0
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final SYSTEM:Landroid/os/UserHandle;

.field public static final USER_ALL:I = -0x1

.field public static final USER_ALL_EXCEPT_KNOX:I = -0x4

.field public static final USER_CURRENT:I = -0x2

.field public static final USER_CURRENT_OR_SELF:I = -0x3

.field public static final USER_NULL:I = -0x2710

.field public static final USER_OWNER:I
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation
.end field

.field public static final USER_SERIAL_SYSTEM:I

.field public static final USER_SYSTEM:I

# instance fields
.field final mHandle:I

# direct methods
.method static constructor <clinit>()V
    .locals 3

    const/4 v2, 0x0

    new-instance v0, Landroid/os/UserHandle;

    const/4 v1, -0x1

    invoke-direct {v0, v1}, Landroid/os/UserHandle;-><init>(I)V

    sput-object v0, Landroid/os/UserHandle;->ALL:Landroid/os/UserHandle;

    sget-object v0, Landroid/os/UserHandle;->ALL:Landroid/os/UserHandle;

    sput-object v0, Landroid/os/UserHandle;->SEM_ALL:Landroid/os/UserHandle;

    new-instance v0, Landroid/os/UserHandle;

    const/4 v1, -0x2

    invoke-direct {v0, v1}, Landroid/os/UserHandle;-><init>(I)V

    sput-object v0, Landroid/os/UserHandle;->CURRENT:Landroid/os/UserHandle;

    sget-object v0, Landroid/os/UserHandle;->CURRENT:Landroid/os/UserHandle;

    sput-object v0, Landroid/os/UserHandle;->SEM_CURRENT:Landroid/os/UserHandle;

    new-instance v0, Landroid/os/UserHandle;

    const/4 v1, -0x3

    invoke-direct {v0, v1}, Landroid/os/UserHandle;-><init>(I)V

    sput-object v0, Landroid/os/UserHandle;->CURRENT_OR_SELF:Landroid/os/UserHandle;

    new-instance v0, Landroid/os/UserHandle;

    invoke-direct {v0, v2}, Landroid/os/UserHandle;-><init>(I)V

    sput-object v0, Landroid/os/UserHandle;->OWNER:Landroid/os/UserHandle;

    sget-object v0, Landroid/os/UserHandle;->OWNER:Landroid/os/UserHandle;

    sput-object v0, Landroid/os/UserHandle;->SEM_OWNER:Landroid/os/UserHandle;

    new-instance v0, Landroid/os/UserHandle;

    invoke-direct {v0, v2}, Landroid/os/UserHandle;-><init>(I)V

    sput-object v0, Landroid/os/UserHandle;->SYSTEM:Landroid/os/UserHandle;

    new-instance v0, Landroid/os/UserHandle$1;

    invoke-direct {v0}, Landroid/os/UserHandle$1;-><init>()V

    sput-object v0, Landroid/os/UserHandle;->CREATOR:Landroid/os/Parcelable$Creator;

    return-void
.end method

.method public constructor <init>(I)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput p1, p0, Landroid/os/UserHandle;->mHandle:I

    return-void
.end method

.method public constructor <init>(Landroid/os/Parcel;)V
    .locals 1

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v0

    iput v0, p0, Landroid/os/UserHandle;->mHandle:I

    return-void
.end method

.method public static formatUid(I)Ljava/lang/String;
    .locals 2

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    invoke-static {v0, p0}, Landroid/os/UserHandle;->formatUid(Ljava/lang/StringBuilder;I)V

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v1

    return-object v1
.end method

.method public static formatUid(Ljava/io/PrintWriter;I)V
    .locals 4

    const v3, 0x182b8

    const/16 v2, 0x2710

    if-ge p1, v2, :cond_0

    invoke-virtual {p0, p1}, Ljava/io/PrintWriter;->print(I)V

    :goto_0
    return-void

    :cond_0
    const/16 v1, 0x75

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(C)V

    invoke-static {p1}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v1

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(I)V

    invoke-static {p1}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v0

    if-lt v0, v3, :cond_1

    const v1, 0x1869f

    if-gt v0, v1, :cond_1

    const/16 v1, 0x69

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(C)V

    sub-int v1, v0, v3

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(I)V

    goto :goto_0

    :cond_1
    if-lt v0, v2, :cond_2

    const/16 v1, 0x61

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(C)V

    add-int/lit16 v1, v0, -0x2710

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(I)V

    goto :goto_0

    :cond_2
    const/16 v1, 0x73

    invoke-virtual {p0, v1}, Ljava/io/PrintWriter;->print(C)V

    invoke-virtual {p0, v0}, Ljava/io/PrintWriter;->print(I)V

    goto :goto_0
.end method

.method public static formatUid(Ljava/lang/StringBuilder;I)V
    .locals 4

    const v3, 0x182b8

    const/16 v2, 0x2710

    if-ge p1, v2, :cond_0

    invoke-virtual {p0, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    :goto_0
    return-void

    :cond_0
    const/16 v1, 0x75

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    invoke-static {p1}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v1

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    invoke-static {p1}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v0

    if-lt v0, v3, :cond_1

    const v1, 0x1869f

    if-gt v0, v1, :cond_1

    const/16 v1, 0x69

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    sub-int v1, v0, v3

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    goto :goto_0

    :cond_1
    if-lt v0, v2, :cond_2

    const/16 v1, 0x61

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    add-int/lit16 v1, v0, -0x2710

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    goto :goto_0

    :cond_2
    const/16 v1, 0x73

    invoke-virtual {p0, v1}, Ljava/lang/StringBuilder;->append(C)Ljava/lang/StringBuilder;

    invoke-virtual {p0, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    goto :goto_0
.end method

.method public static getAppId(I)I
    .locals 1

    const v0, 0x186a0

    rem-int v0, p0, v0

    return v0
.end method

.method public static getAppIdFromSharedAppGid(I)I
    .locals 3

    const v2, 0xc350

    invoke-static {p0}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v1

    add-int/lit16 v1, v1, 0x2710

    sub-int v0, v1, v2

    if-ltz v0, :cond_0

    if-lt v0, v2, :cond_1

    :cond_0
    const/4 v1, -0x1

    return v1

    :cond_1
    return v0
.end method

.method public static getCacheAppGid(I)I
    .locals 1

    const v0, 0x186a0

    rem-int v0, p0, v0

    add-int/lit16 v0, v0, 0x4e20

    add-int/lit16 v0, v0, -0x2710

    return v0
.end method

.method public static getCallingUserId()I
    .locals 1

    invoke-static {}, Landroid/os/Binder;->getCallingUid()I

    move-result v0

    invoke-static {v0}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v0

    return v0
.end method

.method public static getSharedAppGid(I)I
    .locals 2

    const v0, 0x186a0

    rem-int v0, p0, v0

    const v1, 0xc350

    add-int/2addr v0, v1

    add-int/lit16 v0, v0, -0x2710

    return v0
.end method

.method public static getUid(II)I
    .locals 2

    const v1, 0x186a0

    mul-int v0, p0, v1

    rem-int v1, p1, v1

    add-int/2addr v0, v1

    return v0
.end method

.method public static getUserGid(I)I
    .locals 1

    const/16 v0, 0x270d

    invoke-static {p0, v0}, Landroid/os/UserHandle;->getUid(II)I

    move-result v0

    return v0
.end method

.method public static getUserHandleForUid(I)Landroid/os/UserHandle;
    .locals 1

    invoke-static {p0}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v0

    invoke-static {v0}, Landroid/os/UserHandle;->of(I)Landroid/os/UserHandle;

    move-result-object v0

    return-object v0
.end method

.method public static getUserId(I)I
    .locals 1

    const v0, 0x186a0

    div-int v0, p0, v0

    return v0
.end method

.method public static isApp(I)Z
    .locals 3

    const/4 v1, 0x0

    if-lez p0, :cond_1

    invoke-static {p0}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v0

    const/16 v2, 0x2710

    if-lt v0, v2, :cond_0

    const/16 v2, 0x4e1f

    if-gt v0, v2, :cond_0

    const/4 v1, 0x1

    :cond_0
    return v1

    :cond_1
    return v1
.end method

.method public static isIsolated(I)Z
    .locals 3

    const/4 v1, 0x0

    if-lez p0, :cond_1

    invoke-static {p0}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v0

    const v2, 0x182b8

    if-lt v0, v2, :cond_0

    const v2, 0x1869f

    if-gt v0, v2, :cond_0

    const/4 v1, 0x1

    :cond_0
    return v1

    :cond_1
    return v1
.end method

.method public static isSameApp(II)Z
    .locals 2

    invoke-static {p0}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v0

    invoke-static {p1}, Landroid/os/UserHandle;->getAppId(I)I

    move-result v1

    if-ne v0, v1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public static isSameUser(II)Z
    .locals 2

    invoke-static {p0}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v0

    invoke-static {p1}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v1

    if-ne v0, v1, :cond_0

    const/4 v0, 0x1

    :goto_0
    return v0

    :cond_0
    const/4 v0, 0x0

    goto :goto_0
.end method

.method public static myUserId()I
    .locals 1

    invoke-static {}, Landroid/os/Process;->myUid()I

    move-result v0

    invoke-static {v0}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v0

    return v0
.end method

.method public static of(I)Landroid/os/UserHandle;
    .locals 1

    if-nez p0, :cond_0

    sget-object v0, Landroid/os/UserHandle;->SYSTEM:Landroid/os/UserHandle;

    :goto_0
    return-object v0

    :cond_0
    new-instance v0, Landroid/os/UserHandle;

    invoke-direct {v0, p0}, Landroid/os/UserHandle;-><init>(I)V

    goto :goto_0
.end method

.method public static parseUserArg(Ljava/lang/String;)I
    .locals 5

    const-string/jumbo v2, "all"

    invoke-virtual {v2, p0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_0

    const/4 v1, -0x1

    :goto_0
    return v1

    :cond_0
    const-string/jumbo v2, "current"

    invoke-virtual {v2, p0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-nez v2, :cond_1

    const-string/jumbo v2, "cur"

    invoke-virtual {v2, p0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z

    move-result v2

    if-eqz v2, :cond_2

    :cond_1
    const/4 v1, -0x2

    goto :goto_0

    :cond_2
    :try_start_0
    invoke-static {p0}, Ljava/lang/Integer;->parseInt(Ljava/lang/String;)I
    :try_end_0
    .catch Ljava/lang/NumberFormatException; {:try_start_0 .. :try_end_0} :catch_0

    move-result v1

    goto :goto_0

    :catch_0
    move-exception v0

    new-instance v2, Ljava/lang/IllegalArgumentException;

    new-instance v3, Ljava/lang/StringBuilder;

    invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v4, "Bad user number: "

    invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v3

    invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v3

    invoke-direct {v2, v3}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V

    throw v2
.end method

.method public static readFromParcel(Landroid/os/Parcel;)Landroid/os/UserHandle;
    .locals 2

    invoke-virtual {p0}, Landroid/os/Parcel;->readInt()I

    move-result v0

    const/16 v1, -0x2710

    if-eq v0, v1, :cond_0

    new-instance v1, Landroid/os/UserHandle;

    invoke-direct {v1, v0}, Landroid/os/UserHandle;-><init>(I)V

    :goto_0
    return-object v1

    :cond_0
    const/4 v1, 0x0

    goto :goto_0
.end method

.method public static final semGetCallingUserId()I
    .locals 1

    invoke-static {}, Landroid/os/UserHandle;->getCallingUserId()I

    move-result v0

    return v0
.end method

.method public static final semGetMyUserId()I
    .locals 1

    invoke-static {}, Landroid/os/UserHandle;->myUserId()I

    move-result v0

    return v0
.end method

.method public static final semGetUserId(I)I
    .locals 1

    invoke-static {p0}, Landroid/os/UserHandle;->getUserId(I)I

    move-result v0

    return v0
.end method

.method public static semOf(I)Landroid/os/UserHandle;
    .locals 1

    invoke-static {p0}, Landroid/os/UserHandle;->of(I)Landroid/os/UserHandle;

    move-result-object v0

    return-object v0
.end method

.method public static writeToParcel(Landroid/os/UserHandle;Landroid/os/Parcel;)V
    .locals 1

    if-eqz p0, :cond_0

    const/4 v0, 0x0

    invoke-virtual {p0, p1, v0}, Landroid/os/UserHandle;->writeToParcel(Landroid/os/Parcel;I)V

    :goto_0
    return-void

    :cond_0
    const/16 v0, -0x2710

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    goto :goto_0
.end method

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

    const/4 v0, 0x0

    return v0
.end method

.method public equals(Ljava/lang/Object;)Z
    .locals 6

    const/4 v3, 0x0

    if-eqz p1, :cond_1

    :try_start_0
    move-object v0, p1

    check-cast v0, Landroid/os/UserHandle;

    move-object v2, v0

    iget v4, p0, Landroid/os/UserHandle;->mHandle:I

    iget v5, v2, Landroid/os/UserHandle;->mHandle:I
    :try_end_0
    .catch Ljava/lang/ClassCastException; {:try_start_0 .. :try_end_0} :catch_0

    if-ne v4, v5, :cond_0

    const/4 v3, 0x1

    :cond_0
    return v3

    :catch_0
    move-exception v1

    :cond_1
    return v3
.end method

.method public getIdentifier()I
    .locals 1

    iget v0, p0, Landroid/os/UserHandle;->mHandle:I

    return v0
.end method

.method public hashCode()I
    .locals 1

    iget v0, p0, Landroid/os/UserHandle;->mHandle:I

    return v0
.end method

.method public isOwner()Z
    .locals 1
    .annotation runtime Ljava/lang/Deprecated;
    .end annotation

    sget-object v0, Landroid/os/UserHandle;->OWNER:Landroid/os/UserHandle;

    invoke-virtual {p0, v0}, Landroid/os/UserHandle;->equals(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public isSystem()Z
    .locals 1

    sget-object v0, Landroid/os/UserHandle;->SYSTEM:Landroid/os/UserHandle;

    invoke-virtual {p0, v0}, Landroid/os/UserHandle;->equals(Ljava/lang/Object;)Z

    move-result v0

    return v0
.end method

.method public semGetIdentifier()I
    .locals 1

    invoke-virtual {p0}, Landroid/os/UserHandle;->getIdentifier()I

    move-result v0

    return v0
.end method

.method public toString()Ljava/lang/String;
    .locals 2

    new-instance v0, Ljava/lang/StringBuilder;

    invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V

    const-string/jumbo v1, "UserHandle{"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    iget v1, p0, Landroid/os/UserHandle;->mHandle:I

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;

    move-result-object v0

    const-string/jumbo v1, "}"

    invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

    move-result-object v0

    invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;

    move-result-object v0

    return-object v0
.end method

.method public writeToParcel(Landroid/os/Parcel;I)V
    .locals 1

    iget v0, p0, Landroid/os/UserHandle;->mHandle:I

    invoke-virtual {p1, v0}, Landroid/os/Parcel;->writeInt(I)V

    return-void
.end method


text:
$(document).ready(function() {
    /* If mobile browser, prevent click on parent nav item from redirecting to URL */
    if(is_touch_device()) {
        //$('#mainmenu > li > a').attr('href' ,'#');
        $('#mainmenu li > ul').each(function (index, domEle) {
            /* Method 1: Use this to modify the href on the <a> to # */
            //$(domEle).prev('a').attr('href' ,'#');

            /* Method 2: Use this to keep the href on the <a> intact but prevent the default action */
            $(domEle).prev('a').click(function(event) {
                event.preventDefault();
            });
        });
    }
});

//check is this a mobile browser
function is_touch_device() {
  return !!('ontouchstart' in window);
}

$(document).ready(function(){
    $('.ortsAuswahl').on('change', function(){
        var targetLocation = this.value;
         if (targetLocation != '') {
             window.location = targetLocation;
         }
    });

    urlCategory('karte');
    urlCategory('orte');
    urlCategory('buchten-straende');
    urlCategory('landschaften');
    urlCategory('sehenswuerdigkeiten');

    function urlCategory(string) {
        var regExpEnds = new RegExp('/'+string+'$');
        var regExpInBetween = new RegExp('/'+string+'/');

        if (regExpEnds.test(window.location.href)) {
            $('#category_pic_' + string).addClass('transparent');
        }
        if (regExpInBetween.test(window.location.href)) {
            $('#category_pic_' + string).addClass('transparent');
        }
    }

    if (window.location.href.indexOf('?preview=') != -1) {
        console.log('ja!' + window.location.href);
        console.log('mt' + microtime());
        $("a").click(function(e) {
            e.preventDefault();
            window.location.href = $(this).attr("href") + '?preview=' + microtime();
        });
    }

    initPseudoSelects();

    $('body').click(function(ev){
       if(ev.target.className !== 'pseudo-select-dontclose') {
            $('.pseudo-select-active').removeClass('on');
            $('.pseudo-select-active').addClass('off');
       }
    });

});

function microtime(get_as_float) {
   //  discuss at: http://phpjs.org/functions/microtime/
   // original by: Paulo Freitas
   //   example 1: timeStamp = microtime(true);
   //   example 1: timeStamp > 1000000000 && timeStamp < 2000000000
   //   returns 1: true
   var now = new Date().getTime() / 1000;
   var s = parseInt(now, 10);
   return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + '' + s;
}

// ==============================================================
// PSEUDO-SELECT MENU version 3 - Greg Laycock, Fahlgren
// Emulate SELECT element so that search engines can follow links
// ==============================================================

// Initialize PSEUDO-SELECT elements (use on-load)

function initPseudoSelects() {
    // Check that the browser is DOM compliant
	if (document.getElementsByTagName) {
	    var theClass;
		var objDiv;
	    var aryDivs = document.getElementsByTagName('div');
	    for (var i = 0; i < aryDivs.length; i++) {
		    objDiv = aryDivs[i];
		    // Find all divs with a class name of "pseudo-select"
		    if (/\bpseudo\-select\b/.test(objDiv.className)) {
			   	theClass = objDiv.className;
				objDiv.className = theClass + '-active';
				objDiv.onclick = emulateSelectElement;
			}
	    }
    }
}

// Open and close PSEUDO-SELECT elements

function emulateSelectElement(close) {
	var on = 'pseudo-select-active on'
	var off = 'pseudo-select-active off'

    if (close == 1) {
        console.log('close:'+close);
        this.className = off;
        return;
    }
	switch (this.className) {
		case on:
			this.className = off;
			break;
		case off:
		default:
			this.className = on;
			break;
	}
}


text:
<?php

/**
 * tdSubpage module helper.
 *
 * @package    plugin
 * @subpackage tdCorePlugin
 * @author     Tomasz Ducin <tomasz.ducin@gmail.com>
 * @version    SVN: $Id: helper.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class tdSubpageGeneratorHelper extends BaseTdSubpageGeneratorHelper
{
}


text:
__title__ = 'pyscribe'
__version__ = '0.0.1'
__author__ = 'Alexander Wang'
__license__ = 'MIT'
__copyright__ = 'Copyright 2014 Alexander Wang'


text:
NF_EXPORT void DllStartPlugin(NFIPluginManager* pm)
{
#if NF_PLATFORM == NF_PLATFORM_WIN
#endif // NF_PLATFORM
    CREATE_PLUGIN(pm, NFWorldChatPlugin)
};

NF_EXPORT void DllStopPlugin(NFIPluginManager* pm)
{
    DESTROY_PLUGIN(pm, NFWorldChatPlugin)
};

//////////////////////////////////////////////////////////////////////////

const int NFWorldChatPlugin::GetPluginVersion()
{
    return 0;
}

const std::string NFWorldChatPlugin::GetPluginName()
{
    return GET_CLASS_NAME(NFWorldChatPlugin)
}

void NFWorldChatPlugin::Install()
{

    REGISTER_MODULE(pPluginManager, NFCWorldChatModule)
    REGISTER_MODULE(pPluginManager, NFCWorldChatGroupModule)
    REGISTER_MODULE(pPluginManager, NFCChatGroupBroadcastModule)

}

void NFWorldChatPlugin::Uninstall()
{
    UNREGISTER_MODULE(pPluginManager, NFCChatGroupBroadcastModule)
    UNREGISTER_MODULE(pPluginManager, NFCWorldChatGroupModule)
    UNREGISTER_MODULE(pPluginManager, NFCWorldChatModule)
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Ramularia sambucina f. santonensis Brunaud

### Remarks
null


text:
package com.intellij.vcs.log.ui;

import com.intellij.openapi.util.Condition;
import com.intellij.ui.JBColor;
import com.intellij.vcs.log.*;
import com.intellij.vcs.log.data.LoadingDetails;
import com.intellij.vcs.log.data.VcsLogDataHolder;
import com.intellij.vcs.log.data.VcsLogUiProperties;
import com.intellij.vcs.log.impl.VcsLogUtil;
import com.intellij.vcs.log.ui.filter.VcsLogClassicFilterUi;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;

public class CurrentBranchHighlighter implements VcsLogHighlighter {
  private static final JBColor CURRENT_BRANCH_BG = new JBColor(new Color(228, 250, 255), new Color(63, 71, 73));
  @NotNull private final VcsLogUiProperties myUiProperties;
  @NotNull private final VcsLogDataHolder myDataHolder;
  @NotNull private final VcsLogFilterUi myFilterUi;
  @Nullable private String mySingleFilteredBranch;

  public CurrentBranchHighlighter(@NotNull VcsLogDataHolder logDataHolder,
                                  @NotNull VcsLogUiProperties uiProperties,
                                  @NotNull VcsLogFilterUi filterUi) {
    myDataHolder = logDataHolder;
    myUiProperties = uiProperties;
    myFilterUi = filterUi;

    // this code will look much simpler when history* branch is merged
    ((VcsLogClassicFilterUi)filterUi).getLogUi().addLogListener(new VcsLogListener() {
      @Override
      public void onChange(@NotNull VcsLogDataPack dataPack, boolean refreshHappened) {
        VcsLogBranchFilter branchFilter = myFilterUi.getFilters().getBranchFilter();
        mySingleFilteredBranch = branchFilter == null
                                 ? null
                                 : VcsLogUtil
                                   .getSingleFilteredBranch(branchFilter, dataPack.getRefs());
      }
    });
  }

  @NotNull
  @Override
  public VcsCommitStyle getStyle(int commitIndex, boolean isSelected) {
    if (isSelected || !myUiProperties.isHighlighterEnabled(Factory.ID)) return VcsCommitStyle.DEFAULT;
    VcsShortCommitDetails details = myDataHolder.getMiniDetailsGetter().getCommitDataIfAvailable(commitIndex);
    if (details != null && !(details instanceof LoadingDetails)) {
      VcsLogProvider provider = myDataHolder.getLogProvider(details.getRoot());
      String currentBranch = provider.getCurrentBranch(details.getRoot());
      VcsLogBranchFilter branchFilter = myFilterUi.getFilters().getBranchFilter();
      if (currentBranch != null && (branchFilter == null || !(currentBranch.equals(mySingleFilteredBranch)))) {
        Condition<Hash> condition =
          myDataHolder.getContainingBranchesGetter().getContainedInBranchCondition(currentBranch, details.getRoot());
        if (condition.value(details.getId())) {
          return VcsCommitStyleFactory.background(CURRENT_BRANCH_BG);
        }
      }
    }
    return VcsCommitStyle.DEFAULT;
  }

  public static class Factory implements VcsLogHighlighterFactory {
    @NotNull private static final String ID = "CURRENT_BRANCH";

    @NotNull
    @Override
    public VcsLogHighlighter createHighlighter(@NotNull VcsLogDataHolder logDataHolder,
                                               @NotNull VcsLogUiProperties uiProperties,
                                               @NotNull VcsLogFilterUi filterUi) {
      return new CurrentBranchHighlighter(logDataHolder, uiProperties, filterUi);
    }

    @NotNull
    @Override
    public String getId() {
      return ID;
    }

    @NotNull
    @Override
    public String getTitle() {
      return "Current Branch";
    }
  }
}