text:
import chai, { assert } from 'chai';
import asPromised from 'chai-as-promised';
import sinon from 'sinon';
import * as Reflux from '../src';

chai.use(asPromised);

describe("using the publisher methods mixin",function(){
    var pub = Reflux.PublisherMethods;

    describe("the listen method",function(){
        var emitter = {
                addListener:sinon.spy(),
                removeListener:sinon.spy()
            },
            context = {
                emitter: emitter,
                eventLabel: "LABEL",
            },
            callback = sinon.spy(),
            cbcontext = {foo:"BAR"},
            result = pub.listen.call(context,callback,cbcontext);

        it("should call addListener correctly",function(){
            var args = emitter.addListener.firstCall.args;
            assert.equal(args[0],context.eventLabel);
            assert.isFunction(args[1]);
            args[1](["ARG1","ARG2"]);
            assert.deepEqual(callback.firstCall.args,["ARG1","ARG2"]);
            assert.equal(callback.firstCall.thisValue,cbcontext);
        });

        describe("the returned value",function(){

            it("should be a function",function(){
                assert.isFunction(result);
            });

            it("should remove the listener correctly",function(){
                result();
                assert.deepEqual(emitter.removeListener.firstCall.args,[context.eventLabel,emitter.addListener.firstCall.args[1]]);
            });
        });
    });

    describe("the trigger method",function(){

        describe("when shouldEmit returns true",function(){

            describe("when preEmit returns undefined",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.spy(),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.call(context,"FOO","BAR");

                it("should call preEmit correctly",function(){
                    assert.deepEqual(context.preEmit.firstCall.args,["FOO","BAR"]);
                });

                it("should call shouldEmit correctly",function(){
                    assert.deepEqual(context.shouldEmit.firstCall.args,["FOO","BAR"]);
                });

                it("should call emit on the emitter",function(){
                    // args are weird because it is an arguments object
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1][0],"FOO");
                    assert.deepEqual(args[1][1],"BAR");
                });
            });

            describe("when preEmit returns an array of new args",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    newargs = ["foo","bar"],
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.stub().returns(newargs),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should call shouldEmit with the changed args",function(){
                    assert.deepEqual(context.shouldEmit.firstCall.args,newargs);
                });

                it("should call emit on the emitter with the changed args",function(){
                    // args are weird because it is an arguments object
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1],newargs);
                });
            });

            describe("when preEmit returns the arguments array",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    context = {
                        eventLabel: "LABEL",
                        preEmit:function(){return arguments;},
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should correctly call shouldEmit as if we returned an array",function(){
                    assert.deepEqual(oldargs,context.shouldEmit.firstCall.args);
                });

                it("should call emit the same way too",function(){
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1][0],oldargs[0]);
                    assert.deepEqual(args[1][1],oldargs[1]);
                });
            });

            describe("when preEmit returns a string",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    newarg = "I SHOULD BE USED AS A SINGLE ARG",
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.stub().returns(newarg),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should call shouldEmit with the string",function(){
                    assert.deepEqual([newarg],context.shouldEmit.firstCall.args);
                });

                it("should call emit with the string too",function(){
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1],[newarg]);
                });
            });

            describe("when preEmit returns a number",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    newarg = 12345,
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.stub().returns(newarg),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should call shouldEmit with the number",function(){
                    assert.deepEqual([newarg],context.shouldEmit.firstCall.args);
                });

                it("should call emit with the number too",function(){
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1],[newarg]);
                });
            });

            describe("when preEmit returns false",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    newarg = false,
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.stub().returns(newarg),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should call shouldEmit with false",function(){
                    assert.deepEqual([newarg],context.shouldEmit.firstCall.args);
                });

                it("should call emit with false too",function(){
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1],[newarg]);
                });
            });

            describe("when preEmit returns an object",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    newarg = {a:"foo",b:"bar"},
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.stub().returns(newarg),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should call shouldEmit with the object",function(){
                    assert.deepEqual([newarg],context.shouldEmit.firstCall.args);
                });

                it("should call emit with the object too",function(){
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1],[newarg]);
                });
            });

            describe("when preEmit returns a function",function(){
                var emitter = {
                        emit: sinon.spy()
                    },
                    oldargs = ["what","ever"],
                    newarg = function(foo,bar){console.log(foo,bar);},
                    context = {
                        eventLabel: "LABEL",
                        preEmit:sinon.stub().returns(newarg),
                        shouldEmit:sinon.stub().returns(true),
                        emitter: emitter
                    };
                pub.trigger.apply(context,oldargs);

                it("should call shouldEmit with the function",function(){
                    assert.deepEqual([newarg],context.shouldEmit.firstCall.args);
                });

                it("should call emit with the function too",function(){
                    var args = emitter.emit.firstCall.args;
                    assert.deepEqual(args[0],"LABEL");
                    assert.deepEqual(args[1],[newarg]);
                });
            });
        });

        describe("when shouldEmit returns false",function(){
            var emitter = {
                    emit: sinon.spy()
                },
                context = {
                    preEmit:sinon.spy(),
                    shouldEmit:sinon.stub().returns(false),
                    emitter: emitter
                };
            pub.trigger.call(context,"FOO","BAR");

            it("should not emit anything",function(){
                assert.equal(emitter.emit.callCount,0);
            });
        });
    });

});


text:
using EdiEngine.Common.Enums;
using EdiEngine.Common.Definitions;
using EdiEngine.Standards.X12_004010.Segments;

namespace EdiEngine.Standards.X12_004010.Maps
{
	public class M_251 : MapLoop
	{
		public M_251() : base(null)
		{
			Content.AddRange(new MapBaseEntity[] {
				new BGN() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
				new SPI() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
				new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new CUR() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_REF(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_N1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				new L_PPL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
			});
		}

		//1000
		public class L_REF : MapLoop
		{
			public L_REF(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//2000
		public class L_N1 : MapLoop
		{
			public L_N1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new G61() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
				});
			}
		}

		//3000
		public class L_PPL : MapLoop
		{
			public L_PPL(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PPL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new L_REF_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_PD(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_PL(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_PO1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3100
		public class L_REF_1 : MapLoop
		{
			public L_REF_1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new REF() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3200
		public class L_PD : MapLoop
		{
			public L_PD(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new PDD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3300
		public class L_PL : MapLoop
		{
			public L_PL(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PL() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_PD_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3310
		public class L_PD_1 : MapLoop
		{
			public L_PD_1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PD() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new SPI() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new PDD() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 10 },
				});
			}
		}

		//3400
		public class L_PO1 : MapLoop
		{
			public L_PO1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new PO1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new PID() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_AMT(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new L_LX(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3410
		public class L_AMT : MapLoop
		{
			public L_AMT(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new AMT() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new PCT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
					new MSG() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 999999 },
				});
			}
		}

		//3420
		public class L_LX : MapLoop
		{
			public L_LX(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new LX() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new QTY() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new AMT() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new NTE() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 5 },
					new REF() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new DTM() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
					new L_N1_1(this) { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				});
			}
		}

		//3421
		public class L_N1_1 : MapLoop
		{
			public L_N1_1(MapLoop parentLoop) : base(parentLoop)
			{
				Content.AddRange(new MapBaseEntity[] {
					new N1() { ReqDes = RequirementDesignator.Mandatory, MaxOccurs = 1 },
					new N2() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N3() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 2 },
					new N4() { ReqDes = RequirementDesignator.Optional, MaxOccurs = 1 },
				});
			}
		}

	}
 }

redpajama_set_name: RedPajamaGithub


text:
package logic.cards;

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

import logic.Player;
import logic.Zone;
import logic.states.Game;

public final class Card implements Serializable {
    private List<Action> actionList;
    private Resource     cardResource;
    private int          minimumPlayers;

    public Card(Resource resource, List<Action> actions) throws IllegalArgumentException {
        this(resource, actions, 0);
    }

    public Card(Resource resource, List<Action> actions, int minimumPlayers) throws IllegalArgumentException {
        if (resource == null)
            throw new IllegalArgumentException("Invalid resource");

        if (actions == null)
            throw new IllegalArgumentException("Invalid actions");

        this.actionList = new ArrayList<>();
        for (Action a : actions)
            actionList.add(a);

        this.cardResource = resource;
        this.minimumPlayers = minimumPlayers;
    }

    public Resource getCardResource() {
        return this.cardResource;
    }

    public int getMinimumPlayers() {
        return this.minimumPlayers;
    }

    public int getActionNumber() {
        return this.actionList.size();
    }

    public List<Action> getActionList() {
        return this.actionList;
    }

    public List<Action> getBaseActions() {
        return unfoldActions(this.actionList);
    }

    private List<Action> unfoldActions(List<Action> inputActionList) {

        List<Action> outputActionList = new ArrayList<>();

        for (Action a : inputActionList) {
            if (a instanceof ActionAnd)
                outputActionList.addAll(unfoldActions(((ActionAnd) a).getActionList()));
            else if (a instanceof ActionOr)
                outputActionList.addAll(unfoldActions(((ActionOr) a).getActionList()));
            else
                outputActionList.add(a);
        }

        return outputActionList;
    }

    public void setGame(Game g) {
        if (g == null)
            return;

        for (Action a : actionList)
            a.setGame(g);
    }

    public void placeCity(Player p, Zone zone) {
        for (Action a : this.actionList) {
            boolean exit = false;
            int result = a.placeCity(p, zone);

            switch (result) {
            case Action.ACTION_FAILED:
                break;
            case Action.ACTION_END:
                this.actionList.remove(a);
            case Action.ACTION_SUCCESS:
                exit = true;
            }
            if (exit)
                break;
        }
    }

    public void placeCombatUnit(Player p, Zone zone) {
        for (Action a : this.actionList) {
            boolean exit = false;
            int result = a.placeCombatUnit(p, zone);

            switch (result) {
            case Action.ACTION_FAILED:
                break;
            case Action.ACTION_END:
                this.actionList.remove(a);
            case Action.ACTION_SUCCESS:
                exit = true;
            }
            if (exit)
                break;
        }
    }

    public void moveCombatUnit(Player p, Zone startZone, Zone endZone) {
        for (Action a : this.actionList) {
            boolean exit = false;
            int result = a.moveCombatUnit(p, startZone, endZone);

            switch (result) {
            case Action.ACTION_FAILED:
                break;
            case Action.ACTION_END:
                this.actionList.remove(a);
            case Action.ACTION_SUCCESS:
                exit = true;
            }
            if (exit)
                break;
        }
    }

    public void removeCombatUnit(Player p, Zone zone, Player owner) {
        for (Action a : this.actionList) {
            boolean exit = false;
            int result = a.removeCombatUnit(p, zone, owner);

            switch (result) {
            case Action.ACTION_FAILED:
                break;
            case Action.ACTION_END:
                this.actionList.remove(a);
            case Action.ACTION_SUCCESS:
                exit = true;
            }
            if (exit)
                break;
        }
    }

    @Override
    public String toString() {
        String res = "Resource: " + this.cardResource.toString() + " - Actions: ";
        for (Action a : this.actionList)
            res += a.toString() + "  ";

        return res;
    }
}


text:
@interface PodsDummy_Pods_AwesomeCacheSlashAcceptable_Tests : NSObject
@end
@implementation PodsDummy_Pods_AwesomeCacheSlashAcceptable_Tests
@end


text:
/*
 * $Id$
 */

/*

Copyright (c) 2000-2017 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.plugin.atypon;

import org.lockss.daemon.Crawler.CrawlerFacade;
import org.lockss.plugin.*;
import org.lockss.plugin.base.HttpToHttpsUrlConsumer;
import org.lockss.util.UrlUtil;

/**
 *

 * A variant on
 * {@link HttpToHttpsUrlConsumer}
 * for Atypon that allows a change from a "/" to a "%2F" within the doi
 * of showCitFormat urls
 *

 *
 * @author Alexandra Ohlson
 */
public class BaseAtyponHttpToHttpsUrlConsumerFactory implements UrlConsumerFactory {

  @Override
  public UrlConsumer createUrlConsumer(CrawlerFacade crawlFacade,
                                       FetchedUrlData fud) {
    return new BaseAtyponHttpToHttpsUrlConsumer(crawlFacade, fud);
  }
  public class BaseAtyponHttpToHttpsUrlConsumer extends HttpToHttpsUrlConsumer {

    public BaseAtyponHttpToHttpsUrlConsumer(CrawlerFacade facade, FetchedUrlData fud) {
      super(facade, fud);
    }

    /**
     *

     * Determines if the URL is to be stored under its redirect chain's origin
     * URL. By default in this implementation, this is true when the AU is
     * HTTP-defined and there has been a single-hop redirect from an HTTP URL to
     * the exactly corresponding HTTPS URL.
     * With the additional exception that
     *
     * http://arc.aiaa.org/action/showCitFormats?doi=10.2514/1.C032918
     * redirects to:
     * https://arc.aiaa.org/action/showCitFormats?doi=10.2514%2F1.C032918
     * which will normalize to
     * http://arc.aiaa.org/action/showCitFormats?doi=10.2514%2F1.C032918
     *
     *

     *
     */
    public boolean shouldStoreAtOrigUrl() {
      return AuUtil.isBaseUrlHttp(au)
          && fud.redirectUrls != null
          && fud.redirectUrls.size() == 1
          && fud.fetchUrl.equals(fud.redirectUrls.get(0))
          && UrlUtil.isHttpUrl(fud.origUrl)
          && UrlUtil.isHttpsUrl(fud.fetchUrl)
          && (UrlUtil.stripProtocol(fud.origUrl).equals(UrlUtil.stripProtocol(fud.fetchUrl)) ||
               UrlUtil.stripProtocol(fud.origUrl).equals(UrlUtil.stripProtocol(fud.fetchUrl.replace("%2F","/"))));
    }
 }

}


text:
namespace node {

class Environment;

class StatWatcher : public HandleWrap {
 public:
  static void Initialize(Environment* env, v8::Local<v8::Object> target);

 protected:
  StatWatcher(Environment* env,
              v8::Local<v8::Object> wrap,
              bool use_bigint);

  static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
  static void Start(const v8::FunctionCallbackInfo<v8::Value>& args);

  SET_NO_MEMORY_INFO()
  SET_MEMORY_INFO_NAME(StatWatcher)
  SET_SELF_SIZE(StatWatcher)

 private:
  static void Callback(uv_fs_poll_t* handle,
                       int status,
                       const uv_stat_t* prev,
                       const uv_stat_t* curr);

  uv_fs_poll_t watcher_;
  const bool use_bigint_;
};

}  // namespace node

#endif  // defined(NODE_WANT_INTERNALS) && NODE_WANT_INTERNALS

#endif  // SRC_NODE_STAT_WATCHER_H_


text:
using System;
using System.ComponentModel.Design;
using System.Runtime.InteropServices;
using EnvDTE;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.LanguageServices.Setup;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;

namespace Microsoft.VisualStudio.LanguageServices.Interactive
{
    internal abstract partial class VsInteractiveWindowPackage<TVsInteractiveWindowProvider> : Package, IVsToolWindowFactory
        where TVsInteractiveWindowProvider : VsInteractiveWindowProvider
    {
        protected abstract string LanguageName { get; }
        protected abstract string ProjectKind { get; }

        protected abstract void InitializeMenuCommands(OleMenuCommandService menuCommandService);
        protected abstract CommandID GetResetInteractiveFromProjectCommandID();

        protected abstract string CreateReference(string referenceName);
        protected abstract string CreateImport(string namespaceName);
        protected abstract Guid LanguageServiceGuid { get; }
        protected abstract Guid ToolWindowId { get; }

        private IComponentModel _componentModel;
        private TVsInteractiveWindowProvider _interactiveWindowProvider;

        protected override void Initialize()
        {
            base.Initialize();

            // Load the Roslyn package so that its FatalError handlers are hooked up.
            IVsPackage setupPackage;
            var shell = (IVsShell)this.GetService(typeof(SVsShell));
            shell.LoadPackage(Guids.RoslynPackageId, out setupPackage);
            shell.LoadPackage(Microsoft.VisualStudio.InteractiveWindow.Shell.Guids.InteractiveWindowPackageId, out setupPackage);

            _componentModel = (IComponentModel)GetService(typeof(SComponentModel));
            _interactiveWindowProvider = _componentModel.DefaultExportProvider.GetExportedValue<TVsInteractiveWindowProvider>();

            var menuCommandService = (OleMenuCommandService)GetService(typeof(IMenuCommandService));
            InitializeMenuCommands(menuCommandService);
            InitializeResetInteractiveFromProjectCommand(menuCommandService);

            var telemetrySetupExtensions = _componentModel.GetExtensions<IRoslynTelemetrySetup>();
            foreach (var telemetrySetup in telemetrySetupExtensions)
            {
                telemetrySetup.Initialize(this);
            }
        }

        protected TVsInteractiveWindowProvider InteractiveWindowProvider
        {
            get { return _interactiveWindowProvider; }
        }

        /// <summary>
        /// When a VSPackage supports multi-instance tool windows, each window uses the same rguidPersistenceSlot.
        /// The dwToolWindowId parameter is used to differentiate between the various instances of the tool window.
        /// </summary>
        int IVsToolWindowFactory.CreateToolWindow(ref Guid rguidPersistenceSlot, uint id)
        {
            if (rguidPersistenceSlot == ToolWindowId)
            {
                var result = _interactiveWindowProvider.Create((int)id);

                return (result != null) ? VSConstants.S_OK : VSConstants.E_FAIL;
            }

            return VSConstants.E_FAIL;
        }

        private void InitializeResetInteractiveFromProjectCommand(OleMenuCommandService menuCommandService)
        {
            var resetInteractiveFromProjectCommand = new OleMenuCommand(
                (sender, args) =>
                {
                    var resetInteractive = new ResetInteractive(
                        (DTE)this.GetService(typeof(SDTE)),
                        _componentModel,
                        (IVsMonitorSelection)this.GetService(typeof(SVsShellMonitorSelection)),
                        (IVsSolutionBuildManager)this.GetService(typeof(SVsSolutionBuildManager)),
                        CreateReference,
                        CreateImport);

                    var vsInteractiveWindow = _interactiveWindowProvider.Open(instanceId: 0, focus: true);

                    resetInteractive.Execute(vsInteractiveWindow, LanguageName + " Interactive");
                },
                GetResetInteractiveFromProjectCommandID());

            resetInteractiveFromProjectCommand.Supported = true;

            resetInteractiveFromProjectCommand.BeforeQueryStatus += (_, __) =>
            {
                var project = GetActiveProject();
                var available = project != null && project.Kind == ProjectKind;

                resetInteractiveFromProjectCommand.Enabled = available;
                resetInteractiveFromProjectCommand.Supported = available;
                resetInteractiveFromProjectCommand.Visible = available;
            };

            menuCommandService.AddCommand(resetInteractiveFromProjectCommand);
        }

        private EnvDTE.Project GetActiveProject()
        {
            var monitorSelection = (IVsMonitorSelection)this.GetService(typeof(SVsShellMonitorSelection));

            IntPtr hierarchyPointer = IntPtr.Zero;
            IntPtr selectionContainerPointer = IntPtr.Zero;

            try
            {
                uint itemid;
                IVsMultiItemSelect multiItemSelect;

                Marshal.ThrowExceptionForHR(
                    monitorSelection.GetCurrentSelection(
                        out hierarchyPointer,
                        out itemid,
                        out multiItemSelect,
                        out selectionContainerPointer));

                if (itemid != (uint)VSConstants.VSITEMID.Root)
                {
                    return null;
                }

                var hierarchy = Marshal.GetObjectForIUnknown(hierarchyPointer) as IVsHierarchy;
                if (hierarchy == null)
                {
                    return null;
                }

                object extensibilityObject;
                Marshal.ThrowExceptionForHR(
                    hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out extensibilityObject));

                return extensibilityObject as EnvDTE.Project;
            }
            finally
            {
                if (hierarchyPointer != IntPtr.Zero)
                {
                    Marshal.Release(hierarchyPointer);
                }

                if (selectionContainerPointer != IntPtr.Zero)
                {
                    Marshal.Release(selectionContainerPointer);
                }
            }
        }
    }
}


text:
One of the goals of **Redux First Router** is to *NOT* alter your actions and be 100% *flux standard action*-compliant. That allows
for automatic support for packages such as `redux-actions`.

So simply put, to do that, we stuffed all the info our middleware, reducer, etc, depends on in the `meta` key of your actions.

Without further ado, let's take a look at what your actions look like--here's our pure utility function, `nestAction()`, used to format
and nest your actions:

## The Meta key is the *key*
*Note: If you or other middleware are making use of the `meta` key we'll make sure to hold on to that info as well.*

```javascript
const nestAction = (
  pathname: string,
  receivedAction: Action,
  prev: Location,
  kind?: string
): Action => {
  const { type, payload = {}, meta } = receivedAction

  return {
    type,     // this will remain exactly what you dispatched
    payload,  // this will remain exactly what you dispatched

              // no additional keys!

    meta: {   // all routing information crammed into the meta key
      ...meta,
      location: {
        current: {
          pathname,
          type,
          payload
        },
        prev,
        kind
      }
    }
  }
}
```

So in short, we take a more basic action you dispatch (or that the address-bar listening enhancer dispatches) and assign
all the location-related information we have to the `location` key within the `meta` key.

## Flow Type
For an even clearer sense of what is on the `location` key of your *flux standard actions*, here's its ***Flow*** type:

```javascript
type Action = {
  type: string,
  payload: Object,
  meta: Meta
}

type Meta = {
  location: {
    current: Location,
    prev: Location,
    kind: 'load' | 'redirect' | 'back' | 'next' | 'pop'
  }
}

type Location = {
  pathname: string,
  type: string,
  payload: Object
}
```

## The error key
RFR will ignore actions which contain a truthy `error` key.
This is in case you want to use a different middleware to handle errors.

## Conclusion
You will rarely need to inspect the `meta` key. It's primarily for use by our `location` reducer. However, a common
use for it is to use the `kind` key to make some determinations in your
reducers. `pop` simply indicates the browser back/next buttons were used, where as `back` and `next` indicate explicitly
which direction you were going, which we can determine when using `createMemoryHistory` such as in React Native. In conjunction with `kind`, you can use the `prev` route to
do things like declaratively trigger fancy animations in your components because it will indicate which direction
the user is moving in a funnel/sequence of pages.


text:
package com.codeabovelab.dm.common.kv.mapping;

import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.util.StringUtils;

/**
 */
public class PropertyCipher implements PropertyInterceptor {

    private final TextEncryptor encryptor;

    public PropertyCipher(TextEncryptor encryptor) {
        this.encryptor = encryptor;
    }

    @Override
    public String save(KvPropertyContext prop, String value) {
        if (StringUtils.hasText(value)) {
            return encryptor.encrypt(value);
        } else {
            return value;
        }
    }

    @Override
    public String read(KvPropertyContext prop, String value) {
        if (StringUtils.hasText(value)) {
            return encryptor.decrypt(value);
        } else {
            return value;
        }
    }
}


text:
INPLACE=0
while getopts i option
do
    case $option in
    i)  INPLACE=1
        ;;
    *)  echo "Usage $0 [-i]"
        echo "OPTIONS:"
        echo       -i: Format files according to coding standards in place
        exit 1
        ;;
    esac
done
shift $((OPTIND-1))

if [ $# -ne 1 ]; then
    echo "Usage: $0 [-i] SOURCE_DIR"
    exit 1
fi

SOURCE_DIR=$1

CLANG_FORMAT=`find $SOURCE_DIR -name .clang-format`
if [ ! -f $CLANG_FORMAT ]; then
    echo WARN: No .clang-format found in $SOURCE_DIR
fi

# Find sources
BUILD_DIR="$PWD"
TMP_FILENAME=`mktemp`

RETURN_CODE=0

for SOURCE_FILE in `find "$SOURCE_DIR" -name "*.cpp" -o -name "*.h"`
do
    # In-place formatting
    if [ $INPLACE -eq 1 ]; then
        clang-format -style=file -i "$SOURCE_FILE"
        if [ $? -ne 0 ]; then
            RETURN_CODE=1
        fi
        continue
    fi

    clang-format -style=file "$SOURCE_FILE" > "$TMP_FILENAME"
    diff "$SOURCE_FILE" "$TMP_FILENAME"
    if [ $? -ne 0 ]; then
        FILEPATH=`echo "$SOURCE_FILE" | sed "s/.*\.\.\///g"`
      echo "$FILEPATH" 1>&2
      RETURN_CODE=1
    fi
    rm $TMP_FILENAME
done

if [ $RETURN_CODE -ne 0 ]; then
    echo "The above files do not meet the coding standards."
    echo "Please run $0 -i to remediate."
fi

exit $RETURN_CODE


text:
<?php
// Copyright (c) 2021 by Thomas Pawlitschko. (MIT License)

declare(strict_types=1);

namespace TPawl\LiTE;

use TPawl\LiTE\Expressions\SubTemplateExpression;
use TPawl\Lite\Miscellaneous\PackageErrorHandler;

class SubTemplate
{
    protected $subTemplateExpression;

    /**
     * @return void
     * @throws \InvalidArgumentException if an index does not exist or the type at index is wrong
     */
    public function __construct(string $template, array $variables)
    {
        PackageErrorHandler::pushOnErrorHandlersStack();

        $this->subTemplateExpression = new SubTemplateExpression($template, $variables);

        PackageErrorHandler::popFromErrorHandlersStack();
    }

    public function display(): void
    {
        PackageErrorHandler::pushOnErrorHandlersStack();

        $this->subTemplateExpression->display();

        PackageErrorHandler::popFromErrorHandlersStack();
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name=viewport content="width=device-width, initial-scale=1">
    <title>Specio - Explore the tree of life</title>
    <link rel="shortcut icon" href="image/favicon.ico"/>
    <meta name="description"
          content="With Specio, you can explore the tree of life, from the kingdoms to the species. Specio provides complete information and pictures of life, with an extensive knowledge base and an easy to use interface.">
    <link rel="stylesheet" href="css/sbg.css">
    <link rel="stylesheet" href="semantic/css/semantic.min.css">
    <link rel="stylesheet" href="css/styles.min.css">
    <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css"/>

         Home

         About

             Github

What is Specio?

        With Specio, you can explore the tree of life, from the kingdoms down to the species. Specio provides you with
        information and images about different groups of organisms and their evolutionary relationships.

        Starting with the root of all Life on Earth and moving out along diverging branches to individual species, the
        structure of the tree of life illustrates the genetic connections between all living things. For each group and
        species, you can find information and pictures coming from the Wikipedia database, ensuring extensiveness and
        completeness. There are seven ranks in the tree of life: kingdom, phylum, class, order, family, genus, species.
        Additionally, Domain, which is a level above kingdom, has become popular in recent years. For more information,
        consult
        Wikipedia.

        Here are some good examples of familiar species to help you familiarize with the tree. Try finding them in the
        tree!

                    Human:
                    Animalia

                    Chordates

                    Mammals

                    Primates

                    Man like Primates

                    Hominoids

                    Human

                    Pine trees:
                    Plantae

                    Pinophyta

                    Pinophyta

                    Pinales

                    Pine family

                    Hybrid pine

                    ...


text:
What to do next?
================

You've got dStack running, what should you do next?  A lot of dStack is currently oriented around Docker.  If you're not too familiar with Docker there are some :ref:`basic examples <docker-example>` using Docker.  Once you've got a handle on Docker, you can then :ref:`deploy some things <dstack-example>` in dStack.


text:
static inline NSTimeInterval lfx_NSTimeIntervalWithMinutes(double minutes)
{
	return 60.0 * minutes;
}

static inline NSTimeInterval lfx_NSTimeIntervalWithHours(double hours)
{
	return 60.0 * 60.0 * hours;
}

static inline NSTimeInterval lfx_NSTimeIntervalWithDays(double days)
{
	return 60.0 * 60.0 * 24.0 * days;
}

@interface NSDate (LFXExtensions)

// These are thread safe, since they use Thread Local NSDateFormatters
- (NSString *)lfx_stringWithDateFormatterTemplate:(NSString *)dateFormatterTemplate;
- (NSString *)lfx_stringWithDateFormat:(NSString *)dateFormat;

- (BOOL)lfx_isEarlierThanDate:(NSDate *)date;
- (BOOL)lfx_isLaterThanDate:(NSDate *)date;

- (NSTimeInterval)lfx_timeIntervalUpToNow;

@end


text:
package com.readr.ro.countries.fragment;

import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.readr.ro.countries.R;
import com.readr.ro.countries.constants.Constants;
import com.readr.ro.countries.model.Country;
import com.readr.ro.countries.presenter.CountryPresenter;
import com.readr.ro.countries.util.Utils;
import com.readr.ro.countries.view.CountryView;
import com.squareup.picasso.Picasso;

import butterknife.BindView;
import butterknife.ButterKnife;

import static android.content.Intent.ACTION_VIEW;

/**
 * Created by Domnica on 11/1/2016.
 * Fragment displaying a simple list of details for the selected country
 */

public class CountryFragment extends Fragment implements CountryView {

    private CountryPresenter mCountryPresenter;
    private String countryCodeId;
    private String countryName;
    private ProgressDialog mProgressDialog;

    @BindView(R.id.countryDetailsFlag)
    ImageView flag;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.subTitle)
    TextView subTitle;
    @BindView(R.id.capital)
    TextView capital;
    @BindView(R.id.population)
    TextView population;
    @BindView(R.id.area)
    TextView area;
    @BindView(R.id.location)
    TextView location;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCountryPresenter = new CountryPresenter(getActivity());
        mCountryPresenter.attachView(this);
        Bundle bundle = getArguments();
        countryName = getString(R.string.title_activity_countries);
        if (bundle != null) {
            countryCodeId = bundle.getString(Constants.COUNTRY_CODE_ID);
            // we are sending the country name for a smother transition (if it's available)
            countryName = bundle.getString(Constants.COUNTRY_NAME);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCountryPresenter.detachView();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_country_details, container, false);
        ButterKnife.bind(this, view);
        mCountryPresenter.fetchCountryDetails(countryCodeId);
        setHasOptionsMenu(true);
        ActionBar mActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (mActionBar != null) {
            mActionBar.setDisplayHomeAsUpEnabled(true);
            mActionBar.setTitle(countryName);
        }
        return view;
    }

    @Override
    public void displayCountryDetails(final Country country) {
        title.setText(country.getName());

        int resId = Utils.fetchFlagFromAlphaCode(country.getCountryCode(), country.getAlternativeCountryCode(), getActivity());
        if (resId != 0) {
            Picasso.with(getActivity()).load(resId).into(flag);
        } else {
            Picasso.with(getActivity()).load(R.drawable.flag_placeholder).into(flag);
        }
        subTitle.setText(country.getRegion() + ", " + country.getSubRegion());
        capital.setText(country.getCapital());
        population.setText(country.getPopulation());
        area.setText(country.getArea());

        location.setText(Html.fromHtml("<u>" + getActivity().getString(R.string.latitude) + country.getLocation()[0] + ", " + getActivity().getString(R.string.longitude) + country.getLocation()[1] + "</u>"));

        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ACTION_VIEW, Uri.parse("http://maps.google.com/maps?q=" + country.getLocation()[0] + "," + country.getLocation()[1]));
                startActivity(intent);
            }
        });
    }

    @Override
    public void showProgressDialog() {
        mProgressDialog = new ProgressDialog(getActivity(), R.style.ProgressDialogTheme);
        mProgressDialog.show();
    }

    @Override
    public void dismissProgressDialog() {
        mProgressDialog.dismiss();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            super.getActivity().onBackPressed();

        }

        return super.onOptionsItemSelected(item);
    }

    //Bug known from the support library (workaround if you turn the screen while having animations)
    @Override
    public Animator onCreateAnimator(int transit, boolean enter, int nextAnim) {
        if (enter) {
            return AnimatorInflater.loadAnimator(getActivity(), R.animator.slide_in_right);
        } else {
            return AnimatorInflater.loadAnimator(getActivity(), R.animator.slide_out_left);
        }
    }
}


text:
package com.jjinterna.pbxevents.routes;

import com.jjinterna.pbxevents.model.PBXEvent;

public interface EventSelector {

	boolean select(PBXEvent event);

}


text:
//
//  LMJCircleLayout.h
//  自定义流水布局-22
//
//  Created by apple on 16/7/30.
//  Copyright © 2016年 NJHu. All rights reserved.
//

#import <UIKit/UIKit.h>

@class LMJCircleLayout;

@protocol LMJCircleLayoutDelegate <NSObject>
@optional
/**
 返回 item 的大小, 默认 64
 */
- (CGSize)circleLayout:(LMJCircleLayout *)circleLayout collectionView:(UICollectionView *)collectionView sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

/**
 返回 item 对应的半径 , 默认120
 */
- (CGFloat)circleLayout:(LMJCircleLayout *)circleLayout collectionView:(UICollectionView *)collectionView radiusForItemAtIndexPath:(NSIndexPath *)indexPath;
@end

@interface LMJCircleLayout : UICollectionViewLayout

- (instancetype)initWithDelegate:(id<LMJCircleLayoutDelegate>)delegate;

+ (instancetype)circleLayoutWithDelegate:(id<LMJCircleLayoutDelegate>)delegate;

@end


text:
"""Config flow for ZHA."""
from __future__ import annotations

from typing import Any

import serial.tools.list_ports
import voluptuous as vol
from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH

from homeassistant import config_entries
from homeassistant.components import usb
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.helpers.typing import DiscoveryInfoType

from .core.const import (
    CONF_BAUDRATE,
    CONF_FLOWCONTROL,
    CONF_RADIO_TYPE,
    DOMAIN,
    RadioType,
)

CONF_MANUAL_PATH = "Enter Manually"
SUPPORTED_PORT_SETTINGS = (
    CONF_BAUDRATE,
    CONF_FLOWCONTROL,
)
DECONZ_DOMAIN = "deconz"

class ZhaFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
    """Handle a config flow."""

    VERSION = 3

    def __init__(self):
        """Initialize flow instance."""
        self._device_path = None
        self._radio_type = None
        self._title = None

    async def async_step_user(self, user_input=None):
        """Handle a zha config flow start."""
        if self._async_current_entries():
            return self.async_abort(reason="single_instance_allowed")

        ports = await self.hass.async_add_executor_job(serial.tools.list_ports.comports)
        list_of_ports = [
            f"{p}, s/n: {p.serial_number or 'n/a'}"
            + (f" - {p.manufacturer}" if p.manufacturer else "")
            for p in ports
        ]

        if not list_of_ports:
            return await self.async_step_pick_radio()

        list_of_ports.append(CONF_MANUAL_PATH)

        if user_input is not None:
            user_selection = user_input[CONF_DEVICE_PATH]
            if user_selection == CONF_MANUAL_PATH:
                return await self.async_step_pick_radio()

            port = ports[list_of_ports.index(user_selection)]
            dev_path = await self.hass.async_add_executor_job(
                usb.get_serial_by_id, port.device
            )
            auto_detected_data = await detect_radios(dev_path)
            if auto_detected_data is not None:
                title = f"{port.description}, s/n: {port.serial_number or 'n/a'}"
                title += f" - {port.manufacturer}" if port.manufacturer else ""
                return self.async_create_entry(
                    title=title,
                    data=auto_detected_data,
                )

            # did not detect anything
            self._device_path = dev_path
            return await self.async_step_pick_radio()

        schema = vol.Schema({vol.Required(CONF_DEVICE_PATH): vol.In(list_of_ports)})
        return self.async_show_form(step_id="user", data_schema=schema)

    async def async_step_pick_radio(self, user_input=None):
        """Select radio type."""

        if user_input is not None:
            self._radio_type = RadioType.get_by_description(user_input[CONF_RADIO_TYPE])
            return await self.async_step_port_config()

        schema = {vol.Required(CONF_RADIO_TYPE): vol.In(sorted(RadioType.list()))}
        return self.async_show_form(
            step_id="pick_radio",
            data_schema=vol.Schema(schema),
        )

    async def async_step_usb(self, discovery_info: DiscoveryInfoType):
        """Handle usb discovery."""
        vid = discovery_info["vid"]
        pid = discovery_info["pid"]
        serial_number = discovery_info["serial_number"]
        device = discovery_info["device"]
        manufacturer = discovery_info["manufacturer"]
        description = discovery_info["description"]
        dev_path = await self.hass.async_add_executor_job(usb.get_serial_by_id, device)
        unique_id = f"{vid}:{pid}_{serial_number}_{manufacturer}_{description}"
        if current_entry := await self.async_set_unique_id(unique_id):
            self._abort_if_unique_id_configured(
                updates={
                    CONF_DEVICE: {
                        **current_entry.data.get(CONF_DEVICE, {}),
                        CONF_DEVICE_PATH: dev_path,
                    },
                }
            )
        # Check if already configured
        if self._async_current_entries():
            return self.async_abort(reason="single_instance_allowed")

        # If they already have a discovery for deconz
        # we ignore the usb discovery as they probably
        # want to use it there instead
        for flow in self.hass.config_entries.flow.async_progress():
            if flow["handler"] == DECONZ_DOMAIN:
                return self.async_abort(reason="not_zha_device")
        for entry in self.hass.config_entries.async_entries(DECONZ_DOMAIN):
            if entry.source != config_entries.SOURCE_IGNORE:
                return self.async_abort(reason="not_zha_device")

        self._device_path = dev_path
        self._title = usb.human_readable_device_name(
            dev_path,
            serial_number,
            manufacturer,
            description,
            vid,
            pid,
        )
        self._set_confirm_only()
        self.context["title_placeholders"] = {CONF_NAME: self._title}
        return await self.async_step_confirm()

    async def async_step_confirm(self, user_input=None):
        """Confirm a discovery."""
        if user_input is not None:
            auto_detected_data = await detect_radios(self._device_path)
            if auto_detected_data is None:
                # This path probably will not happen now that we have
                # more precise USB matching unless there is a problem
                # with the device
                return self.async_abort(reason="usb_probe_failed")
            return self.async_create_entry(
                title=self._title,
                data=auto_detected_data,
            )

        return self.async_show_form(
            step_id="confirm",
            description_placeholders={CONF_NAME: self._title},
            data_schema=vol.Schema({}),
        )

    async def async_step_zeroconf(self, discovery_info: DiscoveryInfoType):
        """Handle zeroconf discovery."""
        # Hostname is format: livingroom.local.
        local_name = discovery_info["hostname"][:-1]
        node_name = local_name[: -len(".local")]
        host = discovery_info[CONF_HOST]
        device_path = f"socket://{host}:6638"

        if current_entry := await self.async_set_unique_id(node_name):
            self._abort_if_unique_id_configured(
                updates={
                    CONF_DEVICE: {
                        **current_entry.data.get(CONF_DEVICE, {}),
                        CONF_DEVICE_PATH: device_path,
                    },
                }
            )

        # Check if already configured
        if self._async_current_entries():
            return self.async_abort(reason="single_instance_allowed")

        self.context["title_placeholders"] = {
            CONF_NAME: node_name,
        }

        self._device_path = device_path
        self._radio_type = (
            RadioType.ezsp.name if "efr32" in local_name else RadioType.znp.name
        )

        return await self.async_step_port_config()

    async def async_step_port_config(self, user_input=None):
        """Enter port settings specific for this type of radio."""
        errors = {}
        app_cls = RadioType[self._radio_type].controller

        if user_input is not None:
            self._device_path = user_input.get(CONF_DEVICE_PATH)
            if await app_cls.probe(user_input):
                serial_by_id = await self.hass.async_add_executor_job(
                    usb.get_serial_by_id, user_input[CONF_DEVICE_PATH]
                )
                user_input[CONF_DEVICE_PATH] = serial_by_id
                return self.async_create_entry(
                    title=user_input[CONF_DEVICE_PATH],
                    data={CONF_DEVICE: user_input, CONF_RADIO_TYPE: self._radio_type},
                )
            errors["base"] = "cannot_connect"

        schema = {
            vol.Required(
                CONF_DEVICE_PATH, default=self._device_path or vol.UNDEFINED
            ): str
        }
        radio_schema = app_cls.SCHEMA_DEVICE.schema
        if isinstance(radio_schema, vol.Schema):
            radio_schema = radio_schema.schema

        source = self.context.get("source")
        for param, value in radio_schema.items():
            if param in SUPPORTED_PORT_SETTINGS:
                schema[param] = value
                if source == config_entries.SOURCE_ZEROCONF and param == CONF_BAUDRATE:
                    schema[param] = 115200

        return self.async_show_form(
            step_id="port_config",
            data_schema=vol.Schema(schema),
            errors=errors,
        )

async def detect_radios(dev_path: str) -> dict[str, Any] | None:
    """Probe all radio types on the device port."""
    for radio in RadioType:
        dev_config = radio.controller.SCHEMA_DEVICE({CONF_DEVICE_PATH: dev_path})
        probe_result = await radio.controller.probe(dev_config)
        if probe_result:
            if isinstance(probe_result, dict):
                return {CONF_RADIO_TYPE: radio.name, CONF_DEVICE: probe_result}
            return {CONF_RADIO_TYPE: radio.name, CONF_DEVICE: dev_config}

    return None


text:
swagger-caster-middleware
==============

PHP middleware that casts parameters into their respective types based on their [swagger](http://swagger.io/) definition. Information is stored in a AvalancheDevelopment\ParsedSwaggerInterface attached to a Request object.

[![Build Status](https://travis-ci.org/avalanche-development/swagger-caster-middleware.svg?branch=master)](https://travis-ci.org/avalanche-development/swagger-caster-middleware)
[![Code Climate](https://codeclimate.com/github/avalanche-development/swagger-caster-middleware/badges/gpa.svg)](https://codeclimate.com/github/avalanche-development/swagger-caster-middleware)
[![Test Coverage](https://codeclimate.com/github/avalanche-development/swagger-caster-middleware/badges/coverage.svg)](https://codeclimate.com/github/avalanche-development/swagger-caster-middleware/coverage)

## Installation

It's recommended that you use [Composer](https://getcomposer.org/) to install swagger-caster-middleware.

```bash
$ composer require avalanche-development/swagger-caster-middleware
```

swagger-caster-middleware requires PHP 5.6 or newer.

## Usage

This middleware expects a AvalancheDevelopment\ParsedSwaggerInterface attribute already filled out and attached to the Request object. Without it, all of logic will be skipped. Otherwise, the middleware will walk through the params array and cast each value, overwriting the original 'value' attribute with the casted one.

```php
$caster = new AvalancheDevelopment\SwaggerCasterMiddleware\Caster();
$result = $caster($request, $response, $next); // middleware signature
```

It is recommended that this middleware occurs after AvalancheDevelopment\SwaggerRouterMiddleware, which will parse out and attach the AvalancheDevelopment\ParsedSwaggerInterface. Without it you'll need to reinvent the swagger/request parser.

### Interface

Once everything passes through successfully, each param in the AvalancheDevelopment\ParsedSwaggerInterface will have the following attributes.

```php
'swagger' => [
    ...,
    'params' => [
        'originalValue' => 'true',
        'type' => 'boolean',
        'value' => true,
    ],
]
```

### Invalid Requests

If there is an error with parameter casting that appears to be an issue with request, a peel BadRequest is thrown. An error handler can listen for these HttpErrorInterface exceptions and respond appropriately. This is most relevant with date and date-time properties.

## Development

This library is still being developed and some bugs may be experienced. Feel free to add issues or submit pull requests when road bumps are noticed.

### Tests

To execute the test suite, you'll need phpunit (and to install package with dev dependencies).

```bash
$ phpunit
```

## License

swagger-caster-middleware is licensed under the MIT license. See [License File](LICENSE) for more information.


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

import java.text.MessageFormat;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.flowable.ui.admin.domain.ServerConfig;
import org.flowable.ui.admin.service.engine.exception.FlowableServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

/**
 * Service for invoking Flowable REST services.
 */
@Service
public class TaskService {

    public static final String HISTORIC_TASK_LIST_URL = "history/historic-task-instances";
    public static final String HISTORIC_TASK_QUERY_URL = "query/historic-task-instances";
    public static final String HISTORIC_TASK_URL = "history/historic-task-instances/{0}";
    public static final String RUNTIME_TASK_URL = "runtime/tasks/{0}";
    public static final String HISTORIC_VARIABLE_INSTANCE_LIST_URL = "history/historic-variable-instances";
    public static final String HISTORIC_TASK_IDENTITY_LINK_LIST_URL = "history/historic-task-instances/{0}/identitylinks";

    public static final String[] TASK_FILTERS = new String[] { "taskNameLike", "taskAssigneeLike", "taskOwner", "finished",
            "dueDateAfter", "dueDateBefore", "taskCompletedAfter", "taskCompletedBefore", "taskCreatedAfter", "taskCreatedBefore", "parentTaskId", "processInstanceId" };

    private static final String DEFAULT_SUBTASK_RESULT_SIZE = "1024";
    private static final String DEFAULT_VARIABLE_RESULT_SIZE = "1024";

    @Autowired
    protected FlowableClientService clientUtil;

    @Autowired
    protected ObjectMapper objectMapper;

    public JsonNode listTasks(ServerConfig serverConfig, ObjectNode bodyNode) {

        JsonNode resultNode = null;
        try {
            URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_QUERY_URL);

            String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode);
            HttpPost post = clientUtil.createPost(uri, serverConfig);

            post.setEntity(clientUtil.createStringEntity(bodyNode.toString()));
            resultNode = clientUtil.executeRequest(post, serverConfig);
        } catch (Exception e) {
            throw new FlowableServiceException(e.getMessage(), e);
        }
        return resultNode;
    }

    public JsonNode getTask(ServerConfig serverConfig, String taskId, boolean runtime) {
        if (taskId == null) {
            throw new IllegalArgumentException("Task id is required");
        }

        URIBuilder builder = null;
        if (runtime) {
            builder = clientUtil.createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId));
        } else {
            builder = clientUtil.createUriBuilder(MessageFormat.format(HISTORIC_TASK_URL, taskId));
        }

        HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
        return clientUtil.executeRequest(get, serverConfig);
    }

    /**
     * Delete a task.
     */
    public void deleteTask(ServerConfig serverConfig, String taskId) {
        if (taskId == null) {
            throw new IllegalArgumentException("Task id is required");
        }

        JsonNode taskNode = getTask(serverConfig, taskId, false);
        if (taskNode.has("endTime")) {

            JsonNode endTimeNode = taskNode.get("endTime");
            if (endTimeNode != null && !endTimeNode.isNull() && StringUtils.isNotEmpty(endTimeNode.asText())) {

                // Completed task
                URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(HISTORIC_TASK_URL, taskId));
                HttpDelete delete = new HttpDelete(clientUtil.getServerUrl(serverConfig, builder));
                clientUtil.executeRequestNoResponseBody(delete, serverConfig, HttpStatus.SC_NO_CONTENT);

            } else {

                // Not completed task
                URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId) + "?cascadeHistory=true");
                HttpDelete delete = new HttpDelete(clientUtil.getServerUrl(serverConfig, builder));
                clientUtil.executeRequestNoResponseBody(delete, serverConfig, HttpStatus.SC_NO_CONTENT);

            }
        }

    }

    public void executeTaskAction(ServerConfig serverConfig, String taskId, JsonNode actionRequest) {
        if (taskId == null) {
            throw new IllegalArgumentException("Task id is required");
        }

        URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId));
        HttpPost post = clientUtil.createPost(builder, serverConfig);

        post.setEntity(clientUtil.createStringEntity(actionRequest));
        clientUtil.executeRequestNoResponseBody(post, serverConfig, HttpStatus.SC_OK);
    }

    public void updateTask(ServerConfig serverConfig, String taskId, JsonNode actionRequest) {
        if (taskId == null) {
            throw new IllegalArgumentException("Task id is required");
        }
        URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(RUNTIME_TASK_URL, taskId));
        HttpPut put = clientUtil.createPut(builder, serverConfig);
        put.setEntity(clientUtil.createStringEntity(actionRequest));
        clientUtil.executeRequestNoResponseBody(put, serverConfig, HttpStatus.SC_OK);
    }

    public JsonNode getSubTasks(ServerConfig serverConfig, String taskId) {
        URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_TASK_LIST_URL);
        builder.addParameter("parentTaskId", taskId);
        builder.addParameter("size", DEFAULT_SUBTASK_RESULT_SIZE);

        HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
        return clientUtil.executeRequest(get, serverConfig);
    }

    public JsonNode getVariables(ServerConfig serverConfig, String taskId) {
        URIBuilder builder = clientUtil.createUriBuilder(HISTORIC_VARIABLE_INSTANCE_LIST_URL);
        builder.addParameter("taskId", taskId);
        builder.addParameter("size", DEFAULT_VARIABLE_RESULT_SIZE);
        builder.addParameter("sort", "variableName");

        HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
        return clientUtil.executeRequest(get, serverConfig);
    }

    public JsonNode getIdentityLinks(ServerConfig serverConfig, String taskId) {
        URIBuilder builder = clientUtil.createUriBuilder(MessageFormat.format(HISTORIC_TASK_IDENTITY_LINK_LIST_URL, taskId));

        HttpGet get = new HttpGet(clientUtil.getServerUrl(serverConfig, builder));
        return clientUtil.executeRequest(get, serverConfig);
    }
}


text:
Module Module1

    Sub Main()
        'Constantes
        Const precioHoraNormal As Single = 10
        Const precioHoraExtra As Single = 15

        'Datos de entrada
        Console.WriteLine("Teclea el número de horas que ha trabajado")
        Dim horasTrabajadas As Byte = Byte.Parse(Console.ReadLine())

        Console.WriteLine("Teclea el estado civil del trabajador")
        Dim estadoCivil As Char = Char.ToUpper(CChar(Console.ReadLine()))

        'Validación estado Civil
        'If (estadoCivil.CompareTo("S"c) = 0 or estadoCivil.CompareTo("C"c) = 0 or _
        '    estadoCivil.CompareTo("D"c) = 0 or estadoCivil.CompareTo("V"c) = 0) Then
        If (estadoCivil = "S" Or estadoCivil = "C" Or
            estadoCivil = "D" Or estadoCivil = "V") Then

            Console.WriteLine("Teclea el nivel de estudios del trabajador")
            Dim nivelEstudios As Char = Char.ToUpper(CChar(Console.ReadLine()))

            'Validación nivel Estudios
            'If (nivelEstudios.CompareTo("P") <> 0 And nivelEstudios.CompareTo("M") <> 0 And _
            'nivelEstudios.CompareTo("S") <> 0) Then
            If (nivelEstudios <> "P" And nivelEstudios <> "M" And nivelEstudios <> "S") Then
                Console.WriteLine("El nivel de estudios tecleado no es correcto")
            Else
                'Operaciones para calcular la nómina
                Dim sueldo As Single

                If (horasTrabajadas > 40) Then ' 40 podría ser otra constante
                    sueldo = (horasTrabajadas - 40) * precioHoraExtra + 40 * precioHoraNormal
                Else
                    sueldo = horasTrabajadas * precioHoraNormal
                End If

                Const plus As Single = 100.0F
                'Dim estadoEstudios As String = estadoCivil & nivelEstudios
                'If (estadoEstudios = "SP" Or estadoEstudios = "VS" Or estadoEstudios = "SM" Or estadoEstudios = "CS" Or estadoEstudios = "VP" Or estadoEstudios = "SS" Or estadoEstudios = "DS") Then
                '   sueldo += plus
                'End If

                ''Primera solución
                'If (nivelEstudios = "S" Or estadoCivil = "S" Or (nivelEstudios = "P" And estadoCivil = "V")) Then
                '    sueldo += plus
                'End If

                ''Segunda solución
                'If (nivelEstudios.CompareTo("S") = 0) Then
                '    sueldo = sueldo + plus
                'Else
                '    If (estadoCivil.CompareTo("S") = 0) Then
                '        sueldo += plus
                '    Else
                '        If estadoCivil.CompareTo("V") = 0 And nivelEstudios.CompareTo("P") = 0 Then
                '            sueldo += plus
                '        End If
                '    End If
                'End If

                ''Tercera solución
                Dim combo As String = estadoCivil & nivelEstudios
                Select Case combo
                        Case "SP", "VS", "SM", "CS", "VP", "SS", "DS"
                        sueldo += plus
                End Select

                    'Salida
                    Console.WriteLine("El sueldo de este trabajador asciende a " & sueldo)
                End If
                Else
            Console.WriteLine("El estado civil tecleado no es correcto")
        End If

        Console.ReadLine()

    End Sub

End Module


text:
function [H,X]=loadhead(flnm,ncols);
% loadhead: read in time series matrix with column headings using fscanf; BMDP
% CALL: [H,X]=loadhead(flnm,ncols);
%
% Meko 6-29-97
%
%
%***************  IN ***************************
%
% flnm (1 x ?)s filename, possibly including path of file with input data
% ncols (1 x 1)i number of columns, in the input matrix, including years col
%
%**************** OUT *******************************
%
% H (nsers x  nchars)s   matrix of headings for the cols
%			nsers is one less than ncols
%			nchars is the maximum length of any heading input
%
%
%******************** NOTE ********************************
%
% Some heading for the years column is assumed in the input file
% Column headings are delineated by spaces

hmsg=msgbox('NOTE: THIS FUNCTION USES FSCANF, WHICH WILL NOT WORK WITH NaNs');

% Open input file
fid1=fopen(flnm,'r');

%******************* BUILD STRING MATRIX OF COLUMN HEADINGS

% Get the header line
h = fgetl(fid1);
hlen = length(h);

h = strjust(h); % right justify the header

% Remove any leading blanks
h=fliplr(deblank(fliplr(h)));

% h should now begin with the first char of the year header and end with
% the last char of the last col header.

% Add a single space at left of header and right.  Then any change from space to
% non space will mark start of a col header; any change from
% nonspace to space will mark end of header
h = [ ' ' h ' '];

hs= isspace(h);
dh = diff(hs);
igo = find(dh== -1) + 1;
isp = find(dh==1) + 1;

% Check that number of identified headers equals number of cols
if (length(igo) ~= length(isp)) | length(igo)~=ncols;
   error('Number of identified column headings does not match number of cols');
end

% Find max  number of chars in any col heading, and initialize storage matrix for names
max1 = max(isp-igo+1);
H = blanks(max1);
H=repmat(H,ncols,1);

% Store headings, left justified
ilen=isp-igo+1;
for n = 1:ncols;
   i1=igo(n); i2=isp(n);
   H(n,1:ilen(n)) = h(i1:i2);
end

%**********************  GET THE DATA FOLLOWING THE HEADINGS

% Put data in col vector
x=fscanf(fid1,'%g');

% Check that length x divisible by number of cols
if rem(length(x),ncols)~=0;
   error('Length of x does not equal ncols');
end

% Compute number of years of data
nyrs = length(x)/ncols;

% Re-form the matrix
X=(reshape(x,ncols,nyrs))';
fclose(fid1);


text:
Modify Reservation

To modify your reservation, please enter the confirmation number sent to you via email

<form id="frmReservationModify" name="frmReservationModify" method="post" action="pages/roomchange.php">
    Confirmation Number:

    <input type="text" name="confirmationCode" id="ed" class="validate_string" />
    <input name="" type="submit" value="Continue" id="SUBMIT" class="button" />
</form>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="primary">@color/twitter_blue</color>
    <color name="twitter_blue">#1da1f2</color>
    <color name="twitter_light_blue">#801da1f2</color>
    <color name="twitter_dark_gray">#657786</color>
    <color name="twitter_light_gray">#AAB8C2</color>
    <color name="twitter_red">#e0245e</color>
    <color name="twitter_red_light">#70e0245e</color>
</resources>


text:
cask 'font-freckle-face' do
  version :latest
  sha256 :no_check

  # github.com/google/fonts was verified as official when first introduced to the cask
  url 'https://github.com/google/fonts/raw/master/ofl/freckleface/FreckleFace-Regular.ttf'
  name 'Freckle Face'
  homepage 'https://www.google.com/fonts/specimen/Freckle+Face'

  font 'FreckleFace-Regular.ttf'
end


text:
/**
 * @file
 *
 * OS dependent logging.
 */

/******************************************************************************
 * Copyright AllSeen Alliance. All rights reserved.
 *
 *    Permission to use, copy, modify, and/or distribute this software for any
 *    purpose with or without fee is hereby granted, provided that the above
 *    copyright notice and this permission notice appear in all copies.
 *
 *    THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *    WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *    MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *    ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *    WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *    ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *    OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 ******************************************************************************/
#ifndef _QCC_OS_LOGGER_H
#define _QCC_OS_LOGGER_H

#include <qcc/platform.h>
#include <qcc/Debug.h>

/**
 * Get the OS specific logger if there is one.
 *
 * @param useOSLog
 *
 * @return  Returns a function pointer to the OS-specific logger.
 */
QCC_DbgMsgCallback QCC_GetOSLogger(bool useOSLog);

#endif


text:
[![Build Status](https://travis-ci.org/getopenmono/mono_framework.svg?branch=master)](https://travis-ci.org/getopenmono/mono_framework) [![AppVeyor Build Status](https://ci.appveyor.com/api/projects/status/github/getopenmono/mono_framework?branch=master&svg=true "AppVeyor Build Status")](https://ci.appveyor.com/project/stoffera/mono_framework) [![Docker Build Statu](https://img.shields.io/docker/build/monolit/framework.svg)](https://hub.docker.com/r/monolit/framework/) [![Documentation Status](https://readthedocs.org/projects/mono-developer-documentation/badge/?version=latest)](http://developer.openmono.com/en/latest/?badge=latest) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE.txt) [![Twitter Follow](https://img.shields.io/twitter/follow/getopenmono.svg?style=social&label=Follow)](https://twitter.com/getopenmono)

This is a framework for developing [Mono](http://openmono.com) applications.  For documentation on how to install and use this framework, see the [developer site](http://developer.openmono.com/).  If you want to generate the documentation, see [DOXYGEN.md](src/DOXYGEN.md).

This text describes how to build the framework.

## Setup

Install version 5 of the [ARM GCC Embedded toolchain](https://launchpad.net/gcc-arm-embedded).  Then add the path to your command-line environment if needed:

* MacOS: `/usr/local/openmono/gcc-arm-none-eabi-5_2-2015q4/bin`
* MacOS: XCode.  If problems, see [solution](https://bugreports.qt.io/browse/QTCREATORBUG-17494).
* Windows: `C:/openmono/gcc-arm-none-eabi-5_2-2015q4/bin`

## Building

Run

```
$ bash resources/setup_icons.sh resources/icons.mk.tmp
```

(If you have problems with XCode, you might need to run `sudo xcode-select -s /Applications/Xcode.app/Contents/Developer`.)

Run
```
$ make release
```
to compile a new version of the framework into the `dist` folder.  The result is all header files and 4 static libraries:

* `mono_framework.a` : This framework.
* `mbedlib.a` : The mbed library.
* `monoCyLib.a` : The Cypress hardware library.
* `CyComponentLibrary.a` : Cypress dependencies.

To use these newly created files instead of the ones from the [official release](http://developer.openmono.com/en/latest/getting-started/install.html), overwrite the official file:

* MacOS: `sudo cp -r dist/mono/* /usr/local/openmono/mono/`
* Windows: Copy the `dist/mono` contents to `c:/OpenMono/mono`
* Linux: `sudo cp -r dist/mono/* /usr/lib/openmono/mono/`


text:
from nova.compute import task_states
from nova.compute import vm_states

_VM_TASK_STATE_NEXT_VM_STATE_MAP = {
    task_states.SPAWNING: [vm_states.ACTIVE],
    task_states.PAUSING: [vm_states.PAUSED],
    task_states.UNPAUSING: [vm_states.ACTIVE],
    task_states.SUSPENDING: [vm_states.SUSPENDED],
    task_states.RESUMING: [vm_states.ACTIVE],
    task_states.POWERING_OFF: [vm_states.STOPPED],
    task_states.POWERING_ON: [vm_states.ACTIVE],
    task_states.RESCUING: [vm_states.RESCUED],
    task_states.UNRESCUING: [vm_states.ACTIVE],
    task_states.REBUILDING: [vm_states.ACTIVE],
    task_states.REBUILD_BLOCK_DEVICE_MAPPING: [vm_states.ACTIVE],
    task_states.REBUILD_SPAWNING: [vm_states.ACTIVE],
    task_states.MIGRATING: [vm_states.ACTIVE],
    task_states.RESTORING: [vm_states.ACTIVE],
    task_states.SHELVING: [vm_states.SHELVED, vm_states.SHELVED_OFFLOADED],
    task_states.SHELVING_IMAGE_PENDING_UPLOAD: [vm_states.SHELVED,
                                                vm_states.SHELVED_OFFLOADED],
    task_states.SHELVING_IMAGE_UPLOADING: [vm_states.SHELVED,
                                           vm_states.SHELVED_OFFLOADED],
    task_states.SHELVING_OFFLOADING: [vm_states.SHELVED_OFFLOADED],
    task_states.UNSHELVING: [vm_states.ACTIVE]
}

def expect_vm_states(task_state):
    expect_states = _VM_TASK_STATE_NEXT_VM_STATE_MAP.get(task_state, [])
    if expect_states:
        expect_states = expect_states + [vm_states.ERROR]
    return expect_states


text:
BHPSOWM_FUNCTION=18
BHPSOWM_OPTIMAL=-4189.829
cd ../out/production/src/
for (( i = 0; i < 50; i++ ))
do
	scala application.TrainBinaryHPSOWM $BHPSOWM_FUNCTION $BHPSOWM_OPTIMAL -500 500 > ../../../cmp_result/$BHPSOWM_FUNCTION/hpsowm_result_$i
	scala application.TrainBinaryPSO $BHPSOWM_FUNCTION $BHPSOWM_OPTIMAL -500 500 > ../../../cmp_result/$BHPSOWM_FUNCTION/bpso_result_$i
	scala application.TrainBinaryGA $BHPSOWM_FUNCTION $BHPSOWM_OPTIMAL -500 500 > ../../../cmp_result/$BHPSOWM_FUNCTION/ga_result_$i
done


text:
import tensorflow as tf
import numpy as np

from neupy.utils import tensorflow_session
from neupy.core.properties import BoundedProperty, ProperFractionProperty
from .base import BaseOptimizer

__all__ = ('RPROP', 'IRPROPPlus')

class RPROP(BaseOptimizer):
    """
    Resilient backpropagation (RPROP) is an optimization
    algorithm for supervised learning.

    RPROP algorithm takes into account only direction of the gradient
    and completely ignores its magnitude. Every weight values has a unique
    step size associated with it (by default all of the are equal to ``step``).

    The rule is following, when gradient direction changes (sign of the
    gradient) we decrease step size for specific weight multiplying it by
    ``decrease_factor`` and if sign stays the same than we increase step
    size for this specific weight multiplying it by ``increase_factor``.

    The step size is always bounded by ``minstep`` and ``maxstep``.

    Notes
    -----
    Algorithm doesn't work with mini-batches.

    Parameters
    ----------
    minstep : float
        Minimum possible value for step. Defaults to ``0.001``.

    maxstep : float
        Maximum possible value for step. Defaults to ``10``.

    increase_factor : float
        Increase factor for step in case when gradient doesn't change
        sign compare to previous epoch.

    decrease_factor : float
        Decrease factor for step in case when gradient changes sign
        compare to previous epoch.

    {BaseOptimizer.Parameters}

    Attributes
    ----------
    {BaseOptimizer.Attributes}

    Methods
    -------
    {BaseOptimizer.Methods}

    Examples
    --------
    >>> import numpy as np
    >>> from neupy import algorithms
    >>> from neupy.layers import *
    >>>
    >>> x_train = np.array([[1, 2], [3, 4]])
    >>> y_train = np.array([[1], [0]])
    >>>
    >>> network = Input(2) >> Sigmoid(3) >> Sigmoid(1)
    >>> optimizer = algorithms.RPROP(network)
    >>> optimizer.train(x_train, y_train)

    See Also
    --------
    :network:`IRPROPPlus` : iRPROP+ algorithm.
    :network:`GradientDescent` : GradientDescent algorithm.
    """

    # This properties correct upper and lower bounds for steps.
    minstep = BoundedProperty(default=0.001, minval=0)
    maxstep = BoundedProperty(default=10, minval=0)

    # This properties increase/decrease step by dividing it to
    # some coefficient.
    increase_factor = BoundedProperty(minval=1, default=1.2)
    decrease_factor = ProperFractionProperty(default=0.5)

    def update_prev_delta(self, prev_delta):
        return prev_delta

    def init_train_updates(self):
        updates = []

        variables = []
        for (_, _), variable in self.network.variables.items():
            if variable.trainable:
                variables.append(variable)

        gradients = tf.gradients(self.variables.loss, variables)

        for parameter, gradient in zip(variables, gradients):
            with tf.variable_scope(parameter.op.name):
                steps = tf.Variable(
                    # Steps will be decreased after the first iteration,
                    # because all previous gradients are equal to zero.
                    # In order to make sure that network will use the same
                    # step per every weight we re-scale step and after the
                    # first iteration it will be multiplied by
                    # ``decrease_factor`` and scaled back to the default
                    # step value.
                    tf.ones_like(parameter) * self.step,
                    name="steps",
                    dtype=tf.float32,
                )
                prev_delta = tf.Variable(
                    tf.zeros(parameter.shape),
                    name="prev-delta",
                    dtype=tf.float32,
                )
                # We collect only signs since it ensures numerical stability
                # after multiplication when we deal with small numbers.
                prev_gradient_sign = tf.Variable(
                    tf.zeros(parameter.shape),
                    name="prev-grad-sign",
                    dtype=tf.float32,
                )

            updated_prev_delta = self.update_prev_delta(prev_delta)
            gradient_sign = tf.sign(gradient)

            grad_sign_product = gradient_sign * prev_gradient_sign
            gradient_changed_sign = tf.equal(grad_sign_product, -1)

            updated_steps = tf.clip_by_value(
                tf.where(
                    tf.equal(grad_sign_product, 1),
                    steps * self.increase_factor,
                    tf.where(
                        gradient_changed_sign,
                        steps * self.decrease_factor,
                        steps,
                    )
                ),
                self.minstep,
                self.maxstep,
            )
            parameter_delta = tf.where(
                gradient_changed_sign,
                # If we subtract previous negative weight update it means
                # that we will revert weight update that has been  applied
                # in the previous iteration.
                -updated_prev_delta,
                updated_steps * gradient_sign,
            )
            # Making sure that during the next iteration sign, after
            # we multiplied by the new gradient, won't be negative.
            # Otherwise, the same roll back using previous delta
            # won't make much sense.
            clipped_gradient_sign = tf.where(
                gradient_changed_sign,
                tf.zeros_like(gradient_sign),
                gradient_sign,
            )

            updates.extend([
                (parameter, parameter - parameter_delta),
                (steps, updated_steps),
                (prev_gradient_sign, clipped_gradient_sign),
                (prev_delta, parameter_delta),
            ])

        return updates

class IRPROPPlus(RPROP):
    """
    iRPROP+ is an optimization algorithm for supervised learning.
    This is a variation of the :network:`RPROP` algorithm.

    Parameters
    ----------
    {RPROP.minstep}

    {RPROP.maxstep}

    {RPROP.increase_factor}

    {RPROP.decrease_factor}

    {BaseOptimizer.regularizer}

    {BaseOptimizer.network}

    {BaseOptimizer.loss}

    {BaseNetwork.show_epoch}

    {BaseNetwork.shuffle_data}

    {BaseNetwork.signals}

    {Verbose.verbose}

    Methods
    -------
    {BaseSkeleton.predict}

    {BaseOptimizer.train}

    {BaseSkeleton.fit}

    Notes
    -----
    {RPROP.Notes}

    Examples
    --------
    >>> import numpy as np
    >>> from neupy import algorithms
    >>> from neupy.layers import *
    >>>
    >>> x_train = np.array([[1, 2], [3, 4]])
    >>> y_train = np.array([[1], [0]])
    >>>
    >>> network = Input(2) >> Sigmoid(3) >> Sigmoid(1)
    >>> optimizer = algorithms.IRPROPPlus(network)
    >>> optimizer.train(x_train, y_train)

    References
    ----------
    [1] Christian Igel, Michael Huesken (2000)
        Improving the Rprop Learning Algorithm

    See Also
    --------
    :network:`RPROP` : RPROP algorithm.
    :network:`GradientDescent` : GradientDescent algorithm.
    """
    def init_functions(self):
        self.variables.update(
            last_error=tf.Variable(np.nan, name='irprop-plus/last-error'),
            previous_error=tf.Variable(
                np.nan, name='irprop-plus/previous-error'),
        )
        super(IRPROPPlus, self).init_functions()

    def one_training_update(self, X_train, y_train):
        if len(self.errors.train) >= 2:
            previous_error, last_error = self.errors.train[-2:]
            session = tensorflow_session()

            self.variables.last_error.load(last_error, session)
            self.variables.previous_error.load(previous_error, session)

        return super(IRPROPPlus, self).one_training_update(X_train, y_train)

    def update_prev_delta(self, prev_delta):
        last_error = self.variables.last_error
        prev_error = self.variables.previous_error

        return tf.where(
            # We revert weight when gradient changed the sign only in
            # cases when error increased. Otherwise we don't apply any
            # update for this weight.
            last_error > prev_error,
            prev_delta,
            tf.zeros_like(prev_delta),
        )


text:
@class CThrowBottleWrap;

@interface CThrowBottleEvent : NetCmdEvent
{
    CThrowBottleWrap *m_wrapThrowBottle;
}

@property(retain, nonatomic) CThrowBottleWrap *m_wrapThrowBottle; // @synthesize m_wrapThrowBottle;
- (void).cxx_destruct;
- (void)NotifyFromPrtl:(unsigned int)arg1 MessageInfo:(id)arg2;
- (_Bool)Start:(unsigned int *)arg1 RetInfo:(id)arg2;
- (_Bool)SetEventInfo:(id)arg1;
- (void)dealloc;
- (id)init;

@end


text:
package com.corylucasjeffery.couponassistant.activities;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

import com.corylucasjeffery.couponassistant.BMPtoBlob;
import com.corylucasjeffery.couponassistant.CameraPreview;
import com.corylucasjeffery.couponassistant.DateChooserDialog;
import com.corylucasjeffery.couponassistant.ManualEntryDialog;
import com.corylucasjeffery.couponassistant.ParseUPC;
import com.corylucasjeffery.couponassistant.PhpWrapper;
import com.corylucasjeffery.couponassistant.R;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import java.io.IOException;
import java.util.concurrent.ExecutionException;

public class MainActivity extends FragmentActivity
        implements View.OnClickListener, DatePickerDialog.OnDateSetListener {

    private final String TAG = "MAIN";
    private Camera mCamera = null;
    private CameraPreview mPreview = null;
    private String exp_date = "";
    private String upc = "";
    private String imageBlob;
    private Bitmap image;
    private int clicks = 0;
    private Context context;
    private FrameLayout preview;
    private BMPtoBlob imageConvert;
    public static final String PREFS_CART = "CouponShoppingCart";

    public static final String EXTRA_MESSAGE_UPC =
            "com.corylucasjeffery.couponassistant.activities.MESSAGE_UPC";
    public static final String EXTRA_MESSAGE_FILE_NAME =
            "com.corylucasjeffery.couponassistant.activities.MESSAGE_IMAGE";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        initializeClickyThings();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
        preview.removeView(mPreview);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mCamera == null)
        {
            mCamera = getCameraInstance();
            if(mCamera != null) {
                mPreview = new CameraPreview(this, mCamera);
            }
        }
        if (mPreview != null) {
            preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);
            mCamera.startPreview();
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId()==R.id.scan_button){
            //When the scan button is clicked, a picture is taken of the coupon
            //to upload to the database. Once the picture has been received, the call
            //can be made to the barcode scanner for it to use the camera.
            Camera.PictureCallback mCall = new Camera.PictureCallback() {
                @Override
                public void onPictureTaken(byte[] bytes, Camera camera) {
                    image = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                    //instantiate ZXing integration class
                    IntentIntegrator scanIntegrator = new IntentIntegrator(MainActivity.this);
                    //start scanning
                    scanIntegrator.initiateScan();
                }
            };
            mCamera.takePicture(null, null, mCall);
        }
        else if (v.getId()==R.id.footer_shopping_cart) {
            openCart();
        }
        else if (v.getId()==R.id.footer_manual_add) {
            openManualEntry();
        }
    }

    public void initializeClickyThings() {
        Button scanButton = (Button) findViewById(R.id.scan_button);
        scanButton.setOnClickListener(this);

        ImageView cartImage = (ImageView) findViewById(R.id.footer_shopping_cart);
        cartImage.setOnClickListener(this);

        ImageView plusImage = (ImageView) findViewById(R.id.footer_manual_add);
        plusImage.setOnClickListener(this);
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        upc = "";
        //retrieve result of scanning - instantiate ZXing object
        IntentResult scanningResult =
                IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);

        //check we have a valid result
        if (scanningResult != null) {
            upc = scanningResult.getContents();
            if (upc != "")
            {
                ParseUPC parser = new ParseUPC();
                int barcodeType = parser.determineBarcode(upc);
                // check UPC and determine action
                if (barcodeType == ParseUPC.UPC_IS_ITEM)
                {
                    storeItemShowCoupons();
                }
                else
                {
                    storeCoupon();
                }
            }
            else
                Toast.makeText(this, "Scan failed, retry", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case R.id.menu_settings:
                openSettings();
                return true;
            case R.id.menu_login:
                openLogin();
                return true;
            case R.id.menu_shopping_cart:
                openCart();
                return true;
            case R.id.menu_stats:
                openStats();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    private void openSettings() {
        Intent intent = new Intent(context, SettingsActivity.class);
        startActivity(intent);
    }

    private void openLogin() {
        Intent intent = new Intent(context, LoginActivity.class);
        startActivity(intent);
    }

    private void openCart() {
        Intent intent = new Intent(context, CheckoutActivity.class);
        startActivity(intent);
    }

    private void openStats() {
        Log.v(TAG, "start statistics");
        Intent intent = new Intent(context, StatisticsActivity.class);
        startActivity(intent);
    }

    private void openManualEntry() {
        ManualEntryDialog dialog = new ManualEntryDialog();
        dialog.show(getFragmentManager(), "manualEntry");
    }

    public void storeItem() {
        PhpWrapper db = new PhpWrapper();
        boolean success = db.submitItem(upc);
        if (success)
            Toast.makeText(this, "Item submitted", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(this, "Item failed to submit", Toast.LENGTH_LONG).show();
    }

    public void storeItemShowCoupons() {
        storeItem();

        //open coupon activity
        Intent intent = new Intent(context, ShowCouponsActivity.class);
        String message = upc;
        intent.putExtra(EXTRA_MESSAGE_UPC, message);
        String file = "";
        intent.putExtra(EXTRA_MESSAGE_FILE_NAME, file);
        startActivity(intent);
    }

    public void storeCoupon() {
        //Begin image conversion so it can be working while user is selecting date
        this.imageConvert = new BMPtoBlob(image);
        this.imageConvert.execute();
        //popup, ask for exp-date
        Log.d(TAG, "Date chooser beginning.");
        DateChooserDialog dpd = new DateChooserDialog();
        dpd.show(getFragmentManager(), "DatePicker");
        // when picker finishes, it calls submitCoupon
    }

    public void submitCoupon() {
        PhpWrapper db = new PhpWrapper();
        Log.v(TAG, "upc in submit:"+upc);
        try {
            imageBlob = this.imageConvert.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        Log.d(TAG,"Submitting coupon.");
        boolean success = db.submitCoupon(upc, exp_date, imageBlob);
        if (success)
            Toast.makeText(this, "Coupon submitted", Toast.LENGTH_SHORT).show();
        else
            Toast.makeText(this, "Error, coupon not submitted", Toast.LENGTH_LONG).show();
    }

    public void getItemsFromCoupon() {
        //TODO implement getItemsFromCoupon()

    }

    //override of DateChooserDialog method
    @Override
    public void onDateSet(DatePicker view, int year, int month, int day) {
        if (clicks == 0) {
            String date =   Integer.toString(year) + "-" +
                            Integer.toString(month+1) + "-" +
                            Integer.toString(day);
            exp_date = date;
            submitCoupon();
            clicks++;
        }
        else  {
            clicks = 0;
        }
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }
}