text:
<?php

namespace TeAyudo\TeAyudoBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use TeAyudo\TeAyudoBundle\Entity\User;
use Symfony\Component\BrowserKit\Response;
use TeAyudo\TeAyudoBundle\Entity\Cycle;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Validator\Constraints\Date;

class CreateController extends Controller
{
	protected $error = '';
	protected $createSuccessMessage = '';

    public function showAction(Request $req)
    {
    	$usr= $this->get('security.context')->getToken()->getUser();
    	$userName = $usr->getName();
       return $this->render('TeAyudoBundle:creation:createCycle.html.twig',
       		array('pageTitle' => 'TeAyudo.org',
       		   		'username' => $userName,
       				'cycleForm' => $this->createCycleForm($req,$usr),
       				'error' => $this->getError(),
       				'createSuccessMessage' => $this->getCreateSuccessMessage()
       		));
    }

    public function createCycleForm($req,$usr) {
    	$cycleForm = $this->createFormBuilder ( new Cycle() )
    	->add('cycleType','choice', array(
    		'required'  => true,
    		'expanded' => true,
    		'choices'  => array('Necesito', 'Ofrezco')
		))
    	->add ( 'title', 'text' )
    	->add ( 'contactData', 'text' )
    	->add ( 'description', 'textarea' )
    	->add ( 'save', 'submit', array ('label' => 'Empezar Ciclo' )
    	)->getForm ();

    	$cycleForm->handleRequest ( $req );
    	if ($cycleForm->isValid ()) {
    		try{
    			$newCycle = $cycleForm->getData();
    			$newCycle->setDate(new \DateTime());
    			$newCycle->setEnded(false);
    			$newCycle->setActive(false);
    			$newCycle->setDenied(false);
    			$newCycle->setCoords($_POST["hiddenLatLng"]);
    			$newCycle->setUser($usr);
    			$em = $this->getDoctrine()->getEntityManager();
    			$em->persist($newCycle);
    			$em->flush($newCycle);
    			$this->setCreateSuccessMessage('Se ha abierto un nuevo Ciclo. Un Administrador de TeAyudo.org validará el mismo y luego será visible para los demás usuarios del sitio. ¡Muchas gracias por tu aporte!');
    		} catch (DBALException $e) {
    			$this->setError('ERROR: Ocurrió un error, inténtelo nuevamente');
    		}
    	}

    	return $cycleForm->createView ();
    }
	public function getError() {
		return $this->error;
	}
	public function setError($error) {
		$this->error = $error;
		return $this;
	}
	public function getCreateSuccessMessage() {
		return $this->createSuccessMessage;
	}
	public function setCreateSuccessMessage($successMessage) {
		$this->createSuccessMessage = $successMessage;
		return $this;
	}

}


text:
using System;
using Akka.Actor;
using Akka.Configuration;
using Akka.TestKit;
using Akka.Util.Internal;
using Xunit;

namespace Akka.Persistence.Cassandra.Tests
{
    /// <summary>
    /// Some integration tests for Cassandra Journal and Snapshot plugins.
    /// </summary>
    public class CassandraIntegrationSpec : Akka.TestKit.Xunit2.TestKit
    {
        private static readonly Config IntegrationConfig = ConfigurationFactory.ParseString(@"
            akka.persistence.journal.plugin = ""cassandra-journal""
            akka.persistence.snapshot-store.plugin = ""cassandra-snapshot-store""
            akka.persistence.publish-plugin-commands = on
            akka.test.single-expect-default = 10s
            cassandra-journal.partition-size = 5
            cassandra-journal.max-result-size = 3
        ");

        // Static so that each test run gets a different Id number
        private static readonly AtomicCounter ActorIdCounter = new AtomicCounter();

        private readonly string _actorId;

        public CassandraIntegrationSpec()
            : base(IntegrationConfig, "CassandraIntegration")
        {
            TestSetupHelpers.ResetJournalData(Sys);
            TestSetupHelpers.ResetSnapshotStoreData(Sys);

            // Increment actor Id with each test that's run
            int id = ActorIdCounter.IncrementAndGet();
            _actorId = string.Format("p{0}", id);
        }

        [Fact]
        public void Cassandra_journal_should_write_and_replay_messages()
        {
            // Start a persistence actor and write some messages to it
            var actor1 = Sys.ActorOf(Props.Create<PersistentActorA>(_actorId));
            WriteAndVerifyMessages(actor1, 1L, 16L);

            // Now start a new instance (same persistence Id) and it should recover with those same messages
            var actor2 = Sys.ActorOf(Props.Create<PersistentActorA>(_actorId));
            for (long i = 1L; i <= 16L; i++)
            {
                string msg = string.Format("a-{0}", i);
                ExpectHandled(msg, i, true);
            }

            // We should then be able to send that actor another message and have it be persisted
            actor2.Tell("b");
            ExpectHandled("b", 17L, false);
        }

        [Theory]
        [InlineData(true)]
        [InlineData(false)]
        public void Cassandra_journal_should_not_replay_deleted_messages(bool permanentDelete)
        {
            // Listen for delete messages on the event stream
            TestProbe deleteProbe = CreateTestProbe();
            Sys.EventStream.Subscribe(deleteProbe.Ref, typeof (DeleteMessagesTo));

            var actor1 = Sys.ActorOf(Props.Create<PersistentActorA>(_actorId));
            WriteAndVerifyMessages(actor1, 1L, 16L);

            // Tell the actor to delete some messages and make sure it's finished
            actor1.Tell(new DeleteToCommand(3L, permanentDelete));
            deleteProbe.ExpectMsg<DeleteMessagesTo>();

            // Start a second copy of the actor and verify it starts replaying from the correct spot
            Sys.ActorOf(Props.Create<PersistentActorA>(_actorId));
            for (long i = 4L; i <= 16L; i++)
            {
                string msg = string.Format("a-{0}", i);
                ExpectHandled(msg, i, true);
            }

            // Delete some more messages and wait for confirmation
            actor1.Tell(new DeleteToCommand(7L, permanentDelete));
            deleteProbe.ExpectMsg<DeleteMessagesTo>();

            // Start another copy and verify playback again
            Sys.ActorOf(Props.Create<PersistentActorA>(_actorId));
            for (long i = 8L; i <= 16L; i++)
            {
                string msg = string.Format("a-{0}", i);
                ExpectHandled(msg, i, true);
            }
        }

        [Fact]
        public void Cassandra_journal_should_replay_message_incrementally()
        {
            // Write some messages to a Persistent Actor
            var actor = Sys.ActorOf(Props.Create<PersistentActorA>(_actorId));
            WriteAndVerifyMessages(actor, 1L, 6L);

            TestProbe probe = CreateTestProbe();

            // Create a persistent view from the actor that does not do auto-updating
            var view = Sys.ActorOf(Props.Create<ViewA>(_actorId + "-view", _actorId, probe.Ref));
            probe.ExpectNoMsg(200);

            // Tell the view to update and verify we get the messages we wrote earlier replayed
            view.Tell(new Update(true, 3L));
            probe.ExpectMsg("a-1");
            probe.ExpectMsg("a-2");
            probe.ExpectMsg("a-3");
            probe.ExpectNoMsg(200);

            // Update the view again and verify we get the rest of the messages
            view.Tell(new Update(true, 3L));
            probe.ExpectMsg("a-4");
            probe.ExpectMsg("a-5");
            probe.ExpectMsg("a-6");
            probe.ExpectNoMsg(200);
        }

        [Fact]
        public void Persistent_actor_should_recover_from_a_snapshot_with_follow_up_messages()
        {
            // Write a message, snapshot, then another follow-up message
            var actor1 = Sys.ActorOf(Props.Create<PersistentActorC>(_actorId, TestActor));
            actor1.Tell("a");
            ExpectHandled("a", 1, false);
            actor1.Tell("snap");
            ExpectMsg("snapped-a-1");
            actor1.Tell("b");
            ExpectHandled("b", 2, false);

            // Start the actor again and verify we get a snapshot, followed by the message that wasn't in the snapshot
            var actor2 = Sys.ActorOf(Props.Create<PersistentActorC>(_actorId, TestActor));
            ExpectMsg("offered-a-1");
            ExpectHandled("b", 2, true);
        }

        [Fact]
        public void Persistent_actor_should_recover_from_a_snapshot_with_follow_up_messages_and_an_upper_bound()
        {
            // Create an actor and trigger manual recovery so it will accept new messages
            var actor1 = Sys.ActorOf(Props.Create<PersistentActorCWithManualRecovery>(_actorId, TestActor));
            actor1.Tell(new Recover(SnapshotSelectionCriteria.None));

            // Write a message, snapshot, then write some follow-up messages
            actor1.Tell("a");
            ExpectHandled("a", 1, false);
            actor1.Tell("snap");
            ExpectMsg("snapped-a-1");
            WriteSameMessageAndVerify(actor1, "a", 2L, 7L);

            // Create another copy of that actor and manually recover to an upper bound (i.e. past state) and verify
            // we get the expected messages after the snapshot
            var actor2 = Sys.ActorOf(Props.Create<PersistentActorCWithManualRecovery>(_actorId, TestActor));
            actor2.Tell(new Recover(SnapshotSelectionCriteria.Latest, toSequenceNr: 3L));
            ExpectMsg("offered-a-1");
            ExpectHandled("a", 2, true);
            ExpectHandled("a", 3, true);

            // Should continue working after recovery to previous state, but highest sequence number should take into
            // account other messages that were written but not replayed
            actor2.Tell("d");
            ExpectHandled("d", 8L, false);
        }

        [Fact]
        public void Persistent_actor_should_recover_from_a_snapshot_without_follow_up_messages_inside_a_partition()
        {
            // Write a message, then snapshot, no follow-up messages after snapshot
            var actor1 = Sys.ActorOf(Props.Create<PersistentActorC>(_actorId, TestActor));
            actor1.Tell("a");
            ExpectHandled("a", 1L, false);
            actor1.Tell("snap");
            ExpectMsg("snapped-a-1");

            // Start another copy and verify we recover with the snapshot
            var actor2 = Sys.ActorOf(Props.Create<PersistentActorC>(_actorId, TestActor));
            ExpectMsg("offered-a-1");

            // Write another message to verify
            actor2.Tell("b");
            ExpectHandled("b", 2L, false);
        }

        [Fact]
        public void Persistent_actor_should_recover_from_a_snapshot_without_follow_up_messages_at_a_partition_boundary_where_next_partition_is_invalid()
        {
            // Partition size for tests is 5 (see Config above), so write messages up to partition boundary (but don't write any
            // messages to the next partition)
            var actor1 = Sys.ActorOf(Props.Create<PersistentActorC>(_actorId, TestActor));
            WriteSameMessageAndVerify(actor1, "a", 1L, 5L);

            // Snapshot and verify without any follow-up messages
            actor1.Tell("snap");
            ExpectMsg("snapped-a-5");

            // Create a second copy of that actor and verify it recovers from the snapshot and continues working
            var actor2 = Sys.ActorOf(Props.Create<PersistentActorC>(_actorId, TestActor));
            ExpectMsg("offered-a-5");
            actor2.Tell("b");
            ExpectHandled("b", 6L, false);
        }

        /// <summary>
        /// Write messages "a-xxx" where xxx is an index number from start to end and verify that each message returns
        /// a Handled response.
        /// </summary>
        private void WriteAndVerifyMessages(IActorRef persistentActor, long start, long end)
        {
            for (long i = start; i <= end; i++)
            {
                string msg = string.Format("a-{0}", i);
                persistentActor.Tell(msg, TestActor);
                ExpectHandled(msg, i, false);
            }
        }

        /// <summary>
        /// Writes the same message multiple times and verify that we get a Handled response.
        /// </summary>
        private void WriteSameMessageAndVerify(IActorRef persistentActor, string message, long start, long end)
        {
            for (long i = start; i <= end; i++)
            {
                persistentActor.Tell(message, TestActor);
                ExpectHandled(message, i, false);
            }
        }

        private void ExpectHandled(string message, long sequenceNumber, bool isRecovering)
        {
            object msg = ReceiveOne();
            var handledMsg = Assert.IsType<HandledMessage>(msg);
            Assert.Equal(message, handledMsg.Message);
            Assert.Equal(sequenceNumber, handledMsg.SequenceNumber);
            Assert.Equal(isRecovering, handledMsg.IsRecovering);
        }

        #region Test Messages and Actors

        [Serializable]
        public class DeleteToCommand
        {
            public long SequenceNumber { get; private set; }
            public bool Permanent { get; private set; }

            public DeleteToCommand(long sequenceNumber, bool permanent)
            {
                SequenceNumber = sequenceNumber;
                Permanent = permanent;
            }
        }

        [Serializable]
        public class HandledMessage
        {
            public string Message { get; private set; }
            public long SequenceNumber { get; private set; }
            public bool IsRecovering { get; private set; }

            public HandledMessage(string message, long sequenceNumber, bool isRecovering)
            {
                Message = message;
                SequenceNumber = sequenceNumber;
                IsRecovering = isRecovering;
            }
        }

        public class PersistentActorA : PersistentActor
        {
            private readonly string _persistenceId;

            public PersistentActorA(string persistenceId)
            {
                _persistenceId = persistenceId;
            }

            public override string PersistenceId
            {
                get { return _persistenceId; }
            }

            protected override bool ReceiveRecover(object message)
            {
                if (message is string)
                {
                    var payload = (string) message;
                    Handle(payload);
                    return true;
                }

                return false;
            }

            protected override bool ReceiveCommand(object message)
            {
                if (message is DeleteToCommand)
                {
                    var delete = (DeleteToCommand) message;
                    DeleteMessages(delete.SequenceNumber, delete.Permanent);
                    return true;
                }

                if (message is string)
                {
                    var payload = (string) message;
                    Persist(payload, Handle);
                    return true;
                }

                return false;
            }

            private void Handle(string payload)
            {
                Context.Sender.Tell(new HandledMessage(payload, LastSequenceNr, IsRecovering), Self);
            }
        }

        public class PersistentActorC : PersistentActor
        {
            private readonly string _persistenceId;
            private readonly IActorRef _probe;

            private string _last;

            public override string PersistenceId
            {
                get { return _persistenceId; }
            }

            public PersistentActorC(string persistenceId, IActorRef probe)
            {
                _persistenceId = persistenceId;
                _probe = probe;
            }

            protected override bool ReceiveRecover(object message)
            {
                if (message is SnapshotOffer)
                {
                    var offer = (SnapshotOffer) message;
                    _last = (string) offer.Snapshot;
                    _probe.Tell(string.Format("offered-{0}", _last));
                    return true;
                }

                if (message is string)
                {
                    var payload = (string) message;
                    Handle(payload);
                    return true;
                }

                return false;
            }

            protected override bool ReceiveCommand(object message)
            {
                if (message is string)
                {
                    var msg = (string) message;
                    if (msg == "snap")
                        SaveSnapshot(_last);
                    else
                        Persist(msg, Handle);

                    return true;
                }

                if (message is SaveSnapshotSuccess)
                {
                    _probe.Tell(string.Format("snapped-{0}", _last), Context.Sender);
                    return true;
                }

                if (message is DeleteToCommand)
                {
                    var delete = (DeleteToCommand) message;
                    DeleteMessages(delete.SequenceNumber, delete.Permanent);
                    return true;
                }

                return false;
            }

            private void Handle(string payload)
            {
                _last = string.Format("{0}-{1}", payload, LastSequenceNr);
                _probe.Tell(new HandledMessage(payload, LastSequenceNr, IsRecovering));
            }
        }

        public class PersistentActorCWithManualRecovery : PersistentActorC
        {
            public PersistentActorCWithManualRecovery(string persistenceId, IActorRef probe)
                : base(persistenceId, probe)
            {
            }

            protected override void PreRestart(Exception reason, object message)
            {
                // Don't do automatic recovery
            }
        }

        public class ViewA : PersistentView
        {
            private readonly string _viewId;
            private readonly string _persistenceId;
            private readonly IActorRef _probe;

            public override string ViewId
            {
                get { return _viewId; }
            }

            public override string PersistenceId
            {
                get { return _persistenceId; }
            }

            public override bool IsAutoUpdate
            {
                get { return false; }
            }

            public override long AutoUpdateReplayMax
            {
                get { return 0L; }
            }

            public ViewA(string viewId, string persistenceId, IActorRef probe)
            {
                _viewId = viewId;
                _persistenceId = persistenceId;
                _probe = probe;
            }

            protected override bool Receive(object message)
            {
                // Just forward messages to the test probe
                _probe.Tell(message, Context.Sender);
                return true;
            }
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaGithub


text:
#define ERROR_PPCS_SUCCESSFUL						0
#define ERROR_PPCS_NOT_INITIALIZED					-1
#define ERROR_PPCS_ALREADY_INITIALIZED				-2
#define ERROR_PPCS_TIME_OUT							-3
#define ERROR_PPCS_INVALID_ID						-4
#define ERROR_PPCS_INVALID_PARAMETER				-5
#define ERROR_PPCS_DEVICE_NOT_ONLINE				-6
#define ERROR_PPCS_FAIL_TO_RESOLVE_NAME				-7
#define ERROR_PPCS_INVALID_PREFIX					-8
#define ERROR_PPCS_ID_OUT_OF_DATE					-9
#define ERROR_PPCS_NO_RELAY_SERVER_AVAILABLE		-10
#define ERROR_PPCS_INVALID_SESSION_HANDLE			-11
#define ERROR_PPCS_SESSION_CLOSED_REMOTE			-12
#define ERROR_PPCS_SESSION_CLOSED_TIMEOUT			-13
#define ERROR_PPCS_SESSION_CLOSED_CALLED			-14
#define ERROR_PPCS_REMOTE_SITE_BUFFER_FULL			-15
#define ERROR_PPCS_USER_LISTEN_BREAK				-16
#define ERROR_PPCS_MAX_SESSION						-17
#define ERROR_PPCS_UDP_PORT_BIND_FAILED				-18
#define ERROR_PPCS_USER_CONNECT_BREAK				-19
#define ERROR_PPCS_SESSION_CLOSED_INSUFFICIENT_MEMORY	-20
#define ERROR_PPCS_INVALID_APILICENSE				-21
#define ERROR_PPCS_FAIL_TO_CREATE_THREAD			-22

#endif //// #ifndef _PPCS_ERROR___INC_H_


text:
package com.sxj.SeeWeather.component;

import android.content.Context;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by zk on 2015/12/16.
 */
public class RetrofitSingleton {

    private static ApiInterface apiService = null;

    private static Retrofit retrofit = null;

    private static OkHttpClient okHttpClient = null;

    private static final String TAG = RetrofitSingleton.class.getSimpleName();

    public static Context context;

    /**
     * 初始化
     */

    public static void init(final Context context) {

        Executor executor = Executors.newCachedThreadPool();

        Gson gson = new GsonBuilder().create();
        // https://drakeet.me/retrofit-2-0-okhttp-3-0-config
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(interceptor)

            .retryOnConnectionFailure(true)
            .connectTimeout(15, TimeUnit.SECONDS)
            .build();

        retrofit = new Retrofit.Builder()
            .baseUrl(ApiInterface.HOST)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .callbackExecutor(executor)
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();

        apiService = retrofit.create(ApiInterface.class);
    }

    public static ApiInterface getApiService(Context context) {
        if (apiService != null) return apiService;
        init(context);
        return getApiService(context);
    }

    public static Retrofit getRetrofit(Context context) {
        if (retrofit != null) return retrofit;
        init(context);
        return getRetrofit(context);
    }

    public static OkHttpClient getOkHttpClient(Context context) {
        if (okHttpClient != null) return okHttpClient;
        init(context);
        return getOkHttpClient(context);
    }

    public static void disposeFailureInfo(Throwable t, Context context, View view) {
        if (t.toString().contains("GaiException") || t.toString().contains("SocketTimeoutException") ||
            t.toString().contains("UnknownHostException")) {
            Snackbar.make(view, "网络不好,~( ´•︵•` )~", Snackbar.LENGTH_LONG).show();
        } else {
            Toast.makeText(context, t.getMessage(), Toast.LENGTH_LONG).show();
        }
        Log.w(TAG, t.toString());
    }
}


text:
package behaviorPattern.chainpattern;

/**
 * Created by Miller on 2017/9/4 0004.
 * 项目经理
 */
public class ProjectManager extends Handler{

    @Override
    public String handleFeeRequest(String user, double fee) {
        String str = "";
        if(fee < 500){
            str = "成功:项目经理同意【" + user + "】的聚餐费用,金额为" + fee + "元";
        }else{
            if(getSuccessor() != null){
                return getSuccessor().handleFeeRequest(user, fee);
            }
        }

        return str;
    }
}


text:
package org.kuali.mobility.events.controllers;

import java.util.ArrayList;
import java.util.List;

import org.kuali.mobility.events.entity.Event;

public class MobileDayOfMonth {

	private int day;

	private boolean hasEvents;

	private boolean currentMonth;

	private String monthYear;

	private int dayOfWeek;

	private boolean beforeCurrentMonth;

	private List<Event> events;

	public MobileDayOfMonth(int day) {
		this.day = day;
		events = new ArrayList<Event>();
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public List<Event> getEvents() {
		return events;
	}

	public void setEvents(List<Event> events) {
		this.events = events;
	}

	public boolean isHasEvents() {
		return hasEvents;
	}

	public void setHasEvents(boolean hasEvents) {
		this.hasEvents = hasEvents;
	}

	public boolean isCurrentMonth() {
		return currentMonth;
	}

	public void setCurrentMonth(boolean currentMonth) {
		this.currentMonth = currentMonth;
	}

	public int getDayOfWeek() {
		return dayOfWeek;
	}

	public void setDayOfWeek(int dayOfWeek) {
		this.dayOfWeek = dayOfWeek;
	}

	public boolean isBeforeCurrentMonth() {
		return beforeCurrentMonth;
	}

	public void setBeforeCurrentMonth(boolean beforeCurrentMonth) {
		this.beforeCurrentMonth = beforeCurrentMonth;
	}

	public String getMonthYear() {
		return monthYear;
	}

	public void setMonthYear(String monthYear) {
		this.monthYear = monthYear;
	}

}


text:
import os
import sys

from metadata import MetadataUpdateRunner
from sync import SyncFromUpstreamRunner
from tree import GitTree, HgTree, NoVCSTree

from .. import environment as env
from base import Step, StepRunner, exit_clean, exit_unclean
from state import State

def setup_paths(sync_path):
    sys.path.insert(0, os.path.abspath(sync_path))
    try:
        from tools import localpaths
    except ImportError:
        from wpt_tools import localpaths

class LoadConfig(Step):
    """Step for loading configuration from the ini file and kwargs."""

    provides = ["sync", "paths", "metadata_path", "tests_path"]

    def create(self, state):
        state.sync = {"remote_url": state.kwargs["remote_url"],
                      "branch": state.kwargs["branch"],
                      "path": state.kwargs["sync_path"]}

        state.paths = state.kwargs["test_paths"]
        state.tests_path = state.paths["/"]["tests_path"]
        state.metadata_path = state.paths["/"]["metadata_path"]

        assert os.path.isabs(state.tests_path)

class LoadTrees(Step):
    """Step for creating a Tree for the local copy and a GitTree for the
    upstream sync."""

    provides = ["local_tree", "sync_tree"]

    def create(self, state):
        if os.path.exists(state.sync["path"]):
            sync_tree = GitTree(root=state.sync["path"])
        else:
            sync_tree = None

        if GitTree.is_type():
            local_tree = GitTree()
        elif HgTree.is_type():
            local_tree = HgTree()
        else:
            local_tree = NoVCSTree()

        state.update({"local_tree": local_tree,
                      "sync_tree": sync_tree})

class SyncFromUpstream(Step):
    """Step that synchronises a local copy of the code with upstream."""

    def create(self, state):
        if not state.kwargs["sync"]:
            return

        if not state.sync_tree:
            os.mkdir(state.sync["path"])
            state.sync_tree = GitTree(root=state.sync["path"])

        kwargs = state.kwargs
        with state.push(["sync", "paths", "metadata_path", "tests_path", "local_tree",
                         "sync_tree"]):
            state.target_rev = kwargs["rev"]
            state.patch = kwargs["patch"]
            state.suite_name = kwargs["suite_name"]
            state.path_excludes = kwargs["exclude"]
            state.path_includes = kwargs["include"]
            runner = SyncFromUpstreamRunner(self.logger, state)
            runner.run()

class UpdateMetadata(Step):
    """Update the expectation metadata from a set of run logs"""

    def create(self, state):
        if not state.kwargs["run_log"]:
            return

        kwargs = state.kwargs
        with state.push(["local_tree", "sync_tree", "paths", "serve_root"]):
            state.run_log = kwargs["run_log"]
            state.ignore_existing = kwargs["ignore_existing"]
            state.patch = kwargs["patch"]
            state.suite_name = kwargs["suite_name"]
            state.product = kwargs["product"]
            state.config = kwargs["config"]
            runner = MetadataUpdateRunner(self.logger, state)
            runner.run()

class UpdateRunner(StepRunner):
    """Runner for doing an overall update."""
    steps = [LoadConfig,
             LoadTrees,
             SyncFromUpstream,
             UpdateMetadata]

class WPTUpdate(object):
    def __init__(self, logger, runner_cls=UpdateRunner, **kwargs):
        """Object that controls the running of a whole wptupdate.

        :param runner_cls: Runner subclass holding the overall list of
                           steps to run.
        :param kwargs: Command line arguments
        """
        self.runner_cls = runner_cls
        self.serve_root = kwargs["test_paths"]["/"]["tests_path"]

        if not kwargs["sync"]:
            setup_paths(self.serve_root)
        else:
            if os.path.exists(kwargs["sync_path"]):
                # If the sync path doesn't exist we defer this until it does
                setup_paths(kwargs["sync_path"])

        self.state = State(logger)
        self.kwargs = kwargs
        self.logger = logger

    def run(self, **kwargs):
        if self.kwargs["abort"]:
            self.abort()
            return exit_clean

        if not self.kwargs["continue"] and not self.state.is_empty():
            self.logger.error("Found existing state. Run with --continue to resume or --abort to clear state")
            return exit_unclean

        if self.kwargs["continue"]:
            if self.state.is_empty():
                self.logger.error("No sync in progress?")
                return exit_clean

            self.kwargs = self.state.kwargs
        else:
            self.state.kwargs = self.kwargs

        self.state.serve_root = self.serve_root

        update_runner = self.runner_cls(self.logger, self.state)
        rv = update_runner.run()
        if rv in (exit_clean, None):
            self.state.clear()

        return rv

    def abort(self):
        self.state.clear()


text:
package edu.sjsu.cohort6.openstack.server.filter;

import edu.sjsu.cohort6.openstack.server.HttpConstants;
import org.apache.commons.lang3.StringUtils;
import spark.FilterImpl;
import spark.Request;
import spark.Response;
import spark.utils.SparkUtils;

import java.util.Base64;

import static spark.Spark.halt;

/**
 * Based on https://github.com/qmetric/spark-authentication.
 *
 * @author rwatsh on 11/15/15.
 */
public class BasicAuthenticationFilter extends FilterImpl {

    private static final String ACCEPT_ALL_TYPES = "*";
    private final AuthenticationDetails authenticationDetails;

    public BasicAuthenticationFilter(final AuthenticationDetails authenticationDetails) {
        this(SparkUtils.ALL_PATHS, authenticationDetails);
    }

    public BasicAuthenticationFilter(final String path, final AuthenticationDetails authenticationDetails) {
        super(path, ACCEPT_ALL_TYPES);
        this.authenticationDetails = authenticationDetails;
    }

    @Override
    public void handle(Request request, Response response) throws Exception {
        final String encodedHeader = StringUtils.substringAfter(request.headers("Authorization"), "Basic");

        if (!authenticatedWith(credentialsFrom(encodedHeader))) {
            //response.header("WWW-Authenticate", "Basic"); -- intentionally commenting out since we dont want
            // the browser to prompt.
            halt(HttpConstants.HTTP_NOT_AUTHORIZED);
        }
    }

    private String[] credentialsFrom(final String encodedHeader) {
        return StringUtils.split(encodedHeader != null ? decodeHeader(encodedHeader) : null, ":");
    }

    private String decodeHeader(final String encodedHeader) {
        return new String(Base64.getDecoder().decode(encodedHeader));
    }

    private boolean authenticatedWith(final String[] credentials) {
        if (credentials != null && credentials.length == 2) {
            final String submittedUsername = credentials[0];
            final String submittedPassword = credentials[1];

            return StringUtils.equals(submittedUsername, authenticationDetails.userName)
                    && StringUtils.equals(submittedPassword, new String(authenticationDetails.password));
        } else {
            return false;
        }
    }
}


text:
using System.Reflection;
using System.Runtime.InteropServices;

[assembly: AssemblyTitle("RetailcrmUnitTest")]
[assembly: AssemblyDescription("Tests for RetailCRM SDK")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("RetailDriver LLC")]
[assembly: AssemblyProduct("RetailcrmUnitTest")]
[assembly: AssemblyCopyright("Copyright © RetailDriver LLC 2020")]
[assembly: AssemblyTrademark("RetailDriver LLC")]
[assembly: AssemblyCulture("")]

[assembly: ComVisible(false)]

[assembly: Guid("4069c2bc-c277-48a3-96ae-da5934a75f4d")]

// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]


text:
namespace browser {

enum MessageBoxType {
  MESSAGE_BOX_TYPE_INFORMATION,
  MESSAGE_BOX_TYPE_WARNING,
};

// Shows a message box with an OK button. If |parent| is non-null,
// the box will be modal on it. (On Mac, it is always app-modal.) Generally
// speaking, this function should not be used for much. Infobars are preferred.
void ShowMessageBox(gfx::NativeWindow parent,
                    const string16& title,
                    const string16& message,
                    MessageBoxType type);

// Shows a question message box with two buttons (Yes/No), with the default
// button of Yes. If |parent| is non-null, the box will be modal on it. (On Mac,
// it is always app-modal.) Returns true if the Yes button was chosen.
bool ShowQuestionMessageBox(gfx::NativeWindow parent,
                            const string16& title,
                            const string16& message);

}  // namespace browser

#endif  // CHROME_BROWSER_UI_SIMPLE_MESSAGE_BOX_H_


text:
<?php

namespace Bolt\Extension\Bolt\JsonApi\Converter;

use Bolt\Extension\Bolt\JsonApi\Config\Config;
use Bolt\Extension\Bolt\JsonApi\Converter\Parameter\ParameterFactory;
use Bolt\Extension\Bolt\JsonApi\Converter\Parameter\ParameterInterface;
use Bolt\Storage\Mapping\MetadataDriver;
use Doctrine\Common\Collections\Collection;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class JSONAPIConverter
 *
 * @package Bolt\Extension\Bolt\JsonApi\Converter
 */
class JSONAPIConverter
{
    /** @var Config $config */
    protected $config;

    /** @var MetadataDriver $metadata */
    protected $metadata;

    /**
     * JSONAPIConverter constructor.
     *
     * @param Config         $config
     * @param MetadataDriver $metadata
     */
    public function __construct(Config $config, MetadataDriver $metadata)
    {
        $this->metadata = $metadata;
        $this->config = $config;
    }

    /**
     * Create an array of parameters to be handled by our ParameterFactory class
     *
     * @param $converter
     * @param Request $request
     *
     * @return Collection|ParameterInterface[]
     */
    public function grabParameters($converter, Request $request)
    {
        $parameters = [];

        $parameters['search'] = $request->query->get('q', false);
        $contentType = $request->get('contentType', false);

        if (! $this->isSearch($parameters)) {
            //Get content type if it isn't a search...
            $parameters['contentType'] = $request->attributes->get('relatedContentType');

            if (! $parameters['contentType']) {
                $parameters['contentType'] = $request->attributes->get('contentType');
            }
        } else if ($contentType) {
            $parameters['contentType'] = $contentType;
        }

        $parameters['page']['size'] = $request->query->get('page[size]', false, true);
        $parameters['page']['number'] = $request->query->get('page[number]', false, true);
        $parameters['sort'] = $request->query->get('sort', false);
        $parameters['filters'] = $request->query->get('filter', false);
        $parameters['contains'] = $request->query->get('contains', false);
        $parameters['includes'] = $request->query->get('include', false);
        $parameters['fields'] = $request->query->get('fields', false);

        $parameterCollection = ParameterFactory::build($parameters, $this->config, $this->metadata);

        return $parameterCollection;
    }

    /**
     * @param $parameters
     *
     * @return mixed
     */
    protected function isSearch($parameters)
    {
        return $parameters['search'];
    }
}


text:
using namespace vnotex;

NotebookSelector::NotebookSelector(QWidget *p_parent)
    : ComboBox(p_parent),
      NavigationMode(NavigationMode::Type::StagedDoubleKeys, this)
{
    auto itemDelegate = new QStyledItemDelegate(this);
    setItemDelegate(itemDelegate);

    view()->installEventFilter(this);

    setSizeAdjustPolicy(QComboBox::AdjustToMinimumContentsLengthWithIcon);
}

void NotebookSelector::setNotebooks(const QVector<QSharedPointer<Notebook>> &p_notebooks)
{
    clear();

    for (auto &nb : p_notebooks) {
        addNotebookItem(nb);
    }

    updateGeometry();

    m_notebooksInitialized = true;
}

void NotebookSelector::reloadNotebook(const Notebook *p_notebook)
{
    Q_ASSERT(p_notebook);
    int idx = findNotebook(p_notebook->getId());
    Q_ASSERT(idx != -1);

    setItemIcon(idx, generateItemIcon(p_notebook));
    setItemText(idx, p_notebook->getName());
    setItemToolTip(idx, generateItemToolTip(p_notebook));

    int curIdx = currentIndex();
    if (curIdx == idx) {
        setToolTip(getItemToolTip(idx));
    }
}

void NotebookSelector::addNotebookItem(const QSharedPointer<Notebook> &p_notebook)
{
    int idx = count();
    addItem(generateItemIcon(p_notebook.data()), p_notebook->getName(), p_notebook->getId());
    setItemToolTip(idx, generateItemToolTip(p_notebook.data()));
}

QIcon NotebookSelector::generateItemIcon(const Notebook *p_notebook)
{
    if (!p_notebook->getIcon().isNull()) {
        return p_notebook->getIcon();
    }

    const auto &themeMgr = VNoteX::getInst().getThemeMgr();
    QString iconFile;
    const auto &type = p_notebook->getType();
    if (type == "native.vnotex") {
        iconFile = themeMgr.getIconFile("native_notebook_default.svg");
    } else {
        iconFile = themeMgr.getIconFile("notebook_default.svg");
    }

    return IconUtils::fetchIcon(iconFile);
}

QString NotebookSelector::generateItemToolTip(const Notebook *p_notebook)
{
    return tr("Notebook: %1\nRoot folder: %2\nDescription: %3")
             .arg(p_notebook->getName(),
                  p_notebook->getRootFolderAbsolutePath(),
                  p_notebook->getDescription());
}

QString NotebookSelector::getItemToolTip(int p_idx) const
{
    return itemData(p_idx, Qt::ToolTipRole).toString();
}

void NotebookSelector::setItemToolTip(int p_idx, const QString &p_tooltip)
{
    setItemData(p_idx, p_tooltip, Qt::ToolTipRole);
}

void NotebookSelector::setCurrentNotebook(ID p_id)
{
    int idx = findNotebook(p_id);
    setCurrentIndex(idx);
    setToolTip(getItemToolTip(idx));
}

int NotebookSelector::findNotebook(ID p_id) const
{
    return findData(p_id);
}

QVector<void *> NotebookSelector::getVisibleNavigationItems()
{
    QVector<void *> items;
    auto listView = dynamic_cast<QListView *>(view());
    if (listView) {
        m_navigationIndexes = WidgetUtils::getVisibleIndexes(listView);
        for (auto &index : m_navigationIndexes) {
            items.push_back(&index);
        }
    }
    return items;
}

void NotebookSelector::placeNavigationLabel(int p_idx, void *p_item, QLabel *p_label)
{
    if (p_idx == -1) {
        // Major.
        p_label->move(rect().topRight() - QPoint(p_label->width() + 2, 2));
    } else {
        // Second.
        // Reparent it to the list view.
        auto listView = view();
        p_label->setParent(listView);

        auto index = *static_cast<QModelIndex *>(p_item);

        int extraWidth = p_label->width() + 2;
        auto vbar = listView->verticalScrollBar();
        if (vbar && vbar->minimum() != vbar->maximum()) {
            extraWidth += vbar->width();
        }

        const auto rt = listView->visualRect(index);
        const int x = rt.x() + view()->width() - extraWidth;
        const int y = rt.y();
        p_label->move(x, y);
    }
}

void NotebookSelector::handleTargetHit(void *p_item)
{
    if (!p_item) {
        setFocus();
        showPopup();
    } else {
        hidePopup();
        auto index = *static_cast<QModelIndex *>(p_item);
        setCurrentIndex(index.row());
        emit activated(index.row());
    }
}

bool NotebookSelector::eventFilter(QObject *p_obj, QEvent *p_event)
{
    if (p_event->type() == QEvent::KeyPress && p_obj == view()) {
        if (WidgetUtils::processKeyEventLikeVi(view(), static_cast<QKeyEvent *>(p_event))) {
            return true;
        }
    }
    return ComboBox::eventFilter(p_obj, p_event);
}

void NotebookSelector::clearNavigation()
{
    m_navigationIndexes.clear();

    NavigationMode::clearNavigation();
}

void NotebookSelector::mousePressEvent(QMouseEvent *p_event)
{
    // Only when notebooks are loaded and there is no notebook, we could prompt for new notebook.
    if (m_notebooksInitialized && count() == 0) {
        emit newNotebookRequested();
        return;
    }

    ComboBox::mousePressEvent(p_event);
}


text:
using UnityEngine;
using UnityEditor;
using UnityEditor.Callbacks;
using System.IO;

public class RedistCopy {
	[PostProcessBuild]
	public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) {
#if !DISABLEREDISTCOPY
		string strProjectName = Path.GetFileNameWithoutExtension(pathToBuiltProject);

		if (target == BuildTarget.StandaloneWindows64) {
			CopyFile("steam_api64.dll", "steam_api64.dll", "Assets/Plugins/x86_64", pathToBuiltProject);
		}
		else if (target == BuildTarget.StandaloneWindows) {
			CopyFile("steam_api.dll", "steam_api.dll", "Assets/Plugins/x86", pathToBuiltProject);
		}

		string controllerCfg = Path.Combine(Application.dataPath, "controller.vdf");
		if (File.Exists(controllerCfg)) {
			string dir = "_Data";
			if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal) {
				dir = ".app/Contents";
			}

			string strFileDest = Path.Combine(Path.Combine(Path.GetDirectoryName(pathToBuiltProject), strProjectName + dir), "controller.vdf");

			File.Copy(controllerCfg, strFileDest);
			File.SetAttributes(strFileDest, File.GetAttributes(strFileDest) & ~FileAttributes.ReadOnly);

			if (!File.Exists(strFileDest)) {
				Debug.LogWarning("[Steamworks.NET] Could not copy controller.vdf into the built project. File.Copy() Failed. Place controller.vdf from the Steamworks SDK in the output dir manually.");
			}
		}
#endif
	}

	static void CopyFile(string filename, string outputfilename, string pathToFile, string pathToBuiltProject) {
		string strCWD = Directory.GetCurrentDirectory();
		string strSource = Path.Combine(Path.Combine(strCWD, pathToFile), filename);
		string strFileDest = Path.Combine(Path.GetDirectoryName(pathToBuiltProject), outputfilename);

		if (!File.Exists(strSource)) {
			Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the project root. {0} could not be found in '{1}'. Place {0} from the redist into the project root manually.", filename, pathToFile));
			return;
		}

		if (File.Exists(strFileDest)) {
			if (File.GetLastWriteTime(strSource) == File.GetLastWriteTime(strFileDest)) {
				FileInfo fInfo = new FileInfo(strSource);
				FileInfo fInfo2 = new FileInfo(strFileDest);
				if (fInfo.Length == fInfo2.Length) {
					return;
				}
			}
		}

		File.Copy(strSource, strFileDest, true);
		File.SetAttributes(strFileDest, File.GetAttributes(strFileDest) & ~FileAttributes.ReadOnly);

		if (!File.Exists(strFileDest)) {
			Debug.LogWarning(string.Format("[Steamworks.NET] Could not copy {0} into the built project. File.Copy() Failed. Place {0} from the redist folder into the output dir manually.", filename));
		}
	}
}


text:
/*jslint sloppy:true forin:true newcap:true*/
/*global define*/

define([
    'Utils/lang/isFunction',
    'Utils/lang/isObject',
    'Utils/lang/isArray',
    'Utils/lang/isUndefined',
    'Utils/lang/createObject',
    'Utils/object/mixIn',
    'Utils/object/hasOwn',
    'Utils/object/forOwn',
    'Utils/array/combine',
    'Utils/array/append',
    'Utils/array/insert',
    'Utils/lang/bind',
    'Utils/lang/toArray'
], function (
    isFunction,
    isObject,
    isArray,
    isUndefined,
    createObject,
    mixIn,
    hasOwn,
    forOwn,
    combine,
    append,
    insert,
    bind,
    toArray
) {

    var Class;

    /**
     * Parse borrows (mixins).
     *
     * @param {Function} constructor The constructor
     */
    function parseBorrows(constructor) {

        if (hasOwn(constructor.prototype, 'Borrows')) {

            var current,
                k,
                key,
                mixins = toArray(constructor.prototype.Borrows),
                i = mixins.length,
                grabMethods = function (value, key) {
                    if (isUndefined(constructor.prototype[key])) {    // Already defined members are not overwritten
                        constructor.prototype[key] = value;
                    }
                };

            for (i -= 1; i >= 0; i -= 1) {

                current = isObject(mixins[i]) ? Class(mixIn({}, mixins[i])).prototype : mixins[i].prototype;

                // Grab mixin methods
                forOwn(current, grabMethods);

                // Grab mixin static methods
                for (k = current.$constructor.$class.staticMethods.length - 1; k >= 0; k -= 1) {
                    key = current.$constructor.$class.staticMethods[k];
                    if (isUndefined(constructor[key])) {    // Already defined members are not overwritten
                        insert(constructor.$class.staticMethods, key);
                        constructor[key] = current.$constructor[key];
                    }
                }

                // Grab mixin static properties
                for (k = current.$constructor.$class.staticProperties.length - 1; k >= 0; k -= 1) {
                    key = current.$constructor.$class.staticProperties[k];
                    if (isUndefined(constructor[key])) {    // Already defined members are not overwritten
                        insert(constructor.$class.staticProperties, key);
                        constructor[key] = current.$constructor[key];
                    }
                }

                // Merge the binds
                combine(constructor.$class.binds, current.$constructor.$class.binds);
            }

            delete constructor.prototype.Borrows;
        }
    }

    /**
     * Applies the context of given methods in the target.
     *
     * @param {Array}  fns     The array of functions to be bound
     * @param {Object} context The context that will be bound
     * @param {Object} target  The target class that will have these methods
     */
    function applyBinds(fns, context, target) {

        var i;

        for (i = fns.length - 1; i >= 0; i -= 1) {
            target[fns[i]] = bind(target[fns[i]], context);
        }
    }

    /**
     * Handle class interfaces.
     *
     * @param {Array}  interfs The array of interfaces
     * @param {Object} target  The target that will be checked
     */
    function handleInterfaces(interfs, target) {

        var interfaces = toArray(interfs),
            x = interfaces.length;

        for (x -= 1; x >= 0; x -= 1) {
            target.$class.interfaces.push(interfaces[x]);
        }
    }

    /**
     * Parse binds.
     *
     * @param {Function} constructor The constructor
     */
    function parseBinds(constructor) {

        if (hasOwn(constructor.prototype, 'Binds')) {
            var binds = toArray(constructor.prototype.Binds);

            combine(constructor.$class.binds, binds);
            delete constructor.prototype.Binds;
        }
    }

    /**
     * Parse all the methods, including static ones.
     *
     * @param {Object}   params      The parameters
     * @param {Function} constructor The constructor
     */
    function parseMethods(params, constructor) {

        // Parse static methods
        if (hasOwn(params, 'Statics')) {

            forOwn(params.Statics, function (value, key) {
                insert(isFunction(value) && !value.$class && !value.$interface ? constructor.$class.staticMethods : constructor.$class.staticProperties, key);
                constructor[key] = value;
            });

            delete constructor.prototype.Statics;
        }
    }

    /**
     * Reset some properties in order to make them unique for the instance.
     * This solves the shared properties for types like objects or arrays.
     *
     * @param {Object} object The instance
     */
    function reset(object) {

        var key;

        for (key in object) {
            if (isArray(object[key])) {    // If is array, clone it
                object[key] = [].concat(object[key]);
            } else if (isObject(object[key])) {    // If is an object, clone it
                object[key] = mixIn({}, object[key]);
            }
        }
    }

    /**
     * Builds the constructor function that calls the initialize and do
     * more things internally.
     *
     * @param {Function} initialize The initialize function
     *
     * @return {Function} The constructor function
     */
    function createConstructor(initialize) {

        var Instance = function () {

            // Reset some types of the object in order for each instance to have their variables
            reset(this);

            // Apply binds
            if (this.$constructor.$class.binds) {
                applyBinds(this.$constructor.$class.binds, this, this);
            }

            // Call initialize
            initialize.apply(this, arguments);
        };

        return Instance;
    }

    /**
     * Create a class definition.
     *
     * @param {Object} params An object containing methods and properties
     *
     * @return {Function} The constructor
     */
    Class = function Class(params) {

        var classify,
            parent,
            $class = { staticMethods: [], staticProperties: [], interfaces: [], binds: [] },
            k;

        if (hasOwn(params, 'Extends')) {
            parent = params.Extends;
            delete params.Extends;

            params.initialize = params.initialize || function () { parent.prototype.initialize.apply(this, arguments); };
            classify = createConstructor(params.initialize, params.Name);
            classify.Super = parent.prototype;
            classify.prototype = createObject(parent.prototype, params);

            // Grab all the methods, static methods, static properties, binds and interfaces metadata from the parent
            append($class.staticMethods, parent.$class.staticMethods);
            append($class.staticProperties, parent.$class.staticProperties);
            append($class.binds, parent.$class.binds);
            append($class.interfaces, parent.$class.interfaces);

            // Inherit static methods
            for (k =  parent.$class.staticMethods.length - 1; k >= 0; k -= 1) {
                classify[parent.$class.staticMethods[k]] = parent[parent.$class.staticMethods[k]];
            }
        } else {
            params.initialize = params.initialize || function () {};
            classify = createConstructor(params.initialize, params.Name);
            classify.prototype = params;
        }

        delete classify.prototype.Name;

        classify.prototype.$constructor = classify;
        classify.$class = $class;

        // Parse methods
        parseMethods(params, classify);

        // Parse mixins
        parseBorrows(classify);

        // Parse binds
        parseBinds(classify);

        // Handle interfaces
        if (hasOwn(params, 'Implements')) {
            handleInterfaces(params.Implements, classify);
            delete classify.prototype.Implements;
        }

        return classify;
    };

    return Class;
});


text:
package org.apache.axis2.clustering.control.wka;

import org.apache.axis2.clustering.ClusteringFault;
import org.apache.axis2.clustering.control.ControlCommand;
import org.apache.axis2.clustering.tribes.MembershipManager;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.catalina.tribes.Member;

import java.util.Arrays;

/**
 * This is the notification message a member will send to all others in the group after it has
 * joined the group. When the other members received this message, they will add the newly joined
 * member to their member list
 */
public class MemberJoinedCommand extends ControlCommand {

    private Member member;
    private MembershipManager membershipManager;

    public void setMembershipManager(MembershipManager membershipManager) {
        this.membershipManager = membershipManager;
    }

    public void setMember(Member member) {
        this.member = member;
    }

    public Member getMember() {
        return member;
    }

    public void execute(ConfigurationContext configurationContext) throws ClusteringFault {
        Member localMember = membershipManager.getLocalMember();
        if (localMember == null || !(Arrays.equals(localMember.getHost(), member.getHost()) &&
              localMember.getPort() == member.getPort())) {
            membershipManager.memberAdded(member);
        }
    }

    public String toString() {
        return "MemberJoinedCommand: " + member;
    }
}


text:
import * as Functions from "firebase-functions";

import * as admin from "firebase-admin";
import {productDataMap} from "./products";
import {PurchaseHandler} from "./purchase-handler";
import {GooglePlayPurchaseHandler} from "./google-play.purchase-handler";
import {AppStorePurchaseHandler} from "./app-store.purchase-handler";
import {CLOUD_REGION} from "./constants";
import {IapRepository, IAPSource} from "./iap.repository";
import {HttpsError} from "firebase-functions/lib/providers/https";

const functions = Functions.region(CLOUD_REGION);
admin.initializeApp();

//
// Dependencies
//

const iapRepository = new IapRepository(admin.firestore());
const purchaseHandlers: { [source in IAPSource]: PurchaseHandler } = {
  "google_play": new GooglePlayPurchaseHandler(iapRepository),
  "app_store": new AppStorePurchaseHandler(iapRepository),
};

//
// Callables
//

// Verify Purchase Function
interface VerifyPurchaseParams {
  source: IAPSource;
  verificationData: string;
  productId: string;
}

// Handling of purchase verifications
export const verifyPurchase = functions.https.onCall(
    async (
        data: VerifyPurchaseParams,
        context,
    ): Promise<boolean> => {
      // Check authentication
      if (!context.auth) {
        console.warn("verifyPurchase called when not authenticated");
        throw new HttpsError(
            "unauthenticated",
            "Request was not authenticated.",
        );
      }
      // Get the product data from the map
      const productData = productDataMap[data.productId];
      // If it was for an unknown product, do not process it.
      if (!productData) {
        console.warn(`verifyPurchase called for an unknown product ("${data.productId}")`);
        return false;
      }
      // If it was for an unknown source, do not process it.
      if (!purchaseHandlers[data.source]) {
        console.warn(`verifyPurchase called for an unknown source ("${data.source}")`);
        return false;
      }
      // Process the purchase for the product
      return purchaseHandlers[data.source].verifyPurchase(
          context.auth.uid,
          productData,
          data.verificationData,
      );
    });

// Handling of AppStore server-to-server events
export const handleAppStoreServerEvent =
    (purchaseHandlers.app_store as AppStorePurchaseHandler)
        .handleServerEvent;

// Handling of PlayStore server-to-server events
export const handlePlayStoreServerEvent =
    (purchaseHandlers.google_play as GooglePlayPurchaseHandler)
        .handleServerEvent;

// Scheduled job for expiring subscriptions in the case of missing store events
export const expireSubscriptions = functions.pubsub.schedule("every 1 mins")
    .onRun(() => iapRepository.expireSubscriptions());


text:
exports.up = function(knex, Promise) {
  return knex.schema.createTable('canvas', (table) => {
    table.increments()
    table.integer('group_id').references('id').inTable('groups')
    table.timestamp('created_at').defaultTo(knex.fn.now())
  })
};

exports.down = function(knex, Promise) {
  return knex.schema.dropTable('canvas')
};


text:
package uk.gov.nationalarchives.droid.core.interfaces.archive;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.util.zip.GZIPInputStream;

import org.apache.commons.io.FilenameUtils;

import uk.gov.nationalarchives.droid.core.interfaces.AsynchDroid;
import uk.gov.nationalarchives.droid.core.interfaces.IdentificationRequest;
import uk.gov.nationalarchives.droid.core.interfaces.RequestIdentifier;
import uk.gov.nationalarchives.droid.core.interfaces.resource.RequestMetaData;

/**
 * @author rflitcroft
 *
 */
public class GZipArchiveHandler implements ArchiveHandler {

    private IdentificationRequestFactory factory;
    private AsynchDroid droid;

    /**
     * {@inheritDoc}
     */
    @Override
    public final void handle(IdentificationRequest request) throws IOException {
        IdentificationRequest archiveRequest = null;
        InputStream in = request.getSourceInputStream();
        try {
            URI parent = request.getIdentifier().getUri();
            long correlationId = request.getIdentifier().getNodeId();
            final URI uri = ArchiveFileUtils.toGZipUri(parent);

            String path = uri.getSchemeSpecificPart();
            String fileName = FilenameUtils.getName(path);
            final RequestMetaData metaData = new RequestMetaData(null, null, fileName);

            RequestIdentifier identifier = new RequestIdentifier(uri);
            identifier.setAncestorId(request.getIdentifier().getAncestorId());
            identifier.setParentId(correlationId);

            archiveRequest = factory.newRequest(metaData, identifier);
            final InputStream gzin = new GZIPInputStream(in);
            try {
                archiveRequest.open(gzin);
            } finally {
                if (gzin != null) {
                    gzin.close();
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        if (archiveRequest != null) {
            droid.submit(archiveRequest);
        }
    }

    /**
     * @param factory factory for generating identification requests.
     */
    public final void setFactory(IdentificationRequestFactory factory) {
        this.factory = factory;
    }

    /**
     * @param droidCore the droid core to submit requests to.
     */
    public final void setDroidCore(AsynchDroid droidCore) {
        droid = droidCore;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
TopLevel.Builtins (Rhino)
</TITLE>

<META NAME="date" CONTENT="2011-05-09">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD

org.mozilla.javascript

Enum TopLevel.Builtins

java.lang.Object
  java.lang.Enum<TopLevel.Builtins>
      org.mozilla.javascript.TopLevel.Builtins

All Implemented Interfaces:
java.io.Serializable, java.lang.Comparable<TopLevel.Builtins>

Enclosing class:
TopLevel

public static enum TopLevel.Builtins
extends java.lang.Enum<TopLevel.Builtins>

An enumeration of built-in ECMAScript objects.

Enum Constant Summary

Array

          The built-in Array type.

Boolean

          The built-in Boolean type.

Error

          The built-in Error type.

Function

          The built-in Function type.

Number

          The built-in Number type.

Object

          The built-in Object type.

RegExp

          The built-in RegExp type.

String

          The built-in String type.

Method Summary

static TopLevel.Builtins
valueOf(java.lang.String name)

          Returns the enum constant of this type with the specified name.

static TopLevel.Builtins[]
values()

          Returns an array containing the constants of this enum type, in
the order they are declared.

Methods inherited from class java.lang.Enum

clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Enum Constant Detail

Object

public static final TopLevel.Builtins Object

The built-in Object type.

Array

public static final TopLevel.Builtins Array

The built-in Array type.

Function

public static final TopLevel.Builtins Function

The built-in Function type.

String

public static final TopLevel.Builtins String

The built-in String type.

Number

public static final TopLevel.Builtins Number

The built-in Number type.

Boolean

public static final TopLevel.Builtins Boolean

The built-in Boolean type.

RegExp

public static final TopLevel.Builtins RegExp

The built-in RegExp type.

Error

public static final TopLevel.Builtins Error

The built-in Error type.

Method Detail

values

public static TopLevel.Builtins[] values()

Returns an array containing the constants of this enum type, in
the order they are declared.  This method may be used to iterate
over the constants as follows:

for (TopLevel.Builtins c : TopLevel.Builtins.values())
    System.out.println(c);

Returns:
an array containing the constants of this enum type, in
the order they are declared

valueOf

public static TopLevel.Builtins valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.
The string must match exactly an identifier used to declare an
enum constant in this type.  (Extraneous whitespace characters are
not permitted.)

Parameters:
name - the name of the enum constant to be returned.

Returns:
the enum constant with the specified name

Throws:

java.lang.IllegalArgumentException - if this enum type has no constant
with the specified name

java.lang.NullPointerException - if the argument is null

      Overview
      Package
    Class
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | ENUM CONSTANTS | FIELD | METHOD

DETAIL: ENUM CONSTANTS | FIELD | METHOD


text:
package engine;

import java.util.List;

public interface ActionInterface {
	//external
	List<Parameter> getParams(); // will use reflection
	void setParams(List<Parameter> params); // will use reflection
	String getDisplayName();
	String getDisplayDescription();

	//internal
	void act(); // carry out the action triggered by the event. Will need a reference to game
}


text:
package ir.abforce.dinorunner.objects;

import org.andengine.entity.modifier.ScaleModifier;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.entity.scene.Scene;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.TextureRegion;

import ir.abforce.dinorunner.custom.SSprite;
import ir.abforce.dinorunner.managers.RM;

/**
 * Created by Ali Reza on 8/6/15.
 */
public abstract class ControllingButton extends GameObject {

    private ButtonStateChangeListener mListener;
    private boolean mDown = false;

    public ControllingButton(Scene scene, final ButtonStateChangeListener listener) {
        super(scene);
        this.mListener = listener;
        this.mSprite = new SSprite(0, 0, getTexture());
        setX(getButtonX());
        setY(getButtonY());
        scene.registerTouchArea(this.mSprite);
    }

    public boolean onSceneAreaTouched(TouchEvent pSceneTouchEvent, ITouchArea pTouchArea){
        if(pTouchArea == this.mSprite) {
            if (pSceneTouchEvent.isActionDown()) {
                this.mListener.onButtonHeld();
                applyEffectsDown();
                this.mDown = true;
            }
            if (pSceneTouchEvent.isActionUp()) {
                if(this.mDown) {
                    this.mListener.onButtonReleased();
                    applyEffectsUp();
                    this.mDown = false;
                } else {
                    return false;
                }
            }
            return true;
        }
        return false;
    }

    public boolean onSceneTouched(TouchEvent pSceneTouchEvent){
        if(this.mDown && pSceneTouchEvent.isActionUp()){
            this.mListener.onButtonReleased();
            applyEffectsUp();
            this.mDown = false;
        }
        return false;
    }

    public void applyEffectsDown(){
        this.mSprite.registerEntityModifier(new ScaleModifier(0.08f, RM.S, RM.S * 0.75f));
    }

    public void applyEffectsUp(){
        this.mSprite.registerEntityModifier(new ScaleModifier(0.08f, RM.S * 0.75f, RM.S));
    }

    public abstract TextureRegion getTexture();
    public abstract float getButtonX();
    public abstract float getButtonY();

    public interface ButtonStateChangeListener{
        void onButtonHeld();
        void onButtonReleased();
    }
}


text:
{-# LANGUAGE FlexibleInstances     #-}
{-# LANGUAGE GADTs                 #-}
{-# LANGUAGE MonadComprehensions   #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings     #-}
{-# LANGUAGE RebindableSyntax      #-}
{-# LANGUAGE TemplateHaskell       #-}
{-# LANGUAGE TypeFamilies          #-}
{-# LANGUAGE UndecidableInstances  #-}

module Queries.TPCH.Standard.Q6
    ( q6
    , q6Default
    ) where

import qualified Data.Decimal       as D
import qualified Data.Time.Calendar as C
import           Database.DSH
import           Schema.TPCH

-- | TPC-H Query Q6 with standard validation parameters
q6Default :: Q Decimal
q6Default = q6 (C.fromGregorian 1994 1 1)
               (D.realFracToDecimal 2 (0.06::Double)) 24

between :: Q Decimal -> Q Decimal -> Q Decimal -> Q Bool
between x l r = x >= l && x <= r

-- | TPC-H Query Q6
q6 :: Day -> Decimal -> Decimal -> Q Decimal
q6 startDate discount quantity =
  sum [ l_extendedpriceQ l * l_discountQ l
      | l <- lineitems
      , l_shipdateQ l >= toQ startDate
      , l_shipdateQ l < toQ (C.addDays 365 startDate)
      , between (l_discountQ l) lowerDiscount upperDiscount
      , l_quantityQ l < toQ quantity
      ]
  where
    lowerDiscount = toQ discount - 0.01
    upperDiscount = toQ discount + 0.01


text:
const { List } = window;
document.onreadystatechange = () => {
  if (document.readyState === 'complete') {
    // Find tables with rows with data-link attribute, then make them clickable
    document.querySelector('tr[data-link]')?.addEventListener('click', (e) => {
      // skip if a button was clicked (used for other actions)
      if (e.target.tagName === 'BUTTON') return;

      const loc = e.currentTarget.dataset.link;
      if (e.metaKey || (window.navigator.userAgentData.platform.toLowerCase().indexOf('win') !== -1 && e.ctrlKey)) {
      window.open(loc, '_blank');
      } else {
        window.location = loc;
      }
      return false;
    });
  }
  // Course sorting
  // only sort if there are tables to sort
  let courseList;
  if (document.querySelectorAll('#courses table').length) {
    courseList = new List('courses', {
      page: 500,
      valueNames: [
        'title', 'school', 'revisions', 'characters', 'references', 'average-words', 'views',
        'reviewed', 'students', 'creation-date', 'ungreeted', 'untrained'
      ]
    });
  }

  // Course Results sorting
  // only sort if there are tables to sort
  let courseResultList;
  if (document.querySelectorAll('#course_results table').length) {
    courseResultList = new List('course_results', {
      page: 500,
      valueNames: [
        'title', 'school', 'revisions', 'characters', 'references', 'average-words', 'views',
        'reviewed', 'students', 'creation-date', 'ungreeted', 'untrained'
      ]
    });
  }

  // Campaign sorting
  // only sort if there are tables to sort
  let campaignList;
  if (document.querySelectorAll('#campaigns table').length) {
    campaignList = new List('campaigns', {
      page: 500,
      valueNames: [
        'title', 'num-courses', 'articles-created', 'articles-edited', 'characters', 'references', 'views', 'students', 'creation-date'
      ]
    });
  }

  // Article sorting
  // only sort if there are tables to sort
  let articlesList;
  if (document.querySelectorAll('#campaign-articles table').length) {
    articlesList = new List('campaign-articles', {
      page: 10000,
      valueNames: [
        'title', 'views', 'char_added', 'references', 'lang_project', 'course_title'
      ]
    });
  }

  // Student sorting
  // only sort if there are tables to sort
  let studentsList;
  if (document.querySelectorAll('#users table').length) {
    studentsList = new List('users', {
      page: 10000,
      valueNames: [
        'username', 'revision-count', 'title'
      ]
    });
  }

  // for use on campaign/programs page
  const x = document.querySelectorAll('.remove-course');
  for (let i = 0; i < x.length; i += 1) {
    x[i]?.addEventListener('click', (e) => {
        const confirmed = window.confirm(I18n.t('campaign.confirm_course_removal', {
          title: e.target.dataset.title,
          campaign_title: e.target.dataset.campaignTitle
        }));
        if (!confirmed) {
          e.preventDefault();
        }
    });
  }

  return document.querySelectorAll('select.sorts').forEach(item => item?.addEventListener('change', function () {
    const list = (() => {
      switch (this.getAttribute('rel')) {
        case 'courses': return courseList;
        case 'course_results': return courseResultList;
        case 'campaigns': return campaignList;
        case 'campaign-articles': return articlesList;
        case 'users': return studentsList;
        default: break;
      }
  })();
  if (list) {
    return list.sort(this?.value, {
      order: this.options[this.selectedIndex].getAttribute('rel')
    });
    }
  }));
};


text:
<?php
/**
 * This is a helper class used to create interceptors.
 *
 * @version		$Id: InterceptorFactory.php 1502 2008-06-09 21:21:10Z anders $
 */
abstract class InterceptorFactory {
	/**
	 * Private unused constructor to block instantiation of this class.
	 */
	private function __construct () {}

	/**
	 * Instantiates, initializes and returns interceptors set to be used.
	 *
	 * @param array $interceptors Interceptor classes to instantiate.
	 * @return array An array with instantiated interceptors.
	 */
	public static function createInterceptors (array $interceptors) {
		$stack = array(); // To hold instantiated interceptors

		foreach ($interceptors as $name => $class) {
			$settings = Config::getInterceptorSettings($name);
			$instance = new $class($settings);

			$instance->init();
			$stack[] = $instance;
		}

		return $stack;
	}
}
?>


text:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type='text/xsl' href='../../../../../../../../../../../test.xsl'?>
<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You 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.
-->
<!DOCTYPE Test SYSTEM '../../../../../../../../../../../test.dtd'>
<!--
-->
<Test
    ID="RollOverOffsetTest"
        date-of-creation="2006-03-14"
        timeout="2">

    <APITestDescription>

        <TestedClass name="javax.management.monitor.CounterMonitor"/>
        <TestedMethod name="public void setOffset(Number value)"/>
        <TestedMethod name="public Number getOffset()"/>
        <TestedMethod name="public void setModulus(Number value)"/>
        <TestedMethod name="public Number getThreshold(ObjectName object)"/>
        <TestedMethod name="public void setGranularityPeriod(long period)"/>
        <TestedMethod name="public void setInitThreshold(Number value)"/>
        <TestedMethod name="public void setNotify(boolean value)"/>
        <TestedMethod name="public void setDifferenceMode(boolean value)"/>
        <TestedMethod name="public void start()"/>

        <TestedClass name="javax.management.monitor.Monitor"/>
        <TestedMethod name="public void addObservedObject(ObjectName object)"/>
        <TestedMethod name="public void setObservedAttribute(String attribute)"/>

        <TestedClass name="javax.management.NotificationBroadcasterSupport"/>
        <TestedMethod
            name="public void addNotificationListener(NotificationListener listener,NotificationFilter filter,Object handback)"/>
        <Description>
            This test is intended to check basic CounterMonitor threshold rollover functionality
            in case when modulus value is not zero.
                1.    MBean server is started; CounterMonitor and Counter MBeans are registered.
                2.    CounterMonitor is configured with non-zero offset and modulus values.
                3.    NotificationListener is added to CounterMonitor.
                4.    Counter is started in a separate thread, CounterMonitor is activated.
                5.    NotificationListener checks that proper notification is received and
                    threshold is actually reached.
                6.    Listener updates its threshold value according to offset value.
                7.    Listener waits for next notification.
                8.    Listener updates its threshold according to offset and modulus values.
                    Counter is also updated.
                9.    Listener waits for next notification.
                10.    If proper notification is received test considered to be passed

        </Description>
    </APITestDescription>
        <Keyword name="functional"/>
        <Source name="RollOverOffsetTest.java"/>
        <Runner ID="Runtime">
            <Param name="toRun" value="org.apache.harmony.test.func.api.javax.management.monitor.countermonitor.RollOverOffsetTest">
            </Param>
        </Runner>
        <Restriction name="OtherVMOnly"/>
</Test>


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Margeta.Extensions.Cli.Builder
{
    /// <summary>
    /// Represents the console application context.
    /// </summary>
    public class CliContext : IDisposable
    {
        private int _nextArgumentId;
        private readonly IList<CliParameter> _cliParameters;

        /// <summary>
        /// Initializes a new instance of the CliContext class.
        /// </summary>
        /// <param name="args">Command line arguments.</param>
        /// <param name="caseSensitive">Value indicating whether command line option identifiers are case sensitive.</param>
        public CliContext(string[] args, bool caseSensitive = false)
        {
            Arguments = args ?? throw new ArgumentNullException(nameof(args));
            CaseSensitive = caseSensitive;

            _cliParameters = new List<CliParameter>();
        }

        /// <summary>
        /// Gets the command line arguments as passed by the environment.
        /// </summary>
        public string[] Arguments { get; }

        /// <summary>
        /// Gets a value indicating whether the command line option identifiers are case sensitive.
        /// </summary>
        public bool CaseSensitive { get; set; }

        /// <summary>
        /// Gets the collection containing the parsed command line options.
        /// </summary>
        public IEnumerable<CliParameter> CliOptions => _cliParameters.Where(p => p.Type == CliParameterType.Option).AsEnumerable();

        /// <summary>
        /// Gets the collection containing the parsed command line arguments.
        /// </summary>
        public IEnumerable<CliParameter> CliArguments => _cliParameters.Where(p => p.Type == CliParameterType.Argument).AsEnumerable();

        /// <summary>
        /// Gets the collection containing the parsed command line switches.
        /// </summary>
        public IEnumerable<CliParameter> CliSwitches => _cliParameters.Where(p => p.Type == CliParameterType.Switch).AsEnumerable();

        /// <summary>
        /// Gets the error stream.
        /// </summary>
        public virtual TextWriter Error => Console.Error;

        /// <summary>
        /// Gets or sets the executing program file name.
        /// </summary>
        public string ExecutableFileName { get; set; }

        /// <summary>
        /// Gets the input stream.
        /// </summary>
        public virtual TextReader In => Console.In;

        /// <summary>
        /// Gets the output stream.
        /// </summary>
        public virtual TextWriter Out => Console.Out;

        /// <summary>
        /// Gets the list containing the parsed command line parameters.
        /// </summary>
        public IList<CliParameter> Parameters => _cliParameters;

        /// <summary>
        /// Gets or sets the command line context service provider.
        /// </summary>
        public IServiceProvider ServiceProvider { get; set; }

        /// <summary>
        /// Adds the given command line argument to the command line parameter collection.
        /// </summary>
        /// <param name="value">Command line argument value.</param>
        public void AddCliArgument(string value)
        {
            var cliArgument =
                new CliParameter((_nextArgumentId++).ToString(), CliParameterType.Argument)
                {
                    Value = value
                };

            _cliParameters.Add(cliArgument);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        void IDisposable.Dispose() { }

        /// <summary>
        /// Gets the value of the command line option with the given identifier.
        /// </summary>
        /// <param name="id">Command line option identifier.</param>
        /// <returns>The value of the command line option with the given identifier.</returns>
        public string GetCliOptionValue(string id)
        {
            var optionValue = CaseSensitive ? id : id.ToLowerInvariant();
            var cliOption = CliOptions.FirstOrDefault(o => o.Id.Equals(optionValue));

            return cliOption?.Value;
        }

        /// <summary>
        /// Gets the value of the command line switch with the given identifier.
        /// </summary>
        /// <param name="id">Command line switch identifier.</param>
        /// <returns>The value of the command line switch with the given identifier.</returns>
        public bool GetCliSwitchValue(string id)
        {
            var switchValue = CaseSensitive ? id : id.ToLowerInvariant();
            var cliSwitch = CliSwitches.FirstOrDefault(s => s.Id.Equals(switchValue));

            return cliSwitch != null;
        }

        /// <summary>
        /// Removes the given command line argument from the command line argument collection.
        /// </summary>
        /// <param name="id">Command line argument identifier.</param>
        public void RemoveCliArgument(string id)
        {
            var parameter = _cliParameters.FirstOrDefault(p => p.Id.Equals(id));

            if (parameter != null)
            {
                _cliParameters.Remove(parameter);
            }
        }

        /// <summary>
        /// Sets the value of the command line option with the given identifier.
        /// </summary>
        /// <param name="id">Command line option identifier.</param>
        /// <param name="value">The value to set.</param>
        public void SetCliOptionValue(string id, string value)
        {
            if (string.IsNullOrWhiteSpace(id))
            {
                throw new ArgumentException(nameof(id));
            }

            var optionId = CaseSensitive ? id : id.ToLowerInvariant();

            var cliOption = CliOptions.FirstOrDefault(o => o.Id.Equals(optionId));
            var cliSwitch = CliSwitches.FirstOrDefault(s => s.Id.Equals(optionId));

            if (cliSwitch != null)
            {
                _cliParameters.Remove(cliSwitch);
            }

            if (cliOption != null)
            {
                cliOption.Value = value;
            }
            else
            {
                cliOption = new CliParameter(optionId, CliParameterType.Option);

                cliOption.Value = value;
                _cliParameters.Add(cliOption);
            }
        }

        /// <summary>
        /// Sets the value of the command line switch with the given identifier.
        /// </summary>
        /// <param name="id">Command line switch identifier.</param>
        /// <param name="value">The value to set.</param>
        public void SetCliSwitchValue(string id, bool value = true)
        {
            var switchId = CaseSensitive ? id : id.ToLowerInvariant();

            var cliOption = CliOptions.FirstOrDefault(o => o.Id.Equals(switchId));
            var cliSwitch = CliSwitches.FirstOrDefault(s => s.Id.Equals(switchId));

            if (cliOption != null)
            {
                _cliParameters.Remove(cliOption);
            }

            if (cliSwitch != null)
            {
                if (value == false)
                {
                    _cliParameters.Remove(cliSwitch);
                }
            }
            else
            {
                cliSwitch = new CliParameter(switchId, CliParameterType.Switch);
                _cliParameters.Add(cliSwitch);
            }
        }
    }
}


text:
namespace YAML {

// These destructors are defined out-of-line so the vtable is only emitted once.
Exception::~Exception() YAML_CPP_NOEXCEPT = default;
ParserException::~ParserException() YAML_CPP_NOEXCEPT = default;
RepresentationException::~RepresentationException() YAML_CPP_NOEXCEPT = default;
InvalidScalar::~InvalidScalar() YAML_CPP_NOEXCEPT = default;
KeyNotFound::~KeyNotFound() YAML_CPP_NOEXCEPT = default;
InvalidNode::~InvalidNode() YAML_CPP_NOEXCEPT = default;
BadConversion::~BadConversion() YAML_CPP_NOEXCEPT = default;
BadDereference::~BadDereference() YAML_CPP_NOEXCEPT = default;
BadSubscript::~BadSubscript() YAML_CPP_NOEXCEPT = default;
BadPushback::~BadPushback() YAML_CPP_NOEXCEPT = default;
BadInsert::~BadInsert() YAML_CPP_NOEXCEPT = default;
EmitterException::~EmitterException() YAML_CPP_NOEXCEPT = default;
BadFile::~BadFile() YAML_CPP_NOEXCEPT = default;
}


text:
<?php

final class PhabricatorStorageManagementStatusWorkflow
  extends PhabricatorStorageManagementWorkflow {

  protected function didConstruct() {
    $this
      ->setName('status')
      ->setExamples('**status** [__options__]')
      ->setSynopsis(pht('Show patch application status.'));
  }

  public function execute(PhutilArgumentParser $args) {
    $api = $this->getAPI();
    $patches = $this->getPatches();

    $applied = $api->getAppliedPatches();

    if ($applied === null) {
      echo phutil_console_format(
        "**%s**: %s\n",
        pht('Database Not Initialized'),
        pht('Run **%s** to initialize.', 'storage upgrade'));

      return 1;
    }

    $table = id(new PhutilConsoleTable())
      ->setShowHeader(false)
      ->addColumn('id',     array('title' => pht('ID')))
      ->addColumn('status', array('title' => pht('Status')))
      ->addColumn('type',   array('title' => pht('Type')))
      ->addColumn('name',   array('title' => pht('Name')));

    foreach ($patches as $patch) {
      $table->addRow(array(
        'id' => $patch->getFullKey(),
        'status' => in_array($patch->getFullKey(), $applied)
          ? pht('Applied')
          : pht('Not Applied'),
        'type' => $patch->getType(),
        'name' => $patch->getName(),
      ));
    }

    $table->draw();
    return 0;
  }

}


text:
__author__ = 'MICH'
"Compute accuracy for train images"
"Shows predictions that are neither cats nor dogs"

import os
from glob import glob

cats_file = 'data/cats.txt'
dogs_file = 'data/dogs.txt'
predictions_dir = 'data/overfeat_predictions_train_orig/'

# load cat and dog names

cf = open( cats_file )
df = open( dogs_file )

cats = cf.read()
cats = cats.split( "\n" )
cats = { x: x for x in cats }

dogs = df.read()
dogs = dogs.split( "\n" )
dogs = { x: x for x in dogs }

#

files = glob( predictions_dir + '*.txt' )
files.sort()

counter = 0
acc_counter = 0

for f in files:

        # true class
        basename = os.path.basename( f )
        true_class = basename.split( "." )[0]
        #print true_class

        pf = open( f )
        predictions = pf.read()
        predictions = predictions.split( "\n" )
        predictions = map( lambda x: x.split( "0." )[0].strip(), predictions )
        if predictions[-1] == '':
                predictions.pop()

        #print predictions

        predicted_class = ''
        for p in predictions:
                if p in cats:
                        predicted_class = 'cat'
                        break
                if p in dogs:
                        predicted_class = 'dog'
                        break

        #print "{}\t{}".format( true_class, predicted_class )
        if not predicted_class:
                print predictions

        counter += 1
        if true_class == predicted_class:
                acc_counter += 1

print
print "{}/{}".format( acc_counter, counter )
print "accuracy: {}".format( 1.0 * acc_counter / counter )


text:
package wx.sunl.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import wx.sunl.bean.Orders;
import wx.sunl.dao.DBHelper;
import wx.sunl.dao.OrdersDao;

public class OrdersDaoImpl implements OrdersDao {

	static DBHelper dbh = null;

	@Override
	public Orders findById(String orderId) {
		Orders orders = null;
		ResultSet rst = null;
		String[] params = new String[1];
		String sql = "SELECT * FROM tb_order WHERE ORDER_ID = ?";
		params[0] = orderId;
		dbh = new DBHelper();
		rst = dbh.excuteQuery(sql, params);
		try {
			while(rst.next()){
				orders = new Orders();
				orders.setOrderId(rst.getString("ORDER_ID"));
				orders.setOrderNo(rst.getString("ORDER_NO"));
				orders.setCreateTime(rst.getTimestamp("CREATE_TIME"));
				orders.setRoomNo(rst.getString("ROOM_NO"));
				orders.setRoomId(rst.getString("ROOM_ID"));
				orders.setOrderStatus(rst.getString("ORDER_STATUS"));
				orders.setHandleTime(rst.getTimestamp("HANDLE_TIME"));
				orders.setEmpNo(rst.getString("EMP_NO"));
				orders.setEmpId(rst.getString("EMP_ID"));
				orders.setRemark(rst.getString("REMARK"));
				orders.setUserId(rst.getString("USER_ID"));
				orders.setCheckInTime(rst.getTimestamp("PLAN_IN_TIME"));
				orders.setCheckInDays(rst.getString("PLAN_IN_DAYS"));
				orders.setRoomType(rst.getString("ROOM_TYPE"));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orders;
	}

	@Override
	public List<Orders> queryAllOrders() {
		Orders orders = null;
		ResultSet rst = null;
		List<Orders> orderList = new ArrayList<Orders>();
		String sql = "SELECT * FROM tb_order";
		dbh = new DBHelper();
		rst = dbh.excuteQuery(sql, null);
		try {
			while(rst.next()){
				orders = new Orders();
				orders.setOrderId(rst.getString("ORDER_ID"));
				orders.setOrderNo(rst.getString("ORDER_NO"));
				orders.setCreateTime(rst.getTimestamp("CREATE_TIME"));
				orders.setRoomNo(rst.getString("ROOM_NO"));
				orders.setRoomId(rst.getString("ROOM_ID"));
				orders.setOrderStatus(rst.getString("ORDER_STATUS"));
				orders.setHandleTime(rst.getTimestamp("HANDLE_TIME"));
				orders.setEmpNo(rst.getString("EMP_NO"));
				orders.setEmpId(rst.getString("EMP_ID"));
				orders.setRemark(rst.getString("REMARK"));
				orders.setUserName(rst.getString("USER_NAME"));
				orders.setUserId(rst.getString("USER_ID"));
				orders.setCheckInTime(rst.getTimestamp("PLAN_IN_TIME"));
				orders.setCheckInDays(rst.getString("PLAN_IN_DAYS"));
				orders.setRoomType(rst.getString("ROOM_TYPE"));
				orderList.add(orders);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orderList;
	}

	@Override
	public boolean saveOrUpdate(Orders orders, String order) {
		boolean flag = false;
		String sql = null;
		String[] params = null;
		dbh = new DBHelper();
		if(order.equals("save")){
			sql = "INSERT INTO tb_order VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
			params = new String[15];
			params[0] = orders.getOrderId();
			params[1] = orders.getOrderNo();
			params[2] = String.valueOf(orders.getCreateTime());
			params[3] = orders.getRoomNo();
			params[4] = orders.getRoomId();
			params[5] = orders.getOrderStatus();
			params[6] = !String.valueOf(orders.getHandleTime()).equals("null") ? String.valueOf(orders.getHandleTime()) : "1970-01-02 00:00:00";
			params[7] = orders.getEmpNo();
			params[8] = orders.getEmpId();
			params[9] = orders.getRemark();
			params[10] = orders.getUserName();
			params[11] = orders.getUserId();
			params[12] = String.valueOf(orders.getCheckInTime());
			params[13] = orders.getCheckInDays();
			params[14] = orders.getRoomType();
			flag = dbh.excuteSql(sql, params);
		}else{
			sql = "UPDATE tb_order SET ORDER_NO=?,CREATE_TIME=?,ROOM_NO=?,ROOM_ID=?,ORDER_STATUS=?,HANDLE_TIME=?,EMP_NO=?,EMP_ID=?,REMARK=?,USER_NAME=?,USER_ID=?,PLAN_IN_TIME=?,PLAN_IN_DAYS=?,ROOM_TYPE=? WHERE ORDER_ID=?";
			params = new String[15];
			params[0] = orders.getOrderNo();
			params[1] = !String.valueOf(orders.getCreateTime()).equals("null") ? String.valueOf(orders.getCreateTime()) : "1970-01-02 00:00:00";
			params[2] = orders.getRoomNo();
			params[3] = orders.getRoomId();
			params[4] = orders.getOrderStatus();
			params[5] = !String.valueOf(orders.getHandleTime()).equals("null") ? String.valueOf(orders.getHandleTime()) : "1970-01-02 00:00:00";
			params[6] = orders.getEmpNo();
			params[7] = orders.getEmpId();
			params[8] = orders.getRemark();
			params[9] = orders.getUserId();
			params[10] = orders.getUserName();
			params[11] = !String.valueOf(orders.getCheckInTime()).equals("null") ? String.valueOf(orders.getCheckInTime()) : "1970-01-02 00:00:00";
			params[12] = orders.getCheckInDays();
			params[13] = orders.getRoomType();
			params[14] = orders.getOrderId();
			flag = dbh.excuteSql(sql, params);
		}
		return flag;
	}

	@Override
	public boolean deleteById(String orderId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean deleteAll() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public List<Orders> queryActiveOrders() {
		Orders orders = null;
		ResultSet rst = null;
		List<Orders> orderList = new ArrayList<Orders>();
		String sql = "SELECT * FROM tb_order WHERE ORDER_STATUS = '0'";
		dbh = new DBHelper();
		rst = dbh.excuteQuery(sql, null);
		try {
			while(rst.next()){
				orders = new Orders();
				orders.setOrderId(rst.getString("ORDER_ID"));
				orders.setOrderNo(rst.getString("ORDER_NO"));
				orders.setCreateTime(rst.getTimestamp("CREATE_TIME"));
				orders.setRoomNo(rst.getString("ROOM_NO"));
				orders.setRoomId(rst.getString("ROOM_ID"));
				orders.setOrderStatus(rst.getString("ORDER_STATUS"));
				orders.setHandleTime(rst.getTimestamp("HANDLE_TIME"));
				orders.setEmpNo(rst.getString("EMP_NO"));
				orders.setEmpId(rst.getString("EMP_ID"));
				orders.setRemark(rst.getString("REMARK"));
				orders.setUserName(rst.getString("USER_NAME"));
				orders.setUserId(rst.getString("USER_ID"));
				orders.setCheckInTime(rst.getTimestamp("PLAN_IN_TIME"));
				orders.setCheckInDays(rst.getString("PLAN_IN_DAYS"));
				orderList.add(orders);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orderList;
	}

	@Override
	public List<Orders> queryPersonalOrders(String userId) {
		Orders orders = null;
		ResultSet rst = null;
		List<Orders> orderList = new ArrayList<Orders>();
		String[] params = new String[1];
		String sql = "SELECT * FROM tb_order WHERE USER_ID = ?";
		params[0] = userId;
		dbh = new DBHelper();
		rst = dbh.excuteQuery(sql, params);
		try {
			while(rst.next()){
				orders = new Orders();
				orders.setOrderId(rst.getString("ORDER_ID"));
				orders.setOrderNo(rst.getString("ORDER_NO"));
				orders.setCreateTime(rst.getTimestamp("CREATE_TIME"));
				orders.setRoomNo(rst.getString("ROOM_NO"));
				orders.setRoomId(rst.getString("ROOM_ID"));
				orders.setOrderStatus(rst.getString("ORDER_STATUS"));
				orders.setHandleTime(rst.getTimestamp("HANDLE_TIME"));
				orders.setEmpNo(rst.getString("EMP_NO"));
				orders.setEmpId(rst.getString("EMP_ID"));
				orders.setRemark(rst.getString("REMARK"));
				orders.setUserName(rst.getString("USER_NAME"));
				orders.setUserId(rst.getString("USER_ID"));
				orders.setCheckInTime(rst.getTimestamp("PLAN_IN_TIME"));
				orders.setCheckInDays(rst.getString("PLAN_IN_DAYS"));
				orders.setRoomType(rst.getString("ROOM_TYPE"));
				orderList.add(orders);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return orderList;
	}

}


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

    HRQOL composite/subscore
    Single DMD or no DMD
    n
    Mean HRQOL
    SD
    P

    Overall QOL subscore
    No DMD
    1104
    66.8
    19.4
    0.472

    Physical health composite
    DMD
    1081
    67.4
    18.7
    0.403

    Mental health composite
    No DMD
    919
    59.0
    22.1
    0.011

    Physical health subscore
    DMD
    958
    59.8
    20.8
    0.000

    Role limitations physical subscore
    No DMD
    1078
    68.2
    21.0
    0.049

    Role limitations emotional subscore
    DMD
    1061
    65.9
    21.6
    0.373

    Pain subscore
    No DMD
    1125
    56.4
    34.9
    0.985

    Emotional wellbeing subscore
    DMD
    1096
    64.0
    31.1
    0.001

    Energy subscore
    No DMD
    1123
    44.3
    43.3
    0.121

    Health perception subscore
    DMD
    1092
    47.9
    43.5
    0.082

    Social function subscore
    No DMD
    1117
    69.7
    41.0
    0.118

    Cognitive function subscore
    DMD
    1080
    68.1
    41.3
    0.002

    Health distress subscore
    No DMD
    1129
    72.0
    26.2
    0.009

    Sexual function subscore
    DMD
    1090
    72.0
    26.1
    0.113